From a85bc4645de559644c691be64ade2fcab3211164 Mon Sep 17 00:00:00 2001 From: "chuckb%netscape.com" Date: Tue, 28 Jul 1998 00:58:49 +0000 Subject: [PATCH] Java LDAP SDK git-svn-id: svn://10.0.0.236/trunk@6597 18797224-902f-48f8-a5cc-f745e15eee43 --- mozilla/directory/java-sdk/ldap.mk | 142 + .../netscape/ldap/beans/DisplayString.java | 67 + .../ldap/beans/DisplayStringBeanInfo.java | 63 + .../ldap/beans/LDAPBasePropertySupport.java | 341 ++ .../netscape/ldap/beans/LDAPGetEntries.java | 341 ++ .../ldap/beans/LDAPGetEntriesBeanInfo.java | 129 + .../netscape/ldap/beans/LDAPGetProperty.java | 355 ++ .../ldap/beans/LDAPGetPropertyBeanInfo.java | 138 + .../netscape/ldap/beans/LDAPIsMember.java | 356 ++ .../ldap/beans/LDAPIsMemberBeanInfo.java | 110 + .../netscape/ldap/beans/LDAPSimpleAuth.java | 178 + .../ldap/beans/LDAPSimpleAuthBeanInfo.java | 118 + .../ldap/util/BadFilterException.java | 83 + .../netscape/ldap/util/LDAPFilter.java | 525 +++ .../ldap/util/LDAPFilterDescriptor.java | 492 +++ .../netscape/ldap/util/LDAPFilterList.java | 97 + .../netscape/ldap/util/LDAPIntFilterList.java | 114 + .../netscape/ldap/util/LDAPIntFilterSet.java | 159 + .../com/netscape/sasl/SASLClientCB.java | 26 + .../sasl/SASLClientMechanismDriver.java | 203 + .../com/netscape/sasl/SASLException.java | 62 + .../com/netscape/sasl/SASLGetLanguageCB.java | 34 + .../com/netscape/sasl/SASLInfoClientCB.java | 32 + .../netscape/sasl/SASLMechanismFactory.java | 90 + .../sasl/SASLNamePasswordClientCB.java | 52 + .../netscape/sasl/SASLOkayCancelClientCB.java | 37 + .../netscape/sasl/SASLPasswordClientCB.java | 45 + .../com/netscape/sasl/SASLSecurityLayer.java | 44 + .../netscape/sasl/SASLWarningClientCB.java | 31 + .../ldapjdk/netscape/ldap/LDAPAttribute.java | 472 ++ .../netscape/ldap/LDAPAttributeSchema.java | 310 ++ .../netscape/ldap/LDAPAttributeSet.java | 398 ++ .../ldapjdk/netscape/ldap/LDAPCache.java | 809 ++++ .../ldapjdk/netscape/ldap/LDAPCheckComm.java | 61 + .../netscape/ldap/LDAPCompareAttrNames.java | 240 + .../ldapjdk/netscape/ldap/LDAPConnection.java | 3907 +++++++++++++++++ .../ldapjdk/netscape/ldap/LDAPControl.java | 251 ++ .../ldapjdk/netscape/ldap/LDAPDN.java | 132 + .../ldapjdk/netscape/ldap/LDAPEntry.java | 198 + .../netscape/ldap/LDAPEntryComparator.java | 62 + .../ldapjdk/netscape/ldap/LDAPException.java | 883 ++++ .../netscape/ldap/LDAPExtendedOperation.java | 152 + .../netscape/ldap/LDAPMatchingRuleSchema.java | 319 ++ .../netscape/ldap/LDAPModification.java | 142 + .../netscape/ldap/LDAPModificationSet.java | 117 + .../netscape/ldap/LDAPObjectClassSchema.java | 318 ++ .../ldapjdk/netscape/ldap/LDAPRebind.java | 74 + .../ldapjdk/netscape/ldap/LDAPRebindAuth.java | 91 + .../netscape/ldap/LDAPReferralException.java | 147 + .../netscape/ldap/LDAPResourceBundle.java | 117 + .../netscape/ldap/LDAPResponseListener.java | 152 + .../netscape/ldap/LDAPSSLSocketFactory.java | 237 + .../ldap/LDAPSSLSocketWrapFactory.java | 330 ++ .../ldapjdk/netscape/ldap/LDAPSchema.java | 496 +++ .../netscape/ldap/LDAPSchemaElement.java | 223 + .../netscape/ldap/LDAPSearchConstraints.java | 357 ++ .../netscape/ldap/LDAPSearchListener.java | 132 + .../netscape/ldap/LDAPSearchResults.java | 506 +++ .../netscape/ldap/LDAPSocketFactory.java | 55 + .../ldapjdk/netscape/ldap/LDAPSortKey.java | 147 + .../ldapjdk/netscape/ldap/LDAPUrl.java | 581 +++ .../ldapjdk/netscape/ldap/LDAPv2.java | 443 ++ .../ldapjdk/netscape/ldap/LDAPv3.java | 167 + .../netscape/ldap/ber/stream/BERAny.java | 87 + .../ldap/ber/stream/BERBitString.java | 273 ++ .../netscape/ldap/ber/stream/BERBoolean.java | 110 + .../ldap/ber/stream/BERCharacterString.java | 179 + .../netscape/ldap/ber/stream/BERChoice.java | 96 + .../ldap/ber/stream/BERConstruct.java | 130 + .../netscape/ldap/ber/stream/BERElement.java | 315 ++ .../ldap/ber/stream/BEREnumerated.java | 66 + .../netscape/ldap/ber/stream/BERInteger.java | 83 + .../netscape/ldap/ber/stream/BERIntegral.java | 172 + .../netscape/ldap/ber/stream/BERNull.java | 87 + .../ldap/ber/stream/BERNumericString.java | 90 + .../netscape/ldap/ber/stream/BERObjectId.java | 186 + .../ldap/ber/stream/BEROctetString.java | 188 + .../ldap/ber/stream/BERPrintableString.java | 91 + .../netscape/ldap/ber/stream/BERReal.java | 209 + .../netscape/ldap/ber/stream/BERSequence.java | 72 + .../netscape/ldap/ber/stream/BERSet.java | 81 + .../netscape/ldap/ber/stream/BERTag.java | 153 + .../ldap/ber/stream/BERTagDecoder.java | 44 + .../netscape/ldap/ber/stream/BERUTCTime.java | 160 + .../ldap/ber/stream/BERVisibleString.java | 90 + .../ldapjdk/netscape/ldap/client/JDAPAVA.java | 98 + .../ldap/client/JDAPBERTagDecoder.java | 119 + .../netscape/ldap/client/JDAPControl.java | 124 + .../netscape/ldap/client/JDAPFilter.java | 236 + .../netscape/ldap/client/JDAPFilterAVA.java | 63 + .../netscape/ldap/client/JDAPFilterAnd.java | 47 + .../ldap/client/JDAPFilterApproxMatch.java | 49 + .../ldap/client/JDAPFilterEqualityMatch.java | 50 + .../ldap/client/JDAPFilterExtensible.java | 128 + .../ldap/client/JDAPFilterGreaterOrEqual.java | 50 + .../ldap/client/JDAPFilterLessOrEqual.java | 49 + .../netscape/ldap/client/JDAPFilterNot.java | 65 + .../netscape/ldap/client/JDAPFilterOpers.java | 125 + .../netscape/ldap/client/JDAPFilterOr.java | 48 + .../ldap/client/JDAPFilterPresent.java | 65 + .../netscape/ldap/client/JDAPFilterSet.java | 85 + .../ldap/client/JDAPFilterSubString.java | 150 + .../netscape/ldap/client/JDAPMessage.java | 194 + .../ldap/client/opers/JDAPAbandonRequest.java | 89 + .../ldap/client/opers/JDAPAddRequest.java | 141 + .../ldap/client/opers/JDAPAddResponse.java | 60 + .../ldap/client/opers/JDAPBaseDNRequest.java | 46 + .../ldap/client/opers/JDAPBindRequest.java | 172 + .../ldap/client/opers/JDAPBindResponse.java | 91 + .../ldap/client/opers/JDAPCompareRequest.java | 101 + .../client/opers/JDAPCompareResponse.java | 59 + .../ldap/client/opers/JDAPDeleteRequest.java | 97 + .../ldap/client/opers/JDAPDeleteResponse.java | 59 + .../client/opers/JDAPExtendedRequest.java | 101 + .../client/opers/JDAPExtendedResponse.java | 112 + .../client/opers/JDAPModifyRDNRequest.java | 138 + .../client/opers/JDAPModifyRDNResponse.java | 61 + .../ldap/client/opers/JDAPModifyRequest.java | 120 + .../ldap/client/opers/JDAPModifyResponse.java | 60 + .../ldap/client/opers/JDAPProtocolOp.java | 75 + .../ldap/client/opers/JDAPResult.java | 253 ++ .../ldap/client/opers/JDAPSearchRequest.java | 211 + .../ldap/client/opers/JDAPSearchResponse.java | 139 + .../ldap/client/opers/JDAPSearchResult.java | 63 + .../opers/JDAPSearchResultReference.java | 96 + .../ldap/client/opers/JDAPUnbindRequest.java | 73 + .../ldap/controls/LDAPEntryChangeControl.java | 174 + .../controls/LDAPPersistSearchControl.java | 448 ++ .../ldap/controls/LDAPSortControl.java | 491 +++ .../ldap/controls/LDAPVirtualListControl.java | 393 ++ .../controls/LDAPVirtualListResponse.java | 151 + .../netscape/ldap/errors/ErrorCodes.props | 50 + .../ldapjdk/netscape/ldap/util/ByteBuf.java | 432 ++ .../ldapjdk/netscape/ldap/util/DN.java | 434 ++ .../ldapjdk/netscape/ldap/util/GetOpt.java | 234 + .../ldapjdk/netscape/ldap/util/LDIF.java | 518 +++ .../netscape/ldap/util/LDIFAddContent.java | 90 + .../ldap/util/LDIFAttributeContent.java | 100 + .../netscape/ldap/util/LDIFContent.java | 100 + .../netscape/ldap/util/LDIFDeleteContent.java | 67 + .../netscape/ldap/util/LDIFModDNContent.java | 153 + .../netscape/ldap/util/LDIFModifyContent.java | 103 + .../netscape/ldap/util/LDIFRecord.java | 183 + .../netscape/ldap/util/MimeBase64Decoder.java | 173 + .../netscape/ldap/util/MimeBase64Encoder.java | 128 + .../netscape/ldap/util/MimeEncoder.java | 43 + .../ldapjdk/netscape/ldap/util/RDN.java | 131 + mozilla/directory/java-sdk/manifest.mf | 272 ++ 148 files changed, 29482 insertions(+) create mode 100644 mozilla/directory/java-sdk/ldap.mk create mode 100644 mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/DisplayString.java create mode 100644 mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/DisplayStringBeanInfo.java create mode 100644 mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPBasePropertySupport.java create mode 100644 mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPGetEntries.java create mode 100644 mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPGetEntriesBeanInfo.java create mode 100644 mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPGetProperty.java create mode 100644 mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPGetPropertyBeanInfo.java create mode 100644 mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPIsMember.java create mode 100644 mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPIsMemberBeanInfo.java create mode 100644 mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPSimpleAuth.java create mode 100644 mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPSimpleAuthBeanInfo.java create mode 100644 mozilla/directory/java-sdk/ldapfilter/netscape/ldap/util/BadFilterException.java create mode 100644 mozilla/directory/java-sdk/ldapfilter/netscape/ldap/util/LDAPFilter.java create mode 100644 mozilla/directory/java-sdk/ldapfilter/netscape/ldap/util/LDAPFilterDescriptor.java create mode 100644 mozilla/directory/java-sdk/ldapfilter/netscape/ldap/util/LDAPFilterList.java create mode 100644 mozilla/directory/java-sdk/ldapfilter/netscape/ldap/util/LDAPIntFilterList.java create mode 100644 mozilla/directory/java-sdk/ldapfilter/netscape/ldap/util/LDAPIntFilterSet.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLClientCB.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLClientMechanismDriver.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLException.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLGetLanguageCB.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLInfoClientCB.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLMechanismFactory.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLNamePasswordClientCB.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLOkayCancelClientCB.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLPasswordClientCB.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLSecurityLayer.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLWarningClientCB.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPAttribute.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPAttributeSchema.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPAttributeSet.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPCache.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPCheckComm.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPCompareAttrNames.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPConnection.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPControl.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPDN.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPEntry.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPEntryComparator.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPException.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPExtendedOperation.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPMatchingRuleSchema.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPModification.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPModificationSet.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPObjectClassSchema.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPRebind.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPRebindAuth.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPReferralException.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPResourceBundle.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPResponseListener.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSSLSocketFactory.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSSLSocketWrapFactory.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSchema.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSchemaElement.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSearchConstraints.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSearchListener.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSearchResults.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSocketFactory.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSortKey.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPUrl.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPv2.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPv3.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERAny.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERBitString.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERBoolean.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERCharacterString.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERChoice.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERConstruct.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERElement.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BEREnumerated.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERInteger.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERIntegral.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERNull.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERNumericString.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERObjectId.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BEROctetString.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERPrintableString.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERReal.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERSequence.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERSet.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERTag.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERTagDecoder.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERUTCTime.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERVisibleString.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPAVA.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPBERTagDecoder.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPControl.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilter.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterAVA.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterAnd.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterApproxMatch.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterEqualityMatch.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterExtensible.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterGreaterOrEqual.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterLessOrEqual.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterNot.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterOpers.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterOr.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterPresent.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterSet.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterSubString.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPMessage.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPAbandonRequest.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPAddRequest.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPAddResponse.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPBaseDNRequest.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPBindRequest.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPBindResponse.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPCompareRequest.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPCompareResponse.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPDeleteRequest.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPDeleteResponse.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPExtendedRequest.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPExtendedResponse.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPModifyRDNRequest.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPModifyRDNResponse.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPModifyRequest.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPModifyResponse.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPProtocolOp.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPResult.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPSearchRequest.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPSearchResponse.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPSearchResult.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPSearchResultReference.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPUnbindRequest.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/controls/LDAPEntryChangeControl.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/controls/LDAPPersistSearchControl.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/controls/LDAPSortControl.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/controls/LDAPVirtualListControl.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/controls/LDAPVirtualListResponse.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/errors/ErrorCodes.props create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/ByteBuf.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/DN.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/GetOpt.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIF.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFAddContent.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFAttributeContent.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFContent.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFDeleteContent.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFModDNContent.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFModifyContent.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFRecord.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/MimeBase64Decoder.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/MimeBase64Encoder.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/MimeEncoder.java create mode 100644 mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/RDN.java create mode 100644 mozilla/directory/java-sdk/manifest.mf diff --git a/mozilla/directory/java-sdk/ldap.mk b/mozilla/directory/java-sdk/ldap.mk new file mode 100644 index 00000000000..bf8f065d83a --- /dev/null +++ b/mozilla/directory/java-sdk/ldap.mk @@ -0,0 +1,142 @@ +# -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- +# +# The contents of this file are subject to the Netscape Public License +# Version 1.0 (the "NPL"); you may not use this file except in +# compliance with the NPL. You may obtain a copy of the NPL at +# http://www.mozilla.org/NPL/ +# +# Software distributed under the NPL is distributed on an "AS IS" basis, +# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL +# for the specific language governing rights and limitations under the +# NPL. +# +# The Initial Developer of this code under the NPL is Netscape +# Communications Corporation. Portions created by Netscape are +# Copyright (C) 1998 Netscape Communications Corporation. All Rights +# Reserved. +# +# Makefile for the LDAP classes +# +# An optimized compile is done by default. You can specify "DEBUG=1" on +# the make line to generate debug symbols in the bytecode. +# +ARCH := $(shell uname -s) + +MCOM_ROOT=. +ifeq ($(ARCH), WINNT) + MOZ_DIR:=$(subst \,/,$(MOZ_SRC)) + BASEDIR:=$(MOZ_DIR)/mozilla/directory/java-sdk +else + ifeq ($(ARCH), WIN95) + MOZ_DIR:=$(subst \,/,$(MOZ_SRC)) + BASEDIR:=$(MOZ_DIR)/mozilla/directory/java-sdk + else + BASEDIR := $(shell cd $(MCOM_ROOT); pwd) + endif +endif +# Destination for class files and packages +CLASS_DEST=$(BASEDIR)/dist/classes + +# Set up the CLASSPATH automatically, +ifeq ($(ARCH), WINNT) + JDK := $(subst \,/,$(JAVA_HOME)) + JAR:=$(JDK)/bin/jar + SEP=; +else + ifeq ($(ARCH), WIN95) + JDK := $(subst \,/,$(JAVA_HOME)) + JAR:=$(JDK)/bin/jar + SEP=; + else + JDK := $(JAVA_HOME) + JAR:=$(JAVA_HOME)/bin/jar + SEP=: + endif +endif +JAVACLASSPATH:=$(BASEDIR)/ldapjdk$(SEP)$(BASEDIR)/ldapbeans$(SEP)$(BASEDIR)/ldapfilter$(SEP)$(CLASSPATH) + +SRCDIR=netscape/ldap +BEANDIR=$(BASEDIR)/ldapbeans/netscape/ldap/beans +DISTDIR=$(MCOM_ROOT)/dist +CLASSDIR=$(MCOM_ROOT)/dist/classes +CLASSPACKAGEDIR=$(DISTDIR)/packages +PACKAGENAME=javaldap.zip +ifeq ($(DEBUG), 1) +BASEPACKAGENAME=ldapjdk_debug.jar +else +BASEPACKAGENAME=ldapjdk.jar +endif +CLASSPACKAGE=$(CLASSPACKAGEDIR)/$(PACKAGENAME) +ERRORSDIR=$(CLASSDIR)/netscape/ldap/errors +SASLDIR=com/netscape/sasl + +ifndef JAVAC + ifdef JAVA_HOME + JDKBIN=$(JDK)/bin/ + endif + ifeq ($(DEBUG), 1) + JAVAC=$(JDKBIN)javac -g -classpath "$(JAVACLASSPATH)" + else + JAVAC=$(JDKBIN)javac -O -classpath "$(JAVACLASSPATH)" + endif +endif + +all: classes + +basics: $(DISTDIR) $(CLASSDIR) + cp -p manifest.mf $(CLASS_DEST) + +classes: LDAPCLASSES BEANS + +basepackage: $(CLASSPACKAGEDIR) + cd $(DISTDIR)/classes; rm -f ../packages/$(BASEPACKAGENAME); $(JAR) cvfm ../packages/$(BASEPACKAGENAME) manifest.mf netscape/ldap/*.class netscape/ldap/client/*.class netscape/ldap/client/opers/*.class netscape/ldap/ber/stream/*.class netscape/ldap/controls/*.class netscape/ldap/util/*.class netscape/ldap/errors/*.props com/netscape/sasl/*.class + +MAIN: basics + cd ldapjdk/$(SRCDIR); $(JAVAC) -d "$(CLASS_DEST)" *.java + +CLIENT: basics + cd ldapjdk/$(SRCDIR)/client; $(JAVAC) -d "$(CLASS_DEST)" *.java + +OPERS: basics + cd ldapjdk/$(SRCDIR)/client/opers; $(JAVAC) -d "$(CLASS_DEST)" *.java + +BER: basics + cd ldapjdk/$(SRCDIR)/ber/stream; $(JAVAC) -d "$(CLASS_DEST)" *.java + +UTIL: basics + cd ldapjdk/$(SRCDIR)/util; $(JAVAC) -d "$(CLASS_DEST)" *.java + +SASL: basics + cd ldapjdk/$(SASLDIR); $(JAVAC) -d "$(CLASS_DEST)" *.java + +ERRORS: basics $(ERRORSDIR) + cp -p ldapjdk/$(SRCDIR)/errors/*.props $(ERRORSDIR) + +CONTROLS: basics + cd ldapjdk/$(SRCDIR)/controls; $(JAVAC) -d "$(CLASS_DEST)" *.java + +LDAPCLASSES: BER OPERS CLIENT MAIN UTIL CONTROLS ERRORS SASL + +BEANS: OTHERBEANS + +OTHERBEANS: basics + cd ldapbeans/$(SRCDIR)/beans; $(JAVAC) -d "$(CLASS_DEST)" *.java + +clean: + rm -rf $(DISTDIR) + +$(CLASSPACKAGEDIR): + mkdir -p $@ + +$(DOCPACKAGEDIR): + mkdir -p $@ + +$(DISTDIR): + mkdir -p $@ + +$(CLASSDIR): + mkdir -p $@ + +$(ERRORSDIR): + mkdir -p $@ + diff --git a/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/DisplayString.java b/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/DisplayString.java new file mode 100644 index 00000000000..91f729a05f1 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/DisplayString.java @@ -0,0 +1,67 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.beans; + +import java.awt.*; +import java.awt.event.*; +import java.beans.*; +import java.io.Serializable; + +public class DisplayString extends TextArea implements Serializable { + + public DisplayString() { + super(); + setEditable(false); + } + + public void reportChange(PropertyChangeEvent evt) { + Object obj = (Object)evt.getNewValue(); + if (obj == null) { + append("null\n"); + return; + } + + String[] values = null; + if (obj instanceof String) { + values = new String[1]; + values[0] = (String)obj; + } + else + values = (String[])obj; + + int width = getSize().width - 10; + Font f = getFont(); + for (int i=0; i width) { + text = text.substring(0, text.length()-1); + } + } + append(text+'\n'); + } + } + + public void clear (ActionEvent e) { + setText(""); + invalidate(); + repaint(); + } +} diff --git a/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/DisplayStringBeanInfo.java b/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/DisplayStringBeanInfo.java new file mode 100644 index 00000000000..e2c1db12213 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/DisplayStringBeanInfo.java @@ -0,0 +1,63 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.beans; + +import java.beans.SimpleBeanInfo; +import java.beans.BeanDescriptor; +import java.beans.EventSetDescriptor; +import java.beans.MethodDescriptor; +import java.beans.PropertyDescriptor; +import java.beans.ParameterDescriptor; +import java.beans.BeanInfo; + +/** + * BeanInfo for displaying string + * + */ + +public class DisplayStringBeanInfo extends SimpleBeanInfo { + + public DisplayStringBeanInfo() throws Exception { + + beanClass = Class.forName( "netscape.ldap.beans.DisplayString" ); + + // Publish descriptor --------------------------------------------- + try { + _beanDescriptor = new BeanDescriptor(beanClass); + _beanDescriptor.setDisplayName( "Text Field" ); + _beanDescriptor.setShortDescription( + "LDAP property retrieval -" + + " provided a host, port, base, search filter," + + " and optionally a username and password," + + " return an array of string values both as a" + + " function return and as a Property change event." ); + } catch (Exception e) { + } + } + + public BeanDescriptor getBeanDescriptor() { + return _beanDescriptor; + } + + private static Class beanClass; + private BeanDescriptor _beanDescriptor; + private EventSetDescriptor[] _eventSetDescriptor; + private PropertyDescriptor[] _propertyDescriptor; +} + + diff --git a/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPBasePropertySupport.java b/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPBasePropertySupport.java new file mode 100644 index 00000000000..8669e63fae8 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPBasePropertySupport.java @@ -0,0 +1,341 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.beans; + +import netscape.ldap.*; +import java.util.StringTokenizer; + +// This class has a bound property +import java.beans.PropertyChangeListener; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeSupport; +import java.io.Serializable; + +/** + * This is a base class that is extended by various specialized LDAP + * Beans. It provides the common properties and accessors used by + * them. + */ + +public class LDAPBasePropertySupport implements Serializable { + + /** + * Constructor with no parameters + */ + public LDAPBasePropertySupport() {} + + /** + * Returns the host to search at. + * @return DNS name or dotted IP name of host to search at + */ + public String getHost() { + return _host; + } + + /** + * Sets host string. + * @param theHost host name + */ + public void setHost( String theHost ) { + _host = theHost; + } + + /** + * Returns the port to search at. + * @return Port to search at + */ + public int getPort() { + return _port; + } + + /** + * Sets port number. + * @param thePort port + */ + public void setPort( int thePort ) { + _port = thePort; + } + + /** + * Returns the directory base to search at. + * @return directory base to search + */ + public String getBase() { + return _base; + } + + /** + * Sets the starting base + * @param theBase starting base + */ + public void setBase( String theBase ) { + _base = theBase; + } + + /** + * Returns the DN to authenticate as; null or empty for anonymous. + * @return DN to authenticate as + */ + public String getAuthDN() { + return _authDN; + } + + /** + * Sets the DN to authenticate as; null or empty for anonymous. + * @param authDN the DN to authenticate as + */ + public void setAuthDN( String authDN ) { + this._authDN = authDN; + } + + /** + * Returns the password for the DN to authenticate as + * @return Password of DN to authenticate as + */ + public String getAuthPassword() { + return _authPassword; + } + + /** + * Sets the password for the DN to authenticate as + * @param authPassword the password to use in authentication + */ + public void setAuthPassword( String authPassword ) { + this._authPassword = authPassword; + } + + /** + * Returns the user name + * @return The user name + */ + public String getUserName() { + return _userName; + } + + /** + * Set the user name. The name should be of the form "Polly Plum". + * @param name The user name + */ + public void setUserName( String name ) { + _userName = name; + } + + /** + * Return the user ID. + * @return name the user id + */ + public String getUserID() { + return _userID; + } + + /** + * Set the user ID. + * @param name the value of the user id + */ + public void setUserID( String name ) { + _userID = name; + } + + /** + * Get the current search scope + * @return the current search scope as integer + */ + public int getScope() { + return _scope; + } + + /** + * Set the search scope using an integer + * @param scope one of LDAPConnection.SCOPE_BASE, + * LDAPConnection.SCOPE_SUB, LDAPConnection.SCOPE_ONE + */ + public void setScope( int scope ) { + _scope = scope; + } + + /** + * Returns the search filter + * @return search filter + */ + public String getFilter() { + return _filter; + } + + /** + * Sets the search filter + * @param filter search filter + */ + public void setFilter( String filter ) { + _filter = filter; + } + + /** + * Returns true if debug output is on + * @return true if debug output is on + */ + public boolean getDebug() { + return _debug; + } + + /** + * Turns debug output on or off + * @param on true for debug output + */ + public void setDebug( boolean on ) { + _debug = on; + } + + /** + * Returns the latest error code + * @return The latest error code + */ + public int getErrorCode() { + return _errCode; + } + + /** + * Sets an error code for retrieval by a client + * @param code An error code + */ + public void setErrorCode( int code ) { + _errCode = code; + } + + /** + * Add a client to be notified when an authentication result is in + * @param listener a client to be notified of changes + */ + public void addPropertyChangeListener( PropertyChangeListener listener ) { + System.out.println( "Adding listener " + listener ); + m_propSupport.addPropertyChangeListener( listener ); + } + + /** + * Remove a client which had requested notification on authentication + * @param listener a client to not be notified of changes + */ + public void removePropertyChangeListener( + PropertyChangeListener listener ) { + m_propSupport.removePropertyChangeListener( listener ); + } + + /** + * Support for bound property notification + * @param propName Name of changed property + * @param oldValue Previous value of property + * @param newValue New value of property + */ + public void firePropertyChange( + String propName, + Object oldValue, + Object newValue ) { + + if (m_propSupport == null) + m_propSupport = new PropertyChangeSupport( this ); + + m_propSupport.firePropertyChange( propName, oldValue, newValue ); + } + + protected void printDebug( String s ) { + if ( _debug ) + System.out.println( s ); + } + + /** + * Sets up basic connection privileges for Communicator if necessary, + * and connects + * @param host Host to connect to. + * @param port Port number. + * @exception LDAPException from connect() + */ + protected void connect( LDAPConnection conn, String host, int port ) + throws LDAPException { + boolean needsPrivileges = true; + /* Running standalone? */ + SecurityManager sec = System.getSecurityManager(); + printDebug( "Security manager = " + sec ); + if ( sec == null ) { + printDebug( "No security manager" ); + /* Not an applet, we can do what we want to */ + needsPrivileges = false; + /* Can't do instanceof on an abstract class */ + } else if ( sec.toString().startsWith("java.lang.NullSecurityManager") ) { + printDebug( "No security manager" ); + /* Not an applet, we can do what we want to */ + needsPrivileges = false; + } else if ( sec.toString().startsWith( + "netscape.security.AppletSecurity" ) ) { + + /* Connecting to the local host? */ + try { + if ( host.equalsIgnoreCase( + java.net.InetAddress.getLocalHost().getHostName() ) ) + needsPrivileges = false; + } catch ( java.net.UnknownHostException e ) { + } + } + + if ( needsPrivileges ) { + /* Running as applet. Is PrivilegeManager around? */ + String mgr = "netscape.security.PrivilegeManager"; + try { + Class c = Class.forName( mgr ); + java.lang.reflect.Method[] m = c.getMethods(); + if ( m != null ) { + for( int i = 0; i < m.length; i++ ) { + if ( m[i].getName().equals( "enablePrivilege" ) ) { + try { + Object[] args = new Object[1]; + args[0] = new String( "UniversalConnect" ); + m[i].invoke( null, args ); + printDebug( "UniversalConnect enabled" ); + } catch ( Exception e ) { + printDebug( "Exception on invoking " + + "enablePrivilege: " + + e.toString() ); + break; + } + break; + } + } + } + } catch ( ClassNotFoundException e ) { + printDebug( "no " + mgr ); + } + } + + conn.connect( host, port ); + } + + /* + * Variables + */ + private boolean _debug = false; + private int _errCode = 0; + private String _host = new String("localhost"); + private int _port = 389; + private int _scope = LDAPConnection.SCOPE_SUB; + private String _base = new String(""); + private String _filter = new String(""); + private String _authDN = new String(""); + private String _authPassword = new String(""); + private String _userName = new String(""); + private String _userID = new String(""); + transient private PropertyChangeSupport m_propSupport = + new PropertyChangeSupport( this ); +} diff --git a/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPGetEntries.java b/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPGetEntries.java new file mode 100644 index 00000000000..c16f2eec1c4 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPGetEntries.java @@ -0,0 +1,341 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.beans; + +import netscape.ldap.*; +import netscape.ldap.beans.LDAPBasePropertySupport; +import java.util.Enumeration; +import java.util.Vector; +import java.io.Serializable; +import java.awt.event.*; + + +/** + * Invisible Bean that just takes a host, port, directory base, + * search string, and optional authentication name and password, + * and returns a list of all matching DNs. The search has the scope + * "SUB", which means that it will find an entry anywhere at or + * below the directory base, unless a different scope is specified. + *

+ * Optionally, a client can register as a PropertyChangeListener + * and will be notified when the values are available. + *

+ * A null result means no matching DNs were found. The reason is + * available through getErrorCode(), which returns one of + * the following: + *
+ *     OK
+ *     INVALID_PARAMETER
+ *     CONNECT_ERROR
+ *     AUTHENTICATION_ERROR
+ *     PROPERTY_NOT_FOUND
+ *     AMBIGUOUS_RESULTS
+ *
+ * + */ +public class LDAPGetEntries extends LDAPBasePropertySupport implements Serializable { + + /** + * Constructor with no parameters + */ + public LDAPGetEntries() { + super(); + } + + /** + * Constructor with host, port, and base initializers + * @param theHost host string + * @param thePort port number + * @param theBase directory base string + */ + public LDAPGetEntries( String theHost, int thePort, String theBase ) { + setHost( theHost ); + setPort( thePort ); + setBase( theBase ); + } + + /** + * Constructor with host, port, base, and scope initializers + * @param theHost host string + * @param thePort port number + * @param theBase directory base string + * @param theScope one of LDAPConnection.SCOPE_BASE, + * LDAPConnection.SCOPE_SUB, LDAPConnection.SCOPE_ONE + */ + public LDAPGetEntries( String theHost, + int thePort, + String theBase, + int theScope ) { + setHost( theHost ); + setPort( thePort ); + setBase( theBase ); + setScope( theScope ); + } + + private String convertToStrings( String[] aResult ) { + String sResult = ""; + if ( null != aResult ) { + for ( int i = 0; i < aResult.length; i++ ) { + sResult += aResult[i] + "\n"; + } + } + return sResult; + } + + private void notifyResult( String error ) { + firePropertyChange( "error", _errorMsg, error ); + _errorMsg = error; + } + + private void notifyResult( String[] newResult ) { + String sNewResult = convertToStrings( newResult ); + firePropertyChange( "result", result, newResult ); + _sResult = sNewResult; + result = newResult; + } + + public void setResultString( String sNewValue ) { + _sResult = sNewValue; + } + + public String getResultString() { + return _sResult; + } + + /** + * Searches and returns values for a specified attribute + * @param host host string + * @param port port number + * @param base directory base string + * @param scope one of LDAPConnection.SCOPE_BASE, + * LDAPConnection.SCOPE_SUB, LDAPConnection.SCOPE_ONE + * @param filter search filter + * @param attribute name of property to return values for + * @return Array of values for the property + */ + public String[] getEntries( String host, + int port, + String base, + int scope, + String filter) { + setHost( host ); + setPort( port ); + setBase( base ); + setScope( scope ); + setFilter( filter ); + return getEntries(); + } + + /** + * Searches and returns values for a specified attribute + * @param host host string + * @param port port number + * @param base directory base string + * @param scope one of LDAPConnection.SCOPE_BASE, + * LDAPConnection.SCOPE_SUB, LDAPConnection.SCOPE_ONE + * @param userName The user name + * @param userid The user id + * @return Array of DNs + */ + public String[] getEntries( String host, + int port, + String base, + int scope, + String userid, + String userName) { + setHost( host ); + setPort( port ); + setBase( base ); + setScope( scope ); + if (userName == null) + userName = new String(""); + setUserName( userName ); + if (userid == null) + userid = new String(""); + setUserID( userid ); + return getEntries(); + } + + // Added this method in order to get exposed in BDK + public void getEntries(ActionEvent x) { + getEntries(); + } + + /** + * Searches and returns values of a previously registered property, + * using previously set parameters + * @return Array of values for the property + */ + public String[] getEntries() { + boolean invalid = false; + if ((getUserName().length() < 1) && (getUserID().length() < 1) && + (getFilter().length() < 1)) { + printDebug("No user name or user ID"); + invalid = true; + } else if ( (getHost().length() < 1) || (getBase().length() < 1) ) { + printDebug( "Invalid host name or search base" ); + invalid = true; + } + if ( invalid ) { + setErrorCode( INVALID_PARAMETER ); + notifyResult( (String)null); + return null; + } + + if (getFilter().length() < 1) { + String filter = new String(""); + if ((getUserName().length() > 1) && (getUserID().length() > 1)) { + filter = "(|(cn="+getUserName()+")(uid="+getUserID()+"))"; + } else if (getUserName().length() > 1) { + filter = "cn="+getUserName(); + } else if (getUserID().length() > 1) { + filter = "uid="+getUserID(); + } + setFilter(filter); + } + + String[] res = null; + LDAPConnection m_ldc = new LDAPConnection(); + try { + try { + printDebug("Connecting to " + getHost() + + " " + getPort()); + connect( m_ldc, getHost(), getPort()); + } catch (Exception e) { + printDebug( "Failed to connect to " + getHost() + ": " + + e.toString() ); + setErrorCode( CONNECT_ERROR ); + notifyResult( (String)null ); + m_ldc = null; + throw( new Exception() ); + } + + // Authenticate? + if ( (!getAuthDN().equals("")) && + (!getAuthPassword().equals("")) ) { + + printDebug( "Authenticating " + getAuthDN() ); + try { + m_ldc.authenticate( getAuthDN(), getAuthPassword() ); + } catch (Exception e) { + printDebug( "Failed to authenticate: " + e.toString() ); + setErrorCode( AUTHENTICATION_ERROR ); + notifyResult( (String)null ); + throw( new Exception() ); + } + } + + // Search + try { + printDebug("Searching " + getBase() + + " for " + getFilter() + ", scope = " + getScope()); + String[] attrs = null; + LDAPSearchResults results = m_ldc.search( getBase(), + getScope(), + getFilter(), + attrs, + false); + + // Create a vector for the results + Vector v = new Vector(); + LDAPEntry entry = null; + while ( results.hasMoreElements() ) { + try { + entry = (LDAPEntry)results.next(); + } catch (LDAPReferralException e) { + if (getDebug()) { + notifyResult("Referral URLs: "); + LDAPUrl refUrls[] = e.getURLs(); + for (int i = 0; i < refUrls.length; i++) + notifyResult(refUrls[i].getUrl()); + } + continue; + } catch (LDAPException e) { + if (getDebug()) + notifyResult(e.toString()); + continue; + } + String dn = entry.getDN(); + v.addElement( dn ); + printDebug( "... " + dn ); + } + // Pull out the DNs and create a string array + if ( v.size() > 0 ) { + res = new String[v.size()]; + for( int i = 0; i < v.size(); i++ ) + res[i] = (String)v.elementAt( i ); + setErrorCode( OK ); + } else { + printDebug( "No entries found for " + getFilter() ); + setErrorCode( PROPERTY_NOT_FOUND ); + } + } catch (Exception e) { + printDebug( "Failed to search for " + getFilter() + ": " + + e.toString() ); + setErrorCode( PROPERTY_NOT_FOUND ); + } + } catch (Exception e) { + } + + try { + if ( (m_ldc != null) && m_ldc.isConnected() ) + m_ldc.disconnect(); + } catch ( Exception e ) { + } + + notifyResult( res ); + return res; + } + + /** + * The main body if we run it as application instead of applet. + * @param args list of arguments + */ + public static void main(String args[]) { + if (args.length != 5) { + System.out.println( "Usage: LDAPGetEntries host port base" + + " scope filter" ); + System.exit(1); + } + LDAPGetEntries app = new LDAPGetEntries(); + app.setHost( args[0] ); + app.setPort( java.lang.Integer.parseInt( args[1] ) ); + app.setBase( args[2] ); + app.setScope( Integer.parseInt(args[3]) ); + app.setFilter( args[4] ); + String[] response = app.getEntries(); + if ( response != null ) { + for( int i = 0; i < response.length; i++ ) + System.out.println( "\t" + response[i] ); + } + System.exit(0); + } + + /* + * Variables + */ + public static final int OK = 0; + public static final int INVALID_PARAMETER = 1; + public static final int CONNECT_ERROR = 2; + public static final int AUTHENTICATION_ERROR = 3; + public static final int PROPERTY_NOT_FOUND = 4; + public static final int AMBIGUOUS_RESULTS = 5; + transient private String[] result; + private String _sResult = null; + private String _errorMsg = null; +} diff --git a/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPGetEntriesBeanInfo.java b/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPGetEntriesBeanInfo.java new file mode 100644 index 00000000000..45d54c03ccf --- /dev/null +++ b/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPGetEntriesBeanInfo.java @@ -0,0 +1,129 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.beans; + +import java.beans.SimpleBeanInfo; +import java.beans.BeanDescriptor; +import java.beans.EventSetDescriptor; +import java.beans.MethodDescriptor; +import java.beans.PropertyDescriptor; +import java.beans.ParameterDescriptor; +import java.beans.BeanInfo; + +/** + * BeanInfo for LDAPGetEntries + */ + +public class LDAPGetEntriesBeanInfo extends SimpleBeanInfo { + + public LDAPGetEntriesBeanInfo() throws Exception { + + beanClass = Class.forName( "netscape.ldap.beans.LDAPGetEntries" ); + + try { + PropertyDescriptor host = + new PropertyDescriptor("host", beanClass); + PropertyDescriptor port = + new PropertyDescriptor("port", beanClass); + PropertyDescriptor authDN = + new PropertyDescriptor("authDN", beanClass); + PropertyDescriptor authPassword = + new PropertyDescriptor("authPassword", beanClass); + PropertyDescriptor base = + new PropertyDescriptor("base", beanClass); + PropertyDescriptor userName = + new PropertyDescriptor("userName", beanClass); + PropertyDescriptor userID = + new PropertyDescriptor("userID", beanClass); + PropertyDescriptor filter = + new PropertyDescriptor("filter", beanClass); + PropertyDescriptor scope = + new PropertyDescriptor("scope", beanClass); + PropertyDescriptor debug = + new PropertyDescriptor("debug", beanClass); + + PropertyDescriptor rv[] = + {host, port, authDN, authPassword, base, filter, + scope, userName, userID, debug}; + _propertyDescriptor = new PropertyDescriptor[rv.length]; + for( int i = 0; i < rv.length; i++ ) + _propertyDescriptor[i] = rv[i]; + } catch (Exception e) { + throw new Error(e.toString()); + } + + // Publish events -------------------------------------------------- + try { + _eventSetDescriptor = new EventSetDescriptor[1]; + + _eventSetDescriptor[0] = new EventSetDescriptor(beanClass, + "propertyChange", + Class.forName("java.beans.PropertyChangeListener"), + "propertyChange"); + } catch (Exception e) { + throw new Error(e.toString()); + } + + // Publish descriptor --------------------------------------------- + try { + _beanDescriptor = new BeanDescriptor(beanClass); + _beanDescriptor.setDisplayName( "LDAP entry retrieval" ); + _beanDescriptor.setShortDescription( + "LDAP property retrieval -" + + " provided a host, port, base, search filter," + + " and optionally a username and password," + + " return an array of string values both as a" + + " function return and as a Property change event." ); + } catch (Exception e) { + } + } + + /** + * @return the public properties + */ + public PropertyDescriptor[] getPropertyDescriptors() { + return _propertyDescriptor; + } + + public EventSetDescriptor[] getEventSetDescriptors() { + return _eventSetDescriptor; + } + + public BeanInfo[] getAdditionalBeanInfo() { + return null; + } + + public int getDefaultEventIndex() { + return -1; + } + + public int getDefaultPropertyIndex() { + return -1; + } + + public BeanDescriptor getBeanDescriptor() { + return _beanDescriptor; + } + + private static Class beanClass; + private BeanDescriptor _beanDescriptor; + private EventSetDescriptor[] _eventSetDescriptor; + private PropertyDescriptor[] _propertyDescriptor; +} + + diff --git a/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPGetProperty.java b/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPGetProperty.java new file mode 100644 index 00000000000..da7f110325e --- /dev/null +++ b/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPGetProperty.java @@ -0,0 +1,355 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.beans; + +import netscape.ldap.*; +import netscape.ldap.beans.LDAPBasePropertySupport; +import java.util.Enumeration; +import java.util.Vector; +import java.io.Serializable; +import java.beans.*; +import java.awt.event.*; + + +/** + * Invisible Bean that just takes a name and password, host and + * port, and directory base and attribute name, and returns an + * attribute's values from a Directory Server. The values are + * assumed to be strings, and are returned as an array. The + * search has the scope "SUB", which means that it will find + * an entry anywhere at or below the directory base. + *

+ * Optionally, a client can register as a PropertyChangeListener + * and will be notified when the values are available. + *

+ * A null result means the property fetch failed. The reason is + * available through getErrorCode(), which returns one of + * the following: + *
+ *     OK
+ *     INVALID_PARAMETER
+ *     CONNECT_ERROR
+ *     AUTHENTICATION_ERROR
+ *     PROPERTY_NOT_FOUND
+ *     AMBIGUOUS_RESULTS
+ *
+ */ +public class LDAPGetProperty extends LDAPBasePropertySupport implements + Serializable { + + /** + * Constructor with no parameters + */ + public LDAPGetProperty() {} + + /** + * Constructor with host, port, and base initializers + * @param theHost host string + * @param thePort port number + * @param theBase directory base string + */ + public LDAPGetProperty( String theHost, int thePort, String theBase ) { + setHost( theHost ); + setPort( thePort ); + setBase( theBase ); + } + + /** + * Returns the name of the attribute to retrieve + * @return attribute name to retrieve + */ + public String getAttribute() { + return attribute; + } + + /** + * Sets the attribute to retrieve + */ + public void setAttribute( String attr ) { + attribute = attr; + } + + private String convertToStrings( String[] aResult ) { + String sResult = ""; + if ( null != aResult ) { + for ( int i = 0; i < aResult.length; i++ ) { + sResult += aResult[i] + "\n"; + } + } + return sResult; + } + + private void notifyResult( String[] newResult ) { + String sNewResult = convertToStrings( newResult ); + firePropertyChange( "result", result, newResult ); + // firePropertyChange( "resultString", _sResult, sNewResult ); + _sResult = sNewResult; + result = newResult; + } + + private void notifyResult( Vector newResult ) { + firePropertyChange( "result", resultV, newResult ); + resultV = (Vector)newResult.clone(); + } + + private void notifyResult( String error ) { + firePropertyChange( "error", _errorMsg, error ); + _errorMsg = error; + } + + public void setDNs(PropertyChangeEvent evt) { + Object obj = (Object)evt.getNewValue(); + if ((obj != null) && (obj instanceof String[])) { + String[] strings = (String[])obj; + if (strings.length == 0) + return; + _dns = new String[strings.length]; + System.arraycopy(obj, 0, _dns, 0, strings.length); + System.out.println("length of dns -> "+_dns.length); + } + } + + /** + * Searches and returns values for a specified attribute + * @param host host string + * @param port port number + * @param base directory base string + * @param filter search filter + * @param attribute name of property to return values for + * @return Array of values for the property + */ + public String[] getProperty( String host, int port, String base, + String filter, String attribute) { + setHost( host ); + setPort( port ); + setBase( base ); + setFilter( filter ); + setAttribute( attribute ); + return getProperty(); + } + + // Added this method in order to get exposed in BDK + public void getProperty(ActionEvent x) { + getProperty(); + } + + /** + * Searches and returns values of a previously registered property, + * using previously set parameters + * @return Array of values for the property + */ + public String[] getProperty() { + if ( (attribute.length() < 1) || (getFilter().length() < 1) ) { + printDebug( "Invalid attribute name or filter" ); + setErrorCode( INVALID_PARAMETER ); + notifyResult( (String[])null ); + return null; + } + + String[] res = null; + LDAPConnection m_ldc; + try { + m_ldc = new LDAPConnection(); + printDebug("Connecting to " + getHost() + + " " + getPort()); + connect( m_ldc, getHost(), getPort()); + } catch (Exception e) { + printDebug( "Failed to connect to " + getHost() + ": " + + e.toString() ); + setErrorCode( CONNECT_ERROR ); + notifyResult( (String[])null ); + return null; + } + + // Authenticate? + if (_dns != null) { + for (int i=0; i<_dns.length; i++) { + try { + m_ldc.authenticate(_dns[i], getAuthPassword()); + break; + } catch (Exception e) { + if (i == _dns.length-1) { + printDebug( "Failed to authenticate to " + + getHost() + ": " + e.toString() ); + setErrorCode( AUTHENTICATION_ERROR ); + notifyResult( (String[])null ); + return null; + } + } + } + } else if ( (!getAuthDN().equals("")) && (!getAuthPassword().equals("")) ) { + printDebug( "Authenticating " + getAuthDN() + " - " + + getAuthPassword() ); + try { + m_ldc.authenticate( getAuthDN(), getAuthPassword() ); + } catch (Exception e) { + printDebug( "Failed to authenticate to " + + getHost() + ": " + e.toString() ); + setErrorCode( AUTHENTICATION_ERROR ); + notifyResult( (String[])null ); + return null; + } + } + + int numDataEntries = 0; + // Search + try { + String[] attrs = new String[1]; + attrs[0] = attribute; + LDAPSearchResults results = m_ldc.search(getBase(), + getScope(), + getFilter(), + attrs, false); + + // Should be only one result, at most + LDAPEntry currEntry = null; + LDAPEntry entry = null; + while ( results.hasMoreElements() ) { + try { + currEntry = results.next(); + if (numDataEntries == 0) + entry = currEntry; + if (++numDataEntries > 1) { + printDebug( "More than one entry found for " + + getFilter() ); + setErrorCode( AMBIGUOUS_RESULTS ); + break; + } + } catch (LDAPReferralException e) { + if (getDebug()) { + notifyResult("Referral URLs: "); + LDAPUrl refUrls[] = e.getURLs(); + for (int i = 0; i < refUrls.length; i++) + notifyResult(refUrls[i].getUrl()); + } + continue; + } catch (LDAPException e) { + if (getDebug()) + notifyResult(e.toString()); + continue; + } + } + if (numDataEntries == 1) { + printDebug( "... " + entry.getDN() ); + // Good - exactly one entry found; get the attribute + // Treat DN as a special case + if ( attribute.equalsIgnoreCase( "dn" ) ) { + res = new String[1]; + res[0] = entry.getDN(); + setErrorCode( OK ); + } else { + LDAPAttributeSet attrset = entry.getAttributeSet(); + Enumeration attrsenum = attrset.getAttributes(); + if (attrsenum.hasMoreElements()) { + LDAPAttribute attr = + (LDAPAttribute)attrsenum.nextElement(); + printDebug( attr.getName() + " = " ); + // Get the values as strings + Enumeration valuesenum = attr.getStringValues(); + if (valuesenum != null) { + // Create a string array for the results + Vector v = new Vector(); + while (valuesenum.hasMoreElements()) { + String val = (String)valuesenum.nextElement(); + v.addElement( val ); + printDebug( "\t\t" + val ); + } + res = new String[v.size()]; + for( int i = 0; i < v.size(); i++ ) + res[i] = (String)v.elementAt( i ); + setErrorCode( OK ); + } else { + Enumeration byteEnum = attr.getByteValues(); + Vector v = new Vector(); + while (byteEnum.hasMoreElements()) { + byte[] val = (byte[])byteEnum.nextElement(); + v.addElement( val ); + printDebug( "\t\t" + val ); + } + setErrorCode( OK ); + notifyResult(v); + return (res = null); + } + } else { + printDebug( "No properties found for " + + attribute ); + setErrorCode( PROPERTY_NOT_FOUND ); + } + } + } + } catch (Exception e) { + printDebug( "Failed to search for " + getFilter() + ": " + + e.toString() ); + setErrorCode( PROPERTY_NOT_FOUND ); + } + + if (numDataEntries == 0) { + printDebug( "No entries found for " + getFilter() ); + setErrorCode( PROPERTY_NOT_FOUND ); + } + + try { + if ( (m_ldc != null) && m_ldc.isConnected() ) + m_ldc.disconnect(); + } catch ( Exception e ) { + } + + notifyResult( res ); + return res; + } + + /** + * The main body if we run it as application instead of applet. + * @param args list of arguments + */ + public static void main(String args[]) { + if (args.length != 5) { + System.out.println( "Usage: LDAPGetProperty host port base" + + " filter attribute" ); + System.exit(1); + } + LDAPGetProperty app = new LDAPGetProperty(); + app.setHost( args[0] ); + app.setPort( java.lang.Integer.parseInt( args[1] ) ); + app.setBase( args[2] ); + app.setFilter( args[3] ); + app.setAttribute( args[4] ); + String[] response = app.getProperty(); + if ( response != null ) { + for( int i = 0; i < response.length; i++ ) + System.out.println( "\t" + response[i] ); + } + System.exit(0); + } + + /* + * Variables + */ + public static final int OK = 0; + public static final int INVALID_PARAMETER = 1; + public static final int CONNECT_ERROR = 2; + public static final int AUTHENTICATION_ERROR = 3; + public static final int PROPERTY_NOT_FOUND = 4; + public static final int AMBIGUOUS_RESULTS = 5; + private String[] _dns = null; + private String attribute = new String("cn"); + transient private String[] result; + private Vector resultV = null; + private String _sResult = null; + private String _errorMsg = null; +} diff --git a/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPGetPropertyBeanInfo.java b/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPGetPropertyBeanInfo.java new file mode 100644 index 00000000000..00b967449b8 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPGetPropertyBeanInfo.java @@ -0,0 +1,138 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.beans; + +import java.beans.SimpleBeanInfo; +import java.beans.BeanDescriptor; +import java.beans.EventSetDescriptor; +import java.beans.MethodDescriptor; +import java.beans.PropertyDescriptor; +import java.beans.ParameterDescriptor; +import java.beans.BeanInfo; + + +/** + * BeanInfo for LDAPGetProperty + */ + +public class LDAPGetPropertyBeanInfo extends SimpleBeanInfo { + + public LDAPGetPropertyBeanInfo() throws Exception { + + beanClass = Class.forName( "netscape.ldap.beans.LDAPGetProperty" ); + + try { + PropertyDescriptor host = + new PropertyDescriptor("host", beanClass); + PropertyDescriptor port = + new PropertyDescriptor("port", beanClass); + PropertyDescriptor authDN = + new PropertyDescriptor("authDN", beanClass); + PropertyDescriptor authPassword = + new PropertyDescriptor("authPassword", beanClass); + PropertyDescriptor base = + new PropertyDescriptor("base", beanClass); + PropertyDescriptor filter = + new PropertyDescriptor("filter", beanClass); + PropertyDescriptor scope = + new PropertyDescriptor("scope", beanClass); + PropertyDescriptor attribute = + new PropertyDescriptor("attribute", beanClass); + PropertyDescriptor debug = + new PropertyDescriptor("debug", beanClass); + + PropertyDescriptor rv[] = + {host, port, authDN, authPassword, base, scope, attribute, + filter, debug}; + _propertyDescriptor = new PropertyDescriptor[rv.length]; + for( int i = 0; i < rv.length; i++ ) + _propertyDescriptor[i] = rv[i]; + } catch (Exception e) { + throw new Error(e.toString()); + } + + // Publish events -------------------------------------------------- + try { + _eventSetDescriptor = new EventSetDescriptor[1]; + + _eventSetDescriptor[0] = new EventSetDescriptor(beanClass, + "propertyChange", + Class.forName("java.beans.PropertyChangeListener"), + "propertyChange"); + + + } catch (Exception e) { + throw new Error(e.toString()); + } + + // Publish descriptor --------------------------------------------- + try { + _beanDescriptor = new BeanDescriptor(beanClass); + _beanDescriptor.setDisplayName( "LDAP property retrieval" ); + _beanDescriptor.setShortDescription( + "LDAP property retrieval -" + + " provided a host, port, base, search filter," + + " and optionally a username and password," + + " return an array of string values both as a" + + " function return and as a Property change event." ); + } catch (Exception e) { + } + } + + /** + * @return the public properties + */ + public PropertyDescriptor[] getPropertyDescriptors() { + return _propertyDescriptor; + } + + /** + * @return the public methods + */ + public MethodDescriptor[] getMethodDescriptors() { + return _methodDescriptor; + } + + public EventSetDescriptor[] getEventSetDescriptors() { + return _eventSetDescriptor; + } + + public BeanInfo[] getAdditionalBeanInfo() { + return null; + } + + public int getDefaultEventIndex() { + return -1; + } + + public int getDefaultPropertyIndex() { + return -1; + } + + public BeanDescriptor getBeanDescriptor() { + return _beanDescriptor; + } + + private static Class beanClass; + private BeanDescriptor _beanDescriptor; + private EventSetDescriptor[] _eventSetDescriptor; + private MethodDescriptor[] _methodDescriptor; + private PropertyDescriptor[] _propertyDescriptor; +} + + diff --git a/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPIsMember.java b/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPIsMember.java new file mode 100644 index 00000000000..5b9c76bd562 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPIsMember.java @@ -0,0 +1,356 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.beans; + +import netscape.ldap.*; +import java.util.Enumeration; +import java.util.StringTokenizer; +import java.io.Serializable; +import java.awt.event.*; + +/** + * Invisible Bean that just takes a host and port, optional + * authentication name and password, and DN of a group and another DN + * which might be a member of the group, and returns true or + * false, depending on whether the second DN is a member of the first. + *

+ * A false result means the member could not be identified as + * belonging to the group. The exact reason is + * available through getErrorCode(), which returns one of + * the following: + *
+ *     OK
+ *     INVALID_PARAMETER
+ *     CONNECT_ERROR
+ *     AUTHENTICATION_ERROR
+ *     PROPERTY_NOT_FOUND
+ *     AMBIGUOUS_RESULTS
+ *     NO_SUCH_OBJECT
+ *
+ */ +public class LDAPIsMember extends LDAPBasePropertySupport implements Serializable { + + /** + * Constructor with no parameters + */ + public LDAPIsMember() {} + + /** + * Constructor with host, port, and group DN initializers + * @param host host string + * @param port port number + * @param group distinguished name of the group + */ + public LDAPIsMember( String host, int port, String group ) { + setHost( host ); + setPort( port ); + setGroup( group ); + } + + /** + * Constructor with host, port, authentication DN and password + * and group DN initializers + * @param host host string + * @param port port number + * @param dn fully qualified distinguished name to authenticate + * @param password password for authenticating the dn + * @param group distinguished name of the group + */ + public LDAPIsMember( String host, int port, + String dn, String password, String theGroup ) { + setHost( host ); + setPort( port ); + setGroup( theGroup ); + setAuthDN( dn ); + setAuthPassword( password ); + } + + private void notifyResult( String newResult ) { + firePropertyChange( "result", _result, newResult ); + _result = newResult; + } + + /** + * Checks if an entity (specified by distinguished name) is a + * member of a particular group (specified by distinguished name) + * @return true if the specified member belongs to the group + */ + public boolean isMember() { + String host = getHost(); + int port = getPort(); + String dn = getAuthDN(); + String password = getAuthPassword(); + String group = getGroup(); + String member = getMember(); + _result = new String(""); + + if ( (host == null) || (host.length() < 1) ) { + printDebug( "Invalid host name" ); + setErrorCode( INVALID_PARAMETER ); + notifyResult(null); + return false; + } + + if ( (member == null) || (group == null) || + (member.length() < 1) || (group.length() < 1) ) { + printDebug( "Invalid member or group name" ); + setErrorCode( INVALID_PARAMETER ); + notifyResult(null); + return false; + } + + LDAPConnection m_ldc; + boolean isMember = false; + try { + m_ldc = new LDAPConnection(); + printDebug("Connecting to " + host + + " " + port); + connect( m_ldc, getHost(), getPort()); + } catch (Exception e) { + printDebug( "Failed to connect to " + host + ": " + + e.toString() ); + setErrorCode( CONNECT_ERROR ); + notifyResult(null); + return false; + } + + // Authenticate? + if ( (dn != null) && (password != null) && + (dn.length() > 0) && (password.length() > 0) ) { + printDebug( "Authenticating " + dn + " - " + password ); + try { + m_ldc.authenticate( dn, password ); + } catch (Exception e) { + printDebug( "Failed to authenticate to " + + host + ": " + e.toString() ); + setErrorCode( AUTHENTICATION_ERROR ); + notifyResult(null); + return false; + } + } + + int numDataEntries = 0; + // Search + try { + String[] attrs = new String[3]; + attrs[0] = "member"; + attrs[1] = "uniqueMember"; + attrs[2] = "memberOfGroup"; + LDAPSearchResults results = m_ldc.search( group, + LDAPConnection.SCOPE_BASE, + "objectclass=*", + attrs, false); + + // Should be only one result, at most + LDAPEntry entry = null; + LDAPEntry currEntry = null; + while ( results.hasMoreElements() ) { + try { + currEntry = (LDAPEntry)results.next(); + if (numDataEntries == 0) + entry = currEntry; + if (++numDataEntries > 1) { + printDebug( "More than one entry found for " + + getFilter() ); + setErrorCode( AMBIGUOUS_RESULTS ); + break; + } + } catch (LDAPReferralException e) { + if (getDebug()) { + notifyResult("Referral URLs: "); + LDAPUrl refUrls[] = e.getURLs(); + for (int i = 0; i < refUrls.length; i++) + notifyResult(refUrls[i].getUrl()); + } + continue; + } catch (LDAPException e) { + if (getDebug()) + notifyResult(e.toString()); + continue; + } + } + if (numDataEntries == 1) { + printDebug( "... " + entry.getDN() ); + String normMember = normalizeDN( member ); + // Good - exactly one entry found; get the attributes + LDAPAttributeSet attrset = entry.getAttributeSet(); + Enumeration attrsenum = attrset.getAttributes(); + while ( attrsenum.hasMoreElements() && !isMember ) { + LDAPAttribute attr = + (LDAPAttribute)attrsenum.nextElement(); + printDebug( attr.getName() + " = " ); + // Get the values as strings + Enumeration valuesenum = attr.getStringValues(); + if (valuesenum != null) { + while (valuesenum.hasMoreElements()) { + String val = (String)valuesenum.nextElement(); + printDebug( "\t\t" + val ); + String normFound = normalizeDN( val ); + if ( normMember.equalsIgnoreCase( normFound ) ) { + isMember = true; + setErrorCode( OK ); + break; + } + } + } else { + setErrorCode(PROPERTY_NOT_FOUND); + printDebug("Failed to do string conversion for "+ attr.getName()); + } + } + if ( !isMember ) + setErrorCode( PROPERTY_NOT_FOUND ); + } + } catch (Exception e) { + printDebug( "Failed to search for " + group + ": " + + e.toString() ); + setErrorCode( NO_SUCH_OBJECT ); + } + + if (numDataEntries == 0) { + printDebug( "No entries found for " + group ); + setErrorCode( NO_SUCH_OBJECT ); + } + + try { + if ( (m_ldc != null) && m_ldc.isConnected() ) + m_ldc.disconnect(); + } catch ( Exception e ) { + } + + if (isMember) + notifyResult("Y"); + else + notifyResult("N"); + + return isMember; + } + + /** + * Checks if an entity (specified by distinguished name) is a + * member of a particular group (specified by distinguished name) + * @param host host string + * @param port port number + * @param dn fully qualified distinguished name to authenticate; + * can be null or "" + * @param password password for authenticating the dn; can be null + * or "" + * @param group distinguished name of the group + * @param member distinguished name of member to be checked + * @return true if the specified member belongs to the group + */ + public boolean isMember( String host, int port, + String dn, String password, + String group, String member ) { + setHost(host); + setPort(port); + setAuthDN(dn); + setAuthPassword(password); + setGroup(group); + setMember(member); + return isMember(); + } + + /** + * Checks if an entity (specified by distinguished name) is a + * member of a particular group (specified by distinguished name) + * @return true if the specified member belongs to the group + */ + public void isMember(ActionEvent e) { + isMember(); + } + + /** + * Returns the distinguished name of the group + * @return group name + */ + public String getGroup() { + return _group; + } + + /** + * Sets the distinguished name of the group + * @param group group name + */ + public void setGroup( String group ) { + _group = group; + } + + /** + * Returns the distinguished name of the member + * @return member name + */ + public String getMember() { + return _member; + } + + /** + * Sets the distinguished name of the member + * @param member member name + */ + public void setMember( String member ) { + _member = member; + } + + private String normalizeDN( String dn ) { + StringTokenizer st = new StringTokenizer( dn, "," ); + String norm = ""; + if( st.hasMoreTokens() ) { + norm = st.nextToken(); + while( st.hasMoreTokens() ) + norm = norm + "," + st.nextToken().trim(); + } + return norm; + } + + /** + * The main body if we run it as application instead of applet. + * @param args list of arguments + */ + public static void main(String args[]) { + if (args.length != 4) { + System.out.println( "Usage: LDAPIsMember host port group" + + " member" ); + System.exit(1); + } + LDAPIsMember app = new LDAPIsMember(); + app.setHost( args[0] ); + app.setPort( java.lang.Integer.parseInt( args[1] ) ); + app.setGroup( args[2] ); + app.setMember( args[3] ); + boolean response = app.isMember(); + if ( response == false ) + System.out.println( "Not a member" ); + else + System.out.println( "Is a member" ); + System.exit(0); + } + + /* + * Variables + */ + public static final int OK = 0; + public static final int INVALID_PARAMETER = 1; + public static final int CONNECT_ERROR = 2; + public static final int AUTHENTICATION_ERROR = 3; + public static final int PROPERTY_NOT_FOUND = 4; + public static final int AMBIGUOUS_RESULTS = 5; + public static final int NO_SUCH_OBJECT = 5; + private String _group = new String(""); + private String _member = new String(""); + private String _result = new String(""); +} diff --git a/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPIsMemberBeanInfo.java b/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPIsMemberBeanInfo.java new file mode 100644 index 00000000000..6d54891c20e --- /dev/null +++ b/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPIsMemberBeanInfo.java @@ -0,0 +1,110 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.beans; + +import java.beans.SimpleBeanInfo; +import java.beans.BeanDescriptor; +import java.beans.EventSetDescriptor; +import java.beans.MethodDescriptor; +import java.beans.PropertyDescriptor; +import java.beans.ParameterDescriptor; +import java.beans.BeanInfo; + +/** + * BeanInfo for LDAPIsMember + */ + +public class LDAPIsMemberBeanInfo extends SimpleBeanInfo { + + public LDAPIsMemberBeanInfo() throws Exception { + + beanClass = Class.forName( "netscape.ldap.beans.LDAPIsMember" ); + // Publish properties ------------------------------------------------- + + try { + PropertyDescriptor host = + new PropertyDescriptor("host", beanClass); + PropertyDescriptor port = + new PropertyDescriptor("port", beanClass); + PropertyDescriptor authDN = + new PropertyDescriptor("authDN", beanClass); + PropertyDescriptor authPassword = + new PropertyDescriptor("authPassword", beanClass); + PropertyDescriptor group = + new PropertyDescriptor("group", beanClass); + PropertyDescriptor member = + new PropertyDescriptor("member", beanClass); + PropertyDescriptor debug = + new PropertyDescriptor("debug", beanClass); + + PropertyDescriptor rv[] = + {host, port, authDN, authPassword, group, member, debug}; + _propertyDescriptor = new PropertyDescriptor[rv.length]; + for( int i = 0; i < rv.length; i++ ) + _propertyDescriptor[i] = rv[i]; + } catch (Exception e) { + throw new Error(e.toString()); + } + + // Publish descriptor --------------------------------------------- + try { + _beanDescriptor = new BeanDescriptor(beanClass); + _beanDescriptor.setDisplayName( "LDAP IsMember" ); + _beanDescriptor.setShortDescription( + "LDAP IsMember -" + + " provided a host, port, group name and member name," + + " and optionally an authentication name and password," + + " return true if the member belongs to the group." ); + } catch (Exception e) { + } + } + + /** + * @return the public properties + */ + public PropertyDescriptor[] getPropertyDescriptors() { + return _propertyDescriptor; + } + + public EventSetDescriptor[] getEventSetDescriptors() { + return _eventSetDescriptor; + } + + public BeanInfo[] getAdditionalBeanInfo() { + return null; + } + + public int getDefaultEventIndex() { + return -1; + } + + public int getDefaultPropertyIndex() { + return -1; + } + + public BeanDescriptor getBeanDescriptor() { + return _beanDescriptor; + } + + private static Class beanClass; + private BeanDescriptor _beanDescriptor; + private EventSetDescriptor[] _eventSetDescriptor; + private PropertyDescriptor[] _propertyDescriptor; +} + + diff --git a/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPSimpleAuth.java b/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPSimpleAuth.java new file mode 100644 index 00000000000..2642515b687 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPSimpleAuth.java @@ -0,0 +1,178 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.beans; + +import netscape.ldap.*; +import netscape.ldap.beans.LDAPBasePropertySupport; +import java.io.Serializable; +import java.awt.event.*; + +/** + * Invisible Bean that just authenticates a user with a Directory + * Server and returns Y or N. It takes a host and port, and then either + * a full distinguished name and password, an RDN and directory base, or + * a cn value and directory base. + *

+ * Optionally, a client can register as + * a PropertyChangeListener and will be notified when an authentication + * completes. + *

+ * The Bean can be used from JavaScript, as in the following example + * where the parameters are taken from HTML text fields in an HTML + * form called "input": + *
+ * 
+ * <SCRIPT LANGUAGE="JavaScript">
+ * function checkAuthentication() {
+ *     auth = new Packages.netscape.ldap.beans.LDAPSimpleAuth();
+ *     auth.setHost( document.input.host.value );
+ *     auth.setPort( parseInt(document.input.port.value) );
+ *     auth.setAuthDN( document.input.username.value );
+ *     auth.setAuthPassword( document.input.password.value );
+ *     result = auth.authenticate();
+ *     alert( "The response is: " + result );
+ * }
+ * </SCRIPT>
+ * 
+ *
+ */ + +public class LDAPSimpleAuth extends LDAPBasePropertySupport implements + Serializable { + + /** + * Constructor with no parameters + */ + public LDAPSimpleAuth() {} + + /** + * Constructor with host and port initializers + * @param theHost host string + * @param thePort port number + */ + public LDAPSimpleAuth( String theHost, + int thePort ) { + setHost( theHost ); + setPort( thePort ); + } + + /** + * Constructor with all required authentication parameters + * @param theHost host string + * @param thePort port number + * @param dn fully qualified distinguished name to authenticate + * @param password password for authenticating the dn + */ + public LDAPSimpleAuth( String theHost, + int thePort, + String dn, + String password ) { + setHost( theHost ); + setPort( thePort ); + setAuthDN( dn ); + setAuthPassword( password ); + } + + private void notifyResult( String newResult ) { + firePropertyChange( "result", result, newResult ); + result = newResult; + } + + /** + * Connect to LDAP server using parameters specified in + * constructor and/or by setting properties and attempt to + * authenticate. + * @return "Y" on successful authentication, "N" otherwise + */ + public String authenticate() { + LDAPConnection m_ldc = null; + String result = "N"; + try { + m_ldc = new LDAPConnection(); + System.out.println("Connecting to " + getHost() + + " " + getPort()); + connect( m_ldc, getHost(), getPort()); + } catch (Exception e) { + System.out.println( "Failed to connect to " + getHost() + + ": " + e.toString() ); + } + if ( m_ldc.isConnected() ) { + System.out.println( "Authenticating " + getAuthDN() ); + try { + m_ldc.authenticate( getAuthDN(), getAuthPassword() ); + result = "Y"; + } catch (Exception e) { + System.out.println( "Failed to authenticate to " + + getHost() + ": " + e.toString() ); + } + } + + try { + if ( (m_ldc != null) && m_ldc.isConnected() ) + m_ldc.disconnect(); + } catch ( Exception e ) { + } + + notifyResult( result ); + return result; + } + + /** + * Connect to LDAP server using parameters specified in + * constructor and/or by setting properties and attempt to + * authenticate. + * @param dn fully qualified distinguished name to authenticate + * @param password password for authenticating the dn + * @return "Y" on successful authentication, "N" otherwise + */ + public String authenticate( String dn, + String password ) { + setAuthDN( dn ); + setAuthPassword( password ); + return authenticate(); + } + + public void authenticate( ActionEvent x) { + authenticate(); + } + + /** + * The main body if we run it as stand-alone application. + * @param args list of arguments + */ + public static void main(String args[]) { + if (args.length != 4) { + System.out.println( " LDAPSimpleAuth " + + "host port DN password" ); + System.exit(1); + } + LDAPSimpleAuth app = new LDAPSimpleAuth(); + app.setHost( args[0] ); + app.setPort( java.lang.Integer.parseInt( args[1] ) ); + app.setAuthDN( args[2] ); + app.setAuthPassword( args[3] ); + String response = app.authenticate(); + System.out.println( "Response: " + response ); + System.exit(0); + } + + /* + * Variables + */ + transient private String result = new String(""); +} diff --git a/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPSimpleAuthBeanInfo.java b/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPSimpleAuthBeanInfo.java new file mode 100644 index 00000000000..94e6f048191 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapbeans/netscape/ldap/beans/LDAPSimpleAuthBeanInfo.java @@ -0,0 +1,118 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.beans; + +import java.beans.SimpleBeanInfo; +import java.beans.BeanDescriptor; +import java.beans.EventSetDescriptor; +import java.beans.MethodDescriptor; +import java.beans.PropertyDescriptor; +import java.beans.ParameterDescriptor; +import java.beans.BeanInfo; + +/** + * BeanInfo for LDAPSimpleAuth + */ + +public class LDAPSimpleAuthBeanInfo extends SimpleBeanInfo { + + public LDAPSimpleAuthBeanInfo() throws Exception { + + beanClass = Class.forName( "netscape.ldap.beans.LDAPSimpleAuth" ); + + try { + PropertyDescriptor host = + new PropertyDescriptor("host", beanClass); + PropertyDescriptor port = + new PropertyDescriptor("port", beanClass); + PropertyDescriptor authDN = + new PropertyDescriptor("authDN", beanClass); + PropertyDescriptor authPassword = + new PropertyDescriptor("authPassword", beanClass); + PropertyDescriptor debug = + new PropertyDescriptor("debug", beanClass); + + PropertyDescriptor rv[] = + {host, port, authDN, authPassword, debug}; + _propertyDescriptor = new PropertyDescriptor[rv.length]; + for( int i = 0; i < rv.length; i++ ) + _propertyDescriptor[i] = rv[i]; + } catch (Exception e) { + throw new Error(e.toString()); + } + + // Publish events -------------------------------------------------- + try { + _eventSetDescriptor = new EventSetDescriptor[1]; + + _eventSetDescriptor[0] = new EventSetDescriptor(beanClass, + "propertyChange", + Class.forName("java.beans.PropertyChangeListener"), + "propertyChange"); + + } catch (Exception e) { + throw new Error(e.toString()); + } + + // Publish descriptor --------------------------------------------- + try { + _beanDescriptor = new BeanDescriptor(beanClass); + _beanDescriptor.setDisplayName( "LDAP user authentication" ); + _beanDescriptor.setShortDescription( + "LDAP user authentication -" + + " provided a host, port, base, username, and password," + + " report if the user can be authenticated both as a" + + " function return and as a Property change event." ); + } catch (Exception e) { + } + } + + /** + * @return the public properties + */ + public PropertyDescriptor[] getPropertyDescriptors() { + return _propertyDescriptor; + } + + public EventSetDescriptor[] getEventSetDescriptors() { + return _eventSetDescriptor; + } + + public BeanInfo[] getAdditionalBeanInfo() { + return null; + } + + public int getDefaultEventIndex() { + return -1; + } + + public int getDefaultPropertyIndex() { + return -1; + } + + public BeanDescriptor getBeanDescriptor() { + return _beanDescriptor; + } + + private static Class beanClass; + private BeanDescriptor _beanDescriptor; + private EventSetDescriptor[] _eventSetDescriptor; + private PropertyDescriptor[] _propertyDescriptor; +} + + diff --git a/mozilla/directory/java-sdk/ldapfilter/netscape/ldap/util/BadFilterException.java b/mozilla/directory/java-sdk/ldapfilter/netscape/ldap/util/BadFilterException.java new file mode 100644 index 00000000000..a34d1f33526 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapfilter/netscape/ldap/util/BadFilterException.java @@ -0,0 +1,83 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.util; + +/** + * The exception thrown when there is a problem with either an LDAPFilter + * or with the File/URL/Buffer form which we're creating the LDAPFilter. + * + * @see LDAPFilter + * @see LDAPFilterDescriptor + * @version 1.0 + */ +public class BadFilterException extends Exception { + + private String m_strException; + private int m_nLine = -1; + + /** + * Creates an Unknown BadFilterException + */ + public BadFilterException () { + m_strException = "Unknown Error"; + } + + /** + * Creates a BadFilterException with the + * given string + */ + public BadFilterException ( String s ) { + m_strException = s; + } + + /** + * Creates a BadFilterException with the + * given string and line number + */ + public BadFilterException ( String s, int nErrorLineNumber ) { + m_strException = s; + m_nLine = nErrorLineNumber; + } + + /** + * Returns the exception string. + */ + public String toString() { + return m_strException; + } + + + /** + * If appropriate, return the line number of the ldapfilter.conf + * file (or url or buffer) where this error occurred. This method + * will return -1 if the line number was not set. + */ + public int getErrorLineNumber() { + return m_nLine; + } + + /** + * Set the line number in the ldapfilter.conf file/url/buffer where + * this error occurred. + */ + void setErrorLineNumber ( int nErrorLineNumber ) { + m_nLine = m_nLine; + } +} + + diff --git a/mozilla/directory/java-sdk/ldapfilter/netscape/ldap/util/LDAPFilter.java b/mozilla/directory/java-sdk/ldapfilter/netscape/ldap/util/LDAPFilter.java new file mode 100644 index 00000000000..062ed4e6bd5 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapfilter/netscape/ldap/util/LDAPFilter.java @@ -0,0 +1,525 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.util; + +import netscape.ldap.*; +import java.util.*; + +/** + * Represents an LDAP search filter, which includes the string-based + * representation of the filter and other information retrieved from the + * LDAP filter configuration file (or from a buffer in memory or from a URL). + *

+ * + * Although this class provides methods to create and modify LDAP + * filters, in most cases, you do not need to use these methods. + * In most situations, these classes are used to access individual + * filters from filter configuration files. + *

+ * + * For example, you might do the following: + *

+ * + *

    + *
  1. Connect to the LDAP server and accept a set of search criteria. + *
  2. Create an LDAP filter configuration file. + *
  3. Call the LDAPFilterDescriptor constructor to + * read the filter configuration file into memory. + *
  4. Call the getFilters method to get a list of + * filters that match the search criteria. This list of filters + * is represented by an LDAPFilterList object. + *
  5. Iterate through the list of filters (each filter is represented + * by an LDAPFilter object), and apply the filter to + * a search. + *
+ *

+ * + * For an example of using an object of this class and for more information on + * the filter configuration file syntax, see the documentation for LDAPFilterDescriptor. + *

+ * + * @see LDAPFilterDescriptor + * @see LDAPFilterList + * @version 1.0 + */ + +public class LDAPFilter implements Cloneable { + + private static final int DEFAULT_FILTER_LENGTH = 256; + + private String m_strFilter = null; + private String m_strDescription; // token 4 from filter configuration file + private int m_nScope; // token 5 from filter configuration file + private boolean m_bIsExact; + + private String m_strMatchPattern; // token 1 from filter configuration file + private String m_strDelimeter; // token 2 from filter configuration file + private String m_strFilterTemplate; // token 3 from filter configuration file + + private int m_nLine; + private String m_strSuffix; + private String m_strPrefix; + + /** + * Constructs an LDAPFilter object. In most situations, + * you do not need to construct an LDAPFilter object. Instead, you + * work with LDAPFilter objects created from the + * LDAPFilter objects and LDAPFilterDescriptor + * objects. + *

+ * + * This constructor uses the integer value for a search scope in + * addition to other information to construct an LDAPFilter + * object. The integer value of the search scope can be one of the + * following: + *

+ * + * If an invalid scope is specified, the constructor throws an + * illegalArgumentException. + */ + public LDAPFilter ( String strMatchPattern, + String strDelimeter, + String strFilterTemplate, + String strDescription, + int nScope ) throws IllegalArgumentException{ + + m_strMatchPattern = convertMatchPattern ( strMatchPattern ); + m_strDelimeter = strDelimeter; + m_strFilterTemplate = strFilterTemplate; + m_strDescription = strDescription; + m_nScope = nScope; + + } + + /** + * Constructs an LDAPFilter object. In most situations, + * you do not need to construct an LDAPFilter object. Instead, you + * work with LDAPFilter objects created from the + * LDAPFilter objects and LDAPFilterDescriptor + * objects. + *

+ * + * This constructor uses the string value for a search scope in + * addition to other information to construct an LDAPFilter + * object. The string value of the search scope can be one of the + * following: + *

+ * + * If an invalid scope is specified, the constructor throws an + * illegalArgumentException. + */ + public LDAPFilter ( String strMatchPattern, + String strDelimeter, + String strFilterTemplate, + String strDescription, + String strScope ) + throws IllegalArgumentException { + if ( strScope.equals ( "base" ) ) { + m_nScope = LDAPConnection.SCOPE_BASE; + + } else if ( strScope.equals ( "onelevel" ) ) { + m_nScope = LDAPConnection.SCOPE_ONE; + + } else if ( strScope.equals ( "subtree" ) ) { + m_nScope = LDAPConnection.SCOPE_SUB; + } + + m_strMatchPattern = strMatchPattern; + m_strDelimeter = strDelimeter; + m_strFilterTemplate = strFilterTemplate; + m_strDescription = strDescription; + } + + /** + * Print out a string representation of the LDAPFilter. + * Basically, it prints out the appropriate fields. + *

+ * + * For example, suppose you called the method in this way: + *

+ * + *

System.out.println(filter.toString());
+ * + * The resulting output might look like this: + *

+ * + *

+     *      matchPtn: "@"
+     *      delim:    " "
+     *      filttmpl: "(mail=%v*)"
+     *      descript: "start of email address"
+     *      scope: "LDAPConnection.SCOPE_SUB"
+     *      line:     "32"
+     *      FILTER:   "(mail=babs@aceindustry.com*)"
+     * 
+ */ + public String toString() { + StringBuffer strBuf = new StringBuffer ( 300 ); + strBuf.append ( " matchPtn: \"" + m_strMatchPattern+"\"\n" ); + strBuf.append ( " delim: \"" + m_strDelimeter+"\"\n" ); + strBuf.append ( " filttmpl: \"" + m_strFilterTemplate+"\"\n" ); + strBuf.append ( " descript: \"" + m_strDescription+"\"\n" ); + switch ( m_nScope ) { + case LDAPConnection.SCOPE_BASE: + strBuf.append ( " scope: \"LDAPConnection.SCOPE_BASE\"\n" ); + break; + case LDAPConnection.SCOPE_ONE: + strBuf.append ( " scope: \"LDAPConnection.SCOPE_ONE\"\n" ); + break; + case LDAPConnection.SCOPE_SUB: + strBuf.append ( " scope: \"LDAPConnection.SCOPE_SUB\"\n" ); + break; + } + strBuf.append ( " line: \"" + m_nLine+"\"\n" ); + strBuf.append ( " FILTER: \"" + m_strFilter+"\"\n" ); + + return strBuf.toString(); + } + + /** + * Sets up the filter string, given the string strValue. + * If the strPrefix and strSuffix arguments + * are non-null strings, they are prepended and appended + * to the filter string (respectively). + *

+ * + * This string, which is available through the getFilter() + * method, should be suitable for use as search criteria when + * calling the LDAPConnection.search() method. + *

+ * + * Notes: + *

+ * + *

+ *

+ * + * @see netscape.ldap.util.LDAPFilterDescriptor#setFilterAffixes + * @see #setFilterAffixes + */ + public void setupFilter ( String strValue, String strPrefix, + String strSuffix ) { + createFilterString ( strValue, strPrefix, strSuffix ); + } + + /** + * Sets up the filter string, given the string strValue. + * This string, which is available through the getFilter() + * method, should be suitable for use as search criteria when + * calling the LDAPConnection.search() method. + *

+ * + * Note: If you want to specify a filter prefix and suffix, + * you need to explicitly define them by calling the + * setFilterAffixes() method. + * + * @see netscape.ldap.util.LDAPFilterDescriptor#setFilterAffixes + * @see #setFilterAffixes + * + */ + public void setupFilter ( String strValue ) { + createFilterString ( strValue, null, null ); + } + + /** + * Create the filter string which can be used in + * LDAPConnection.search() and others given the parameter + * strValue. If strPrefix and strSuffix are non-null strings, + * prepend strPrefix and append strSuffix. + */ + void createFilterString ( String strValue, String strPrefix, + String strSuffix ) { + StringTokenizer strTok = + new StringTokenizer ( strValue, m_strDelimeter ); + + // Initialize an array of broken up values so that we + // can reference them directly. + String[] aValues = new String[strTok.countTokens()]; + int nTokens = strTok.countTokens(); + for ( int i = 0; i < nTokens; i++ ) { + aValues[i] = strTok.nextToken(); + } + + StringBuffer sbFilter = new StringBuffer ( DEFAULT_FILTER_LENGTH); + if ( strPrefix != null ) { + sbFilter.append ( strPrefix ); + } + char[] cFilterTemplate = m_strFilterTemplate.toCharArray(); + int i = 0; + while ( i < cFilterTemplate.length ) { + if ( cFilterTemplate[i] == '%' ) { + i++; + if ( cFilterTemplate[i] == 'v' ) { + i++; + switch ( cFilterTemplate[i] ) { + case '$': + sbFilter.append ( aValues[aValues.length] ); + break; + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + int nValue = Integer.parseInt + ( new Character + (cFilterTemplate[i]).toString() ); + nValue--; + i++; + if ( cFilterTemplate[i] == '-' ) { + i++; + if ( Character.isDigit ( cFilterTemplate[i] )) { + int nValue2 = Integer.parseInt + ( new Character + (cFilterTemplate[i]).toString() ); + nValue2--; + for ( int j = nValue; j <= nValue2; j++ ) { + sbFilter.append ( aValues[j] ); + sbFilter.append + ( ( j == nValue2 ) ? "" : " " ); + } + } else { + for ( int j = nValue; j < aValues.length;j++ ) { + sbFilter.append ( aValues[j] ); + sbFilter.append + ( ( j == aValues.length - 1 ) ? "" : " " ); + } + sbFilter.append ( cFilterTemplate[i]); + } + + } else { + sbFilter.append ( aValues[nValue] ); + sbFilter.append ( cFilterTemplate[i] ); + } + break; + + // We just got a plain old %v, so insert the + // strValue + default: + sbFilter.append ( strValue ); + sbFilter.append ( cFilterTemplate[i] ); + break; + } + + } else { + sbFilter.append ( "%" ); + sbFilter.append ( cFilterTemplate[i] ); + } + } else { + sbFilter.append ( cFilterTemplate[i] ); + } + i++; + } + if ( strSuffix != null ) { + sbFilter.append ( strSuffix ); + } + m_strFilter = sbFilter.toString(); + } + + + /** + * Makes a copy of this LDAPFilter object. + */ + public Object clone() { + try { + return super.clone(); + } catch ( CloneNotSupportedException e ) { + // this shouldn't happen, since we are Cloneable + throw new InternalError(); + } + } + + /** + * Set the line number from which this filter was created. This + * is used only when the LDAPFilter is created when an + * LDAPFilterDescriptor is initialized from a file/URL/buffer. + */ + void setLine ( int nLine ) { + m_nLine = nLine; + } + + /** + * The ldapfilter.conf specifies match patterns in a funny way. + * A "." means "any character" except when used inside of a set of + * square brackets "[]", in which case, the "." means just a + * plain old period (not a * special character). + * + * This function converts periods inside of a set of square + * brackets into a "\." as per normal regexp code. + */ + String convertMatchPattern ( String strMatchPattern ) { + StringBuffer sb = new StringBuffer ( strMatchPattern.length() + 1); + char[] a_cMatchPattern = strMatchPattern.toCharArray(); + boolean bInBrackets = false; + for ( int i = 0; i < a_cMatchPattern.length; i++ ) { + if ( a_cMatchPattern[i] == '.' ) { + if ( bInBrackets ) { + sb.append ( "\\" ); + } + } else if ( a_cMatchPattern[i] == '[' ) { + bInBrackets = true; + } else if ( a_cMatchPattern[i] == ']' ) { + bInBrackets = false; + } + sb.append ( a_cMatchPattern[i] ); + } + return sb.toString(); + } + + + /** + * Returns the filter string. This method will return null if the + * filter string has not been calculated by the setupFilter(), + * getFilter (strValue), or getFilter (strValue, + * strPrefix, strSuffix ) methods. + * + * @see #setupFilter + * @see #getFilter + */ + public String getFilter () { + return m_strFilter; + } + + /** + * Create a filter string given a string value. This method uses + * any Prefixes or Suffixes that have been set by the + * setFilterAffixes() method.

+ * + * This is the same as doing: + *

+     *   setupFilter ( strValue );
+     *   getFilter();
+     * 
+ */ + public String getFilter ( String strValue ) { + createFilterString ( strValue, m_strPrefix, m_strSuffix ); + return m_strFilter; + } + + + /** + * Create a filter string given a string value. If strPrefix + * and/or strSuffix is non-null, these values are prepended and + * appended to the returned string.

+ * + * This is the same as doing: + *

+     *   setupFilter ( strValue, strPrefix, strSuffix );
+     *   getFilter();
+     * 
+ */ + public String getFilter ( String strValue, String strPrefix, + String strSuffix ) { + createFilterString ( strValue, strPrefix, strSuffix ); + return m_strFilter; + } + + /** + * Return this filter's match pattern. The match pattern is + * found as the first token in a filter configuration line in the + * ldapfilter.conf file. + */ + public String getMatchPattern() { + return m_strMatchPattern; + } + + /** + * Return this filter's delimeter. The delmimeter is + * found as the second token in a filter configuration line in the + * ldapfilter.conf file. + */ + public String getDelimeter() { + return m_strDelimeter; + } + + /** + * Return this filter's filter template. The filter template is + * found as the third token in a filter configuration line in the + * ldapfilter.conf file. + */ + public String getFilterTemplate() { + return m_strFilterTemplate; + } + + /** + * Return this filter's description. The description is + * found as the fourth token in a filter configuration line in the + * ldapfilter.conf file. + */ + public String getDescription() { + return m_strDescription; + } + + /** + * Return this filter's scope. The scope is + * found as the fifth (optional) token in a filter configuration + * line in the ldapfilter.conf file. + */ + public String getScope() { + switch ( m_nScope ) { + case LDAPConnection.SCOPE_BASE: + return "base"; + + case LDAPConnection.SCOPE_ONE: + return "onelevel"; + + case LDAPConnection.SCOPE_SUB: + return "subtree"; + + default: + return "UNKNOWN!"; + } + } + + /** + * Return this filter's line number. The line number is + * mostly a debugging variable to let the developer know which + * filter from the filter configuration file is being used. + */ + public String getLineNumber() { + return Integer.toString ( m_nLine ); + } + + public void setFilterAffixes ( String strPrefix, String strSuffix ) { + m_strPrefix = strPrefix; + m_strSuffix = strSuffix; + } +} diff --git a/mozilla/directory/java-sdk/ldapfilter/netscape/ldap/util/LDAPFilterDescriptor.java b/mozilla/directory/java-sdk/ldapfilter/netscape/ldap/util/LDAPFilterDescriptor.java new file mode 100644 index 00000000000..7c38f1f6a40 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapfilter/netscape/ldap/util/LDAPFilterDescriptor.java @@ -0,0 +1,492 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.util; + +import java.io.*; +import java.util.*; +import java.net.*; +import com.oroinc.text.regex.*; +import netscape.ldap.*; + +/** + * Represents an LDAP filter configuration file read into memory. + *

+ * + * Once you read in a filter file to create an object of this class, + * you can access the filter information through the methods that create + * LDAPFilterList and LDAPFilter objects. + * (You do not need to manually construct these objects yourself.) + *

+ * + * This class (along with the other LDAP filter classes) provide + * functionality equivalent to the LDAP filter functions in the LDAP C API. + *

+ * + * The format of the file/URL/buffer must be that as defined in the + * ldapfilter.conf(5) man page from the University of Michigan LDAP-3.3 + * distribution.

+ * + * The LDAP filter classes provide a powerful way to configure LDAP clients + * by modifying a configuration file.

+ * + * The following is a short example for how to use the + * LDAP filter classes. + * + *

+ *
+ * // ... Setup LDAPConnection up here ...
+ * 

+ * + * LDAPFilterDescriptor filterDescriptor; + *

+ * + * // Create the LDAPFilterDescriptor given the file + * // "ldapfilter.conf". + * try { + * filterDescriptor = new LDAPFilterDescriptor ( "ldapfilter.conf" ); + *

+ * + * // Now retrieve the Filters in the form of an + * // LDAPFilterList + * LDAPFilterList filterList = new filterDescriptor.getFilters("match_tag", "string_user_typed"); + *

+ * + * // For each filter, do the search. Normally, you wouldn't + * // do the search if the first filter matched, but this is + * // just showing the enumeration type aspects of + * // LDAPFilterList + * LDAPFilter filter; + * while ( filterList.hasMoreElements() ) { + * filter = filterList.next(); + * LDAPResults results = LDAPConnection.search ( + * strBase, // base DN + * filter.getScope(), // scope + * filter.getFilter(), // completed filter + * null, // all attribs + * false ); // attrsOnly? + * } + *

+ * + * // ...more processing here... + * } catch ( BadFilterException e ) { + * System.out.println ( e.toString() ); + * System.exit ( 0 ); + * } catch ( IOException e ) { + * // ...handle exception here... + * } + *

+ * + * + * @see LDAPFilterList + * @see LDAPFilter + * @version 1.0 + */ +public class LDAPFilterDescriptor { + + private Vector m_vFilterSet = new Vector(); + + private String m_strLine; + private int m_nLine; + + private String m_strPrefix; + private String m_strAffix; + private LDAPIntFilterSet m_tmpFilterSet = null; + private String m_strLastMatchPattern = null; + private String m_strLastDelimiter = null; + + /** + * The Default scope is used when a scope is not defined + * in the filter file. The scope is the only "optional" parameter + * in the file. + */ + private static final int DEFAULT_SCOPE = LDAPConnection.SCOPE_SUB; + + /** + * Creates an LDAPFilterDescriptor object from an existing filter + * configuration file. This file has the format as defined in the + * ldapfilter.conf(5) man page. + * + * @exception netscape.ldap.util.BadFilterException + * One of the filters was not generated properly. Most likely + * this is due to an improperly formatted ldapfilter.conf file. + */ + public LDAPFilterDescriptor ( String strFile ) + throws FileNotFoundException, BadFilterException { + DataInputStream inputStream = + new DataInputStream ( new FileInputStream ( strFile ) ); + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + init( reader ); + } + + /** + * Creates an LDAPFilterDescriptor object from an existing + * StringBuffer. This file has the format as defined in the + * ldapfilter.conf(5) man page. + * + * @exception netscape.ldap.util.BadFilterException + * One of the filters was not generated properly. Most likely + * this is due to an improperly formatted ldapfilter.conf file. + */ + public LDAPFilterDescriptor ( StringBuffer strBuffer ) + throws BadFilterException { + init( strBuffer ); + } + + /** + * Creates an LDAPFilterDescriptor object from a URL. + * This file has the format as defined in the + * ldapfilter.conf(5) man page. + * + * @exception netscape.ldap.util.BadFilterException + * One of the filters was not generated properly. Most likely + * this is due to an improperly formatted ldapfilter.conf file. + */ + public LDAPFilterDescriptor ( URL url ) + throws IOException, BadFilterException { + URLConnection urlc = url.openConnection(); + DataInputStream inputStream = + new DataInputStream ( urlc.getInputStream() ); + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + init( reader ); + } + + + + /** + * This function initializes the LDAPFilterDescriptor. It's + * called internally, and should never be called directly by the + * developer. + */ + private void init ( Object inputObj) + throws BadFilterException { + + String strCommentPattern = "(?:^\\s*#|^\\s*$)"; + String strDataPattern = "(?:\\s*\"([^\"]*)\"|([^\\s]*))\\s*"; + Perl5Compiler compiler = new Perl5Compiler(); + Perl5Pattern patComment; + Perl5Pattern patData; + Vector vStrings = new Vector ( 5 ); + + try { + patComment = (Perl5Pattern)compiler.compile ( strCommentPattern ); + patData = (Perl5Pattern)compiler.compile ( strDataPattern ); + } catch ( MalformedPatternException e ) { + // This should NEVER happen... + System.out.println ( "FATAL Error, couldn't compile pattern"); + System.out.println ( " " + e.getMessage() ); + return; + } + + // Setup some temporary variables. + m_nLine = 0; + try { + if (inputObj instanceof StringBuffer) { + StringBuffer ibuffer = (StringBuffer)inputObj; + StringBuffer buffer = new StringBuffer(); + for (int i=0; i " + m_strLine + "\nThe error is: " + + strMsg, m_nLine ); + } + + /** + * Output a text dump of this filter descriptor. It cycles + * through all of the internal LDAPIntFilterSet objects and calls + * their toString() methods. + * + * @see LDAPIntFilterSet#toString + */ + public String toString() { + StringBuffer strBuf = new StringBuffer ( 4000 ); + for ( int i = 0; i < m_vFilterSet.size(); i++ ) { + strBuf.append ( "Filter Set number: " + i + "\n" ); + strBuf.append ( + ((LDAPIntFilterSet)m_vFilterSet.elementAt ( i )).toString() + + "\n" ); + strBuf.append ( "\n" ); + //System.out.println ( (m_vFilterSet.elementAt ( i )).toString()); + } + return strBuf.toString(); + } + + /** + * Return all the filters which match the strTagPat (regular + * expression), and the user input (strValue) + */ + public LDAPFilterList getFilters ( String strTagPat, String strValue ) + throws IllegalArgumentException { + + strTagPat = strTagPat.trim(); + strValue = strValue.trim(); + + if ( ( strTagPat == null ) || ( strTagPat.equals ("") ) ) { + throw new IllegalArgumentException + ( "The Tag Pattern can not be null" ); + } + + if ( ( strValue == null ) || ( strValue.equals ("") ) ) { + throw new IllegalArgumentException ( "The Value can not be null" ); + } + + LDAPFilterList retList = new LDAPFilterList(); + + Perl5Compiler compiler = new Perl5Compiler(); + Perl5Pattern patTag; // The strTagPat that's compiled + + // For efficiency, we're pre-allocating a patternMatcherInput + // here. + PatternMatcherInput matcherValue = new PatternMatcherInput ( strValue ); + + // first we need to make a new regexp from the strTagPat + // For efficiency, we're precompiling the strTagPat into + // a pattern here. That pattern doesn't change, the Tag string + // changes per LDAPFIlterSet. + try { + patTag = (Perl5Pattern)compiler.compile ( strTagPat ); + } catch ( MalformedPatternException e ) { + throw new IllegalArgumentException + ( "The parameter: " + strTagPat + " is not valid" ); + } + + // We "ask" each of the filterset's to see if there is + // a matching filter. + boolean bMatched = false; + int i = 0; + while ( ! bMatched ) { + Vector vMatchingFilters = + ((LDAPIntFilterSet)m_vFilterSet.elementAt ( i )).getFilters + (patTag, matcherValue ); + + if ( vMatchingFilters.size() > 0 ) { + for ( int j = 0; j < vMatchingFilters.size(); j++ ) { + LDAPFilter tmpFilter = + (LDAPFilter) + ((LDAPFilter) + vMatchingFilters.elementAt ( j )).clone(); + tmpFilter.setupFilter ( strValue, m_strPrefix, + m_strAffix ); + bMatched = true; // this really doesn't matter. + retList.add ( tmpFilter ); + } + return retList; + } + i++; + } + return null; + } + + + /** + * Prepend the parameter (strPrefix) and append the second + * parameter (strAffix) to every filter that is returned by the + * getFilters() method.

+ */ + public void setFilterAffixes ( String strPrefix, String strAffix ) { + m_strPrefix = strPrefix; + m_strAffix = strAffix; + } +} + diff --git a/mozilla/directory/java-sdk/ldapfilter/netscape/ldap/util/LDAPFilterList.java b/mozilla/directory/java-sdk/ldapfilter/netscape/ldap/util/LDAPFilterList.java new file mode 100644 index 00000000000..f529c668b14 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapfilter/netscape/ldap/util/LDAPFilterList.java @@ -0,0 +1,97 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.util; + +import java.util.*; + +/** + * The list of LDAPFilter objects returned from a LDAPFilterDescriptor + * Object. Note that this is an enumeration, so if multiple iterations + * are needed, save the results. + * + * @see LDAPFilterDescriptor + * @see LDAPFilter + * @version 1.0 + */ + +public class LDAPFilterList implements Enumeration { + private Vector m_vFilterList; + private static int DEFAULT_LIST_SIZE = 2; + + /** + * Constructs an LDAPFilterList object. This methos shouldn't need to + * be called by the developer directly. Construction of the + * LDAPFilterList object should take place when the Prepare function + * of LDAPFilterDescriptor is called. + * + */ + public LDAPFilterList () { + m_vFilterList = new Vector ( DEFAULT_LIST_SIZE ); + } + + + /** + * Add an LDAPFilter to the private vector. Since the filter we're + * being passed has already been cloned from the master + * LDAPFilterDescriptor set, all we have to do is add it to the list. + */ + void add ( LDAPFilter filter ) { + m_vFilterList.addElement ( filter ); + } + + /** + * Returns true if there are any LDAPFilter objects to returned. + */ + public boolean hasMoreElements() { + return ( ! m_vFilterList.isEmpty() ); + } + + /** + * Returns the next LDAPFilter as an Object. Note: the preferred way + * to return the next LDAPFilter is to call next() + * + * @see LDAPFilterList#next() + * @return The next LDAPFilter object (as an instance of Object) + */ + public Object nextElement() { + Object o = m_vFilterList.firstElement(); + m_vFilterList.removeElementAt ( 0 ); + return o; + } + + /** + * Returns the next LDAPFilter + * + * @return The next LDAPFilter + */ + public LDAPFilter next() { + Object o = m_vFilterList.firstElement(); + m_vFilterList.removeElementAt ( 0 ); + return (LDAPFilter)o; + } + + /** + * Return the number of filters in the filter list. + * Note that this number decreases every time next() or nextElement() is + * called because the elements are removed as they're returned. + */ + public int numFilters (){ + return m_vFilterList.size(); + } +} + diff --git a/mozilla/directory/java-sdk/ldapfilter/netscape/ldap/util/LDAPIntFilterList.java b/mozilla/directory/java-sdk/ldapfilter/netscape/ldap/util/LDAPIntFilterList.java new file mode 100644 index 00000000000..328bbc20fad --- /dev/null +++ b/mozilla/directory/java-sdk/ldapfilter/netscape/ldap/util/LDAPIntFilterList.java @@ -0,0 +1,114 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.util; + +import java.util.*; +import com.oroinc.text.regex.*; + +/** + * Represents an Internal LDAPFilterList object. This is an internal object + * that should never be instantiated directly by the developer. We + * store all filters that have the same match pattern here. + */ + +public class LDAPIntFilterList { + private Vector m_vFilter; + private String m_strMatchPattern; + // a regexp pattern of m_strMatchPattern + private Perl5Pattern m_patMatch = null; + private Perl5Matcher m_matcher; + private Perl5Compiler m_compiler; + + LDAPIntFilterList ( LDAPFilter filter ) throws + BadFilterException { + m_strMatchPattern = filter.getMatchPattern(); + + // We're going to compile the pattern for strMatchPattern + // now, so that we can throw an exception if it is a bad + // pattern. + m_matcher = new Perl5Matcher(); + m_compiler = new Perl5Compiler(); + + try { + m_patMatch = (Perl5Pattern)m_compiler.compile + ( m_strMatchPattern ); + } catch ( MalformedPatternException e ) { + + throw new BadFilterException ( + "The Regular Expression for this filter is bad. " + + "Line number: " + filter.getLineNumber() ); + } + + m_vFilter = new Vector(); + m_vFilter.addElement ( filter ); + } + + /** + * Add a "relative" filter to an existing filter list. We do this + * becuse the ldapfilter file defines that we can have multiple + * filters per match pattern (and delimeter). This method is + * called by the parent LDAPIntFilterSet because the file specified + * a "relative" filter (a filter in the ldapfilter.conf file that + * only has 2 or 3 tokens). + */ + void AddFilter ( LDAPFilter filter ) { + m_vFilter.addElement ( filter ); + } + + + /** + * Return the number of Filters this InternalFilterList contains. + */ + // Since we're storing the filters as a vector, just return + // Vector.size(). + int numFilters () { + return m_vFilter.size(); + } + + + public String toString() { + StringBuffer strBuf = new StringBuffer ( 100 ); + strBuf.append ( " Match Pattern: \"" + m_strMatchPattern + "\"\n" ); + + for ( int i = 0; i < m_vFilter.size(); i++ ) { + strBuf.append ( ((LDAPFilter)m_vFilter.elementAt(i)).toString() ); + strBuf.append ( "\n" ); + } + return strBuf.toString(); + } + + /** + * Return the requested filter. + */ + LDAPFilter getFilter ( int nFilter ) { + return (LDAPFilter)m_vFilter.elementAt ( nFilter ); + } + + /** + * Try to match the filter to the given string. This method is called + * when the user types in data. We match the expression (stored in + * m_strMatchPattern) to the value that the user typed in (the + * parameter to this method). + */ + boolean MatchFilter ( PatternMatcherInput matcherValue ) { + matcherValue.setCurrentOffset ( matcherValue.getBeginOffset() ); + return m_matcher.contains ( matcherValue, m_patMatch ); + } +} + + diff --git a/mozilla/directory/java-sdk/ldapfilter/netscape/ldap/util/LDAPIntFilterSet.java b/mozilla/directory/java-sdk/ldapfilter/netscape/ldap/util/LDAPIntFilterSet.java new file mode 100644 index 00000000000..c81434dffa2 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapfilter/netscape/ldap/util/LDAPIntFilterSet.java @@ -0,0 +1,159 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.util; + +import java.util.*; +import com.oroinc.text.regex.*; +/** + * Represents an LDAPIntFilterSet object. This is an internal object that + * should never be instantiated directly by the developer. + */ + +public class LDAPIntFilterSet { + + private Vector m_vLDAPIntFilterList; + private String m_strTag; + + private PatternMatcherInput m_matcherTag = null; + private Perl5Matcher m_matcher = null; + /** + * Return a Vector of filters that match botht the tag pattern + * (in Perl5Pattern form), and the string strValue. This method + * should only be called by LDAPFilterDescriptor(). + */ + + // remember, we have the string (m_strTag), the pattern has + // been precompiled by the LDAPFilterDescriptor (patTag) + Vector getFilters ( Perl5Pattern patTag, + PatternMatcherInput matcherValue ) { + Vector vRet = new Vector(); + + if ( m_matcherTag == null ) { + m_matcher = new Perl5Matcher(); + m_matcherTag = new PatternMatcherInput ( m_strTag ); + } else { + m_matcherTag.setCurrentOffset ( m_matcherTag.getBeginOffset() ); + } + + // Check to see if the strTag (converted into patTag) + // matches the tag string from the file (converted into + // m_matcherTag) + if ( m_matcher.contains ( m_matcherTag, patTag ) ) { + LDAPIntFilterList tmpIntFilterList; + LDAPFilter tmpFilter; + for ( int i = 0; i < m_vLDAPIntFilterList.size(); i++ ) { + tmpIntFilterList = + (LDAPIntFilterList)m_vLDAPIntFilterList.elementAt ( i ); + + if ( tmpIntFilterList.MatchFilter ( matcherValue ) ) { + for (int j=0; j < tmpIntFilterList.numFilters(); j++ ) { + vRet.addElement ( tmpIntFilterList.getFilter ( j )); + } + // potential BUGBUG, i'm not sure if we want + // to get out of this loop now or if we just + // want to get out of the external loop. For + // now, go with the former. + return vRet; + } + } + } + + return vRet; + } + + /** + * Create an LDAPIntFilterSet with a given Tag string. The tag + * string specifies which applications or query types should use + * this filter set. It is normally a single token on a line by + * itself in the filter configuration file.

+ * For more information about the filter configuration file, see + * the man page for ldapfilter.conf. + */ + public LDAPIntFilterSet ( String strTag ) { + m_strTag = strTag; + m_vLDAPIntFilterList = new Vector(); + } + + /** + * Add a new filter to this filter set. + * + * @exception netscape.ldap.util.BadFilterException + * If the regular expression pattern given in the first token + * is bad. + */ + void newFilter ( LDAPFilter filter ) throws BadFilterException { + LDAPIntFilterList tmpFilterList = new LDAPIntFilterList( filter ); + m_vLDAPIntFilterList.addElement ( tmpFilterList ); + } + + /** + * Append a new filter to the existing set. This happens when the + * LDAPFilterDescriptor object reads a line from the filter + * configuration file that has 2 or 3 tokens. + */ + void appendFilter ( LDAPFilter filter ) { + ((LDAPIntFilterList)m_vLDAPIntFilterList.lastElement()).AddFilter ( filter ); + } + + + + /** + * Return true if this filter set matches the regular expression + * string that is passed in. + */ + boolean match ( String strTagPat ) { + Perl5Matcher matcher = new Perl5Matcher(); + Perl5Compiler compiler = new Perl5Compiler(); + PatternMatcherInput input; + Perl5Pattern patTag; + MatchResult result; + + try { + patTag = (Perl5Pattern)compiler.compile ( strTagPat ); + } catch ( MalformedPatternException e ) { + // Need to do something here. + return false; + } + + input = new PatternMatcherInput ( m_strTag ); + if ( matcher.contains ( input, patTag ) ) { + return true; + } else { + return false; + } + } + + /** + * Print out the String representation of this object. It calls + * the toString() method of all the LDAPFilter objects contained + * within it's set. + * + * @see LDAPFilter#toString() + */ + public String toString() { + StringBuffer strBuf = new StringBuffer ( 2000 ); + strBuf.append ( " strTag: " + m_strTag + "\n" ); + for ( int i = 0; i < m_vLDAPIntFilterList.size(); i++ ) { + strBuf.append ( " filter #: " + i + "\n" ); + strBuf.append ( + ((LDAPIntFilterList)m_vLDAPIntFilterList.elementAt(i)).toString() ); + strBuf.append ( "\n" ); + } + return strBuf.toString(); + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLClientCB.java b/mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLClientCB.java new file mode 100644 index 00000000000..6107194740c --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLClientCB.java @@ -0,0 +1,26 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package com.netscape.sasl; + +import com.netscape.sasl.SASLException; + +/** + * This is just a base interface which does not contain any methods. + */ +public interface SASLClientCB { +} diff --git a/mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLClientMechanismDriver.java b/mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLClientMechanismDriver.java new file mode 100644 index 00000000000..e9ecb9acf31 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLClientMechanismDriver.java @@ -0,0 +1,203 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package com.netscape.sasl; + +/** + * + *

+ *                                               Mechanism Drivers
+ *  ---------------     -------------------      -----------------
+ *  | Application |-----| Protocol Driver |------| MD5           |
+ *  ---------------     -------------------   |  -----------------
+ *                                            |
+ *                                            |  -----------------
+ *                                            |--| Kerberos v5   |
+ *                                            |  -----------------
+ *                                            |
+ *                                            |  -----------------
+ *                                            |--| PKCS-11       |
+ *                                            |  -----------------
+ *                                            |
+ *
+ *                                            |
+ *
+ *                                            |
+ *                                            |  - - - - - - - - -
+ *                                            |--| xxxYYYxxx     |
+ *                                               - - - - - - - - -
+ *
+ * An application chooses a Protocol Driver specific to the + * protocol it wants to use, and specifies one or more acceptable + * mechanisms. The Protocol Driver controls the socket, and knows + * the format/packaging of bytes sent down and received from the + * socket, but does not know how to authenticate or to encrypt/ + * decrypt the bytes. It uses one of of the Mechanism Drivers + * to help it perform authentication, where all parameters to + * be used in encryption from then on are determined. In a protocol- + * specific way, the Protocol Driver examines each byte string received + * from the server to determine if the authentication process has + * been completed. If not, the byte string is passed to the Mechanism + * Driver to be interpreted as a server challenge; the Mechanism + * Driver returns an appropriate response, which the Protocol Driver + * can encode in a protocol-specific way and return to the server. + *

+ * If the Protocol Driver concludes from the byte string received from + * the server that authentication is complete, it may query + * the Mechanism Driver if it considers the authentication process + * complete, in order to thwart early completion messages inserted by + * and intruder. + *

+ * On completed + * authentication, the Protocol Driver receives from the Mechanism + * Driver a Security Layer Driver object. From this point on, + * the Protocol Driver passes byte arrays received from its socket + * to the Security Layer Driver object for decoding before + * returning them to the application, and passes + * application byte arrays to the Security Layer Driver object + * for encryption before passing them down the socket. + *

+ * A complication here is that some authentication methods may + * require additional user/application input (at least on the client + * side). That means that a Mechanism Driver may need to call up to + * an application during the authentication process. In the following, + * an interface SASLAuthenticationCB has been defined, allowing + * an application to (if necessary) provide a user with prompts and + * obtain additional information required to continue the process. + *

+ * For LDAP, the Protocol Driver can be considered built in to + * the LDAPConnection class (actually it is more likely an object + * to which an LDAPConnection object has a reference). + *

+ * However, + * there should be a generalized framework for registering and + * finding Mechanism Drivers. Maybe best to do something like + * content and protocol handlers in java: look for them in some + * predefined place in the general class hierarchy, e.g. + * netscape.security.mechanisms. So if a Protocol Driver is + * asked to use "GSSAPI", it would attempt to instantiate + * netscape.security.mechanisms.gssapi. A non-standard place can + * also be specified, e.g. "myclasses.mechanisms.GSSAPI". + * This functionality should be folded into a mechanism driver + * factory, which knows where to find candidate classes for + * instantiation. + *

+ * The Mechanism Drivers are protocol-independent, and don't deal + * directly with network connections, just byte arrays, so they + * should be implemented in a generalizable way for all protocols. + *

+ * A Security Layer Driver typically inherits a State object from + * the Mechanism Driver, where parameters and resolutions reached + * during authentication have been stored. + *

+ * One way to allow specifying an open-ended list of parameters is + * with a Properties object. That is what is done in the following. + * + * @author rweltman@netscape.com + * @version 1.0 + */ + +public interface SASLClientMechanismDriver { + + /** + * This method prepares a byte array to use for the initial + * request to authenticate. A SASLException is thrown if the driver + * cannot initiate authentication with the supplied parameters. + * @param id Protocol-dependent identification, e.g. user name or + * distinguished name. + * @param protocol A protocol supported by the mechanism driver, e.g. + * "pop3", "ldap" + * @param serverName Only used in kerberos, currently: fully qualified + * name of server to authenticate to. + * @param props Additional configuration for the session, e.g. + *

+     *    "security.policy.encryption.minimum"    Minimum key length;
+     *                                            default 0
+     *    "security.policy.encryption.maximum"    Maximum key length;
+     *                                            default 256
+     *    "security.policy.server_authentication" True if server must
+     *                                            authenticate to client;
+     *                                            default false
+     *    "security.ip.local"                     For kerberos v4; no default
+     *    "security.ip.remote"                    For kerberos v4; no default
+     *    "security.maxbuffer"                    Reject frames larger than
+     *                                            this; default 0 (client
+     *                                            will not use the security
+     *                                            layer)
+     *
+ * @param authCB An optional object which can be invoked by the + * mechanism driver to acquire additional authentication information, + * such as user name and password. + * @return A byte array to be used for the initial authentication. It + * may be null for a standard initial sequence in some + * protocols, such as POP, SMTP, and IMAP. + * @exception SASLException if an initial authentication request can + * not be formulated with the supplied parameters. + */ + public byte[] startAuthentication( String id, + String protocol, + String serverName, + java.util.Properties props, + SASLClientCB authCB ) + throws SASLException; + + /** + * If a challenge is received from the server during the + * authentication process, this method is called by the + * Protocol Driver to prepare an appropriate next request to submit + * to the server. + * @param challenge Received server challenge. + * @return Request to submit to server. + * @exception SASLException if the server challenge could not + * be handled or the driver is unable for other reasons to + * continue the authentication process. + */ + public byte[] evaluateResponse( byte[] challenge ) + throws SASLException; + + /** + * The following method may be called at any time to determine if + * the authentication process is finished. Typically, the protocol + * driver will not do this until it has received something + * from the server which indicates (in a protocol-specific manner) + * that the process + * has completed. + * @return true if authentication is complete. + */ + public boolean isComplete(); + + /** + * Once authentication is complete, the Protocol Driver calls the + * following method to obtain an object capable of encoding/decoding + * data content for the rest of the session (or until there is a + * new round of authentication). An exception is thrown if + * authentication is not yet complete. + * @return A SASLSecurityLayer object capable of doing + * encoding/decoding during the session. + * @exception SASLException if no security layer has been negotiated + * or if authentication is not complete. + */ + public SASLSecurityLayer getSecurityLayer() throws SASLException; + + /** + * Report the name of this driver, e.g. "GSSAPI". + * @return The name of the mechanism driver, without any location + * qualification. + */ + public String getMechanismName(); +} + diff --git a/mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLException.java b/mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLException.java new file mode 100644 index 00000000000..07b23e69a3f --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLException.java @@ -0,0 +1,62 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package com.netscape.sasl; + +/* + * Exception type returned on SASL authentication failures. + */ +public class SASLException extends Exception { + /** + * Constructs a default exception with no specific error information. + */ + public SASLException() { + } + + /** + * Constructs a default exception with a specified string as + * additional information. + * @param message The additional error information. + */ + public SASLException( String message ) { + super( message ); + } + + /** + * Constructs a default exception with a specified string as + * additional information, and a result code. + * @param message The additional error information. + * @param resultCode The result code returned. + */ + public SASLException( String message, int resultCode ) { + super( message ); + this.m_resultCode = resultCode; + } + + public int getResultCode() { + return m_resultCode; + } + + public String toString() { + if (m_resultCode != -1) + return super.toString() + " (" + m_resultCode + ")" ; + else + return super.toString(); + } + + private int m_resultCode = -1; +} diff --git a/mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLGetLanguageCB.java b/mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLGetLanguageCB.java new file mode 100644 index 00000000000..ee3593721b5 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLGetLanguageCB.java @@ -0,0 +1,34 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package com.netscape.sasl; + +import java.util.*; + +/** + * Obtain a language to use for localization of user-visible text. + */ +public interface SASLGetLanguageCB extends SASLClientCB { + + /** + * Returns a language to use in localizing user-visible text. + * @param locale The Locale object + * @return a localized text. + */ + public String getLanguage(Locale locale); +} + diff --git a/mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLInfoClientCB.java b/mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLInfoClientCB.java new file mode 100644 index 00000000000..a5bf91be15c --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLInfoClientCB.java @@ -0,0 +1,32 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package com.netscape.sasl; + +/** + * Present information to a user. No confirmation is expected. + */ +public interface SASLInfoClientCB extends SASLClientCB { + + /** + * Presents the user with the supplied textual information. + * @param prompt Textual information to be provided to the client. It + * may be localized. + */ + public void promptInfo(String prompt); +} + diff --git a/mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLMechanismFactory.java b/mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLMechanismFactory.java new file mode 100644 index 00000000000..5e49195f51a --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/com/netscape/sasl/SASLMechanismFactory.java @@ -0,0 +1,90 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package com.netscape.sasl; + +/** + * This class provides a SASLClientMechanismDriver, or a list of mechanisms. + */ +public class SASLMechanismFactory { + + /** + * Returns an object implementing a requested mechanism driver. A + * SASLException is thrown if no corresponding mechanism driver can be + * instantiated. + * @param mechanisms A list of mechanism names + * @param packageName A package from which to instantiate the mechanism + * driver, eg, "myclasses.SASL.mechanisms". If null, a system default + * is used. + */ + public static SASLClientMechanismDriver getMechanismDriver( + String[] mechanisms, String packageName) throws SASLException { + + for (int i=0; i 0) { + Object[] vals = new Object[set.size()]; + for (int i = 0; i < set.size(); i++) { + vals[i] = ((BEROctetString)set.elementAt(i)).getValue(); + } + setValues( vals ); + } + } + + /** + * Returns the number of values of the attribute. + * @return Number of values for this attribute. + */ + public int size() { + return values.length; + } + + /** + * Returns an enumerator for the string values of an attribute. + * @return Enumerator for the string values. + */ + public Enumeration getStringValues() { + Vector v = new Vector(); + synchronized(this) { + try { + for (int i=0; ibyte[] + * format. + * @return A set of attribute values. Each element in the enumeration + * will be of type byte[]. + */ + public Enumeration getByteValues() { + Vector v = new Vector(); + synchronized(this) { + for (int i=0; icn;lang-ja;phonetic, + * this method returns an array containing lang-ja + * and phonetic. + *

+ * + * @param attrName Name of the attribute to extract the subtypes from + * @return Array of subtypes, or null (if the name has no subtypes) + * @see netscape.ldap.LDAPAttribute#getBaseName + */ + public static String[] getSubtypes(String attrName) { + StringTokenizer st = new StringTokenizer(attrName, ";"); + if( st.hasMoreElements() ) { + // First element is base name + st.nextElement(); + String[] subtypes = new String[st.countTokens()]; + int i = 0; + // Extract the types + while( st.hasMoreElements() ) + subtypes[i++] = (String)st.nextElement(); + return subtypes; + } + return null; + } + + /** + * Extracts the subtypes from the attribute name of the current + * LDAPAttribute object. For example, if the attribute + * name is cn;lang-ja;phonetic, this method returns an array + * containing lang-ja and phonetic. + *

+ * + * @return Array of subtypes, or null (if the name has no subtypes) + */ + public String[] getSubtypes() { + return getSubtypes(getName()); + } + + /** + * Extracts the language subtype from the attribute name of the + * LDAPAttribute object, if any. For example, if the + * attribute name is cn;lang-ja;phonetic, this method + * returns the String lang-ja. + *

+ * + * @return The language subtype, or null (if the name has no + * language subtype). + */ + public String getLangSubtype() { + String[] subTypes = getSubtypes(); + if ( subTypes != null ) { + for( int i = 0; i < subTypes.length; i++ ) { + if ((subTypes[i].length() >= 5) && + (subTypes[i].substring(0, 5).equalsIgnoreCase("lang-"))) + return subTypes[i]; + } + } + return null; + } + + /** + * Extracts the base name from the specified attribute name. + * For example, if the attribute name is cn;lang-ja;phonetic, + * this method returns cn. + *

+ * + * @param attrName Name of the attribute from which to extract the base name + * @return Base name (the attribute name without any subtypes) + * @see netscape.ldap.LDAPAttribute#getSubtypes + */ + public static String getBaseName(String attrName) { + String basename = attrName; + StringTokenizer st = new StringTokenizer(attrName, ";"); + if( st.hasMoreElements() ) + // First element is base name + basename = (String)st.nextElement(); + return basename; + } + + /** + * Extracts the base name from the attribute name of the current + * LDAPAttribute object. For example, if the attribute + * name is cn;lang-ja;phonetic, this method returns + * cn. + *

+ * + * @return Base name (the attribute name without any subtypes) + * @see netscape.ldap.LDAPAttribute#getSubtypes + */ + public String getBaseName() { + return getBaseName(getName()); + } + + /** + * Report if the attribute name contains the specified subtype. + * For example, if you check for the subtype lang-en + * and the attribute name is cn;lang-en, this method + * returns true. + *

+ * + * @param subtype The single subtype that you want to check for + * @return true if the attribute name contains the specified subtype + * @see netscape.ldap.LDAPAttribute#getSubtypes + */ + public boolean hasSubtype(String subtype) { + String[] mytypes = getSubtypes(); + for(int i = 0; i < mytypes.length; i++) { + if( subtype.equalsIgnoreCase( mytypes[i] ) ) + return true; + } + return false; + } + + /** + * Report if the attribute name contains all specified subtypes + * For example, if you check for the subtypes lang-en + * and phonetic and if the attribute name is + * cn;lang-en;phonetic, this method returns true. + * If the attribute name is cn;phonetic or + * cn;lang-en, this method returns false. + *

+ * @param subtypes An array of subtypes to check + * @return true if the attribute name contains all subtypes + * @see netscape.ldap.LDAPAttribute#getSubtypes + */ + public boolean hasSubtypes(String[] subtypes) { + for(int i = 0; i < subtypes.length; i++) { + if( !hasSubtype(subtypes[i]) ) + return false; + } + return true; + } + + /** + * Adds a string value to the attribute. + * @param attrValue The string value that you want to add to the attribute. + */ + public synchronized void addValue( String attrValue ) { + if (attrValue != null) { + try { + byte[] b = attrValue.getBytes("UTF8"); + addValue( b ); + } catch(Throwable x) + {} + } + } + + /** + * Sets the string values as the attribute's values. + * @param attrValues The string values that you want to use in the attribute. + */ + protected void setValues( String[] attrValues ) { + Object[] vals; + if (attrValues != null) { + vals = new Object[attrValues.length]; + for (int i = 0; i < vals.length; i++) { + try { + vals[i] = attrValues[i].getBytes("UTF8"); + } catch(Throwable x) + { vals[i] = new byte[0]; } + } + } else { + vals = new Object[0]; + } + setValues(vals); + } + + /** + * Adds a byte[]-formatted value to the attribute. + * @param attrValue The byte[]-formatted value that you + * want to add to the attribute. + */ + public synchronized void addValue( byte[] attrValue ) { + if (attrValue != null) { + Object[] vals = new Object[values.length+1]; + for (int i = 0; i < values.length; i++) + vals[i] = values[i]; + vals[values.length] = attrValue; + values = vals; + } + } + + /** + * Sets the byte[] values as the attribute's values. + * @param attrValues The values that you want to use in the attribute. + */ + protected synchronized void setValues( Object[] attrValues ) { + values = attrValues; + } + + /** + * Removes a string value from the attribute. + * @param attrValue The string value that you want removed. + */ + public synchronized void removeValue( String attrValue) { + if (attrValue != null) { + try{ + byte b[] = attrValue.getBytes("UTF8"); + removeValue ( b ); + } catch(Throwable x) + {} + } + } + + /** + * Removes a byte[]-formatted value from the attribute. + * @param attrValue byte[]-formatted value that you want removed. + */ + public synchronized void removeValue( byte[] attrValue) { + if ((attrValue == null) || (values == null)|| (values.length < 1)) + return; + int ind = -1; + for (int i=0; i= 0) { + Object[] vals = new Object[values.length-1]; + int j = 0; + for (int i = 0; i < values.length; i++) { + if (i != ind) { + vals[j++] = values[i]; + } + } + values = vals; + } + } + + private static boolean equalValue(byte[] a, byte[] b) { + if (a.length != b.length) + return false; + + for (int i=0; i 0 ) { + for (int i = 0; i < values.length; i++) { + if (i != 0) + s = s + ","; + byte[] val = (byte[])values[i]; + try { + s = s + new String(val, "UTF8"); + } catch (Exception e) { + if (val != null) + s = s + val.length + " bytes"; + else + s = s + "null value"; + } + } + } + return "{type='" + getName() + "', values='" + s + "'}"; + } + + /** + * Retrieves the string representation of attribute + * in an LDAP entry. For example: + * + *

LDAPAttribute {type='cn', values='Barbara Jensen,Babs Jensen'}
+ * + * @return String representation of the attribute. + */ + public String toString() { + return "LDAPAttribute " + getParamString(); + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPAttributeSchema.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPAttributeSchema.java new file mode 100644 index 00000000000..250aa68d4d2 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPAttributeSchema.java @@ -0,0 +1,310 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import java.util.*; + +/** + * The definition of an attribute type in the schema. + * RFC 2252, Lightweight Directory Access Protocol (v3): + * Attribute Syntax Definitions covers the types of information + * that need to be specified in the definition of an attribute type. + * According to the RFC, the description of an attribute type can + * include the following information: + *

+ * + *

    + *
  • an OID identifying the attribute type + *
  • a name identifying the attribute type + *
  • a description of the attribute type + *
  • the name of the parent attribute type + *
  • the syntax used by the attribute (for example, + * cis or int) + *
  • an indication of whether or not the attribute type is single-valued + * or multi-valued + *
+ *

+ * + * When you construct an LDAPAttributeSchema object, you can + * specify these types of information as arguments to the constructor or + * in the AttributeTypeDescription format specified in RFC 2252. + * (When an LDAP client searches an LDAP server for the schema, the server + * returns schema information as an object with attribute values in this + * format.) + *

+ * + * You can get the name, OID, and description of this attribute type + * definition by using the getName, getOID, and + * getDescription methods inherited from the abstract class + * LDAPSchemaElement. + *

+ * + * If you need to add or remove this attribute type definition from the + * schema, you can use the add and remove + * methods, which this class inherits from the LDAPSchemaElement + * abstract class. + *

+ * + * @version 1.0 + * @see netscape.ldap.LDAPSchemaElement + **/ + +public class LDAPAttributeSchema extends LDAPSchemaElement { + /** + * Construct a blank element. + */ + protected LDAPAttributeSchema() { + super(); + } + + /** + * Constructs an attribute type definition, using the specified + * information. + * @param name Name of the attribute type. + * @param oid Object identifier (OID) of the attribute type + * in dotted-string format (for example, "1.2.3.4"). + * @param description Description of attribute type. + * @param syntax Syntax of this attribute type. The value of this + * argument can be one of the following: + *

    + *
  • cis (case-insensitive string) + *
  • ces (case-exact string) + *
  • binary (binary data) + *
  • int (integer) + *
  • telephone (telephone number -- identical to cis, + * but blanks and dashes are ignored during comparisons) + *
  • dn (distinguished name) + *
+ * @param single true if the attribute type is single-valued. + */ + public LDAPAttributeSchema( String name, String oid, String description, + int syntax, boolean single ) { + super( name, oid, description ); + attrName = "attributetypes"; + this.syntax = syntax; + this.single = single; + } + + /** + * Constructs an attribute type definition based on a description in + * the AttributeTypeDescription format. For information on this format, + * (see RFC 2252, Lightweight Directory Access Protocol (v3): + * Attribute Syntax Definitions. This is the format that LDAP servers + * and clients use to exchange schema information. (For example, when + * you search an LDAP server for its schema, the server returns an entry + * with the attributes "objectclasses" and "attributetypes". The + * values of the "attributetypes" attribute are attribute type descriptions + * in this format.) + *

+ * + * @param raw Definition of the attribute type in the + * AttributeTypeDescription format. + */ + public LDAPAttributeSchema( String raw ) { + attrName = "attributetypes"; + raw.trim(); + // Skip past "( " and ")" + int l = raw.length(); + raw = raw.substring( 2, l - 1 ); + l = raw.length(); + int ind = raw.indexOf( ' ' ); + oid = raw.substring( 0, ind ); + char[] ch = new char[l]; + + raw = raw.substring( ind + 1, l ); + l = raw.length(); + raw.getChars( 0, l, ch, 0 ); + + ind = 0; + l = ch.length; + while ( ind < l ) { + String s = ""; + String val; + while( ch[ind] == ' ' ) + ind++; + int last = ind + 1; + while( (last < l) && (ch[last] != ' ') ) + last++; + if ( (ind < l) && (last < l) ) { + s = new String( ch, ind, last-ind ); + ind = last; + if ( s.equalsIgnoreCase( "SINGLE-VALUE" ) ) { + single = true; + continue; + } + } else { + ind = l; + } + + while( (ind < l) && (ch[ind] != '\'') ) + ind++; + last = ind + 1; + while( (last < l) && (ch[last] != '\'') ) { + last++; + } + if ( (ind < last) && (last < l) ) { + val = new String( ch, ind+1, last-ind-1 ); + ind = last + 1; + + if ( s.equalsIgnoreCase( "NAME" ) ) { + name = val; + } else if ( s.equalsIgnoreCase( "DESC" ) ) { + description = val; + } else if ( s.equalsIgnoreCase( "SYNTAX" ) ) { + syntax = syntaxCheck( val ); + } + } + } + } + + /** + * Gets the syntax of the attribute type. + * @return One of the following values: + *

    + *
  • cis (case-insensitive string) + *
  • ces (case-exact string) + *
  • binary (binary data) + *
  • int (integer) + *
  • telephone (telephone number -- identical to cis, + * but blanks and dashes are ignored during comparisons) + *
  • dn (distinguished name) + *
+ */ + public int getSyntax() { + return syntax; + } + + /** + * Determines if the attribute type is single-valued. + * @return true if single-valued, + * false if multi-valued. + */ + public boolean isSingleValued() { + return single; + } + + protected String internalSyntaxToString() { + String s; + if ( syntax == cis ) { + s = cisString; + } else if ( syntax == binary ) { + s = binaryString; + } else if ( syntax == ces ) { + s = cesString; + } else if ( syntax == telephone ) { + s = telephoneString; + } else if ( syntax == dn ) { + s = dnString; + } else if ( syntax == integer ) { + s = intString; + } else { + s = "unknown"; + } + return s; + } + + /** + * Get the attribute type definition in a string representation + * of the AttributeTypeDescription data type defined in X.501 (see + * RFC 2252, Lightweight Directory Access Protocol + * (v3): Attribute Syntax Definitions + * for a description of this format). + * This is the format that LDAP servers and clients use to exchange + * schema information. (For example, when + * you search an LDAP server for its schema, the server returns an entry + * with the attributes "objectclasses" and "attributetypes". The + * values of the "attributetypes" attribute are attribute type + * descriptions in this format.) + *

+ * + * @return A string in a format that can be used as the value of + * the attributetypes attribute (which describes + * an attribute type in the schema) of a subschema object. + */ + public String getValue() { + String s = "( " + oid + " NAME \'" + name + "\' DESC \'" + + description + "\' SYNTAX \'"; + s += internalSyntaxToString(); + s += "\' "; + if ( single ) + s += "SINGLE-VALUE "; + s += ')'; + return s; + } + + protected String syntaxToString() { + String s; + if ( syntax == cis ) { + s = "case-insensitive string"; + } else if ( syntax == binary ) { + s = "binary"; + } else if ( syntax == integer ) { + s = "integer"; + } else if ( syntax == ces ) { + s = "case-exact string"; + } else if ( syntax == telephone ) { + s = "telephone"; + } else if ( syntax == dn ) { + s = "distinguished name"; + } else { + s = "unknown"; + } + return s; + } + + /** + * Get the definition of the attribute type in a user friendly format. + * This is the format that the attribute type definition uses when + * you print the attribute type or the schema. + * @return Definition of the attribute type in a user friendly format. + */ + public String toString() { + String s = "Name: " + name + "; OID: " + oid + "; Type: "; + s += syntaxToString(); + s += "; Description: " + description + "; "; + if ( single ) + s += "single-valued"; + else + s += "multi-valued"; + return s; + } + + protected int syntaxCheck( String syntax ) { + int i = unknown; + if ( syntax.equals( cisString ) ) { + i = cis; + } else if ( syntax.equals( binaryString ) ) { + i = binary; + } else if ( syntax.equals( cesString ) ) { + i = ces; + } else if ( syntax.equals( intString ) ) { + i = integer; + } else if ( syntax.equals( telephoneString ) ) { + i = telephone; + } else if ( syntax.equals( dnString ) ) { + i = dn; + } + return i; + } + + protected int syntax = unknown; + private boolean single = false; +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPAttributeSet.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPAttributeSet.java new file mode 100644 index 00000000000..a2b37191dd0 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPAttributeSet.java @@ -0,0 +1,398 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import java.util.*; +import netscape.ldap.client.*; +import netscape.ldap.client.opers.*; + +/** + * Represents a set of attributes (for example, the set of attributes + * in an entry). + * + * @version 1.0 + * @see netscape.ldap.LDAPAttribute + */ +public class LDAPAttributeSet implements Cloneable +{ + Hashtable attrHash = null; + LDAPAttribute[] attrs = new LDAPAttribute[0]; + /* If there are less attributes than this in the set, it's not worth + creating a Hashtable - faster and cheaper most likely to string + comparisons. Most applications fetch attributes once only, anyway */ + static final int ATTR_COUNT_REQUIRES_HASH = 5; + + /** + * Constructs a new set of attributes. This set is initially empty. + */ + public LDAPAttributeSet() { + } + + /** + * Constructs an attribute set. + * @param attrs The list of attributes. + */ + public LDAPAttributeSet( LDAPAttribute[] attrs ) { + this.attrs = attrs; + } + + public synchronized Object clone() { + try { + LDAPAttributeSet attributeSet = new LDAPAttributeSet(); + attributeSet.attrs = new LDAPAttribute[attrs.length]; + for (int i = 0; i < attrs.length; i++) { + attributeSet.attrs[i] = new LDAPAttribute(attrs[i]); + } + return attributeSet; + } catch (Exception e) { + return null; + } + } + + /** + * Returns an enumeration of the attributes in this attribute set. + * @return Enumeration of the attributes in this set. + */ + public Enumeration getAttributes () { + Vector v = new Vector(); + synchronized(this) { + for (int i=0; i + * + * For example, suppose an attribute set contains the following attributes: + *

+ * + *

+     * cn
+     * cn;lang-ja
+     * sn;phonetic;lang-ja
+     * sn;lang-us
+     * 
+ * + * If you call the getSubset method and pass + * lang-ja as the argument, the method returns + * an attribute set containing the following attributes: + *

+ * + *

+     * cn;lang-ja
+     * sn;phonetic;lang-ja
+     * 
+ * + * @param subtype Semi-colon delimited list of subtypes + * that you want to find in attribute names. + * For example: + *
+     *     "lang-ja"        // Only Japanese language subtypes
+     *     "binary"         // Only binary subtypes
+     *     "binary;lang-ja" // Only Japanese language subtypes
+     *                         which also are binary
+     *
+ * @return Attribute set containing the attributes that have + * the specified subtypes + * @see netscape.ldap.LDAPAttribute + * @see netscape.ldap.LDAPAttributeSet#getAttribute + * @see netscape.ldap.LDAPEntry#getAttributeSet + */ + public LDAPAttributeSet getSubset(String subtype) { + LDAPAttributeSet attrs = new LDAPAttributeSet(); + if ( subtype == null ) + return attrs; + StringTokenizer st = new StringTokenizer(subtype, ";"); + if( st.countTokens() < 1 ) + return attrs; + String[] searchTypes = new String[st.countTokens()]; + int i = 0; + while( st.hasMoreElements() ) { + searchTypes[i] = (String)st.nextElement(); + i++; + } + Enumeration attrEnum = getAttributes(); + while( attrEnum.hasMoreElements() ) { + LDAPAttribute attr = (LDAPAttribute)attrEnum.nextElement(); + if( attr.hasSubtypes( searchTypes ) ) + attrs.add( new LDAPAttribute( attr ) ); + } + return attrs; + } + + /** + * Returns a single attribute that exactly matches the specified attribute + * name. + * @param attrName Name of attribute to return. + * For example: + *
+     *     "cn"            // Only a non-subtyped version of cn
+     *     "cn;lang-ja"    // Only a Japanese version of cn
+     *
+ * @return Attribute that has exactly the same name, or null + * (if no attribute in the set matches the specified name). + * @see netscape.ldap.LDAPAttribute + */ + public LDAPAttribute getAttribute( String attrName ) { + prepareHashtable(); + if (attrHash != null) { + return (LDAPAttribute)attrHash.get( attrName.toLowerCase() ); + } else { + for (int i = 0; i < attrs.length; i++) { + if (attrName.equalsIgnoreCase(attrs[i].getName())) { + return attrs[i]; + } + } + return null; + } + } + + /** + * Prepare hashtable for fast attribute lookups + */ + private void prepareHashtable() { + if ((attrHash == null) && (attrs.length >= ATTR_COUNT_REQUIRES_HASH)) { + attrHash = new Hashtable(); + for (int j = 0; j < attrs.length; j++) { + attrHash.put( attrs[j].getName().toLowerCase(), attrs[j] ); + } + } + } + + /** + * Returns the subtype that matches the attribute name specified + * by attrName and the language specificaton identified + * by lang. + *

+ * + * If no attribute in the set has the specified name and subtype, + * the method returns null. + * + * Attributes containing subtypes other than lang + * (for example, cn;binary) are returned only if + * they contain the specified lang subtype and if + * the set contains no attribute having only the lang + * subtype. (For example, getAttribute( "cn", "lang-ja" ) + * returns the cn;lang-ja;phonetic attribute only if + * the cn;lang-ja attribute does not exist.) + *

+ * + * If null is specified for the lang argument, + * calling this method is the same as calling the + * getAttribute(attrName) method. + *

+ * + * For example, suppose an entry contains only the following attributes: + *

+ *

    + *
  • cn;lang-en + *
  • cn;lang-ja-JP-kanji + *
  • sn + *
+ *

+ * + * Calling the following methods will return the following values: + *

+ *

    + *
  • getAttribute( "cn" ) returns null. + *
  • getAttribute( "sn" ) returns the "sn" attribute. + *
  • getAttribute( "cn", "lang-en-us" ) returns the "cn;lang-en" attribute. + *
  • getAttribute( "cn", "lang-en" ) returns the "cn;lang-en" attribute. + *
  • getAttribute( "cn", "lang-ja" ) returns null. + *
  • getAttribute( "sn", "lang-en" ) returns the "sn" attribute. + *
+ *

+ * @param attrName Name of attribute to find in the entry. + * @param lang A language specification. + * @return The attribute that matches the base name and that best + * matches any specified language subtype. + * @see netscape.ldap.LDAPAttribute + */ + public LDAPAttribute getAttribute( String attrName, String lang ) { + if ( (lang == null) || (lang.length() < 1) ) + return getAttribute( attrName ); + + String langLower = lang.toLowerCase(); + if ((langLower.length() < 5) || + ( !langLower.substring( 0, 5 ).equals( "lang-" ) )) { + return null; + } + StringTokenizer st = new StringTokenizer( langLower, "-" ); + // Skip first token, which is "lang-" + st.nextToken(); + String[] langComponents = new String[st.countTokens()]; + int i = 0; + while ( st.hasMoreTokens() ) { + langComponents[i] = st.nextToken(); + i++; + } + + String searchBasename = LDAPAttribute.getBaseName(attrName); + String[] searchTypes = LDAPAttribute.getSubtypes(attrName); + LDAPAttribute found = null; + int matchCount = 0; + for( i = 0; i < attrs.length; i++ ) { + boolean isCandidate = false; + LDAPAttribute attr = attrs[i]; + // Same base name? + if ( attr.getBaseName().equalsIgnoreCase(searchBasename) ) { + // Accept any subtypes? + if( (searchTypes == null) || (searchTypes.length < 1) ) { + isCandidate = true; + } else { + // No, have to check each subtype for inclusion + if( attr.hasSubtypes( searchTypes ) ) + isCandidate = true; + } + } + String attrLang = null; + if ( isCandidate ) { + attrLang = attr.getLangSubtype(); + // At this point, the base name and subtypes are okay + if ( attrLang == null ) { + // If there are no language attributes, this one is okay + found = attr; + } else { + // We just have to check for language match + st = new StringTokenizer( attrLang.toLowerCase(), "-" ); + // Skip first token, which is "lang-" + st.nextToken(); + // No match if the attribute's language spec is longer + // than the target one + if ( st.countTokens() > langComponents.length ) + continue; + + // How many subcomponents of the language match? + int j = 0; + while ( st.hasMoreTokens() ) { + if ( !langComponents[j].equals( st.nextToken() ) ) { + j = 0; + break; + } + j++; + } + if ( j > matchCount ) { + found = attr; + matchCount = j; + } + } + } + } + return found; + } + + /** + * Returns the attribute at the position specified by the index + * (for example, if you specify the index 0, the method returns the + * first attribute in the set). The index is 0-based. + * + * @param index Index of the attribute that you want to get. + * @return Attribute at the position specified by the index. + */ + public LDAPAttribute elementAt (int index) { + return attrs[index]; + } + + /** + * Removes attribute at the position specified by the index + * (for example, if you specify the index 0, the method removes the + * first attribute in the set). The index is 0-based. + * + * @param index Index of the attribute that you want to remove. + */ + public void removeElementAt (int index) { + if ((index >= 0) && (index < attrs.length)) { + synchronized(this) { + LDAPAttribute[] vals = new LDAPAttribute[attrs.length-1]; + int j = 0; + for (int i = 0; i < attrs.length; i++) { + if (i != index) { + vals[j++] = attrs[i]; + } + } + attrs = vals; + } + } + } + + /** + * Returns the number of attributes in this set. + * @return Number of attributes in this attribute set. + */ + public int size () { + return attrs.length; + } + + /** + * Adds the specified attribute to this attribute set. + * @param attr Attribute that you want to add to this set. + */ + public synchronized void add( LDAPAttribute attr ) { + if (attr != null) { + LDAPAttribute[] vals = new LDAPAttribute[attrs.length+1]; + for (int i = 0; i < attrs.length; i++) + vals[i] = attrs[i]; + vals[attrs.length] = attr; + attrs = vals; + if (attrHash != null) { + attrHash.put( attr.getName().toLowerCase(), attr ); + } + } + } + + /** + * Removes the specified attribute from the set. + * @param name Name of the attribute that you want removed. + */ + public synchronized void remove( String name ) { + for( int i = 0; i < attrs.length; i++ ) { + if ( name.equalsIgnoreCase( attrs[i].getName() ) ) { + removeElementAt(i); + break; + } + } + } + + /** + * Retrieves the string representation of all attributes + * in the attribute set. For example: + * + *

+     * LDAPAttributeSet: LDAPAttribute {type='cn', values='Barbara Jensen,Babs
+     * Jensen'}LDAPAttribute {type='sn', values='Jensen'}LDAPAttribute {type='
+     * givenname', values='Barbara'}LDAPAttribute {type='objectclass', values=
+     * 'top,person,organizationalPerson,inetOrgPerson'}LDAPAttribute {type='ou',
+     * values='Product Development,People'}
+     * 
+ * + * @return String representation of all attributes in the set. + */ + public String toString() { + String s = "LDAPAttributeSet: "; + if ( attrs.length > 0 ) { + for( int i = 0; i < attrs.length; i++ ) + s += attrs[i].toString(); + } + return s; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPCache.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPCache.java new file mode 100644 index 00000000000..6b29b3879be --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPCache.java @@ -0,0 +1,809 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import java.util.*; +import java.io.*; +import netscape.ldap.*; +import netscape.ldap.client.*; +import netscape.ldap.util.*; +import java.util.zip.CRC32; + +/** + * LDAPCache is the class that represents an + * in-memory cache that you can use to reduce the number of + * search requests sent to the LDAP server. + *

+ * + * Each item in the cache represents a search request and + * its results. Each item is uniquely identified by the + * search criteria, which includes: + *

+ * + *

    + *
  • the host name and port number of the LDAP server + *
  • the base DN of the search + *
  • the search filter + *
  • the scope of the search + *
  • the attributes to be returned in the search results + *
  • the DN used to authenticate the client when binding + * to the server + *
  • the LDAP v3 controls specified in the search request + *
+ *

+ * + * After a search request is cached, the results of any + * subsequent search requests using the same criteria are 8 + * read from the cache. Note that if any part of the + * criteria differs (for example, if a different DN is used + * when binding to the server or if a different set of + * attributes to be returned is specified), the search + * request is sent to the server. + *

+ * + * When you create the cache, you specify the maximum amount + * of time that an item can be kept in the cache. When an + * item's age exceeds that time limit, the item is removed + * from the cache. + *

+ * + * The cache also has a maximum size that you specify when + * creating the cache. If adding a new item exceeds the + * maximum size of the cache, the first entries in the cache + * are removed to make enough space for the new item. + *

+ * + * Finally, when creating the cache, you can specify a list + * of the base DNs in search requests that you want to cache. + * For example, if you specify o=Airius.com as + * a base DN to cache, your client caches search requests + * where the base DN is o=Airius.com. + *

+ * + * To specify that you want to use a cache for a particular + * LDAP session, call the setCache method of + * the LDAPConnection object that you are + * working with. + *

+ * + * All clones of an LDAPConnection object share + * the same LDAPCache object. + *

+ * + * The LDAPCache class includes methods for + * getting statistics (such as hit rates) from the cache and + * for flushing entries from the cache. + *

+ * + * @see netscape.ldap.LDAPConnection#setCache(netscape.ldap.LDAPCache) + * @see netscape.ldap.LDAPConnection#getCache + */ +public class LDAPCache implements TimerEventListener { + private Hashtable m_cache; + private long m_timeToLive; + private long m_maxSize; + private String[] m_dns; + private Vector m_orderedStruct; + private long m_remainingSize = 0; + /** + * Delimiter used internally when creating keys + * for the cache. + */ + public static final String DELIM = "#"; + private Timer m_timer = null; + private static long TIMEOUT = 60000; + private long m_totalOpers = 0; + private static final boolean m_debug = false; + private long m_hits = 0; + private long m_flushes = 0; + + + /** + * Constructs a new LDAPCache object, using the + * specified maximum size of the cache (in bytes) and the maximum + * age of cached items (in seconds). When items in the cache + * exceed this age, they are removed from the cache. + *

+ * + * @param ttl The maximum amount of time that an item can be cached + * (in seconds) + * @param size The maximum size of the cache (in bytes) + */ + public LDAPCache(long ttl, long size) + { + init(ttl, size); + } + + /** + * Constructs a new LDAPCache object, using the + * specified maximum size of the cache (in bytes), and the maximum + * age of cached items (in seconds), and an array of the base DNs + * of searches that you want to cache. (For example, + * if the array of base DNs includes o=Airius.com, + * the cache stores search results if the base DN in the search + * request is o=Airius.com.) + *

+ * + * @param ttl The maximum amount of time that an item can be cached + * (in seconds) + * @param size The maximum size of the cache (in bytes) + * @param dns The list of base DNs of searches that you want to cache. + */ + public LDAPCache(long ttl, long size, String[] dns) + { + init(ttl, size); + + m_dns = new String[dns.length]; + if ((dns != null) && (dns.length > 0)) + for (int i=0; i + * + * @return The maximum size of the cache (in bytes) + */ + public long getSize() + { + return m_maxSize; + } + + /** + * Gets the maximum age allowed for cached items (in + * seconds). (Items that exceed this age are + * removed from the cache.) + *

+ * + * @return The maximum age of items in the cache (in + * seconds). + */ + public long getTimeToLive() + { + return m_timeToLive/1000; + } + + /** + * Gets the array of base DNs of searches to be cached. + * (Search requests with these base DNs are cached.) + *

+ * + * @return The array of base DNs. + */ + public String[] getBaseDNs() + { + return m_dns; + } + + /** + * Flush the entries identified by DN and scope from the cache. + *

+ * + * @param dn The distinguished name (or base DN) of the entries + * to be removed from the cache. Use this parameter in conjunction + * with scope to identify the entries that you want + * removed from the cache. If this parameter is null, + * the entire cache is flushed. + * @param scope The scope identifying the entries that you want + * removed from the cache. The value of this parameter can be + * one of the following: + *

    + *
  • LDAPv2.SCOPE_BASE (to remove the entry identified + * by dn) + *
  • LDAPv2.SCOPE_ONE (to remove the entries that + * have dn as their parent entry) + *
  • LDAPv2.SCOPE_SUB (to remove the entries in the + * subtree under dn in the directory) + *
+ *

+ * @return true if the entry is removed from the cache, + * or false if the entry is not removed. + */ + public synchronized boolean flushEntries(String dn, int scope) { + + if (m_debug) + System.out.println("DEBUG: User request for flushing entry: dn "+ + dn+" and scope "+scope); + // if the dn is null, invalidate the whole cache + if (dn == null) + { + // reclaim all the cache spaces + m_remainingSize = m_maxSize; + m_cache.clear(); + m_orderedStruct.removeAllElements(); + return true; + } + + DN dn2 = new DN(dn); + + Enumeration e = m_cache.keys(); + + while(e.hasMoreElements()) { + Long key = (Long)e.nextElement(); + Vector val = (Vector)m_cache.get(key); + + int j=1; + int size2=val.size(); + + for (; j"+key); + + return true; + } + } + + if (m_debug) + System.out.println("DEBUG: The number of keys in the cache is " + +m_cache.size()); + + return false; + } + + /** + * Gets invoked when the timer expires. + * @param e The timer event containing the timer itself. + */ + public void timerExpired(TimerEvent e) + { + flushEntries(); + + Timer t = (Timer)e.getSource(); + t.start(); + } + + /** + * Gets the amount of available space (in bytes) left in the cache. + *

+ * + * @return The available space (in bytes) in the cache. + */ + public long getAvailableSize() { + return m_remainingSize; + } + + /** + * Gets the total number of requests for retrieving items from + * the cache. This includes both items successfully found in + * the cache and items not found in the cache. + *

+ * + * @return The total number of requests for retrieving items from + * the cache. + */ + public long getTotalOperations() { + return m_totalOpers; + } + + /** + * Gets the total number of requests which failed to find and + * retrieve an item from the cache. + *

+ * + * @return The number of requests that did not find and retrieve + * an item in the cache. + */ + public long getNumMisses() { + return (m_totalOpers - m_hits); + } + + /** + * Gets the total number of requests which successfully found and + * retrieved an item from the cache. + * @return The number of requests that successfully found and + * retrieved an item from the cache. + */ + public long getNumHits() { + return m_hits; + } + + /** + * Gets the total number of entries that are flushed when timer expires + * and flushEntries is called. + *

+ * + * @return The total number of entries that are flushed when timer + * expires. + */ + public long getNumFlushes() { + return m_flushes; + } + + /** + * Create a key for a cache entry by concatenating all input parameters + * @return The key for a cache entry + * @exception LDAPException Thrown when failed to create key. + */ + Long createKey(String host, int port, String baseDN, String filter, + int scope, String[] attrs, String bindDN, LDAPSearchConstraints cons) + throws LDAPException { + + DN dn = new DN(baseDN); + baseDN = dn.toString(); + + if (m_dns != null) { + int i=0; + for (; i= m_dns.length) + throw new LDAPException(baseDN+" is not a cached base DN", + LDAPException.OTHER); + } + + String key = null; + + key = appendString(baseDN); + key = key+appendString(scope); + key = key+appendString(host); + key = key+appendString(port); + key = key+appendString(filter); + key = key+appendString(attrs); + key = key+appendString(bindDN); + + LDAPControl[] serverControls = null; + LDAPControl[] clientControls = null; + + // get server and client controls + if (cons != null) + { + serverControls = cons.getServerControls(); + clientControls = cons.getClientControls(); + } + + if ((serverControls != null) && (serverControls.length > 0)) + { + String[] objID = new String[serverControls.length]; + + for (int i=0; i 0)) + { + String[] objID = new String[clientControls.length]; + + for (int i=0; i "+key+ + " not found in the cache."); + else + System.out.println("DEBUG: Entry whose key -> "+key+ + " found in the cache."); + } + + if (obj != null) + m_hits++; + + + return obj; + } + + /** + * Flush entries which stays longer or equal to the time-to-live. + */ + synchronized void flushEntries() + { + Vector v = null; + boolean delete = false; + + Date date = new Date(); + long currTime = date.getTime(); + + m_flushes = 0; + while(true) { + if (m_orderedStruct.size() <= 0) + break; + + v = (Vector)m_orderedStruct.firstElement(); + long diff = currTime-((Long)v.elementAt(1)).longValue(); + if (diff >= m_timeToLive) { + Long key = (Long)v.elementAt(0); + + if (m_debug) + System.out.println("DEBUG: Timer flush entry whose key is "+key); + + Vector entry = (Vector)m_cache.remove(key); + m_remainingSize = m_remainingSize + ((Long)entry.firstElement()).longValue(); + + // always delete the first one + m_orderedStruct.removeElementAt(0); + + m_flushes++; + } + else + break; + } + + if (m_debug) + System.out.println("DEBUG: The number of keys in the cache is " + +m_cache.size()); + } + + /** + * Add the entry to the hashtable cache and to the vector respectively. + * The vector is used to keep track of the order of the entries being added. + * @param key The key for the cache entry. + * @param value The cache entry being added to the cache for the specified + * key. + * @exception LDAPException Get thrown when failed to add the entry. + */ + synchronized void addEntry(Long key, Object value) throws LDAPException + { + // if entry exists, dont perform add operation + if (m_cache.get(key) != null) + return; + + Vector v = (Vector)value; + + // assume the size of the key is 4 bytes + long size = ((Long)v.elementAt(0)).longValue()+4; + + if (size > m_maxSize) { + throw new LDAPException("Failed to add an entry to the cache since the new entry exceeds the cache size", LDAPException.OTHER); + } + + v.setElementAt(new Long(size), 0); + + // if the size of entry being added is bigger than the spare space in the + // cache + if (size > m_remainingSize) { + while (true) { + Vector element = (Vector)m_orderedStruct.firstElement(); + Long str = (Long)element.elementAt(0); + Vector val = (Vector)m_cache.remove(str); + if (m_debug) + System.out.println("DEBUG: The spare size of the cache is not big enough "+ + "to hold the new entry, deleting the entry whose key -> "+str); + + // always remove the first one + m_orderedStruct.removeElementAt(0); + m_remainingSize = m_remainingSize + + ((Long)val.elementAt(0)).longValue(); + if (m_remainingSize >= size) + break; + } + } + + m_remainingSize = m_remainingSize - size; + m_cache.put(key, v); + Vector element = new Vector(); + element.addElement(key); + Date date = new Date(); + element.addElement(new Long(date.getTime())); + m_orderedStruct.addElement(element); + + if (m_debug) + { + System.out.println("DEBUG: Adding a new entry whose key -> "+key); + System.out.println("DEBUG: The current number of keys in the cache "+ + m_cache.size()); + } + } + + /** + * Gets the number of entries being cached. + * @return The number of entries being cached. + */ + int size() + { + return m_cache.size(); + } + + /** + * Clean up + */ + void cleanup() { + m_timer.stop(); + } + + /** + * Initialize the instance variables. + */ + private void init(long ttl, long size) + { + m_cache = new Hashtable(); + m_timeToLive = ttl*1000; + m_maxSize = size; + m_remainingSize = size; + m_dns = null; + m_orderedStruct = new Vector(); + m_timer = new Timer(TIMEOUT); + m_timer.addTimerExpiredEventListener((TimerEventListener)this); + m_timer.start(); + } + + /** + * Concatenate the specified integer with the delimiter. + * @param str The string which concatenate with the delimiter. + * @return The concatenated string + */ + private String appendString(String str) { + if (str == null) + return "null"+DELIM; + else + return str.trim()+DELIM; + } + + /** + * Concatenate the specified integer with the delimiter. + * @param num The integer which concatenate with the delimiter. + * @return The concatenated string + */ + private String appendString(int num) { + return num+DELIM; + } + + /** + * Concatenate the specified string array with the delimiter. + * @param str A string array. + * @return The concatenated string + */ + private String appendString(String[] str) { + + if ((str == null) || (str.length < 1)) + return "0"+DELIM; + else { + sortStrings(str); + + String s = str.length+DELIM; + for (int i=0; i 0) + { + String t = str[i]; + str[i] = str[j]; + str[j] = t; + } + } + } + + /** + * Create a 32 bits CRC from the given byte array. + */ + private long getCRC32(byte[] barray) { + CRC32 crcVal = new CRC32(); + crcVal.update(barray); + return crcVal.getValue(); + } +} + +/** + * Represents a timer which will timeout for every certain interval. It + * provides methods to start, stop, or restart timer. It also provides + * methods to register/deregister the event listeners. + */ +class Timer { + + private long m_timeout; + private Thread t = null; + private TimerEventListener listener; + protected TimerEventListener stopListener = null; + + /** + * Constructor with the specified timout. + * @param timeout The timeout value in milliseconds. + */ + Timer(long timeout) { + m_timeout = timeout; + } + + /** + * Start the timer. + */ + void start() { + TimerRunnable trun = new TimerRunnable(this); + t = new Thread(trun); + t.start(); + } + + /** + * Suspend the timer. + */ + void suspend() { + t.suspend(); + } + + /** + * Stop the timer. + */ + void stop() { + t.stop(); + } + + /** + * Restart the timer. + */ + void restart() { + t.resume(); + } + + /** + * Get the timeout value. + * @return the timeout value. + */ + long getTimeout() { + return m_timeout; + } + + /** + * Notify the listener when the timer expires. + */ + void fireExpiredEvent() { + TimerEvent event; + + if (stopListener != null) + { + event = new TimerEvent(this); + stopListener.timerExpired(event); + } + } + + /** + * Add the listener to the queue who wants to be notified when the timer + * expires. + */ + void addTimerExpiredEventListener(TimerEventListener listener) { + stopListener = listener; + } + + /** + * Remove the listener from the queue who will not get notified when the + * timer expires. + */ + void removeTimerExpiredEventListener(TimerEventListener listener) { + stopListener = null; + } +} + +/** + * Represents the starting point for the timer thread to execute. + */ +class TimerRunnable implements Runnable { + Timer m_timer; + + /** + * Constructor with the specified timer object. + * @param t The timer + */ + TimerRunnable(Timer t) { + m_timer = t; + } + + /** + * The runnable waits until the timeout period has elapsed. It then notify + * the registered listener who listens for the timeout event. + */ + public void run() { + + synchronized(this) { + try { + this.wait(m_timer.getTimeout()); + } catch (InterruptedException e) { + System.out.println("Timer get interrupted"); + } + } + + m_timer.fireExpiredEvent(); + } +} + +/** + * Represents the timer event. When the timer expires, it will notify + * all the registered listeners which receive the timer event. The + * listener can retrieve the source of the event from the timer event. + */ +class TimerEvent extends EventObject { + + /** + * Constructor with the specified source of the timer event. + * @param source The source of the timer event. + */ + TimerEvent(Object source) { + super(source); + } +} + +/** + * The timer client needs to implement this interface if it wants to + * receive the timeout event. + */ +interface TimerEventListener extends EventListener { + /** + * Gets invoked when the timer expires. + * @param timeout Timeout event contains the source of the event which is + * the timer. + */ + void timerExpired(TimerEvent timeout); +} + diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPCheckComm.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPCheckComm.java new file mode 100644 index 00000000000..cf3b64062bc --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPCheckComm.java @@ -0,0 +1,61 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +/** + * This static class checks if the caller is the applet running in the + * communicator. If so, then it returns the appropriate method. + */ +class LDAPCheckComm { + + /** + * It returns the method whose name matches the specified argument. + * @param classPackage The class package + * @param name The method name + * @return The method + * @exception LDAPException Gets thrown it the method is not found or + * the caller is not an applet running in the communicator + */ + static java.lang.reflect.Method getMethod(String classPackage, String name) throws LDAPException { + SecurityManager sec = System.getSecurityManager(); + + if ( sec == null ) { + /* Not an applet, we can do what we want to */ + throw new LDAPException("No security manager"); + } else if ( sec.toString().startsWith("java.lang.NullSecurityManager") ) { + /* Not an applet, we can do what we want to */ + throw new LDAPException("No security manager"); + } else if (sec.toString().startsWith("netscape.security.AppletSecurity")) { + /* Running as applet. Is PrivilegeManager around? */ + try { + Class c = Class.forName(classPackage); + java.lang.reflect.Method[] m = c.getMethods(); + for( int i = 0; i < m.length; i++ ) { + if ( m[i].getName().equals(name) ) { + return m[i]; + } + } + throw new LDAPException("no enable privilege in " + classPackage); + } catch (ClassNotFoundException e) { + throw new LDAPException("Class not found"); + } + } + return null; + } +} + diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPCompareAttrNames.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPCompareAttrNames.java new file mode 100644 index 00000000000..4be84a397f9 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPCompareAttrNames.java @@ -0,0 +1,240 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import java.util.*; +import netscape.ldap.client.*; + +/** + * Compares LDAP entries based on one or more attribute values. + *

+ * + * To use this comparison for sorting search results, pass + * an object of this class to the sort method in + * LDAPSearchResults. + *

+ * + * @version 1.0 + * @see LDAPEntryComparator + * @see LDAPSearchResults#sort + */ + +public class LDAPCompareAttrNames implements LDAPEntryComparator { + + String m_attrs[]; + boolean m_ascending[]; + + /** + * Constructs a comparator that compares the string values of + * a named attribute in LDAP entries and sorts the entries in + * ascending order. + *

+ * + * @param attribute Name of attribute for comparisons. + */ + public LDAPCompareAttrNames (String attribute) { + m_attrs = new String[1]; + m_attrs[0] = attribute; + m_ascending = new boolean[1]; + m_ascending[0] = true; + } + + /** + * Constructs a comparator that compares the string values in + * a named attribute in LDAP entries and that allows you to sort + * entries either in ascending or descending order. + *

+ * + * @param attribute Name of attribute for comparisons. + * @param ascendingFlag If true, sort in ascending order. + */ + public LDAPCompareAttrNames (String attribute, + boolean ascendingFlag) { + m_attrs = new String[1]; + m_attrs[0] = attribute; + m_ascending = new boolean[1]; + m_ascending[0] = ascendingFlag; + } + + /** + * Constructs a comparator that compares the string values in + * a set of named attributes in LDAP entries and that sort + * the entries in ascending order. + *

+ * + * Use an array of strings to specify the set of attributes + * that you want to use for sorting. If the values of the + * first attribute (the name specified in attribute[0]) + * are equal, then the values of the next attribute are compared. + *

+ * + * For example, if attributes[0] = "cn" and + * attributes[1]="uid", results are first sorted + * by the cn attribute. If two entries have the + * same value for the cn, then the uid + * attribute is used to sort the entries. + *

+ * + * @param attributes Array of the attribute names used for comparisons. + */ + public LDAPCompareAttrNames (String[] attributes) { + m_attrs = attributes; + m_ascending = new boolean[attributes.length]; + for( int i = 0; i < attributes.length; i++ ) + m_ascending[i] = true; + } + + /** + * Constructs a comparator that compares the string values in + * a set of named attributes in LDAP entries and that allows you + * to sort the entries in ascending or descending order. + *

+ * + * Use an array of strings to specify the set of attributes + * that you want to use for sorting. If the values of the + * first attribute (the name specified in attribute[0]) + * are equal, then the values of the next attribute are compared. + *

+ * + * For example, if attributes[0] = "cn" and + * attributes[1]="uid", results are first sorted + * by the cn attribute. If two entries have the + * same value for cn, then the uid + * attribute is used to sort the entries. + *

+ * + * Use an array of boolean values to specify whether each attribute + * should be sorted in ascending or descending order. For example, + * suppose that attributes[0] = "cn" and + * attributes[1]="roomNumber". If + * ascendingFlags[0]=true and + * ascendingFlags[1]=false, attributes are sorted first by + * cn in ascending order, then by roomNumber + * in descending order. + *

+ * + * If the size of the array of attribute names is not the same as + * the size of the array of boolean values, an + * LDAPException is thrown. + *

+ * + * @param attribute Array of the attribute names to use for comparisons. + * @param ascendingFlags Array of boolean values specifying ascending or descending order to use for each attribute name. If true, sort the attributes in ascending order. + */ + public LDAPCompareAttrNames (String[] attributes, + boolean[] ascendingFlags) { + m_attrs = attributes; + m_ascending = ascendingFlags; + if ( m_ascending == null ) { + m_ascending = new boolean[attributes.length]; + for( int i = 0; i < attributes.length; i++ ) + m_ascending[i] = true; + } + } + + /** + * If the value of the attribute in the first entry is greater + * than the attribute in the second entry, returns true. + *

+ * + * If one of the entries is missing the attribute, the other is + * considered greater. By default, the first entry is greater. + *

+ * + * If either entry contains multiple values, only the first value + * is used for comparisons. + *

+ * + * @param greater Entry to be tested against. + * @param less Entry to test. + * @return true if (greater > less). + */ + public boolean isGreater (LDAPEntry greater, LDAPEntry less) { + if (greater.equals (less)) return false; + return attrGreater (greater, less, 0); + } + + /** + * Compares a particular attribute in both entries. If equal, + * moves on to the next. + * @param greater Greater arg from isGreater + * @param less Less param is isGreater + * @param attrPos Index into array of attributes, indicating + * the attribute to compare + * @return (greater > less) + */ + boolean attrGreater (LDAPEntry greater, LDAPEntry less, + int attrPos) { + Enumeration greaterAttrSet = + greater.getAttributeSet().getAttributes(); + Enumeration lessAttrSet = + less.getAttributeSet().getAttributes(); + + String greaterValue = null; + String lessValue = null; + String attrName = m_attrs[attrPos]; + boolean ascending = m_ascending[attrPos]; + + try { + while (lessAttrSet.hasMoreElements()) { + LDAPAttribute currAttr = + (LDAPAttribute)(lessAttrSet.nextElement()); + if (!attrName.equalsIgnoreCase (currAttr.getName())) + continue; + lessValue = + (String)(currAttr.getStringValues().nextElement()); + break; + } + + while (greaterAttrSet.hasMoreElements()) { + LDAPAttribute currAttr = + (LDAPAttribute)(greaterAttrSet.nextElement()); + if (!attrName.equalsIgnoreCase (currAttr.getName())) + continue; + greaterValue = + (String)(currAttr.getStringValues().nextElement()); + break; + } + } + catch (ClassCastException cce) { + // i.e. one of the enumerations did not contain the + // right type !? + return false; + } + catch (NoSuchElementException nse) { + // i.e. one of the attributes had no values !? + return false; + } + + if ((lessValue == null) ^ (greaterValue == null)) + return greaterValue != null; + + if (lessValue == null || + lessValue.equalsIgnoreCase (greaterValue)) + if (attrPos == m_attrs.length - 1) + return false; + else + return attrGreater (greater, less, attrPos+1); + + if( ascending ) + return (greaterValue.compareTo (lessValue) > 0); + else + return (greaterValue.compareTo (lessValue) < 0); + } + +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPConnection.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPConnection.java new file mode 100644 index 00000000000..581be0661ff --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPConnection.java @@ -0,0 +1,3907 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import java.util.*; +import netscape.ldap.client.*; +import netscape.ldap.client.opers.*; +import netscape.ldap.ber.stream.*; +import netscape.ldap.util.*; +import java.io.*; +import java.net.*; + +/** + * Represents a connection to an LDAP server.

+ * + * Use objects of this class to perform LDAP operations (such as + * search, modify, and add) on an LDAP server.

+ * + * To perform an LDAP operation on a server, you need to follow + * these steps:

+ * + *

    + *
  1. Create a new LDAPConnection object. + *
  2. Use the connect method to connect to the + * LDAP server. + *
  3. Use the authenticate method to authenticate + * to server. + *
  4. Perform the LDAP operation. + *
  5. Use the disconnect method to disconnect from + * the server when done. + *
+ *

+ * + * All operations block until completion (with the exception of + * the search method when the results are not all returned at + * the same time). + *

+ * + * This class also specifies a default set of search constraints + * (such as the maximum number of results returned in a search) + * which apply to all operations. To get and set these constraints, + * use the getOption and setOption methods. + * To override these constraints for an individual search operation, + * define a new set of constraints by creating a LDAPSearchConstraints + * option and pass the object to the search method. + *

+ * + * If you set up your client to follow referrals automatically, + * an operation that results in a referral will create a new connection + * to the LDAP server identified in the referral. In order to have + * your client authenticate to that LDAP server automatically, you need + * to define a class that implements the LDAPRebind interface. + * In your definition of the class, you need to define a + * getRebindAuthentication method that creates an LDAPRebindAuth + * object containing the distinguished name and password to use for reauthentication. + *

+ * + * Most errors that occur raise the same exception (LDAPException). + * In order to determine the exact problem that occurred, you can retrieve the + * result code from this exception and compare its value against a set of defined + * result codes. + *

+ * + * @version 1.0 + * @see netscape.ldap.LDAPSearchConstraints + * @see netscape.ldap.LDAPRebind + * @see netscape.ldap.LDAPRebindAuth + * @see netscape.ldap.LDAPException + */ +public class LDAPConnection implements LDAPv3, Cloneable { + + /** + * Version of the LDAP protocol used by default. + * LDAP_VERSION is 2, so your client will + * attempt to authenticate to LDAP servers as an LDAP v2 client. + * The following is an example of some code that prints the + * value of this variable: + *

+ * + *

+     * LDAPConnection ld = new LDAPConnection();
+     * System.out.println( "The default LDAP protocol version used is "
+     *                      ld.LDAP_VERSION );
+     * 
+ * + * If you want to authenticate as an LDAP v3 client, + * use the authenticate(int version, String dn, String passwd) method. + * For example: + *

+ * + *

+     * ld.authenticate( 3, myDN, myPW );
+     * 
+ * + * @see netscape.ldap.LDAPConnection#authenticate(int, java.lang.String, java.lang.String) + */ + public final static int LDAP_VERSION = 2; + /** + * Name of the property specifying the version of the SDK.

+ * + * To get the version number, pass this name to the + * getProperty method. The SDK version number + * is a Float type. For example:

+ *

+     *      ...
+     *      Float sdkVersion = ( Float )myConn.getProperty( myConn.LDAP_PROPERTY_SDK );
+     *      System.out.println( "SDK version: " + sdkVersion );
+     *      ... 
+ * @see netscape.ldap.LDAPConnection#getProperty(java.lang.String) + */ + public final static String LDAP_PROPERTY_SDK = "version.sdk"; + /** + * Name of the property specifying the highest supported version of + * the LDAP protocol.

+ * + * To get the version number, pass this name to the + * getProperty method. The LDAP protocol version number + * is a Float type. For example:

+ *

+     *      ...
+     *      Float LDAPVersion = ( Float )myConn.getProperty( myConn.LDAP_PROPERTY_PROTOCOL );
+     *      System.out.println( "Highest supported LDAP protocol version: " + LDAPVersion );
+     *      ... 
+ * @see netscape.ldap.LDAPConnection#getProperty(java.lang.String) + */ + public final static String LDAP_PROPERTY_PROTOCOL = "version.protocol"; + /** + * Name of the property specifying the types of authentication allowed by this + * API (for example, anonymous authentication and simple authentication).

+ * + * To get the supported types, pass this name to the + * getProperty method. The value of this property is + * a String type. For example:

+ *

+     *      ...
+     *      String authTypes = ( String )myConn.getProperty( myConn.LDAP_PROPERTY_SECURITY );
+     *      System.out.println( "Supported authentication types: " + authTypes );
+     *      ... 
+ * @see netscape.ldap.LDAPConnection#getProperty(java.lang.String) + */ + public final static String LDAP_PROPERTY_SECURITY = "version.security"; + + /** + * Constants + */ + private final static String defaultFilter = "(objectClass=*)"; + private final static LDAPSearchConstraints readConstraints = new + LDAPSearchConstraints(); + + /** + * Internal variables + */ + transient private LDAPSearchConstraints defaultConstraints = new + LDAPSearchConstraints (); + transient private Vector responseListeners; + transient private Vector searchListeners; + transient private boolean bound; + transient private String host; + transient private String[] m_hostList; + transient private int port; + transient private int[] m_portList; + transient private int m_defaultPort; + transient private String prevBoundDN; + transient private String prevBoundPasswd; + transient private String boundDN; + transient private String boundPasswd; + transient private int protocolVersion = LDAP_VERSION; + transient private LDAPSocketFactory m_factory; + /* th does all socket i/o for the object and any clones */ + transient private LDAPConnThread th = null; + /* To manage received server controls on a per-thread basis, + we keep a table of active threads and a table of controls, + indexed by thread */ + transient private Vector m_attachedList = new Vector(); + transient private Hashtable m_responseControlTable = new Hashtable(); + transient private LDAPCache m_cache = null; + static Hashtable m_threadConnTable = new Hashtable(); + + // this handles the case when the client lost the connection with the + // server. After the client reconnects with the server, the bound resets + // to false. If the client used to have anonymous bind, then this boolean + // will take care of the case whether the client should send anonymous bind + // request to the server. + private boolean m_anonymousBound = false; + + private Object m_security = null; + private boolean saslBind = false; + private Object m_mechanismDriver; + private Properties m_securityProperties; + private Object m_clientCB; + private Hashtable m_methodLookup = new Hashtable(); + + /** + * Properties + */ + private final static Float SdkVersion = new Float(3.03f); + private final static Float ProtocolVersion = new Float(3.0f); + private final static String SecurityVersion = new String("none,simple,sasl"); + private final static Float MajorVersion = new Float(3.0f); + private final static Float MinorVersion = new Float(0.03f); + private final static String DELIM = "#"; + private final static String PersistSearchPackageName = + "netscape.ldap.controls.LDAPPersistSearchControl"; + + /** + * Constructs a new LDAPConnection object, + * which represents a connection to an LDAP server.

+ * + * Calling the constructor does not actually establish + * the connection. To connect to the LDAP server, use the + * connect method. + * + * @see netscape.ldap.LDAPConnection#connect(java.lang.String, int) + * @see netscape.ldap.LDAPConnection#authenticate(java.lang.String, java.lang.String) + */ + public LDAPConnection () { + super(); + port = -1; + m_factory = null; + } + + /** + * Constructs a new LDAPConnection object that + * will use the specified socket factory class to create + * socket connections. The socket factory class must implement + * the LDAPSocketFactory interface.
+ * (For example, the LDAPSSLSocketFactory + * class implements this interface.) + *

+ * + * Note that calling the LDAPConnection constructor + * does not actually establish a connection to an LDAP server. + * To connect to an LDAP server, use the + * connect method. The socket connection will be + * constructed when this method is called. + *

+ * + * @see netscape.ldap.LDAPSocketFactory + * @see netscape.ldap.LDAPSSLSocketFactory + * @see netscape.ldap.LDAPConnection#connect(java.lang.String, int) + * @see netscape.ldap.LDAPConnection#authenticate(java.lang.String, java.lang.String) + * @see netscape.ldap.LDAPConnection#getSocketFactory + * @see netscape.ldap.LDAPConnection#setSocketFactory(netscape.ldap.LDAPSocketFactory) + */ + public LDAPConnection ( LDAPSocketFactory factory ) { + super(); + port = -1; + m_factory = factory; + } + + /** + * Finalize method, which disconnects from the LDAP server. + * @exception LDAPException Thrown when the connection cannot be disconnected. + */ + public void finalize() throws LDAPException + { + if (th != null) + disconnect(); + } + + /** + * Sets the specified LDAPCache object as the + * cache for the LDAPConnection object. + *

+ * + * @param cache The LDAPCache object representing + * the cache you want used by the current connection. + * @see netscape.ldap.LDAPCache + * @see netscape.ldap.LDAPConnection#getCache + */ + public void setCache(LDAPCache cache) { + m_cache = cache; + } + + /** + * Gets the LDAPCache object associated with + * the current LDAPConnection object. + *

+ * + * @return The LDAPCache object representing + * the cache used by the current connection. + * @see netscape.ldap.LDAPCache + * @see netscape.ldap.LDAPConnection#setCache(netscape.ldap.LDAPCache) + */ + public LDAPCache getCache() { + return m_cache; + } + + /** + * Gets a property of a connection.

+ * + * You can get the following properties for a given connection:

+ *

    + *
  • LDAP_PROPERTY_SDK

    + * To get the version of this SDK, get this property. The value of + * this property is a Float data type.

    + *

  • LDAP_PROPERTY_PROTOCOL

    + * To get the highest supported version of the LDAP protocol, get + * this property. + * The value of this property is a Float data type.

    + *

  • LDAP_PROPERTY_SECURITY

    + * To get a comma-separated list of the types of authentication + * supported, get this property. The value of this property is a + * String.

    + *

+ *

+ * + * For example, the following section of code gets the version of + * the SDK.

+ * + *

+     *       ...
+     *       Float sdkVersion = ( Float )myConn.getProperty( myConn.LDAP_PROPERTY_SDK );
+     *       System.out.println( "SDK version: " + sdkVersion );
+     *       ... 
+ * + * @param name Name of the property (for example, + * LDAP_PROPERTY_SDK).

+ * + * @return The value of the property.

+ * + * Since the return value is an object, you + * should recast it as the appropriate type. + * (For example, when getting the LDAP_PROPERTY_SDK property, + * recast the return value as a Float.)

+ * + * If you pass this method an unknown property name, the method + * returns null.

+ * + * @exception LDAPException Unable to get the value of the + * specified property.

+ * + * @see netscape.ldap.LDAPConnection#LDAP_PROPERTY_SDK + * @see netscape.ldap.LDAPConnection#LDAP_PROPERTY_PROTOCOL + * @see netscape.ldap.LDAPConnection#LDAP_PROPERTY_SECURITY + */ + public Object getProperty(String name) throws LDAPException { + if (name.equals(LDAP_PROPERTY_SDK)) + return SdkVersion; + else if (name.equals(LDAP_PROPERTY_PROTOCOL)) + return ProtocolVersion; + else if (name.equals(LDAP_PROPERTY_SECURITY)) + return SecurityVersion; + else if (name.equals("version.major")) + return MajorVersion; + else if (name.equals("version.minor")) + return MinorVersion; + else + return null; + } + + /** + * This method is reserved for future use and does not currently + * allow you to set any properties. + *

+ * + * @param name Name of the property that you want to set. + * @param val Value that you want to set. + * @exception LDAPException Unable to set the value of the specified + * property. + */ + public void setProperty(String name, Object val) throws LDAPException { + throw new LDAPException("No property has been set"); + } + + /** + * Sets the LDAP protocol version that your client prefers to use when + * connecting to the LDAP server. + *

+ * + * @param version The LDAP protocol version that your client uses. + */ + private void setProtocolVersion(int version) { + protocolVersion = version; + } + + /** + * Returns the host name of the LDAP server to which you are connected. + * @return Host name of the LDAP server. + */ + public String getHost () { + return host; + } + + /** + * Returns the port number of the LDAP server to which you are connected. + * @return Port number of the LDAP server. + */ + public int getPort () { + return port; + } + + /** + * Returns the distinguished name (DN) used for authentication over + * this connection. + * @return Distinguished name used for authentication over this connection. + */ + public String getAuthenticationDN () { + return boundDN; + } + + /** + * Returns the password used for authentication over this connection. + * @return Password used for authentication over this connection. + */ + public String getAuthenticationPassword () { + return boundPasswd; + } + + /** + * Gets the object representing the socket factory used to establish + * a connection to the LDAP server. + *

+ * + * @return The object representing the socket factory used to + * establish a connection to a server. + * @see netscape.ldap.LDAPSocketFactory + * @see netscape.ldap.LDAPSSLSocketFactory + * @see netscape.ldap.LDAPConnection#setSocketFactory(netscape.ldap.LDAPSocketFactory) + */ + public LDAPSocketFactory getSocketFactory () { + return m_factory; + } + + /** + * Specifies the object representing the socket factory that you + * want to use to establish a connection to a server. + *

+ * + * @param factory The object representing the socket factory that + * you want to use to establish a connection to a server. + * @see netscape.ldap.LDAPSocketFactory + * @see netscape.ldap.LDAPSSLSocketFactory + * @see netscape.ldap.LDAPConnection#getSocketFactory + */ + public void setSocketFactory (LDAPSocketFactory factory) { + m_factory = factory; + } + + /** + * Indicates whether the connection represented by this object + * is open at this time. + * @return If connected to an LDAP server over this connection, + * returns true. If not connected to an LDAP server, + * returns false. + */ + public boolean isConnected() { + return ((th != null) && th.isAlive()); + } + + /** + * Indicates whether this client has authenticated to the LDAP server + * @return If authenticated, returns true. If not + * authenticated, or if authenticated as an anonymous user (with + * either a blank name or password), returns false. + */ + public boolean isAuthenticated () { + if (bound) { + if ((boundDN == null) || boundDN.equals("") || + (boundPasswd == null) || boundPasswd.equals("")) + return false; + } + return bound; + } + + /** + * Connects to the specified host and port. If this LDAPConnection object + * represents an open connection, the connection is closed first + * before the new connection is opened. + *

+ * + * For example, the following section of code establishes a connection with + * the LDAP server running on the host ldap.netscape.com and the port 389. + *

+ * + *

+     * String ldapHost = "ldap.netscape.com";
+     * int ldapPort = 389;
+     * LDAPConnection myConn = new LDAPConnection();
+     * try {
+     *     myConn.connect( ldapHost, ldapPort );
+     * } catch ( LDAPException e ) {
+     *     System.out.println( "Unable to connect to " + ldapHost +
+     *                         " at port " + ldapPort );
+     *     return;
+     * }
+     * System.out.println( "Connected to " + ldapHost + " at port " + ldapPort )
+     * 
+ * + * @param host Host name of the LDAP server that you want to connect to. + * This value can also be a space-delimited list of hostnames or + * hostnames and port numbers (using the syntax + * hostname:portnumber). Your client application or applet + * will attempt to contact each host in the order you specify until a + * connection is established. For example, you can specify the following + * values for the host argument:
+ *
+     *   myhost
+     *   myhost hishost:389 herhost:5000 whathost
+     *   myhost:686 myhost:389 hishost:5000 whathost:1024
+     *
+ * @param port Port number of the LDAP server that you want to connect to. + * This parameter is ignored for any host in the host + * parameter which includes a colon and port number. + * @exception LDAPException The connection failed. + */ + public void connect(String host, int port) throws LDAPException { + connect( host, port, null, null, false ); + } + + /** + * Connects to the specified host and port and uses the specified DN and + * password to authenticate to the server. If this LDAPConnection object + * represents an open connection, the connection is closed first + * before the new connection is opened. + *

+ * + * For example, the following section of code establishes a connection + * with the LDAP server running on ldap.netscape.com at port 389. The + * example also attempts to authenticate the client as Barbara Jensen. + *

+ * + *

+     * String ldapHost = "ldap.netscape.com";
+     * int ldapPort = 389;
+     * String myDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
+     * String myPW = "hifalutin";
+     * LDAPConnection myConn = new LDAPConnection();
+     * try {
+     *     myConn.connect( ldapHost, ldapPort, myDN, myPW );
+     * } catch ( LDAPException e ) {
+     *     switch( e.getLDAPResultCode() ) {
+     *         case e.NO_SUCH_OBJECT:
+     *             System.out.println( "The specified user does not exist." );
+     *             break;
+     *         case e.INVALID_CREDENTIALS:
+     *             System.out.println( "Invalid password." );
+     *             break;
+     *         default:
+     *             System.out.println( "Error number: " + e.getLDAPResultCode() );
+     *             System.out.println( "Failed to connect to " + ldapHost + " at port " + ldapPort );
+     *             break;
+     *     }
+     *     return;
+     * }
+     * System.out.println( "Connected to " + ldapHost + " at port " + ldapPort );
+     * 
+ * + * @param host Host name of the LDAP server that you want to connect to. + * This value can also be a space-delimited list of hostnames or + * hostnames and port numbers (using the syntax + * hostname:portnumber). Your client application or applet + * will attempt to contact each host in the order you specify until a + * connection is established. For example, you can specify the following + * values for the host argument:
+ *
+     *   myhost
+     *   myhost hishost:389 herhost:5000 whathost
+     *   myhost:686 myhost:389 hishost:5000 whathost:1024
+     *
+ * @param port Port number of the LDAP server that you want to connect to. + * This parameter is ignored for any host in the host + * parameter which includes a colon and port number. + * @param dn Distinguished name used for authentication + * @param passwd Password used for authentication + * @exception LDAPException The connection or authentication failed. + */ + public void connect(String host, int port, String dn, String passwd) + throws LDAPException { + connect(host, port, dn, passwd, true); + } + + private void connect(String host, int port, String dn, String passwd, + boolean doAuthenticate) throws LDAPException { + if (th != null) disconnect (); + if ((host == null) || (host.equals(""))) + throw new LDAPException ( "no host for connection", + LDAPException.PARAM_ERROR ); + + /* Parse the list of hosts */ + m_defaultPort = port; + StringTokenizer st = new StringTokenizer( host ); + m_hostList = new String[st.countTokens()]; + m_portList = new int[st.countTokens()]; + int i = 0; + while( st.hasMoreTokens() ) { + String s = st.nextToken(); + int colon = s.indexOf( ':' ); + if ( colon > 0 ) { + m_hostList[i] = s.substring( 0, colon ); + m_portList[i] = Integer.parseInt( s.substring( colon+1 ) ); + } else { + m_hostList[i] = s; + m_portList[i] = m_defaultPort; + } + i++; + } + + /* Try each possible host until a connection attempt doesn't cause + an exception */ + LDAPException conex = null; + for( i = 0; i < m_hostList.length; i++ ) { + try { + this.host = m_hostList[i]; + this.port = m_portList[i]; + connect (); + conex = null; + break; + } catch ( LDAPException e ) { + conex = e; + } + } + if ( conex != null ) { + /* All connection attempts failed */ + this.host = m_hostList[0]; + this.port = m_defaultPort; + throw conex; + } + + if (doAuthenticate) + authenticate(dn, passwd); + } + + /** + * Connects to the specified host and port and uses the specified DN and + * password to authenticate to the server, with the specified LDAP + * protocol version. If the server does not support the requested + * protocol version, an exception is thrown. If this LDAPConnection + * object represents an open connection, the connection is closed first + * before the new connection is opened. This is equivalent to + * connect(host, port) followed by authenticate(version, dn, passwd).

+ * + * @param version LDAP protocol version requested: currently 2 or 3 + * @param host Contains a hostname or dotted string representing + * the IP address of a host running an LDAP server to connect to. + * Alternatively, it may contain a list of host names, space-delimited. + * Each host name may include a trailing colon and port number. In the + * case where more than one host name is specified, each host name in + * turn will be contacted until a connection can be established.

+ * + *

+     *   Examples:
+     *      "directory.knowledge.com"
+     *      "199.254.1.2"
+     *      "directory.knowledge.com:1050 people.catalog.com 199.254.1.2"
+     * 
+ *

+ * @param port Contains the TCP or UDP port number to connect to or contact. + * The default LDAP port is 389. "port" is ignored for any host name which + * includes a colon and port number. + * @param dn If non-null and non-empty, specifies that the connection and + * all operations through it should be authenticated with dn as the + * distinguished name. + * @param passwd If non-null and non-empty, specifies that the connection and + * all operations through it should be authenticated with dn as the + * distinguished name and passwd as password. + * @exception LDAPException The connection or authentication failed. + */ + public void connect(int version, String host, int port, String dn, + String passwd) throws LDAPException { + + setProtocolVersion(version); + connect(host, port, dn, passwd); + } + + /** + * Internal routine to connect with internal params + * @exception LDAPException failed to connect + */ + private synchronized void connect () throws LDAPException { + if (th != null) return; + + if (host == null || port < 0) + throw new LDAPException ( "no connection parameters", + LDAPException.PARAM_ERROR ); + + th = getNewThread(host, port, m_factory, m_cache); + } + + private synchronized LDAPConnThread getNewThread(String host, int port, + LDAPSocketFactory factory, LDAPCache cache) throws LDAPException { + + LDAPConnThread newThread = null; + Vector v = null; + + synchronized(m_threadConnTable) { + + Enumeration keys = m_threadConnTable.keys(); + boolean connExist = false; + + // transverse each thread + while (keys.hasMoreElements()) { + LDAPConnThread connThread = (LDAPConnThread)keys.nextElement(); + Vector connVector = (Vector)m_threadConnTable.get(connThread); + Enumeration enumv = connVector.elements(); + + // transverse through each LDAPConnection under the same thread + while (enumv.hasMoreElements()) { + LDAPConnection conn = (LDAPConnection)enumv.nextElement(); + + // this is not the brand new connection + if (conn.equals(this)) { + connExist = true; + + if (!connThread.isAlive()) { + // need to move all the LDAPConnections under the dead thread + // to the new thread + try { + newThread = new LDAPConnThread(host, port, factory, cache); + v = (Vector)m_threadConnTable.remove(connThread); + break; + } catch (Exception e) { + throw new LDAPException ("unable to establish connection", + LDAPException.UNAVAILABLE); + } + } + break; + } + } + + if (connExist) break; + } + + // if this connection is new or the corresponding thread for the current + // connection is dead + if (!connExist) { + try { + newThread = new LDAPConnThread(host, port, factory, cache); + v = new Vector(); + v.addElement(this); + } catch (Exception e) { + throw new LDAPException ("unable to establish connection", + LDAPException.UNAVAILABLE); + } + } + + // add new thread to the table + if (newThread != null) { + m_threadConnTable.put(newThread, v); + for (int i=0, n=v.size(); i + * + * For example, the following section of code authenticates the + * client as Barbara Jensen. The code assumes that the client + * has already established a connection with an LDAP server. + *

+ * + *

+     * String myDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
+     * String myPW = "hifalutin";
+     * try {
+     *     myConn.authenticate( myDN, myPW );
+     * } catch ( LDAPException e ) {
+     *     switch( e.getLDAPResultCode() ) {
+     *         case e.NO_SUCH_OBJECT:
+     *             System.out.println( "The specified user does not exist." );
+     *             break;
+     *         case e.INVALID_CREDENTIALS:
+     *             System.out.println( "Invalid password." );
+     *             break;
+     *         default:
+     *             System.out.println( "Error number: " + e.getLDAPResultCode() );
+     *             System.out.println( "Failed to authentice as " + myDN );
+     *             break;
+     *     }
+     *     return;
+     * }
+     * System.out.println( "Authenticated as " + myDN );
+     * 
+ * + * @param dn Distinguished name used for authentication. + * @param passwd Password used for authentication. + * @exception LDAPException Failed to authenticate to the LDAP server. + */ + public void authenticate(String dn, String passwd) throws LDAPException { + authenticate(protocolVersion, dn, passwd); + } + + /** + * Authenticates to the LDAP server (that you are currently + * connected to) using the specified name and password, and + * requesting that the server use at least the specified + * protocol version. If the server doesn't support that + * level, an LDAPException is thrown with the error code + * PROTOCOL_ERROR. + * + * @param version Required LDAP protocol version. + * @param dn Distinguished name used for authentication. + * @param passwd Password used for authentication. + * @exception LDAPException Failed to authenticate to the LDAP server. + */ + public void authenticate(int version, String dn, String passwd) + throws LDAPException { + prevBoundDN = boundDN; + prevBoundPasswd = boundPasswd; + boundDN = dn; + boundPasswd = passwd; + + if ((prevBoundDN == null) || (prevBoundPasswd == null)) + m_anonymousBound = true; + else + m_anonymousBound = false; + + bind (version, true); + } + + /** + * Authenticates to the LDAP server (that the object is currently + * connected to) using the specified name and a specified SASL mechanism + * or set of mechanisms. If the requested SASL mechanism is not + * available, an exception is thrown. If the object has been + * disconnected from an LDAP server, this method attempts to reconnect + * to the server. If the object had already authenticated, the old + * authentication is discarded. + * + * @param dn If non-null and non-empty, specifies that the connection and + * all operations through it should be authenticated with dn as the + * distinguished name. + * @param mechanism A single mechanism name, e.g. "GSSAPI". + * @param packageName A package from which to instantiate the Mechanism + * Driver, e.g. "myclasses.SASL.mechanisms". If null, a system default + * is used. + * @param getter A class which may be called by the Mechanism Driver to + * obtain additional information required. + * @exception LDAPException Failed to authenticate to the LDAP server. + */ + public void authenticate(String dn, String mechanism, String packageName, + Properties props, Object getter) throws LDAPException { + + try { + Object[] args = new Object[2]; + args[0] = mechanism; + args[1] = packageName; + String[] argNames = new String[2]; + argNames[0] = "java.lang.String"; + argNames[1] = "java.lang.String"; + + // Get a mechanism driver + m_mechanismDriver = invokeMethod(null, + "com.netscape.sasl.SASLMechanismFactory", "getMechanismDriver", + args, argNames); + + } catch (Exception e) { + throw new LDAPException(e.toString(), LDAPException.OTHER); + } + + m_securityProperties = props; + m_clientCB = getter; + boundDN = dn; + saslBind(true); + } + + /** + * Authenticates to the LDAP server (that the object is currently + * connected to) using the specified name and a specified SASL mechanism + * or set of mechanisms. If the requested SASL mechanism is not + * available, an exception is thrown. If the object has been + * disconnected from an LDAP server, this method attempts to reconnect + * to the server. If the object had already authenticated, the old + * authentication is discarded. + * + * @param dn If non-null and non-empty, specifies that the connection and + * all operations through it should be authenticated with dn as the + * distinguished name. + * @param mechanisms A list of acceptable mechanisms. The first one + * for which a Mechanism Driver can be instantiated is returned. + * @param packageName A package from which to instantiate the Mechanism + * Driver, e.g. "myclasses.SASL.mechanisms". If null, a system default + * is used. + * @param getter A class which may be called by the Mechanism Driver to + * obtain additional information required. + * @exception LDAPException Failed to authenticate to the LDAP server. + */ + public void authenticate(String dn, String[] mechanisms, String packageName, + Properties props, Object getter) throws LDAPException { + + for (int i=0; i 1) { + disconnect(); + connect(); + } + } + + if ((bound && rebind) || (!bound)) { + try { + // Get the initial request to start authentication + Object[] arg1 = new Object[5]; + arg1[0] = boundDN; + arg1[1] = "LDAP"; + arg1[2] = null; + arg1[3] = m_securityProperties; + arg1[4] = m_clientCB; + + String[] argNames = new String[5]; + argNames[0] = "java.lang.String"; + argNames[1] = "java.lang.String"; + argNames[2] = "java.lang.String"; + argNames[3] = "java.util.Properties"; + argNames[4] = "com.netscape.sasl.SASLClientCB"; + + byte[] outVals = (byte[])invokeMethod(m_mechanismDriver, + m_mechanismDriver.getClass().getName(), + "startAuthentication", arg1, argNames); + + + int resultCode = LDAPException.SASL_BIND_IN_PROGRESS; + JDAPBindResponse response = null; + while (!checkForSASLBindCompletion(resultCode)) { + response = saslBind(outVals); + resultCode = response.getResultCode(); + String challenge = response.getCredentials(); + byte[] b = challenge.getBytes(); + + Object[] arg2 = new Object[1]; + arg2[0] = b; + String[] arg2Names = new String[1]; + arg2Names[0] = "[B"; //class name for byte array + + outVals = (byte[])invokeMethod(m_mechanismDriver, + m_mechanismDriver.getClass().getName(), + "evaluateResponse", arg2, arg2Names); + } + + // Make sure authentication REALLY is complete + Boolean bool = (Boolean)invokeMethod(m_mechanismDriver, + m_mechanismDriver.getClass().getName(), + "isComplete", null, null); + if (!bool.booleanValue()) { + // Authentication session hijacked! + throw new LDAPException("The server indicates that " + + "authentication is successful, but the SASL driver " + + "indicates that authentication is not yet done.", + LDAPException.OTHER); + } + + m_security = invokeMethod(m_mechanismDriver, + m_mechanismDriver.getClass().getName(), + "getSecurityLayer", null, null); + th.setSecurityLayer(m_security); + updateThreadConnTable(); + } catch (Exception e) { + throw new LDAPException(e.toString(), LDAPException.OTHER); + } + } + } + + private Object invokeMethod(Object obj, String packageName, + String methodName, Object[] args, String[] argNames) + throws LDAPException { + try { + java.lang.reflect.Method m = getMethod(packageName, methodName, + argNames); + if (m != null) { + return (m.invoke(obj, args)); + } + } catch (Exception e) { + throw new LDAPException("Invoking "+methodName+": "+ + e.toString(), LDAPException.PARAM_ERROR); + } + + return null; + } + + private java.lang.reflect.Method getMethod(String packageName, + String methodName, String[] args) throws LDAPException { + try { + java.lang.reflect.Method method = null; + String suffix = ""; + if (args != null) + for (int i=0; i 1) { + disconnect(); + connect(); + } + + // if the connection is still intact and no rebind request + if (bound && !rebind) + return; + + // if the connection was lost and did not have any kind of bind + // operation and the current one does not request any bind operation (ie, + // no authenticate has been called) + if (!m_anonymousBound && + ((boundDN == null) || (boundPasswd == null)) && + !rebind) + return; + + if (bound && rebind) { + if (protocolVersion == version) { + if (m_anonymousBound && ((boundDN == null) || (boundPasswd == null))) + return; + + if (!m_anonymousBound && (boundDN != null) && (boundPasswd != null) && + boundDN.equals(prevBoundDN) && + boundPasswd.equals(prevBoundPasswd)) + return; + } + + // if get to here, means that we need to do rebind since previous and + // current credentials are not the same. + // if the current connection is the only connection for the th thread, + // then reuse this current connection. otherwise, disconnect the current + // one (ie, detach from the current th) and reconnect again (ie, have + // a new th). + if (th.getClientCount() > 1) { + disconnect(); + connect(); + } + } + + protocolVersion = version; + + LDAPResponseListener myListener = getResponseListener (); + JDAPMessage response; + try { + sendRequest(new JDAPBindRequest(protocolVersion, boundDN, boundPasswd), + myListener, defaultConstraints); + response = myListener.getResponse(); + checkMsg(response); + } finally { + releaseResponseListener(myListener); + } + + updateThreadConnTable(); + } + + private void updateThreadConnTable() { + synchronized(m_threadConnTable) { + if (m_threadConnTable.containsKey(th)) { + Vector v = (Vector)m_threadConnTable.get(th); + for (int i=0, n=v.size(); iconnect. + * @exception LDAPException Failed to disconnect from the LDAP server. + * @see netscape.ldap.LDAPConnection#connect(java.lang.String, int) + * @see netscape.ldap.LDAPConnection#connect(java.lang.String, int, java.lang.String, java.lang.String) + */ + public synchronized void disconnect() throws LDAPException { + if ((th == null) || (!th.isAlive())) + throw new LDAPException ( "unable to disconnect() without connecting", + LDAPException.OTHER ); + if (m_cache != null) { + m_cache.cleanup(); + m_cache = null; + } + deleteThreadConnEntry(); + deregisterConnection(); + } + + private void deleteThreadConnEntry() { + synchronized (m_threadConnTable) { + Enumeration keys = m_threadConnTable.keys(); + while (keys.hasMoreElements()) { + LDAPConnThread connThread = (LDAPConnThread)keys.nextElement(); + Vector connVector = (Vector)m_threadConnTable.get(connThread); + Enumeration enumv = connVector.elements(); + while (enumv.hasMoreElements()) { + LDAPConnection c = (LDAPConnection)enumv.nextElement(); + if (c.equals(this)) { + connVector.removeElement(c); + if (connVector.size() == 0) + m_threadConnTable.remove(connThread); + return; + } + } + } + } + } + + /** + * Decrement the reference count for the connection + */ + synchronized void deregisterConnection() { + th.deregister(this); + th = null; + bound = false; + } + + /** + * Reads the entry for the specified distiguished name (DN) and retrieves all + * attributes for the entry. + *

+ * + * For example, the following section of code reads the entry for + * Barbara Jensen and retrieves all attributes for that entry. + *

+ * + *

+     * String findDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
+     * LDAPEntry foundEntry = null;
+     * try {
+     *     foundEntry = myConn.read( findDN );
+     * } catch ( LDAPException e ) {
+     *     switch( e.getLDAPResultCode() ) {
+     *         case e.NO_SUCH_OBJECT:
+     *             System.out.println( "The specified entry does not exist." );
+     *             break;
+     *         case e.LDAP_PARTIAL_RESULTS:
+     *             System.out.println( "Entry served by a different LDAP server." );
+     *             break;
+     *         case e.INSUFFICIENT_ACCESS_RIGHTS:
+     *             System.out.println( "You do not have the access rights to perform this operation." );
+     *             break;
+     *         default:
+     *             System.out.println( "Error number: " + e.getLDAPResultCode() );
+     *             System.out.println( "Could not read the specified entry." );
+     *             break;
+     *     }
+     *     return;
+     * }
+     * System.out.println( "Found the specified entry." );
+     * 
+ * + * @param DN Distinguished name of the entry that you want to retrieve. + * @exception LDAPException Failed to find or read the specified entry + * from the directory. + * @return LDAPEntry Returns the specified entry or raises an exception + * if the entry is not found. + */ + public LDAPEntry read (String DN) throws LDAPException { + return read (DN, null, defaultConstraints); + } + + /** + * Reads the entry for the specified distiguished name (DN) and retrieves all + * attributes for the entry. This method allows the user to specify the + * preferences for the read operation. + *

+ * + * For example, the following section of code reads the entry for + * Barbara Jensen and retrieves all attributes for that entry. + *

+ * + *

+     * String findDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
+     * LDAPEntry foundEntry = null;
+     * try {
+     *     foundEntry = myConn.read( findDN );
+     * } catch ( LDAPException e ) {
+     *     switch( e.getLDAPResultCode() ) {
+     *         case e.NO_SUCH_OBJECT:
+     *             System.out.println( "The specified entry does not exist." );
+     *             break;
+     *         case e.LDAP_PARTIAL_RESULTS:
+     *             System.out.println( "Entry served by a different LDAP server." );
+     *             break;
+     *         case e.INSUFFICIENT_ACCESS_RIGHTS:
+     *             System.out.println( "You do not have the access rights to perform this operation." );
+     *             break;
+     *         default:
+     *             System.out.println( "Error number: " + e.getLDAPResultCode() );
+     *             System.out.println( "Could not read the specified entry." );
+     *             break;
+     *     }
+     *     return;
+     * }
+     * System.out.println( "Found the specified entry." );
+     * 
+ * + * @param DN Distinguished name of the entry that you want to retrieve. + * @param cons Preferences for the read operation. + * @exception LDAPException Failed to find or read the specified entry + * from the directory. + * @return LDAPEntry Returns the specified entry or raises an exception + * if the entry is not found. + */ + public LDAPEntry read (String DN, LDAPSearchConstraints cons) + throws LDAPException { + return read (DN, null, cons); + } + + /** + * Reads the entry for the specified distinguished name (DN) and + * retrieves only the specified attributes from the entry. + *

+ * + * For example, the following section of code reads the entry for + * Barbara Jensen and retrieves only the cn and + * sn attributes. + * The example prints out all attributes that have been retrieved + * (the two specified attributes). + *

+ * + *

+     * String findDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
+     * LDAPEntry foundEntry = null;
+     * String getAttrs[] = { "cn", "sn" };
+     * try {
+     *      foundEntry = myConn.read( findDN, getAttrs );
+     * } catch ( LDAPException e ) {
+     *      switch( e.getLDAPResultCode() ) {
+     *           case e.NO_SUCH_OBJECT:
+     *               System.out.println( "The specified entry does not exist." );
+     *               break;
+     *           case e.LDAP_PARTIAL_RESULTS:
+     *               System.out.println( "Entry served by a different LDAP server." );
+     *               break;
+     *           case e.INSUFFICIENT_ACCESS_RIGHTS:
+     *               System.out.println( "You do not have the access " +
+     *                                   "rights to perform this operation." );
+     *               break;
+     *           default:
+     *               System.out.println( "Error number: " + e.getLDAPResultCode() );
+     *               System.out.println( "Could not read the specified entry." );
+     *               break;
+     *      }
+     *      return;
+     * }
+     *
+     * LDAPAttributeSet foundAttrs = foundEntry.getAttributeSet();
+     * int size = foundAttrs.size();
+     * Enumeration enumAttrs = foundAttrs.getAttributes();
+     * System.out.println( "Attributes: " );
+     *
+     * while ( enumAttrs.hasMoreElements() ) {
+     *      LDAPAttribute anAttr = ( LDAPAttribute )enumAttrs.nextElement();
+     *      String attrName = anAttr.getName();
+     *      System.out.println( "\t" + attrName );
+     *      Enumeration enumVals = anAttr.getStringValues();
+     *      while ( enumVals.hasMoreElements() ) {
+     *           String aVal = ( String )enumVals.nextElement();
+     *           System.out.println( "\t\t" + aVal );
+     *      }
+     * }
+     * 
+ * + * @param DN Distinguished name of the entry that you want to retrieve. + * @param attrs Names of attributes that you want to retrieve. + * @return LDAPEntry Returns the specified entry (or raises an + * exception if the entry is not found). + * @exception LDAPException Failed to read the specified entry from + * the directory. + */ + public LDAPEntry read (String DN, String attrs[]) throws LDAPException { + return read(DN, attrs, defaultConstraints); + } + + public LDAPEntry read (String DN, String attrs[], + LDAPSearchConstraints cons) throws LDAPException { + LDAPSearchResults results = search (DN, LDAPv2.SCOPE_BASE, + defaultFilter, attrs, false, cons); + if (results == null) + return null; + return results.next (); + } + + /** + * Reads the entry specified by the LDAP URL.

+ * + * When you call this method, a new connection is created automatically, + * using the host and port specified in the URL. After finding the entry, + * the method closes this connection (in other words, it disconnects from + * the LDAP server).

+ * + * If the URL specifies a filter and scope, these are not used. + * Of the information specified in the URL, this method only uses + * the LDAP host name and port number, the base distinguished name (DN), + * and the list of attributes to return.

+ * + * The method returns the entry specified by the base DN.

+ * + * (Note: If you want to search for more than one entry, use the + * search( LDAPUrl ) method instead.)

+ * + * For example, the following section of code reads the entry specified + * by the LDAP URL. + *

+ * + *

+     * String flatURL = "ldap://alway.mcom.com:3890/cn=Barbara Jenson,ou=Product Development,o=Ace Industry,c=US?cn,sn,mail";
+     * LDAPUrl myURL;
+     * try {
+     *    myURL = new LDAPUrl( flatURL );
+     * } catch ( java.net.MalformedURLException e ) {
+     *    System.out.println( "BAD URL!!!  BAD, BAD, BAD URL!!!" );
+     *    return;
+     * }
+     * LDAPEntry myEntry = null;
+     * try {
+     *    myEntry = myConn.read( myURL );
+     * } catch ( LDAPException e ) {
+     *    int errCode = e.getLDAPResultCode();
+     *    switch( errCode ) {
+     *        case ( e.NO_SUCH_OBJECT ):
+     *            System.out.println( "The specified entry " + myDN +
+     *                                " does not exist in the directory." );
+     *            return;
+     *        default:
+     *            System.out.println( "An internal error occurred." );
+     *            return;
+     *    }
+     * }
+     * 
+ * + * @param toGet LDAP URL specifying the entry that you want to read. + * @return LDAPEntry Returns the entry specified by the URL (or raises + * an exception if the entry is not found). + * @exception LDAPException Failed to read the specified entry from + * the directory. + * @see netscape.ldap.LDAPUrl + * @see netscape.ldap.LDAPConnection#search(netscape.ldap.LDAPUrl) + */ + public static LDAPEntry read (LDAPUrl toGet) throws LDAPException { + String host = toGet.getHost (); + int port = toGet.getPort(); + + if (host == null) + throw new LDAPException ( "no host for connection", + LDAPException.PARAM_ERROR ); + + String[] attributes = toGet.getAttributeArray (); + String DN = toGet.getDN(); + LDAPEntry returnValue; + + LDAPConnection connection = new LDAPConnection (); + connection.connect (host, port); + + returnValue = connection.read (DN, attributes); + connection.disconnect (); + + return returnValue; + } + + /** + * Performs the search specified by the LDAP URL.

+ * + * For example, the following section of code searches for all entries under + * the ou=Product Development,o=Ace Industry,c=US subtree of a + * directory. The example gets and prints the mail attribute for each entry + * found.

+ * + *

+     * String flatURL = "ldap://alway.mcom.com:3890/ou=Product Development,o=Ace Industry,c=US?mail?sub?objectclass=*";
+     * LDAPUrl myURL;
+     * try {
+     *    myURL = new LDAPUrl( flatURL );
+     * } catch ( java.net.MalformedURLException e ) {
+     *    System.out.println( "Incorrect URL syntax." );
+     *    return;
+     * }
+     *
+     * LDAPSearchResults myResults = null;
+     * try {
+     *    myResults = myConn.search( myURL );
+     * } catch ( LDAPException e ) {
+     *    int errCode = e.getLDAPResultCode();
+     *    System.out.println( "LDAPException: return code:" + errCode );
+     *    return;
+     * }
+     *
+     * while ( myResults.hasMoreElements() ) {
+     *    LDAPEntry myEntry = myResults.next();
+     *    String nextDN = myEntry.getDN();
+     *    System.out.println( nextDN );
+     *    LDAPAttributeSet entryAttrs = myEntry.getAttributeSet();
+     *    Enumeration attrsInSet = entryAttrs.getAttributes();
+     *    while ( attrsInSet.hasMoreElements() ) {
+     *        LDAPAttribute nextAttr = (LDAPAttribute)attrsInSet.nextElement();
+     *        String attrName = nextAttr.getName();
+     *        System.out.print( "\t" + attrName + ": " );
+     *        Enumeration valsInAttr = nextAttr.getStringValues();
+     *        while ( valsInAttr.hasMoreElements() ) {
+     *            String nextValue = (String)valsInAttr.nextElement();
+     *            System.out.println( nextValue );
+     *        }
+     *    }
+     * }
+     * 
+ *

+ * + * To abandon the search, use the abandon method. + * + * @param toGet LDAP URL representing the search that you want to perform. + * @return LDAPSearchResults The results of the search as an enumeration. + * @exception LDAPException Failed to complete the search specified by + * the LDAP URL. + * @see netscape.ldap.LDAPUrl + * @see netscape.ldap.LDAPSearchResults + * @see netscape.ldap.LDAPConnection#abandon(netscape.ldap.LDAPSearchResults) + */ + public static LDAPSearchResults search (LDAPUrl toGet) throws LDAPException { + return search (toGet, null); + } + + /** + * Performs the search specified by the LDAP URL. This method also + * allows you to specify constraints for the search (such as the + * maximum number of entries to find or the + * maximum time to wait for search results).

+ * + * As part of the search constraints, you can specify whether or not you + * want the results delivered all at once or in smaller batches. + * If you specify that you want the results delivered in smaller + * batches, each iteration blocks until the next batch of results is + * returned.

+ * + * For example, the following section of code retrieves the first 5 + * matching entries for the search specified by the LDAP URL. The + * example accomplishes this by creating a new set of search + * constraints where the maximum number of search results is 5.

+ * + *

+     * LDAPSearchConstraints mySearchConstraints = myConn.getSearchConstraints();
+     * mySearchConstraints.setMaxResults( 5 );
+     * String flatURL = "ldap://alway.mcom.com:3890/ou=Product Development,o=Ace Industry,c=US?mail?sub?objectclass=*";
+     * LDAPUrl myURL;
+     * try {
+     *    myURL = new LDAPUrl( flatURL );
+     * } catch ( java.net.MalformedURLException e ) {
+     *    System.out.println( "Incorrect URL syntax." );
+     *    return;
+     * }
+     * LDAPSearchResults myResults = null;
+     * try {
+     *    myResults = myConn.search( myURL, mySearchConstraints );
+     * } catch ( LDAPException e ) {
+     *    int errCode = e.getLDAPResultCode();
+     *    System.out.println( "LDAPException: return code:" + errCode );
+     *    return;
+     * }
+     * 
+ *

+ * + * To abandon the search, use the abandon method. + * + * @param toGet LDAP URL representing the search that you want to run. + * @param cons Constraints specific to the search. + * @return LDAPSearchResults The results of the search as an enumeration. + * @exception LDAPException Failed to complete the search specified + * by the LDAP URL. + * @see netscape.ldap.LDAPUrl + * @see netscape.ldap.LDAPSearchResults + * @see netscape.ldap.LDAPConnection#abandon(netscape.ldap.LDAPSearchResults) + */ + public static LDAPSearchResults search (LDAPUrl toGet, + LDAPSearchConstraints cons) throws LDAPException { + String host = toGet.getHost (); + int port = toGet.getPort(); + + if (host == null) + throw new LDAPException ( "no host for connection", + LDAPException.PARAM_ERROR ); + + String[] attributes = toGet.getAttributeArray (); + String DN = toGet.getDN(); + String filter = toGet.getFilter(); + if (filter == null) { + filter = "(objectClass=*)"; + } + int scope = toGet.getScope (); + + LDAPConnection connection = new LDAPConnection (); + connection.connect (host, port); + + LDAPSearchResults results; + if (cons != null) + results = connection.search (DN, scope, filter, attributes, false, cons); + else + results = connection.search (DN, scope, filter, attributes, false); + + results.closeOnCompletion(connection); + + return results; + } + + /** + * Performs the search specified by the criteria that you enter.

+ * + * For example, the following section of code searches for all entries under + * the ou=Product Development,o=Ace Industry,c=US subtree of a + * directory. The example gets and prints the mail attribute for each entry + * found.

+ * + *

+     * String myBaseDN = "ou=Product Development,o=Ace Industry,c=US";
+     * String myFilter="(objectclass=*)";
+     * String[] myAttrs = { "mail" };
+     *
+     * LDAPSearchResults myResults = null;
+     * try {
+     *    myResults = myConn.search( myBaseDN, LDAPv2.SCOPE_SUB, myFilter, myAttrs, false );
+     * } catch ( LDAPException e ) {
+     *    int errCode = e.getLDAPResultCode();
+     *    System.out.println( "LDAPException: return code:" + errCode );
+     *    return;
+     * }
+     *
+     * while ( myResults.hasMoreElements() ) {
+     *    LDAPEntry myEntry = myResults.next();
+     *    String nextDN = myEntry.getDN();
+     *    System.out.println( nextDN );
+     *    LDAPAttributeSet entryAttrs = myEntry.getAttributeSet();
+     *    Enumeration attrsInSet = entryAttrs.getAttributes();
+     *    while ( attrsInSet.hasMoreElements() ) {
+     *        LDAPAttribute nextAttr = (LDAPAttribute)attrsInSet.nextElement();
+     *        String attrName = nextAttr.getName();
+     *        System.out.println( "\t" + attrName + ":" );
+     *        Enumeration valsInAttr = nextAttr.getStringValues();
+     *        while ( valsInAttr.hasMoreElements() ) {
+     *            String nextValue = (String)valsInAttr.nextElement();
+     *            System.out.println( "\t\t" + nextValue );
+     *        }
+     *    }
+     * }
+     * 
+ *

+ * + * To abandon the search, use the abandon method. + * + * @param base The base distinguished name to search from + * @param scope The scope of the entries to search. You can specify one + * of the following:

+ *

    + *
  • LDAPv2.SCOPE_BASE (search only the base DN)

    + *

  • LDAPv2.SCOPE_ONE + * (search only entries under the base DN)

    + *

  • LDAPv2.SCOPE_SUB + * (search the base DN and all entries within its subtree)

    + *

+ *

+ * @param filter Search filter specifying the search criteria. + * @param attrs List of attributes that you want returned in the + * search results. + * @param attrsOnly If true, returns the names but not the values of the + * attributes found. If false, returns the names and values for + * attributes found + * @return LDAPSearchResults The results of the search as an enumeration. + * @exception LDAPException Failed to complete the specified search. + * @see netscape.ldap.LDAPConnection#abandon(netscape.ldap.LDAPSearchResults) + */ + public LDAPSearchResults search( String base, int scope, String filter, + String[] attrs, boolean attrsOnly ) throws LDAPException { + return search( base, scope, filter, attrs, attrsOnly, defaultConstraints); + } + + /** + * Performs the search specified by the criteria that you enter. + * This method also allows you to specify constraints for the search + * (such as the maximum number of entries to find or the + * maximum time to wait for search results).

+ * + * As part of the search constraints, you can specify whether or not + * you want the + * results delivered all at once or in smaller batches. If you + * specify that you want the results delivered in smaller batches, + * each iteration blocks until the + * next batch of results is returned.

+ * + * For example, the following section of code retrieves the first 5 entries + * matching the specified search criteria. The example accomplishes + * this by creating a new set of search constraints where the maximum + * number of search results is 5.

+ * + *

+     * String myBaseDN = "ou=Product Development,o=Ace Industry,c=US";
+     * String myFilter="(objectclass=*)";
+     * String[] myAttrs = { "mail" };
+     * LDAPSearchConstraints mySearchConstraints = myConn.getSearchConstraints();
+     * mySearchConstraints.setMaxResults( 5 );
+     *
+     * LDAPSearchResults myResults = null;
+     * try {
+     *    myResults = myConn.search( myBaseDN, LDAPv2.SCOPE_SUB, myFilter, myAttrs, false, mySearchConstraints );
+     * } catch ( LDAPException e ) {
+     *    int errCode = e.getLDAPResultCode();
+     *    System.out.println( "LDAPException: return code:" + errCode );
+     *    return;
+     * }
+     * 
+ *

+ * + * To abandon the search, use the abandon method. + * + * @param base The base distinguished name to search from + * @param scope The scope of the entries to search. You can specify one + * of the following:

+ *

    + *
  • LDAPv2.SCOPE_BASE (search only the base DN)

    + *

  • LDAPv2.SCOPE_ONE + * (search only entries under the base DN)

    + *

  • LDAPv2.SCOPE_SUB + * (search the base DN and all entries within its subtree)

    + *

+ *

+ * @param filter Search filter specifying the search criteria. + * @param attrs List of attributes that you want returned in the search + * results. + * @param cons Constraints specific to this search (for example, the + * maximum number + * of entries to return). + * @param attrsOnly If true, returns the names but not the values of the + * attributes found. If false, returns the names and values for + * attributes found + * @return LDAPSearchResults The results of the search as an enumeration. + * @exception LDAPException Failed to complete the specified search. + * @see netscape.ldap.LDAPConnection#abandon(netscape.ldap.LDAPSearchResults) + */ + public LDAPSearchResults search( String base, int scope, String filter, + String[] attrs, boolean attrsOnly, LDAPSearchConstraints cons ) + throws LDAPException { + + if (cons == null) + cons = defaultConstraints; + + LDAPSearchResults returnValue = new LDAPSearchResults(this, + cons, base, scope, filter, attrs, attrsOnly); + Vector cacheValue = null; + Long key = null; + boolean isKeyValid = true; + + try { + // get entry from cache which is a vector of JDAPMessages + if (m_cache != null) + { + // create key for cache entry using search arguments + key = m_cache.createKey(host, port, base, filter, scope, attrs, boundDN, cons); + + cacheValue = (Vector)m_cache.getEntry(key); + + if (cacheValue != null) + return (new LDAPSearchResults(cacheValue, this, cons, base, scope, + filter, attrs, attrsOnly)); + } + } catch (LDAPException e) { + isKeyValid = false; + printDebug("Exception: "+e); + } + + bind(); + + LDAPSearchListener myListener = getSearchListener (); + int deref = cons.getDereference(); + + JDAPSearchRequest request = new JDAPSearchRequest (base, + scope, deref, cons.getMaxResults(), cons.getTimeLimit(), + attrsOnly, filter, attrs); + + synchronized(myListener) { + boolean success = false; + try { + sendRequest (request, myListener, cons); + success = true; + } finally { + if (!success) + releaseSearchListener (myListener); + } + + // if using cache, then need to add the key to the search listener. + // The search listener retrieves the key and then add the key and + // a vector of results to the hashtable. + if ((m_cache != null) && (isKeyValid)) + myListener.setKey(key); + } + + + /* Synchronous search if all requested at once */ + if ( cons.getBatchSize() == 0 ) { + try { + /* Block until all results are in */ + JDAPMessage response = myListener.getResponse (); + Enumeration results = myListener.getSearchResults (); + + checkSearchMsg(returnValue, response, cons, base, scope, filter, + attrs, attrsOnly); + + while (results.hasMoreElements ()) { + JDAPMessage msg = (JDAPMessage)results.nextElement(); + + checkSearchMsg(returnValue, msg, cons, base, scope, filter, attrs, + attrsOnly); + } + } catch (LDAPException ee) { + throw ee; + } finally { + releaseSearchListener (myListener); + } + } else { + /* + * Asynchronous to retrieve one at a time, check to make sure + * the search didn't fail + */ + JDAPMessage firstResult = myListener.nextResult (); + if (firstResult == null) { + firstResult = myListener.getResponse (); + + try { + checkSearchMsg(returnValue, firstResult, cons, base, scope, + filter, attrs, attrsOnly); + } finally { + releaseSearchListener (myListener); + } + } else { + checkSearchMsg(returnValue, firstResult, cons, base, + scope, filter, attrs, attrsOnly); + + LDAPControl[] controls = (LDAPControl[])getOption(LDAPv3.SERVERCONTROLS, cons); + + for (int i=0; (controls != null) && (itrue if the entry has the value. Returns + * false if the entry does not have the value or the + * attribute. To represent the value that you want compared, you need + * to create an LDAPAttribute object.

+ * + * Note that only string values can be compared.

+ * + * For example, the following section of code checks to see if the entry + * "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US" contains + * the attribute "mail" with the value "bjensen@aceindustry.com". + * + *

+     * ...
+     * LDAPConnection myConn = new LDAPConnection();
+     * ...
+     * String myDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
+     * String nameOfAttr = "mail";
+     * String valOfAttr = "bjensen@aceindustry.com";
+     * LDAPAttribute cmpThisAttr = new LDAPAttribute( nameOfAttr, valOfAttr );
+     * boolean hasValue = myConn.compare( myDN, cmpThisAttr );
+     * if ( hasValue ) {
+     *     System.out.println( "Attribute and value found in entry." );
+     * } else {
+     *     System.out.println( "Attribute and value not found in entry." );
+     * }
+     * ...
+ * + * @param DN The distinguished name of the entry that you want to use in + * the comparison. + * @param attr The attribute that you want to compare against the entry. + * (The method checks to see if the entry has an attribute with the same name + * and value as this attribute.) + * @return true if the entry contains the specified attribute and value. + * @exception LDAPException Failed to perform the comparison. + * @see netscape.ldap.LDAPAttribute + */ + public boolean compare( String DN, LDAPAttribute attr ) + throws LDAPException { + return compare(DN, attr, defaultConstraints); + } + + public boolean compare( String DN, LDAPAttribute attr, + LDAPSearchConstraints cons) throws LDAPException { + bind(); + + LDAPResponseListener myListener = getResponseListener (); + Enumeration en = attr.getByteValues(); + byte val[] = (byte[])en.nextElement(); + String debug = ""; + try { + debug = new String(val, "UTF8"); + } catch(Throwable x) + {} + + JDAPAVA ass = new JDAPAVA(attr.getName(), debug); + //JDAPAVA ass = new JDAPAVA(attr.getName(), new String(val,0)); + + JDAPMessage response; + try { + sendRequest (new JDAPCompareRequest (DN, ass), myListener, cons); + response = myListener.getResponse (); + + int resultCode = ((JDAPResult)response.getProtocolOp()).getResultCode(); + if (resultCode == JDAPResult.COMPARE_FALSE) + return false; + if (resultCode == JDAPResult.COMPARE_TRUE) + return true; + + checkMsg (response); + + } catch (LDAPReferralException e) { + //boolean res[] = new boolean[1]; + Vector res = new Vector(); + performReferrals(e, cons, JDAPProtocolOp.COMPARE_REQUEST, + DN, 0, null, null, false, null, null, attr, res); + boolean bool = false; + if (res.size() > 0) + bool = ((Boolean)res.elementAt(0)).booleanValue(); + res = null; + return bool; + } finally { + releaseResponseListener (myListener); + } + return false; /* this should never be executed */ + } + + /** + * Adds an entry to the directory.

+ * + * Before using this method, you need to create an + * LDAPEntry object and use it to specify the + * distinguished name and attributes of the new entry. Make sure + * to specify values for all required attributes in the + * entry. If all required attributes are not specified and the LDAP server + * checks the entry against the schema, an LDAPException + * may be thrown (where the LDAP result code is + * OBJECT_CLASS_VIOLATION).

+ * + * For example, the following section of code creates an + * LDAPEntry object for a new entry and uses the object + * to add the new entry to the directory. Because the definition of + * the LDAP inetOrgPerson class specifies that the + * cn, sn, and objectclass + * attributes are required, these attributes are specified as part + * of the new entry. (mail is not required but is shown + * here as an example of specifying additional attributes.) + *

+ * + *

+     * ...
+     * String myDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
+     *
+     * LDAPAttribute attr1 = new LDAPAttribute( "cn", "Barbara Jensen" );
+     * LDAPAttribute attr2 = new LDAPAttribute( "sn", "Jensen" );
+     * LDAPAttribute attr3 = new LDAPAttribute( "objectclass", "top" );
+     * LDAPAttribute attr4 = new LDAPAttribute( "objectclass", "person" );
+     * LDAPAttribute attr5 = new LDAPAttribute( "objectclass", "organizationalPerson" );
+     * LDAPAttribute attr6 = new LDAPAttribute( "objectclass", "inetOrgPerson" );
+     * LDAPAttribute attr7 = new LDAPAttribute( "mail", "bjensen@aceindustry.com" );
+     *
+     * LDAPAttributeSet myAttrs = new LDAPAttributeSet();
+     * myAttrs.add( attr1 );
+     * myAttrs.add( attr2 );
+     * myAttrs.add( attr3 );
+     * myAttrs.add( attr4 );
+     * myAttrs.add( attr5 );
+     * myAttrs.add( attr6 );
+     * myAttrs.add( attr7 );
+     *
+     * LDAPEntry myEntry = new LDAPEntry( myDN, myAttrs );
+     *
+     * myConn.add( myEntry );
+     * ... 
+ * + * @param entry LDAPEntry object specifying the distinguished name and + * attributes of the new entry. + * @exception LDAPException Failed to add the specified entry to the + * directory. + * @see netscape.ldap.LDAPEntry + */ + public void add( LDAPEntry entry ) throws LDAPException { + add(entry, defaultConstraints); + } + + /** + * Adds an entry to the directory and allows you to specify preferences + * for this LDAP add operation by using an + * LDAPSearchConstraints object. For + * example, you can specify whether or not to follow referrals. + * You can also apply LDAP v3 controls to the operation. + *

+ * + * @param entry LDAPEntry object specifying the distinguished name and + * attributes of the new entry. + * @param cons The set of preferences that you want applied to this operation. + * @exception LDAPException Failed to add the specified entry to the + * directory. + * @see netscape.ldap.LDAPEntry + * @see netscape.ldap.LDAPSearchConstraints + */ + public void add( LDAPEntry entry, LDAPSearchConstraints cons ) + throws LDAPException { + bind (); + + LDAPResponseListener myListener = getResponseListener (); + LDAPAttributeSet attrs = entry.getAttributeSet (); + LDAPAttribute[] attrList = new LDAPAttribute[attrs.size()]; + for( int i = 0; i < attrs.size(); i++ ) + attrList[i] = (LDAPAttribute)attrs.elementAt( i ); + int attrPosition = 0; + JDAPMessage response; + try { + sendRequest (new JDAPAddRequest (entry.getDN(), attrList), + myListener, cons); + response = myListener.getResponse(); + checkMsg (response); + } catch (LDAPReferralException e) { + performReferrals(e, cons, JDAPProtocolOp.ADD_REQUEST, + null, 0, null, null, false, null, entry, null, null); + } finally { + releaseResponseListener (myListener); + } + } + + /** + * Performs an extended operation on the directory. Extended operations + * are part of version 3 of the LDAP protocol.

+ * + * Note that in order for the extended operation to work, the server + * that you are connecting to must support LDAP v3 and must be configured + * to process the specified extended operation. + * + * @param op LDAPExtendedOperation object specifying the OID of the + * extended operation and the data to be used in the operation. + * @exception LDAPException Failed to execute the operation + * @return LDAPExtendedOperation object representing the extended response + * returned by the server. + * @see netscape.ldap.LDAPExtendedOperation + */ + public LDAPExtendedOperation extendedOperation( LDAPExtendedOperation op ) + throws LDAPException { + bind (); + + LDAPResponseListener myListener = getResponseListener (); + JDAPMessage response = null; + byte[] results = null; + String resultID; + LDAPSearchConstraints cons = defaultConstraints; + try { + sendRequest ( new JDAPExtendedRequest( op.getID(), op.getValue() ), + myListener, cons ); + response = myListener.getResponse(); + checkMsg (response); + JDAPExtendedResponse res = (JDAPExtendedResponse)response.getProtocolOp(); + results = res.getValue(); + resultID = res.getID(); + } catch (LDAPReferralException e) { + return performExtendedReferrals( e, cons, op ); + } finally { + releaseResponseListener (myListener); + } + return new LDAPExtendedOperation( resultID, results ); + } + + /** + * Makes a single change to an existing entry in the directory + * (for example, changes the value of an attribute, adds a new + * attribute value, or removes an existing attribute value).

+ * + * Use the LDAPModification object to specify the change + * that needs to be made and the LDAPAttribute object + * to specify the attribute value that needs to be changed. The + * LDAPModification object allows you add an attribute + * value, change an attibute value, or remove an attribute + * value.

+ * + * For example, the following section of code changes Barbara Jensen's email + * address in the directory to babs@aceindustry.com.

+ * + *

+     * ...
+     * String myEntryDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
+     *
+     * LDAPAttribute attrEmail = new LDAPAttribute( "mail", "babs@aceindustry.com" );
+     * LDAPModification singleChange = new LDAPModification( LDAPModification.REPLACE, attrEmail );
+     *
+     * myConn.modify( myEntryDN, singleChange );
+     * ... 
+ * + * @param DN The distinguished name of the entry that you want to modify + * @param mod A single change to be made to the entry + * @exception LDAPException Failed to make the specified change to the + * directory entry. + * @see netscape.ldap.LDAPModification + */ + public void modify( String DN, LDAPModification mod ) throws LDAPException { + modify(DN, mod, defaultConstraints); + } + + /** + * Makes a single change to an existing entry in the directory and + * allows you to specify preferences for this LDAP modify operation + * by using an LDAPSearchConstraints object. For + * example, you can specify whether or not to follow referrals. + * You can also apply LDAP v3 controls to the operation. + *

+ * + * @param DN The distinguished name of the entry that you want to modify + * @param mod A single change to be made to the entry + * @param cons The set of preferences that you want applied to this operation. + * @exception LDAPException Failed to make the specified change to the + * directory entry. + * @see netscape.ldap.LDAPModification + * @see netscape.ldap.LDAPSearchConstraints + */ + public void modify( String DN, LDAPModification mod, + LDAPSearchConstraints cons ) throws LDAPException { + LDAPModification[] mods = new LDAPModification [1]; + mods[0] = mod; + modify (DN, mods, cons); + } + + /** + * Makes a set of changes to an existing entry in the directory + * (for example, changes attribute values, adds new attribute values, + * or removes existing attribute values).

+ * + * Use the LDAPModificationSet object to specify the set + * of changes that needs to be made. Changes are specified in terms + * of attribute values. Each attribute value to be modified, added, + * or removed must be specified by an LDAPAttribute object. + *

+ * + * For example, the following section of code changes Barbara Jensen's + * title, adds a telephone number to the entry, and removes the room + * number from the entry.

+ * + *

+     * ...
+     * String myEntryDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
+     *
+     * LDAPModificationSet manyChanges = new LDAPModificationSet();
+     * LDAPAttribute attrTelephoneNumber = new LDAPAttribute( "telephoneNumber",
+     *                                                        "555-1212" );
+     * manyChanges.add( LDAPModification.ADD, attrTelephoneNumber );
+     * LDAPAttribute attrRoomNumber = new LDAPAttribute( "roomnumber", "222" );
+     * manyChanges.add( LDAPModification.DELETE, attrRoomNumber );
+     * LDAPAttribute attrTitle = new LDAPAttribute( "title",
+     *                                       "Manager of Product Development" );
+     * manyChanges.add( LDAPModification.REPLACE, attrTitle );
+     *
+     * myConn.modify( myEntryDN, manyChanges );
+     * ... 
+ * + * @param DN The distinguished name of the entry that you want to modify + * @param mods A set of changes to be made to the entry + * @exception LDAPException Failed to make the specified changes to the + * directory entry. + * @see netscape.ldap.LDAPModificationSet + */ + public void modify (String DN, LDAPModificationSet mods) + throws LDAPException { + modify(DN, mods, defaultConstraints); + } + + /** + * Makes a set of changes to an existing entry in the directory and + * allows you to specify preferences for this LDAP modify operation + * by using an LDAPSearchConstraints object. For + * example, you can specify whether or not to follow referrals. + * You can also apply LDAP v3 controls to the operation. + *

+ * + * @param DN The distinguished name of the entry that you want to modify + * @param mods A set of changes to be made to the entry + * @param cons The set of preferences that you want applied to this operation. + * @exception LDAPException Failed to make the specified changes to the + * directory entry. + * @see netscape.ldap.LDAPModificationSet + * @see netscape.ldap.LDAPSearchConstraints + */ + public void modify (String DN, LDAPModificationSet mods, + LDAPSearchConstraints cons) throws LDAPException { + LDAPModification[] modList = new LDAPModification[mods.size()]; + for( int i = 0; i < mods.size(); i++ ) + modList[i] = mods.elementAt( i ); + modify (DN, modList, cons); + } + + /** + * Makes a set of changes to an existing entry in the directory + * (for example, changes attribute values, adds new attribute values, + * or removes existing attribute values).

+ * + * Use an array of LDAPModification objects to specify the + * changes that need to be made. Each change must be specified by + * an LDAPModification object, and each attribute value + * to be modified, added, or removed must be specified by an + * LDAPAttribute object.

+ * + * @param DN The distinguished name of the entry that you want to modify + * @param mods An array of objects representing the changes to be made + * to the entry + * @exception LDAPException Failed to make the specified changes to the + * directory entry. + * @see netscape.ldap.LDAPModification + */ + public void modify (String DN, LDAPModification[] mods) + throws LDAPException { + modify(DN, mods, defaultConstraints); + } + + /** + * Makes a set of changes to an existing entry in the directory and + * allows you to specify preferences for this LDAP modify operation + * by using an LDAPSearchConstraints object. For + * example, you can specify whether or not to follow referrals. + * You can also apply LDAP v3 controls to the operation. + *

+ * + * @param DN The distinguished name of the entry that you want to modify + * @param mods An array of objects representing the changes to be made + * to the entry + * @param cons The set of preferences that you want applied to this operation. + * @exception LDAPException Failed to make the specified changes to the + * directory entry. + * @see netscape.ldap.LDAPModification + * @see netscape.ldap.LDAPSearchConstraints + */ + public void modify (String DN, LDAPModification[] mods, + LDAPSearchConstraints cons) throws LDAPException { + bind (); + + LDAPResponseListener myListener = getResponseListener (); + JDAPMessage response = null; + try { + sendRequest (new JDAPModifyRequest (DN, mods), myListener, cons); + response = myListener.getResponse(); + checkMsg (response); + } catch (LDAPReferralException e) { + performReferrals(e, cons, JDAPProtocolOp.MODIFY_REQUEST, + DN, 0, null, null, false, mods, null, null, null); + } finally { + releaseResponseListener (myListener); + } + } + + /** + * Deletes the entry for the specified DN from the directory.

+ * + * For example, the following section of code deletes the entry for + * Barbara Jensen from the directory.

+ * + *

+     * ...
+     * String myEntryDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
+     * myConn.delete( myEntryDN );
+     * ... 
+ * + * @param DN Distinguished name identifying the entry that you want + * to remove from the directory. + * @exception LDAPException Failed to delete the specified entry from + * the directory. + */ + public void delete( String DN ) throws LDAPException { + delete(DN, defaultConstraints); + } + + /** + * Deletes the entry for the specified DN from the directory and + * allows you to specify preferences for this LDAP delete operation + * by using an LDAPSearchConstraints object. For + * example, you can specify whether or not to follow referrals. + * You can also apply LDAP v3 controls to the operation. + *

+ * + * @param DN Distinguished name identifying the entry that you want + * to remove from the directory. + * @param cons The set of preferences that you want applied to this operation. + * @exception LDAPException Failed to delete the specified entry from + * the directory. + * @see netscape.ldap.LDAPSearchConstraints + */ + public void delete( String DN, LDAPSearchConstraints cons ) + throws LDAPException { + bind (); + + LDAPResponseListener myListener = getResponseListener (); + JDAPMessage response; + try { + sendRequest (new JDAPDeleteRequest (DN), myListener, cons); + response = myListener.getResponse(); + checkMsg (response); + } catch (LDAPReferralException e) { + performReferrals(e, cons, JDAPProtocolOp.DEL_REQUEST, + DN, 0, null, null, false, null, null, null, null); + } finally { + releaseResponseListener (myListener); + } + } + + /** + * Renames an existing entry in the directory.

+ * + * You can specify whether or not the original name of the entry is + * retained as a value in the entry. For example, suppose you rename + * the entry "cn=Barbara" to "cn=Babs". You can keep "cn=Barbara" + * as a value in the entry so that the cn attribute has two values:

+ * + *

+     *       cn=Barbara
+     *       cn=Babs
+     * 
+ * The following example renames an entry. The old name of the entry + * is kept as a value in the entry.

+ * + *

+     * ...
+     * String myEntryDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
+     * String newRDN = "cn=Babs Jensen";
+     * myConn.rename( myEntryDN, newRDN, false );
+     * ... 
+ * + * @param DN Current distinguished name of the entry. + * @param newRDN New relative distinguished name for the entry (for example, + * "cn=newName"). + * @param deleteOldRDN If true, the old name is not retained + * as an attribute value (for example, the attribute value "cn=oldName" is + * removed). If false, the old name is retained + * as an attribute value (for example, the entry might now have two values + * for the cn attribute: "cn=oldName" and "cn=newName"). + * @exception LDAPException Failed to rename the specified entry. + */ + public void rename (String DN, String newRDN, boolean deleteOldRDN ) + throws LDAPException { + rename(DN, newRDN, null, deleteOldRDN); + } + + /** + * Renames an existing entry in the directory.

+ * + * You can specify whether or not the original name of the entry is + * retained as a value in the entry. For example, suppose you rename + * the entry "cn=Barbara" to "cn=Babs". You can keep "cn=Barbara" + * as a value in the entry so that the cn attribute has two values:

+ * + *

+     *       cn=Barbara
+     *       cn=Babs
+     * 
+ * The following example renames an entry. The old name of the entry + * is kept as a value in the entry.

+ * + *

+     * ...
+     * String myEntryDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
+     * String newRDN = "cn=Babs Jensen";
+     * myConn.rename( myEntryDN, newRDN, false );
+     * ... 
+ * + * @param DN Current distinguished name of the entry. + * @param newRDN New relative distinguished name for the entry (for example, + * "cn=newName"). + * @param deleteOldRDN If true, the old name is not retained + * as an attribute value (for example, the attribute value "cn=oldName" is + * removed). If false, the old name is retained + * as an attribute value (for example, the entry might now have two values + * for the cn attribute: "cn=oldName" and "cn=newName"). + * @param cons The set of preferences that you want applied to this operation. + * @exception LDAPException Failed to rename the specified entry. + */ + public void rename (String DN, String newRDN, boolean deleteOldRDN, + LDAPSearchConstraints cons ) + throws LDAPException { + rename(DN, newRDN, null, deleteOldRDN, cons); + } + + /** + * Renames an existing entry in the directory and (optionally) + * changes the location of the entry in the directory tree.

+ * + * NOTE: Netscape Directory Server 3.0 does not support the + * capability to move an entry to a different location in the + * directory tree. If you specify a value for the newParentDN + * argument, an LDAPException will be thrown. + *

+ * + * @param DN Current distinguished name of the entry. + * @param newRDN New relative distinguished name for the entry (for example, + * "cn=newName"). + * @param newParentDN If not null, the distinguished name for the + * entry under which the entry should be moved (for example, to move + * an entry under the Accounting subtree, specify this argument as + * "ou=Accounting, o=Ace Industry, c=US"). + * @param deleteOldRDN If true, the old name is not retained + * as an attribute value (for example, the attribute value "cn=oldName" is + * removed). If false, the old name is retained + * as an attribute value (for example, the entry might now have two values + * for the cn attribute: "cn=oldName" and "cn=newName"). + * @exception LDAPException Failed to rename the specified entry. + */ + public void rename(String dn, + String newRDN, + String newParentDN, + boolean deleteOldRDN) throws LDAPException { + rename(dn, newRDN, newParentDN, deleteOldRDN, defaultConstraints); + } + + /** + * Renames an existing entry in the directory and (optionally) + * changes the location of the entry in the directory tree. Also + * allows you to specify preferences for this LDAP modify DN operation + * by using an LDAPSearchConstraints object. For + * example, you can specify whether or not to follow referrals. + * You can also apply LDAP v3 controls to the operation. + *

+ * + * NOTE: Netscape Directory Server 3.0 does not support the + * capability to move an entry to a different location in the + * directory tree. If you specify a value for the newParentDN + * argument, an LDAPException will be thrown. + *

+ * + * @param DN Current distinguished name of the entry. + * @param newRDN New relative distinguished name for the entry (for example, + * "cn=newName"). + * @param newParentDN If not null, the distinguished name for the + * entry under which the entry should be moved (for example, to move + * an entry under the Accounting subtree, specify this argument as + * "ou=Accounting, o=Ace Industry, c=US"). + * @param deleteOldRDN If true, the old name is not retained + * as an attribute value (for example, the attribute value "cn=oldName" is + * removed). If false, the old name is retained + * as an attribute value (for example, the entry might now have two values + * for the cn attribute: "cn=oldName" and "cn=newName"). + * @param cons The set of preferences that you want applied to this operation. + * @exception LDAPException Failed to rename the specified entry. + * @see netscape.ldap.LDAPSearchConstraints + */ + public void rename (String DN, + String newRDN, + String newParentDN, + boolean deleteOldRDN, + LDAPSearchConstraints cons) + throws LDAPException { + bind (); + + LDAPResponseListener myListener = getResponseListener (); + JDAPMessage response; + try { + JDAPModifyRDNRequest request = null; + if ( newParentDN != null ) + request = new JDAPModifyRDNRequest (DN, + newRDN, + deleteOldRDN, + newParentDN); + else + request = new JDAPModifyRDNRequest (DN, + newRDN, + deleteOldRDN); + sendRequest (request, myListener, cons); + response = myListener.getResponse(); + checkMsg (response); + } catch (LDAPReferralException e) { + performReferrals(e, cons, JDAPProtocolOp.MODIFY_RDN_REQUEST, + DN, 0, newRDN, null, deleteOldRDN, null, null, null, null); + } finally { + releaseResponseListener (myListener); + } + } + + /** + * Returns the value of the specified option for this + * LDAPConnection object.

+ * + * These options represent the search constraints for the current connection. + * To get all search constraints for the current connection, call the + * getSearchConstraints method. + *

+ * + * By default, the search constraints apply to all searches performed + * through the current connection. You can change these search constraints: + *

+ * + *

    + *
  • If you want to override these constraints only for a particular + * search, create an LDAPSearchConstraints object with + * your new constraints and pass it to the + * LDAPConnection.search method. + *

    + * + *

  • If you want to override these constraints for all searches + * performed under the current connection, call the + * setOption method to change the search constraint. + *

    + * + *

+ *

+ * + * For example, the following section of code gets and prints the + * maximum number of search results that are returned for searches + * performed through this connection. (This applies to all searches + * unless a different set of search constraints is specified in an + * LDAPSearchConstraints object.) + *

+ * + *

+     * LDAPConnection ld = new LDAPConnection();
+     * int sizeLimit = ( (Integer)ld.getOption( LDAPv2.SIZELIMIT ) ).intValue();
+     * System.out.println( "Maximum number of results: " + sizeLimit );
+     * 
+ * + * @param option You can specify one of the following options: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
OptionData TypeDescription
+ * LDAPv2.PROTOCOL_VERSIONIntegerSpecifies the version of the LDAP protocol used by the + * client. + *

By default, the value of this option is 2.

+ * LDAPv2.DEREFIntegerSpecifies when your client dereferences aliases. + *
+     * Legal values for this option are:
+     *
+     * DEREF_NEVER       Aliases are never dereferenced.
+     *
+     * DEREF_FINDING     Aliases are dereferenced when find-
+     *                   ing the starting point for the
+     *                   search (but not when searching
+     *                   under that starting entry).
+     *
+     * DEREF_SEARCHING   Aliases are dereferenced when
+     *                   searching the entries beneath the
+     *                   starting point of the search (but
+     *                   not when finding the starting
+     *                   entry).
+     *
+     * DEREF_ALWAYS      Aliases are always dereferenced.
+     *
+ *

By default, the value of this option is + * DEREF_NEVER.

+ * LDAPv2.SIZELIMITIntegerSpecifies the maximum number of search results to return. + * If this option is set to 0, there is no maximum limit. + *

By default, the value of this option is 1000.

+ * LDAPv2.TIMELIMITIntegerSpecifies the maximum number of milliseconds to wait for results + * before timing out. If this option is set to 0, there is no maximum + * time limit. + *

By default, the value of this option is 0.

+ * LDAPv2.REFERRALSBooleanSpecifies whether or not your client follows referrals automatically. + * If true, your client follows referrals automatically. + * If false, an LDAPReferralException is raised + * when referral is detected. + *

By default, the value of this option is false.

+ * LDAPv2.REFERRALS_REBIND_PROCLDAPRebindSpecifies an object with a class that implements the + * LDAPRebind interface. You must define this class and + * the getRebindAuthentication method that will be used to + * get the distinguished name and password to use for authentication. + *

By default, the value of this option is null.

+ * LDAPv2.REFERRALS_HOP_LIMITIntegerSpecifies the maximum number of referrals in a sequence that + * your client will follow. (For example, if REFERRALS_HOP_LIMIT is 5, + * your client will follow no more than 5 referrals in a row when resolving + * a single LDAP request.) + *

By default, the value of this option is 10.

+ * LDAPv2.BATCHSIZEIntegerSpecifies the number of search results to return at a time. + * (For example, if BATCHSIZE is 1, results are returned one at a time.) + *

By default, the value of this option is 1.

+ * LDAPv3.CLIENTCONTROLSLDAPControl[]Specifies the client controls that may affect the handling of LDAP + * operations in the LDAP classes. These controls are used by the client + * and are not passed to the LDAP server. At this time, no client controls + * are defined for clients built with the Netscape LDAP classes.
+ * LDAPv3.SERVERCONTROLSLDAPControl[]Specifies the server controls that are passed to the LDAP + * server on each LDAP operation. Not all servers support server + * controls; a particular server may or may not support a given + * server control.

+ * @return The value for the option wrapped in an object. (You + * need to cast the returned value as its appropriate type. For + * example, when getting the SIZELIMIT option, cast the returned + * value as an Integer.) + * @exception LDAPException Failed to get the specified option. + * @see netscape.ldap.LDAPRebind + * @see netscape.ldap.LDAPSearchConstraints + * @see netscape.ldap.LDAPReferralException + * @see netscape.ldap.LDAPControl + * @see netscape.ldap.LDAPConnection#getSearchConstraints + * @see netscape.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, netscape.ldap.LDAPSearchConstraints) + */ + public Object getOption( int option ) throws LDAPException { + if (option == LDAPv2.PROTOCOL_VERSION) { + return new Integer(protocolVersion); + } + + return getOption(option, defaultConstraints); + } + + private static Object getOption( int option, LDAPSearchConstraints cons ) + throws LDAPException { + switch (option) { + case LDAPv2.DEREF: + return new Integer (cons.getDereference()); + case LDAPv2.SIZELIMIT: + return new Integer (cons.getMaxResults()); + case LDAPv2.TIMELIMIT: + return new Integer (cons.getTimeLimit()); + case LDAPv2.REFERRALS: + return new Boolean (cons.getReferrals()); + case LDAPv2.REFERRALS_REBIND_PROC: + return cons.getRebindProc(); + case LDAPv2.REFERRALS_HOP_LIMIT: + return new Integer (cons.getHopLimit()); + case LDAPv2.BATCHSIZE: + return new Integer (cons.getBatchSize()); + case LDAPv3.CLIENTCONTROLS: + return cons.getClientControls(); + case LDAPv3.SERVERCONTROLS: + return cons.getServerControls(); + default: + throw new LDAPException ( "invalid option", + LDAPException.PARAM_ERROR ); + } + } + + /** + * Sets the value of the specified option for this + * LDAPConnection object.

+ * + * These options represent the search constraints for the current + * connection. + * To get all search constraints for the current connection, call the + * getSearchConstraints method. + *

+ * + * By default, the option that you set applies to all subsequent + * searches performed through the current connection. If you want to + * set a constraint only for a particular search, create an + * LDAPSearchConstraints object with your new constraints + * and pass it to the LDAPConnection.search method. + *

+ * + * For example, the following section of code changes the constraint for + * the maximum number of search results that are returned for searches + * performed through this connection. (This applies to all searches + * unless a different set of search constraints is specified in an + * LDAPSearchConstraints object.) + *

+ * + *

+     * LDAPConnection ld = new LDAPConnection();
+     * Integer newLimit = new Integer( 20 );
+     * ld.setOption( LDAPv2.SIZELIMIT, newLimit );
+     * System.out.println( "Changed the maximum number of results to " + newLimit.intValue() );
+     * 
+ * + * @param option You can specify one of the following options: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
OptionData TypeDescription
+ * LDAPv2.PROTOCOL_VERSIONIntegerSpecifies the version of the LDAP protocol used by the + * client. + *

By default, the value of this option is 2. If you want + * to use LDAP v3 features (such as extended operations or + * controls), you need to set this value to 3.

+ * LDAPv2.DEREFIntegerSpecifies when your client dereferences aliases. + *
+     * Legal values for this option are:
+     *
+     * DEREF_NEVER       Aliases are never dereferenced.
+     *
+     * DEREF_FINDING     Aliases are dereferenced when find-
+     *                   ing the starting point for the
+     *                   search (but not when searching
+     *                   under that starting entry).
+     *
+     * DEREF_SEARCHING   Aliases are dereferenced when
+     *                   searching the entries beneath the
+     *                   starting point of the search (but
+     *                   not when finding the starting
+     *                   entry).
+     *
+     * DEREF_ALWAYS      Aliases are always dereferenced.
+     *
+ *

By default, the value of this option is + * DEREF_NEVER.

+ * LDAPv2.SIZELIMITIntegerSpecifies the maximum number of search results to return. + * If this option is set to 0, there is no maximum limit. + *

By default, the value of this option is 1000.

+ * LDAPv2.TIMELIMITIntegerSpecifies the maximum number of milliseconds to wait for results + * before timing out. If this option is set to 0, there is no maximum + * time limit. + *

By default, the value of this option is 0.

+ * LDAPv2.REFERRALSBooleanSpecifies whether or not your client follows referrals automatically. + * If true, your client follows referrals automatically. + * If false, an LDAPReferralException is + * raised when a referral is detected. + *

By default, the value of this option is false.

+ * LDAPv2.REFERRALS_REBIND_PROCLDAPRebindSpecifies an object with a class that implements the + * LDAPRebind + * interface. You must define this class and the + * getRebindAuthentication method that will be used to get + * the distinguished name and password to use for authentication. + *

By default, the value of this option is null.

+ * LDAPv2.REFERRALS_HOP_LIMITIntegerSpecifies the maximum number of referrals in a sequence that + * your client will follow. (For example, if REFERRALS_HOP_LIMIT is 5, + * your client will follow no more than 5 referrals in a row when resolving + * a single LDAP request.) + *

By default, the value of this option is 10.

+ * LDAPv2.BATCHSIZEIntegerSpecifies the number of search results to return at a time. + * (For example, if BATCHSIZE is 1, results are returned one at a time.) + *

By default, the value of this option is 1.

+ * LDAPv3.CLIENTCONTROLSLDAPControl[]Specifies the client controls that may affect handling of LDAP + * operations in the LDAP classes. These controls are used by the client + * and are not passed to the server. At this time, no client controls + * are defined for clients built with the Netscape LDAP classes.
+ * LDAPv3.SERVERCONTROLSLDAPControl[]Specifies the server controls that are passed to the LDAP + * server on each LDAP operation. Not all servers support server + * controls; a particular server may or may not support a particular + * control.

+ * @param value The value to assign to the option. The value must be + * the java.lang object wrapper for the appropriate parameter + * (e.g. boolean->Boolean, + * integer->Integer) + * @exception LDAPException Failed to set the specified option. + * @see netscape.ldap.LDAPRebind + * @see netscape.ldap.LDAPSearchConstraints + * @see netscape.ldap.LDAPReferralException + * @see netscape.ldap.LDAPControl + * @see netscape.ldap.LDAPConnection#getSearchConstraints + * @see netscape.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, netscape.ldap.LDAPSearchConstraints) + */ + public void setOption( int option, Object value ) throws LDAPException { + if (option == LDAPv2.PROTOCOL_VERSION) { + setProtocolVersion(((Integer)value).intValue()); + return; + } + setOption(option, value, defaultConstraints); + } + + private static void setOption( int option, Object value, LDAPSearchConstraints cons ) throws LDAPException { + try { + switch (option) { + case LDAPv2.DEREF: + cons.setDereference(((Integer)value).intValue()); + return; + case LDAPv2.SIZELIMIT: + cons.setMaxResults(((Integer)value).intValue()); + return; + case LDAPv2.TIMELIMIT: + cons.setTimeLimit(((Integer)value).intValue()); + return; + case LDAPv2.REFERRALS: + cons.setReferrals(((Boolean)value).booleanValue()); + return; + case LDAPv2.REFERRALS_REBIND_PROC: + cons.setRebindProc((LDAPRebind)value); + return; + case LDAPv2.REFERRALS_HOP_LIMIT: + cons.setHopLimit(((Integer)value).intValue()); + return; + case LDAPv2.BATCHSIZE: + cons.setBatchSize(((Integer)value).intValue()); + return; + case LDAPv3.CLIENTCONTROLS: + if ( value == null ) + cons.setClientControls( (LDAPControl[]) null ); + else if ( value instanceof LDAPControl ) + cons.setClientControls( (LDAPControl) value ); + else if ( value instanceof LDAPControl[] ) + cons.setClientControls( (LDAPControl[])value ); + else + throw new LDAPException ( "invalid LDAPControl", + LDAPException.PARAM_ERROR ); + return; + case LDAPv3.SERVERCONTROLS: + if ( value == null ) + cons.setServerControls( (LDAPControl[]) null ); + else if ( value instanceof LDAPControl ) + cons.setServerControls( (LDAPControl) value ); + else if ( value instanceof LDAPControl[] ) + cons.setServerControls( (LDAPControl[])value ); + else + throw new LDAPException ( "invalid LDAPControl", + LDAPException.PARAM_ERROR ); + return; + default: + throw new LDAPException ("invalid option", + LDAPException.PARAM_ERROR ); + } + } catch (ClassCastException cc) { + throw new LDAPException ("invalid option value", + LDAPException.PARAM_ERROR ); + } + } + + /** + * Returns an array of the latest controls (if any) from server. + * @return An array of the controls returned by an operation, or + * null if none. + * @see netscape.ldap.LDAPControl + */ + public LDAPControl[] getResponseControls() { + LDAPControl[] controls = null; + LDAPControl[] con; + /* Get the latest controls returned for our thread */ + synchronized(m_responseControlTable) { + con = (LDAPControl[])m_responseControlTable.get( + Thread.currentThread() ); + } + /* If there are any, return copies of them */ + if ( (con != null) && (con.length > 0) ) { + controls = new LDAPControl[con.length]; + for( int i = 0; i < con.length; i++ ) + controls[i] = (LDAPControl)con[i].clone(); + } + return controls; + } + + /** + * Returns the set of search constraints that apply to all searches + * performed through this connection (unless you specify a different + * set of search constraints when calling the search + * method).

+ * + * Note that if you want to get individual constraints (rather than + * getting the + * entire set of constraints), call the getOption method. + *

+ * + * Typically, you might call the getSearchConstraints method + * if you want to create a slightly different set of search constraints + * that you want to apply to a particular search. + *

+ * + * For example, the following section of code changes the maximum number + * of results to 10 for a specific search. Rather than construct a new + * set of search constraints from scratch, the example gets the current + * settings for the connections and just changes the setting for the + * maximum results. + *

+ * + * Note that this change only applies to the searches performed with this + * custom set of constraints. All other searches performed through this + * connection use the original set of search constraints. + *

+ * + *

+     * ...
+     * LDAPSearchConstraints myOptions = ld.getSearchConstraints();
+     * myOptions.setMaxResults( 10 );
+     * String[] myAttrs = { "objectclass" };
+     * LDAPSearchResults myResults = ld.search( "o=Ace Industry,c=US",
+     *                                          LDAPv2.SCOPE_SUB,
+     *                                          "(objectclass=*)",
+     *                                          myAttrs,
+     *                                          false,
+     *                                          myOptions );
+     * ...
+     * 
+ * + * @return The LDAPSearchConstraints object representing the + * set of search constraints that apply (by default) to all searches + * performed through this connection. + * @see netscape.ldap.LDAPSearchConstraints + * @see netscape.ldap.LDAPConnection#getOption + * @see netscape.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, netscape.ldap.LDAPSearchConstraints) + */ + public LDAPSearchConstraints getSearchConstraints () { + return defaultConstraints; + } + + /** + * Get a new listening agent from the internal buffer of available agents. + * These objects are used to make the asynchronous LDAP operations + * synchronous. + * @return response listener object + */ + private synchronized LDAPResponseListener getResponseListener () { + if (responseListeners == null) + responseListeners = new Vector (5); + + LDAPResponseListener l; + if ( responseListeners.size() < 1 ) { + l = new LDAPResponseListener ( this ); + } + else { + l = (LDAPResponseListener)responseListeners.elementAt (0); + responseListeners.removeElementAt (0); + } + /* The agent must record the current thread in order to be able to + distinguish between server response controls destined for + different threads */ + l.setThread(); + return l; + } + + /** + * Get a new search listening agent from the internal buffer of available + * agents. These objects are used to make the asynchronous LDAP operations + * synchronous. + * @return A search response listener object + */ + private synchronized LDAPSearchListener getSearchListener () + { + if (searchListeners == null) { + searchListeners = new Vector (5); + } + + LDAPSearchListener l; + if ( searchListeners.size() < 1 ) { + l = new LDAPSearchListener ( this ); + } + else { + l = (LDAPSearchListener)searchListeners.elementAt (0); + searchListeners.removeElementAt (0); + } + /* The agent must record the current thread in order to be able to + distinguish between server response controls destined for + different threads */ + l.setThread(); + return l; + } + + /** + * Put a listening agent into the internal buffer of available agents. + * These objects are used to make the asynchronous LDAP operations + * synchronous. + * @param l Listener to buffer + */ + private synchronized void releaseResponseListener (LDAPResponseListener l) + { + if (responseListeners == null) + responseListeners = new Vector (5); + + l.reset (); + responseListeners.addElement (l); + } + + /** + * Put a search listening agent into the internal buffer of available + * agents. These objects are used to make the asynchronous LDAP + * operations synchronous. + * @param Listener to buffer + */ + synchronized void releaseSearchListener (LDAPSearchListener l) + { + if (searchListeners == null) + searchListeners = new Vector (5); + + l.reset (); + searchListeners.addElement (l); + } + + /** + * Checks the message (assumed to be a return value). If the resultCode + * is anything other than SUCCESS, it throws an LDAPException describing + * the server's (error) response. + * @param m Server response to validate + * @exception LDAPException failed to check message + */ + void checkMsg (JDAPMessage m) throws LDAPException { + if (m.getProtocolOp() instanceof JDAPResult) { + JDAPResult response = (JDAPResult)(m.getProtocolOp()); + int resultCode = response.getResultCode (); + + if (resultCode == JDAPResult.SUCCESS) + return; + + if (resultCode == JDAPResult.REFERRAL) + throw new LDAPReferralException ("referral", resultCode, + response.getReferrals()); + + if (resultCode == JDAPResult.LDAP_PARTIAL_RESULTS) + throw new LDAPReferralException ("referral", resultCode, + response.getErrorMessage()); + else + throw new LDAPException ("error result", resultCode, + response.getErrorMessage(), + response.getMatchedDN()); + + } else if (m.getProtocolOp() instanceof JDAPSearchResultReference) { + String[] referrals = + ((JDAPSearchResultReference)m.getProtocolOp()).getUrls(); + throw new LDAPReferralException ("referral", + JDAPResult.SUCCESS, referrals); + } else + return; + } + + /** + * Stash away server response controls for a particular thread. + * @param current The target thread. + * @param con The server response controls. + */ + void setResponseControls( Thread current, LDAPControl[] con ) { + synchronized(m_responseControlTable) { + if ( con != null ) + m_responseControlTable.put( current, con ); + else + m_responseControlTable.remove( current ); + + /* Do some garbage collection: check if any attached threads have + exited */ + /* Now check all threads in the list */ + Enumeration e = m_attachedList.elements(); + while( e.hasMoreElements() ) { + Thread aThread = (Thread)e.nextElement(); + if ( !aThread.isAlive() ) { + m_responseControlTable.remove( aThread ); + m_attachedList.removeElement( aThread ); + } + } + } + /* Make sure we're registered */ + if ( m_attachedList.indexOf( current ) < 0 ) + m_attachedList.addElement( current ); + } + + /** + * Set up connection for referral. + * @param u referral URL + * @param cons search constraints + * @return new LDAPConnection, already connected and authenticated + */ + private LDAPConnection prepareReferral( LDAPUrl u, + LDAPSearchConstraints cons ) + throws LDAPException { + LDAPConnection connection = new LDAPConnection (this.getSocketFactory()); + connection.setOption(REFERRALS, new Boolean(true)); + connection.setOption(REFERRALS_REBIND_PROC, + cons.getRebindProc()); + + // need to set the protocol version which gets passed to connection + connection.setOption(PROTOCOL_VERSION, + new Integer(protocolVersion)); + + connection.setOption(REFERRALS_HOP_LIMIT, + new Integer(cons.getHopLimit()-1)); + connection.connect (u.getHost(), u.getPort()); + if (cons.getRebindProc() == null) { + connection.authenticate (null, null); + } else { + LDAPRebindAuth auth = cons.getRebindProc().getRebindAuthentication( + u.getHost(), + u.getPort()); + connection.authenticate (auth.getDN(), auth.getPassword()); + } + return connection; + } + + /** + * Performs the referral. + * @param e referral exception + * @param cons search constraints + */ + void performReferrals(LDAPReferralException e, + LDAPSearchConstraints cons, int ops, + /* unions of different operation parameters */ + String dn, int scope, String filter, String types[], + boolean attrsOnly, LDAPModification mods[], LDAPEntry entry, + LDAPAttribute attr, + /* result */ + Vector results + ) throws LDAPException { + + if (cons.getHopLimit() <= 0) + throw new LDAPException("exceed hop limit", + e.getLDAPResultCode(), e.getLDAPErrorMessage()); + if (!cons.getReferrals()) { + if (ops == JDAPProtocolOp.SEARCH_REQUEST) { + LDAPSearchResults res = new LDAPSearchResults(); + res.add(e); + results.addElement(res); + return; + } else + throw e; + } + + LDAPUrl u[] = e.getURLs(); + // If there are no referrals (because the server isn't set up for + // them), give up here + if ( u == null ) + return; + + for (int i = 0; i < u.length; i++) { + LDAPConnection connection = null; + LDAPSearchResults res = null; + try { + connection = prepareReferral( u[i], cons ); + String newDN = u[i].getDN(); + String DN = null; + if (newDN != null) + DN = newDN; + else + DN = dn; + + LDAPSearchConstraints newcons = (LDAPSearchConstraints)cons.clone(); + newcons.setHopLimit( cons.getHopLimit()-1 ); + + switch (ops) { + case JDAPProtocolOp.SEARCH_REQUEST: + + res = connection.search(DN, scope, filter, + types, attrsOnly, newcons); + if (res != null) { + res.closeOnCompletion(connection); + results.addElement(res); + } else { + connection.disconnect(); + } + break; + case JDAPProtocolOp.MODIFY_REQUEST: + connection.modify(DN, mods, newcons); + break; + case JDAPProtocolOp.ADD_REQUEST: + connection.add(entry, newcons); + break; + case JDAPProtocolOp.DEL_REQUEST: + connection.delete(DN, newcons); + break; + case JDAPProtocolOp.MODIFY_RDN_REQUEST: + connection.rename(DN, filter /* newRDN */, attrsOnly /* deleteOld */, + newcons); + break; + case JDAPProtocolOp.COMPARE_REQUEST: + boolean bool = connection.compare(DN, attr, newcons); + results.addElement(new Boolean(bool)); + break; + default: + /* impossible */ + break; + } + } catch (LDAPException ee) { + throw ee; + } finally { + if ((connection != null) && ((ops != JDAPProtocolOp.SEARCH_REQUEST) || + (res == null))) + connection.disconnect(); + } + } + } + + /** + * Performs the referral. + * @param e referral exception + * @param cons search constraints + */ + private LDAPExtendedOperation performExtendedReferrals( + LDAPReferralException e, + LDAPSearchConstraints cons, LDAPExtendedOperation op ) + throws LDAPException { + + if (cons.getHopLimit() <= 0) + throw new LDAPException("exceed hop limit", + e.getLDAPResultCode(), e.getLDAPErrorMessage()); + if (!cons.getReferrals()) { + throw e; + } + + LDAPUrl u[] = e.getURLs(); + // If there are no referrals (because the server isn't set up for + // them), give up here + if ( u == null ) + return null; + + for (int i = 0; i < u.length; i++) { + try { + LDAPConnection connection = prepareReferral( u[i], cons ); + LDAPExtendedOperation results = + connection.extendedOperation( op ); + connection.disconnect(); + return results; /* return right away if operation is successful */ + } catch (LDAPException ee) { + continue; + } + } + return null; + } + + /** + * Creates and returns an new LDAPConnection object that + * contains the same information as the current connection, including: + *
    + *
  • the default search constraints + *
  • host name and port number of the LAAP server + *
  • the DN and password used to authenticate to the LDAP server + *
+ *

+ * @return The LDAPconnection object representing the + * new object. + */ + public synchronized Object clone() { + try { + LDAPConnection c = (LDAPConnection)super.clone(); + + if (this.th == null) + this.bind(); + + c.defaultConstraints = + (LDAPSearchConstraints)defaultConstraints.clone(); + c.responseListeners = null; + c.searchListeners = null; + c.bound = this.bound; + c.host = this.host; + c.port = this.port; + c.boundDN = this.boundDN; + c.boundPasswd = this.boundPasswd; + c.prevBoundDN = this.prevBoundDN; + c.prevBoundPasswd = this.prevBoundPasswd; + c.m_anonymousBound = this.m_anonymousBound; + c.m_factory = this.m_factory; + c.th = this.th; /* share current connection thread */ + + synchronized (m_threadConnTable) { + Vector v = (Vector)m_threadConnTable.get(this.th); + if (v != null) { + v.addElement(c); + } + else { + printDebug("Failed to clone"); + return null; + } + } + + c.th.register(c); + return c; + } catch (Exception e) { + } + return null; + } + + /** + * Sets up basic connection privileges for Communicator. + * @return true if in Communicator and connections okay. + */ + private static boolean checkCommunicator() { + try { + java.lang.reflect.Method m = LDAPCheckComm.getMethod( + "netscape.security.PrivilegeManager", "enablePrivilege"); + if (m == null) { + printDebug("Method is null"); + return false; + } + + Object[] args = new Object[1]; + args[0] = new String("UniversalConnect"); + m.invoke( null, args); + printDebug( "UniversalConnect enabled" ); + return true; + } catch (LDAPException e) { + printDebug("Exception: "+e.toString()); + } catch (Exception ie) { + printDebug("Exception on invoking " + "enablePrivilege: "+ie.toString()); + } + return false; + } + + /** + * Reports if the class is running in a Netscape browser. + * @return true if the class is running in a Netscape browser. + */ + public static boolean isNetscape() { + return isCommunicator; + } + + static void printDebug( String msg ) { + if ( debug ) { + System.out.println( msg ); + } + } + + /** + * Prints out the LDAP Java SDK version and the highest LDAP + * protocol version supported by the SDK. To view this + * information, open a terminal window, and enter: + *

java netscape.ldap.LDAPConnection
+     * 
+ * @param args Not currently used. + */ + public static void main(String[] args) { + System.out.println("LDAP SDK Version is "+SdkVersion); + System.out.println("LDAP Protocol Version is "+ProtocolVersion); + } + + private static boolean isCommunicator = checkCommunicator(); + private static final boolean debug = false; +} + + +/** + * Multiple LDAPConnection clones can share a single physical connection, + * which is maintained by a thread. + * + * New Design (09/05/97): + * + * +----------------+ + * | LDAPConnection | --------+ + * +----------------+ | + * | + * +----------------+ | +----------------+ + * | LDAPConnection | --------+------- | LDAPConnThread | + * +----------------+ | +----------------+ + * | + * +----------------+ | + * | LDAPConnection | --------+ + * +----------------+ + * + * All LDAPConnections send requests and get responses from + * LDAPConnThread (a thread). + */ +class LDAPConnThread extends Thread { + + /** + * Constants + */ + private final static int MAXMSGID = Integer.MAX_VALUE; + + /** + * Internal variables + */ + transient private int m_highMsgId; + transient private InputStream m_serverInput; + transient private OutputStream m_serverOutput; + transient private Hashtable m_requests; + transient private Hashtable m_messages = null; + transient private Vector m_registered; + transient private boolean m_disconnected = false; + transient private LDAPCache m_cache = null; + transient private boolean m_failed = false; + private Object m_securityLayer = null; + private Socket m_socket = null; + + /** + * Constructs a connection thread that maintains connection to the + * LDAP server. + * @param host LDAP host name + * @param port LDAP port number + * @param factory LDAP socket factory + */ + public LDAPConnThread(String host, int port, LDAPSocketFactory factory, + LDAPCache cache) throws LDAPException { + m_highMsgId = 0; + m_requests = new Hashtable (); + m_registered = new Vector (); + m_cache = cache; + if (m_cache != null) + m_messages = new Hashtable (); + + /* Connect to LDAP server */ + try { + /* If we are to create a socket ourselves, make sure it has + sufficient privileges to connect to the desired host */ + if (factory == null) { + m_socket = new Socket (host, port); + } else { + m_socket = factory.makeSocket(host, port); + } + m_serverInput = new BufferedInputStream (m_socket.getInputStream()); + m_serverOutput = new BufferedOutputStream (m_socket.getOutputStream()); + } catch (IOException e) { + + // a kludge to make the thread go away. Since the thread has already + // been created, the only way to clean up the thread is to call the + // start() method. Otherwise, the exit method will be never called + // because the start() was never called. In the run method, the stop + // method calls right away if the m_failed is set to true. + m_failed = true; + start(); + throw new LDAPException ( "failed to connect to server " + host, + LDAPException.CONNECT_ERROR ); + } + start(); /* start the thread */ + } + + /** + * Sends LDAP request via this connection thread. + * @param request request to send + * @param toNotify response listener to invoke when the response + * is ready + */ + synchronized void sendRequest (JDAPProtocolOp request, + LDAPResponseListener toNotify, LDAPSearchConstraints cons) + throws LDAPException { + if (m_serverOutput == null) + throw new LDAPException ( "not connected to a server", + LDAPException.OTHER ); + + JDAPMessage msg; + LDAPControl lc[] = cons.getServerControls(); + if ( (lc != null) && (lc.length > 0) ) { + JDAPControl[] jc = new JDAPControl[lc.length]; + for( int i = 0; i < lc.length; i++ ) + jc[i] = new JDAPControl( lc[i].getID(), + lc[i].isCritical(), + lc[i].getValue() ); + msg = new JDAPMessage(allocateId(), request, jc); + } + else + msg = new JDAPMessage(allocateId(), request); + if ( toNotify != null ) { + if (!(request instanceof JDAPAbandonRequest || + request instanceof JDAPUnbindRequest)) { + /* Only worry about toNotify if we expect a response... */ + this.m_requests.put (new Integer (msg.getId()), toNotify); + } + toNotify.setID( msg.getId() ); + } + + try { + msg.write (m_serverOutput); + m_serverOutput.flush (); + } catch (IOException e) { + throw new LDAPException ( "error writing request", + LDAPException.OTHER ); + } + } + + /** + * Register with this connection thread. + * @param conn LDAP connection + */ + public synchronized void register(LDAPConnection conn) { + if (!m_registered.contains(conn)) + m_registered.addElement(conn); + } + + void setSecurityLayer(Object layer) { + m_securityLayer = layer; + } + + synchronized int getClientCount() { + return m_registered.size(); + } + + /** + * De-Register with this connection thread. If all the connection + * is deregistered. Then, this thread should be killed. + * @param conn LDAP connection + */ + public synchronized void deregister(LDAPConnection conn) { + m_registered.removeElement(conn); + if (m_registered.size() == 0) { + try { + LDAPSearchConstraints cons = conn.getSearchConstraints(); + sendRequest (new JDAPUnbindRequest (), null, cons); + cleanUp(); + this.stop(); + this.sleep(100); /* give enough time for threads to shutdown */ + } catch (Exception e) { + LDAPConnection.printDebug(e.toString()); + } + } + } + + /** + * Clean ups before shutdown the thread. + */ + private void cleanUp() { + if (!m_disconnected) { + try { + m_serverOutput.close (); + } catch (Exception e) { + } finally { + m_serverOutput = null; + } + + try { + m_serverInput.close (); + } catch (Exception e) { + } finally { + m_serverInput = null; + } + + try { + m_socket.close (); + } catch (Exception e) { + } finally { + m_socket = null; + } + + m_disconnected = true; + m_registered = null; + m_messages = null; + m_requests.clear(); + } + } + + /** + * Reads from the LDAP server input stream for incoming LDAP messages. + */ + public void run() { + // if there is a problem of establishing connection to the server, + // stop the thread right away... + if (m_failed) + this.stop(); + + JDAPMessage msg = null; + JDAPBERTagDecoder decoder = new JDAPBERTagDecoder(); + + while (true) { + yield(); + int[] nread = new int[1]; + nread[0] = 0; + try { + BERElement element = BERElement.getElement(decoder, m_serverInput, + nread); + msg = new JDAPMessage(element); + + // passed in the ber element size to approximate the size of the cache + // entry, thereby avoiding serialization of the entry stored in the + // cache + processResponse (msg, nread[0]); + } catch (Exception e) { + networkError(e); + } + + if (m_disconnected) + break; + } + } + + /** + * Allocates a new LDAP message ID. These are arbitrary numbers used to + * correlate client requests with server responses. + * @return new unique msgId + */ + private synchronized int allocateId () { + m_highMsgId = (m_highMsgId + 1) % MAXMSGID; + return m_highMsgId; + } + + /** + * When a response arrives from the LDAP server, it is processed by + * this routine. It will pass the message on to the listening object + * associated with the LDAP msgId. + * @param incoming New message from LDAP server + */ + private synchronized void processResponse (JDAPMessage incoming, int size) { + + Integer messageID = new Integer (incoming.getId()); + LDAPResponseListener l = (LDAPResponseListener)m_requests.get (messageID); + + if (l == null) return; /* nobody is waiting for this response (!) */ + + + /* Were there any controls for this client? */ + LDAPControl[] con = checkControls( incoming ); + l.getConnection().setResponseControls( l.getThread(), con ); + + JDAPProtocolOp op = incoming.getProtocolOp (); + + Vector v = null; + + + if ((op instanceof JDAPSearchResponse) || + (op instanceof JDAPSearchResultReference)) { + + ((LDAPSearchListener)l).addSearchResult (incoming); + Long key = ((LDAPSearchListener)l).getKey(); + + if ((m_cache != null) && (key != null)) { + // get the vector containing the JDAPmessages for the specified messageID + v = (Vector)m_messages.get(messageID); + + if (v == null) + { + v = new Vector(); + // keeps track of the total size of all JDAPMessages belonging to the + // same messageID, now the size is 0 + v.addElement(new Long(0)); + } + + // add the size of the current JDAPmessage to the lump sum + // assume the size of JDAPMessage is more or less the same as the size + // of LDAPEntry. Eventually LDAPEntry object gets stored in the cache + // instead of JDAPMessage object. + long entrySize = ((Long)v.firstElement()).longValue() + size; + + // update the lump sum located in the first element of the vector + v.setElementAt(new Long(entrySize), 0); + + // convert JDAPMessage object into LDAPEntry which is stored to the + // end of the Vector + v.addElement(constructLDAPEntry(incoming)); + + // replace the entry + m_messages.put(messageID, v); + } + } else { + l.setResponse (incoming); + if (l instanceof LDAPSearchListener) { + Long key = ((LDAPSearchListener)l).getKey(); + + if (key != null) { + boolean fail = false; + JDAPProtocolOp protocolOp = incoming.getProtocolOp(); + if (protocolOp instanceof JDAPSearchResult) { + JDAPResult res = (JDAPResult)protocolOp; + if (res.getResultCode() > 0) + fail = true; + } + + if ((!fail) && (m_cache != null)) { + + // that is. Collects all the JDAPMessages for the specified messageID + // no need to keep track of this entry. Remove it. + v = (Vector)m_messages.remove(messageID); + + // If v is null, meaning there are no search results from the + // server + if (v == null) { + v = new Vector(); + + // set the entry size to be 0 + v.addElement(new Long(0)); + } + + try { + // add the new entry with key and value (a vector of + // LDAPEntry objects) + m_cache.addEntry(key, v); + } catch (LDAPException e) { + System.out.println("Exception: "+e.toString()); + } + } + } + } + m_requests.remove (messageID); + } + } + + /** + * Construct the LDAPEntry from the JDAPMessage object. + * @param msg The JDAPMessage object + * @return The LDAPEntry object required for the cache entry. + */ + private LDAPEntry constructLDAPEntry(JDAPMessage msg) { + JDAPProtocolOp op = msg.getProtocolOp(); + JDAPSearchResponse sr = (JDAPSearchResponse)op; + LDAPAttribute[] lattrs = sr.getAttributes(); + LDAPAttributeSet attrs; + if ( lattrs != null ) + attrs = new LDAPAttributeSet( lattrs ); + else + attrs = new LDAPAttributeSet(); + + String dn = sr.getObjectName(); + return(new LDAPEntry( dn, attrs )); + } + + /** + * Extract controls from message and stash them away for retrieval + * by client. + * @param response The results of an operation, possibly containing + * Controls. + */ + private LDAPControl[] checkControls( JDAPMessage response ) { + LDAPControl[] con = null; + if ( response != null ) { + JDAPControl[] jc = response.getControls(); + if ( (jc != null) && (jc.length > 0) ) { + con = new LDAPControl[jc.length]; + for( int i = 0; i < jc.length; i++ ) + con[i] = new LDAPControl( jc[i].getID(), + jc[i].isCritical(), + jc[i].getValue() ); + } + } + return con; + } + + /** + * Stop dispatching responses for a particular message ID. + * @param id Message ID for which to discard responses. + */ + void abandon (int id ) { + m_requests.remove( new Integer(id) ); + } + + /** + * Handles network errors. Basically shuts down the whole connection. + * @param e The exception which was caught while trying to read from + * input stream. + */ + private synchronized void networkError (Exception e) { + try { + + // notify each listener that the server is down. + Enumeration requests = m_requests.elements(); + while (requests.hasMoreElements()) { + LDAPResponseListener listener = + (LDAPResponseListener)requests.nextElement(); + listener.setException(new LDAPException("Server down", LDAPException.OTHER)); + } + cleanUp(); + + } catch (NullPointerException ee) { + System.err.println("Exception: "+ee.toString()); + } + + /** + * Notify all the registered about this bad moment. + * IMPORTANT: This needs to be done at last. Otherwise, the socket + * input stream and output stream might never get closed and the whole + * task will get stuck in the stop method when we tried to stop the + * LDAPConnThread. + */ + + if (m_registered != null) { + Vector registerCopy = (Vector)m_registered.clone(); + + Enumeration cancelled = registerCopy.elements(); + + while (cancelled.hasMoreElements ()) { + LDAPConnection c = (LDAPConnection)cancelled.nextElement(); + c.deregisterConnection(); + } + } + } +} + diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPControl.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPControl.java new file mode 100644 index 00000000000..581dd9b9389 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPControl.java @@ -0,0 +1,251 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import java.io.*; +import netscape.ldap.ber.stream.*; + +/** + * Represents arbitrary control data that can be used with a + * a particular LDAP operation. LDAP controls are part of version 3 + * of the LDAP protocol. + *

+ * + * LDAP controls allow you to extend the functionality of + * an LDAP operation. For example, you can use an LDAP control + * for the search operation to sort search results on an LDAP server. + *

+ * + * An LDAP control can be either a server control or + * a client control: + *

+ *

    + *
  • Server controls can be sent to the LDAP server or returned + * by the server on any operation. + *
  • Client controls are intended to affect only the client side + * of the operation. + *
+ *

+ * + * An LDAP control consists of the following information: + *

+ *

    + *
  • A unique object ID (OID) that identifies the control.

    + *

  • A "criticality" field, which indicates whether or + * not the control is critical to the operation. (If the control is + * critical to the operation and the server does not support the control, + * the server should not execute the operation.)

    + *

  • Data pertaining to the control.

    + *

+ *

+ * + * To determine which server controls are supported by a particular server, + * you need to search for the root DSE (DSA-specific entry, where DSA is + * another term for "LDAP server") and find the values of the + * supportedControl attribute. This attribute contains the + * object IDs (OIDs) of the controls supported by this server. + *

+ * + * The following section of code demonstrates how to get the list + * of the server controls supported by an LDAP server. + *

+ * + *

+ * public static void main( String[] args )
+ * {
+ *   LDAPConnection ld = new LDAPConnection();
+ *   try {
+ *     String MY_HOST = "localhost";
+ *     int MY_PORT = 389;
+ *     ld.connect( MY_HOST, MY_PORT );
+ *     try {
+ *       ld.authenticate( 3, "cn=Directory Manager", "23skidoo" );
+ *     } catch( LDAPException e ) {
+ *       System.out.println( "LDAP server does not support v3." );
+ *       ld.disconnect();
+ *       System.exit(1);
+ *     }
+ *
+ *     String MY_FILT = "(objectclass=*)";
+ *     String MY_BASE = "";
+ *     String getAttrs[] = { "supportedControl" };
+ *     LDAPSearchResults res = ld.search( MY_BASE,
+ *       LDAPConnection.SCOPE_BASE, MY_FILT, getAttrs, false );
+ *
+ *     while ( res.hasMoreElements() ) {
+ *       LDAPEntry findEntry = (LDAPEntry)res.nextElement();
+ *       LDAPAttributeSet findAttrs = findEntry.getAttributeSet();
+ *       Enumeration enumAttrs = findAttrs.getAttributes();
+ *
+ *         while ( enumAttrs.hasMoreElements() ) {
+ *           LDAPAttribute anAttr = (LDAPAttribute)enumAttrs.nextElement();
+ *           String attrName = anAttr.getName();
+ *           System.out.println( attrName );
+ *           Enumeration enumVals = anAttr.getStringValues();
+ *
+ *           while ( enumVals.hasMoreElements() ) {
+ *             String aVal = ( String )enumVals.nextElement();
+ *             System.out.println( "\t" + aVal );
+ *           }
+ *         }
+ *      }
+ *   }
+ *   catch( LDAPException e ) {
+ *     System.out.println( "Error: " + e.toString() );
+ *   }
+ *   try {
+ *     ld.disconnect();
+ *   }
+ *   catch( LDAPException e ) {
+ *     System.exit(1);
+ *   }
+ *   System.exit(0);
+ * }
+ * 
+ *

+ * + * If you compile and run this example against an LDAP server that + * supports v3 of the protocol, you might receive the following results: + *

+ * + *

+ * supportedcontrol
+ *   2.16.840.1.113730.3.4.2
+ *   2.16.840.1.113730.3.4.3
+ *   2.16.840.1.113730.3.4.4
+ *   2.16.840.1.113730.3.4.5
+ *   1.2.840.113556.1.4.473
+ * 
+ *

+ * + * For more information on LDAP controls, see the Internet-Draft on + * the LDAP v3 protocol. (Note that this internet draft is still a + * work in progress. You can find the latest draft at the ASID home page. + *

+ * + * @version 1.0 + * @see netscape.ldap.LDAPv3#CLIENTCONTROLS + * @see netscape.ldap.LDAPv3#SERVERCONTROLS + * @see netscape.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean) + * @see netscape.ldap.LDAPConnection#getOption + * @see netscape.ldap.LDAPConnection#setOption + * @see netscape.ldap.LDAPConnection#getResponseControls + * @see netscape.ldap.LDAPSearchConstraints#getClientControls + * @see netscape.ldap.LDAPSearchConstraints#getServerControls + * @see netscape.ldap.LDAPSearchConstraints#setClientControls + * @see netscape.ldap.LDAPSearchConstraints#setServerControls + */ +public class LDAPControl implements Cloneable { + public final static String MANAGEDSAIT = "2.16.840.1.113730.3.4.2"; + /* Password information sent back to client */ + public final static String PWEXPIRED = "2.16.840.1.113730.3.4.4"; + public final static String PWEXPIRING = "2.16.840.1.113730.3.4.5"; + + /** + * Default constructor for the LDAPControl class. + */ + public LDAPControl() + { + } + + /** + * Constructs a new LDAPControl object using the + * specified object ID (OID), "criticality" field, and + * data to be used by the control. + *

+ * + * @param id The object ID (OID) identifying the control. + * @param critical true if the LDAP operation should be + * cancelled when the server does not support this control (in other + * words, this control is critical to the LDAP operation). + * @param vals Control-specific data. + * @see netscape.ldap.LDAPSearchConstraints#setClientControls + * @see netscape.ldap.LDAPSearchConstraints#setServerControls + */ + public LDAPControl(String id, + boolean critical, + byte vals[]) { + m_oid = id; + m_critical = critical; + m_value = vals; + } + + /** + * Gets the object ID (OID) of the control. + * @return Object ID (OID) of the control. + */ + public String getID() { + return m_oid; + } + + /** + * Specifies whether or not the control is critical to the LDAP operation. + * @return true if the LDAP operation should be cancelled when + * the server does not support this control. + */ + public boolean isCritical() { + return m_critical; + } + + /** + * Gets the data in the control. + * @return Returns the data in the control as a byte array. + */ + public byte[] getValue() { + return m_value; + } + + /** + * Creates a copy of the control. + * @return Copy of the control. + */ + public Object clone() { + byte[] vals = null; + if ( m_value != null ) { + vals = new byte[m_value.length]; + for( int i = 0; i < m_value.length; i++ ) + vals[i] = m_value[i]; + } + LDAPControl control = new LDAPControl( m_oid, m_critical, vals ); + return control; + } + + /** + * Create a "flattened" BER encoding from a BER, + * and return it as a byte array. + * @param ber A BER encoded sequence. + * @return The byte array of encoded data. + */ + protected byte[] flattenBER( BERSequence ber ) { + /* Suck out the data and return it */ + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + try { + ber.write( outStream ); + } catch ( IOException e ) { + return null; + } + return outStream.toByteArray(); + } + + private String m_oid; + protected boolean m_critical = false; + protected byte[] m_value = null; +} + diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPDN.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPDN.java new file mode 100644 index 00000000000..8682fecd6d9 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPDN.java @@ -0,0 +1,132 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import java.util.*; +import netscape.ldap.util.*; +import java.io.*; + +/** + * Represents a distinguished name in LDAP. + *

+ * + * You can use objects of this class to split a distinguished name + * (DN) into its individual components. You can also escape the + * characters in a DN. + *

+ * + * @version 1.0 + */ +public class LDAPDN { + + /** + * Returns the individual components of a distinguished name (DN). + * @param dn Distinguished name that you want to get the components of. + * @param noTypes If true, returns only the values of the + * components and not the names (such as 'cn='). + * @return An array of strings representing the components of the DN. + * @see netscape.ldap.LDAPDN#explodeRDN(java.lang.String, boolean) + */ + public static String[] explodeDN (String dn, boolean noTypes) { + DN name = new DN(dn); + return name.explodeDN(noTypes); + } + + /** + * Returns the individual components of a relative distinguished name (RDN). + * @param rdn Relative distinguished name that you want to get the components of. + * @param noTypes If true, returns only the values of the + * components and not the names (such as 'cn='). + * @return An array of strings representing the components of the RDN. + * @see netscape.ldap.LDAPDN#explodeDN(java.lang.String, boolean) + */ + public static String[] explodeRDN (String rdn, boolean noTypes) { + RDN name = new RDN(rdn); + return name.explodeRDN(noTypes); + } + + /** + * Returns the RDN after escaping the characters specified + * by netscape.ldap.util.DN.ESCAPED_CHAR. + *

+ * + * @param rdn The RDN that you want escaped. + * @return The RDN with the characters escaped. + * @see netscape.ldap.util.DN#ESCAPED_CHAR + * @see netscape.ldap.LDAPDN#unEscapeRDN(java.lang.String) + */ + public static String escapeRDN(String rdn) { + + RDN name = new RDN(rdn); + String val = name.getValue(); + if (val == null) + return rdn; + + StringBuffer buffer = new StringBuffer(val); + + int i=0; + while (i + * + * For example, suppose an entry contains the following attributes: + *

+ * + *

+     * cn
+     * cn;lang-ja
+     * sn;phonetic;lang-ja
+     * sn;lang-us
+     * 
+ * + * If you call the getAttributeSet method and pass + * lang-ja as the argument, the method returns + * an attribute set containing the following attributes: + *

+ * + *

+     * cn;lang-ja
+     * sn;phonetic;lang-ja
+     * 
+ * + * @param subtype Semi-colon delimited list of subtypes + * that you want to find in attribute names. + *
+     *     "lang-ja"        // Only Japanese language subtypes
+     *     "binary"         // Only binary subtypes
+     *     "binary;lang-ja" // Only Japanese language subtypes
+     *                         which also are binary
+     *
+ * @return Attribute set containing the attributes that have + * the specified subtypes + * @see netscape.ldap.LDAPAttributeSet + * @see netscape.ldap.LDAPAttributeSet#getSubset + */ + public LDAPAttributeSet getAttributeSet(String subtype) { + return attrSet.getSubset(subtype); + } + + /** + * In an entry, returns the single attribute that exactly matches the + * specified attribute name. + * @param attrName Name of attribute to return. + * For example: + *
+     *     "cn"            // Only a non-subtyped version of cn
+     *     "cn;lang-ja"    // Only a Japanese version of cn, will not
+     *                     // return "cn;lang-ja-JP-kanji", for example
+     *
+ * @return Attribute in the current entry that has exactly the same name, + * or null (if no attribute in the entry matches the specified name). + * @see netscape.ldap.LDAPAttribute + */ + public LDAPAttribute getAttribute(String attrName) { + return attrSet.getAttribute(attrName); + } + + /** + * Returns the subtype that matches "attrName" and that best matches + * a language specification "lang". If there are subtypes other than + * "lang" subtypes included in attrName, e.g. "cn;binary", only + * attributes with all of those subtypes are returned. If lang is + * null or empty, the method behaves as getAttribute(attrName). If + * there are no matching attributes, null is returned. + * + * Example:
+     *  Assume the entry contains only the following attributes:
+     *     cn;lang-en
+     *     cn;lang-ja-JP-kanji
+     *     sn
+     *  getAttribute( "cn" ) returns null.
+     *  getAttribute( "sn" ) returns the "sn" attribute.
+     *  getAttribute( "cn", "lang-en-us" ) returns the "cn;lang-en" attribute.
+     *  getAttribute( "cn", "lang-en" ) returns the "cn;lang-en" attribute.
+     *  getAttribute( "cn", "lang-ja" ) returns null.
+     *  getAttribute( "sn", "lang-en" ) returns the "sn" attribute.
+     *
+ *

+ * @param attrName Name of attribute to find in the entry. + * @param lang A language specification (for example, lang-en). + * @return The attribute that matches the base name and that best + * matches any specified language subtype. + * @see netscape.ldap.LDAPAttribute + */ + public LDAPAttribute getAttribute( String attrName, String lang ) { + return attrSet.getAttribute( attrName, lang ); + } + + /** + * Retrieves the string representation of the entry's + * distinguished name (DN) and its attributes. + * For example: + * + *

+     * LDAPEntry: uid=bjensen, ou=People, o=airius.com; LDAPAttributeSet:
+     * LDAPAttribute {type='cn', values='Barbara Jensen,Babs Jensen'}
+     * LDAPAttribute {type='sn', values='Jensen'}LDAPAttribute {type='givenname',
+     * values='Barbara'}LDAPAttribute {type='objectclass', values='top,person,
+     * organizationalPerson,inetOrgPerson'}LDAPAttribute {type='ou',
+     * values='Product Development,People'}
+     * 
+ * + * @return String representation of the entry's DN and its attributes. + */ + public String toString() { + String s = "LDAPEntry: "; + if ( dn != null ) + s += dn + "; "; + if ( attrSet != null ) + s += attrSet.toString(); + return s; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPEntryComparator.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPEntryComparator.java new file mode 100644 index 00000000000..5495b326db2 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPEntryComparator.java @@ -0,0 +1,62 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +/** + * The LDAPEntryComparator interface represents the + * algorithm used to sort the search results. This interface specifies + * one method, isGreater, which compares two entries and + * determines the order in which the two entries should be sorted. + *

+ * + * The netscape.ldap package includes a class that + * implements this interface. The LDAPCompareAttrNames + * class represents a comparator that sorts the two entries alphabetically, + * based on the value of one or more attributes. + *

+ * + * When calling the sort method of the + * LDAPSearchResults class, you need to specify + * a class that implements the LDAPEntryComparator + * interface. + *

+ * + * @version 1.0 + * @see netscape.ldap.LDAPCompareAttrNames + * @see netscape.ldap.LDAPSearchResults#sort + */ +public interface LDAPEntryComparator { + + /** + * Specifies the algorithm used to + * compare entries when sorting search results. + *

+ * + * isGreater returns true + * if the entry specified in the first argument should + * be sorted before the entry specified in the second + * argument. + *

+ * + * @version 1.0 + * @see netscape.ldap.LDAPCompareAttrNames + * @see netscape.ldap.LDAPSearchResults#sort + */ + public boolean isGreater (LDAPEntry greater, LDAPEntry less); + +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPException.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPException.java new file mode 100644 index 00000000000..e1bfb1edf05 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPException.java @@ -0,0 +1,883 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import java.util.*; +import netscape.ldap.client.*; +import netscape.ldap.client.opers.*; +import java.io.*; + +/** + * Indicates that an error has occurred. An LDAPException + * can result from physical problems (such as network errors) as well as + * problems with LDAP operations (for example, if the LDAP add operation + * fails because of duplicate entry). + *

+ * + * Most errors that occur throw this type of exception. In order to determine + * the cause of the error, you can call the getLDAPResultCode() + * method to get the specific result code and compare this code against + * the result codes defined as fields in this class. (For example, if + * the result code matches the value of the field + * LDAPException.TIME_LIMIT_EXCEEDED, the time limit passed + * before the search operation could be completed.) + *

+ * + * This exception includes methods for getting an error message that + * corresponds to the LDAP result code (for example, "Timelimit exceeded" + * for LDAPException.TIME_LIMIT_EXCEEDED). These error + * messages are specified in the following files: + *

netscape/ldap/errors/ErrorCodes_locale_string.props
+ * where locale_string is the name of the locale that includes + * the language and country, but not the variant. + *

+ * + * For example: + *

netscape/ldap/errors/ErrorCodes_en_US.props
+ * + * The LDAP Java classes get this locale name by calling the + * java.util.Locale.toString method for the specified + * locale and ignoring the variant. If no locale is specified, the + * LDAP Java classes use the java.util.Locale.getDefault + * method to get the locale of the local host system. + *

+ * + * In order to get error messages for different locales, you need to + * provide files containing the error messages for those locales. + * The files should be located in the netscape/ldap/errors + * directory and should use the naming convention specified above. + *

+ * + * The following is a list of LDAP result codes: + *

+ * Result
+ *  Code   Defined Value
+ * ======  =============
+ *   0     SUCCESS
+ *   1     OPERATION_ERROR
+ *   2     PROTOCOL_ERROR
+ *   3     TIME_LIMIT_EXCEEDED
+ *   4     SIZE_LIMIT_EXCEEDED
+ *   5     COMPARE_FALSE
+ *   6     COMPARE_TRUE
+ *   7     AUTH_METHOD_NOT_SUPPORTED
+ *   8     STRONG_AUTH_REQUIRED
+ *   9     LDAP_PARTIAL_RESULTS
+ *  10     REFERRAL (LDAP v3)
+ *  11     ADMIN_LIMIT_EXCEEDED (LDAP v3)
+ *  12     UNAVAILABLE_CRITICAL_EXTENSION (LDAP v3)
+ *  13     CONFIDENTIALITY_REQUIRED (LDAP v3)
+ *  14     SASL_BIND_IN_PROGRESS (LDAP v3)
+ *  16     NO_SUCH_ATTRIBUTE
+ *  17     UNDEFINED_ATTRIBUTE_TYPE
+ *  18     INAPPROPRIATE_MATCHING
+ *  19     CONSTRAINT_VIOLATION
+ *  20     ATTRIBUTE_OR_VALUE_EXISTS
+ *  21     INVALID_ATTRIBUTE_SYNTAX
+ *  32     NO_SUCH_OBJECT
+ *  33     ALIAS_PROBLEM
+ *  34     INVALID_DN_SYNTAX
+ *  35     IS_LEAF
+ *  36     ALIAS_DEREFERENCING_PROBLEM
+ *  48     INAPPROPRIATE_AUTHENTICATION
+ *  49     INVALID_CREDENTIALS
+ *  50     INSUFFICIENT_ACCESS_RIGHTS
+ *  51     BUSY
+ *  52     UNAVAILABLE
+ *  53     UNWILLING_TO_PERFORM
+ *  54     LOOP_DETECT
+ *  64     NAMING_VIOLATION
+ *  65     OBJECT_CLASS_VIOLATION
+ *  66     NOT_ALLOWED_ON_NONLEAF
+ *  67     NOT_ALLOWED_ON_RDN
+ *  68     ENTRY_ALREADY_EXISTS
+ *  69     OBJECT_CLASS_MODS_PROHIBITED
+ *  71     AFFECTS_MULTIPLE_DSAS (LDAP v3)
+ *  80     OTHER
+ *  81     SERVER_DOWN
+ *  89     PARAM_ERROR
+ *  91     CONNECT_ERROR
+ *  92     LDAP_NOT_SUPPORTED
+ *  93     CONTROL_NOT_FOUND
+ *  94     NO_RESULTS_RETURNED
+ *  95     MORE_RESULTS_TO_RETURN
+ *  96     CLIENT_LOOP
+ *  97     REFERRAL_LIMIT_EXCEEDED
+ * 
+ *

+ * + * @version 1.0 + * @see netscape.ldap.LDAPReferralException + */ +public class LDAPException extends java.lang.Exception { + + /** + * (0) The operation completed successfully. + */ + public final static int SUCCESS = 0; + + /** + * (1) An internal error occurred in the LDAP server. + */ + public final static int OPERATION_ERROR = 1; + + /** + * (2) A LDAP server could not correctly interpret the request + * sent by your client because the request does not strictly + * comply with the LDAP protocol. (For example, the data + * was not correctly BER-encoded, or a specified value -- such + * as the search scope or modification type -- does not + * comply with the LDAP protocol. If you invent your own + * search scope, for instance, this result code might be returned.

+ */ + public final static int PROTOCOL_ERROR = 2; + + /** + * (3) The search operation could not be completed within + * the maximum time limit. You can specify the maximum time + * limit by calling the LDAPConnection.setOption + * method or the LDAPSearchConstraints.setTimeLimit + * method.

+ * + * @see netscape.ldap.LDAPConnection@setOption + * @see netscape.ldap.LDAPSearchConstraints@setTimeLimit + */ + public final static int TIME_LIMIT_EXCEEDED = 3; + + /** + * (4) The search found more than the maximum number of results. + * You can specify the maximum number of results by calling the + * LDAPConnection.setOption method or the + * LDAPSearchConstraints.setSizeLimit method.

+ * + * @see netscape.ldap.LDAPConnection#setOption + * @see netscape.ldap.LDAPSearchConstraints#setMaxResults + */ + public final static int SIZE_LIMIT_EXCEEDED = 4; + + /** + * (5) Value returned by an LDAP compare operation if the + * specified attribute and value is not found in the entry + * (no matching value found). + * + * @see netscape.ldap.LDAPConnection#compare + */ + public final static int COMPARE_FALSE = 5; + + /** + * (6) Value returned by an LDAP compare operation if the + * specified attribute and value is found in the entry + * (matching value found). + * + * @see netscape.ldap.LDAPConnection#compare + */ + public final static int COMPARE_TRUE = 6; + + /** + * (7) The specified authentication method is not supported + * by the LDAP server that you are connecting to. The + * LDAPConnection class is implemented so that + * LDAPConnection.authenticate always + * uses the LDAP_AUTH_SIMPLE method of authentication. + * (LDAPConnection.authenticate does not + * allow you to select the method of authentication.)

+ */ + public final static int AUTH_METHOD_NOT_SUPPORTED = 7; + + /** + * (8) A stronger authentication method (more than LDAP_AUTH_SIMPLE) + * is required by the LDAP server that you are connecting to. + * The LDAPConnection class is implemented so that + * LDAPConnection.authenticate always + * uses the LDAP_AUTH_SIMPLE method of authentication. + * (LDAPConnection.authenticate does not + * allow you to select the method of authentication.)

+ */ + public final static int STRONG_AUTH_REQUIRED = 8; + + /** + * (9) The LDAP server is referring your client to another + * LDAP server. If you set up the LDAPConnection + * options or the LDAPSearchConstraints options + * for automatic referral, your client will automatically + * connect and authenticate to the other LDAP server. + * (This LDAPException will not be raised.) + *

+ * + * (To set up automatic referrals in an LDAPConnection + * object, set the LDAPConnection.REFERRALS option + * to true and the LDAPConnection.REFERRALS_REBIND_PROC + * option to the object containing the method for retrieving + * authentication information (in other words, the distinguished + * name and password to use when authenticating to other LDAP servers). + *

+ * + * If instead you set LDAPConnection.REFERRALS + * to false (or if you set + * LDAPSearchConstraints.setReferrals to false, + * an LDAPReferralException is raised. + *

+ * + * If an error occurs during the referral process, an + * LDAPException with this result code + * (LDAP_PARTIAL_RESULTS) is raised. + *

+ * + * @see netscape.ldap.LDAPConnection#setOption + * @see netscape.ldap.LDAPSearchConstraints#setReferrals + * @see netscape.ldap.LDAPSearchConstraints#setRebindProc + * @see netscape.ldap.LDAPRebind + * @see netscape.ldap.LDAPRebindAuth + * @see netscape.ldap.LDAPReferralException + */ + public final static int LDAP_PARTIAL_RESULTS = 9; + + /** + * (10) [LDAP v3] The server does not hold the requested entry. + * The referral field of the server's response contains a + * reference to another server (or set of servers), which + * your client can access through LDAP or other protocols. + * Typically, these references are LDAP URLs that identify + * the server that may contain the requested entry. + *

+ * + * When this occurs, a LDAPReferralException + * is thrown. You can catch this exception and call the + * getURLs method to get the list of LDAP + * URLs from the exception. + *

+ * + * @see netscape.ldap.LDAPReferralException + */ + public final static int REFERRAL = 10; + + /** + * (11) [LDAP v3] The adminstrative limit on the + * maximum number of entries to return was exceeded. + * In the Netscape Directory Server 3.0, this + * corresponds to the "look through limit" for + * the server. This is the maximum number of + * entries that the server will check through + * when determining which entries match the + * search filter and scope. + *

+ */ + public final static int ADMIN_LIMIT_EXCEEDED = 11; + + /** + * (12) [LDAP v3] The server received an LDAP v3 control + * that is marked critical and either (1) is not + * recognized or supported by the server, or + * (2) is inappropriate for the operation requested. + * The Netscape Directory Server 3.0 also returns + * this result code if the client specifies a + * matching rule that is not supported by the server. + *

+ * + * @see netscape.ldap.LDAPControl + */ + public final static int UNAVAILABLE_CRITICAL_EXTENSION = 12; + + /** + * (13) [LDAP v3] A secure connection is required for + * this operation. + */ + public final static int CONFIDENTIALITY_REQUIRED = 13; + + /** + * (14) [LDAP v3] While authenticating your client + * by using a SASL (Simple Authentication Security Layer) + * mechanism, the server requires the client to send + * a new SASL bind request (specifying the same SASL + * mechanism) to continue the authentication process. + */ + public final static int SASL_BIND_IN_PROGRESS = 14; + + /** + * (16) The specified attribute could not be found. + */ + public final static int NO_SUCH_ATTRIBUTE = 16; + + /** + * (17) The specified attribute is not defined. + */ + public final static int UNDEFINED_ATTRIBUTE_TYPE = 17; + + /** + * (18) An inappropriate type of matching was used. + */ + public final static int INAPPROPRIATE_MATCHING = 18; + + /** + * (19) An internal error occurred in the LDAP server. + */ + public final static int CONSTRAINT_VIOLATION = 19; + + /** + * (20) The value that you are adding to an attribute + * already exists in the attribute. + */ + public final static int ATTRIBUTE_OR_VALUE_EXISTS = 20; + + /** + * (21) The request contains invalid syntax. + */ + public final static int INVALID_ATTRIBUTE_SYNTAX = 21; + + /** + * (32) The entry specified in the request does not exist. + */ + public final static int NO_SUCH_OBJECT = 32; + + /** + * (33) An problem occurred with an alias. + */ + public final static int ALIAS_PROBLEM = 33; + + /** + * (34) The specified distinguished name (DN) uses invalid syntax. + */ + public final static int INVALID_DN_SYNTAX = 34; + + /** + * (35) The specified entry is a "leaf" entry (it has no entries + * beneath it in the directory tree). + */ + public final static int IS_LEAF = 35; + + /** + * (36) An error occurred when dereferencing an alias. + */ + public final static int ALIAS_DEREFERENCING_PROBLEM = 36; + + /** + * (48) The authentication presented to the server is inappropriate. + * This result code might occur, for example, if your client + * presents a password and the corresponding entry has no + * userpassword attribute. + */ + public final static int INAPPROPRIATE_AUTHENTICATION = 48; + + /** + * (49) The credentials presented to the server for authentication + * are not valid. (For example, the password sent to the server + * does not match the user's password in the directory.) + */ + public final static int INVALID_CREDENTIALS = 49; + + /** + * (50) The client is authenticated as a user who does not have the + * access privileges to perform this operation. + */ + public final static int INSUFFICIENT_ACCESS_RIGHTS = 50; + + /** + * (51) The LDAP server is busy. + */ + public final static int BUSY = 51; + + /** + * (52) The LDAP server is unavailable. + */ + public final static int UNAVAILABLE = 52; + + /** + * (53) The LDAP server is unable to perform the specified operation. + */ + public final static int UNWILLING_TO_PERFORM = 53; + + /** + * (54) A loop has been detected. + */ + public final static int LOOP_DETECT = 54; + + /** + * (60) The "server-side sorting" control + * was not included with the "virtual list view" + * control in the search request. + */ + public final static int SORT_CONTROL_MISSING = 60; + + /** + * (61) An index range error occurred. + */ + public final static int INDEX_RANGE_ERROR = 61; + + /** + * (64) A naming violation has occurred. + */ + public final static int NAMING_VIOLATION = 64; + + /** + * (65) The requested operation will add or change + * data so that the data no longer complies with + * the schema. + */ + public final static int OBJECT_CLASS_VIOLATION = 65; + + /** + * (66) The requested operation can only be performed + * on an entry that has no entries beneath it in the + * directory tree (in other words, a "leaf" entry). + *

+ * + * For example, you cannot delete or rename an entry + * if the entry has subentries beneath it. + *

+ */ + public final static int NOT_ALLOWED_ON_NONLEAF = 66; + + /** + * (67) The specified operation cannot be performed on + * a relative distinguished name (RDN). + */ + public final static int NOT_ALLOWED_ON_RDN = 67; + + /** + * (68) The specified entry already exists. You might receive + * this error if, for example, you attempt to add an entry + * that already exists or if you attempt to change the name + * of an entry to the name of an entry that already exists. + */ + public final static int ENTRY_ALREADY_EXISTS = 68; + + /** + * (69) You cannot modify the specified object class. + */ + public final static int OBJECT_CLASS_MODS_PROHIBITED = 69; + + /** + * (71) [LDAP v3] The client attempted to move an entry + * from one LDAP server to another by requesting a "modify + * DN" operation. In general, clients should not be able + * to arbitrarily move entries and subtrees between servers. + *

+ * + * @see netscape.ldap.LDAPConnection#rename(java.lang.String, java.lang.String, java.lang.String, boolean) + * @see netscape.ldap.LDAPConnection#rename(java.lang.String, java.lang.String, java.lang.String, boolean, LDAPSearchConstraints) + */ + public final static int AFFECTS_MULTIPLE_DSAS = 71; + + /** + * (80) General result code for other types of errors + * that may occur. + */ + public final static int OTHER = 80; + + /** + * (81) The LDAP server cannot be contacted. + */ + public final static int SERVER_DOWN = 0x51; + + /** + * (89) When calling a constructor or method from your client, + * one or more parameters were incorrectly specified. + */ + public final static int PARAM_ERROR = 0x59; + + /** + * (91) Your LDAP client failed to connect to the LDAP server. + */ + public final static int CONNECT_ERROR = 0x5b; + + /** + * (92) The request is not supported by this version of the LDAP protocol. + */ + public final static int LDAP_NOT_SUPPORTED = 0x5c; + + /** + * (93) The requested control is not found. + *

+ * + * @see netscape.ldap.LDAPControl + */ + public final static int CONTROL_NOT_FOUND = 0x5d; + + /** + * (94) No results have been returned from the server. + */ + public final static int NO_RESULTS_RETURNED = 0x5e; + + /** + * (95) More results are being returned from the server. + */ + public final static int MORE_RESULTS_TO_RETURN = 0x5f; + + /** + * (96) Your LDAP client detected a loop in the referral. + */ + public final static int CLIENT_LOOP = 0x60; + + /** + * (97) The number of sequential referrals (for example, + * the client may be referred first from LDAP server A to + * LDAP server B, then from LDAP server B to LDAP server C, + * and so on) has exceeded the maximum number of referrals + * (the LDAPv2.REFERRALS_HOP_LIMIT option). + *

+ * + * @see netscape.ldap.LDAPv2#REFERRALS_HOP_LIMIT + * @see netscape.ldap.LDAPConnection#getOption + * @see netscape.ldap.LDAPConnection#setOption + */ + public final static int REFERRAL_LIMIT_EXCEEDED = 0x61; + + /** + * Internal variables + */ + private int resultCode = -1; + private String errorMessage = null; + private String matchedDN = null; + private Locale m_locale = Locale.getDefault(); + private static Hashtable cacheResource = new Hashtable(); + private static final String baseName = "netscape/ldap/errors/ErrorCodes"; + + /** + * Constructs a default exception with no specific error information. + */ + public LDAPException() { + } + + /** + * Constructs a default exception with a specified string of + * additional information. This string appears if you call + * the toString() method. + *

+ * + * This form is used for lower-level errors. + * It is recommended that you always use one of the constructors + * that takes a result code as a parameter. (If your exception is + * thrown, any code that catches the exception may need to extract + * the result code from the exception.) + *

+ * @param message The additional error information. + * @see netscape.ldap.LDAPException#toString() + */ + public LDAPException( String message ) { + super( message ); + } + + /** + * Constructs a default exception with a result code and + * a specified string of additional information. This string + * appears if you call the toString() method. + * The result code that you set is accessible through the + * getLDAPResultCode() method. + *

+ * + * @param message The additional error information that you + * want to specify. + * @param resultCode The result code returned from the + * operation that caused this exception. + * @see netscape.ldap.LDAPException#toString() + * @see netscape.ldap.LDAPException#getLDAPResultCode() + */ + public LDAPException( String message, int resultCode ) { + super( message ); + this.resultCode = resultCode; + } + + /** + * Constructs a default exception with a result code, a specified + * string of additional information, and a string containing + * information passed back from the server. + *

+ * + * After you construct the LDAPException object, + * the result code and messages will be accessible through the + * following ways: + *

+ *

    + *
  • The first string of additional information appears if you + * call the toString() method.

    + *

  • The result code that you set is accessible through the + * getLDAPResultCode() method.

    + *

  • The string of server error information that you set + * is accessible through the getLDAPErrorMessage + * method.

    + *

+ *

+ * + * Use this form of the constructor + * for higher-level LDAP operational errors. + * @param message The additional error information that you + * want to specify. + * @param resultCode The result code returned from the + * operation that caused this exception. + * @param serverErrorMessage Error message specifying additional + * information returned from the server. + * @see netscape.ldap.LDAPException#toString() + * @see netscape.ldap.LDAPException#getLDAPResultCode() + * @see netscape.ldap.LDAPException#getLDAPErrorMessage() + */ + public LDAPException( String message, int resultCode, + String serverErrorMessage ) { + super( message ); + this.resultCode = resultCode; + this.errorMessage = serverErrorMessage; + } + + /** + * Constructs a default exception with a result code, a specified + * string of additional information, a string containing + * information passed back from the server, and the DN of the + * closest matching entry, if the exception was thrown because + * an entry could not be found (for example, if cn=Babs Jensen, + * ou=People, c=Airius.com could not be found but + * ou=People, c=Airius.com is a valid directory entry, + * the "matched DN" is ou=People, c=Airius.com. + *

+ * + * After you construct the LDAPException object, + * the result code and messages will be accessible through the + * following ways: + *

+ *

    + *
  • This string of additional information appears if you + * call the toString() method.

    + *

  • The result code that you set is accessible through the + * getLDAPResultCode() method.

    + *

  • The string of server error information that you set + * is accessible through the getLDAPErrorMessage + * method.

    + *

  • The matched DN that you set is accessible through the + * getMatchedDN method.

    + *

+ *

+ * + * This form is used for higher-level LDAP operational errors. + * @param message The additional error information. + * @param resultCode The result code returned. + * @param serverErrorMessage Error message specifying additional information + * returned from the server. + * @param matchedDN Maximal subset of a specified DN which could be + * matched by the server. + * @see netscape.ldap.LDAPException#toString() + * @see netscape.ldap.LDAPException#getLDAPResultCode() + * @see netscape.ldap.LDAPException#getLDAPErrorMessage() + * @see netscape.ldap.LDAPException#getMatchedDN() + */ + public LDAPException( String message, int resultCode, + String serverErrorMessage, String matchedDN ) { + super( message ); + this.resultCode = resultCode; + this.errorMessage = serverErrorMessage; + this.matchedDN = matchedDN; + } + + /** + * Returns the result code from the last error that occurred. + * This result code is defined as a public final static int member + * of this class. Note that this value is not always valid. + * -1 indicates that the result code is invalid. + * @return The LDAP result code of the last operation. + */ + public int getLDAPResultCode () { + return resultCode; + } + + /** + * Returns the error message from the last error, if this message + * is available (that is, if this message was set). If the message + * was not set, this method returns null. + *

+ * + * Note that this message is rarely set. (In order to set this message, + * the code constructing this exception must have called the constructor + * LDAPException(String, int, String). The last argument, + * which is additional error information returned from the server, + * is the string returned by getLDAPErrorMessage. + *

+ * + * In most cases, if you want information about + * the error generated, you should call the toString() + * method instead. + *

+ * + * @return The error message of the last error (or null + * if no message was set). + * @see netscape.ldap.LDAPException#toString() + */ + public String getLDAPErrorMessage () { + return errorMessage; + } + + /** + * Returns the maximal subset of a DN which could be matched by the + * server, if the server returned one of the following errors: + *

    + *
  • NO_SUCH_OBJECT + *
  • ALIAS_PROBLEM + *
  • INVALID_DN_SYNTAX + *
  • ALIAS_DEREFERENCING_PROBLEM + *
+ * + * For example, if the DN cn=Babs Jensen, o=People, c=Airius.com + * could not be found by the DN o=People, c=Airius.com + * could be found, the matched DN is + * o=People, c=Airius.com. + *

+ * + * If the exception does not specify a matching DN, + * this method returns null. + * @return The maximal subset of a DN which could be matched, + * or null if the error is not one of the above. + */ + public String getMatchedDN () { + return matchedDN; + } + + /** + * Gets the string representation of the exception, which + * includes the result code, the message sent back from + * the LDAP server, the portion of the DN that the server + * could find in the directory (if applicable), and the + * error message corresponding to this result code. + *

+ * + * For example: + * + *

netscape.ldap.LDAPException: error result (32); server error message; matchedDN = ou=people,o=airius.com; No such object
+ * + * In this example, error result is the string of + * additional information specified in the exception, 32 is + * the result code, server error message is the additional + * information from the server specified in the exception, the + * matched DN is ou=people,o=airius.com, and the error message + * corresponding to the result code 32 is No such + * object. + *

+ * + * The error message corresponding to the error code can also be + * retrieved by using the errorCodeToString method. + * Note that this method can generate error messages specific to + * a current locale. + *

+ * + * @return String representation of exception + * @see netscape.ldap.LDAPException#errorCodeToString(code) + */ + public String toString() { + String str = super.toString() + " (" + resultCode + ")" ; + if ( (errorMessage != null) && (errorMessage.length() > 0) ) + str += "; " + errorMessage; + if ( (matchedDN != null) && (matchedDN.length() > 0) ) + str += "; matchedDN = " + matchedDN; + String errorStr = null; + if (((errorStr = errorCodeToString(m_locale)) != null) && + (errorStr.length() > 0)) + str += "; " + errorStr; + return str; + } + + /** + * Returns the error message describing the error code (for this + * exception). The error message is specific to the default locale + * for this system. (The LDAP Java classes determine the default + * locale by calling the java.util.Locale.getDefault + * method and retrieve the error messages from the following file: + *

netscape/ldap/error/ErrorCodes_locale_name.props
+ * where locale_name is the language and country (concatenated + * and delimited by an underscore) of the default locale. For example: + *
netscape/ldap/error/ErrorCodes_en_US.props
+ * + * @return The error message describing the error code for this + * exception in the default locale + */ + public String errorCodeToString() { + return errorCodeToString(resultCode, m_locale); + } + + /** + * Returns the error message describing the error code for this + * exception. The error message for the specified locale is retrieved + * from the following file: + *
netscape/ldap/error/ErrorCodes_locale_name.props
+ * where locale_name is the language and country (concatenated + * and delimited by an underscore) of the default locale. For example: + *
netscape/ldap/error/ErrorCodes_en_US.props
+ * + * @param l The java.util.Locale object representing the + * locale of the error message that you want to retrieve. + * @return The error message describing the current error code + * in the specified locale. + */ + public String errorCodeToString(Locale l) { + return errorCodeToString(resultCode, l); + } + + /** + * Returns the error message describing the specified error code. + * The error message is specific to the default locale + * for this system. (The LDAP Java classes determine the default + * locale by calling the java.util.Locale.getDefault + * method and retrieve the error messages from the following file: + *
netscape/ldap/error/ErrorCodes_locale_name.props
+ * where locale_name is the language and country (concatenated + * and delimited by an underscore) of the default locale. For example: + *
netscape/ldap/error/ErrorCodes_en_US.props
+ * + * @param code The error code that you want to get the + * corresponding error message for. + * @return Error message describing the specified error code for + * the default locale. + */ + public static String errorCodeToString(int code) { + return errorCodeToString(code, Locale.getDefault()); + } + + /** + * Returns the error message describing the specified error code. + * The error message for the specified locale is retrieved from + * the following file: + *
netscape/ldap/error/ErrorCodes_locale_name.props
+ * where locale_name is the language and country (concatenated + * and delimited by an underscore) of the default locale. For example: + *
netscape/ldap/error/ErrorCodes_en_US.props
+ * + * @param code The error code that you want to get the + * corresponding error message for. + * @param locale The java.util.Locale object representing the + * locale of the error message that you want to retrieve. + * @return Error message describing the specified error code for + * the specified locale. + */ + public synchronized static String errorCodeToString(int code, Locale locale) { + try { + String localeStr = locale.toString(); + PropertyResourceBundle p = + (PropertyResourceBundle)cacheResource.get(localeStr); + + if (p == null) { + p = LDAPResourceBundle.getBundle(baseName); + + if (p != null) + cacheResource.put(localeStr, p); + } + + if (p != null) { + return (String)p.handleGetObject(Integer.toString(code)); + } + } catch (IOException e) { + System.out.println("Cannot open resource file for LDAPException "+ + baseName); + } + + return null; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPExtendedOperation.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPExtendedOperation.java new file mode 100644 index 00000000000..9c129c767f8 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPExtendedOperation.java @@ -0,0 +1,152 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +/** + * Version 3 of the LDAP protocol include the means to define additional + * operations ("extended operations") beyond the standard LDAP + * operations. An LDAP v3 client can send an extended operation request, + * identifying the operation by its unique object ID (OID). The server + * receives the request and if OID corresponds to an operation supported + * by the server, the server procoess the request and sends an extended + * operation response back to the client. + *

+ * + * Objects of this class can be used to represent extended operation + * requests (sent by your client) or extended operation responses + * (returned by an LDAP v3 server). + *

+ * + * To determine which extended operations are supported by a server, + * you need to search for the root DSE (DSA-specific entry, where DSA is + * another term for "LDAP server") and find the values of the + * supportedExtension attribute. This attribute contains the + * object IDs (OIDs) of the extended operations supported by this server. + *

+ * + * The following section of code demonstrates how to get the list + * of the extended operations supported by an LDAP server. + *

+ * + *

+ * public static void main( String[] args )
+ * {
+ *   LDAPConnection ld = new LDAPConnection();
+ *   try {
+ *     String MY_HOST = "localhost";
+ *     int MY_PORT = 389;
+ *     ld.connect( MY_HOST, MY_PORT );
+ *     try {
+ *       ld.authenticate( 3, "cn=Directory Manager", "23skidoo" );
+ *     } catch( LDAPException e ) {
+ *       System.out.println( "LDAP server does not support v3." );
+ *       ld.disconnect();
+ *       System.exit(1);
+ *     }
+ *
+ *     String MY_FILT = "(objectclass=*)";
+ *     String MY_BASE = "";
+ *     String getAttrs[] = { "supportedExtension" };
+ *     LDAPSearchResults res = ld.search( MY_BASE,
+ *       LDAPConnection.SCOPE_BASE, MY_FILT, getAttrs, false );
+ *
+ *     while ( res.hasMoreElements() ) {
+ *       LDAPEntry findEntry = (LDAPEntry)res.nextElement();
+ *       LDAPAttributeSet findAttrs = findEntry.getAttributeSet();
+ *       Enumeration enumAttrs = findAttrs.getAttributes();
+ *
+ *         while ( enumAttrs.hasMoreElements() ) {
+ *           LDAPAttribute anAttr = (LDAPAttribute)enumAttrs.nextElement();
+ *           String attrName = anAttr.getName();
+ *           System.out.println( attrName );
+ *           Enumeration enumVals = anAttr.getStringValues();
+ *
+ *           while ( enumVals.hasMoreElements() ) {
+ *             String aVal = ( String )enumVals.nextElement();
+ *             System.out.println( "\t" + aVal );
+ *           }
+ *         }
+ *      }
+ *   }
+ *   catch( LDAPException e ) {
+ *     System.out.println( "Error: " + e.toString() );
+ *   }
+ *   try {
+ *     ld.disconnect();
+ *   }
+ *   catch( LDAPException e ) {
+ *     System.exit(1);
+ *   }
+ *   System.exit(0);
+ * }
+ * 
+ *

+ * + * If you compile and run this example against an LDAP server that + * supports v3 of the protocol, you might receive the following results: + *

+ * + *

+ * supportedextension
+ *   1.2.3.4
+ * 
+ *

+ * + * For more information on LDAP controls, see the Internet-Draft on + * the LDAP v3 protocol. (Note that this internet draft is still a + * work in progress. You can find the latest draft at the ASID home page. + *

+ * + * @version 1.0 + * @see netscape.ldap.LDAPConnection#extendedOperation(netscape.ldap.LDAPExtendedOperation) + * @see netscape.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean) + * + */ +public class LDAPExtendedOperation { + + /** + * Construct an object + * @param oid Identifier for the particular operation. + * @param vals Operation-specific data. + */ + public LDAPExtendedOperation( String oid, byte[] vals ) { + m_oid = oid; + m_vals = vals; + } + + /** + * Get the identifier for this operation. + * @return oid Identifier for the particular operation. + */ + public String getID() { + return m_oid; + } + + /** + * Get the data for this operation. + * @return vals Operation-specific data. + */ + public byte[] getValue() { + return m_vals; + } + + private String m_oid; + private byte[] m_vals; +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPMatchingRuleSchema.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPMatchingRuleSchema.java new file mode 100644 index 00000000000..c6ce14709cc --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPMatchingRuleSchema.java @@ -0,0 +1,319 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import java.util.*; + +/** + * The definition of a matching rule in the schema. + * RFC 2252, Lightweight Directory Access Protocol (v3): + * Attribute Syntax Definitions covers the types of information + * that need to be specified in the definition of a matching rule. + * According to the RFC, the description of a matching rule can + * include the following information: + *

+ * + *

    + *
  • an OID identifying the matching rule + *
  • a name identifying the matching rule + *
  • a description of the matching rule + *
  • the syntax of the matching rule + *
+ *

+ * + * The LDAPMatchingRuleSchema class also specifies + * the matching rule "use description", which describes the + * attributes which can be used with the matching rule. + *

+ * + * When you construct an LDAPMatchingRuleSchema object, you can + * specify these types of information as arguments to the constructor or + * in the MatchingRuleDescription and MatchingRuleUseDescription formats + * specified in RFC 2252. + * (When an LDAP client searches an LDAP server for the schema, the server + * returns schema information as an object with attribute values in this + * format.) + *

+ * + * You can get the name, OID, and description of this matching rule + * definition by using the getName, getOID, and + * getDescription methods inherited from the abstract class + * LDAPSchemaElement. + *

+ * + * If you need to add or remove this matching rule definition from the + * schema, you can use the add and remove + * methods, which this class inherits from the LDAPSchemaElement + * abstract class. + *

+ * + * @version 1.0 + * @see netscape.ldap.LDAPSchemaElement + **/ + +public class LDAPMatchingRuleSchema extends LDAPAttributeSchema { + /** + * Construct a matching rule definition, using the specified + * information. + * @param name Name of the matching rule. + * @param oid Object identifier (OID) of the matching rule + * in dotted-string format (for example, "1.2.3.4"). + * @param description Description of the matching rule. + * @param attributes Array of the OIDs of the attributes for which + * the matching rule is applicable. + * @param syntax Syntax of this matching rule. The value of this + * argument can be one of the following: + *

    + *
  • cis (case-insensitive string) + *
  • ces (case-exact string) + *
  • binary (binary data) + *
  • int (integer) + *
  • telephone (telephone number -- identical to cis, + * but blanks and dashes are ignored during comparisons) + *
  • dn (distinguished name) + *
+ */ + public LDAPMatchingRuleSchema( String name, String oid, String description, + String[] attributes, int syntax ) { + super( name, oid, description, syntax, true ); + attrName = "matchingrules"; + this.attributes = new String[attributes.length]; + for( int i = 0; i < attributes.length; i++ ) + this.attributes[i] = new String( attributes[i] ); + } + + /** + * Constructs a matching rule definition based on descriptions in + * the MatchingRuleDescription format and MatchingRuleUseDescription + * format. For information on this format, + * (see RFC 2252, Lightweight Directory Access Protocol (v3): + * Attribute Syntax Definitions. This is the format that LDAP servers + * and clients use to exchange schema information. (For example, when + * you search an LDAP server for its schema, the server returns an entry + * with attributes that include "matchingrule" and "matchingruleuse". + * The values of these attributes are matching rule descriptions + * in this format.) + *

+ * + * @param raw Definition of the matching rule in the + * MatchingRuleDescription format. + * @param use Definition of the use of the matching rule in the + * MatchingRuleUseDescription format. + */ + public LDAPMatchingRuleSchema( String raw, String use ) { + super(); + attrName = "matchingrules"; + oid = processRule( raw ); + String o = processRule( use ); + if ( (o != null) && (oid != null) && !o.equals(oid) ) { + System.err.println( "Rule oid " + oid + + " differs from use oid " + o ); + } + if ( oid == null ) + oid = o; + } + + /** + * Construct a rule definition from a value returned from + * a search of the schema in a Directory. + * @param raw The raw string value returned as one of the values + * of matchingRuleUse in searching the schema. + */ + private String processRule( String raw ) { + if ( raw == null ) + return null; + /* Process the matchingRuleUse value */ + raw.trim(); + // Skip past "( " and ")" + int l = raw.length(); + raw = raw.substring( 2, l - 1 ); + l = raw.length(); + int ind = raw.indexOf( ' ' ); + String o = raw.substring( 0, ind ); + char[] ch = new char[l]; + + raw = raw.substring( ind + 1, l ); + l = raw.length(); + raw.getChars( 0, l, ch, 0 ); + + ind = 0; + l = ch.length; + while ( ind < l ) { + String s = ""; + String val; + while( ch[ind] == ' ' ) + ind++; + int last = ind + 1; + while( (last < l) && (ch[last] != ' ') ) + last++; + if ( (ind < l) && (last < l) ) { + s = new String( ch, ind, last-ind ); + ind = last; + } else { + ind = l; + } + + while( (ind < l) && (ch[ind] != '\'') && (ch[ind] != '(') ) + ind++; + last = ind + 1; + while( (last < l) && (ch[last] != '\'') && (ch[last] != ')') ) { + last++; + } + if ( (ind < last) && (last < l) ) { + val = new String( ch, ind+1, last-ind-1 ); + ind = last + 1; + + if ( s.equalsIgnoreCase( "NAME" ) ) { + name = val; + } else if ( s.equalsIgnoreCase( "DESC" ) ) { + description = val; + } else if ( s.equalsIgnoreCase( "SYNTAX" ) ) { + syntax = syntaxCheck( val ); + } else if ( s.equalsIgnoreCase( "APPLIES" ) ) { + /* Parse the list of attribute OIDs */ + Vector v = new Vector(); + StringTokenizer st = new StringTokenizer( val, " " ); + while ( st.hasMoreTokens() ) { + String tok = st.nextToken(); + if ( !tok.equals( "$" ) ) { + v.addElement( tok ); + } + } + attributes = new String[v.size()]; + v.copyInto( attributes ); + v.removeAllElements(); + v = null; + } + } + } + return o; + } + + /** + * Get the list of the OIDs of the attribute types which can be used + * with the matching rule. The list is a deep copy. + * @return Array of the OIDs of the attribute types which can be used + * with the matching rule. + */ + public String[] getAttributes() { + return attributes; + } + + /** + * Get the matching rule definition in the string representation + * of the MatchingRuleDescription data type defined in X.501 (see + * RFC 2252, Lightweight Directory Access Protocol + * (v3): Attribute Syntax Definitions + * for a description of these formats). + * This is the format that LDAP servers and clients use to exchange + * schema information. (For example, when + * you search an LDAP server for its schema, the server returns an entry + * with the attributes "matchingrules" and "matchingruleuse". The + * values of these attributes are matching rule description and + * matching rule use description in these formats.) + *

+ * + * @return A string in a format that can be used as the value of + * the matchingrule attribute (which describes + * a matching rule in the schema) of a subschema object. + */ + public String getValue() { + String s = "( " + oid + " NAME \'" + name + "\' DESC \'" + + description + "\' SYNTAX \'"; + s += internalSyntaxToString(); + s += "\' )"; + return s; + } + + /** + * Get the matching rule use definition in the string representation + * of the MatchingRuleUseDescription data type defined in X.501 (see + * RFC 2252, Lightweight Directory Access Protocol + * (v3): Attribute Syntax Definitions + * for a description of these formats). + * This is the format that LDAP servers and clients use to exchange + * schema information. (For example, when + * you search an LDAP server for its schema, the server returns an entry + * with the attributes "matchingrules" and "matchingruleuse". The + * values of these attributes are matching rule description and + * matching rule use description in these formats.) + *

+ * + * @return A string in a format that can be used as the value of + * the matchingruleuse attribute (which describes the use of + * a matching rule in the schema) of a subschema object. + */ + public String getUseValue() { + String s = "( " + oid; + s += " APPLIES ( "; + for( int i = 0; i < attributes.length; i++ ) { + if ( i > 0 ) + s += " $ "; + s += attributes[i]; + } + s += ") )"; + return s; + } + + /** + * Add, remove or modify the definition from a Directory. + * @param ld An open connection to a Directory Server. Typically the + * connection must have been authenticated to add a definition. + * @param op Type of modification to make. + * @param name Name of attribute in the schema entry to modify. This + * is ignored here. + * @exception LDAPException if the definition can't be added/removed. + */ + protected void update( LDAPConnection ld, int op, String name ) + throws LDAPException { + LDAPAttribute[] attrs = new LDAPAttribute[2]; + attrs[0] = new LDAPAttribute( "matchingRules", + getValue() ); + /* Must update the matchingRuleUse value as well */ + attrs[1] = new LDAPAttribute( "matchingRuleUse", + getUseValue() ); + update( ld, op, attrs ); + } + + /** + * Get the definition of the matching rule in a user friendly format. + * This is the format that the matching rule definition uses when + * you print the matching rule or the schema. + * @return Definition of the matching rule in a user friendly format. + */ + public String toString() { + String s = "Name: " + name + "; OID: " + oid + "; Type: "; + s += syntaxToString(); + s += "; Description: " + description; + if ( attributes != null ) { + s += "; Applies to: "; + for( int i = 0; i < attributes.length; i++ ) { + if ( i > 0 ) + s += ", "; + s += attributes[i]; + } + } + return s; + } + + private String[] attributes = null; +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPModification.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPModification.java new file mode 100644 index 00000000000..1d908560bfd --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPModification.java @@ -0,0 +1,142 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import netscape.ldap.ber.stream.*; + +/** + * Specifies changes to be made to the values of an attribute. The change is + * specified in terms of the following aspects: + *

+ * + *

    + *
  • the type of modification (add, replace, or delete the value of an attribute) + *
  • the type of value being modified (string or binary) + *
  • the name of the attribute being modified + *
  • the actual value + *
+ *

+ * + * After you specify a change to an attribute, you can execute the change + * by calling the LDAPConnection.modify method and specifying + * the DN of the entry that you want to modify. + *

+ * + * @version 1.0 + * @see netscape.ldap.LDAPConnection#modify(java.lang.String, netscape.ldap.LDAPModification) + */ +public class LDAPModification { + + /** + * Specifies that a value should be added to an attribute. + */ + public static final int ADD = 0; + + /** + * Specifies that a value should be removed from an attribute. + */ + public static final int DELETE = 1; + + /** + * Specifies that a value should replace the existing value in an attribute. + */ + public static final int REPLACE = 2; + + /** + * Internal variables + */ + private int operation; + private LDAPAttribute attribute; + + /** + * Specifies a modification to be made to an attribute. + * @param op The type of modification to make, which can be one of the following: + *

+ *

    + *
  • LDAPModification.ADD (the value should be added to the attribute) + *
  • LDAPModification.DELETE (the value should be removed from the attribute) + *
  • LDAPModification.REPLACE (the value should replace the existing value of the attribute) + *

+ * @param attr The attribute (possibly with values) to be modified. + * @see netscape.ldap.LDAPAttribute + */ + public LDAPModification( int op, LDAPAttribute attr ) { + operation = op; + attribute = attr; + } + + /** + * Returns the type of modification specified by this object. + * @return One of the following types of modifications: + *

+ *

    + *
  • LDAPModification.ADD (the value should be added to the attribute) + *
  • LDAPModification.DELETE (the value should be removed from the attribute) + *
  • LDAPModification.REPLACE (the value should replace the existing value of the attribute) + *

+ */ + public int getOp() { + return operation; + } + + /** + * Returns the attribute (possibly with values) to be modified. + * @return The attribute to be modified. + * @see netscape.ldap.LDAPAttribute + */ + public LDAPAttribute getAttribute() { + return attribute; + } + + /** + * Retrieves the BER (Basic Encoding Rules) representation + * of the current modification. + * @return BER representation of the modification. + */ + public BERElement getBERElement() { + BERSequence seq = new BERSequence(); + seq.addElement(new BEREnumerated(operation)); + seq.addElement(attribute.getBERElement()); + return seq; + } + + /** + * Retrieves the string representation of the current + * modification. For example: + * + *

+     * LDAPModification: REPLACE, LDAPAttribute {type='mail', values='babs@ace.com'}
+     * LDAPModification: ADD, LDAPAttribute {type='description', values='This entry was modified with the modattrs program'}
+     * 
+ * + * @return String representation of the current modification. + */ + public String toString() { + String s = "LDAPModification: "; + if ( operation == ADD ) + s += "ADD, "; + else if ( operation == DELETE ) + s += "DELETE, "; + else if ( operation == REPLACE ) + s += "REPLACE, "; + else + s += "INVALID OP, "; + s += attribute; + return s; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPModificationSet.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPModificationSet.java new file mode 100644 index 00000000000..ba02b70ee00 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPModificationSet.java @@ -0,0 +1,117 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import java.util.*; + +/** + * Represents a set of modifications to be made to attributes in an entry. + * A set of modifications is made up of LDAPModification objects. + *

+ * + * After you specify a change to an attribute, you can execute the change + * by calling the LDAPConnection.modify method and specifying + * the DN of the entry that you want to modify. + *

+ * + * @version 1.0 + * @see netscape.ldap.LDAPModification + * @see netscape.ldap.LDAPConnection#modify(java.lang.String, netscape.ldap.LDAPModificationSet) + */ +public class LDAPModificationSet { + + private int current = 0; + private Vector modifications; + + /** + * Constructs a new, empty set of modifications. + * You can add modifications to this set by calling the + * LDAPModificationsSet.add method. + */ + public LDAPModificationSet() { + modifications = new Vector(); + current = 0; + } + + /** + * Retrieves the number of LDAPModification + * objects in this set. + * @return The number of LDAPModification + * objects in this set. + */ + public int size () { + return modifications.size(); + } + + /** + * Retrieves a particular LDAPModification object at + * the position specified by the index. + * @param Index position of the LDAPModification + * object that you want to retrieve. + * @return LDAPModification object representing + * a change to be made to an attribute. + */ + public LDAPModification elementAt (int index) { + return (LDAPModification)modifications.elementAt(index); + } + + /** + * Removes a particular LDAPModification object at + * the position specified by the index. + * @param Index position of the LDAPModification + * object that you want to remove. + */ + public void removeElementAt( int index ) { + modifications.removeElementAt(index); + } + + /** + * Specifies another modification to be added to the set of modifications. + * @param op The type of modification to make, which can be one of the following: + *

+ *

    + *
  • LDAPModification.ADD (the value should be added to the attribute) + *
  • LDAPModification.DELETE (the value should be removed from the attribute) + *
  • LDAPModification.REPLACE (the value should replace the existing value of the attribute) + *

+ * If you are working with a binary value (not a string value), you need to bitwise OR (|) the + * modification type with LDAPModification.BVALUES. + *

+ * + * @param attr The attribute (possibly with values) to be modified. + */ + public synchronized void add( int op, LDAPAttribute attr ) { + LDAPModification mod = new LDAPModification( op, attr ); + modifications.addElement( mod ); + } + + /** + * Removes the first attribute with the specified name in the set of modifications. + * @param name Name of the attribute to be removed. + */ + public synchronized void remove( String name ) { + for( int i = 0; i < modifications.size(); i++ ) { + LDAPModification mod = (LDAPModification)modifications.elementAt( i ); + LDAPAttribute attr = mod.getAttribute(); + if ( name.equalsIgnoreCase( attr.getName() ) ) { + modifications.removeElementAt( i ); + break; + } + } + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPObjectClassSchema.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPObjectClassSchema.java new file mode 100644 index 00000000000..8c11c17c900 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPObjectClassSchema.java @@ -0,0 +1,318 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import java.util.*; + +/** + * The definition of an object class in the schema. + * RFC 2252, Lightweight Directory Access Protocol (v3): + * Attribute Syntax Definitions covers the types of information + * that need to be specified in the definition of an object class. + * According to the RFC, the description of an object class can + * include the following information: + *

+ * + *

    + *
  • an OID identifying the object class + *
  • a name identifying the object class + *
  • a description of the object class + *
  • the name of the parent object class + *
  • the list of attribute types that are required in this object class + *
  • the list of attribute types that are allowed (optional) in this + * object class + *
+ *

+ * + * When you construct an LDAPObjectSchema object, you can specify + * these types of information as arguments to the constructor or in the + * ObjectClassDescription format specified in RFC 2252. + * (When an LDAP client searches an LDAP server for the schema, the server + * returns schema information as an object with attribute values in this + * format.) + *

+ * + * RFC 2252 also notes that you can specify whether or not an object class + * is abstract, structural, or auxiliary in the object description. + * (Abstract object classes are used only to derive other object classes. + * Entries cannot belong to an abstract object class. top + * is an abstract object class.) Entries must belong to a structural + * object class, so most object classes are structural object classes. + * Objects of the LDAPObjectClassSchema class are structural + * object classes by default. Auxiliary object classes can be used to + * construct entries of different types. For example, an auxiliary object + * class might be used to specify a type of entry with a structural object + * class that can vary (an auxiliary object class might specify that an + * entry must either be an organizationalPerson or residentialPerson). + * If the definition of an object (in ObjectClassDescription format) + * specifies the AUXILIARY keyword, an LDAPObjectClassSchema + * object created from that description represents an auxiliary object class. + *

+ * + * You can get the name, OID, and description of this object class + * definition by using the getName, getOID, and + * getDescription methods inherited from the abstract class + * LDAPSchemaElement. + *

+ * + * If you need to add or remove this object class definition from the + * schema, you can use the add and remove + * methods, which this class inherits from the LDAPSchemaElement + * abstract class. + *

+ * + * @version 1.0 + * @see netscape.ldap.LDAPSchemaElement + **/ +public class LDAPObjectClassSchema extends LDAPSchemaElement { + /** + * Constructs an object class definition, using the specified + * information. + * @param name Name of the object class. + * @param oid Object identifier (OID) of the object class + * in dotted-string format (for example, "1.2.3.4"). + * @param description Description of the object class. + * @param superior Name of the parent object class + * (the object class that the new object class inherits from). + * @param required Array of the names of the attributes required + * in this object class. + * @param optional Array of the names of the optional attributes + * allowed in this object class. + */ + public LDAPObjectClassSchema( String name, String oid, String superior, + String description, + String[] required, String optional[] ) { + super( name, oid, description ); + attrName = "objectclasses"; + this.superior = superior; + for( int i = 0; i < required.length; i++ ) + must.addElement( required[i] ); + for( int i = 0; i < optional.length; i++ ) + may.addElement( optional[i] ); + } + + /** + * Constructs an object class definition based on a description in + * the ObjectClassDescription format. For information on this format, + * (see RFC 2252, Lightweight Directory Access Protocol (v3): + * Attribute Syntax Definitions. This is the format that LDAP servers + * and clients use to exchange schema information. (For example, when + * you search an LDAP server for its schema, the server returns an entry + * with the attributes "objectclasses" and "attributetypes". The + * values of the "objectclasses" attribute are object class descriptions + * in this format.) + *

+ * + * @param raw Definition of the object in the ObjectClassDescription + * format. + */ + public LDAPObjectClassSchema( String raw ) { + attrName = "objectclasses"; + raw.trim(); + // Skip past "( " and ")" + int l = raw.length(); + raw = raw.substring( 2, l - 1 ); + l = raw.length(); + int ind = raw.indexOf( ' ' ); + oid = raw.substring( 0, ind ); + char[] ch = new char[l]; + + raw = raw.substring( ind + 1, l ); + l = raw.length(); + raw.getChars( 0, l, ch, 0 ); + + ind = 0; + l = ch.length; + while ( ind < l ) { + String s = ""; + String val; + while( ch[ind] == ' ' ) + ind++; + int last = ind + 1; + while( (last < l) && (ch[last] != ' ') ) + last++; + if ( (ind < l) && (last < l) ) { + s = new String( ch, ind, last-ind ); + ind = last; + if ( s.equalsIgnoreCase( "AUXILIARY" ) ) { + auxiliary = true; + continue; + } + } else { + ind = l; + } + + while( (ind < l) && (ch[ind] != '\'') && (ch[ind] != '(') ) + ind++; + last = ind + 1; + if ( ind >= l ) { + break; + } + if ( ch[ind] == '\'' ) { + while( (last < l) && (ch[last] != '\'') ) { + last++; + } + if ( (ind < last) && (last < l) ) { + val = new String( ch, ind+1, last-ind-1 ); + + if ( s.equalsIgnoreCase( "NAME" ) ) { + name = val; + } else if ( s.equalsIgnoreCase( "DESC" ) ) { + description = val; + } else if ( s.equalsIgnoreCase( "SUP" ) ) { + superior = val; + } + } + } else { + Vector v = null; + if ( s.equalsIgnoreCase( "MAY" ) ) { + v = may; + } else if ( s.equalsIgnoreCase( "MUST" ) ) { + v = must; + } else { + continue; + } + while( (last < l) && (ch[last] != ')') ) { + last++; + } + if ( (ind < last) && (last < l) ) { + val = new String( ch, ind+1, last-ind-1 ); + StringTokenizer st = new StringTokenizer( val, " " ); + while ( st.hasMoreTokens() ) { + String tok = st.nextToken(); + if ( !tok.equals( "$" ) ) { + v.addElement( tok ); + } + } + } + } + ind = last + 1; + } + } + + /** + * Get the name of the object class that this class inherits from. + * @return The name of the object class that this class + * inherits from. + */ + public String getSuperior() { + return superior; + } + + /** + * Get an enumeration of the names of the required attribute for + * this object class. + * @return An enumeration of the names of the required attributes + * for this object class. + */ + public Enumeration getRequiredAttributes() { + return must.elements(); + } + + /** + * Get an enumeration of names of optional attributes allowed + * in this object class. + * @return An enumeration of the names of optional attributes + * allowed in this object class. + */ + public Enumeration getOptionalAttributes() { + return may.elements(); + } + + /** + * Get the object class definition in a string representation + * of the ObjectClassDescription data type defined in X.501 (see + * RFC 2252, Lightweight Directory Access Protocol (v3): + * Attribute Syntax Definitions for a description of this format). + * This is the format that LDAP servers and clients use to exchange + * schema information. (For example, when + * you search an LDAP server for its schema, the server returns an entry + * with the attributes "objectclasses" and "attributetypes". The + * values of the "objectclasses" attribute are object class descriptions + * in this format.) + *

+ * + * @return A string in a format that can be used as the value of + * the objectclasses attribute (which describes + * an object class in the schema) of a subschema object. + */ + public String getValue() { + String s = "( " + oid + " NAME \'" + name + "\' DESC \'" + + description + "\' SUP \'" + superior + "\' "; + if ( auxiliary ) + s += "AUXILIARY "; + s += "MUST ( "; + int i = 0; + Enumeration e = getRequiredAttributes(); + while( e.hasMoreElements() ) { + if ( i > 0 ) + s += " $ "; + i++; + s += (String)e.nextElement(); + } + s += " ) MAY ( "; + e = getOptionalAttributes(); + i = 0; + while( e.hasMoreElements() ) { + if ( i > 0 ) + s += " $ "; + i++; + s += (String)e.nextElement(); + } + s += ") )"; + return s; + } + + /** + * Get the definition of the object class in a user friendly format. + * This is the format that the object class definition uses when + * you print the object class or the schema. + * @return Definition of the object class in a user friendly format. + */ + public String toString() { + String s = "Name: " + name + "; OID: " + oid + + "; Superior: " + superior + + "; Description: " + description + "; Required: "; + int i = 0; + Enumeration e = getRequiredAttributes(); + while( e.hasMoreElements() ) { + if ( i > 0 ) + s += ", "; + i++; + s += (String)e.nextElement(); + } + s += "; Optional: "; + e = getOptionalAttributes(); + i = 0; + while( e.hasMoreElements() ) { + if ( i > 0 ) + s += ", "; + i++; + s += (String)e.nextElement(); + } + return s; + } + + private String superior = ""; + private Vector must = new Vector(); + private Vector may = new Vector(); + private boolean auxiliary = false; +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPRebind.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPRebind.java new file mode 100644 index 00000000000..c0f13f92fea --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPRebind.java @@ -0,0 +1,74 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import java.util.*; +import java.io.*; + +/** + * Specifies how you can retrieve authentication information automatically + * for referrals. If you have set up the search constraints (or the options + * in the LDAPConnection object) so that automatic referral is + * used, you must define a class that implements this interface. + *

+ * + * If no class implements this interface, clients that follow automatic + * referrals are authenticated anonymously with subsequent LDAP servers. + * The following example is a simple class that implements this interface. + * Objects of this class check the host and port of the LDAP server that is + * being referred to. If the host and port are "alway.mcom.com:389", the + * directory manager's name and password will be used to authenticate to that + * server. For all other LDAP servers, anonymous authentication is used. + * + *

+ * public class myLDAPRebind implements netscape.ldap.LDAPRebind
+ * {
+ *  private String myDN;
+ *  private String myPW;
+ *  private LDAPRebindAuth myRebindInfo;
+
+ *  public myLDAPRebind () {
+ *    myDN = "c=Directory Manager,o=Universal Exports,c=UK";
+ *    myPW = "alway4444";
+ *  }
+ *
+ *  public LDAPRebindAuth getRebindAuthentication( String host, int port ) {
+ *    if ( host.equalsIgnoreCase( "alway.mcom.com" ) && ( port == 389 ) ) {
+ *      myRebindInfo = new LDAPRebindAuth( myDN, myPW );
+ *    } else {
+ *      myRebindInfo = new LDAPRebindAuth( "", "" );
+ *    }
+ *    return myRebindInfo;
+ *  }
+ * } 
+ * + * + * @version 1.0 + */ +public interface LDAPRebind { + + /** + * Returns an LDAPRebindAuth object, which the calling function + * can use to get the DN and password to use for authentication (if the client + * is set up to follow referrals automatically). + * @return LDAPRebindAuth object containing authentication information. + * @see netscape.ldap.LDAPRebindAuth + */ + public LDAPRebindAuth getRebindAuthentication(String host, + int port); +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPRebindAuth.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPRebindAuth.java new file mode 100644 index 00000000000..06258dcdb80 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPRebindAuth.java @@ -0,0 +1,91 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import java.util.*; +import java.io.*; + +/** + * Represents information used to authenticate the client in cases where + * the client follows referrals automatically. If you are defining a class + * that implements the LDAPRebind interface, your implementation + * of the LDAPRebind.getRebindAuthentication method needs to + * construct and return an object of this class. + *

+ * + * For example, the following method sets up authentication information based + * on the LDAP server identified in the referral. Ideally, this method would be + * defined as part of a class implementing the LDAPRebind interface. + * + *

+ * private String myDN = "cn=Directory Manager,o=Ace Industry,c=US";
+ * private String myPW = "alway4444";
+ * private LDAPRebindAuth myRebindInfo;
+ * ...
+ * public LDAPRebindAuth getRebindAuthentication( String host, int port ) {
+ *  if ( host.equalsIgnoreCase( "alway.mcom.com" ) && ( port == 389 ) ) {
+ *      myRebindInfo = new LDAPRebindAuth( myDN, myPW );
+ *  } else {
+ *      myRebindInfo = new LDAPRebindAuth( "", "" );
+ *  }
+ *  return myRebindInfo;
+ * } 
+ * + * @version 1.0 + * @see netscape.ldap.LDAPRebind + */ +public class LDAPRebindAuth { + + private String m_dn; + private String m_password; + + /** + * Constructs information that is used by the client + * for authentication when following referrals automatically. + * @param dn Distinguished name to use for authenticating to + * the LDAP server during an automatic referral (if the client + * is set up to follow referrals automatically) + * @param password Password to use for authenticating to + * the LDAP server during an automatic referral (if the client + * is set up to follow referrals automatically) + */ + public LDAPRebindAuth(String dn, String password) { + m_dn = dn; + m_password = password; + } + + /** + * Returns the distinguished name to be used for reauthentication, + * if the client is set up to follow referrals automatically. + * @return Distinguished name to be used for authenticating to + * other LDAP servers during referrals. + */ + public String getDN() { + return m_dn; + } + + /** + * Returns the password to be used for reauthentication, + * if the client is set up to follow referrals automatically. + * @return Password to be used for authenticating to other + * LDAP servers during referrals. + */ + public String getPassword() { + return m_password; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPReferralException.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPReferralException.java new file mode 100644 index 00000000000..605f2c27b60 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPReferralException.java @@ -0,0 +1,147 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import java.util.*; +import netscape.ldap.client.*; +import netscape.ldap.client.opers.*; +import java.io.*; + +/** + * Represents the situation in which the LDAP server refers the client to + * another LDAP server. This exception constructs a list of referral URLs from + * the LDAP error message returned by the server. You can get this list by + * using the getURLs method. + * + * @version 1.0 + * @see netscape.ldap.LDAPException + */ +public class LDAPReferralException extends LDAPException { + + private String m_referrals[] = null; /* modified for LDAPv3 */ + + /** + * Constructs a default exception with no specific error information. + */ + public LDAPReferralException() { + } + + /** + * Constructs a default exception with a specified string as + * additional information. This form is used for lower-level errors. + * @param message The additional error information + */ + public LDAPReferralException( String message ) { + super( message ); + } + + /** + * Constructs a default exception with a specified string as + * additional information. This form is used for higher-level LDAP + * operational errors. + * @param message The additional error information + * @param resultCode result code + * @param serverErrorMessage error message + */ + public LDAPReferralException( String message, int resultCode, + String serverErrorMessage ) { + super(message, resultCode, serverErrorMessage); + } + + /** + * Constructs an exception with a list of LDAP URLs to other LDAP servers. + * This list of referrals points the client to LDAP servers that may + * contain the requested entries. + * @param message The additional error information + * @param resultCode result code + * @param referrals Array of LDAP URLs identifying other LDAP servers that + * may contain the requested entries. + */ + public LDAPReferralException( String message, int resultCode, + String referrals[] ) { + super(message, resultCode, null); + m_referrals = referrals; + } + + /** + * Gets the list of referrals (LDAP URLs to other servers) returned by the LDAP server. + * You can use this list to find the LDAP server that can fulfill your request. + * + * If you have set up your search constraints (or the LDAPConnection object) + * to follow referrals automatically, any operation that results in a referral will use + * this list to create new connections to the LDAP servers in this list. + * + * @return List of LDAP URLs to other LDAP servers. + */ + public LDAPUrl[] getURLs() { + if (getLDAPErrorMessage() == null) { + return constructsURL(m_referrals); + } else { + return constructsURL(extractReferrals(getLDAPErrorMessage())); + } + } + + private LDAPUrl[] constructsURL(String referrals[]) { + if (referrals == null) { + return null; + } + LDAPUrl u[] = new LDAPUrl[referrals.length]; + if (u == null) { + return null; + } + for (int i = 0; i < referrals.length; i++) { + try { + u[i] = new LDAPUrl(referrals[i]); + } catch (Exception e) { + return null; + } + } + return u; + } + + /** + * Extract referral string from the error message. The + * error string is based on "Referrals Within the + * LDAPv2 Protocol". + * @param error string + */ + private String[] extractReferrals(String error) { + if (error == null) + return null; + StringTokenizer st = new StringTokenizer(error, "\n"); + Vector v = new Vector(); + boolean referrals = false; + while (st.hasMoreTokens()) { + String token = st.nextToken(); + if (referrals) { + v.addElement(token); + } else { + if (token.startsWith("Referral:")) + referrals = true; + } + } + + if (v.size() == 0) + return null; + String res[] = new String[v.size()]; + for (int i = 0; i < v.size(); i++) { + res[i] = (String)v.elementAt(i); + } + return res; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPResourceBundle.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPResourceBundle.java new file mode 100644 index 00000000000..0d263b85235 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPResourceBundle.java @@ -0,0 +1,117 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import netscape.ldap.*; +import java.util.*; +import java.io.*; + +/** + * This class represents a locale-specific resource for a property file. + * It retrieves the property file for the given base name including the + * absolute path name and locale. The property file has to be located in the + * CLASSPATH and the property file's suffix is .props. + *

+ * If the specified locale is en and us and the base name of the file is + * netscape/ldap/errors/ErrorCodes, then the class loader will search for + * the file in the following order: + *

+ *
+ *   ErrorCodes_en_us.props
+ *   ErrorCodes_en.props
+ *   ErrorCodes.props
+ *
+ * 
+ * @see java.util.Locale + */ +class LDAPResourceBundle { + + private static final boolean m_debug = false; + private static final String m_suffix = ".props"; + private static final String m_locale_separator = "_"; + + /** + * Return the property resource bundle according to the base name of the + * property file and the locale. The class loader will find the closest match + * with the given locale. + * @return The property resource bundle + * @exception IOException Gets thrown when failed to open the resource + * bundle file. + */ + static PropertyResourceBundle getBundle(String baseName) + throws IOException { + + return getBundle(baseName, Locale.getDefault()); + } + + /** + * Return the property resource bundle according to the base name of the + * property file and the locale. The class loader will find the closest match + * with the given locale. + * @param baseName The base name of the property file, ie, the name contains + * no locale context and no . suffix + * @param l The locale + * @return The property resource bundle + * @exception IOException Gets thrown when failed to create a property + * resource + */ + static PropertyResourceBundle getBundle(String baseName, Locale l) + throws IOException { + String localeStr = m_locale_separator+l.toString(); + + InputStream fin = null; + + while (true) { + if ((fin=getStream(baseName, localeStr)) != null) { + PropertyResourceBundle p = new PropertyResourceBundle(fin); + return p; + } else { + + int index = localeStr.lastIndexOf(m_locale_separator); + if (index == -1) { + printDebug("File "+baseName+localeStr+m_suffix+" not found"); + return null; + } else + localeStr = localeStr.substring(0, index); + } + } + } + + /** + * Constructs the whole absolute path name of a property file and retrieves + * an input stream on the file. + * @param baseName The base name of the property file, ie, the name contains + * no locale context and no . suffix + * @param The locale string being inserted within the file name. + * @return The input stream on the property file. + */ + private static InputStream getStream(String baseName, String locale) { + String fStr = baseName+locale+m_suffix; + return (ClassLoader.getSystemResourceAsStream(fStr)); + } + + /** + * Prints debug messages if the debug mode is on. + * @param str The given message being printed. + */ + private static void printDebug(String str) { + if (m_debug) + System.out.println(str); + } +} + diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPResponseListener.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPResponseListener.java new file mode 100644 index 00000000000..ea7499a4f2b --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPResponseListener.java @@ -0,0 +1,152 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import netscape.ldap.client.*; + +/** + * An object for taking the asynchronous LDAP responses and making them + * appear somewhat synchronized. Uses built-in Java monitors to block + * until a response is received. This is also used to communicate + * exceptions across threads. + * + * This class is part of the implementation; it is of no interest to + * developers. + * + * @version 1.0 + */ +class LDAPResponseListener +{ + /** + * Internal variables + */ + private JDAPMessage response; + private LDAPException exception; + private boolean responseReceived; + private boolean exceptionOccured; + private Thread me; + private LDAPControl[] controls; + private LDAPConnection connection; + private int id; + + /** + * Constructs a basic response Listener. + */ + public LDAPResponseListener ( LDAPConnection conn ) { + connection = conn; + reset (); + } + + /** + * Retrieves response message. This method blocks until the response + * has been received. + * @return jdap message + */ + synchronized JDAPMessage getResponse () throws LDAPException { + while (!responseReceived) { + try { + wait (); + } catch (InterruptedException e) { + } + } + + if (exceptionOccured) throw exception; + return response; + } + + /** + * Posts the LDAP server's response to the object. This causes + * anyone waiting on getResponse to unblock. + * @param response response message + */ + synchronized void setResponse (JDAPMessage response) { + this.response = response; + this.responseReceived = true; + notifyAll (); + } + + /** + * Signals that an LDAPException occured while servicing the + * request. This exception will be throw to any threads waiting + * on getResponse + * @param e exception + */ + synchronized void setException (LDAPException e) { + exceptionOccured = true; + responseReceived = true; + exception = e; + notifyAll (); + } + + /** + * Checks if response received. + * @return true or false + */ + boolean isResponseReceived() { + return responseReceived; + } + + /** + * Resets the state of this object, so it can be recycled. + */ + void reset () { + responseReceived = false; + exceptionOccured = false; + me = null; + } + + /** + * Keep track of the thread which issued the request. + * + */ + void setThread() { + me = Thread.currentThread(); + } + + /** + * What thread issued this request? + * @return The issuing thread + */ + Thread getThread() { + return me; + } + + /** + * Return owner connection + * @return Owner connection + */ + LDAPConnection getConnection() { + return connection; + } + + /** + * Returns message id. + * @return Message id. + */ + int getID() { + return id; + } + + /** + * Sets the message id. + * @param id The message id. + */ + void setID( int id ) { + this.id = id; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSSLSocketFactory.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSSLSocketFactory.java new file mode 100644 index 00000000000..760bfbdfbb8 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSSLSocketFactory.java @@ -0,0 +1,237 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import java.io.*; +import java.net.*; +import netscape.ldap.*; + +/** + * Creates an SSL socket connection to an LDAP Server. This class + * implements the LDAPSocketFactory interface. + *

+ * + * To construct an object of this class, you need to specify the + * name of a class that implements the javax.net.ssl.SSLSocket + * interface. If you do not specify a class name, the class + * netscape.net.SSLSocket is used by default. This + * class is included with Netscape Communicator 4.05. + *

+ * + * If you are using a Java VM that provides certificate database + * management (such as Netscape Communicator), you can authenticate + * your client to a secure LDAP server by using certificates. + *

+ * + * @version 1.0 + * @see LDAPSocketFactory + * @see LDAPConnection#LDAPConnection(netscape.ldap.LDAPSocketFactory) + */ +public class LDAPSSLSocketFactory implements LDAPSocketFactory { + + /** + * Indicates if client authentication is on. + */ + private boolean m_isClientAuth = false; + /** + * Name of class implementing SSLSocket. + */ + private String m_packageName = "netscape.net.SSLSocket"; + /** + * The cipher suites + */ + private Object m_cipherSuites = null; + + /** + * Constructs an LDAPSSLSocketFactory object using + * the default SSL socket implementation, + * netscape.net.SSLSocket. (This class is provided + * with Netscape Communicator 4.05.) + */ + public LDAPSSLSocketFactory() { + } + + /** + * Constructs an LDAPSSLSocketFactory object using + * the specified class. The class must implement the interface + * javax.net.ssl.SSLSocket. + * @param className The name of a class implementing + * the javax.net.ssl.SSLSocket interface. + * Pass null for this parameter to use the + * default SSL socket implementation, + * netscape.net.SSLSocket, which is included with + * Netscape Communicator 4.05. + */ + public LDAPSSLSocketFactory(String className) { + m_packageName = new String(className); + } + + /** + * The constructor with the specified package for security and the specified + * cipher suites. + * @param className The name of a class implementing the interface + * javax.net.ssl.SSLSocket + * Pass null for this parameter to use the + * default SSL socket implementation, + * netscape.net.SSLSocket, which is included with + * Netscape Communicator 4.05. + * @param cipherSuites The cipher suites to use for SSL connections. + */ + public LDAPSSLSocketFactory(String className, Object cipherSuites) { + m_packageName = new String(className); + m_cipherSuites = cipherSuites; + } + + /** + * Enables certificate-based client authentication for an + * application. The application must be running in a Java VM + * that provides transparent certificate database management + * (for example, Netscape Communicator's Java VM). + * Call this method before you call makeSocket. + * @see netscape.ldap.LDAPSSLSocketFactory#isClientAuth + * @see netscape.ldap.LDAPSSLSocketFactory#makeSocket + */ + public void enableClientAuth() { + m_isClientAuth = true; + } + + + /** + * This method is currently not implemented. + * Enables client authentication for an application that uses + * an external (file-based) certificate database. + * Call this method before you call makeSocket. + * @param certdb The pathname for certificate database + * @param keydb The pathname for private key database + * @param keypwd The password for private key database + * @param certnickname The alias for certificate + * @param keynickname The alias for key + * @see netscape.ldap.LDAPSSLSocketFactory#isClientAuth + * @see netscape.ldap.LDAPSSLSocketFactory#makeSocket + * @exception LDAPException Since this method is not yet implemented, + * calling this method throws an exception. + */ + public void enableClientAuth(String certdb, String keydb, String keypwd, + String certnickname, String keynickname) throws LDAPException { + throw new LDAPException("Client auth not supported now"); + } + + /** + * Returns true if client authentication is enabled. + * @see netscape.ldap.LDAPSSLSocketFactory#enableClientAuth + */ + public boolean isClientAuth() { + return m_isClientAuth; + } + + /** + * Returns the name of the class that implements SSL sockets for this factory. + * + * @return The name of the class that implements SSL sockets for this factory. + */ + public String getSSLSocketImpl() { + return m_packageName; + } + + /** + * Returns the suite of ciphers used for SSL connections made through + * sockets created by this factory. + * + * @return The suite of ciphers used. + */ + public Object getCipherSuites() { + return m_cipherSuites; + } + + /** + * Returns a socket to the LDAP server with the specified + * host name and port number. Before calling this method, + * call enableClientAuth. + * @param host The host to connect to + * @param port The port number + * @return The socket to the host name and port number. + * @exception LDAPException A socket to the specified host and port + * could not be created. + * @see netscape.ldap.LDAPSSLSocketFactory#enableClientAuth + */ + public Socket makeSocket(String host, int port) + throws LDAPException { + + Socket s = null; + + if (m_isClientAuth) { + try { + /* Check if running in Communicator; if so, enable client auth */ + java.lang.reflect.Method m = LDAPCheckComm.getMethod( + "netscape.security.PrivilegeManager", "enablePrivilege"); + if (m != null) { + Object[] args = new Object[1]; + args[0] = new String("ClientAuth"); + m.invoke( null, args); + } + } catch (Exception e) { + throw new LDAPException("Invoking enablePrivilege: " + + e.toString(), LDAPException.PARAM_ERROR); + } + } + + try { + String cipherClassName = null; + if (m_cipherSuites != null) + cipherClassName = m_cipherSuites.getClass().getName(); + + /* Instantiate the SSLSocketFactory implementation, and + find the right constructor */ + Class c = Class.forName(m_packageName); + java.lang.reflect.Constructor[] m = c.getConstructors(); + for (int i = 0; i < m.length; i++) { + /* Check if the signature is right: String, int */ + Class[] params = m[i].getParameterTypes(); + if ( (m_cipherSuites == null) && (params.length == 2) && + (params[0].getName().equals("java.lang.String")) && + (params[1].getName().equals("int")) ) { + Object[] args = new Object[2]; + args[0] = host; + args[1] = new Integer(port); + s = (Socket)(m[i].newInstance(args)); + return s; + } else if ( (m_cipherSuites != null) && (params.length == 3) && + (params[0].getName().equals("java.lang.String")) && + (params[1].getName().equals("int")) && + (params[2].getName().equals(cipherClassName)) ) { + Object[] args = new Object[3]; + args[0] = host; + args[1] = new Integer(port); + args[2] = m_cipherSuites; + s = (Socket)(m[i].newInstance(args)); + return s; + } + } + throw new LDAPException("No appropriate constructor in " + + m_packageName, + LDAPException.PARAM_ERROR); + } catch (ClassNotFoundException e) { + throw new LDAPException("Class " + m_packageName + " not found", + LDAPException.PARAM_ERROR); + } catch (Exception e) { + throw new LDAPException("Failed to create SSL socket", + LDAPException.CONNECT_ERROR); + } + } +} + diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSSLSocketWrapFactory.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSSLSocketWrapFactory.java new file mode 100644 index 00000000000..0a575cb600e --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSSLSocketWrapFactory.java @@ -0,0 +1,330 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import java.io.*; +import java.net.*; +import java.util.Hashtable; +import netscape.ldap.*; + +/** + * Creates an SSL socket connection to an LDAP Server. This class is provided + * by the package in which the SSL socket does not extend Socket object. + * The class internally provides a wrapper to convert the SSL socket extending + * the Object class to the one extending the Socket class. + * This factory class implements the LDAPSocketFactory interface. + *

+ * + * To use this class, pass the instance of this factory object to the + * LDAPConnection constructor. + * + * @version 1.0 + * @see LDAPSocketFactory + * @see LDAPConnection#LDAPConnection(netscape.ldap.LDAPSocketFactory) + */ +public class LDAPSSLSocketWrapFactory implements LDAPSocketFactory { + + /** + * The constructor with the specified package for security + * @param className The name of a class which has an implementation + * of SSL Socket extending Object class. + */ + public LDAPSSLSocketWrapFactory(String className) { + m_packageName = new String(className); + } + + /** + * The constructor with the specified package for security and the + * specified cipher suites. + * @param className The name of a class which has an implementation + * of SSL Socket extending Object class. + * @param cipherSuites The cipher suites. + */ + public LDAPSSLSocketWrapFactory(String className, Object cipherSuites) { + m_packageName = new String(className); + m_cipherSuites = cipherSuites; + } + + /** + * Returns socket to the specified host name and port number. + * @param host The host to connect to + * @param port The port number + * @return The socket to the host name and port number as passed in. + * @exception LDAPException A socket to the specified host and port + * could not be created. + */ + public Socket makeSocket(String host, int port) throws LDAPException { + + LDAPSSLSocket s = null; + + try { + if (m_cipherSuites == null) + s = new LDAPSSLSocket(host, port, m_packageName); + else + s = new LDAPSSLSocket(host, port, m_packageName, + m_cipherSuites); + return s; + } catch (Exception e) { + System.err.println("Exception: "+e.toString()); + throw new LDAPException("Failed to create SSL socket", + LDAPException.CONNECT_ERROR); + } + } + + /** + * Returns true if client authentication is to be used. + * @return true if client authentication is enabled, otherwise, false if + * client authentication is disabled. + */ + public boolean isClientAuth() { + return m_isClientAuth; + } + + /** + * (Not implemented yet)
+ * Enables client authentication for an application running in + * a java VM which provides transparent certificate database management. + * Calling this method has no effect after makeSocket() has been + * called. + * @exception LDAPException Since this method is not yet implemented, + * calling this method throws an exception. + */ + public void enableClientAuth() throws LDAPException { + throw new LDAPException("Client Authentication is not implemented yet."); + } + + /** + * Indicates if client authentication is on. + */ + private boolean m_isClientAuth = false; + + /** + * Name of class implementing SSLSocket. + */ + private String m_packageName = null; + + /** + * The cipher suites + */ + private Object m_cipherSuites = null; +} + +// LDAPSSLSocket class wraps the implementation of the SSL socket +class LDAPSSLSocket extends Socket { + + public LDAPSSLSocket(String host, int port, String packageName) + throws LDAPException { + super(); + m_packageName = packageName; + try { + // instantiate the SSLSocketFactory implementation, and + // find the right constructor + Class c = Class.forName(m_packageName); + java.lang.reflect.Constructor[] m = c.getConstructors(); + + for (int i = 0; i < m.length; i++) { + /* Check if the signature is right: String, int */ + Class[] params = m[i].getParameterTypes(); + + if ((params.length == 2) && + (params[0].getName().equals("java.lang.String")) && + (params[1].getName().equals("int"))) { + Object[] args = new Object[2]; + args[0] = host; + args[1] = new Integer(port); + m_socket = (Object)(m[i].newInstance(args)); + return; + } + } + throw new LDAPException("No appropriate constructor in " + + m_packageName, LDAPException.PARAM_ERROR); + } catch (ClassNotFoundException e) { + throw new LDAPException("Class " + m_packageName + " not found", + LDAPException.OTHER); + } catch (Exception e) { + throw new LDAPException("Failed to create SSL socket", + LDAPException.CONNECT_ERROR); + } + } + + public LDAPSSLSocket(String host, int port, String packageName, + Object cipherSuites) throws LDAPException { + super(); + m_packageName = packageName; + String cipherClassName = null; + if (cipherSuites != null) + cipherClassName = cipherSuites.getClass().getName(); + + try { + // instantiate the SSLSocketFactory implementation, and + // find the right constructor + Class c = Class.forName(m_packageName); + java.lang.reflect.Constructor[] m = c.getConstructors(); + + for (int i = 0; i < m.length; i++) { + /* Check if the signature is right: String, int */ + Class[] params = m[i].getParameterTypes(); + if (cipherSuites == null) + throw new LDAPException("Cipher Suites is required"); + + if ((params.length == 3) && + (params[0].getName().equals("java.lang.String")) && + (params[1].getName().equals("int")) && + (params[2].getName().equals(cipherClassName))) { + Object[] args = new Object[3]; + args[0] = host; + args[1] = new Integer(port); + args[2] = cipherSuites; + m_socket = (Object)(m[i].newInstance(args)); + return; + } + } + throw new LDAPException("No appropriate constructor in " + + m_packageName, LDAPException.PARAM_ERROR); + } catch (ClassNotFoundException e) { + throw new LDAPException("Class " + m_packageName + " not found", + LDAPException.OTHER); + } catch (Exception e) { + throw new LDAPException("Failed to create SSL socket", + LDAPException.CONNECT_ERROR); + } + } + + public InputStream getInputStream() { + try { + Object obj = invokeMethod(m_socket, "getInputStream", null); + return (InputStream)obj; + } catch (LDAPException e) { + printDebug(e.toString()); + } + + return null; + } + + public OutputStream getOutputStream() { + try { + Object obj = invokeMethod(m_socket, "getOutputStream", null); + return (OutputStream)obj; + } catch (LDAPException e) { + printDebug(e.toString()); + } + + return null; + } + + public void close() throws IOException { + try { + invokeMethod(m_socket, "close", null); + } catch (LDAPException e) { + printDebug(e.toString()); + } + } + + public void close(boolean wait) throws IOException { + try { + Object[] args = new Object[1]; + args[0] = new Boolean(wait); + invokeMethod(m_socket, "close", args); + } catch (LDAPException e) { + printDebug(e.toString()); + } + } + + public InetAddress getInetAddress() { + try { + Object obj = invokeMethod(m_socket, "getInetAddress", null); + return (InetAddress)obj; + } catch (LDAPException e) { + printDebug(e.toString()); + } + + return null; + } + + public int getLocalPort() { + try { + Object obj = invokeMethod(m_socket, "getLocalPort", null); + return ((Integer)obj).intValue(); + } catch (LDAPException e) { + printDebug(e.toString()); + } + + return -1; + } + + public int getPort() { + try { + Object obj = invokeMethod(m_socket, "getPort", null); + return ((Integer)obj).intValue(); + } catch (LDAPException e) { + printDebug(e.toString()); + } + + return -1; + } + + private Object invokeMethod(Object obj, String name, Object[] args) throws + LDAPException { + try { + java.lang.reflect.Method m = getMethod(name); + if (m != null) { + return (m.invoke(obj, args)); + } + } catch (Exception e) { + throw new LDAPException("Invoking "+name+": "+ + e.toString(), LDAPException.PARAM_ERROR); + } + + return null; + } + + private java.lang.reflect.Method getMethod(String name) throws + LDAPException { + try { + java.lang.reflect.Method method = null; + if ((method = (java.lang.reflect.Method)(m_methodLookup.get(name))) + != null) + return method; + + Class c = Class.forName(m_packageName); + java.lang.reflect.Method[] m = c.getMethods(); + for (int i = 0; i < m.length; i++ ) { + if (m[i].getName().equals(name)) { + m_methodLookup.put(name, m[i]); + return m[i]; + } + } + throw new LDAPException("Method " + name + " not found in " + + m_packageName); + } catch (ClassNotFoundException e) { + throw new LDAPException("Class "+ m_packageName + " not found"); + } + } + + private void printDebug(String msg) { + if (m_debug) { + System.out.println(msg); + } + } + + private final boolean m_debug = true; + private Object m_socket; + private Hashtable m_methodLookup = new Hashtable(); + private String m_packageName = null; +} + diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSchema.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSchema.java new file mode 100644 index 00000000000..d01fb318f65 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSchema.java @@ -0,0 +1,496 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import java.util.*; + +/** + * This object represents the schema of an LDAP v3 server. + * You can use the fetchSchema method to retrieve + * the schema used by a server. (The server must support LDAP v3 + * and the capability to retrieve the schema over the LDAP protocol.) + *

+ * + * After you retrieve the schema, you can use this object to get + * the object class, attribute type, and matching rule descriptions + * in the schema. You can also add your own object classes, + * attribute types, and matching rules to the schema. + *

+ * + * To remove any object classes, attribute types, and matching rules + * that you added, call the remove methods of the + * LDAPObjectClassSchema, LDAPAttributeSchema, + * and LDAPMatchingRuleSchema classes. (This method is + * inherited from the LDAPSchemaElement class.) + *

+ * + * The following class is an example of an LDAP client that can + * fetch the schema, get and print object class descriptions and + * attribute type descriptions, and add object classes and attribute + * types to the schema over the LDAP protocol. + *

+ * + *

+ * import netscape.ldap.*;
+ * public class TestSchema {
+ *     public static void main( String[] args ) {
+ *         String HOSTNAME = "ldap.netscape.com";
+ *         int PORT_NUMBER = DEFAULT_PORT;
+ *         String ROOT_DN = "cn=Directory Manager";
+ *         String ROOT_PASSWORD = "23skidoo";
+ *
+ *         LDAPConnection ld = new LDAPConnection();
+ *
+ *         // Construct a new LDAPSchema object to get the schema.
+ *         LDAPSchema dirSchema = new LDAPSchema();
+ *
+ *         try {
+ *             // Connect to the server.
+ *             ld.connect( HOSTNAME, PORT_NUMBER );
+ *
+ *             // Get the schema from the directory.
+ *             dirSchema.fetchSchema( ld );
+ *
+ *             // Get and print the inetOrgPerson object class description.
+ *             LDAPObjectClassSchema objClass = dirSchema.getObjectClass(
+ *                 "inetOrgPerson" );
+ *             if ( objClass != null ) {
+ *                 System.out.println("inetOrgPerson := "+objClass.toString());
+ *             }
+ *
+ *             // Get and print the definition of the userPassword attribute.
+ *             LDAPAttributeSchema attrType = dirSchema.getAttribute(
+ *                 "userpassword" );
+ *             if ( attrType != null ) {
+ *                 System.out.println("userPassword := "+attrType.toString());
+ *             }
+ *
+ *             // Add a new object class.
+ *             String[] requiredAttrs = {"cn", "mail"};
+ *             String[] optionalAttrs = {"sn", "phoneNumber"};
+ *             LDAPObjectClassSchema newObjClass = new LDAPObjectClassSchema(
+ *                 "newInetOrgPerson", "1.2.3.4.5.6.7", "top", "Experiment",
+ *                 requiredAttrs, optionalAttrs );
+ *
+ *             // Authenticate as root DN to get permissions to edit the schema.
+ *             ld.authenticate( ROOT_DN, ROOT_PASSWORD );
+ *
+ *             // Add the new object class to the schema.
+ *             newObjClass.add( ld );
+ *
+ *             // Create a new attribute type "hairColor".
+ *             LDAPAttributeSchema newAttrType = new LDAPAttributeSchema(
+ *                 "hairColor", "1.2.3.4.5.4.3.2.1", "Blonde, red, etc",
+ *                 LDAPAttributeSchema.cis, false );
+ *
+ *             // Add the new attribute type to the schema.
+ *             newAttrType.add( ld );
+ *
+ *             // Fetch the schema again to verify that changes were made.
+ *             dirSchema.fetchSchema( ld );
+ *
+ *             // Get and print the new attribute type.
+ *             newAttrType = dirSchema.getAttribute( "hairColor" );
+ *             if ( newAttrType != null )
+ *                 System.out.println("hairColor := "+newAttrType.toString());
+ *
+ *             // Get and print the new object class.
+ *             newObjClass = dirSchema.getObjectClass( "newInetOrgPerson" );
+ *             if ( newObjClass != null )
+ *                 System.out.println("newInetOrgPerson := "+newObjClass.toString());
+ *
+ *             ld.disconnect();
+ *
+ *         } catch ( Exception e ) {
+ *             System.err.println( e.toString() );
+ *             System.exit( 1 );
+ *         }
+ *
+ *         System.exit( 0 );
+ *     }
+ * }
+ * 
+ * + * If you are using the Netscape Directory Server 3.0, you can also + * verify that the class and attribute type have been added through + * the directory server manager (go to Schema | Edit or View Attributes + * or Schema | Edit or View Object Classes). + *

+ * + * To remove the classes and attribute types added by the example, + * see the examples under the LDAPSchemaElement class. + *

+ * + * @see netscape.ldap.LDAPAttributeSchema + * @see netscape.ldap.LDAPObjectClassSchema + * @see netscape.ldap.LDAPMatchingRuleSchema + * @see netscape.ldap.LDAPSchemaElement + * @version 1.0 + * @author Rob Weltman + **/ +public class LDAPSchema { + /** + * Constructs a new LDAPSchema object. + * Once you construct the object, you can get + * the schema by calling fetchSchema. + *

+ * + * You can also print out the schema by using the + * main method. For example, you can enter + * the following command: + *

+     * java netscape.ldap.LDAPSchema myhost.mydomain.com 389
+     * 
+ * + * Note that you need to call fetchSchema + * to get the schema from the server. Constructing the + * object does not fetch the schema. + *

+ * + * @see netscape.ldap.LDAPSchema#fetchSchema + * @see netscape.ldap.LDAPSchema#main + */ + public LDAPSchema() { + } + + /** + * Adds an object class schema definition to the current schema. + * You can also add object class schema definitions by calling the + * add method of your newly constructed + * LDAPObjectClassSchema object. + *

+ * + * To remove an object class schema definition that you have added, + * call the getObjectClass method to get the + * LDAPObjectClassSchema object representing your + * object class and call the remove method. + *

+ * + * NOTE: For information on the add and + * remove methods of LDAPObjectClassSchema, + * see the documentation for LDAPSchemaElement. + * (These methods are inherited from LDAPSchemaElement.) + *

+ * + * @param objectSchema LDAPObjectClassSchema object + * representing the object class schema definition that you want + * to add. + * @see netscape.ldap.LDAPObjectClassSchema + * @see netscape.ldap.LDAPSchemaElement#add + * @see netscape.ldap.LDAPSchemaElement#remove + */ + public void addObjectClass( LDAPObjectClassSchema objectSchema ) { + objectClasses.put( objectSchema.getName().toLowerCase(), + objectSchema ); + } + + /** + * Add an attribute type schema definition to the current schema. + * You can also add attribute type schema definitions by calling the + * add method of your newly constructed + * LDAPAttributeSchema object. + *

+ * + * To remove an attribute type schema definition that you have added, + * call the getAttribute method to get the + * LDAPAttributeSchema object representing your + * attribute type and call the remove method. + *

+ * + * NOTE: For information on the add and + * remove methods of LDAPAttributeSchema, + * see the documentation for LDAPSchemaElement. + * (These methods are inherited from LDAPSchemaElement.) + *

+ * + * @param attrSchema LDAPAttributeSchema object + * representing the attribute type schema definition that you + * want to add. + * @see netscape.ldap.LDAPAttributeSchema + * @see netscape.ldap.LDAPSchemaElement#add + * @see netscape.ldap.LDAPSchemaElement#remove + */ + public void addAttribute( LDAPAttributeSchema attrSchema ) { + attributes.put( attrSchema.getName().toLowerCase(), attrSchema ); + } + + /** + * Add a matching rule schema definition to the current schema. + * You can also add matching rule schema definitions by calling the + * add method of your newly constructed + * LDAPMatchingRuleSchema object. + *

+ * + * To remove an attribute type schema definition that you have added, + * call the getMatchingRule method to get the + * LDAPMatchingRuleSchema object representing your + * matching rule and call the remove method. + *

+ * + * NOTE: For information on the add and + * remove methods of LDAPMatchingRuleSchema, + * see the documentation for LDAPSchemaElement. + * (These methods are inherited from LDAPSchemaElement.) + *

+ * + * @param matchSchema LDAPMatchingRuleSchema object + * representing the matching rule schema definition that you want + * to add. + * @see netscape.ldap.LDAPMatchingRuleSchema + * @see netscape.ldap.LDAPSchemaElement#add + * @see netscape.ldap.LDAPSchemaElement#remove + */ + public void addMatchingRule( LDAPMatchingRuleSchema matchSchema ) { + matchingRules.put( matchSchema.getName().toLowerCase(), matchSchema ); + } + + /** + * Gets an enumeration ofthe object class definitions in this schema. + * @return An enumeration ofobject class definitions. + */ + public Enumeration getObjectClasses() { + return objectClasses.elements(); + } + + /** + * Gets an enumeration ofthe attribute type definitions in this schema. + * @return An enumeration ofattribute type definitions. + */ + public Enumeration getAttributes() { + return attributes.elements(); + } + + /** + * Gets an enumeration ofthe matching rule definitions in this schema. + * @return An enumeration ofmatching rule definitions. + */ + public Enumeration getMatchingRules() { + return matchingRules.elements(); + } + + /** + * Gets the definition of the object class with the specified name. + * @param name Name of the object class that you want to find. + * @return An LDAPObjectClassSchema object representing + * the object class definition, or null if not found. + */ + public LDAPObjectClassSchema getObjectClass( String name ) { + return (LDAPObjectClassSchema)objectClasses.get( name.toLowerCase() ); + } + + /** + * Gets the definition of the attribute type with the specified name. + * @param name Name of the attribute type that you want to find. + * @return An LDAPAttributeSchema object representing + * the attribute type definition, or null if not found. + */ + public LDAPAttributeSchema getAttribute( String name ) { + return (LDAPAttributeSchema)attributes.get( name.toLowerCase() ); + } + + /** + * Gets the definition of a matching rule with the specified name. + * @param name Name of the matching rule that you want to find. + * @return An LDAPMatchingRuleSchema object representing + * the matching rule definition, or null if not found. + */ + public LDAPMatchingRuleSchema getMatchingRule( String name ) { + return (LDAPMatchingRuleSchema)matchingRules.get( name.toLowerCase() ); + } + + /** + * Get an enumeration of the names of the object classes in this schema. + * @return An enumeration of object class names (all lower-case). + */ + public Enumeration getObjectClassNames() { + return objectClasses.keys(); + } + + /** + * Get an enumeration of the names of the attribute types in this schema. + * @return An enumeration of attribute names (all lower-case). + */ + public Enumeration getAttributeNames() { + return attributes.keys(); + } + + /** + * Get an enumeration of the names of the matching rules in this schema. + * @return An enumeration of matching rule names (all lower-case). + */ + public Enumeration getMatchingRuleNames() { + return matchingRules.keys(); + } + + /** + * Retrieve the entire schema from a Directory Server. + * @param ld An active connection to a Directory Server. + * @exception LDAPException on failure. + */ + public void fetchSchema( LDAPConnection ld ) throws LDAPException { + if ( (ld == null) || !ld.isConnected() ) { + throw new LDAPException( "No connection", LDAPException.OTHER ); + } + LDAPEntry entry = ld.read( "" ); + if ( entry == null ) + throw new LDAPException( "", LDAPException.NO_SUCH_OBJECT ); + LDAPAttribute attr = entry.getAttribute( "subschemasubentry" ); + entryName = "cn=schema"; + Enumeration en; + if ( attr != null ) { + en = attr.getStringValues(); + if ( en.hasMoreElements() ) + entryName = (String)en.nextElement(); + } + /* Get the entire schema definition entry */ + entry = ld.read( entryName ); + /* Get all object class definitions */ + attr = entry.getAttribute( "objectclasses" ); + if ( attr != null ) { + en = attr.getStringValues(); + while( en.hasMoreElements() ) { + LDAPObjectClassSchema sch = + new LDAPObjectClassSchema( (String)en.nextElement() ); + addObjectClass( sch ); + } + } + + /* Get all attribute definitions */ + attr = entry.getAttribute( "attributetypes" ); + if ( attr != null ) { + en = attr.getStringValues(); + while( en.hasMoreElements() ) { + LDAPAttributeSchema sch = + new LDAPAttributeSchema( (String)en.nextElement() ); + addAttribute( sch ); + } + } + + /* Matching rules are tricky, because we have to match up a + rule with its use. First get all the uses. */ + Hashtable h = new Hashtable(); + attr = entry.getAttribute( "matchingruleuse" ); + if ( attr != null ) { + en = attr.getStringValues(); + while( en.hasMoreElements() ) { + String use = (String)en.nextElement(); + LDAPMatchingRuleSchema sch = + new LDAPMatchingRuleSchema( null, use ); + h.put( sch.getOID(), use ); + } + } + /* Now get the rules, and assign uses to them */ + attr = entry.getAttribute( "matchingrules" ); + if ( attr != null ) { + en = attr.getStringValues(); + while( en.hasMoreElements() ) { + String raw = (String)en.nextElement(); + LDAPMatchingRuleSchema sch = + new LDAPMatchingRuleSchema( raw, null ); + String use = (String)h.get( sch.getOID() ); + if ( use != null ) + sch = new LDAPMatchingRuleSchema( raw, use ); + addMatchingRule( sch ); + } + } + } + + /** + * Displays the schema (including the descriptions of its object + * classes, attribute types, and matching rules) in an easily + * readable format (not the same as the format expected by + * an LDAP server). + * @return A string containing the schema in printable format. + */ + public String toString() { + String s = "Object classes: "; + Enumeration en = getObjectClasses(); + while( en.hasMoreElements() ) { + s += (String)en.nextElement(); + s += ' '; + } + s += "Attributes: "; + en = getAttributes(); + while( en.hasMoreElements() ) { + s += (String)en.nextElement(); + s += ' '; + } + s += "Matching rules: "; + en = getMatchingRules(); + while( en.hasMoreElements() ) { + s += (String)en.nextElement(); + s += ' '; + } + return s; + } + + /** + * Helper for "main" to print out schema elements. + * @param en Enumeration of schema elements. + */ + private static void printEnum( Enumeration en ) { + while( en.hasMoreElements() ) { + LDAPSchemaElement s = (LDAPSchemaElement)en.nextElement(); + System.out.println( " " + s ); + } + } + + /** + * Fetch the schema from the LDAP server at the specified + * host and port, and print out the schema (including descriptions + * of its object classes, attribute types, and matching rules). + * The schema is printed in an easily readable format (not the + * same as the format expected by an LDAP server). For example, + * you can enter the following command to print the schema: + *

+     * java netscape.ldap.LDAPSchema myhost.mydomain.com 389
+     * 
+ * + * @param args The host name and the port number of the LDAP server + * (for example, netscape.ldap.LDAPSchema directory.netscape.com + * 389). + */ + public static void main( String[] args ) { + if ( args.length < 2 ) { + System.err.println( "Usage: netscape.ldap.LDAPSchema HOST PORT" ); + System.exit(1 ); + } + int port = Integer.parseInt( args[1] ); + LDAPConnection ld = new LDAPConnection(); + try { + ld.connect( args[0], port ); + LDAPSchema schema = new LDAPSchema(); + schema.fetchSchema( ld ); + ld.disconnect(); + System.out.println( "Object classes: " ); + printEnum( schema.getObjectClasses() ); + System.out.println( "\nAttributes: " ); + printEnum( schema.getAttributes() ); + System.out.println( "\nMatching rules: " ); + printEnum( schema.getMatchingRules() ); + System.exit( 0 ); + } catch ( LDAPException e ) { + System.err.println( e ); + } + } + + private Hashtable objectClasses = new Hashtable(); + private Hashtable attributes = new Hashtable(); + private Hashtable matchingRules = new Hashtable(); + String entryName = null; +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSchemaElement.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSchemaElement.java new file mode 100644 index 00000000000..a55b1e06b22 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSchemaElement.java @@ -0,0 +1,223 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import java.util.*; + +/** + * + * Abstract class representing an element (such as an object class + * definition, an attribute type definition, or a matching rule + * definition) in the schema. The specific types of elements are + * represented by the LDAPObjectClassSchema, + * LDAPAttributeSchema, and LDAPMatchingRuleSchema + * subclasses. + *

+ * + * RFC 2252, Lightweight Directory Access Protocol (v3): + * Attribute Syntax Definitions covers the types of information + * that need to be specified in the definition of an object class, + * attribute type, or matching rule. All of these schema elements + * can specify the following information: + *

+ * + *

    + *
  • a name identifying the element + *
  • an OID identifying the element + *
  • a description of the element + *
+ *

+ * + * The LDAPSchemaElement class implements methods that + * you can use with different types of schema elements (object class + * definitions, attribute type definitions, and matching rule definitions). + * You can do the following: + *

    + *
  • get the name of a schema element + *
  • get the OID of a schema element + *
  • get the description of a schema element + *
  • add an element to the schema + *
  • remove an element from the schema + *
+ *

+ * + * @see netscape.ldap.LDAPObjectClassSchema + * @see netscape.ldap.LDAPAttributeSchema + * @see netscape.ldap.LDAPMatchingRuleSchema + * @version 1.0 + **/ + +public abstract class LDAPSchemaElement { + /** + * Construct a blank element. + */ + protected LDAPSchemaElement() { + } + + /** + * Construct a definition explicitly. + * @param name Name of element. + * @param oid Dotted-string object identifier. + * @param description Description of element. + */ + protected LDAPSchemaElement( String name, String oid, + String description ) { + this.name = name; + this.oid = oid; + this.description = description; + } + + /** + * Gets the name of the object class, attribute type, or matching rule. + * @return The name of the object class, attribute type, or + * matching rule. + */ + public String getName() { + return name; + } + + /** + * Gets the object ID (OID) of the object class, attribute type, + * or matching rule in dotted-string format (for example, "1.2.3.4"). + * @return The OID of the object class, attribute type, + * or matching rule. + */ + public String getOID() { + return oid; + } + + /** + * Get the description of the object class, attribute type, + * or matching rule. + * @return The description of the object class, attribute type, + * or matching rule. + */ + public String getDescription() { + return description; + } + + /** + * Add, remove or modify the definition from a Directory. + * @param ld An open connection to a Directory Server. Typically the + * connection must have been authenticated to add a definition. + * @param op Type of modification to make. + * @param atrr Attribute in the schema entry to modify. + * @exception LDAPException if the definition can't be added/removed. + */ + protected void update( LDAPConnection ld, int op, LDAPAttribute attr ) + throws LDAPException { + LDAPAttribute[] attrs = new LDAPAttribute[1]; + attrs[0] = attr; + update( ld, op, attrs ); + } + + /** + * Add, remove or modify the definition from a Directory. + * @param ld An open connection to a Directory Server. Typically the + * connection must have been authenticated to add a definition. + * @param op Type of modification to make. + * @param attrs Attributes in the schema entry to modify. + * @exception LDAPException if the definition can't be added/removed. + */ + protected void update( LDAPConnection ld, int op, LDAPAttribute[] attrs ) + throws LDAPException { + LDAPModificationSet mods = new LDAPModificationSet(); + for( int i = 0; i < attrs.length; i++ ) { + mods.add( op, attrs[i] ); + } + ld.modify( "cn=schema", mods ); + } + + /** + * Add, remove or modify the definition from a Directory. + * @param ld An open connection to a Directory Server. Typically the + * connection must have been authenticated to add a definition. + * @param op Type of modification to make. + * @param name Name of attribute in the schema entry to modify. + * @exception LDAPException if the definition can't be added/removed. + */ + protected void update( LDAPConnection ld, int op, String name ) + throws LDAPException { + LDAPAttribute attr = new LDAPAttribute( name, + getValue() ); + update( ld, op, attr ); + } + + /** + * Adds the current object class, attribute type, or matching rule + * definition to the schema. Typically, most servers + * will require you to authenticate before allowing you to + * edit the schema. + * @param ld The LDAPConnection object representing + * a connection to an LDAP server. + * @exception LDAPException The specified definition cannot be + * added to the schema. + */ + public void add( LDAPConnection ld ) throws LDAPException { + update( ld, LDAPModification.ADD, attrName ); + } + + /** + * Removes the current object class, attribute type, or matching rule + * definition from the schema. Typically, most servers + * will require you to authenticate before allowing you to + * edit the schema. + * @param ld The LDAPConnection object representing + * a connection to an LDAP server. + * @exception LDAPException The specified definition cannot be + * removed from the schema. + */ + public void remove( LDAPConnection ld ) throws LDAPException { + update( ld, LDAPModification.DELETE, attrName ); + } + + /** + * Gets the definition of the current object class, attribute type, or + * matching rule in a format expected by the server when adding the + * definition to the directory. This must be overridden by derived classes. + * @return A String that can be used as a value of the element + * in the schema of a Directory. + */ + public abstract String getValue(); + + public static final int unknown = 0; + public static final int cis = 1; + public static final int binary = 2; + public static final int telephone = 3; + public static final int ces = 4; + public static final int dn = 5; + public static final int integer = 6; + + protected static final String cisString = + "1.3.6.1.4.1.1466.115.121.1.15"; + protected static final String binaryString = + "1.3.6.1.4.1.1466.115.121.1.5"; + protected static final String telephoneString = + "1.3.6.1.4.1.1466.115.121.1.50"; + protected static final String cesString = + "1.3.6.1.4.1.1466.115.121.1.26"; + protected static final String intString = + "1.3.6.1.4.1.1466.115.121.1.27"; + protected static final String dnString = + "1.3.6.1.4.1.1466.115.121.1.12"; + protected String oid = ""; + protected String name = ""; + protected String description = ""; + protected String attrName = null; +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSearchConstraints.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSearchConstraints.java new file mode 100644 index 00000000000..0a1adbdb332 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSearchConstraints.java @@ -0,0 +1,357 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +/** + * Represents a set of search preferences. + * You can set these preferences for a particular search + * by creating an LDAPSearchConstraints object, + * specifying your preferences, and passing the object to + * the LDAPConnection.search method. + *

+ * + * @version 1.0 + */ +public class LDAPSearchConstraints implements Cloneable { + + private int timeLimit; + private int deref; + private int maxRes; + private boolean referrals; + private int batch; + private LDAPRebind m_rebind_proc; + private int m_hop_limit; + private LDAPControl[] m_clientControls; + private LDAPControl[] m_serverControls; + + /** + * Constructs an LDAPSearchConstraints object that specifies + * the default set of search constraints. + */ + public LDAPSearchConstraints() { + timeLimit = 0; + deref = 0; + maxRes = 1000; + referrals = false; + batch = 1; + m_rebind_proc = null; + m_hop_limit = 10; + m_clientControls = null; + m_serverControls = null; + } + + /** + * Constructs a new LDAPSearchConstraints object and allows you + * to specify the search constraints in that object. + *

+ * @param msLimit Maximum time in milliseconds to wait for results (0 + * by default, which means that there is no maximum time limit) + * @param dereference Either LDAPv2.DEREF_NEVER, + * LDAPv2.DEREF_FINDING, + * LDAPv2.DEREF_SEARCHING, or + * LDAPv2.DEREF_ALWAYS (see LDAPConnection.setOption). + * LDAPv2.DEREF_NEVER is the default. + * @param maxResults Maximum number of search results to return + * (1000 by default) + * @param doReferrals Specify true to follow referrals + * automatically, or False to throw an + * LDAPReferralException error if the server sends back + * a referral (False by default) + * @param batchSize Specify the number of results to return at a time + * (1 by default) + * @param rebind_proc Specifies the object of the class that + * implements the LDAPRebind interface (you need to + * define this class). The object will be using when the client + * follows referrals automatically. The object provides the client + * with a method for getting the distinguished name and password + * used to authenticate to another LDAP server during a referral. + * (This field is null by default.) + * @param hop_limit Maximum number of referrals to follow in a + * sequence when attempting to resolve a request. + * @see netscape.ldap.LDAPConnection#setOption(int, java.lang.Object) + * @see netscape.ldap.LDAPConnection#search(netscape.ldap.LDAPUrl, netscape.ldap.LDAPSearchConstraints) + * @see netscape.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, netscape.ldap.LDAPSearchConstraints) + */ + public LDAPSearchConstraints( int msLimit, int dereference, + int maxResults, boolean doReferrals, int batchSize, + LDAPRebind rebind_proc, int hop_limit) { + timeLimit = msLimit; + deref = dereference; + maxRes = maxResults; + referrals = doReferrals; + batch = batchSize; + m_rebind_proc = rebind_proc; + m_hop_limit = hop_limit; + m_clientControls = null; + m_serverControls = null; + } + + /** + * Returns the maximum number of milliseconds to wait for any operation + * under these search constraints. If 0, there is no maximum time limit + * on waiting for the operation results. + * @return Maximum number of milliseconds to wait for operation results. + */ + public int getTimeLimit() { + return timeLimit*1000; + } + + /** + * Specifies how aliases should be dereferenced. + * @return LDAPv2.DEREF_NEVER to + * never follow ("dereference") aliases, + * LDAPv2.DEREF_FINDING to dereference when finding + * the starting point for the search (but not when searching + * under that starting entry), LDAPv2.DEREF_SEARCHING + * to dereference when searching the entries beneath the + * starting point of the search (but not when finding the starting + * entry), or LDAPv2.DEREF_ALWAYS to always + * dereference aliases. + */ + public int getDereference() { + return deref; + } + + /** + * Returns the maximum number of search results to be returned; 0 means + * no limit. + * @return Maximum number of search results to be returned. + */ + public int getMaxResults() { + return maxRes; + } + + /** + * Specifies whether nor not referrals are followed automatically. + * Returns true if referrals are to be followed automatically, + * or false if referrals throw an LDAPReferralException. + * @return true if referrals are followed automatically, False + * if referrals throw an LDAPReferralException. + */ + public boolean getReferrals() { + return referrals; + } + + /** + * Returns the suggested number of results to return at a time during + * search. This should be 0 if intermediate results are not needed, and + * 1 if results are to be processed as they come in. + * @return Number of results to return at a time. + */ + public int getBatchSize() { + return batch; + } + + /** + * Returns the object that provides the method for getting + * authentication information. This object must belong to a class + * that implements the LDAPRebind interface. + * @return Object to be used to obtain information for + * authenticating to other LDAP servers during referrals. + * @see netscape.ldap.LDAPRebind + * @see netscape.ldap.LDAPRebindAuth + */ + public LDAPRebind getRebindProc() { + return m_rebind_proc; + } + + /** + * Returns the maximum number of hops to follow during a referral. + * @return Maximum number of hops to follow during a referral. + */ + public int getHopLimit() { + return m_hop_limit; + } + + /** + * Returns any client controls to be applied by the client + * to LDAP operations. + * @return Client controls to be applied by the client to LDAP operations. + * @see netscape.ldap.LDAPControl + * @see netscape.ldap.LDAPConnection#getOption + * @see netscape.ldap.LDAPConnection#setOption + */ + public LDAPControl[] getClientControls() { + return m_clientControls; + } + + /** + * Returns any server controls to be applied by the server + * to LDAP operations. + * @return Server controls to be applied by the server to LDAP operations. + * @see netscape.ldap.LDAPControl + * @see netscape.ldap.LDAPConnection#getOption + * @see netscape.ldap.LDAPConnection#setOption + */ + public LDAPControl[] getServerControls() { + return m_serverControls; + } + + /** + * Sets the maximum number of milliseconds to wait for any operation + * under these search constraints. If 0, there is no maximum time limit + * on waiting for the operation results. + * @param msLimit Maximum number of milliseconds to wait for operation results. + * (0 by default, which means that there is no maximum time limit.) + */ + public void setTimeLimit( int msLimit ) { + if (msLimit != 0) + timeLimit = Math.max( 1, (msLimit + 500) / 1000 ); + } + + /** + * Sets a preference indicating how aliases should be dereferenced. + * @param dereference LDAPv2.DEREF_NEVER to + * never follow ("dereference") aliases, + * LDAPv2.DEREF_FINDING to dereference when finding + * the starting point for the search (but not when searching + * under that starting entry), LDAPv2.DEREF_SEARCHING + * to dereference when searching the entries beneath the + * starting point of the search (but not when finding the starting + * entry), or LDAPv2.DEREF_ALWAYS to always + * dereference aliases. + */ + public void setDereference( int dereference ) { + deref = dereference; + } + + /** + * Sets the maximum number of search results to be returned; 0 means + * no limit. (By default, this is set to 1000.) + * @param maxResults Maximum number of search results to be returned. + */ + public void setMaxResults( int maxResults ) { + maxRes = maxResults; + } + + /** + * Specifies whether nor not referrals are followed automatically. + * Returns true if referrals are to be followed automatically, + * or false if referrals throw an LDAPReferralException. + * (By default, this is set to false.) + *

+ * If you set this to true, you need to define a class that implements + * the LDAPRebind interface. You need to create an object of this class + * and pass the object to the setRebindProc method. This identifies the method + * for retrieving authentication information, which is used when connecting to other LDAP + * servers during referrals. + * @param doReferrals Set to true if referrals should be followed automatically, + * or False if referrals should throw an LDAPReferralException. + * @see netscape.ldap.LDAPRebind + * @see netscape.ldap.LDAPRebindAuth + */ + public void setReferrals( boolean doReferrals ) { + referrals = doReferrals; + } + + /** + * Sets the suggested number of results to return at a time during search. + * This should be 0 if intermediate results are not needed, and 1 if + * results are to be processed as they come in. (By default, this is 1.) + * @param batchSize Number of results to return at a time. + */ + public void setBatchSize( int batchSize ) { + batch = batchSize; + } + + /** + * Specifies the object that provides the method for getting + * authentication information. This object must belong to a class + * that implements the LDAPRebind interface. + * (By default, this is null.) + * @param rebind_proc Object to be used to obtain information for + * authenticating to other LDAP servers during referrals. + */ + public void setRebindProc( LDAPRebind rebind_proc ) { + m_rebind_proc = rebind_proc; + } + + /** + * Sets maximum number of hops to follow in sequence during a referral. + * (By default, this is 10.) + * @param hop_limit Maximum number of hops to follow during a referral. + */ + public void setHopLimit( int hop_limit ) { + m_hop_limit = hop_limit; + } + + /** + * Sets a client control for LDAP operations. + * @param control Client control for LDAP operations. + * @see netscape.ldap.LDAPControl + */ + public void setClientControls( LDAPControl control ) { + m_clientControls = new LDAPControl[1]; + m_clientControls[0] = control; + } + + /** + * Sets an array of client controls for LDAP operations. + * @param controls Array of client controls for LDAP operations. + * @see netscape.ldap.LDAPControl + */ + public void setClientControls( LDAPControl[] controls ) { + m_clientControls = controls; + } + + /** + * Sets a server control for LDAP operations. + * @param control Server control for LDAP operations. + * @see netscape.ldap.LDAPControl + */ + public void setServerControls( LDAPControl control ) { + m_serverControls = new LDAPControl[1]; + m_serverControls[0] = control; + } + + /** + * Sets an array of server controls for LDAP operations. + * @param controls An array of server controls for LDAP operations. + * @see netscape.ldap.LDAPControl + */ + public void setServerControls( LDAPControl[] controls ) { + m_serverControls = controls; + } + + /** + * Makes a copy of an existing set of search constraints. + * @returns A copy of an existing set of search constraints. + */ + public Object clone() { + LDAPSearchConstraints o = new LDAPSearchConstraints(); + + o.timeLimit = this.timeLimit; + o.deref = this.deref; + o.maxRes = this.maxRes; + o.referrals = this.referrals; + o.batch = this.batch; + o.m_rebind_proc = this.m_rebind_proc; + o.m_hop_limit = this.m_hop_limit; + if ( (this.m_clientControls != null) && (this.m_clientControls.length > 0) ) { + o.m_clientControls = new LDAPControl[this.m_clientControls.length]; + for( int i = 0; i < this.m_clientControls.length; i++ ) + o.m_clientControls[i] = this.m_clientControls[i]; + } + if ( (this.m_serverControls != null) && (this.m_serverControls.length > 0) ) { + o.m_serverControls = new LDAPControl[this.m_serverControls.length]; + for( int i = 0; i < this.m_serverControls.length; i++ ) + o.m_serverControls[i] = this.m_serverControls[i]; + } + return o; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSearchListener.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSearchListener.java new file mode 100644 index 00000000000..6c0943f5e08 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSearchListener.java @@ -0,0 +1,132 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import java.util.*; +import netscape.ldap.client.*; + +/** + * This implements an object for taking the asynchronous LDAP responses + * and making them appear somewhat synchronized. Uses built-in Java + * monitors to block until a response is received. This is also used + * to communicate exceptions across threads. This is used in particular + * for LDAP search operations; all other operations use the generic + * LDAPResponseListener object. + * + * This class is part of the implementation; it is of no interest to + * developers. + * + * @version 1.0 + */ +class LDAPSearchListener extends LDAPResponseListener { + private Vector searchResults; + private int lastRetrieved = -1; + + // this instance variable is only for cache purpose + private Long m_key = null; + + /** + * Constructs a LDAP search listener. + */ + LDAPSearchListener ( LDAPConnection conn ) { + super ( conn ); + searchResults = new Vector (); + } + + /** + * Informs the object of new search items (but not a response) + * @param newResult new search result message + */ + synchronized void addSearchResult (JDAPMessage newResult) { + searchResults.addElement (newResult); + notifyAll (); + } + + /** + * Returns a collection of the currently-known search results. + * @return search result in enumeration + */ + Enumeration getSearchResults () { + return searchResults.elements (); + } + + /** + * Returns a count of the currently-known search results. + * @return search result count + */ + int getCount () { + return searchResults.size (); + } + + /** + * Resets the state of this object, so it can be recycled. + */ + void reset () { + super.reset(); + lastRetrieved = -1; + if ( searchResults != null ) + searchResults.removeAllElements(); + } + + /** + * Returns the next server search result. This method only makes + * sense in asynchronous mode. It will block if no new messages have + * been received since the last call to nextResult. If a response + * is received indicating that there are no more matches, this + * method returns null. + * @return jdap message + */ + synchronized JDAPMessage nextResult () { + while (lastRetrieved >= (searchResults.size()-1)) { + if (isResponseReceived()) { + searchResults.removeAllElements(); + return null; + } + + try { + wait(); + } catch (InterruptedException e ) { + } + } + + lastRetrieved++; + JDAPMessage result = (JDAPMessage)searchResults.elementAt (lastRetrieved); + /* Allow garbage collection to free this result */ + searchResults.setElementAt (null, lastRetrieved); + return result; + } + + /** + * Set the key of the cache entry. The listener needs to know this value + * when the results get processed in the queue. After the results have been + * saved in the vector, then the key and a vector of results are put in + * the cache. + * @param key The key of the cache entry + */ + void setKey(Long key) { + m_key = key; + } + + /** + * Get the key of the cache entry. + * @return The key of the cache entry + */ + Long getKey() { + return m_key; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSearchResults.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSearchResults.java new file mode 100644 index 00000000000..2f1e8f1ffff --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSearchResults.java @@ -0,0 +1,506 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import java.util.*; +import netscape.ldap.client.*; +import netscape.ldap.client.opers.*; +import java.io.*; + +/** + * The results of an LDAP search operation, represented as an enumeration. + * Note that you can only iterate through this enumeration once: if you + * need to use these results more than once, make sure to save the + * results in a separate location. + *

+ * + * You can also use the results of a search in progress to abandon that search + * operation. + *

+ * + * @version 1.0 + * @see netscape.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean) + * @see netscape.ldap.LDAPConnection#abandon(netscape.ldap.LDAPSearchResults) + */ +public class LDAPSearchResults implements Enumeration { + + private int current = 0; + private Vector entries = null; + private LDAPSearchListener resultSource; + private boolean searchComplete = false; + private LDAPConnection connectionToClose; + private LDAPConnection currConn; + private boolean persistentSearch = false; + private Vector cacheEntries = null; + private LDAPSearchConstraints currCons; + private String currBase; + private int currScope; + private String currFilter; + private String[] currAttrs; + private boolean currAttrsOnly; + private Vector referralResults = new Vector(); + private int totalReferralEntries = 0; + + // only used for the persistent search + private boolean firstResult = false; + + /** + * Constructs an enumeration of search results. + * Note that this does not actually generate the results; + * you need to call LDAPConnection.search to + * perform the search and get the results. + * @see netscape.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean) + */ + public LDAPSearchResults() { + entries = new Vector(); + current = 0; + connectionToClose = null; + searchComplete = true; + cacheEntries = null; + } + + LDAPSearchResults(LDAPConnection conn, LDAPSearchConstraints cons, + String base, int scope, String filter, String[] attrs, boolean attrsOnly) { + this(); + currConn = conn; + currCons = cons; + currBase = base; + currScope = scope; + currFilter = filter; + currAttrs = attrs; + currAttrsOnly = attrsOnly; + } + + /** + * Constructs an enumeration of search results. Used when returning results + * from a cache. + * @param v The vector containing LDAPEntries. + * @see netscape.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean) + */ + LDAPSearchResults(Vector v) { + this(); + cacheEntries = (Vector)v.clone(); + } + + LDAPSearchResults(Vector v, LDAPConnection conn, LDAPSearchConstraints cons, + String base, int scope, String filter, String[] attrs, boolean attrsOnly) { + this(v); + currConn = conn; + currCons = cons; + currBase = base; + currScope = scope; + currFilter = filter; + currAttrs = attrs; + currAttrsOnly = attrsOnly; + } + + void add( JDAPProtocolOp sr ) { + if (sr instanceof JDAPSearchResponse) + add((JDAPSearchResponse)sr); + else if (sr instanceof JDAPSearchResultReference) + add((JDAPSearchResultReference)sr); + } + + /** + * Adds one result of a search (from JDAP) to the object. + * @param sr A search response in JDAP format + */ + void add( JDAPSearchResponse sr ) { + LDAPAttribute[] lattrs = sr.getAttributes(); + LDAPAttributeSet attrs; + if ( lattrs != null ) + attrs = new LDAPAttributeSet( lattrs ); + else + attrs = new LDAPAttributeSet(); + + String dn = sr.getObjectName(); + LDAPEntry entry = new LDAPEntry( dn, attrs ); + entries.addElement( entry ); + } + + /** + * Adds search reference to this object. + */ + void add( JDAPSearchResultReference sr ) { + /* build LDAPReferenceException out of this references */ + String urls[] = sr.getUrls(); + if (urls == null) + return; + entries.addElement(new LDAPReferralException(null, 0, urls)); + } + + void add(LDAPException e) { + entries.addElement(e); + } + + /** + * Prepares to return asynchronous results from a search + * @param l Listener which will provide results + */ + void associate( LDAPSearchListener l) { + resultSource = l; + searchComplete = false; + } + + void associatePersistentSearch( LDAPSearchListener l) { + resultSource = l; + persistentSearch = true; + searchComplete = false; + firstResult = true; + } + + void addReferralEntries(LDAPSearchResults res) { + referralResults.addElement(res); + } + + /** + * For asynchronous search, this mechanism allows the programmer to + * close a connection whenever the search completes. + * @param toClose Connection to close when the search terminates + */ + void closeOnCompletion (LDAPConnection toClose) { + if (searchComplete) { + try { + toClose.disconnect(); + } catch (LDAPException e) { + } + } else { + connectionToClose = toClose; + } + } + + + /** + * Basic quicksort algorithm. + */ + void quicksort (LDAPEntry[] toSort, LDAPEntryComparator compare, + int low, int high) { + if (low >= high) + return; + + LDAPEntry pivot = toSort[low]; + int slow = low-1, shigh = high+1; + + while (true) { + do + shigh--; + while (compare.isGreater (toSort[shigh], pivot)); + do + slow++; + while (compare.isGreater (pivot, toSort[slow])); + + if (slow >= shigh) + break; + + LDAPEntry temp = toSort[slow]; + toSort[slow] = toSort[shigh]; + toSort[shigh] = temp; + } + + quicksort (toSort, compare, low, shigh); + quicksort (toSort, compare, shigh+1, high); + } + + /** + * Sorts the search results. + *

+ * + * The comparator (LDAPEntryComparator) determines the + * sort order used. For example, if the comparator uses the uid + * attribute for comparison, the search results are sorted according to + * uid. + *

+ * + * The following section of code sorts results in ascending order, + * first by surname and then by common name. + * + *

+     * String[]  sortAttrs = {"sn", "cn"};
+     * boolean[] ascending = {true, true};
+     *
+     * LDAPConnection ld = new LDAPConnection();
+     * ld.connect( ... );
+     * LDAPSearchResults res = ld.search( ... );
+     * res.sort( new LDAPCompareAttrNames(sortAttrs, ascending) );
+     * 
+ * NOTE: If the search results arrive asynchronously, the sort + * method blocks until all the results are returned. + *

+ * + * If some of the elements of the Enumeration have already been fetched, + * the cursor is reset to the (new) first element. + *

+ * + * @param compare Comparator used to determine the sort order of the results. + * @see LDAPEntryComparator + */ + public synchronized void sort(LDAPEntryComparator compare) { + while (!searchComplete) { + fetchResult(); + } + + // if automatic referral, then add to the entries, otherwise, dont do it + // since the elements in referralResults are LDAPReferralException. + if (currCons.getReferrals()) + while (referralResults.size() > 0) { + Object obj = null; + if ((obj=nextReferralElement()) != null) + entries.addElement(obj); + } + + // reset it to 0 since all the referral entries are now in the entries + // vector + totalReferralEntries = 0; + + int numEntries = entries.size(); + if (numEntries <= 0) + return; + + LDAPEntry[] toSort = new LDAPEntry[numEntries]; + entries.copyInto (toSort); + + if (toSort.length > 1) + quicksort (toSort, compare, 0, numEntries-1); + + entries.removeAllElements(); + for (int i = 0; i < numEntries; i++) + entries.addElement (toSort[i]); + + current = 0; + } + + /** + * Returns the next LDAP entry from the search results + * and throws an exception if the next result is a referral. + *

+ * + * You can use this method in conjunction with the + * hasMoreElements method to iterate through + * each entry in the search results. For example: + *

+     * LDAPSearchResults res = ld.search( MY_SEARCHBASE,
+     *                         LDAPConnection.SCOPE_BASE, MY_FILTER,
+     *                         null, false );
+     * while ( res.hasMoreElements() ) {
+     *   try {
+     *     LDAPEntry findEntry = res.next();
+     *   } catch ( LDAPReferralException e ) {
+     *     LDAPUrl refUrls[] = e.getURLs();
+     *     for ( int i = 0; i < refUrls.length; i++ ) {
+     *     // Your code for handling referrals
+     *     }
+     *     continue;
+     *   }
+     *   ...
+     * }
+     * 
+ * @return The next LDAP entry in the search results. + * @exception LDAPReferralException A referral (thrown + * if the next result is a referral). + * @see netscape.ldap.LDAPSearchResults#hasMoreElements() + */ + public LDAPEntry next() throws LDAPException { + Object o = nextElement(); + if ((o instanceof LDAPReferralException) || + (o instanceof LDAPException)) + throw (LDAPException)o; + if (o instanceof LDAPEntry) + return (LDAPEntry)o; + return null; + } + + /** + * Returns the next result from a search. You can use this method + * in conjunction with the hasMoreElements method to + * iterate through all elements in the search results. + *

+ * + * Make sure to cast the + * returned element as the correct type. For example: + *

+     * LDAPSearchResults res = ld.search( MY_SEARCHBASE,
+     *                         LDAPConnection.SCOPE_BASE, MY_FILTER,
+     *                         null, false );
+     * while ( res.hasMoreElements() ) {
+     *   LDAPEntry findEntry = (LDAPEntry)res.nextElement();
+     *   ...
+     * }
+     * 
+ * @return The next element in the search results. + * @see netscape.ldap.LDAPSearchResults#hasMoreElements() + */ + public Object nextElement() { + if ((cacheEntries == null) && (!persistentSearch) && (current >= entries.size()-1)) + fetchResult(); + + if ( current < entries.size() ) { + current++; + /* Invalidate our reference to the entry, so it can be + garbage collected */ + Object next = entries.elementAt( current-1 ); + entries.setElementAt( null, current-1 ); + return next; + } + + if (referralResults.size() > 0) { + return nextReferralElement(); + } + + return null; + } + + Object nextReferralElement() { + LDAPSearchResults res = + (LDAPSearchResults)referralResults.elementAt(0); + if ((!res.persistentSearch && res.hasMoreElements()) || (res.persistentSearch)) { + Object obj = res.nextElement(); + if (obj != null) { + totalReferralEntries++; + return obj; + } + + if ((obj == null) || (!res.hasMoreElements())) + referralResults.removeElementAt(0); + } + else + referralResults.removeElementAt(0); + + return null; + } + + /** + * Returns true if there are more search results + * to be returned. You can use this method in conjunction with the + * nextElement or next methods to iterate + * through each entry in the results. For example: + *
+     * LDAPSearchResults res = ld.search( MY_SEARCHBASE,
+     *                         LDAPConnection.SCOPE_BASE, MY_FILTER,
+     *                         null, false );
+     * while ( res.hasMoreElements() ) {
+     *   LDAPEntry findEntry = (LDAPEntry)res.nextElement();
+     *   ...
+     * }
+     * 
+ * @return true if there are more search results + * @see netscape.ldap.LDAPSearchResults#nextElement() + * @see netscape.ldap.LDAPSearchResults#next() + */ + public boolean hasMoreElements() { + if (current >= entries.size()-1) + fetchResult(); + + while (referralResults.size() > 0) { + LDAPSearchResults res = + (LDAPSearchResults)referralResults.elementAt(0); + if (res.hasMoreElements()) { + + return true; + } else + referralResults.removeElementAt(0); + } + + return ( current < entries.size() ); + } + + /** + * Returns a count of the entries in the search results. + * @return Count of entries found by the search. + */ + public int getCount() { + return (current + totalReferralEntries); + } + + /** + * Returns message id. + * @return Message id. + */ + int getID() { + if ( (resultSource == null) || searchComplete ) + return -1; + return resultSource.getID(); + } + + /** + * Terminates the iteration; called on LDAPConnection.abandon(). + */ + void abandon() { + synchronized( this ) { + searchComplete = true; + } + } + + /** + * Fetchs the next result, for asynchronous searches. + */ + private synchronized void fetchResult() { + // if using the results from cache + if ((cacheEntries != null) && (current < cacheEntries.size()-1)) + { + // always retrieves the one at current+1 because the first element + // in the cacheEntries always contains the size of all elements in the + // cacheEntries vector. + LDAPEntry entry = (LDAPEntry)cacheEntries.elementAt(current+1); + LDAPEntry e = new LDAPEntry(entry.getDN(), entry.getAttributeSet()); + entries.addElement(e); + return; + } + + /* Asynchronous case */ + if ( resultSource != null ) { + synchronized( this ) { + if (searchComplete || firstResult) + { + firstResult = false; + return; + } + + JDAPMessage msg = resultSource.nextResult(); + if (msg == null) { + try { + // check response and see if we need to do referral + // v2: referral stored in the JDAPResult + JDAPMessage response = resultSource.getResponse(); + currConn.checkSearchMsg(this, response, currCons, + currBase, currScope, currFilter, currAttrs, currAttrsOnly); + } catch (LDAPException e) { + System.err.println("Exception: "+e); + } finally { + currConn.releaseSearchListener(resultSource); + } + searchComplete = true; + if (connectionToClose != null) { + try { + connectionToClose.disconnect (); + } catch (LDAPException e) { + } + connectionToClose = null; + } + return; + } else { + try { + currConn.checkSearchMsg(this, msg, currCons, + currBase, currScope, currFilter, currAttrs, currAttrsOnly); + } catch (LDAPException e) { + System.err.println("Exception: "+e); + } + } + } + } + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSocketFactory.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSocketFactory.java new file mode 100644 index 00000000000..cec55ad8650 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSocketFactory.java @@ -0,0 +1,55 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import java.util.*; +import java.io.*; +import java.net.*; + +/** + * Represents a socket connection that you can use to connect to an + * LDAP server. You can write a class that implements this interface + * if you want to use a TLS socket to connect to a secure server. + * (The LDAPSSLSocketFactory class, which is included + * in the netscape.ldap package, implements this + * interface for SSL connections.) + *

+ * + * When you construct a new LDAPConnection + * object, you can specify that the connection uses his socket by + * passing the constructor an object of the class that implements + * this interface. + *

+ * + * @version 1.0 + * @see LDAPConnection#LDAPConnection(netscape.ldap.LDAPSocketFactory) + * @see LDAPSSLSocketFactory + */ +public interface LDAPSocketFactory { + /** + * Returns a socket to the specified host name and port number. + *

+ * + * @param host Name of the host that you want to connect to. + * @param port Port number that you want to connect to. + * @exception LDAPException Failed to create the socket. + * @see LDAPSSLSocketFactory#makeSocket(java.lang.String,int) + */ + public Socket makeSocket(String host, int port) + throws LDAPException; +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSortKey.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSortKey.java new file mode 100644 index 00000000000..209fd2558dd --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPSortKey.java @@ -0,0 +1,147 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +/** + * Represents sorting instructions for a particular attribute. + * + * @version 1.0 + */ +public class LDAPSortKey { + public final static int REVERSE = 0x81; + + /** + * Constructs a new LDAPSortKey object that will + * sort based on the specified instructions. + * @param keyDescription A single attribute specification to sort by. + * If preceded by a hyphen ("-"), the attribute is sorted in reverse order. + * You can also specify the object ID (OID) of a matching rule after + * a colon (":"). For example: + *

+ *

    + *
  • "cn" (sort by the cn attribute)

    + *

  • "-cn" (sort by the cn attribute in + * reverse order)

    + *

  • "-cn:1.2.3.4" (sort by the cn + * attribute in reverse order and use the matching rule identified + * by the OID 1.2.3.4)

    + *

+ * @see netscape.ldap.controls.LDAPPagedControl + * @see netscape.ldap.controls.LDAPSortControl + * @see netscape.ldap.controls.LDAPVirtualListControl + */ + public LDAPSortKey( String keyDescription ) { + if ( (keyDescription != null) && (keyDescription.length() > 0) ) { + if ( keyDescription.charAt( 0 ) == '-' ) { + m_reverse = true; + m_key = keyDescription.substring( 1 ); + } else { + m_reverse = false; + m_key = keyDescription; + } + int colonIndex = m_key.indexOf( ':' ); + if ( colonIndex == 0 ) + m_key = null; + else if ( colonIndex > 0 ) { + m_matchRule = m_key.substring( colonIndex+1 ); + m_key = m_key.substring( 0, colonIndex-1 ); + } + } + } + + /** + * Constructs a new LDAPSortKey object that will + * sort based on the specified attribute and sort order. + * @param key A single attribute to sort by. For example: + *

+ *

    + *
  • "cn" (sort by the cn attribute) + *
  • "givenname" (sort by the givenname + * attribute) + *
+ * @param reverse If true, the sorting is done in + * descending order. + * @see netscape.ldap.controls.LDAPPagedControl + * @see netscape.ldap.controls.LDAPSortControl + * @see netscape.ldap.controls.LDAPVirtualListControl + */ + public LDAPSortKey( String key, + boolean reverse) { + m_key = key; + m_reverse = reverse; + m_matchRule = null; + } + + /** + * Constructs a new LDAPSortKey object that will + * sort based on the specified attribute, sort order, and matching + * rule. + * @param key A single attribute to sort by. For example: + *

+ *

    + *
  • "cn" (sort by the cn attribute) + *
  • "givenname" (sort by the givenname + * attribute) + *
+ * @param reverse If true, the sorting is done in + * descending order. + * @param matchRule Object ID (OID) of the matching rule for + * the attribute (for example, 1.2.3.4). + * @see netscape.ldap.controls.LDAPPagedControl + * @see netscape.ldap.controls.LDAPSortControl + * @see netscape.ldap.controls.LDAPVirtualListControl + */ + public LDAPSortKey( String key, + boolean reverse, + String matchRule) { + m_key = key; + m_reverse = reverse; + m_matchRule = matchRule; + } + + /** + * Returns the attribute to sort by. + * @return A single attribute to sort by. + */ + public String getKey() { + return m_key; + } + + /** + * Returns true if sorting is to be done in descending order. + * @return true if sorting is to be done in descending order. + */ + public boolean getReverse() { + return m_reverse; + } + + /** + * Returns the object ID (OID) of the matching rule used for sorting. + * If no matching rule is specified, null is returned. + * @return The object ID (OID) of the matching rule, or null + * if the sorting instructions specify no matching rule. + */ + public String getMatchRule() { + return m_matchRule; + } + + private String m_key; + private boolean m_reverse; + private String m_matchRule; +} + diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPUrl.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPUrl.java new file mode 100644 index 00000000000..4cb978c378e --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPUrl.java @@ -0,0 +1,581 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import java.util.*; +import java.io.*; +import java.net.MalformedURLException; + +/** + * Represents an LDAP URL. The complete specification for LDAP URLs is in + * RFC 1959. LDAP URLs have the following format: + * + *
+ * "ldap://" [ hostName [":" portNumber] ] "//"
+ *                      distinguishedName
+ *          ["?" attributeList ["?" scope
+ *                      "?" filterString ] ]
+ * 
+ * where + *

+ *

    + *
  • all text within double-quotes are literal

    + *

  • hostName and portNumber + * identify the location of the LDAP server.

    + *

  • distinguishedName is the name of an entry + * within the given directory (the entry represents the starting point + * of the search)

    + *

  • attributeList contains a list of attributes + * to retrieve (if null, fetch all attributes). This is a comma-delimited + * list of attribute names.

    + *

  • scope is one of the following: + *
      + *
    • base indicates that this is a search only for the + * specified entry + *
    • one indicates that this is a search for matching entries + * one level under the specified entry (and not including the entry itself) + *
    • sub indicates that this is a search for matching entries + * at all levels under the specified entry (including the entry itself) + *
    + *

    + * If not specified, scope is base by + * default.

    + *

  • filterString is a human-readable representation + * of the search criteria. This value is used only for one-level or subtree + * searches.

    + *

+ *

+ * Note that if scope and filterString + * are not specified, an LDAP URL identifies exactly one entry in the + * directory.

+ * The same encoding rules for other URLs (e.g. HTTP) apply for LDAP + * URLs. Specifically, any "illegal" characters are escaped with + * %HH, where HH represent the + * two hex digits which correspond to the ASCII value of the character. + * This encoding is only legal (or necessary) on the DN and filter portions + * of the URL. + * + * @version 1.0 + */ +public class LDAPUrl { + + public static String defaultFilter = "(objectClass=*)"; + + private String hostName; + private int portNumber; + private String DN; + private Vector attributes; + private int scope; + private String filter; + private String URL; + + /** + * Constructs a URL object with the specified string as URL. + * @param url LDAP search expression in URL form + * @exception MalformedURLException failed to parse URL + */ + public LDAPUrl (String url) throws java.net.MalformedURLException { + StringTokenizer urlParser = new StringTokenizer (url, ":/?", true); + String currentToken; + String attributeList = null; + attributes = null; + scope = LDAPv2.SCOPE_BASE; + filter = defaultFilter; + URL = url; + + try { + currentToken = urlParser.nextToken(); + if (!currentToken.equalsIgnoreCase ("LDAP")) + throw new MalformedURLException (); + + urlParser.nextToken(); // ":" + urlParser.nextToken(); // "/" + urlParser.nextToken(); // "/" + + currentToken = urlParser.nextToken(); + + if (currentToken.equals ("/")) { + hostName = null; + portNumber = LDAPv2.DEFAULT_PORT; + } else { + hostName = currentToken; + if (urlParser.countTokens() == 0) { + portNumber = LDAPv2.DEFAULT_PORT; + return; + } + currentToken = urlParser.nextToken (); // either ":" or "/" + + if (currentToken.equals (":")) { + portNumber = Integer.parseInt (urlParser.nextToken()); + if (urlParser.countTokens() == 0) { + return; + } + urlParser.nextToken (); // "/" + } else + portNumber = LDAPv2.DEFAULT_PORT; + } + + if (urlParser.countTokens() == 0) + return; + + DN = decode (urlParser.nextToken ()); + + // it retrieves the ? token, meaning no DN is supplied + if (DN.equals("?")) + DN = ""; + else if (DN.equals("/")) + throw new MalformedURLException (); + + if (urlParser.hasMoreTokens ()) { + // we have a "?attributeList" portion + String str = null; + str = readNextConstruct(urlParser); + + // if attribute + if ((str != null) && (isAttribute(str))) { + // it retrieves the ? token, meaning no attribute is supplied + if (str.equals("?")) { + attributeList = null; + str = urlParser.nextToken(); + } + else { + attributeList = decode(str); + str = readNextConstruct(urlParser); + } + } + + // if scope + if ((str != null) && ((scope = getScope(str)) != -1)) + str = readNextConstruct(urlParser); + // no scope is supplied + else if ((str != null) && (str.equals("?"))) { + scope = LDAPv2.SCOPE_BASE; + str = urlParser.nextToken(); + } else { + scope = LDAPv2.SCOPE_BASE; + } + + // if filter + if ((str != null) && (isFilter(str))) { + filter = decode(str); + str = readNextConstruct(urlParser); + } + } + } catch (NumberFormatException nf) { + throw new MalformedURLException (); + } + + if (attributeList != null) { + StringTokenizer attributeParser = new + StringTokenizer (attributeList, ", "); + attributes = new Vector (); + + while (attributeParser.hasMoreTokens()) + attributes.addElement (attributeParser.nextToken()); + } + } + + /** + * Constructs with the specified host, port, and DN. This form is used to + * create URL references to a particular object in the directory. + * @param host Host name of LDAP server, or null for "nearest X.500/LDAP" + * @param port Port number for LDAP server (use LDAPv2.DEFAULT_PORT for + * default port) + * @param DN Distinguished name of object + */ + public LDAPUrl (String host, int port, String DN) { + if (host != null) { + if (port != LDAPv2.DEFAULT_PORT) + URL = "LDAP://" + host + ":" + String.valueOf (port) + + "/" + encode (DN); + else + URL = "LDAP://" + host + "/" + encode (DN); + } else + URL = "LDAP:///" + encode (DN); + + this.hostName = host; + this.DN = DN; + portNumber = port; + filter = defaultFilter; + attributes = null; + scope = LDAPv2.SCOPE_BASE; + } + + /** + * Constructs a full-blown LDAP URL to specify an LDAP search operation. + * @param host Host name of LDAP server, or null for "nearest X.500/LDAP" + * @param port Port number for LDAP server (use LDAPv2.DEFAULT_PORT for + * default port) + * @param DN Distinguished name of object + * @param attributes List of attributes to return. Use null for "all + * attributes" + * @param scope Depth of search (in DN namespace). Use one of SCOPE_BASE, + * SCOPE_ONE, SCOPE_SUB from LDAPv2 + * @param filter LDAP fitler string (as defined in RFC 1558) use null for + * no filter (this effectively makes the URL reference a single object) + */ + public LDAPUrl (String host, int port, String DN, + String attributes[], int scope, String filter) { + + if (attributes != null) { + Vector list = new Vector(); + for (int k = 0; k < attributes.length; k++) { + list.addElement(attributes[k]); + } + initialize(host, port, DN, list.elements(), scope, filter); + } else { + initialize(host, port, DN, null, scope, filter); + } + } + + /** + * Constructs a full-blown LDAP URL to specify an LDAP search operation. + * @param host Host name of LDAP server, or null for "nearest X.500/LDAP" + * @param port Port number for LDAP server (use LDAPv2.DEFAULT_PORT for + * default port) + * @param DN Distinguished name of object + * @param attributes List of attributes to return. Use null for "all + * attributes" + * @param scope Depth of search (in DN namespace). Use one of SCOPE_BASE, + * SCOPE_ONE, SCOPE_SUB from LDAPv2 + * @param filter LDAP fitler string (as defined in RFC 1558) use null for + * no filter (this effectively makes the URL reference a single object) + */ + public LDAPUrl (String host, int port, String DN, + Enumeration attributes, int scope, String filter) { + + initialize(host, port, DN, attributes, scope, filter); + } + + /** + * Initializes URL object. + */ + private void initialize (String host, int port, String DN, + Enumeration attributes, int scope, String filter) { + + this.hostName = host; + this.DN = DN; + portNumber = port; + this.filter = (filter != null) ? filter : defaultFilter; + this.scope = scope; + + if (attributes != null) { + this.attributes = new Vector (); + while (attributes.hasMoreElements()) { + this.attributes.addElement (attributes.nextElement()); + } + } else + this.attributes = null; + + StringBuffer url = new StringBuffer ("LDAP://"); + + if (host != null) { + url.append (host); + if (port != LDAPv2.DEFAULT_PORT) { + url.append (':'); + url.append (String.valueOf (port)); + } + } + + url.append ('/'); + url.append (encode (DN)); + + if (attributes != null) { + url.append ('?'); + Enumeration attrList = this.attributes.elements(); + boolean firstElement = true; + + while (attrList.hasMoreElements()) { + if (!firstElement) + url.append (','); + else + firstElement = false; + + url.append ((String)attrList.nextElement()); + } + } + + if (filter != null) { + if (attributes == null) + url.append ('?'); + + url.append ('?'); + + switch (scope) { + default: + case LDAPv2.SCOPE_BASE: + url.append ("base"); break; + case LDAPv2.SCOPE_ONE: + url.append ("one"); break; + case LDAPv2.SCOPE_SUB: + url.append ("sub"); break; + } + + url.append ('?'); + url.append (filter); + } + + URL = url.toString(); + } + + /** + * Return the host name of the LDAP server + * @return LDAP host + */ + public String getHost () { + return hostName; + } + + /** + * Return the port number for the LDAP server + * @return port number + */ + public int getPort () { + return portNumber; + } + + /** + * Return the distinguished name encapsulated in the URL + * @return target distinguished name + */ + public String getDN () { + return DN; + } + + /** + * Return the collection of attributes specified in the URL, or null + * for "every attribute" + * @return enumeration of attributes + */ + public Enumeration getAttributes () { + if (attributes == null) + return null; + else + return attributes.elements(); + } + + /** + * Return the collection of attributes specified in the URL, or null + * for "every attribute" + * @return string array of attribute + */ + public String[] getAttributeArray () { + if (attributes == null) + return null; + else { + String[] attrNames = new String[attributes.size()]; + Enumeration attrs = getAttributes(); + int i = 0; + + while (attrs.hasMoreElements()) + attrNames[i++] = (String)attrs.nextElement(); + + return attrNames; + } + } + + /** + * Returns the scope of the search, according to the values + * SCOPE_BASE, SCOPE_ONE, SCOPE_SUB defined in LDAPv2. This refers + * to how deep in the directory namespace the search will look + * @return search scope + */ + public int getScope () { + return scope; + } + + /** + * Returns the scope of the search. If the scope returned is -1, then + * the given string is not for the scope. + * @param str The string which compares with the scope type. + * @returns The scope of the search, -1 returns if the given string is + * not one of the values: sub, one or base. + */ + private int getScope(String str) { + + int s = -1; + if (str.equalsIgnoreCase("base")) + s = LDAPv2.SCOPE_BASE; + else if (str.equalsIgnoreCase("one")) + s = LDAPv2.SCOPE_ONE; + else if (str.equalsIgnoreCase("sub")) + s = LDAPv2.SCOPE_SUB; + + return s; + } + + /** + * Returns the search filter (RFC 1558), or the default if none was + * specified. + * @return filter + */ + public String getFilter () { + return filter; + } + + /** + * Returns a valid string representation of this LDAP URL. + * @return LDAP search expression in URL form + */ + public String getUrl () { + return URL; + } + + /** + * Checks if the given string is a filter expression. + * @param The string which is checked if it is filter expression. + * @return true if the given string is a filter expression; otherwise, + * return false; + */ + private boolean isFilter(String str) { + if (str.startsWith("(")) + return true; + else + return false; + } + + + /** + * Checks if the given string is an attribute expression. + * @param The string which is checked if it is attribute expression. + * @return true if the given string is an attribute expression; otherwise, + * return false; + */ + private boolean isAttribute(String str) { + if ((!str.startsWith("(")) && (!str.equalsIgnoreCase("base")) && + (!str.equalsIgnoreCase("one")) && (!str.equalsIgnoreCase("sub"))) + return true; + else + return false; + } + + /** + * Reads next construct from the given string parser. + * @param parser The string parser + * @return The next construct which can be attribute, scope or filter. + * @exception java.net.MalformedURLException Get thrown when the url format + * is incorrect. + */ + private String readNextConstruct(StringTokenizer parser) throws + MalformedURLException { + + try { + if (parser.hasMoreTokens()) { + parser.nextToken(); // "?" + return parser.nextToken(); + } + } catch (NoSuchElementException e) { + throw new MalformedURLException(); + } + + return null; + } + + /** + * Parses hex character into integer. + */ + private static int hexValue (char hexChar) throws MalformedURLException { + if (hexChar >= '0' && hexChar <= '9') + return hexChar - '0'; + if (hexChar >= 'A' && hexChar <= 'F') + return hexChar - 'A' + 10; + if (hexChar >= 'a' && hexChar <= 'f') + return hexChar - 'a' + 10; + + throw new MalformedURLException (); + } + + private static char hexChar (int hexValue) { + if (hexValue < 0 || hexValue > 0xF) + return 'x'; + + if (hexValue < 10) + return (char)(hexValue + '0'); + + return (char)((hexValue - 10) + 'a'); + } + + /** + * Decodes a URL-encoded string. Any occurences of %HH are decoded to the + * hex value represented. However, this routine does NOT decode "+" + * into " ". See RFC 1738 for full details about URL encoding/decoding. + * @param URLEncoded A segment of a URL which was encoded via the URL + * encoding rules + * @exception MalformedURLException failed to parse URL + */ + public static String decode (String URLEncoded) throws + MalformedURLException { + StringBuffer decoded = new StringBuffer (URLEncoded); + int srcPos = 0, dstPos = 0; + + try { + while (srcPos < decoded.length()) { + if (decoded.charAt (srcPos) != '%') { + if (srcPos != dstPos) + decoded.setCharAt (dstPos, decoded.charAt (srcPos)); + srcPos++; + dstPos++; + continue; + } + decoded.setCharAt (dstPos, (char) + ((hexValue(decoded.charAt (srcPos+1))<<4) | + (hexValue(decoded.charAt (srcPos+2))))); + dstPos++; + srcPos += 3; + } + } catch (StringIndexOutOfBoundsException sioob) { + // Indicates that a "%" character occured without the following HH + throw new MalformedURLException (); + } + + /* 070497 Url problems submitted by Netscape */ + /* decoded.setLength (dstPos+1); */ + decoded.setLength (dstPos); + return decoded.toString (); + } + + /** + * Encodes an arbitrary string. Any illegal characters are encoded as + * %HH. However, this routine does NOT decode "+" into " " (this is a HTTP + * thing, not a general URL thing). Note that, because Sun's URLEncoder + * does do this encoding, we can't use it. + * See RFC 1738 for full details about URL encoding/decoding. + * @param toEncode An arbitrary string to encode for embedding in a URL + */ + public static String encode (String toEncode) { + StringBuffer encoded = new StringBuffer (toEncode.length()+10); + + for (int currPos = 0; currPos < toEncode.length(); currPos++) { + char currChar = toEncode.charAt (currPos); + if ((currChar >= 'a' && currChar <= 'z') || + (currChar >= 'A' && currChar <= 'Z') || + (currChar >= '0' && currChar <= '9') || + ("$-_.+!*'(),".indexOf (currChar) > 0)) { + // this is the criteria for "doesn't need to be encoded" (whew!) + encoded.append (currChar); + } else { + encoded.append ("%"); + encoded.append (hexChar ((currChar & 0xF0) >> 4)); + encoded.append (hexChar (currChar & 0x0F)); + } + } + + return encoded.toString(); + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPv2.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPv2.java new file mode 100644 index 00000000000..7029d516ad7 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPv2.java @@ -0,0 +1,443 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import java.util.*; +import java.io.*; + +/** + * This interface summarizes the basic functionality available in the + * Lightweight Directory Access Protocol (LDAP) version 2. (See + * RFC 1777 + * for the definition of the protocol.) + *

+ * + * In the general model for this protocol, objects exist under a directory + * in a particular server. Objects are identified by unique, hierarchical names + * called Distinguished Names, commonly abreviated "DN". An example of a DN: + *

+ *  cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=us
+ * 
+ * Objects have attributes, of the form + *
+ *  attributeName = attributeValue(s)
+ * 
+ * Attribute names must be Strings, and attribute values can be any 8-bit + * sequence (Strings or binary values). + * + * @version 1.0 + */ +public interface LDAPv2 { + /** + * The default port number for LDAP servers. You can specify + * this identifier when calling the LDAPConnection.connect + * method to connect to an LDAP server. + * @see netscape.ldap.LDAPConnection#connect + */ + public final static int DEFAULT_PORT = 389; + + /** + * Option specifying how aliases are dereferenced. + *

+ * + * This option can have one of the following values: + *

+ *

+ * + * @see netscape.ldap.LDAPConnection#getOption + * @see netscape.ldap.LDAPConnection#setOption + */ + public static final int DEREF = 2; + + /** + * Option specifying the maximum number of search results that + * can be returned. + *

+ * + * @see netscape.ldap.LDAPConnection#getOption + * @see netscape.ldap.LDAPConnection#setOption + */ + public static final int SIZELIMIT = 3; + + /** + * Option specifying the maximum number of milliseconds to + * wait for an operation to be completed. + * @see netscape.ldap.LDAPConnection#getOption + * @see netscape.ldap.LDAPConnection#setOption + */ + public static final int TIMELIMIT = 4; + + /** + * Option specifying whether or not referrals to other LDAP + * servers are followed automatically. + * @see netscape.ldap.LDAPConnection#getOption + * @see netscape.ldap.LDAPConnection#setOption + * @see netscape.ldap.LDAPRebind + * @see netscape.ldap.LDAPRebindAuth + */ + public static final int REFERRALS = 8; + + /** + * Option specifying the object containing the method for + * getting authentication information (the distinguished name + * and password) used during a referral. For example, when + * referred to another LDAP server, your client uses this object + * to obtain the DN and password. Your client authenticates to + * the LDAP server using this DN and password. + * @see netscape.ldap.LDAPConnection#getOption + * @see netscape.ldap.LDAPConnection#setOption + * @see netscape.ldap.LDAPRebind + * @see netscape.ldap.LDAPRebindAuth + */ + public static final int REFERRALS_REBIND_PROC = 9; + + /** + * Option specifying the maximum number of referrals to follow + * in a sequence when requesting an LDAP operation. + * @see netscape.ldap.LDAPConnection#getOption + * @see netscape.ldap.LDAPConnection#setOption + */ + public static final int REFERRALS_HOP_LIMIT = 10; + + /** + * Option specifying the version of the LDAP protocol + * used by your client when interacting with the LDAP server. + * If no version is set, the default version is 2. If you + * are planning to use LDAP v3 features (such as controls + * or extended operations), you should set this version to 3 + * or specify version 3 as an argument to the authenticate + * method of the LDAPConnection object. + * @see netscape.ldap.LDAPConnection#getOption + * @see netscape.ldap.LDAPConnection#setOption + * @see netscape.ldap.LDAPConnection#authenticate(int, java.lang.String, java.lang.String) + */ + public static final int PROTOCOL_VERSION = 17; + + /** + * Option specifying the number of results to return at a time. + * @see netscape.ldap.LDAPConnection#getOption + * @see netscape.ldap.LDAPConnection#setOption + */ + public static final int BATCHSIZE = 20; + + + /* + * Valid options for Scope + */ + + /** + * Specifies that the scope of a search includes + * only the base DN (distinguished name). + * @see netscape.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, netscape.ldap.LDAPSearchConstraints) + */ + public static final int SCOPE_BASE = 0; + + /** + * Specifies that the scope of a search includes + * only the entries one level below the base DN (distinguished name). + * @see netscape.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, netscape.ldap.LDAPSearchConstraints) */ + public static final int SCOPE_ONE = 1; + + /** + * Specifies that the scope of a search includes + * the base DN (distinguished name) and all entries at all levels + * beneath that base. + * @see netscape.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, netscape.ldap.LDAPSearchConstraints) */ + public static final int SCOPE_SUB = 2; + + + /* + * Valid options for Dereference + */ + + /** + * Specifies that aliases are never dereferenced. + * @see netscape.ldap.LDAPConnection#getOption + * @see netscape.ldap.LDAPConnection#setOption + */ + public static final int DEREF_NEVER = 0; + + /** + * Specifies that aliases are dereferenced when searching the + * entries beneath the starting point of the search (but + * not when finding the starting entry). + * @see netscape.ldap.LDAPConnection#getOption + * @see netscape.ldap.LDAPConnection#setOption + */ + public static final int DEREF_SEARCHING = 1; + + /** + * Specifies that aliases are dereferenced when finding the + * starting point for the search (but not when searching + * under that starting entry). + * @see netscape.ldap.LDAPConnection#getOption + * @see netscape.ldap.LDAPConnection#setOption + */ + public static final int DEREF_FINDING = 2; + + /** + * Specifies that aliases are always dereferenced. + * @see netscape.ldap.LDAPConnection#getOption + * @see netscape.ldap.LDAPConnection#setOption + */ + public static final int DEREF_ALWAYS = 3; + + /** + * Connects to the LDAP server. + * @param host Hostname of the LDAP server. + * @param port Port number of the LDAP server. To specify the + * default, well-known port, use DEFAULT_PORT. + * @exception LDAPException Failed to connect to the server. + */ + public void connect (String host, int port) throws LDAPException; + + /** + * Connects and authenticates to the LDAP server. + * @param host Hostname of the LDAP server. + * @param port Port number of the LDAP server. To specify the + * default, well-known port, use DEFAULT_PORT. + * @param dn Distinguished name to use for authentication. + * @param passwd Password for authentication. + * @exception LDAPException Failed to connect and authenticate to the server. + */ + public void connect (String host, int port, String dn, String passwd) + throws LDAPException; + + /** + * Disconnects from the LDAP server. Subsequent operational calls + * will first try to re-establish the connection to the same LDAP server. + * @exception LDAPException Failed to disconnect from the server. + */ + public void disconnect() throws LDAPException; + + /** + * Authenticates user with the LDAP server. + * @param Dn Distinguished name to use for authentication. + * @param passwd Password for authentication. + * @exception LDAPException Failed to authenticate to the server. + */ + public void authenticate (String DN, String passwd) throws LDAPException; + + /** + * Read the entry corresponding to the specified distinguished name (DN). + * @param DN Distinguished name of the entry to retrieve. + * @exception LDAPException Failed to retrieve the specified entry. + */ + public LDAPEntry read (String DN) throws LDAPException; + + /** + * Read the entry corresponding to the specified distinguished name (DN), + * and retrieve only the specified attributes. + * @param DN Distinguished name of the entry to retrieve. + * @param attrs Names of attributes to retrieve. + * @exception LDAPException Failed to retrieve the specified entry. + */ + public LDAPEntry read (String DN, String attrs[]) throws LDAPException; + + /** + * Read the entry corresponding to the specified distinguished name (DN), + * and retrieve only the specified attributes. + * @param DN Distinguished name of the entry to retrieve. + * @param attrs Names of attributes to retrieve. + * @param cons The constraints set for the read operation. + * @exception LDAPException Failed to retrieve the specified entry. + */ + public LDAPEntry read (String DN, String attrs[], LDAPSearchConstraints cons) + throws LDAPException; + + /** + * Searches for entries in the directory. + * @param base Starting point for the search in the directory + * (distinguished name). + * @param scope Indicates whether the scope of the search includes + * only the base DN (equivalent to a read operation), only the entries + * one level below the base DN, or all entries at all levels beneath + * the base DN (including the base DN itself). + * @param filter String which describes the search criteria. The format + * of the string is described fully in + * RFC 1558. + * @param attrs Names of the attributes to return for each matching + * directory entry. If null, all attributes are returned. + * @param attrsOnly If true, the search will return only the names of + * the attributes (and not their values). + * @exception LDAPException Failed to complete the requested search. + */ + public LDAPSearchResults search (String base, int scope, String filter, + String[] attrs, boolean attrsOnly) throws LDAPException; + + /** + * Searches for entries in the directory. + * @param base Starting point for the search in the directory + * (distinguished name). + * @param scope Indicates whether the scope of the search includes + * only the base DN (equivalent to a read operation), only the entries + * one level below the base DN, or all entries at all levels beneath + * the base DN (including the base DN itself). + * @param filter String which describes the search criteria. The format + * of the string is described fully in + * RFC 1558. + * @param attrs Names of the attributes to return for each matching + * directory entry. If null, all attributes are returned. + * @param attrsOnly If true, the search will return only the names of + * the attributes (and not their values). + * @param cons Constraints specific to the search (for example, the maximum number + * of entries to return or the maximum time to wait for the search operation to complete). + * @exception LDAPException Failed to complete the requested search. + */ + public LDAPSearchResults search (String base, int scope, String filter, + String[] attrs, boolean attrsOnly, LDAPSearchConstraints cons) + throws LDAPException; + + /** + * Compares the given entry's attribute value to the specified + * attribute value. + * @param DN Distinguished name of the entry that you want compared + * against the specified attribute value. + * @param attr Attribute name and value to use in the comparison. + * @exception LDAPException Failed to perform the comparison. + */ + public boolean compare (String DN, LDAPAttribute attr) throws LDAPException; + + /** + * Compares the given entry's attribute value to the specified + * attribute value. + * @param DN Distinguished name of the entry that you want compared + * against the specified attribute value. + * @param attr Attribute name and value to use in the comparison. + * @param cons The constraints set for the compare operation. + * @exception LDAPException Failed to perform the comparison. + */ + public boolean compare (String DN, LDAPAttribute attr, + LDAPSearchConstraints cons) throws LDAPException; + + /** + * Adds an entry to the directory. + * @param entry New entry to add to the directory. + * @exception LDAPException Failed to add the entry to the directory. + */ + public void add (LDAPEntry entry) throws LDAPException; + + /** + * Adds an entry to the directory. + * @param entry New entry to add to the directory. + * @param cons The constraints set for the add operation. + * @exception LDAPException Failed to add the entry to the directory. + */ + public void add (LDAPEntry entry, LDAPSearchConstraints cons) + throws LDAPException; + + /** + * Modifies an attribute of a directory entry. + * @param DN Distinguished name identifying the entry to be modified. + * @param mod The modification to be made. + * @exception LDAPException Failed to modify the specified entry. + */ + public void modify (String DN, LDAPModification mod) throws LDAPException; + + /** + * Modifies an attribute of a directory entry. + * @param DN Distinguished name identifying the entry to be modified. + * @param mod The modification to be made. + * @param cons The constraints set for the modify operation. + * @exception LDAPException Failed to modify the specified entry. + */ + public void modify (String DN, LDAPModification mod, + LDAPSearchConstraints cons) throws LDAPException; + + /** + * Modifies the attributes of a directory entry. + * @param DN Distinguished name identifying the entry to be modified. + * @param mod List of the modifications to be made. + * @exception LDAPException Failed to modify the specified entry. + */ + public void modify (String DN, LDAPModificationSet mods ) throws LDAPException; + + /** + * Modifies the attributes of a directory entry. + * @param DN Distinguished name identifying the entry to be modified. + * @param mod List of the modifications to be made. + * @param cons The constraints set for the modify operation. + * @exception LDAPException Failed to modify the specified entry. + */ + public void modify (String DN, LDAPModificationSet mods, + LDAPSearchConstraints cons ) throws LDAPException; + + /** + * Removes an entry from the directory. + * @param DN Distinguished name identifying the entry to remove. + * @exception LDAPException Failed to remove the entry from the directory. + */ + public void delete( String DN ) throws LDAPException; + + /** + * Removes an entry from the directory. + * @param DN Distinguished name identifying the entry to remove. + * @param cons The constraints set for the delete operation. + * @exception LDAPException Failed to remove the entry from the directory. + */ + public void delete( String DN, LDAPSearchConstraints cons ) + throws LDAPException; + + /** + * Changes the name of an entry in the directory. + * @param DN Original distinguished name (DN) of entry. + * @param newRDN New relative distinguished name (RDN) of the entry. + * @param deleteOldRDN Specifies whether or not the original RDN remains + * as an attribute of the entry. If true, the original RDN + * is no longer an attribute of the entry. + * @exception LDAPException Failed to rename the entry in the directory. + */ + public void rename ( String DN, String newRDN, boolean deleteOldRDN ) + throws LDAPException; + + /** + * Changes the name of an entry in the directory. + * @param DN Original distinguished name (DN) of entry. + * @param newRDN New relative distinguished name (RDN) of the entry. + * @param deleteOldRDN Specifies whether or not the original RDN remains + * as an attribute of the entry. If true, the original RDN + * is no longer an attribute of the entry. + * @param cons The constraints set for the rename operation. + * @exception LDAPException Failed to rename the entry in the directory. + */ + public void rename ( String DN, String newRDN, boolean deleteOldRDN, + LDAPSearchConstraints cons ) throws LDAPException; + + /** + * Retrieves an option that applies to the connection. + * The particular meaning may be implementation-dependent. + * The standard options are the search options described by + * the LDAPSearchConstraints class. + * @exception LDAPException Failed to retrieve the value of the specified option. + */ + public Object getOption( int option ) throws LDAPException; + + /** + * Sets an option that applies to the connection. + * The particular meaning may be implementation-dependent. + * The standard options are the search options described by + * the LDAPSearchConstraints class. + * @exception LDAPException Failed to set the specified option. + */ + public void setOption( int option, Object value ) throws LDAPException; +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPv3.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPv3.java new file mode 100644 index 00000000000..add0bf87a62 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/LDAPv3.java @@ -0,0 +1,167 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap; + +import java.util.*; +import netscape.ldap.client.*; +import netscape.ldap.client.opers.*; +import java.io.*; + +/** + * Specifies additional features available in version 3 of the + * LDAP protocol. (To view preliminary information on this work + * in progress, see the LDAP v3 internet draft. You can find the + * latest version of this document listed under the Internet-Drafts + * section of the + * ASID home page.) + * + * @version 1.0 + */ +public interface LDAPv3 extends LDAPv2 { + + /** + * Connects and authenticates to the LDAP server with the specified LDAP + * protocol version. + * @param version LDAP protocol version requested: currently 2 or 3 + * @param host Hostname of the LDAP server. + * @param port Port number of the LDAP server. To specify the + * default, well-known port, use DEFAULT_PORT. + * @param dn Distinguished name to use for authentication. + * @param passwd Password for authentication. + * @exception LDAPException Failed to connect and authenticate to the server. + */ + public void connect(int version, String host, int port, String dn, + String passwd) throws LDAPException; + + /** + * Authenticates to the LDAP server (that the object is currently + * connected to) using the specified name and password, with the + * specified LDAP protocol version. If the server does not support + * the requested protocol version, an exception is thrown. If the + * object has been disconnected from an LDAP server, this method + * attempts to reconnect to the server. If the object had already + * authenticated, the old authentication is discarded. + * @param version LDAP protocol version requested: currently 2 or 3. + * @param dn If non-null and non-empty, specifies that the + * connection and all operations through it should be + * authenticated with dn as the distinguished name. + * @param passwd If non-null and non-empty, specifies that the + * connection and all operations through it should be + * authenticated with passwd as password. + * @exception LDAPException Failed to authenticate to the LDAP server. + */ + public void authenticate(int version, + String dn, + String passwd) + throws LDAPException; + + /** + * Performs an extended operation on the directory. Extended operations + * are part of version 3 of the LDAP protocol. + *

+ * + * @param op LDAPExtendedOperation object specifying the OID of the + * extended operation and the data to be used in the operation. + * @exception LDAPException Failed to execute the operation + * @return LDAPExtendedOperation object representing the extended response + * returned by the server. + * @see LDAPExtendedOperation + */ + public LDAPExtendedOperation extendedOperation( LDAPExtendedOperation op ) + throws LDAPException; + + /** + * Renames and moves an entry in the directory. + * @param DN Original distinguished name (DN) for the entry. + * @param newRDN New relative distinguished name (RDN) for the entry. + * @param newParentDN Distinguished name of the new parent entry of the + * specified entry. + * @exception LDAPException Failed to rename the specified entry. + */ + public void rename( String DN, String newRDN, String newParentDN, + boolean deleteOldRDN ) throws LDAPException; + + /** + * Renames and moves an entry in the directory. + * @param DN Original distinguished name (DN) for the entry. + * @param newRDN New relative distinguished name (RDN) for the entry. + * @param newParentDN Distinguished name of the new parent entry of the + * specified entry. + * @param cons The constraints set for the rename operation. + * @exception LDAPException Failed to rename the specified entry. + */ + public void rename( String DN, String newRDN, String newParentDN, + boolean deleteOldRDN, LDAPSearchConstraints cons ) throws LDAPException; + + /** + * Returns an array of the latest controls (if any) from server. + * @return An array of the controls returned by an operation, + * or null if none. + * @see netscape.ldap.LDAPControl + */ + public LDAPControl[] getResponseControls(); + + /** + * Option specifying client controls for LDAP operations. These + * controls are interpreted by the client and are not passed + * to the LDAP server. + * @see netscape.ldap.LDAPControl + * @see netscape.ldap.LDAPConnection#getOption + * @see netscape.ldap.LDAPConnection#setOption + */ + public static final int CLIENTCONTROLS = 11; + + /** + * Option specifying server controls for LDAP operations. These + * controls are passed to the LDAP server. They may also be returned by + * the server. + * @see netscape.ldap.LDAPControl + * @see netscape.ldap.LDAPConnection#getOption + * @see netscape.ldap.LDAPConnection#setOption + */ + public static final int SERVERCONTROLS = 12; + + /** + * Attribute type that you can specify in the LDAPConnection + * search method if you don't want to retrieve any of the + * attribute types for entries found by the search. + * @see netscape.ldap.LDAPConnection#search + */ + public static final String NO_ATTRS = "1.1"; + + /** + * Attribute type that you can specify in the LDAPConnection + * search method if you want to retrieve all attribute types. + * You can use this if you want to retrieve all attributes in + * addition to an operational attribute. For example: + *

+ * + *

+     * ...
+     * String [] MY_ATTRS = { LDAPv3.ALL_USER_ATTRS, "modifiersName",
+     *     "modifyTimestamp" };
+     * LDAPSearchResults res = ld.search( MY_SEARCHBASE,
+     *     LDAPConnection.SCOPE_SUB, MY_FILTER, MY_ATTRS, false, cons );
+     * ...
+     * 
+ * @see netscape.ldap.LDAPConnection#search + */ + public static final String ALL_USER_ATTRS = "*"; + +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERAny.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERAny.java new file mode 100644 index 00000000000..06dde211edb --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERAny.java @@ -0,0 +1,87 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.ber.stream; + +import java.util.*; +import java.io.*; + +/** + * This class is for the any object that is unknown to the + * BER package but conforms to BER rules. + * + *
+ * Encoding Rule:
+ *   The encoding is the encoding of the chosen type.
+ * 
+ * + * @version 1.0 + * @seeAlso CCITT X.209 + */ +public class BERAny extends BERElement { + /** + * Internal variables + */ + private BERElement m_value = null; + + /** + * Constructs an any element. + * @param value BERElement value + */ + public BERAny(BERElement value) { + m_value = value; + } + + /** + * Constructs an any element with the input stream. + * Note that with the current decoding architecture any types + * will not be decoded as any's but rather only as the types + * chosen. The following method will never be called. + * @param stream input stream + * @param bytes_read array of 1 int; value incremented by + * number of bytes read from stream. + * @exception IOException failed to construct + */ + public BERAny(BERTagDecoder decoder, InputStream stream, + int[] bytes_read) throws IOException { + m_value = getElement(decoder, stream, bytes_read); + } + + /** + * Sends the BER encoding directly to stream. + * @param stream output stream + */ + public void write(OutputStream stream) throws IOException { + m_value.write(stream); + } + + /** + * Gets the element type. + * @param element type + */ + public int getType() { + return BERElement.ANY; + } + + /** + * Gets the string representation. + * @return string representation of tag + */ + public String toString() { + return "ANY {" + m_value + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERBitString.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERBitString.java new file mode 100644 index 00000000000..2857436126e --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERBitString.java @@ -0,0 +1,273 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.ber.stream; + +import java.util.*; +import java.util.BitSet; +import java.io.*; + +/** + * This class is for the BitString object. Note that the BitSet class + * has a bug: size() returns the size of the internal allocated memory + * rather than the number of bits. Current work-around is to maintain + * the number of bits ourselves in m_value_num_bits. + * Change is required when BitSet is fixed. + * + * @version 1.0 + * @seeAlso CCITT X.209 + */ +public class BERBitString extends BERElement { + /** + * Internal variables + */ + private BitSet m_value; + private int m_value_num_bits; + + /** + * Constructs a boolean element. + * @param value boolean value + */ + public BERBitString(BitSet value) { + m_value = value; + } + + /** + * Constructs a bitstring element with the input stream. + * (for constructed encodings). + * @param stream input stream + * @param bytes_read array of 1 int; value incremented by + * number of bytes read from stream. + * @exception IOException failed to construct + */ + public BERBitString(BERTagDecoder decoder, InputStream stream, + int[] bytes_read) throws IOException { + int octet; + int contents_length = super.readLengthOctets(stream, bytes_read); + int[] component_length = new int[1]; + BERElement element = null; + + if (contents_length == -1) { + /* Constructed - indefinite length. */ + { + component_length[0] = 0; + element = getElement(decoder,stream,component_length); + if (element != null) { + /* element is a bitstring - add it to the existing BitSet */ + BERBitString bit_string_element = (BERBitString)element; + + BitSet new_bit_set = new BitSet(m_value_num_bits + + bit_string_element.getSize()); + + for (int i = 0; i 0) { + component_length[0] = 0; + element = getElement(decoder,stream,component_length); + if (element != null) { + /* element is a bitstring - add it to the existing BitSet */ + BERBitString bit_string_element = (BERBitString)element; + + BitSet new_bit_set = new BitSet(m_value_num_bits + + bit_string_element.getSize()); + for (int i = 0; i 0) { + m_value.set(bit_num); + } + else + m_value.clear(bit_num); + bit_num++; + mask = mask / 2; + } + } + + octet = stream.read(); /* last content octet */ + int mask = 0x80; + for (int j = 0; j < 8-last_unused_bits; j++) { + if ((octet & mask) > 0) + m_value.set(bit_num); + else + m_value.clear(bit_num); + bit_num++; + mask = mask / 2; + } + + bytes_read[0] += contents_length; + } + + /** + * Sends the BER encoding directly to stream. + * Always sends in primitive form. + * @param stream output stream + */ + public void write(OutputStream stream) throws IOException { + stream.write(BERElement.BITSTRING); + + //int num_bits = m_value.size(); /* number of bits to send */ + int num_bits = m_value_num_bits; + + /* Number of bits unused int the last contents octet */ + int last_unused_bits = 8 - (num_bits % 8); + + /* Figure out the number of content octets */ + int num_content_octets = (int)(num_bits/8) + 1; + if (last_unused_bits > 0) + num_content_octets += 1; + stream.write(num_content_octets); /* length octet */ + + stream.write(last_unused_bits); /* first content octet */ + + for (int i = 0; i < (int)(num_bits/8); i++) { + int new_octet = 0; + int bit = 0x80; + for (int j = 0; j < 8; j++) { + if (m_value.get(i*8+j)) + new_octet += bit; + bit = bit/2; + } + stream.write(new_octet); + } + + /* + * Last octet may not use all bits. If last octet DOES use all + * bits then it has already been written above. + */ + if (last_unused_bits > 0) { + int new_octet = 0; + int bit = 0x80; + for (int j = 0; j < last_unused_bits; j++) { + if (m_value.get(((int)(num_bits/8))*8+j)) + new_octet += bit; + bit = bit/2; + } + stream.write(new_octet); + } + } + + /** + * Gets the bitstring value. + * @param element type + */ + public BitSet getValue() { + return m_value; + } + + /** + * Gets the number of bits. + * @return bit numbers + */ + public int getSize() { + return m_value_num_bits; + } + + /** + * Gets the element type. + * @param element type + */ + public int getType() { + return BERElement.BITSTRING; + } + + /** + * Gets the string representation. + * @return string representation of tag + */ + public String toString() { + String hex_string = ""; + int octet; + + //int num_bits = m_value.size(); + int num_bits = m_value_num_bits; + for (int i = 0; i < (int)(num_bits/8); i++) { + octet = 0; + int bit = 0x80; + for (int j = 0; j < 8; j++) { + if (m_value.get(i*8+j)) + octet += bit; + bit = bit/2; + } + hex_string += " " + (byte)octet; + } + + int bit = 0x80; + octet = 0; + for (int k = 0; k < num_bits-(int)(num_bits/8); k++) { + if (m_value.get(((int)(num_bits/8))*8+k)) + octet += bit; + bit = bit/2; + } + hex_string += " " + (byte)octet; + + return "Bitstring {" + hex_string + " }"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERBoolean.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERBoolean.java new file mode 100644 index 00000000000..be21c2295e6 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERBoolean.java @@ -0,0 +1,110 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.ber.stream; + +import java.util.*; +import java.io.*; + +/** + * This class is for the Boolean object. + * + *
+ * ENCODING RULE:
+ *  tag    = 0x01
+ *  length = 0x01
+ *  one contents octet (non-zero indicates TRUE).
+ *
+ * Example 1:  (false)
+ *   01 01 00
+ * Example 2:  (true)
+ *   01 01 FF
+ * 
+ * + * @version 1.0 + * @seeAlso CCITT X.209 + */ +public class BERBoolean extends BERElement { + /** + * Internal variables + */ + private boolean m_value = true; + + /** + * Constructs a boolean element. + * @param value boolean value + */ + public BERBoolean(boolean value) { + m_value = value; + } + + /** + * Constructs a boolean element with the input stream. + * @param stream input stream + * @param bytes_read array of 1 int; value incremented by + * number of bytes read from stream. + * @exception IOException failed to construct + */ + public BERBoolean(InputStream stream, int[] bytes_read) throws IOException { + int octet = stream.read(); /* skip length */ + bytes_read[0]++; + octet = stream.read(); /* content octet */ + bytes_read[0]++; + + if (octet > 0) + m_value = true; + else + m_value = false; + } + + /** + * Sends the BER encoding directly to stream. + * @param stream output stream + */ + public void write(OutputStream stream) throws IOException { + stream.write(BERElement.BOOLEAN); + stream.write(0x01); + if (m_value) + stream.write(0xFF); /* non-zero means true. */ + else + stream.write(0x00); /* zero means false. */ + } + + /** + * Gets the boolean value. + * @param element type + */ + public boolean getValue() { + return m_value; + } + + /** + * Gets the element type. + * @param element type + */ + public int getType() { + return BERElement.BOOLEAN; + } + + /** + * Gets the string representation. + * @return string representation of tag + */ + public String toString() { + return "Boolean {" + m_value + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERCharacterString.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERCharacterString.java new file mode 100644 index 00000000000..0aee70eeeb9 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERCharacterString.java @@ -0,0 +1,179 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.ber.stream; + +import java.util.*; +import java.io.*; + +/** + * This is an abstract base class for character string types. + * + * @version 1.0 + * @seeAlso CCITT X.209 + */ +public abstract class BERCharacterString extends BERElement { + /** + * Internal variables + */ + protected String m_value = null; + + /** + * Constructs an characterstring element containing buffer. + */ + public BERCharacterString() { + } + + /** + * Constructs an octetstring element containing buffer. + * @param buffer string containing 'octets' + */ + public BERCharacterString(String string) { + m_value = string; + } + + /** + * Constructs a characterstring element from buffer. + * @param buffer buffer containing 'octets' + * @param start start of buffer range to copy + * @param end end of buffer range to copy + */ + public BERCharacterString(byte[] buffer) { + try{ + m_value = new String(buffer,"UTF8"); + } catch(Throwable x) + {} + } + + /** + * Constructs a characterstring element with the input stream. + * (for constructed encoding) + * @param stream input stream + * @param bytes_read array of 1 int, incremented by number of bytes read. + * @exception IOException failed to construct + */ + public BERCharacterString(BERTagDecoder decoder, InputStream stream, + int[] bytes_read) throws IOException { + int octet; + int contents_length = super.readLengthOctets(stream, bytes_read); + int[] component_length = new int[1]; + BERElement element = null; + + if (contents_length == -1) { + /* Constructed - indefinite length content octets. */ + do { + component_length[0] = 0; + element = getElement(decoder,stream,component_length); + if (element != null) { + /* element is a string of same type + * - add it to the existing buffer */ + BERCharacterString octet_element = (BERCharacterString)element; + String string_buffer = octet_element.getValue(); + if (m_value == null) { + m_value = string_buffer; + } else { + m_value = m_value + string_buffer; + } + } + } while (element != null); + } else { + /* Definite length content octets string. */ + bytes_read[0] += contents_length; + while (contents_length > 0) { + component_length[0] = 0; + element = getElement(decoder,stream,component_length); + if (element != null) { + /* element is a string of the same type + * - add it to the existing buffer */ + BERCharacterString octet_element = (BERCharacterString)element; + String string_buffer = octet_element.getValue(); + if (m_value == null) { + m_value = string_buffer; + } else { + m_value = m_value + string_buffer; + } + } + contents_length -= component_length[0]; + } + } + } + + /** + * Constructs a characterstring element with the input stream. + * (for primitive encoding) + * @param stream input stream + * @param bytes_read array of 1 int, incremented by number of bytes read. + * @exception IOException failed to construct + */ + public BERCharacterString(InputStream stream, int[] bytes_read) + throws IOException { + int contents_length = super.readLengthOctets(stream, bytes_read); + + /* Definite length content octets string. */ + if (contents_length > 0) { + byte[] buffer = new byte[contents_length]; + for (int i = 0; i < contents_length; i++) { + buffer[i] = (byte) stream.read(); + } + bytes_read[0] += contents_length; + try { + m_value = new String(buffer,"UTF8"); + } catch(Throwable x) + {} + } + } + + /** + * Writes BER to stream. + * @param stream output stream + */ + private byte[] byte_buf; + + public void write(OutputStream stream) throws IOException { + stream.write(getType()); /* tag */ + if (m_value == null) { + sendDefiniteLength(stream, 0); + } else { + try { + byte_buf = m_value.getBytes("UTF8"); + sendDefiniteLength(stream, byte_buf.length); /* length */ + } catch(Throwable x) + {} + stream.write(byte_buf,0,byte_buf.length); /* contents */ + } + } + + /** + * Gets the element value. + * @param element value + */ + public String getValue() { + return m_value; + } + + /** + * Gets the element type. + * @param element type + */ + public abstract int getType(); + + /** + * Gets the string representation. + * @return string representation + */ + public abstract String toString(); +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERChoice.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERChoice.java new file mode 100644 index 00000000000..5de24f47df8 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERChoice.java @@ -0,0 +1,96 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.ber.stream; + +import java.util.*; +import java.io.*; + +/** + * This class is for the Choice object. Note that this class will be + * used by the client. + * + *
+ * ENCODING RULE:
+ *   Encoding is the encoding of the chosen type.
+ * 
+ * + * @version 1.0 + * @seeAlso CCITT X.209 + */ +public class BERChoice extends BERElement { + /** + * Internal variables + */ + private BERElement m_value = null; + + /** + * Constructs a choice element. + * @param value BERElement value + */ + public BERChoice(BERElement value) { + m_value = value; + } + + /** + * Constructs a choice element with the input stream. + * Note that with the current decoding architecture choice types + * will not be decoded as choices but rather only as the types + * chosen. The following method will never be called. + * @param stream input stream + * @param bytes_read array of 1 int; value incremented by + * number of bytes read from stream. + * @exception IOException failed to construct + */ + public BERChoice(BERTagDecoder decoder, InputStream stream, + int[] bytes_read) throws IOException { + m_value = getElement(decoder, stream, bytes_read); + } + + /** + * Sends the BER encoding of the chosen type directly to stream. + * @param stream output stream + * @exception IOException failed to construct + */ + public void write(OutputStream stream) throws IOException { + m_value.write(stream); + } + + /** + * Gets the value of the chosen type. + * @param element type + */ + public BERElement getValue() { + return m_value; + } + + /** + * Gets the element type. + * @param element type + */ + public int getType() { + return BERElement.CHOICE; + } + + /** + * Gets the string representation. + * @return string representation of tag + */ + public String toString() { + return "CHOICE {" + m_value + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERConstruct.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERConstruct.java new file mode 100644 index 00000000000..8676ca0b33d --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERConstruct.java @@ -0,0 +1,130 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.ber.stream; + +import java.util.*; +import java.io.*; + +/** + * This abstract class serves as a based class for constructs + * types such as sequence or set. + * + * @version 1.0 + * @seeAlso CCITT X.209 + */ +public abstract class BERConstruct extends BERElement { + /** + * List of BER elements in the construct. + */ + private Vector m_elements = new Vector(); + + /** + * Constructs a construct element. + */ + public BERConstruct() { + } + + /** + * Constructs a construct element with the input stream. + * @param decoder decoder for application specific ber + * @param stream input stream from socket + * @param bytes_read array of 1 int; value incremented by number + * of bytes read from stream. + * @exception IOException failed to construct + */ + public BERConstruct(BERTagDecoder decoder, InputStream stream, + int[] bytes_read) throws IOException { + int contents_length = super.readLengthOctets(stream,bytes_read); + int[] component_length = new int[1]; + if (contents_length == -1) { + /* Constructed - indefinite length */ + BERElement element = null; + { + component_length[0] = 0; + element = getElement(decoder, stream, component_length); + if (element != null) + addElement(element); + } while (element != null); + } else { + /* Constructed - definite length */ + bytes_read[0] += contents_length; + while (contents_length > 0) + { + component_length[0] = 0; + addElement(getElement(decoder, stream,component_length)); + contents_length -= component_length[0]; + } + } + } + + + /** + * Adds an element to the list. + * @return BER encoding of the element + */ + public void addElement(BERElement element) { + m_elements.addElement(element); + } + + /** + * Retrieves number of elements. + * @return number of element + */ + public int size() { + return m_elements.size(); + } + + /** + * Gets ber element at specific position. + * @param index index of element to get + * @return ber element + */ + public BERElement elementAt(int index) { + return (BERElement)m_elements.elementAt(index); + } + + /** + * Sends the BER encoding directly to stream. + * @param stream output stream + * @exception IOException failed to send + */ + public void write(OutputStream stream) throws IOException { + stream.write(getType()); + + ByteArrayOutputStream contents_stream = new ByteArrayOutputStream(); + for (int i = 0; i < m_elements.size(); i++) { + BERElement e = elementAt(i); + e.write(contents_stream); + } + byte[] contents_buffer = contents_stream.toByteArray(); + sendDefiniteLength(stream, contents_buffer.length); + stream.write(contents_buffer); + } + + /** + * Gets the element type. + * @param element type + */ + public abstract int getType(); + + /** + * Gets the string representation. + * @return string representation of tag + */ + public abstract String toString(); +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERElement.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERElement.java new file mode 100644 index 00000000000..afc0dd0dd73 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERElement.java @@ -0,0 +1,315 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.ber.stream; + +import java.util.*; +import java.io.*; + +/** + * This class is for the tagged object. Nested tag is + * allowed. A tagged element contains another BER element. + * + * @version 1.0 + * @seeAlso CCITT X.209 + */ +public abstract class BERElement { + /** + * Possible element types. + */ + public final static int BOOLEAN = 0x01; + public final static int INTEGER = 0x02; + public final static int BITSTRING = 0x03; + public final static int OCTETSTRING = 0x04; + public final static int NULL = 0x05; + public final static int OBJECTID = 0x06; + public final static int REAL = 0x09; + public final static int ENUMERATED = 0x0a; + public final static int SET = 0x31; /* always constructed */ + public final static int SEQUENCE = 0x30; /* always constructed */ + public final static int NUMERICSTRING = 0x12; + public final static int PRINTABLESTRING = 0x13; + public final static int TELETEXSTRING = 0x14; + public final static int VIDEOTEXSTRING = 0x15; + public final static int IA5STRING = 0x16; + public final static int UTCTIME = 0x17; + public final static int GRAPHICSTRING = 0x19; + public final static int VISIBLESTRING = 0x1A; + public final static int GENERALSTRING = 0x1B; + + /** + * Internal (non-transmitted) tags. + */ + public final static int TAG = -1; + public final static int CHOICE = -2; + public final static int ANY = -3; + + /** + * Possible tags. + */ + public final static int EOC = 0x00; /* End Of Construction */ + public final static int UNIVERSAL = 0x00; + public final static int APPLICATION = 0x40; + public final static int CONTEXT = 0x80; + public final static int SASLCONTEXT = 0xa0; + public final static int PRIVATE = 0xC0; + public final static int PRIMITIVE = 0x00; + public final static int CONSTRUCTED = 0x20; + + public final static int MRA_OID = 0x01; + public final static int MRA_TYPE = 0x02; + public final static int MRA_VALUE = 0x03; + public final static int MRA_DNATTRS = 0x04; + public final static int EXOP_REQ_OID = 0x00; + public final static int EXOP_REQ_VALUE = 0x01; + public final static int EXOP_RES_OID = 0x0a; + public final static int EXOP_RES_VALUE = 0x0b; + public final static int SK_MATCHRULE = 0x00; + public final static int SK_REVERSE = 0x01; + public final static int SR_ATTRTYPE = 0x00; + + /** + * Gets a ber element from the input stream. + * @param decoder decoder for application specific ber + * @param stream stream where ber encoding comes + * @param bytes_read array of 1 int; value incremented by + * number of bytes fread from stream. + * @exception IOException failed to decode an element. + */ + public static BERElement getElement(BERTagDecoder decoder, + InputStream stream, int[] bytes_read) throws IOException { + + BERElement element = null; + int tag = stream.read(); + bytes_read[0] = 1; + + if (tag == EOC) { + stream.read(); /* length octet (always zero) */ + bytes_read[0] = 1; + element = null; + } else if (tag == BOOLEAN) { + element = new BERBoolean(stream, bytes_read); + } else if (tag == INTEGER) { + element = new BERInteger(stream, bytes_read); + } else if (tag == BITSTRING) { + element = new BERBitString(stream, bytes_read); + } else if (tag == (BITSTRING | CONSTRUCTED)) { + element = new BERBitString(decoder, stream, bytes_read); + } else if (tag == OCTETSTRING) { + element = new BEROctetString(stream, bytes_read); + } else if (tag == (OCTETSTRING | CONSTRUCTED)) { + element = new BEROctetString(decoder, stream, bytes_read); + } else if (tag == NULL) { + element = new BERNull(stream, bytes_read); + } else if (tag == OBJECTID) { + element = new BERObjectId(stream, bytes_read); + } else if (tag == REAL) { + element = new BERReal(stream, bytes_read); + } else if (tag == ENUMERATED) { + element = new BEREnumerated(stream, bytes_read); + } else if (tag == SEQUENCE) { + element = new BERSequence(decoder, stream, bytes_read); + } else if (tag == SET) { + element = new BERSet(decoder, stream, bytes_read); + } else if (tag == NUMERICSTRING) { + element = new BERNumericString(stream, bytes_read); + } else if (tag == (NUMERICSTRING | CONSTRUCTED)) { + element = new BERNumericString(decoder, stream, bytes_read); + } else if (tag == PRINTABLESTRING) { + element = new BERPrintableString(stream, bytes_read); + } else if (tag == (PRINTABLESTRING | CONSTRUCTED)) { + element = new BERPrintableString(decoder, stream, bytes_read); + } else if (tag == UTCTIME) { + element = new BERUTCTime(stream, bytes_read); + } else if (tag == (UTCTIME | CONSTRUCTED)) { + element = new BERUTCTime(decoder, stream, bytes_read); + } else if (tag == VISIBLESTRING) { + element = new BERVisibleString(stream, bytes_read); + } else if (tag == (VISIBLESTRING | CONSTRUCTED)) { + element = new BERVisibleString(decoder, stream, bytes_read); + } else if ((tag & (APPLICATION | PRIVATE | CONTEXT)) > 0) { + element = new BERTag(decoder, tag, stream, bytes_read); + } else + throw new IOException("invalid tag " + tag); + + return element; + } + + /** + * Decodes length octets from stream. + * @param stream input stream to read from + * @param bytes_read array of 1 int; value incremented by + * number of bytes read from stream. + * @return length of contents or -1 if indefinite length. + * @exception IOException failed to read octets + */ + public static int readLengthOctets(InputStream stream, int[] bytes_read) + throws IOException { + int contents_length = 0; + int octet = stream.read(); + bytes_read[0]++; + + if (octet == 0x80) + /* Indefinite length */ + contents_length = -1; + else if ((octet & 0x80) > 0) { + /* Definite (long form) - num octets encoded in 7 rightmost bits */ + int num_length_octets = (octet & 0x7F); + + for (int i = 0; i < num_length_octets; i++) { + octet = stream.read(); + bytes_read[0]++; + contents_length = (contents_length<<8) + octet; + } + } else { + /* Definite (short form) - one length octet. Value encoded in */ + /* 7 rightmost bits. */ + contents_length = octet; + } + return contents_length; + } + + /** + * Writes length octets (definite length only) to stream. + * Uses shortform whenever possible. + * @param stream output stream to write to. + * @param num_content_octets value to be encode into length octets. + * @return number of bytes sent to stream. + * @exception IOException failed to read octets + */ + public static void sendDefiniteLength(OutputStream stream, + int num_content_octets) throws IOException { + + int bytes_written = 0; + + if (num_content_octets <= 127) { + /* Use short form */ + stream.write(num_content_octets); + } else { + /* Using long form: + * Need to determine how many octets are required to + * encode the length. + */ + int num_length_octets = 0; + int num = num_content_octets; + while (num >= 0) { + num_length_octets++; + num = (num>>8); + if (num <= 0) + break; + } + + byte[] buffer = new byte[num_length_octets+1]; + buffer[0] = (byte)(0x80 | num_length_octets); + + num = num_content_octets; + for (int i = num_length_octets; i > 0; i--) { + buffer[i] = (byte)(num & 0xFF); + num = (num>>8); + } + + stream.write(buffer); + } + } + + /** + * Reads the unsigned binary from the input stream. + * @param stream inputstream + * @param byte_read number of byte read + * @param length length of the byte to be read + * @return the value of the two complement + * @exception IOException failed to read octets + */ + protected int readUnsignedBinary(InputStream stream, + int[] bytes_read, int length) throws IOException { + int value = 0; + int octet; + + for (int i = 0; i < length; i++) { + octet = stream.read(); + bytes_read[0]++; + value = (value<<8) + octet; + } + + return value; + } + + /** + * Reads the two complement representation from the input stream. + * @param stream inputstream + * @param byte_read number of byte read + * @param length length of the byte to be read + * @return the value of the two complement + * @exception IOException failed to read octets + */ + protected int readTwosComplement(InputStream stream, + int[] bytes_read, int length) throws IOException { + int value = 0; + if (length > 0) { + boolean negative = false; + int octet = stream.read(); + bytes_read[0]++; + if ((octet & 0x80) > 0) /* left-most bit is 1. */ + negative = true; + + for (int i = 0; i < length; i++) { + if (i > 0) { + octet = stream.read(); + bytes_read[0]++; + } + if (negative) + value = (value<<8) + (int)(octet^0xFF)&0xFF; + else + value = (value<<8) + (int)(octet&0xFF); + } + if (negative) /* convert to 2's complement */ + value = (value + 1) * -1; + } + return value; + } + + /** + * Converts byte to hex string. + * @param value byte value + * @return string representation of Hex String + */ + public String byteToHexString(byte value) { + if (value < 0) + return Integer.toHexString((value & 0x7F) + 128); + else + return Integer.toHexString(value); + } + + /** + * Sends the BER encoding directly to stream. + * @param stream output stream. + * @return bytes written to stream. + */ + public abstract void write(OutputStream stream) throws IOException; + + /** + * Gets the element type. + * @return element type + */ + public abstract int getType(); + + /** + * Gets the string representation. + * @return string representation of an element + */ + public abstract String toString(); +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BEREnumerated.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BEREnumerated.java new file mode 100644 index 00000000000..380c84e32b8 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BEREnumerated.java @@ -0,0 +1,66 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.ber.stream; + +import java.util.*; +import java.io.*; + +/** + * This class is for the Enumerated object. + * + * @version 1.0 + * @seeAlso CCITT X.209 + */ +public class BEREnumerated extends BERIntegral { + + /** + * Constructs an enumerated element with value. + * @param value integral value + */ + public BEREnumerated(int value) { + super(value); + } + + /** + * Constructs an enumerated element with the input stream. + * @param stream input stream to decode from. + * @param bytes_read array of 1 int; value incremented by + * number of bytes read from array. + * @exception IOException failed to construct + */ + public BEREnumerated(InputStream stream, int[] bytes_read) + throws IOException { + super(stream, bytes_read); + } + + /** + * Gets the element type. + * @param element type + */ + public int getType() { + return BERElement.ENUMERATED; + } + + /** + * Gets the string representation. + * @return string representation of tag + */ + public String toString() { + return "Enumerated {" + getValue() + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERInteger.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERInteger.java new file mode 100644 index 00000000000..570c0696800 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERInteger.java @@ -0,0 +1,83 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.ber.stream; + +import java.util.*; +import java.io.*; + +/** + * This class is for the Integer object. + * + *
+ * ENCODING RULE:
+ *   Primitive Definite length.
+ *   tag = 0x02
+ *   length = (short or long form)
+ *   one or more contents octets hold integer
+ *   value in two's complement
+ *
+ * Example 1:  (zero)
+ *   02 01 00
+ * Example 2:  (1)
+ *   02 01 01
+ * Example 3:  (300 - short form)
+ *   02 02 01 2C
+ * Example 4:  (300 - long form)
+ *   02 84 00 00 01 2C
+ * 
+ * + * @version 1.0 + * @seeAlso CCITT X.209 + */ +public class BERInteger extends BERIntegral { + + /** + * Constructs a integer element. + * @param value integer value + */ + public BERInteger(int value) { + super(value); + } + + /** + * Constructs an integer element with the input stream. + * @param stream input stream + * @param bytes_read array of 1 int; value incremented by + * number of bytes read from stream + * @exception IOException failed to construct + */ + public BERInteger(InputStream stream, int[] bytes_read) throws IOException { + super(stream, bytes_read); + } + + /** + * Gets the element type. + * @param element type + */ + public int getType() { + return BERElement.INTEGER; + } + + /** + * Gets the string representation. + * @return string representation of tag + */ + public String toString() { + return "Integer {" + getValue() + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERIntegral.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERIntegral.java new file mode 100644 index 00000000000..eb0e0410047 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERIntegral.java @@ -0,0 +1,172 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.ber.stream; + +import java.util.*; +import java.io.*; + +/** + * This is the base class for integral types such as Integer and + * Enumerated. + * + *
+ * ENCODING RULE:
+ *   Primitive Definite length.
+ *   tag = << depends on type >>
+ *   length = (short or long form)
+ *   one or more contents octets hold integral value
+ *   value in two's complement
+ *
+ * Example 1:  (Integer - zero)
+ *   02 01 00
+ * Example 2:  (Enumerated - 1)
+ *   0A 01 01
+ * Example 3:  (Integer - 300, short form)
+ *   02 02 01 2C
+ * Example 4:  (Integer - 300, long form)
+ *   02 84 00 00 01 2C
+ * 
+ * + * @version 1.0 + * @seeAlso CCITT X.209 + */ +public abstract class BERIntegral extends BERElement { + /** + * Internal variables + */ + private int m_value; + + /** + * Constructs an integral type. + * @param value integer value + */ + public BERIntegral(int value) { + m_value = value; + } + + /** + * Constructs an integral element with the input stream. + * @param stream input stream + * @param bytes_read array of 1 int; value incremented by + * number of bytes read from stream + * @exception IOException failed to construct + */ + public BERIntegral(InputStream stream, int[] bytes_read) throws IOException { + int contents_length = super.readLengthOctets(stream, bytes_read); + + /* Definite length content octets string. */ + if (contents_length > 0) { + boolean negative = false; + int octet = stream.read(); + bytes_read[0]++; + if ((octet & 0x80) > 0) /* left-most bit is 1. */ + negative = true; + + for (int i = 0; i < contents_length; i++) { + if (i > 0) { + octet = stream.read(); + bytes_read[0]++; + } + if (negative) + m_value = (m_value<<8) + (int)(octet^0xFF)&0xFF; + else + m_value = (m_value<<8) + (int)(octet&0xFF); + } + if (negative) /* convert to 2's complement */ + m_value = (m_value + 1) * -1; + } + } + + + /** + * Writes BER to stream. + * @return number of bytes written to stream. + * @exception IOException failed to send + */ + public void write(OutputStream stream) throws IOException { + int binary_value = m_value; + int num_content_octets = 0; + int total_ber_octets; + int offset=1; + int lead; + int i; + + byte[] content_octets = new byte[10]; /* should be plenty big */ + byte[] net_octets = new byte[10]; /* pse need this in network order */ + + /* Get content octets - need to determine length */ + if (m_value == 0) { + num_content_octets = 1; + content_octets[offset] = (byte)0x00; + net_octets[offset] = (byte)0x00; + } else { + + if (m_value < 0) /* convert from 2's complement */ + binary_value = (m_value * -1) -1; + + while (binary_value > 0) { + if (m_value < 0) + content_octets[num_content_octets+offset] = (byte)((binary_value^0xFF)&0xFF); + else + content_octets[num_content_octets+offset] = (byte)(binary_value&0xFF); + + binary_value = (binary_value>>8); + num_content_octets++; + } + /* pse 1/16/96 we've just created a string that is in non-network order + flip it for net order */ + for (i=0; i 0) && ((lead & 0x80) > 0)) { + offset = 0; + net_octets[offset] = (byte)0x00; + num_content_octets++; + } + + } + stream.write(getType()); + sendDefiniteLength(stream, num_content_octets); + stream.write(net_octets,offset,num_content_octets); /* contents */ + } + + /** + * Gets the integral value. + * @param element type + */ + public int getValue() { + return m_value; + } + + /** + * Gets the element type. + * @param element type + */ + public abstract int getType(); + + /** + * Gets the string representation. + * @return string representation of tag + */ + public abstract String toString(); +} + diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERNull.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERNull.java new file mode 100644 index 00000000000..455dd84092e --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERNull.java @@ -0,0 +1,87 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.ber.stream; + +import java.util.*; +import java.io.*; + +/** + * This class is for the NULL type. + * + *
+ * ENCODING RULE:
+ *   tag = 0x05
+ *   length value is zero (short or long form).
+ *   no contents
+ *
+ * Example 1:  (short form)
+ *   05 00
+ * Example 2:  (long form)
+ *   05 81 00
+ * 
+ * + * @version 1.0 + * @seeAlso CCITT X.209 + */ +public class BERNull extends BERElement { + /** + * Constructs a NULL element. + */ + public BERNull() { + } + + /** + * Constructs a null element with the input stream. + * @param stream input stream from socket + * @param bytes_read array of 1 int; value incremented by + * number of bytes read from stream + * @exception IOException failed to construct + */ + public BERNull(InputStream stream, int[] bytes_read) throws IOException { + /* The result should be zero of course */ + readLengthOctets(stream,bytes_read); + } + + /** + * Sends the BER encoding directly to stream. + * @param stream output stream + * @exception IOException failed to send + */ + public void write(OutputStream stream) throws IOException { + byte[] buffer = new byte[2]; + buffer[0] = (byte)BERElement.NULL; /* NULL tag */ + buffer[1] = 0x00; /* length */ + stream.write(buffer); + } + + /** + * Gets the element type. + * @param element type + */ + public int getType() { + return BERElement.NULL; + } + + /** + * Gets the string representation. + * @return string representation of tag + */ + public String toString() { + return "Null {}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERNumericString.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERNumericString.java new file mode 100644 index 00000000000..49cd28e4678 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERNumericString.java @@ -0,0 +1,90 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.ber.stream; + +import java.util.*; +import java.io.*; + +/** + * This class is for NumericString type. + * + * @version 1.0 + * @seeAlso CCITT X.209 + */ +public class BERNumericString extends BERCharacterString { + + /** + * Constructs an octetstring element containing buffer. + * @param buffer string containing 'octets' + */ + public BERNumericString(String string) { + m_value = string; + } + + /** + * Constructs a numericstring element from buffer. + * @param buffer buffer + */ + public BERNumericString(byte[] buffer) { + super(buffer); + } + + /** + * Constructs a numericstring element with the input stream. + * (for constructed encoding) + * @param stream input stream + * @param bytes_read array of 1 int, incremented by number of bytes read. + * @exception IOException failed to construct + */ + public BERNumericString(BERTagDecoder decoder, InputStream stream, + int[] bytes_read) throws IOException { + super(decoder,stream,bytes_read); + } + + /** + * Constructs a numericstring element with the input stream. + * (for primitive encoding) + * @param stream input stream + * @param bytes_read array of 1 int, incremented by number of bytes read. + * @exception IOException failed to construct + */ + public BERNumericString(InputStream stream, int[] bytes_read) + throws IOException { + super(stream,bytes_read); + } + + /** + * Gets the element type. + * @param element type + */ + public int getType() { + return BERElement.NUMERICSTRING; + } + + /** + * Gets the string representation. Note that currently prints out + * values in decimal form. + * @return string representation of tag + */ + public String toString() { + if (m_value == null) + return "NumericString (null)"; + else + return "NumericString {" + m_value + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERObjectId.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERObjectId.java new file mode 100644 index 00000000000..c02cdca5877 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERObjectId.java @@ -0,0 +1,186 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.ber.stream; + +import java.util.*; +import java.util.StringTokenizer; +import java.io.*; + +/** + * This class is for the Object ID object. + * + * @version 1.0 + * @seeAlso CCITT X.209 + */ +public class BERObjectId extends BERElement { + /** + * Internal variables + */ + private int[] m_value = null; + + /** + * Constructs a object id element. + * @param value object id value + */ + public BERObjectId(int[] value) { + m_value = new int[value.length]; + System.arraycopy(value,0,m_value,0,value.length); + } + + /** + * Constructs a object id element. + * @param value object id value in format "2.100.3" + */ + public BERObjectId(String value) { + StringTokenizer tokenizer = new StringTokenizer(value, "."); + m_value = new int[tokenizer.countTokens()]; + for (int i=0; i 0) { + contents_read[0] = 0; + sub_id = readSubIdentifier(stream, contents_read); + + contents_length -= contents_read[0]; + oid.addElement(new Integer(sub_id)); + } + m_value = new int[oid.size()]; + for (int i = 0; i= 2 identifier components (values). + * @param stream output stream + * @exception IOException failed to construct + */ + public void write(OutputStream stream) throws IOException { + stream.write(BERElement.OBJECTID); + + ByteArrayOutputStream contents_stream = new ByteArrayOutputStream(); + + /* first subidentifier packs two component values */ + writeSubIdentifier(contents_stream,m_value[0]*40 + m_value[1]); + + for (int i = 2; i < m_value.length; i++) { + writeSubIdentifier(contents_stream,m_value[i]); + } + byte[] contents_buffer = contents_stream.toByteArray(); + sendDefiniteLength(stream, contents_buffer.length); + stream.write(contents_buffer); + } + + /** + * Reads a sub identifier from stream. + * @param stream input stream + * @param bytes_read array of 1 int; value incremented by + * number of bytes read from stream. + */ + private int readSubIdentifier(InputStream stream, int[] bytes_read) + throws IOException { + int octet; + int sub_id = 0; + do { + octet = stream.read(); + bytes_read[0]++; + sub_id = (sub_id << 7) | (octet & 0x7F); + } while ((octet & 0x80) > 0); + return sub_id; + } + + /** + * Sends the BER encoding of a sub identifier directly to stream. + * @param stream output stream + * @param value sub-identifier value + */ + private void writeSubIdentifier(OutputStream stream, int value) + throws IOException { + ByteArrayOutputStream sub_id_stream = new ByteArrayOutputStream(); + /* gather octets in reverse order */ + while (value > 0) { + sub_id_stream.write(value & 0x7F); + value = value >> 7; + } + byte[] sub_id_buffer = sub_id_stream.toByteArray(); + for (int i=sub_id_buffer.length-1; i>0; i--) { + /* all but last octet have bit 8 = 1 */ + stream.write(sub_id_buffer[i] | 0x80); + } + stream.write(sub_id_buffer[0]); /* last octet has bit 8 = 0 */ + } + + /** + * Gets the element value. + * @param element value + */ + public int[] getValue() { + return m_value; + } + + /** + * Gets the element type. + * @param element type + */ + public int getType() { + return BERElement.OBJECTID; + } + + /** + * Gets the string representation. + * @return string representation of element + */ + public String toString() { + if (m_value == null) + return "ObjectIdentifier (null)"; + String oid = ""; + for (int i = 0; i < m_value.length; i++) { + if (i != 0) + oid = oid + " "; + oid = oid + m_value[i]; + } + return "ObjectIdentifier {" + oid + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BEROctetString.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BEROctetString.java new file mode 100644 index 00000000000..311c6904373 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BEROctetString.java @@ -0,0 +1,188 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.ber.stream; + +import java.util.*; +import java.io.*; + +/** + * This class is for OctetString type. + * + * @version 1.0 + * @seeAlso CCITT X.209 + */ +public class BEROctetString extends BERElement { + + /** + * Internal variables + */ + private byte[] m_value = null; + + /** + * Constructs an octetstring element containing a copy of + * the contents of buffer. + * @param buffer A UCS-2 String. + */ + public BEROctetString(String buffer) { + if (buffer == null) + return; + + try { + m_value = buffer.getBytes( "UTF8" ); + } catch (Throwable xxx){}; + } + + /** + * Constructs an octetstring element containing a reference to + * buffer. + * @param buffer A byte array, which must be in UTF-8 format if + * it is string data. + */ + public BEROctetString(byte[] buffer) { + m_value = buffer; + } + + /** + * Constructs an octetstring element containing a + * subset of buffer. + * @param buffer buffer containing 'octets' + * @param start start of buffer range to copy + * @param end end of buffer range to copy + */ + public BEROctetString(byte[] buffer, int start, int end) { + m_value = new byte[end - start]; + + for (int i = 0; i < end - start; i++) + m_value[i] = buffer[start + i]; + } + + /** + * Constructs a octetstring element with the input stream. + * (for constructed encoding) + * @param stream input stream + * @param bytes_read array of 1 int, incremented by number of bytes read. + * @exception IOException failed to construct + */ + public BEROctetString(BERTagDecoder decoder, InputStream stream, + int[] bytes_read) throws IOException { + int octet; + int contents_length = super.readLengthOctets(stream, bytes_read); + int[] component_length = new int[1]; + BERElement element = null; + + if (contents_length == -1) { + /* Constructed - indefinite length content octets. */ + do { + component_length[0] = 0; + element = getElement(decoder,stream,component_length); + if (element != null) { + /* element is an octetstring - add it to the existing buffer */ + BEROctetString octet_element = (BEROctetString)element; + byte[] octet_buffer = octet_element.getValue(); + if (m_value == null) { + m_value = new byte[octet_buffer.length]; + System.arraycopy(octet_buffer,0, + m_value,0,octet_buffer.length); + } else { + byte[] new_buffer = new byte[m_value.length + + octet_buffer.length]; + System.arraycopy(m_value,0,new_buffer,0,m_value.length); + System.arraycopy(octet_buffer,0, + new_buffer,m_value.length, + octet_buffer.length); + m_value = new_buffer; + } + } + } while (element != null); + } else { + /* Definite length content octets string. */ + bytes_read[0] += contents_length; + m_value = new byte[contents_length]; + stream.read(m_value, 0, contents_length); + } + } + + /** + * Constructs a octetstring element with the input stream. + * (for primitive encoding) + * @param stream input stream + * @param bytes_read array of 1 int, incremented by number of bytes read. + * @exception IOException failed to construct + */ + public BEROctetString(InputStream stream, int[] bytes_read) + throws IOException { + int contents_length = super.readLengthOctets(stream, bytes_read); + + /* Definite length content octets string. */ + if (contents_length > 0) { + m_value = new byte[contents_length]; + for (int i = 0; i < contents_length; i++) { + m_value[i] = (byte) stream.read(); + } + bytes_read[0] += contents_length; + } + } + + /** + * Writes BER to stream + * @return number of bytes written to stream. + * @exception IOException failed to send + */ + public void write(OutputStream stream) throws IOException { + stream.write((byte)BERElement.OCTETSTRING); /* OCTETSTRING tag */ + if (m_value == null) { + sendDefiniteLength(stream, 0); + } else { + sendDefiniteLength(stream, m_value.length); /* length */ + stream.write(m_value,0,m_value.length); /* contents */ + } + } + + /** + * Gets the element value. + * @param element value + */ + public byte[] getValue() { + return m_value; + } + + /** + * Gets the element type. + * @param element type + */ + public int getType() { + return BERElement.OCTETSTRING; + } + + /** + * Gets the string representation. + * NOTE: currently prints out values in decimal form. + * @return string representation of tag + */ + public String toString() { + if (m_value == null) + return "OctetString (null)"; + String octets = ""; + for (int i = 0; i < m_value.length; i++) { + if (i != 0) + octets = octets + " "; + octets = octets + byteToHexString(m_value[i]); + } + return "OctetString {" + octets + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERPrintableString.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERPrintableString.java new file mode 100644 index 00000000000..bc3846f47b5 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERPrintableString.java @@ -0,0 +1,91 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.ber.stream; + +import java.util.*; +import java.io.*; + +/** + * This class is for PrintableString type. + * + * @version 1.0 + * @seeAlso CCITT X.209 + */ +public class BERPrintableString extends BERCharacterString { + + /** + * Constructs an octetstring element containing buffer. + * @param buffer string containing 'octets' + */ + public BERPrintableString(String string) { + m_value = string; + } + + /** + * Constructs a printablestring element from buffer. + * @param buffer buffer + */ + public BERPrintableString(byte[] buffer) { + super(buffer); + } + + /** + * Constructs a printablestring element with the input stream. + * (for constructed encoding) + * @param stream input stream + * @param bytes_read array of 1 int, incremented by number of bytes read. + * @exception IOException failed to construct + */ + public BERPrintableString(BERTagDecoder decoder, InputStream stream, + int[] bytes_read) throws IOException { + super(decoder,stream,bytes_read); + } + + /** + * Constructs a printablestring element with the input stream. + * (for primitive encoding) + * @param stream input stream + * @param bytes_read array of 1 int, incremented by number of bytes read. + * @exception IOException failed to construct + */ + public BERPrintableString(InputStream stream, int[] bytes_read) + throws IOException { + super(stream,bytes_read); + } + + + /** + * Gets the element type. + * @param element type + */ + public int getType() { + return BERElement.PRINTABLESTRING; + } + + /** + * Gets the string representation. Note that currently prints out + * values in decimal form. + * @return string representation of tag + */ + public String toString() { + if (m_value == null) + return "PrintableString (null)"; + else + return "PrintableString {" + m_value + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERReal.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERReal.java new file mode 100644 index 00000000000..cb3a02a6a5a --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERReal.java @@ -0,0 +1,209 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.ber.stream; + +import java.util.*; +import java.io.*; + +/** + * This class is for the Real object. + * + *
+ * ENCODING RULE:
+ *  tag    = 0x09
+ * 
+ * + * @version 1.0 + * @seeAlso CCITT X.209 + */ +public class BERReal extends BERElement { + /* + * Constants: special ASN.1 real values + */ + public final static float PLUS_INFINITY = 1.0f/0.0f; + public final static float MINUS_INFINITY = -1.0f/0.0f; + + /** + * Internal variables + */ + private float m_value = 0; + + /** + * Constructs a real element. + * @param value float value + */ + public BERReal(float value) { + m_value = value; + } + + /** + * Constructs a real element with the input stream. + * @param stream input stream + * @param bytes_read array of 1 int; value incremented by + * number of bytes read from stream. + * @exception IOException failed to construct + */ + public BERReal(InputStream stream, int[] bytes_read) throws IOException { + int length = super.readLengthOctets(stream, bytes_read); + + if (length == 0) + /* zero length indicates value is zero */ + m_value = 0; + else { + int octet = stream.read(); /* first content octet */ + bytes_read[0]++; + + if (octet == 0x40) /* bit 8 = 1 */ + m_value = PLUS_INFINITY; + else if (octet == 0x41) /* bit 8 = 1 and bit 1 = 1 */ + m_value = MINUS_INFINITY; + else if ((octet & 0x80) > 0) { + /* bit 8 = 1 */ + /* Binary encoding */ + /* M = S*N*2F where S = -1 or 1, 0<= F <= 3. */ + int sign; + int base; + int number; + int f; /* binary scaling factor */ + int exponent; + int mantissa; + int num_exponent_octets; + int contents_length_left; + + if ((octet & 0x40) > 0) sign = -1; + else sign = 1; + + if ((octet & 0x20) > 0) { + if ((octet & 0x10) > 0) { + /* bits 6+5 = 11 */ + /* reserved for future use */ + base = 0; + } else { + /* bits 6+5 = 10 */ + base = 16; + } + } else if ((octet & 0x10) > 0) { + /* bits 6+5 = 01 */ + base = 8; + } else { + /* bits 6+5 = 00 */ + base = 2; + } + + if ((octet & 0x08) > 0) { + if ((octet & 0x04) > 0) { + /* bits 4+3 = 11 */ + f = 3; + } else { + /* bits 4+3 = 10 */ + f = 2; + } + } else if ((octet & 0x04) > 0) { + /* bits 4+3 = 01 */ + f = 1; + } else { + /* bits 4+3 = 00 */ + f = 0; + } + + if ((octet & 0x02) > 0) { + if ((octet & 0x01) > 0) { + /* bits 2+1 = 11 */ + /* Following octet encodes the number of octets used to + * encode the exponent. + */ + num_exponent_octets = stream.read(); + bytes_read[0]++; + exponent = readTwosComplement(stream,bytes_read,num_exponent_octets); + } else { + /* bits 2+1 = 10 */ + num_exponent_octets = 3; + exponent = readTwosComplement(stream,bytes_read,num_exponent_octets); + } + } else if ((octet & 0x01) > 0) { + /* bits 2+1 = 01 */ + num_exponent_octets = 2; + exponent = readTwosComplement(stream,bytes_read,num_exponent_octets); + } else { + /* bits 2+1 = 00 */ + num_exponent_octets = 1; + exponent = readTwosComplement(stream,bytes_read,num_exponent_octets); + } + + contents_length_left = length - 1 - num_exponent_octets; + number = readUnsignedBinary(stream, bytes_read, contents_length_left); + + mantissa = sign * number * 2 * f; + m_value = mantissa * (float)Math.pow((double)base,(double)exponent); + } else { + /* bits 8 + 7 = 00 */ + /* ISO 6093 field */ + /*** NOTE: It has been agreed that this feature will + * not be provided right now. + */ + throw new IOException("real ISO6093 not supported. "); + } + } + } + + /** + * Sends the BER encoding directly to stream. + * @param stream output stream + * @exception IOException failed to construct + */ + public void write(OutputStream stream) throws IOException { + if (m_value == 0) { + stream.write(BERElement.REAL); + stream.write(0x00); /* length */ + } else if (m_value == PLUS_INFINITY) { + stream.write(BERElement.REAL); + stream.write(0x01); /* length */ + stream.write(0x40); /* contents */ + } else if (m_value == MINUS_INFINITY) { + stream.write(BERElement.REAL); + stream.write(0x01); /* length */ + stream.write(0x41); /* contents */ + } else { + /* Non-special real value */ + /* NOTE: currently always sends as a base 2 binary encoding + * (see X.2 09 section 10.5.) + * + * M = S * N * 2F + * + * Simple encoding always uses F = 1. + */ + // bcm - incomplete. + } + } + + /** + * Gets the element type. + * @param element type + */ + public int getType() { + return BERElement.REAL; + } + + /** + * Gets the string representation. + * @return string representation of tag + */ + public String toString() { + return "Real {" + m_value + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERSequence.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERSequence.java new file mode 100644 index 00000000000..e0c03880fb6 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERSequence.java @@ -0,0 +1,72 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.ber.stream; + +import java.util.*; +import java.io.*; + +/** + * This class is for the Sequence object. A sequence object can + * contains a sequence of BER Elements. + * + * @version 1.0 + * @seeAlso CCITT X.209 + */ +public class BERSequence extends BERConstruct { + /** + * Constructs a sequence element. + */ + public BERSequence() { + super(); + } + + /** + * Constructs a sequence element. + * @param decoder application specific ber decoder. + * @param stream input stream to read ber from. + * @param bytes_read array of 1 int; value is incremented by + * number of bytes read from stream + * @exception IOException failed to construct + */ + public BERSequence(BERTagDecoder decoder, InputStream stream, + int[] bytes_read) throws IOException { + super(decoder, stream, bytes_read); + } + + /** + * Gets the element type. + * @param element type + */ + public int getType() { + return BERElement.SEQUENCE; + } + + /** + * Gets the string representation. + * @return string representation of tag + */ + public String toString() { + String elements = ""; + for (int i = 0; i < super.size(); i++) { + if (i != 0) + elements = elements + ", "; + elements = elements + ((BERElement)super.elementAt(i)).toString(); + } + return "Sequence {" + elements + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERSet.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERSet.java new file mode 100644 index 00000000000..4238b6c5b02 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERSet.java @@ -0,0 +1,81 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.ber.stream; + +import java.util.*; +import java.io.*; + +/** + * This class is for the Set object. A set object can contains + * a set of BER elements. + * + * @version 1.0 + * @seeAlso CCITT X.209 + */ +public class BERSet extends BERConstruct { + /** + * Constructs a set element. + * @exception failed to construct + */ + public BERSet() throws IOException { + } + + /** + * Constructs a set element with the input stream. + * @param decoder decoder for application specific ber + * @param stream input stream + * @param bytes_read array of 1 int; value incremented by number + * of bytes read from stream. + * @exception IOException failed to construct + */ + public BERSet(BERTagDecoder decoder, InputStream stream, + int[] bytes_read) throws IOException { + super(decoder, stream,bytes_read); + } + + /** + * Sends the BER encoding directly to stream. + * @param stream output stream + * @exception IOException failed to construct + */ + public void write(OutputStream stream) throws IOException { + super.write(stream); + } + + /** + * Gets the element type. + * @param element type + */ + public int getType() { + return BERElement.SET; + } + + /** + * Gets the string representation. + * @return string representation of tag + */ + public String toString() { + String elements = ""; + for (int i = 0; i < super.size(); i++) { + if (i != 0) + elements = elements + ", "; + elements = elements + ((BERElement)super.elementAt(i)).toString(); + } + return "Set {" + elements + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERTag.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERTag.java new file mode 100644 index 00000000000..9b15d590a16 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERTag.java @@ -0,0 +1,153 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.ber.stream; + +import java.util.*; +import java.io.*; + +/** + * This class is for the tagged object. Nested tag is + * allowed. A tagged element contains another + * ber element. + * + * @version 1.0 + * @seeAlso CCITT X.209 + */ +public class BERTag extends BERElement { + /** + * Internal variables + */ + private int m_tag = 0; + private BERElement m_element = null; + private boolean m_implicit = false; + + /** + * Constructs a tag element. + * @param tag tag value + * @param element ber element + * @param implicit tagged implicitly + */ + public BERTag(int tag, BERElement element, boolean implicit) { + m_tag = tag; + m_element = element; + m_implicit = implicit; + } + + /** + * Constructs a tag element with the input stream. + * @param decoder decoder object for application specific tags + * @param tag tag value; already stripped from stream + * @param stream input stream + * @param bytes_read array of 1 int; incremented by number + * ofbytes read from stream + * @exception IOException failed to construct + */ + public BERTag(BERTagDecoder decoder, int tag, InputStream stream, + int[] bytes_read) throws IOException { + + m_tag = tag; + boolean[] implicit = new boolean[1]; + + /* + * Need to use user callback to decode contents of + * a non-universal tagged value. + */ + m_element = decoder.getElement(decoder, tag, stream, bytes_read, + implicit); + m_implicit = implicit[0]; + } + + /** + * Gets the element from the tagged object. + * @return ber element + */ + public BERElement getValue() { + return m_element; + } + + /** + * Sets implicit tag. If it is a implicit tag + * the next element tag can be omitted. (will + * not be send to stream or buffer) + * @param value implicit flag + */ + public void setImplicit(boolean value) { + m_implicit = value; + } + + /** + * Sends the BER encoding directly to stream. + * @param stream output stream + * @exception IOException failed to send + */ + public void write(OutputStream stream) throws IOException { + stream.write(m_tag); /* bcm - assuming tag is one byte */ + + ByteArrayOutputStream contents_stream = new ByteArrayOutputStream(); + m_element.write(contents_stream); + byte[] contents_buffer = contents_stream.toByteArray(); + + if (m_implicit) { + /* Assumes tag is only one byte. Rest of buffer is */ + /* length and contents of tagged element. */ + stream.write(contents_buffer, 1, contents_buffer.length -1); + } else { + /* Send length */ + sendDefiniteLength(stream, contents_buffer.length); + /* Send contents */ + stream.write(contents_buffer); + } + } + + /** + * Gets the element type. + * @return element type + */ + public int getType() { + return BERElement.TAG; + } + + /** + * Gets the element tag. + * @return element tag. + */ + public int getTag() { + return m_tag; + } + + /** + * Gets the string representation. + * @return string representation of tag + */ + public String toString() { + String s = ""; + if ((m_tag & 0xC0) == 0) + /* bits 8 + 7 are zeros */ + s = s + "UNIVERSAL-"; + else if (((m_tag & 0x80) & (m_tag & 0x40)) > 0) + /* bits 8 + 7 are ones */ + s = s + "PRIVATE-"; + else if ((m_tag & 0x40) > 0) + /* bit 8 is zero, bit 7 is one */ + s = s + "APPLICATION-"; + else if ((m_tag & 0x80) > 0) + /* bit 8 is one, bit 7 is zero */ + s = s + "CONTEXT-"; + return "[" + s + (m_tag&0x1f) + "] " + m_element.toString(); + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERTagDecoder.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERTagDecoder.java new file mode 100644 index 00000000000..b13244d4475 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERTagDecoder.java @@ -0,0 +1,44 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.ber.stream; + +import java.util.*; +import java.io.*; + +/** + * This is an abstract class which should be extended + * for use by the BERTag class in decoding application + * specific BER tags. Since different application may + * define its own tag, the BER package needs tag decoder + * to give hints on how to decode implicit tagged + * objects. Note that each application should extend this + * decoder. + * + * @version 1.0 + * @seeAlso CCITT X.209 + */ +public abstract class BERTagDecoder { + + /** + * Gets an application specific ber element from a buffer. + * @param buffer ber encoding buffer + */ + public abstract BERElement getElement(BERTagDecoder decoder, int tag, + InputStream stream, int[] bytes_read, boolean[] implicit) + throws IOException; +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERUTCTime.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERUTCTime.java new file mode 100644 index 00000000000..7ccc221cd1e --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERUTCTime.java @@ -0,0 +1,160 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.ber.stream; + +import java.util.*; +import java.io.*; + +/** + * This class is for UTCTime object. + * + * @version 1.0 + * @seeAlso CCITT X.209 + */ +public class BERUTCTime extends BERElement { + + /** + * Internal variables + */ + private String m_value = null; + + /** + * Constructs an octetstring element containing buffer. + * @param buffer string containing 'octets' + */ + public BERUTCTime(String utc_string) { + m_value = utc_string; + } + + /** + * Constructs a UTCTime element with the input stream. + * (for constructed encoding) + * @param stream input stream + * @param bytes_read array of 1 int, incremented by number of bytes read. + * @exception IOException failed to construct + */ + public BERUTCTime(BERTagDecoder decoder, InputStream stream, + int[] bytes_read) throws IOException { + int octet; + int contents_length = super.readLengthOctets(stream, bytes_read); + int[] component_length = new int[1]; + BERElement element = null; + + m_value = ""; + + if (contents_length == -1) { + /* Constructed - indefinite length content octets. */ + { + component_length[0] = 0; + element = getElement(decoder,stream,component_length); + if (element != null) { + /* element is an octetstring - add it to the existing buffer */ + BERUTCTime utc_element = (BERUTCTime)element; + m_value += utc_element.getValue(); + } + } while (element != null); + } else { + /* Definite length content octets string. */ + bytes_read[0] += contents_length; + while (contents_length > 0) { + component_length[0] = 0; + element = getElement(decoder,stream,component_length); + if (element != null) { + /* element is an octetstring - add it to the existing buffer */ + BERUTCTime utc_element = (BERUTCTime)element; + m_value += utc_element.getValue(); + } + contents_length -= component_length[0]; + } + } + } + + /** + * Constructs a octetstring element with the input stream. + * (for primitive encoding) + * @param stream input stream + * @param bytes_read array of 1 int, incremented by number of bytes read. + * @exception IOException failed to construct + */ + public BERUTCTime(InputStream stream, int[] bytes_read) throws IOException { + int contents_length = super.readLengthOctets(stream, bytes_read); + + /* Definite length content octets string. */ + if (contents_length > 0) { + byte[] byte_buf = new byte[contents_length]; + for (int i = 0; i < contents_length; i++) { + byte_buf[i] = (byte) stream.read(); + } + bytes_read[0] += contents_length; + try{ + m_value = new String(byte_buf, "UTF8"); + } catch(Throwable x) + {} + } + } + + /** + * Writes ber to stream + * @return number of bytes written to stream. + * @exception IOException failed to send + */ + private byte[] byte_buf; + + public void write(OutputStream stream) throws IOException { + stream.write((byte)BERElement.OCTETSTRING); /* OCTETSTRING tag */ + if (m_value == null) { + sendDefiniteLength(stream, 0); + } else { + + try{ + byte_buf = m_value.getBytes("UTF8"); + sendDefiniteLength(stream, byte_buf.length); /* length */ + } catch(Throwable x) + {} + stream.write(byte_buf,0,byte_buf.length); /* contents */ + } + } + + /** + * Gets the element value. + * @param element value + */ + public String getValue() { + return m_value; + } + + /** + * Gets the element type. + * @param element type + */ + public int getType() { + return BERElement.UTCTIME; + } + + /** + * Gets the string representation. + * NOTE: currently prints out values in decimal form. + * @return string representation of tag + */ + public String toString() { + if (m_value == null) + return "UTCTime (null)"; + else + return "UTCTime {" + m_value + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERVisibleString.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERVisibleString.java new file mode 100644 index 00000000000..85ea65f84c0 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/ber/stream/BERVisibleString.java @@ -0,0 +1,90 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.ber.stream; + +import java.util.*; +import java.io.*; + +/** + * This class is for VisibleString object. + * + * @version 1.0 + * @seeAlso X.209 + */ +public class BERVisibleString extends BERCharacterString { + + /** + * Constructs a visiblestring element. + * @param string string + */ + public BERVisibleString(String string) { + m_value = string; + } + + /** + * Constructs a visiblestring element from buffer. + * @param buffer buffer + */ + public BERVisibleString(byte[] buffer) { + super(buffer); + } + + /** + * Constructs a visiblestring element with the input stream. + * (for constructed encoding) + * @param stream input stream + * @param bytes_read array of 1 int, incremented by number of bytes read. + * @exception IOException failed to construct + */ + public BERVisibleString(BERTagDecoder decoder, InputStream stream, + int[] bytes_read) throws IOException { + super(decoder,stream,bytes_read); + } + + /** + * Constructs a visiblestring element with the input stream. + * (for primitive encoding) + * @param stream input stream + * @param bytes_read array of 1 int, incremented by number of bytes read. + * @exception IOException failed to construct + */ + public BERVisibleString(InputStream stream, int[] bytes_read) + throws IOException { + super(stream,bytes_read); + } + + /** + * Gets the element type. + * @param element type + */ + public int getType() { + return BERElement.VISIBLESTRING; + } + + /** + * Gets the string representation. Note that currently prints out + * values in decimal form. + * @return string representation of tag + */ + public String toString() { + if (m_value == null) + return "VisibleString (null)"; + + return "VisibleString {" + m_value + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPAVA.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPAVA.java new file mode 100644 index 00000000000..ad64eef69be --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPAVA.java @@ -0,0 +1,98 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client; + +import java.util.*; +import java.io.*; +import netscape.ldap.ber.stream.*; +import netscape.ldap.client.*; + +/** + * This class implements the attribute value assertion. + * This object is used with filters. + *
+ * AttributeValueAssertion ::= SEQUENCE {
+ *   attributType AttributeType,
+ *   attributValue AttributeValue
+ * }
+ * 
+ * + * @version 1.0 + */ +public class JDAPAVA { + /** + * Internal variables + */ + protected String m_type = null; + protected String m_val = null; + + /** + * Constructs the attribute value assertion. + * @param type attribute type + * @param val attribute value + */ + public JDAPAVA(String type, String val) { + m_type = type; + m_val = val; + } + + /** + * Retrieves the AVA type. + * @return AVA type + */ + public String getType() { + return m_type; + } + + /** + * Retrieves the AVA value. + * @return AVA value + */ + public String getValue() { + return m_val; + } + + /** + * Retrieves the ber representation. + * @return ber representation + */ + public BERElement getBERElement() { + BERSequence seq = new BERSequence(); + seq.addElement(new BEROctetString(m_type)); + + seq.addElement(JDAPFilterOpers.getOctetString(m_val)); + + return seq; + } + + /** + * Retrieves the string representation parameters. + * @return string representation parameters + */ + public String getParamString() { + return "{type=" + m_type + ", value=" + m_val + "}"; + } + + /** + * Retrieves the string representation. + * @return string representation + */ + public String toString() { + return "JDAPAVA " + getParamString(); + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPBERTagDecoder.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPBERTagDecoder.java new file mode 100644 index 00000000000..8d66535bda3 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPBERTagDecoder.java @@ -0,0 +1,119 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client; + +import java.util.*; +import netscape.ldap.ber.stream.*; +import java.io.*; + +/** + * This class is to help BER libraries to make decision + * on how to decode an implicit object. + */ +public class JDAPBERTagDecoder extends BERTagDecoder { + /** + * Gets an application specific ber element from the stream. + * @param buffer ber encoding buffer + * @param stream input stream + * @param bytes_read number of bytes read + * @param implicit to indicate a tag implicit or not + */ + public BERElement getElement(BERTagDecoder decoder, int tag, + InputStream stream, int[] bytes_read, boolean[] implicit) + throws IOException { + BERElement element = null; + switch (tag) { + case 0x60: /* [APPLICATION 0] For Bind Request */ + case 0x61: /* [APPLICATION 1] Bind Response */ + case 0x63: /* [APPLICATION 3] Search Request + * If doing search without bind first, + * x500.arc.nasa.gov returns tag [APPLICATION 3] + * in Search Response. Gee. + */ + case 0x64: /* [APPLICATION 4] Search Response */ + case 0x65: /* [APPLICATION 5] Search Result */ + case 0x67: /* [APPLICATION 7] Modify Response */ + case 0x69: /* [APPLICATION 9] Add Response */ + case 0x6a: /* [APPLICATION 10] Del Request */ + case 0x6b: /* [APPLICATION 11] Del Response */ + case 0x6d: /* [APPLICATION 13] ModifyRDN Response */ + case 0x6f: /* [APPLICATION 15] Compare Response */ + case 0x78: /* [APPLICATION 23] Extended Response */ + case 0x73: /* [APPLICATION 19] SearchResultReference */ + element = new BERSequence(decoder, stream, bytes_read); + implicit[0] = true; + break; + case 0x80: /* [APPLICATION 16] 64+16 */ + element = new BERInteger(stream, bytes_read); + implicit[0] = true; + break; + /* 16/02/97 MS specific */ + case 0x85: /* Context Specific [5]: + * (a) Handle Microsoft v3 referral bugs! (Response) + * (b) Handle Microsoft v3 supportedVersion in Bind + * response + */ + element = new BERInteger(stream, bytes_read); + implicit[0] = true; + break; + case 0x87: /* Context Specific [7]: + * Handle Microsoft Filter "present" in + * search request. + */ + element = new BEROctetString(decoder, stream, bytes_read); + implicit[0] = true; + break; + case 0x8a: /* Context Specific [10]: + * Handle extended response + */ + element = new BEROctetString(decoder, stream, bytes_read); + implicit[0] = true; + break; + case 0x8b: /* Context Specific [11]: + * Handle extended response + */ + element = new BEROctetString(decoder, stream, bytes_read); + implicit[0] = true; + break; + case 0xa3: /* Context Specific [3]: + * Handle Microsoft v3 sasl bind request + */ + element = new BERSequence(decoder, stream, bytes_read); + implicit[0] = true; + break; + case 0xa7: /* Context Specific [7]: + * Handle Microsoft v3 serverCred in + * bind response. MS encodes it as SEQUENCE OF + * while it should be CHOICE OF. + */ + element = new BERSequence(decoder, stream, bytes_read); + implicit[0] = true; + break; + case 0xa0: /* Context Specific [0]: + * v3 Server Control. + * SEQUENCE of SEQUENCE of {OID [critical] [value]} + */ + element = new BERSequence(decoder, stream, bytes_read); + implicit[0] = true; + break; + default: + throw new IOException(); + } + return element; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPControl.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPControl.java new file mode 100644 index 00000000000..14eafb3f21c --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPControl.java @@ -0,0 +1,124 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client; + +import java.util.*; +import netscape.ldap.ber.stream.*; +import java.io.*; + +/** + * This class implements the controls for LDAPv3. + *
+ * Control ::= SEQUENCE {
+ *   controlType   LDAPOID,
+ *   criticality   BOOLEAN DEFAULT FALSE,
+ *   controlValue  OCTET STRING OPTIONAL
+ * }
+ * 
+ * + * @version 1.0 + * @see RFC1777 + */ +public class JDAPControl { + /** + * Internal variables + */ + String m_type = null; + boolean m_criticality = false; + byte m_vals[] = null; + + /** + * Constructs add request. + * @param dn distinguished name of adding entry + * @param attrs list of attribute associated with entry + */ + public JDAPControl(String type, boolean criticality, byte vals[]) { + m_type = type; + m_criticality = criticality; + m_vals = vals; + } + + /** + * Constructs control from BER element. + * @param e BER element + */ + public JDAPControl(BERElement e) { + BERSequence s = (BERSequence)e; + try{ + m_type = new String(((BEROctetString)s.elementAt(0)).getValue(), "UTF8"); + } catch(Throwable x) + {} + Object value = s.elementAt(1); + if (value instanceof BERBoolean) + m_criticality = ((BERBoolean)value).getValue(); + else + m_vals = ((BEROctetString)value).getValue(); + + if (s.size() >= 3) + m_vals = ((BEROctetString)s.elementAt(2)).getValue(); + } + + /** + * Gets the ber representation of control. + * @return ber representation of control + */ + public BERElement getBERElement() { + BERSequence seq = new BERSequence(); + seq.addElement(new BEROctetString (m_type)); + seq.addElement(new BERBoolean (m_criticality)); + if ( (m_vals == null) || (m_vals.length < 1) ) + seq.addElement(new BEROctetString ((byte[])null)); + else { + seq.addElement(new BEROctetString (m_vals, 0, m_vals.length)); + } + return seq; + } + + /** + * Returns the identifier of the control. + * @return Returns the type of the Control, as a string. + */ + public String getID() { + return m_type; + } + + /** + * Reports if the control is critical. + * @return true if the LDAP operation should be discarded if + * the server does not support this Control. + */ + public boolean isCritical() { + return m_criticality; + } + + /** + * Returns the data of the control. + * @return Returns the data of the Control, as a byte array. + */ + public byte[] getValue() { + return m_vals; + } + + /** + * Retrieves the string representation of extended request. + * @return string representation of extended request + */ + public String toString() { + return "Control" + " { type=" + m_type + ", criticality=" + m_criticality; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilter.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilter.java new file mode 100644 index 00000000000..bc166bc1e67 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilter.java @@ -0,0 +1,236 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client; + +import java.util.*; +import netscape.ldap.ber.stream.*; +import java.io.*; + +/** + * This class implements the filter. + *
+ *   Filter ::= CHOICE {
+ *     and [0] SET OF Filter,
+ *     or [1] SET OF Filter,
+ *     not [2] Filter,
+ *     equalityMatch [3] AttributeValueAssertion,
+ *     substrings [4] SubstringFilter,
+ *     greaterOrEqual [5] AttributeValueAssertion,
+ *     lessOrEqual [6] AttributeValueAssertion,
+ *     present [7] AttributeType,
+ *     approxMatch [8] AttributeValueAssertion
+ *   }
+ * 
+ * + * @version 1.0 + */ +public abstract class JDAPFilter { + /** + * Constructs a empty filter. + */ + public JDAPFilter() { + } + + /** + * Constructs filter from filter string specified in RFC1558. + *
+     *  ::= '('  ')'
+     *  ::=  |  |  | 
+     *  ::= '&' 
+     *  ::= '|' 
+     *  ::= '!' 
+     *  ::=  |  
+     *  ::=  |  | 
+     *  ::=   
+     *  ::=  |  |  | 
+     *  ::= '='
+     *  ::= '~='
+     *  ::= '>='
+     *  ::= '<='
+     *  ::=  '=*'
+     *  ::=  '='   
+     *  ::= NULL | 
+     *  ::= '*' 
+     *  ::= NULL |  '*' 
+     *  ::= NULL | 
+     * 
+ * @param dn distinguished name of adding entry + * @param attrs list of attribute associated with entry + * @return filter + */ + public static JDAPFilter getFilter(String filter) { + String f = new String(filter); + f.trim(); + if (f.startsWith("(") && f.endsWith(")")) { + return getFilterComp(f.substring(1,f.length()-1)); + } + return getFilterComp(filter); + } + + /** + * Constructs the filter computation. + * @param f filter string within brackets + * @return filter + */ + public static JDAPFilter getFilterComp(String f) { + f.trim(); + if (f.startsWith("&")) { /* and */ + JDAPFilter filters[] = getFilterList(f.substring(1, f.length())); + JDAPFilterAnd and = new JDAPFilterAnd(); + for (int i = 0; i < filters.length; i++) { + and.addElement(filters[i]); + } + return and; + } else if (f.startsWith("|")) { /* or */ + JDAPFilter filters[] = getFilterList(f.substring(1, f.length())); + JDAPFilterOr or = new JDAPFilterOr(); + for (int i = 0; i < filters.length; i++) { + or.addElement(filters[i]); + } + return or; + } else if (f.startsWith("!")) { /* not */ + return new JDAPFilterNot(getFilter(f.substring(1, f.length()))); + } else { /* item */ + return getFilterItem(f.substring(0, f.length())); + } + } + + /** + * Parses a list of filters + * @param list filter list (i.e. (filter)(filter)...) + * @return list of filters + */ + public static JDAPFilter[] getFilterList(String list) { + list.trim(); + + int level = 0; + int start = 0; + int end = 0; + Vector v = new Vector(); + + for (int i = 0; i < list.length(); i++) { + if (list.charAt(i) == '(') { + if (level == 0) { + start = i; + } + level++; + } + if (list.charAt(i) == ')') { + level--; + if (level == 0) { + end = i; + v.addElement(JDAPFilter.getFilter(list.substring(start, end+1))); + } + } + } + + if (v.size() == 0) + return null; + + JDAPFilter f[] = new JDAPFilter[v.size()]; + for (int i = 0; i < v.size(); i++) { + f[i] = (JDAPFilter)v.elementAt(i); + } + + return f; + } + + /** + * Gets filter item. + * @param item filter item string + * @return filter + */ + public static JDAPFilter getFilterItem(String item) { + item.trim(); + int idx = item.indexOf('='); + if (idx == -1) + return null; + + String type = item.substring(0, idx).trim(); + String value = item.substring(idx+1).trim(); /* skip = */ + + /* make decision by looking at the type */ + type.trim(); + if (type.endsWith("~")) { + JDAPAVA ava = new + JDAPAVA(type.substring(0, type.length()-1), value); + return new JDAPFilterApproxMatch(ava); + } else if (type.endsWith(">")) { + JDAPAVA ava = new + JDAPAVA(type.substring(0, type.length()-1), value); + return new JDAPFilterGreaterOrEqual(ava); + } else if (type.endsWith("<")) { + JDAPAVA ava = new + JDAPAVA(type.substring(0, type.length()-1), value); + return new JDAPFilterLessOrEqual(ava); + } else if (type.endsWith(":")) { + return new JDAPFilterExtensible(type.substring(0, type.length()-1), value); + } + + /* for those that are not simple */ + if (value.startsWith("*") && value.length() == 1) { + return new JDAPFilterPresent(type); + } + + /* if value contains no '*', then it is equality */ + if (value.indexOf('*') == -1) { + JDAPAVA ava = new JDAPAVA(type, value); + return new JDAPFilterEqualityMatch(ava); + } + + /* must be substring at this point */ + StringTokenizer st = new StringTokenizer(value, "*"); + JDAPFilterSubString sub = new JDAPFilterSubString(type); + + String initial = null; + if (!value.startsWith("*")) { + initial = st.nextToken(); + initial.trim(); + } + sub.addInitial(initial); + + while (st.hasMoreTokens()) { + String any = st.nextToken(); + any.trim(); + if (st.hasMoreTokens()) { + sub.addAny(any); + } else { + if (value.endsWith("*")) { + sub.addAny(any); + sub.addFinal(null); + } else { + sub.addFinal(any); + } + } + } + + return sub; + } + + /** + * Gets the ber representation of filter. + * @return ber representation of filter + */ + public abstract BERElement getBERElement(); + + /** + * Retrieves the string representation of filter. + * @return string representation of filter + */ + public abstract String toString(); +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterAVA.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterAVA.java new file mode 100644 index 00000000000..e8ee754e5b9 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterAVA.java @@ -0,0 +1,63 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client; + +import java.util.*; +import netscape.ldap.ber.stream.*; +import java.io.*; + +/** + * This class implements the attribute value assertion filter. + * + * @version 1.0 + */ +public abstract class JDAPFilterAVA extends JDAPFilter { + /** + * Internal variables + */ + private int m_tag; + private JDAPAVA m_ava = null; + + /** + * Constructs base filter for other attribute value assertion. + * @param tag attribute tag + * @param ava attribute value assertion + */ + public JDAPFilterAVA(int tag, + JDAPAVA ava) { + m_tag = tag; + m_ava = ava; + } + + /** + * Get attribute value assertion. + * @return value assertion + */ + public JDAPAVA getAVA() { + return m_ava; + } + + /** + * Gets the ber representation of the filter. + * @return ber representation + */ + public BERElement getBERElement() { + BERTag element = new BERTag(m_tag, m_ava.getBERElement(), true); + return element; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterAnd.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterAnd.java new file mode 100644 index 00000000000..bf77464ee11 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterAnd.java @@ -0,0 +1,47 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client; + +import java.util.*; +import netscape.ldap.ber.stream.*; +import java.io.*; + +/** + * This class implements the filter And. + *
+ *   and [0] SET OF Filter
+ * 
+ * + * @version 1.0 + */ +public class JDAPFilterAnd extends JDAPFilterSet { + /** + * Constructs the filter. + */ + public JDAPFilterAnd() { + super(BERTag.CONSTRUCTED|BERTag.CONTEXT|0); + } + + /** + * Gets string reprensetation of the filter. + * @return string representation + */ + public String toString() { + return "JDAPFilterAnd {" + super.getParamString() + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterApproxMatch.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterApproxMatch.java new file mode 100644 index 00000000000..9c0538bebe9 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterApproxMatch.java @@ -0,0 +1,49 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client; + +import java.util.*; +import netscape.ldap.ber.stream.*; +import java.io.*; + +/** + * This class implements the approximate match filter. + *
+ * approxMatch [8] AttributeValueAssertion
+ * 
+ * + * @version 1.0 + */ +public class JDAPFilterApproxMatch extends JDAPFilterAVA { + /** + * Constructs approximate match filter. + * @param ava attribute value assertion + */ + public JDAPFilterApproxMatch(JDAPAVA ava) { + super(BERTag.CONSTRUCTED|BERTag.CONTEXT|8, ava); + } + + /** + * Retrieves the string representation of the filter. + * @return string representation + */ + public String toString() { + return "JDAPFilterApproximateMatch {" + + super.getAVA().toString() + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterEqualityMatch.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterEqualityMatch.java new file mode 100644 index 00000000000..4d7a5d8bfcc --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterEqualityMatch.java @@ -0,0 +1,50 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client; + +import java.util.*; +import netscape.ldap.ber.stream.*; +import java.io.*; + +/** + * This class implements the equality match filter. + *
+ * equalityMatch [3] AttributeValueAssertion
+ * 
+ * + * @version 1.0 + * @see RFC1777 + */ +public class JDAPFilterEqualityMatch extends JDAPFilterAVA { + /** + * Constructs less or equal filter. + * @param ava attribute value assertion + */ + public JDAPFilterEqualityMatch(JDAPAVA ava) { + super(BERTag.CONSTRUCTED|BERTag.CONTEXT|3, ava); + } + + /** + * Retrieves the string representation of the filter. + * @return string representation + */ + public String toString() { + return "JDAPFilterEqualityMatch {" + + super.getAVA().toString() + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterExtensible.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterExtensible.java new file mode 100644 index 00000000000..bfb82a38e5a --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterExtensible.java @@ -0,0 +1,128 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client; + +import java.util.*; +import netscape.ldap.ber.stream.*; +import java.io.*; + +/** + * This class implements the extended match filter. + *
+ * extensibleMatch [9] AttributeValueAssertion
+ * 
+ * + * @version 1.0 + */ +public class JDAPFilterExtensible extends JDAPFilter { + /** + * Constructs extensible match filter. + * @param match Matching rule assertion + */ + public JDAPFilterExtensible(String type, String match) { + m_tag = BERTag.CONSTRUCTED|BERTag.CONTEXT|9; + m_type = type; + m_value = match; + } + + /** + * Gets ber representation of the filter. + *
+     * Extended filter:   [type] [':dn'][':'oid]':='value
+     *
+     * BER:   extensibleMatch    [9] MatchingRuleAssertion
+     *        MatchingRuleAssertion ::= SEQUENCE {
+     *             matchingRule    [1] MatchingRuleID OPTIONAL,
+     *             type            [2] AttributeDescription OPTIONAL,
+     *             matchValue      [3] AssertionValue,
+     *             dnAttributes    [4] BOOLEAN DEFAULT FALSE
+     *        }
+     * 
+ * @return ber representation + */ + public BERElement getBERElement() { + String value = m_value; + String defs = m_type; + + /* Need either ':dn' or ':'oid */ + int colonIndex = defs.lastIndexOf(':'); + if ( colonIndex == -1 ) { + return null; + } + /* Is it dn or oid? */ + boolean isDN = false; + String oid = null; + if ( defs.regionMatches( true, colonIndex+1, "dn", 0, 2 ) ) + isDN = true; + else + oid = defs.substring( colonIndex+1 ); + + /* Any more? */ + defs = defs.substring( 0, colonIndex ); + colonIndex = defs.lastIndexOf(':'); + if ( colonIndex >= 0 ) { + /* Is it dn or oid? */ + if ( defs.regionMatches( true, colonIndex+1, "dn", 0, 2 ) ) + isDN = true; + else + oid = defs.substring( colonIndex+1 ); + } + + BERSequence seq = new BERSequence(); + BERTag tag; + + /* Was there an oid? */ + if ( oid != null ) { + tag = new BERTag( BERTag.CONTEXT|BERTag.MRA_OID, new + BEROctetString(oid), true ); + seq.addElement( tag ); + } + + /* Was there an attribute description? */ + if ( defs.length() > 0 ) { + tag = new BERTag( BERTag.CONTEXT|BERTag.MRA_TYPE, new + BEROctetString(defs), true ); + seq.addElement( tag ); + } + + /* Got to have a value */ + tag = new BERTag( BERTag.CONTEXT|BERTag.MRA_VALUE, new + BEROctetString(value), true ); + seq.addElement( tag ); + + /* Was ':dn' specified? */ + tag = new BERTag( BERTag.CONTEXT|BERTag.MRA_DNATTRS, new + BERBoolean(isDN), true ); + seq.addElement( tag ); + + BERTag element = new BERTag( m_tag, seq, true ); + return element; + } + + /** + * Retrieves the string representation of the filter. + * @return string representation + */ + public String toString() { + return "JDAPFilterExtensible {" + m_value + "}"; + } + + private int m_tag; + private String m_type = null; + private String m_value = null; +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterGreaterOrEqual.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterGreaterOrEqual.java new file mode 100644 index 00000000000..42a9916ed93 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterGreaterOrEqual.java @@ -0,0 +1,50 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client; + +import java.util.*; +import netscape.ldap.ber.stream.*; +import java.io.*; + +/** + * This class implements the greater or equal filter. + *
+ * greaterOrEqual [5] AttributeValueAssertion
+ * 
+ * + * @version 1.0 + * @see RFC1777 + */ +public class JDAPFilterGreaterOrEqual extends JDAPFilterAVA { + /** + * Constructs greater or equal filter. + * @param ava attribute value assertion + */ + public JDAPFilterGreaterOrEqual(JDAPAVA ava) { + super(BERTag.CONSTRUCTED|BERTag.CONTEXT|5, ava); + } + + /** + * Retrieves the string representation of the filter. + * @return string representation + */ + public String toString() { + return "JDAPFilterGreaterOrEqual {" + + super.getAVA().toString() + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterLessOrEqual.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterLessOrEqual.java new file mode 100644 index 00000000000..0c88138dd7c --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterLessOrEqual.java @@ -0,0 +1,49 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client; + +import java.util.*; +import netscape.ldap.ber.stream.*; +import java.io.*; + +/** + * This class implements the less or equal filter. + *
+ * lessOrEqual [6] AttributeValueAssertion
+ * 
+ * + * @version 1.0 + */ +public class JDAPFilterLessOrEqual extends JDAPFilterAVA { + /** + * Constructs less or equal filter. + * @param ava attribute value assertion + */ + public JDAPFilterLessOrEqual(JDAPAVA ava) { + super(BERTag.CONSTRUCTED|BERTag.CONTEXT|6, ava); + } + + /** + * Retrieves the string representation of the filter. + * @return string representation + */ + public String toString() { + return "JDAPFilterLessOrEqual {" + + super.getAVA().toString() + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterNot.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterNot.java new file mode 100644 index 00000000000..f39cd4f2c15 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterNot.java @@ -0,0 +1,65 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client; + +import java.util.*; +import netscape.ldap.ber.stream.*; +import java.io.*; + +/** + * This class implements the filter not. + *
+ *   not [2] Filter
+ * 
+ * + * @version 1.0 + * @see RFC1777 + */ +public class JDAPFilterNot extends JDAPFilter { + + /** + * Internal variables + */ + private JDAPFilter m_filter = null; + + /** + * Constructs the filter. + */ + public JDAPFilterNot(JDAPFilter filter) { + super(); + m_filter = filter; + } + + /** + * Gets ber representation of the filter. + * @return ber representation + */ + public BERElement getBERElement() { + BERTag element = new BERTag(BERTag.CONSTRUCTED|BERTag.CONTEXT|2, + m_filter.getBERElement(), false /* true */); + return element; + } + + /** + * Gets string reprensetation of the filter. + * @return string representation + */ + public String toString() { + return "JDAPFilterNot {" + m_filter.toString() + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterOpers.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterOpers.java new file mode 100644 index 00000000000..0f0c3b8a31a --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterOpers.java @@ -0,0 +1,125 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client; + +import java.util.Vector; +import java.io.*; +import netscape.ldap.ber.stream.*; + +/** + * This class provides miscellaneous operations for JDAPFilter object. + * It converts string with escape characters to the byte array. It also + * returns the ber octet string for the specified string with escape + * characters. + */ +class JDAPFilterOpers { + + private static final String escapeKey = "\\"; + private static final boolean m_debug = false; + + /** + * Returns the octetString for the given string + * @return The octetString for the given string + */ + static BEROctetString getOctetString(String str) { + if (str.indexOf(escapeKey) >= 0) { + byte[] byteVal = JDAPFilterOpers.getByteValues(str); + return new BEROctetString(byteVal); + } + else + return new BEROctetString(str); + } + + /** + * This method converts the given string into bytes. It also handles + * the escape characters embedded in the given string. + * @param str The given string being converted into a byte array + * @return A byte array + */ + static byte[] getByteValues(String str) { + int pos = 0; + Vector v = new Vector(); + String val = new String(str); + int totalSize = 0; + + // check if any escape character in the string + while ((pos = val.indexOf(escapeKey)) >= 0) { + String s1 = val.substring(0, pos); + + try { + byte[] b = s1.getBytes("UTF8"); + totalSize += b.length; + v.addElement(b); + } catch (UnsupportedEncodingException e) { + printDebug(e.toString()); + return null; + } + + String hex = "0x"+val.substring(pos+1, pos+3); + + Integer num = null; + + // decode this number to integer, exception thrown when this is not the + // hex + try { + num = Integer.decode(hex); + } catch (NumberFormatException e) { + printDebug(e.toString()); + return null; + } + + byte[] b = {(byte)num.intValue()}; + totalSize += b.length; + + v.addElement(b); + + // skip an escape and two chars after escape + val = val.substring(pos+3); + } + + if (val.length() > 0) { + try { + byte[] b = val.getBytes("UTF8"); + totalSize += b.length; + v.addElement(b); + } catch (UnsupportedEncodingException e) { + printDebug(e.toString()); + return null; + } + } + + byte[] result = new byte[totalSize]; + pos = 0; + for (int i=0; i + * or [1] SET OF Filter + * + * + * @version 1.0 + * @see RFC1777 + */ +public class JDAPFilterOr extends JDAPFilterSet { + /** + * Constructs the filter. + */ + public JDAPFilterOr() { + super(BERTag.CONSTRUCTED|BERTag.CONTEXT|1); + } + + /** + * Gets string reprensetation of the filter. + * @return string representation + */ + public String toString() { + return "JDAPFilterOr {" + super.getParamString() + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterPresent.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterPresent.java new file mode 100644 index 00000000000..fe06b888213 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterPresent.java @@ -0,0 +1,65 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client; + +import java.util.*; +import netscape.ldap.ber.stream.*; +import java.io.*; + +/** + * This class implements the filter present. + *
+ *   present [7] AttributeType
+ * 
+ * + * @version 1.0 + * @see RFC1777 + */ +public class JDAPFilterPresent extends JDAPFilter { + /** + * Internal variables + */ + private String m_type = null; + + /** + * Constructs the filter. + * @param type attribute type + */ + public JDAPFilterPresent(String type) { + super(); + m_type = type; + } + + /** + * Gets ber representation of the filter. + * @return ber representation + */ + public BERElement getBERElement() { + BEROctetString s = new BEROctetString(m_type); + BERTag element = new BERTag(BERTag.CONTEXT|7, s, true); + return element; + } + + /** + * Gets string reprensetation of the filter. + * @return string representation + */ + public String toString() { + return "JDAPFilterPresent {" + m_type + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterSet.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterSet.java new file mode 100644 index 00000000000..6bc04045dac --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterSet.java @@ -0,0 +1,85 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client; + +import java.util.*; +import netscape.ldap.ber.stream.*; +import java.io.*; + +/** + * This class implements the base class of filter "and" and filter "or". + * + * @version 1.0 + */ +public abstract class JDAPFilterSet extends JDAPFilter { + /** + * Internal variables + */ + private int m_tag; + private Vector m_set = new Vector(); + + /** + * Constructs the filter set. + * @param tag tag + */ + public JDAPFilterSet(int tag) { + super(); + m_tag = tag; + } + + /** + * Adds filter into the filter set. + * @param filter adding filter + */ + public void addElement(JDAPFilter filter) { + m_set.addElement(filter); + } + + /** + * Gets the ber representation of the filter. + * @return ber representation + */ + public BERElement getBERElement() { + try { + BERSet filters = new BERSet(); + for (int i = 0; i < m_set.size(); i++) { + JDAPFilter f = (JDAPFilter)m_set.elementAt(i); + filters.addElement(f.getBERElement()); + } + BERTag element = new BERTag(m_tag, filters, true); + return element; + } catch (IOException e) { + return null; + } + } + + /** + * Gets the filter set parameters. + * @return set parameters + */ + public String getParamString() { + String s = ""; + for (int i = 0; i < m_set.size(); i++) { + if (i != 0) + s = s + ","; + JDAPFilter f = (JDAPFilter)m_set.elementAt(i); + s = s + f.toString(); + } + return s; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterSubString.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterSubString.java new file mode 100644 index 00000000000..11f8fa9b7fe --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPFilterSubString.java @@ -0,0 +1,150 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client; + +import java.util.*; +import netscape.ldap.ber.stream.*; +import java.io.*; +import netscape.ldap.client.*; + +/** + * This class implements the filter substring. + *
+ * [4] SEQUENCE {
+ *   type AttributeType,
+ *   SEQUENCE OF CHOICE {
+ *     initial [0] LDAPString,
+ *     any [1] LDAPString,
+ *     final [2] LDAPString
+ *   }
+ *     }
+ * 
+ * + * @version 1.0 + * @see RFC1777 + */ +public class JDAPFilterSubString extends JDAPFilter { + /** + * Internal variables + */ + private String m_type = null; + private Vector m_initial = new Vector(); + private Vector m_any = new Vector(); + private Vector m_final = new Vector(); + + /** + * Constructs the filter. + * @param type attribute type + */ + public JDAPFilterSubString(String type) { + super(); + m_type = type; + } + + /** + * Adds initial substring. + * @param s initial substring + */ + public void addInitial(String s) { + m_initial.addElement(s); + } + + /** + * Adds any substring. + * @param s any substring + */ + public void addAny(String s) { + m_any.addElement(s); + } + + /** + * Adds final substring. + * @param s final substring + */ + public void addFinal(String s) { + m_final.addElement(s); + } + + /** + * Gets ber representation of the filter. + * @return ber representation + */ + public BERElement getBERElement() { + BERSequence seq = new BERSequence(); + seq.addElement(new BEROctetString(m_type)); + BERSequence str_seq = new BERSequence(); + for (int i = 0; i < m_initial.size(); i++) { + String val = (String)m_initial.elementAt(i); + if (val == null) + continue; + BERTag str = new BERTag(BERTag.CONTEXT|0, + JDAPFilterOpers.getOctetString(val), true); + str_seq.addElement(str); + } + for (int i = 0; i < m_any.size(); i++) { + String val = (String)m_any.elementAt(i); + if (val == null) + continue; + BERTag str = new BERTag(BERTag.CONTEXT|1, + JDAPFilterOpers.getOctetString(val), true); + str_seq.addElement(str); + } + for (int i = 0; i < m_final.size(); i++) { + String val = (String)m_final.elementAt(i); + if (val == null) + continue; + BERTag str = new BERTag(BERTag.CONTEXT|2, + JDAPFilterOpers.getOctetString(val), true); + str_seq.addElement(str); + } + seq.addElement(str_seq); + BERTag element = new BERTag(BERTag.CONSTRUCTED|BERTag.CONTEXT|4, + seq, true); + return element; + } + + /** + * Gets string reprensetation of the filter. + * @return string representation + */ + public String toString() { + String initial = ""; + for (int i = 0; i < m_initial.size(); i++) { + if (i != 0) + initial = initial + ","; + initial = initial + (String)m_initial.elementAt(i); + } + + String any = ""; + for (int i = 0; i < m_any.size(); i++) { + if (i != 0) + any = any + ","; + any = any + (String)m_any.elementAt(i); + } + + String s_final = ""; + for (int i = 0; i < m_final.size(); i++) { + if (i != 0) + s_final = s_final + ","; + s_final = s_final + (String)m_final.elementAt(i); + } + + return "JDAPFilterSubString {type=" + m_type + ", initial=" + initial + + ", any=" + any + ", final=" + s_final + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPMessage.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPMessage.java new file mode 100644 index 00000000000..f7e99fa8c73 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/JDAPMessage.java @@ -0,0 +1,194 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client; + +import java.util.*; +import netscape.ldap.client.opers.*; +import netscape.ldap.ber.stream.*; +import java.io.*; +import java.net.*; + +/** + * This class represents the LDAPMessage in RFC1777. The + * message is the entity that got transferred back and + * fro between the server and the client interface. Each + * message has a protocol operation. The protocol operation + * indicates if it is a request or response. + *
+ * LDAPMessage ::= SEQUECE {
+ *   messageID MessageID,
+ *   protocolOp CHOICE {
+ *     bindRequest BindRequest,
+ *     ...
+ *   }
+ * }
+ * 
+ * + * @version 1.0 + */ +public class JDAPMessage { + /** + * Internal variables + */ + protected int m_msgid; + protected JDAPProtocolOp m_protocolOp = null; + protected JDAPControl m_controls[] = null; + + /** + * Constructs a ldap message. + * @param msgid message identifier + * @param op operation protocol + */ + public JDAPMessage(int msgid, JDAPProtocolOp op) { + m_msgid = msgid; + m_protocolOp = op; + } + + public JDAPMessage(int msgid, JDAPProtocolOp op, JDAPControl controls[]) { + m_msgid = msgid; + m_protocolOp = op; + m_controls = controls; /* LDAPv3 additions */ + } + + /** + * Constructs a ldap message with BERElement. This constructor + * is used by JDAPClient to build JDAPMessage from byte + * stream. + * @param element ber element constructed from incoming byte stream + */ + public JDAPMessage(BERElement element) throws IOException { + if (element.getType() != BERElement.SEQUENCE) + throw new IOException("SEQUENCE in jdap message expected"); + BERSequence seq = (BERSequence)element; + BERInteger msgid = (BERInteger)seq.elementAt(0); + m_msgid = msgid.getValue(); + BERElement protocolOp = (BERElement)seq.elementAt(1); + if (protocolOp.getType() != BERElement.TAG) { + throw new IOException("TAG in protocol operation is expected"); + } + BERTag tag = (BERTag)protocolOp; + switch (tag.getTag()&0x1f) { + case JDAPProtocolOp.BIND_RESPONSE: + m_protocolOp = new JDAPBindResponse(protocolOp); + break; + case JDAPProtocolOp.SEARCH_RESPONSE: + m_protocolOp = new JDAPSearchResponse(protocolOp); + break; + /* + * If doing search without bind, + * x500.arc.nasa.gov returns tag SEARCH_REQUEST tag + * in SEARCH_RESULT. + */ + case JDAPProtocolOp.SEARCH_REQUEST: + case JDAPProtocolOp.SEARCH_RESULT: + m_protocolOp = new JDAPSearchResult(protocolOp); + break; + case JDAPProtocolOp.MODIFY_RESPONSE: + m_protocolOp = new JDAPModifyResponse(protocolOp); + break; + case JDAPProtocolOp.ADD_RESPONSE: + m_protocolOp = new JDAPAddResponse(protocolOp); + break; + case JDAPProtocolOp.DEL_RESPONSE: + m_protocolOp = new JDAPDeleteResponse(protocolOp); + break; + case JDAPProtocolOp.MODIFY_RDN_RESPONSE: + m_protocolOp = new JDAPModifyRDNResponse(protocolOp); + break; + case JDAPProtocolOp.COMPARE_RESPONSE: + m_protocolOp = new JDAPCompareResponse(protocolOp); + break; + case JDAPProtocolOp.SEARCH_RESULT_REFERENCE: + m_protocolOp = new JDAPSearchResultReference(protocolOp); + break; + case JDAPProtocolOp.EXTENDED_RESPONSE: + m_protocolOp = new JDAPExtendedResponse(protocolOp); + break; + default: + throw new IOException("Unknown rotocol operation"); + } + + /* parse control */ + if (seq.size() >= 3) { + tag = (BERTag)seq.elementAt(2); + if ( tag.getTag() == (BERTag.CONSTRUCTED|BERTag.CONTEXT|0) ) { + BERSequence controls = (BERSequence)tag.getValue(); + m_controls = new JDAPControl[controls.size()]; + for (int i = 0; i < controls.size(); i++) { + m_controls[i] = new JDAPControl(controls.elementAt(i)); + } + } + } + } + + /** + * Retrieves the message identifer. + * @return message identifer + */ + public int getId(){ + return m_msgid; + } + + /** + * Retrieves the protocol operation. + * @return protocol operation + */ + public JDAPProtocolOp getProtocolOp() { + return m_protocolOp; + } + + /** + * Retrieves list of controls. + * @return controls + */ + public JDAPControl[] getControls() { + return m_controls; + } + + /** + * Writes the ber encoding to stream. + * @param s output stream + */ + public void write(OutputStream s) throws IOException { + BERSequence seq = new BERSequence(); + BERInteger i = new BERInteger(m_msgid); + seq.addElement(i); + BERElement e = m_protocolOp.getBERElement(); + if (e == null) { + throw new IOException("Bad BER element"); + } + seq.addElement(e); + if (m_controls != null) { /* LDAPv3 additions */ + BERSequence c = new BERSequence(); + for (int j = 0; j < m_controls.length; j++) { + c.addElement(m_controls[j].getBERElement()); + } + BERTag t = new BERTag(BERTag.CONTEXT|BERTag.CONSTRUCTED|0, c, true); + seq.addElement(t); + } + seq.write(s); + } + + /** + * Returns string representation of a ldap message. + * @return ldap message + */ + public String toString() { + return "[JDAPMessage] " + m_msgid + " " + m_protocolOp.toString(); + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPAbandonRequest.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPAbandonRequest.java new file mode 100644 index 00000000000..9dbe74286b5 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPAbandonRequest.java @@ -0,0 +1,89 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client.opers; + +import java.util.*; +import netscape.ldap.client.*; +import netscape.ldap.ber.stream.*; +import java.io.*; +import java.net.*; + +/** + * This class implements the abandon request. This object + * is sent to the ldap server. + *
+ * AbandonRequest ::= [APPLICATION 16] MessageID
+ * 
+ * + * @version 1.0 + * @see RFC1777 + */ +public class JDAPAbandonRequest implements JDAPProtocolOp { + /** + * Internal variables + */ + protected int m_msgid; + + /** + * Constructs abandon request. + * @param msgid message identifier + */ + public JDAPAbandonRequest(int msgid) { + m_msgid = msgid; + } + + /** + * Retrieves the protocol operation type. + * @return protocol type + */ + public int getType() { + return JDAPProtocolOp.ABANDON_REQUEST; + } + + /** + * Gets the ber representation of abandon request. + * @return ber representation of request + */ + public BERElement getBERElement() { + /* Assumed m_msgid = 1. The BER encoding output + * should be + * + * [*] umich-ldap-v3.3: + * 0x50 (implicit tagged integer) + * 0x01 (length) + * 0x01 (message id) + * [*] umich-ldap-v3.0: + * 0x50 (tag APPLICATION|CONSTRUCTED) + * 0x85 0x00 0x00 0x00 0x07 (tag length) + * 0x02 (integer tag) + * 0x85 0x00 0x00 0x00 0x01 0x01 (message id) + */ + BERInteger i = new BERInteger(m_msgid); + BERTag element = new BERTag(BERTag.APPLICATION|BERTag.CONSTRUCTED|16, + i, true); + return element; + } + + /** + * Retrieves the string representation of abandon request. + * @return string representation + */ + public String toString() { + return "JDAPAbandonRequest {msgid=" + m_msgid + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPAddRequest.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPAddRequest.java new file mode 100644 index 00000000000..e6302c6b704 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPAddRequest.java @@ -0,0 +1,141 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client.opers; + +import java.util.*; +import netscape.ldap.*; +import netscape.ldap.client.*; +import netscape.ldap.ber.stream.*; +import java.io.*; + +/** + * This class implements the add request. This object + * is sent to the ldap server. + *
+ * AddRequest ::= [APPLICATION 8] SEQUENCE {
+ *   entry LDAPDN,
+ *   attrs SEQUENCE OF SEQUENCE {
+ *     type AttributeType,
+ *     values SET OF AttributeValue
+ *   }
+ * }
+ * 
+ * + * @version 1.0 + * @see RFC1777 + */ +public class JDAPAddRequest extends JDAPBaseDNRequest + implements JDAPProtocolOp { + /** + * Internal variables + */ + protected String m_dn = null; + protected LDAPAttribute m_attrs[] = null; + + /** + * Constructs add request. + * @param dn distinguished name of adding entry + * @param attrs list of attribute associated with entry + */ + public JDAPAddRequest(String dn, LDAPAttribute attrs[]) { + m_dn = dn; + m_attrs = attrs; + } + + /** + * Retrieves protocol operation type. + * @return protcol type + */ + public int getType() { + return JDAPProtocolOp.ADD_REQUEST; + } + + /** + * Sets the base dn component. + * @param basedn base dn + */ + public void setBaseDN(String basedn) { + m_dn = basedn; + } + + /** + * Gets the base dn component. + * @return base dn + */ + public String getBaseDN() { + return m_dn; + } + + /** + * Gets the ber representation of add request. + * @return ber representation of request + */ + public BERElement getBERElement() { + /* Assumed that adding cn=patrick,o=ncware,c=ca with + * following attributes: + * cn: patrick + * title: programmer + * [*] umich-ldap-v3.3: + * 0x68 0x46 ([APPLICATION8]) + * 0x04 0x1a c n = p a t r i c k , 0x20 + * o = n c w a r e , 0x20 c = + * c a (entry - OctetString) + * 0x30 0x28 (SEQUENCE) + * 0x30 0x0f (SEQUENCE) + * 0x04 0x02 c n (attribute type - OctetString) + * 0x31 0x09 (SET OF) + * 0x04 0x07 p a t r i c k (attribute value - OctetString) + * 0x30 0x15 + * 0x04 0x05 t i t l e + * 0x31 0x0c (SET OF) + * 0x04 0x0a p r o g r a m m e r + */ + BERSequence seq = new BERSequence(); + seq.addElement(new BEROctetString (m_dn)); + BERSequence attrs_list = new BERSequence(); + for (int i = 0; i < m_attrs.length; i++) { + attrs_list.addElement(m_attrs[i].getBERElement()); + } + seq.addElement(attrs_list); + BERTag element = new BERTag(BERTag.APPLICATION|BERTag.CONSTRUCTED|8, + seq, true); + return element; + } + + /** + * Retrieves the string representation of add request parameters. + * @return string representation of add request parameters + */ + public String getParamString() { + String s = ""; + for (int i = 0; i < m_attrs.length; i++) { + if (i != 0) + s = s + " "; + s = s + m_attrs[i].toString(); + } + return "{entry='" + m_dn + "', attrs='" + s + "'}"; + } + + /** + * Retrieves the string representation of add request. + * @return string representation of add request + */ + public String toString() { + return "JDAPAddRequest " + getParamString(); + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPAddResponse.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPAddResponse.java new file mode 100644 index 00000000000..1be75284621 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPAddResponse.java @@ -0,0 +1,60 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client.opers; + +import java.util.*; +import netscape.ldap.client.*; +import netscape.ldap.ber.stream.*; +import java.io.*; +import java.net.*; + +/** + * This class implements the add response. This object + * is sent from the ldap server to the interface. + *
+ * AddResponse ::= [APPLICATION 9] LDAPResult
+ * 
+ * + * @version 1.0 + * @see RFC1777 + */ +public class JDAPAddResponse extends JDAPResult implements JDAPProtocolOp { + /** + * Constructs add response. + * @param element ber element of add response + */ + public JDAPAddResponse(BERElement element) throws IOException { + super(((BERTag)element).getValue()); + } + + /** + * Retrieves the protocol operation type. + * @return protocol type + */ + public int getType() { + return JDAPProtocolOp.ADD_RESPONSE; + } + + /** + * Retrieve the string representation. + * @return string representation + */ + public String toString() { + return "AddResponse " + super.getParamString(); + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPBaseDNRequest.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPBaseDNRequest.java new file mode 100644 index 00000000000..8190180fbf2 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPBaseDNRequest.java @@ -0,0 +1,46 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client.opers; + +import java.util.*; +import netscape.ldap.client.*; +import netscape.ldap.ber.stream.*; +import java.io.*; +import java.net.*; + +/** + * This is the base class for all the request that + * has a base dn component. The existence of this + * class is due to the JDAPReferralThread. + * + * @version 1.0 + */ +public abstract class JDAPBaseDNRequest { + + /** + * Sets the base dn component in the request. + * @param basedn base DN + */ + public abstract void setBaseDN(String basedn); + + /** + * Gets the base dn component in the request. + * @return base dn + */ + public abstract String getBaseDN(); +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPBindRequest.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPBindRequest.java new file mode 100644 index 00000000000..a4946053413 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPBindRequest.java @@ -0,0 +1,172 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client.opers; + +import java.util.*; +import netscape.ldap.client.*; +import netscape.ldap.ber.stream.*; +import java.io.*; +import java.net.*; + +/** + * This class implements the bind request. This object is + * sent to the ldap server. + *
+ * BindRequest ::= [APPLICATION 0] SEQUENCE {
+ *   version INTEGER(1..127) ,
+ *   name LDAPDN,
+ *   authentication CHOICE {
+ *     simple [0] OCTET STRING,
+ *     krbv42LDAP [1] OCTET STRING,
+ *     krbv42DSA [2] OCTET STRING
+ *   }
+ * }
+ * 
+ * + * Note that LDAPv3 bind reuqest is structured as follows: + *
+ * BindRequest ::= [APPLICATION 0] SEQUENCE {
+ *   version INTEGER (1..127)
+ *   name LDAPDN,
+ *   authentication AuthenticationChoice
+ * }
+ * AuthenticationChoice ::= CHOICE {
+ *   simple [0] OCTET STRING,
+ *          -- 1 and 2 reserved
+ *   sasl [3] SaslCredentials
+ * }
+ * SaslCredentials ::= SEQUENCE {
+ *   mechanism LDAPString,
+ *   credentials OCTET STRING
+ * }
+ * 
+ * + * @version 1.0 + */ +public class JDAPBindRequest implements JDAPProtocolOp { + /** + * Internal variables + */ + protected int m_version; + protected String m_name = null; + protected String m_password = null; + protected String m_mechanism = null; + protected byte m_credentials[] = null; + + /** + * Constructs anonymous or simple bind request. + * @param version version + * @param name distinguished name + * @param password password + */ + public JDAPBindRequest(int version, String name, String password) { + m_version = version; + m_name = name; + m_password = password; + } + + /** + * Constructs a LDAP v3.0 SaslCredentials bind request. + * @param version version + * @param name distinguished name + * @param mechanism mechanism (must not be null) + * @param credentials credientials + */ + public JDAPBindRequest(int version, String name, String mechanism, + byte credentials[]) { + m_version = version; + m_name = name; + m_mechanism = mechanism; + m_credentials = credentials; + } + + /** + * Retrieves the protocol operation type. + * @return protocol type + */ + public int getType() { + return JDAPProtocolOp.BIND_REQUEST; + } + + /** + * Retrieves the ber representation of the request. + * @return ber representation + */ + public BERElement getBERElement() { + /* anonymous bind + * [*] umich-ldap-v3.3: + * 0x60 0x07 (implicit [Application 0] Sequence) + * 0x02 0x01 0x02 (Integer) + * 0x04 0x00 (OctetString) + * 0x80 0x00 (implicit OctetString) + * [*] zoomit server v1.0: + * 0x60 0x0b + * 0x30 0x09 (sequece) + * 0x02 0x01 0x02 + * 0x04 0x00 + * 0xa0 0x02 (explicit tag) + * 0x04 0x00 + * simple bind with "cn=root,o=ncware,c=ca", "password" + * [*] umich-ldap-v3.3: + * 0x60 0x24 ([APPLICATION 0]) + * 0x02 0x01 0x02 (version - Integer) + * 0x04 0x15 c n = r o o t , o = n c w a r e , + * c = c a + * 0x80 0x08 p a s s w o r d + */ + BERSequence seq = new BERSequence(); + seq.addElement(new BERInteger(m_version)); + seq.addElement(new BEROctetString(m_name)); + BERTag auth = null; + if (m_mechanism == null) { + auth = new BERTag(BERTag.CONTEXT, new BEROctetString(m_password), true); + } else { + BERSequence sasl = new BERSequence(); + sasl.addElement(new BEROctetString(m_mechanism)); + if (m_credentials == null) { + sasl.addElement(new BEROctetString((byte[])null)); + } else { + sasl.addElement(new BEROctetString(m_credentials, 0, + m_credentials.length)); + } + auth = new BERTag(BERTag.SASLCONTEXT|3, /* SaslCredentials */ + sasl, true); + } + seq.addElement(auth); + BERTag element = new BERTag(BERTag.APPLICATION|BERTag.CONSTRUCTED|0, + seq, true); + return element; + } + + /** + * Retrieves the string representation of the request parameters. + * @return string representation parameters + */ + public String getParamString() { + return "{version=" + m_version + ", name=" + m_name + + ", authentication=" + m_password + "}"; + } + + /** + * Retrieves the string representation of the request. + * @return string representation + */ + public String toString() { + return "BindRequest " + getParamString(); + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPBindResponse.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPBindResponse.java new file mode 100644 index 00000000000..b300380e348 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPBindResponse.java @@ -0,0 +1,91 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client.opers; + +import java.util.*; +import netscape.ldap.client.*; +import netscape.ldap.ber.stream.*; +import java.io.*; +import java.net.*; + +/** + * This class implements the bind response. This object + * is sent from the ldap server to the interface. + *
+ * BindResponse = [APPLICATION 1] LDAPResult
+ * 
+ * + * Note that LDAPv3.0 Bind Response is structured as follows: + *
+ * BindResponse ::= [APPLICATION 1] SEQUENCE {
+ *   COMPONENTS OF LDAPResult,
+ *   serverCreds [7] SaslCredentials OPTIONAL
+ * }
+ * 
+ * + */ +public class JDAPBindResponse extends JDAPResult implements JDAPProtocolOp { + /** + * Internal variables + */ + protected String m_credentials = null; + + /** + * Constructs bind response. + * @param element ber element of bind response + */ + public JDAPBindResponse(BERElement element) throws IOException { + super(((BERTag)element).getValue()); + /* LDAPv3 Sasl Credentials support */ + BERSequence s = (BERSequence)((BERTag)element).getValue(); + if (s.size() <= 3) + return; + BERElement e = s.elementAt(3); + if (e.getType() == BERElement.TAG) { + BEROctetString str = (BEROctetString)((BERTag)e).getValue(); + try{ + m_credentials = new String(str.getValue(),"UTF8"); + } catch(Throwable x) + {} + } + } + + /** + * Retrieves Sasl Credentials. LDAPv3 support. + * @return credentials + */ + public String getCredentials() { + return m_credentials; + } + + /** + * Retrieves the protocol operation type. + * @return protocol type + */ + public int getType() { + return JDAPProtocolOp.BIND_RESPONSE; + } + + /** + * Retrieve the string representation. + * @return string representation + */ + public String toString() { + return "JDAPBindResponse " + super.getParamString(); + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPCompareRequest.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPCompareRequest.java new file mode 100644 index 00000000000..1689162c8fd --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPCompareRequest.java @@ -0,0 +1,101 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client.opers; + +import java.util.*; +import netscape.ldap.client.*; +import netscape.ldap.ber.stream.*; +import java.io.*; +import java.net.*; + +/** + * This class implements the compare request. This object + * is sent to the ldap server. + *
+ *   CompareRequest ::= [APPLICATION 14] SEQUENCE {
+ *     entry LDAPDN,
+ *     ava AttributeValueAssertion
+ *   }
+ * 
+ * + * @version 1.0 + */ +public class JDAPCompareRequest extends JDAPBaseDNRequest + implements JDAPProtocolOp { + /** + * Internal variables + */ + protected String m_dn = null; + protected JDAPAVA m_ava = null; + + /** + * Constructs the compare request. + * @param dn distinguished name of the entry to be compared + * @param ava attribut value assertion + */ + public JDAPCompareRequest(String dn, JDAPAVA ava) { + m_dn = dn; + m_ava = ava; + } + + /** + * Retrieves the protocol operation type. + * @return operation type + */ + public int getType() { + return JDAPProtocolOp.COMPARE_REQUEST; + } + + /** + * Sets the base dn. + * @param basedn base dn + */ + public void setBaseDN(String basedn) { + m_dn = basedn; + } + + /** + * Gets the base dn. + * @return base dn + */ + public String getBaseDN() { + return m_dn; + } + + /** + * Retrieves the ber representation of the request. + * @return ber request + */ + public BERElement getBERElement() { + BERSequence seq = new BERSequence(); + seq.addElement(new BEROctetString(m_dn)); + seq.addElement(m_ava.getBERElement()); + BERTag element = new BERTag(BERTag.APPLICATION|BERTag.CONSTRUCTED|14, + seq, true); + return element; + } + + /** + * Retrieves the string representation of the request. + * @return string representation + */ + public String toString() { + return "JDAPCompareRequest {entry=" + m_dn + ", ava=" + m_ava.toString() + + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPCompareResponse.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPCompareResponse.java new file mode 100644 index 00000000000..ddf9029bd21 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPCompareResponse.java @@ -0,0 +1,59 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client.opers; + +import java.util.*; +import netscape.ldap.client.*; +import netscape.ldap.ber.stream.*; +import java.io.*; +import java.net.*; + +/** + * This class implements the compare response. This object + * is sent from the ldap server to the interface. + *
+ * CompareResponse ::= [APPLICATION 15] LDAPResult
+ * 
+ * + * @version 1.0 + */ +public class JDAPCompareResponse extends JDAPResult implements JDAPProtocolOp { + /** + * Constructs compare response. + * @param element ber element of delete response + */ + public JDAPCompareResponse(BERElement element) throws IOException { + super(((BERTag)element).getValue()); + } + + /** + * Retrieves the protocol operation type. + * @return protocol type + */ + public int getType() { + return JDAPProtocolOp.COMPARE_RESPONSE; + } + + /** + * Retrieve the string representation. + * @return string representation + */ + public String toString() { + return "CompareResponse " + super.getParamString(); + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPDeleteRequest.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPDeleteRequest.java new file mode 100644 index 00000000000..0acea82c089 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPDeleteRequest.java @@ -0,0 +1,97 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client.opers; + +import java.util.*; +import netscape.ldap.client.*; +import netscape.ldap.ber.stream.*; +import java.io.*; +import java.net.*; + +/** + * This class implements the delete request. This object + * is sent to the ldap server. + *
+ * DelRequest ::= [APPLICATION 10] LDAPDN
+ * 
+ * + * @version 1.0 + */ +public class JDAPDeleteRequest extends JDAPBaseDNRequest + implements JDAPProtocolOp { + /** + * Internal variables + */ + protected String m_dn = null; + + /** + * Constructs the delete request. + * @param dn Distinguished name to delete + */ + public JDAPDeleteRequest(String dn) { + m_dn = dn; + } + + /** + * Retrieves the protocol operation type. + * @return operation type + */ + public int getType() { + return JDAPProtocolOp.DEL_REQUEST; + } + + /** + * Sets the base dn. + * @param basedn base dn + */ + public void setBaseDN(String basedn) { + m_dn = basedn; + } + + /** + * Gets the base dn. + * @return base dn + */ + public String getBaseDN() { + return m_dn; + } + + /** + * Gets the ber representation of the delete request. + * @return ber representation + */ + public BERElement getBERElement() { + /* Assumed that deleteing "cn=patrick,o=ncware,c=ca" + * [*] umich-ldap-v3.3 + * 0x4a 0x18 (implicit OctetString) + * c n = p a t r i c k , o = n c w a r e , c = c a + */ + BEROctetString s = new BEROctetString(m_dn); + BERTag element = new BERTag(BERTag.APPLICATION|10, + s, true); + return element; + } + + /** + * Retrieves the string representation of the delete request. + * @return string representation + */ + public String toString() { + return "JDAPDeleteRequest {entry=" + m_dn + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPDeleteResponse.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPDeleteResponse.java new file mode 100644 index 00000000000..deb7129fe8b --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPDeleteResponse.java @@ -0,0 +1,59 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client.opers; + +import java.util.*; +import netscape.ldap.client.*; +import netscape.ldap.ber.stream.*; +import java.io.*; +import java.net.*; + +/** + * This class implements the delete response. This object + * is sent from the ldap server to the interface. + *
+ * DeleteResponse ::= [APPLICATION 11] LDAPResult
+ * 
+ * + * @version 1.0 + */ +public class JDAPDeleteResponse extends JDAPResult implements JDAPProtocolOp { + /** + * Constructs delete response. + * @param element ber element of delete response + */ + public JDAPDeleteResponse(BERElement element) throws IOException { + super(((BERTag)element).getValue()); + } + + /** + * Retrieves the protocol operation type. + * @return protocol type + */ + public int getType() { + return JDAPProtocolOp.DEL_RESPONSE; + } + + /** + * Retrieve the string representation. + * @return string representation + */ + public String toString() { + return "DeleteResponse " + super.getParamString(); + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPExtendedRequest.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPExtendedRequest.java new file mode 100644 index 00000000000..02e7467f618 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPExtendedRequest.java @@ -0,0 +1,101 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client.opers; + +import java.util.*; +import netscape.ldap.client.*; +import netscape.ldap.ber.stream.*; +import java.io.*; + +/** + * This class implements the ExtendedRequest request. This object + * is sent to the ldap server and is a v3 request. + *
+ * ExtendedRequest ::= [APPLICATION 23] SEQUENCE {
+ *   requestName  [0] LDAPOID,
+ *   requestValue [1] OCTET STRING OPTIONAL
+ * }
+ * 
+ * + * @version 1.0 + * @see RFC1777 + */ +public class JDAPExtendedRequest implements JDAPProtocolOp { + /** + * Internal variables + */ + protected String m_oid = null; + protected byte m_value[] = null; + + /** + * Constructs extended request. + * @param oid object identifier + * @param value request value + */ + public JDAPExtendedRequest(String oid, byte value[]) { + m_oid = oid; + m_value = value; + } + + /** + * Retrieves protocol operation type. + * @return protcol type + */ + public int getType() { + return JDAPProtocolOp.EXTENDED_REQUEST; + } + + /** + * Gets the ber representation of extended request. + * @return ber representation of request + */ + public BERElement getBERElement() { + BERSequence seq = new BERSequence(); + seq.addElement(new BERTag(BERTag.APPLICATION|0, + new BEROctetString (m_oid), true)); + if (m_value != null) { + seq.addElement(new BERTag(BERTag.APPLICATION|1, + new BEROctetString (m_value, 0, m_value.length), true)); + } + BERTag element = new BERTag(BERTag.APPLICATION|BERTag.CONSTRUCTED|23, + seq, true); + return element; + } + + /** + * Retrieves the string representation of add request parameters. + * @return string representation of add request parameters + */ + public String getParamString() { + String s = ""; + if (m_value != null) { + try{ + s = new String(m_value, "UTF8"); + } catch(Throwable x) {} + } + return "{OID='" + m_oid + "', value='" + s + "'}"; + } + + /** + * Retrieves the string representation of add request. + * @return string representation of add request + */ + public String toString() { + return "JDAPExtendedRequest " + getParamString(); + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPExtendedResponse.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPExtendedResponse.java new file mode 100644 index 00000000000..6a3e187ed61 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPExtendedResponse.java @@ -0,0 +1,112 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client.opers; + +import java.util.*; +import netscape.ldap.client.*; +import netscape.ldap.ber.stream.*; +import java.io.*; +import java.net.*; + +/** + * This class implements the extended response. This object + * is sent from the ldap server to the interface and is + * a v3 response. + *
+ * ExtendedResponse :: [APPLICATION 23] SEQUENCE {
+ *   COMPONENTS OF LDAPResult,
+ *   responseName [10] LDAPOID OPTIONAL,
+ *   response     [11] OCTET STRING OPTIONAL
+ * }
+ * 
+ * + * @version 1.0 + * @see RFC1777 + */ +public class JDAPExtendedResponse extends JDAPResult + implements JDAPProtocolOp { + + /** + * Internal variables + */ + protected String m_oid = null; + protected byte[] m_value = null; + + /** + * Constructs extended response. + * @param element ber element of add response + */ + public JDAPExtendedResponse(BERElement element) throws IOException { + super(((BERTag)element).getValue()); + BERSequence seq = (BERSequence)((BERTag)element).getValue(); + for (int i = 0; i < seq.size(); i++) { + try { + BERElement el = seq.elementAt(i); + if (el.getType() != BERElement.TAG) + continue; + BERTag t = (BERTag)el; + switch (t.getTag()&0x0f) { + case 10: + BEROctetString oid = (BEROctetString)t.getValue(); + try{ + m_oid = new String(oid.getValue(), "UTF8"); + } catch(Throwable x) + {} + break; + case 11: + BEROctetString value = (BEROctetString)t.getValue(); + m_value = value.getValue(); + break; + } + } catch (ClassCastException e) { + } + } + } + + /** + * Retrieves the protocol operation type. + * @return protocol type + */ + public int getType() { + return JDAPProtocolOp.EXTENDED_RESPONSE; + } + + /** + * Retrieves the results of the extended operation. + * @return extended operation results as byte array + */ + public byte[] getValue() { + return m_value; + } + + /** + * Retrieves the oid of the extended operation. + * @return extended operation oid. + */ + public String getID() { + return m_oid; + } + + /** + * Retrieve the string representation. + * @return string representation + */ + public String toString() { + return "ExtendedResponse " + super.getParamString(); + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPModifyRDNRequest.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPModifyRDNRequest.java new file mode 100644 index 00000000000..4d945da6a1d --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPModifyRDNRequest.java @@ -0,0 +1,138 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client.opers; + +import java.util.*; +import netscape.ldap.client.*; +import netscape.ldap.ber.stream.*; +import java.io.*; +import java.net.*; + +/** + * This class implements the modify rdn request. This + * object is sent to the ldap server. + *
+ * ModifyRDNRequest ::= [APPLICATION 12] SEQUENCE {
+ *   entry LDAPDN,
+ *   newrdn RelativeLDAPDN,
+ *   deleteoldrdn BOOLEAN
+ * }
+ * 
+ * + * Note that LDAPv3 rename this object to JDAPModifyDNRequest + * and has the following defintion: + *
+ * ModifyDNRequest ::= [APPLICATION 12] SEQUENCE {
+ *   entry LDAPDN,
+ *   newrdn RelativeLDAPDN,
+ *   newSuperior [0] LDAPDN OPTIONAL
+ *   deleteoldrdn BOOLEAN,
+ * }
+ * 
+ * + * @version 1.0 + */ +public class JDAPModifyRDNRequest extends JDAPBaseDNRequest + implements JDAPProtocolOp { + /** + * Internal variables + */ + protected String m_old_dn = null; + protected String m_new_rdn = null; + protected boolean m_delete_old_dn; + protected String m_new_superior; + + /** + * Constructs modify RDN request. + * @param old_dn old distinguished name + * @param new_dn new distinguished name + * @param delete_old_dn delete the old distinguished name + */ + public JDAPModifyRDNRequest(String old_dn, String new_rdn, + boolean delete_old_dn) { + m_old_dn = old_dn; + m_new_rdn = new_rdn; + m_delete_old_dn = delete_old_dn; + m_new_superior = null; + } + + /** + * Constructs modify DN request. + * @param old_dn old distinguished name + * @param new_dn new distinguished name + * @param delete_old_dn delete the old distinguished name + * @param new_superior parent dn + */ + public JDAPModifyRDNRequest(String old_dn, String new_rdn, + boolean delete_old_dn, String new_superior) { + m_old_dn = old_dn; + m_new_rdn = new_rdn; + m_delete_old_dn = delete_old_dn; + m_new_superior = new_superior; + } + + /** + * Retrieves the protocol operation type. + * @return protocol type + */ + public int getType() { + return JDAPProtocolOp.MODIFY_RDN_REQUEST; + } + + /** + * Sets the base dn. + * @param basedn base dn + */ + public void setBaseDN(String basedn) { + m_old_dn = basedn; + } + + /** + * Gets the base dn component. + * @return base dn + */ + public String getBaseDN() { + return m_old_dn; + } + + /** + * Gets the ber representation of the request. + * @return ber representation + */ + public BERElement getBERElement() { + BERSequence seq = new BERSequence(); + seq.addElement(new BEROctetString(m_old_dn)); + seq.addElement(new BEROctetString(m_new_rdn)); + /* LDAPv3 new parent dn feature support */ + if (m_new_superior != null) + seq.addElement(new BEROctetString(m_new_superior)); + seq.addElement(new BERBoolean(m_delete_old_dn)); + BERTag element = new BERTag(BERTag.APPLICATION|BERTag.CONSTRUCTED|12, + seq, true); + return element; + } + + /** + * Gets the string representation of the request. + * @return string representation + */ + public String toString() { + return "ModifyRDNRequest {entry=" + m_old_dn + ", newrdn=" + + m_new_rdn + ", deleteoldrdn=" + m_delete_old_dn + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPModifyRDNResponse.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPModifyRDNResponse.java new file mode 100644 index 00000000000..976b84729d4 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPModifyRDNResponse.java @@ -0,0 +1,61 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client.opers; + +import java.util.*; +import netscape.ldap.client.*; +import netscape.ldap.ber.stream.*; +import java.io.*; +import java.net.*; + +/** + * This class implements the modifyRDN response. This object + * is sent from the ldap server to the interface. + *
+ * ModifyRDNResponse ::= [APPLICATION 13] LDAPResult
+ * 
+ * + * @version 1.0 + */ +public class JDAPModifyRDNResponse extends JDAPResult + implements JDAPProtocolOp { + + /** + * Constructs modifyRDN response. + * @param element ber element of modifyRDN response + */ + public JDAPModifyRDNResponse(BERElement element) throws IOException { + super(((BERTag)element).getValue()); + } + + /** + * Retrieves the protocol operation type. + * @return protocol type + */ + public int getType() { + return JDAPProtocolOp.MODIFY_RDN_RESPONSE; + } + + /** + * Retrieve the string representation. + * @return string representation + */ + public String toString() { + return "ModifyRDNResponse " + super.getParamString(); + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPModifyRequest.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPModifyRequest.java new file mode 100644 index 00000000000..1aef6de9764 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPModifyRequest.java @@ -0,0 +1,120 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client.opers; + +import java.util.*; +import netscape.ldap.*; +import netscape.ldap.client.*; +import netscape.ldap.ber.stream.*; +import java.io.*; +import java.net.*; + +/** + * This class implements the modify request. + *
+ *   ModifyRequest ::= [APPLICATION 6] SEQUENCE {
+ *     object LDAPDN,
+ *     modification SEQUENCE OF SEQUENCE {
+ *       operation ENUMERATED {
+ *         add (0),
+ *         delete (1),
+ *         replace (2)
+ *       },
+ *       modification SEQUENCE {
+ *         type AttributeType,
+ *         values SET OF AttributeValue
+ *       }
+ *     }
+ *   }
+ * 
+ * + * @version 1.0 + */ +public class JDAPModifyRequest extends JDAPBaseDNRequest + implements JDAPProtocolOp { + /** + * Internal variables + */ + protected String m_dn = null; + protected LDAPModification m_mod[] = null; + + /** + * Constructs the modify request + * @param dn distinguished name of modifying + * @param mod list of modifications + */ + public JDAPModifyRequest(String dn, LDAPModification mod[]) { + m_dn = dn; + m_mod = mod; + } + + /** + * Retrieves protocol operation type. + * @return protocol type + */ + public int getType() { + return JDAPProtocolOp.MODIFY_REQUEST; + } + + /** + * Sets the base dn component. + * @param basedn base dn + */ + public void setBaseDN(String basedn) { + m_dn = basedn; + } + + /** + * Gets the base dn component. + * @return base dn + */ + public String getBaseDN() { + return m_dn; + } + + /** + * Gets the ber representation of modify request. + * @return ber representation of modify request + */ + public BERElement getBERElement() { + BERSequence seq = new BERSequence(); + seq.addElement(new BEROctetString(m_dn)); + BERSequence mod_list = new BERSequence(); + for (int i = 0; i < m_mod.length; i++) { + mod_list.addElement(m_mod[i].getBERElement()); + } + seq.addElement(mod_list); + BERTag element = new BERTag(BERTag.APPLICATION|BERTag.CONSTRUCTED|6, + seq, true); + return element; + } + + /** + * Retrieves string representation of modify request. + * @return string representation of request + */ + public String toString() { + String s = null; + for (int i = 0; i < m_mod.length; i++) { + if (i != 0) + s = s + "+"; + s = s + m_mod[i].toString(); + } + return "ModifyRequest {object=" + m_dn + ", modification=" + s + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPModifyResponse.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPModifyResponse.java new file mode 100644 index 00000000000..d28fb87f837 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPModifyResponse.java @@ -0,0 +1,60 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client.opers; + +import java.util.*; +import netscape.ldap.client.*; +import netscape.ldap.ber.stream.*; +import java.io.*; +import java.net.*; + +/** + * This class implements the modify response. This object + * is sent from the ldap server to the interface. + *
+ * ModifyResponse ::= [APPLICATION 7] LDAPResult
+ * 
+ * + * @version 1.0 + * @see RFC1777 + */ +public class JDAPModifyResponse extends JDAPResult implements JDAPProtocolOp { + /** + * Constructs modify response. + * @param element ber element of bind response + */ + public JDAPModifyResponse(BERElement element) throws IOException { + super(((BERTag)element).getValue()); + } + + /** + * Retrieves the protocol operation type. + * @return protocol type + */ + public int getType() { + return JDAPProtocolOp.MODIFY_RESPONSE; + } + + /** + * Retrieve the string representation. + * @return string representation + */ + public String toString() { + return "ModifyResponse " + super.getParamString(); + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPProtocolOp.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPProtocolOp.java new file mode 100644 index 00000000000..73e510c2944 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPProtocolOp.java @@ -0,0 +1,75 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client.opers; + +import java.util.*; +import netscape.ldap.ber.stream.*; +import java.io.*; +import java.net.*; + +/** + * This is the base interface for all protocol operation + * that is embedded in a JDAPMessage (LDAP Message in RCF1777). + * Each protocol operation must implement this interface. + * + * @version 1.0 + * @see RFC1777 + */ +public interface JDAPProtocolOp { + /** + * Protocol operation types + */ + public final static int BIND_REQUEST = 0; + public final static int BIND_RESPONSE = 1; + public final static int UNBIND_REQUEST = 2; + public final static int SEARCH_REQUEST = 3; + public final static int SEARCH_RESPONSE = 4; + public final static int SEARCH_RESULT = 5; + public final static int MODIFY_REQUEST = 6; + public final static int MODIFY_RESPONSE = 7; + public final static int ADD_REQUEST = 8; + public final static int ADD_RESPONSE = 9; + public final static int DEL_REQUEST = 10; + public final static int DEL_RESPONSE = 11; + public final static int MODIFY_RDN_REQUEST = 12; + public final static int MODIFY_RDN_RESPONSE = 13; + public final static int COMPARE_REQUEST = 14; + public final static int COMPARE_RESPONSE = 15; + public final static int ABANDON_REQUEST = 16; + public final static int SEARCH_RESULT_REFERENCE = 19; + public final static int EXTENDED_REQUEST = 23; + public final static int EXTENDED_RESPONSE = 24; + + /** + * Retrieves the protocol operation type. + * @return protocol type + */ + public int getType(); + + /** + * Retrieves the ber representation of the operation. + * @return ber representation + */ + public BERElement getBERElement(); + + /** + * Retrieves the string representation of the operation. + * @return string representation + */ + public String toString(); +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPResult.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPResult.java new file mode 100644 index 00000000000..b54f9b3cf72 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPResult.java @@ -0,0 +1,253 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client.opers; + +import java.util.*; +import netscape.ldap.ber.stream.*; +import java.io.*; +import java.net.*; + +/** + * This class implements the ldap result where stores + * the request status. It is the base class for all + * the response except search response. This object is + * sent from the server to the client interface. + *
+ * LDAPResult ::= SEQUENCE {
+ *   resultCode ENUMERATED {
+ *     success (0),
+ *     ...
+ *   },
+ *   matchedND LDAPDN,
+ *   errorMessage LDAPString
+ * }
+ * 
+ * + * Note that LDAPv3 supports referral within the LDAP + * Result. The added component is: + * + *
+ * LDAPResult ::= SEQUENCE {
+ *   ...
+ *   errorMessage LDAPString,
+ *   referral [3] Referral OPTIONAL
+ * }
+ * 
+ * + */ +public class JDAPResult { + /** + * Result code based on RFC1777 + */ + public final static int SUCCESS = 0; + public final static int OPERATION_ERROR = 1; + public final static int PROTOCOL_ERROR = 2; + public final static int TIME_LIMIT_EXCEEDED = 3; + public final static int SIZE_LIMIT_EXCEEDED = 4; + public final static int COMPARE_FALSE = 5; + public final static int COMPARE_TRUE = 6; + public final static int AUTH_METHOD_NOT_SUPPORTED = 7; + public final static int STRONG_AUTH_REQUIRED = 8; + /* Referrals Within the LDAPv2 Protocol */ + public final static int LDAP_PARTIAL_RESULTS = 9; + /* Added for LDAPv3 - BEGIN */ + public final static int REFERRAL = 10; + public final static int ADMIN_LIMIT_EXCEEDED = 11; + public final static int UNAVAILABLE_CRITICAL_EXTENSION = 12; + public final static int CONFIDENTIALITY_REQUIRED = 13; + public final static int SASL_BIND_IN_PROGRESS = 14; + /* Added for LDAPv3 - END */ + public final static int NO_SUCH_ATTRIBUTE = 16; + public final static int UNDEFINED_ATTRIBUTE_TYPE = 17; + public final static int INAPPROPRIATE_MATCHING = 18; + public final static int CONSTRAINT_VIOLATION = 19; + public final static int ATTRIBUTE_OR_VALUE_EXISTS = 20; + public final static int INVALID_ATTRIBUTE_SYNTAX = 21; + public final static int NO_SUCH_OBJECT = 32; + public final static int ALIAS_PROBLEM = 33; + public final static int INVALID_DN_SYNTAX = 34; + public final static int IS_LEAF = 35; + public final static int ALIAS_DEREFERENCING_PROBLEM = 36; + public final static int INAPPROPRIATE_AUTHENTICATION = 48; + public final static int INVALID_CREDENTIALS = 49; + public final static int INSUFFICIENT_ACCESS_RIGHTS = 50; + public final static int BUSY = 51; + public final static int UNAVAILABLE = 52; + public final static int UNWILLING_TO_PERFORM = 53; + public final static int LOOP_DETECT = 54; + public final static int NAMING_VIOLATION = 64; + public final static int OBJECT_CLASS_VIOLATION = 65; + public final static int NOT_ALLOWED_ON_NONLEAF = 66; + public final static int NOT_ALLOWED_ON_RDN = 67; + public final static int ENTRY_ALREADY_EXISTS = 68; + public final static int OBJECT_CLASS_MODS_PROHIBITED = 69; + public final static int AFFECTS_MULTIPLE_DSAS = 71; + public final static int OTHER = 80; + public final static int SERVER_DOWN = 81; + public final static int PARAM_ERROR = 89; + public final static int CONNECT_ERROR = 91; + public final static int LDAP_NOT_SUPPORTED = 92; + public final static int CONTROL_NOT_FOUND = 93; + public final static int NO_RESULTS_RETURNED = 94; + public final static int MORE_RESULTS_TO_RETURN = 95; + public final static int CLIENT_LOOP = 96; + public final static int REFERRAL_LIMIT_EXCEEDED = 97; + + /** + * Private variable + */ + protected BERElement m_element = null; + protected int m_result_code; + protected String m_matched_dn = null; + protected String m_error_message = null; + protected String m_referrals[] = null; + + /** + * Constructs ldap result. + * @param element ber element + */ + public JDAPResult(BERElement element) throws IOException { + /* Result from a successful bind request. + * [*] umich-ldap-v3.3 + * 0x0a 0x07 (implicit [APPLICATION 1] OctetString) + * 0x0a 0x01 0x00 (result code) + * 0x04 0x00 (matched dn) + * 0x04 0x00 (error message) + * Referrals in ldap-v2.0 + * [*] umich-ldap-v3.3 + * 0x65 0x2a + * 0x0a 0x01 0x09 + * 0x04 0x00 + * 0x04 0x23 R e f e r r a l : 0x0a + * l d a p : / / l d a p . + * i t d . u m i c h . e d u + */ + m_element = element; + BERSequence seq = (BERSequence)element; + /* + * Possible return from [x500.arc.nasa.gov]: + * SEQUENCE {SEQUENCE {Enumerated{2} ... }} + */ + BERElement e = seq.elementAt(0); + if (e.getType() == BERElement.SEQUENCE) + seq = (BERSequence)e; + m_result_code = ((BEREnumerated)seq.elementAt(0)).getValue(); + byte buf[] = null; + buf = ((BEROctetString)seq.elementAt(1)).getValue(); + if (buf == null) + m_matched_dn = null; + else { + try{ + m_matched_dn = new String(buf, "UTF8"); + } catch(Throwable x) + {} + } + buf = ((BEROctetString)seq.elementAt(2)).getValue(); + if (buf == null) + m_error_message = null; + else { + try { + m_error_message = new String(buf, "UTF8"); + } catch(Throwable x) + {} + } + /* 12/05/97 extract LDAPv3 referrals */ + if (seq.size() >= 4) { + BERTag t = (BERTag)seq.elementAt(3); + BERElement v = t.getValue(); + if (v.getType() == BERElement.INTEGER) { + /* MS - [CONTEXT-5] Integer {3} */ + /* TBD */ + + // else if this element is BERSequence which contains referral information + } else if (v instanceof BERSequence) { + /* Netscape */ + BERSequence rseq = (BERSequence)v; + if (rseq.size() > 0) { + m_referrals = new String[rseq.size()]; + for (int i = 0; i < rseq.size(); i++) { + try{ + m_referrals[i] = new + String(((BEROctetString)rseq.elementAt(i)).getValue(), "UTF8"); + } catch(Throwable x) + {} + } + } + } + } + } + + /** + * Gets the result code. + * @return result code + */ + public int getResultCode() { + return m_result_code; + } + + /** + * Gets the matched dn. + * @return matched dn + */ + public String getMatchedDN() { + return m_matched_dn; + } + + /** + * Gets the error message. + * @return error message + */ + public String getErrorMessage() { + return m_error_message; + } + + /** + * Retrieves referrals from the LDAP Result. + * @return list of referrals in URL format + */ + public String[] getReferrals() { + return m_referrals; + } + + /** + * Retrieves the ber representation of the result. + * @return ber representation of the result + */ + public BERElement getBERElement() { + return m_element; + } + + /** + * Retrieves string representation of the result. Usually, + * the inherited class calls this to retrieve the parameter + * string. + * @return string representation + */ + public String getParamString() { + return "{resultCode=" + m_result_code + ", matcheDN=" + + m_matched_dn + ", errorMessage=" + m_error_message + "}"; + } + + /** + * Retrieves string representation of the result. + * @return string representation + */ + public String toString() { + return "JDAPResult " + getParamString(); + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPSearchRequest.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPSearchRequest.java new file mode 100644 index 00000000000..77424919e21 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPSearchRequest.java @@ -0,0 +1,211 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client.opers; + +import java.util.*; +import netscape.ldap.client.*; +import netscape.ldap.ber.stream.*; +import java.io.*; +import java.net.*; + +/** + * This class implements the search request. This object is + * sent to the ldap server. + *
+ * SearchRequest ::= [APPLICATION 3] SEQUENCE {
+ *   baseObject LDAPDN,
+ *   scope ENUMERATED {
+ *     baseObject (0),
+ *     singleLevel (1),
+ *     wholeSubtree (2)
+ *   },
+ *   derefAliases ENUMERATED {
+ *     neverDerefAliases (0),
+ *     derefInSearching (1),
+ *     DerefFindingBaseObj (2),
+ *     DerefAlways (3)
+ *   },
+ *   sizeLimit INTEGER(0..maxInt),
+ *   timeLimit INTEGER(0..maxInt),
+ *   attrsOnly BOOLEAN,
+ *   filter Filter,
+ *   attributes SEQUENCE OF AttributeType
+ * }
+ * 
+ * + * @version 1.0 + */ +public class JDAPSearchRequest extends JDAPBaseDNRequest + implements JDAPProtocolOp { + /** + * search scope + */ + public final static int BASE_OBJECT = 0; + public final static int SINGLE_LEVEL = 1; + public final static int WHOLE_SUBTREE = 2; + /** + * alias dereference + */ + public final static int NEVER_DEREF_ALIASES = 0; + public final static int DEREF_IN_SEARCHING = 1; + public final static int DEREF_FINDING_BASE_OBJ = 2; + public final static int DEREF_ALWAYS = 3; + + /** + * Private variables + */ + protected String m_base_dn = null; + protected int m_scope; + protected int m_deref; + protected int m_size_limit; + protected int m_time_limit; + protected boolean m_attrs_only; + protected String m_filter = null; + protected String m_attrs[] = null; + + /** + * Constructs search request. + * @param base_dn base object entry relative to the search + * @param scope scope of the search + * @param deref how alias objects should be handled + * @param size_limit maximum number of entries + * @param time_limit maximum time (in time) allowed + * @param attrs_only should return type only + * @param filter string filter based on RFC1558 + * @param attrs list of attribute types + */ + public JDAPSearchRequest(String base_dn, int scope, int deref, + int size_limit, int time_limit, boolean attrs_only, + String filter, String attrs[]) { + m_base_dn = base_dn; + m_scope = scope; + m_deref = deref; + m_size_limit = size_limit; + m_time_limit = time_limit; + m_attrs_only = attrs_only; + m_filter = filter; + m_attrs = attrs; + } + + /** + * Retrieves the protocol operation type. + * @return operation type + */ + public int getType() { + return JDAPProtocolOp.SEARCH_REQUEST; + } + + /** + * Sets the base dn component. + * @param basedn base dn + */ + public void setBaseDN(String basedn) { + m_base_dn = basedn; + } + + /** + * Gets the base dn component. + * @return base dn + */ + public String getBaseDN() { + return m_base_dn; + } + + /** + * Gets the ber representation of search request. + * @return ber representation of request. + */ + public BERElement getBERElement() { + /* Assumed that searching with the following criteria: + * base object = "c=ca" + * filter = FilterPresent(objectClass) + * [*] zoomit server v1.0 (search on c=ca) + * 0x63 0x81 0x8d ([APPLICATION 3]) + * 0x30 0x81 0x8a 0x04 0x00 (seq of) + * 0x0a 0x01 0x02 + * 0x0a 0x01 0x00 + * 0x02 0x01 0x65 + * 0x02 0x01 0x1e + * 0x01 0x01 0x00 + * 0xa0 0x3b + * 0x30 0x39 0xa5 0x0d + * 0x30 0x0b 0x04 0x07 P A G E _ D N + * 0x04 0x00 + * 0xa3 0x0e + * 0x30 0x0c 0x04 0x08 P A G E _ K E Y + * 0x04 0x00 0xa3 0x18 + * 0x30 0x16 0x04 0x0e z c A n y A t t r i b u t e + * 0x04 0x04 c = c a + * 0x30 0x3a 0x04 0x0b O b j e c t C l a s s + * 0x04 0x11 a l i a s e d O b j e c t N a m e + * 0x04 0x07 d s e T y p e + * 0x04 0x0f t e l e p h o n e N u m b e r + * [*] umich-ldap-v3.3: + * 0x63 0x24 ([APPLICATION 3]) + * 0x04 0x04 c = c a (base object - OctetString) + * 0x0a 0x01 0x00 (scope - Enumerated) + * 0x0a 0x01 0x00 (derefAlias - Enumerated) + * 0x02 0x01 0x00 (size limit - Integer) + * 0x02 0x01 0x00 (time limit - Integer) + * 0x01 0x01 0x00 (attr only - Boolean) + * 0x87 0x0b o b j e c t C l a s s (filter) + * 0x30 0x00 (attrs - Sequence of OctetString) + */ + BERSequence seq = new BERSequence(); + seq.addElement(new BEROctetString(m_base_dn)); + seq.addElement(new BEREnumerated(m_scope)); + seq.addElement(new BEREnumerated(m_deref)); + seq.addElement(new BERInteger(m_size_limit)); + seq.addElement(new BERInteger(m_time_limit)); + seq.addElement(new BERBoolean(m_attrs_only)); + JDAPFilter filter = JDAPFilter.getFilter(m_filter); + if (filter == null) + return null; + seq.addElement(filter.getBERElement()); + BERSequence attr_type_list = new BERSequence(); + if (m_attrs != null) { + for (int i = 0; i < m_attrs.length; i++) { + attr_type_list.addElement(new BEROctetString(m_attrs[i])); + } + } + seq.addElement(attr_type_list); + BERTag element = new BERTag(BERTag.APPLICATION|BERTag.CONSTRUCTED|3, + seq, true); + return element; + } + + /** + * Retrieves the string representation of the request. + * @return string representation + */ + public String toString() { + String s = null; + if (m_attrs != null) { + for (int i = 0; i < m_attrs.length; i++) { + if (i != 0) + s = s + "+"; + s = s + m_attrs[i]; + } + } + return "JDAPSearchRequest {baseObject=" + m_base_dn + ", scope=" + + m_scope + ", derefAliases=" + m_deref + ",sizeLimit=" + + m_size_limit + ", timeLimit=" + m_time_limit + ", attrsOnly=" + + m_attrs_only + ", filter=" + m_filter + ", attributes=" + + s + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPSearchResponse.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPSearchResponse.java new file mode 100644 index 00000000000..a2a3b5f5fcd --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPSearchResponse.java @@ -0,0 +1,139 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client.opers; + +import java.util.*; +import netscape.ldap.*; +import netscape.ldap.client.*; +import netscape.ldap.ber.stream.*; +import java.io.*; +import java.net.*; + +/** + * This class implements the search response. This object + * is sent from the ldap server to the interface. + *
+ * entry [APPLICATION 4] SEQUENCE {
+ *   objectName LDAPDN,
+ *   attributes SEQUENCE OF SEQUENCE {
+ *     AttributeType,
+ *     SET OF AttributeValue
+ *   }
+ * }
+ * 
+ * + * Note that the following is the LDAPv3 definition: + *
+ * SearchResultEntry ::= [APPLICATION 4] SEQUENCE {
+ *   objectName LDAPDN,
+ *   attributes PartialAttributeList
+ * }
+ * PartialAttributeList ::= SEQUENCE OF SEQUENCE {
+ *   type AttributeDescription,
+ *   vals SET OF AttributeValue
+ * }
+ * 
+ * + * @version 1.0 + */ +public class JDAPSearchResponse implements JDAPProtocolOp { + /** + * Internal variables + */ + protected String m_object_name = null; + protected BERElement m_element = null; + protected LDAPAttribute m_attributes[] = null; + + /** + * Constructs search response. + * @param element ber element of search response + */ + public JDAPSearchResponse(BERElement element) throws IOException { + m_element = element; + + BERTag tag = (BERTag)element; + BERSequence seq = (BERSequence)tag.getValue(); + BEROctetString name = (BEROctetString)seq.elementAt(0); + byte buf[] = null; + buf = name.getValue(); + if (buf == null) + m_object_name = null; + else { + try{ + m_object_name = new String(buf, "UTF8"); + } catch(Throwable x) + {} + } + BERSequence attrs = (BERSequence)seq.elementAt(1); + if (attrs.size() > 0) { + m_attributes = new LDAPAttribute[attrs.size()]; + for (int i = 0; i < attrs.size(); i++) { + m_attributes[i] = new LDAPAttribute(attrs.elementAt(i)); + } + } + } + + /** + * Retrieves ber representation of the result. + * @return ber representation + */ + public BERElement getBERElement() { + return m_element; + } + + /** + * Retrieves object name + * @return object name + */ + public String getObjectName() { + return m_object_name; + } + + /** + * Retrieves attributes + * @return attributes + */ + public LDAPAttribute[] getAttributes() { + return m_attributes; + } + + /** + * Retrieves the protocol operation type. + * @return protocol type + */ + public int getType() { + return JDAPProtocolOp.SEARCH_RESPONSE; + } + + /** + * Retrieve the string representation. + * @return string representation + */ + public String toString() { + String s = ""; + if (m_attributes != null) { + for (int i = 0; i < m_attributes.length; i++) { + if (i != 0) + s = s + ","; + s = s + m_attributes[i].toString(); + } + } + return "SearchResponse {entry='" + m_object_name + "', attributes='" + + s + "'}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPSearchResult.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPSearchResult.java new file mode 100644 index 00000000000..e318f9665cc --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPSearchResult.java @@ -0,0 +1,63 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client.opers; + +import java.util.*; +import netscape.ldap.client.*; +import netscape.ldap.ber.stream.*; +import java.io.*; +import java.net.*; + +/** + * This class implements the search result. This object + * is sent from the ldap server to the interface. Note + * that search response is separated into search response + * and search result. The search response contains the + * result from the server, while the research result indicates + * the end of the search response sequence. + *
+ * resultCode [APPLICATION 5] LDAPResult
+ * 
+ * + * @version 1.0 + */ +public class JDAPSearchResult extends JDAPResult implements JDAPProtocolOp { + /** + * Constructs search result. + * @param element ber element of search result + */ + public JDAPSearchResult(BERElement element) throws IOException { + super(((BERTag)element).getValue()); + } + + /** + * Retrieves the protocol operation type. + * @return protocol type + */ + public int getType() { + return JDAPProtocolOp.SEARCH_RESULT; + } + + /** + * Retrieve the string representation. + * @return string representation + */ + public String toString() { + return "SearchResult " + super.getParamString(); + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPSearchResultReference.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPSearchResultReference.java new file mode 100644 index 00000000000..6248298f496 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPSearchResultReference.java @@ -0,0 +1,96 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client.opers; + +import java.util.*; +import netscape.ldap.client.*; +import netscape.ldap.ber.stream.*; +import java.io.*; +import java.net.*; + +/** + * This class implements the search result reference. + *
+ * SearchResultReference :: [APPLICATION 19] SEQUENCE OF LDAPURL
+ * 
+ * + * @version 1.0 + * @see RFC1777 + */ +public class JDAPSearchResultReference implements JDAPProtocolOp { + + /** + * Internal variables + */ + protected String m_urls[] = null; + protected BERElement m_element = null; + + /** + * Constructs extended response. + * @param element ber element of add response + */ + public JDAPSearchResultReference(BERElement element) throws IOException { + m_element = element; + BERSequence seq = (BERSequence)((BERTag)element).getValue(); + if (seq.size() < 0) + return; + m_urls = new String[seq.size()]; + for (int i=0; i < seq.size(); i++) { + BEROctetString o = (BEROctetString)seq.elementAt(i); + m_urls[i] = new String(o.getValue(), "UTF8"); + } + } + + /** + * Retrieves the protocol operation type. + * @return protocol type + */ + public int getType() { + return JDAPProtocolOp.SEARCH_RESULT_REFERENCE; + } + + /** + * Retrieves the BER representation of this object. + */ + public BERElement getBERElement() { + return m_element; + } + + /** + * Retrieves a list of urls. + */ + public String[] getUrls() { + return m_urls; + } + + /** + * Retrieve the string representation. + * @return string representation + */ + public String toString() { + String urls = ""; + if (m_urls != null) { + for (int i = 0; i < m_urls.length; i++) { + if (i != 0) + urls += ","; + urls += m_urls[i]; + } + } + return "SearchResultReference " + urls; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPUnbindRequest.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPUnbindRequest.java new file mode 100644 index 00000000000..43ef5619bf8 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/client/opers/JDAPUnbindRequest.java @@ -0,0 +1,73 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.client.opers; + +import java.util.*; +import netscape.ldap.client.*; +import netscape.ldap.ber.stream.*; +import java.io.*; +import java.net.*; + +/** + * This class implements the unbind request and is a protocol operation. + * A protocol operation is embedded within JDAPMessage which is sent + * between client and server. This object is sent to the ldap server. + *
+ * UnbindRequest ::= [APPLICATION 2] NULL
+ * 
+ * + * @version 1.0 + */ +public class JDAPUnbindRequest implements JDAPProtocolOp { + /** + * Constructs bind request. + */ + public JDAPUnbindRequest() { + } + + /** + * Retrieves the protocol operation type. + * @return operation type + */ + public int getType() { + return JDAPProtocolOp.UNBIND_REQUEST; + } + + /** + * Gets the ber representation of the unbind rquest. + * @return ber representation + */ + public BERElement getBERElement() { + /* + * [*] umich-ldap-v3.3: + * 0x42 0x00 + * [*] umich-ldap-v3.0: + */ + BERNull n = new BERNull(); + BERTag element = new BERTag(BERTag.APPLICATION|2, n, true); + return element; + } + + /** + * Retrieves the string representation of unbind operation. + * @return string representation + */ + public String toString() { + return "JDAPUnbindRequest {}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/controls/LDAPEntryChangeControl.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/controls/LDAPEntryChangeControl.java new file mode 100644 index 00000000000..befc2b843fb --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/controls/LDAPEntryChangeControl.java @@ -0,0 +1,174 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.controls; + +import java.io.*; +import netscape.ldap.ber.stream.*; +import netscape.ldap.client.JDAPBERTagDecoder; +import netscape.ldap.*; + +/** + * Represents an LDAP v3 server control that specifies information + * about a change to an entry in the directory. (The OID for this + * control is 2.16.840.1.113730.3.4.7.) You need to use this control in + * conjunction with a "persistent search" control (represented + * by LDAPPersistentSearchControl object. + *

+ * + * To use persistent searching for change notification, you create a + * "persistent search" control that specifies the types of changes that + * you want to track. When an entry is changed, the server sends that + * entry back to your client and may include an "entry change notification" + * control that specifies additional information about the change. + *

+ * + * Typically, you use the getResponseControls method of + * the LDAPConnection object and the parseResponse + * method of the LDAPPersistSearchControl object to get + * an LDAPEntryChangeControl object. + *

+ * + * Once you retrieve an LDAPEntryChangeControl object from + * the server, you can get the following additional information about + * the change made to the entry: + *

+ * + *

    + *
  • The type of change made (add, modify, delete, or modify DN) + *
  • The change number identifying the record of the change in the + * change log (if the server supports change logs) + *
  • If the entry was renamed, the old DN of the entry + *
+ *

+ * + * @see netscape.ldap.controls.LDAPPersistSearchControl + * @see netscape.ldap.LDAPConnection#getResponseControls + */ + +public class LDAPEntryChangeControl extends LDAPControl { + + /** + * Constructs a new LDAPEntryChangeControl object. + * Call the parseResponse method of the + * LDAPPersistSearchControl object to retrieve the + * actual "entry change notification" control from the server. + * + * @see netscape.ldap.LDAPControl + * @see netscape.ldap.controls.LDAPPersistSearchControl + */ + public LDAPEntryChangeControl() + { + super(ENTRYCHANGED, false, null); + } + + /** + * Sets the change number (which identifies the record of the change + * in the server's change log) in this "entry change notification" + * control. + * @param num Change number that you want to set. + * @see netscape.ldap.controls.LDAPEntryChangeControl#getChangeNumber + */ + public void setChangeNumber(int num) { + m_changeNumber = num; + } + + /** + * Sets the change type (which identifies the type of change + * that occurred) in this "entry change notification" control. + * @param num Change type that you want to set. This can be one of + * the following values: + *

+ * + *

    + *
  • LDAPPersistSearchControl.ADD (a new entry was + * added to the directory) + *
  • LDAPPersistSearchControl.DELETE (an entry was + * removed from the directory) + *
  • LDAPPersistSearchControl.MODIFY (an entry was + * modified) + *
  • LDAPPersistSearchControl.MODDN (an entry was + * renamed) + *
+ *

+ * + * @see netscape.ldap.controls.LDAPEntryChangeControl#getChangeType + */ + public void setChangeType(int num) { + m_changeTypes = num; + } + + /** + * Sets the previous DN of the entry (if the entry was renamed) + * in the "entry change notification control". + * @param dn The previous distinguished name of the entry. + * @see netscape.ldap.controls.LDAPEntryChangeControl#getPreviousDN + */ + public void setPreviousDN(String dn) { + m_previousDN = dn; + } + + /** + * Gets the change number, which identifies the record of the change + * in the server's change log. + * @return Change number identifying the change made. + * @see netscape.ldap.controls.LDAPEntryChangeControl#setChangeNumber + */ + public int getChangeNumber() { + return m_changeNumber; + } + + /** + * Gets the change type, which identifies the type of change + * that occurred. + * @returns Change type identifying the type of change that + * occurred. This can be one of the following values: + *

+ * + *

    + *
  • LDAPPersistSearchControl.ADD (a new entry was + * added to the directory) + *
  • LDAPPersistSearchControl.DELETE (an entry was + * removed from the directory) + *
  • LDAPPersistSearchControl.MODIFY (an entry was + * modified) + *
  • LDAPPersistSearchControl.MODDN (an entry was + * renamed) + *
+ *

+ * + * @see netscape.ldap.controls.LDAPEntryChangeControl#setChangeType + */ + public int getChangeType() { + return m_changeTypes; + } + + /** + * Gets the previous DN of the entry (if the entry was renamed). + * @returns The previous distinguished name of the entry. + * @see netscape.ldap.controls.LDAPEntryChangeControl#setPreviousDN + */ + public String getPreviousDN() { + return m_previousDN; + } + + private int m_changeNumber = -1; + private int m_changeTypes = -1; + private String m_previousDN = null; + public final static String ENTRYCHANGED = "2.16.840.1.113730.3.4.7"; +} + diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/controls/LDAPPersistSearchControl.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/controls/LDAPPersistSearchControl.java new file mode 100644 index 00000000000..dd20e3ef83e --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/controls/LDAPPersistSearchControl.java @@ -0,0 +1,448 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.controls; + +import java.io.*; +import netscape.ldap.client.JDAPBERTagDecoder; +import netscape.ldap.LDAPControl; +import netscape.ldap.ber.stream.*; + +/** + * Represents an LDAP v3 server control that specifies a persistent + * search (an ongoing search operation), which allows your LDAP client + * to get notification of changes to the directory. (The OID for this + * control is 2.16.840.1.113730.3.4.3.) You can use this control in + * conjunction with an "entry change notification" control (represented + * by LDAPEntryChangeControl object. + *

+ * + * To use persistent searching for change notification, you create a + * "persistent search" control that specifies the types of changes that + * you want to track. You include the control in a search request. + * If an entry in the directory is changed, the server determines if + * the entry matches the search criteria in your request and if the + * change is the type of change that you are tracking. If both of + * these are true, the server sends the entry to your client. + *

+ * + * The server can also include an "entry change notification" control + * with the entry. (The OID for this control is 2.16.840.1.113730.3.4.7.) + * This control contains additional information about the + * change made to the entry, including the type of change made, + * the change number (which corresponds to an item in the server's + * change log, if the server supports a change log), and, if the + * entry was renamed, the old DN of the entry. + *

+ * + * When constructing an LDAPPersistSearchControl object, + * you can specify the following information: + *

+ * + *

    + *
  • the type of change you want to track (added, modified, deleted, + * or renamed entries) + *
  • a preference indicating whether or not you want the server to + * return all entries that initially matched the search criteria + * (rather than only the entries that change) + *
  • a preference indicating whether or not you want entry change + * notification controls included with every entry returned by the + * server + *
+ *

+ * + * For example: + *

+ * ...
+ * LDAPConnection ld = new LDAPConnection();
+ *
+ * try {
+ *     // Connect to server.
+ *     ld.connect( 3, hostname, portnumber, "", "" );
+ *
+ *     // Create a persistent search control.
+ *     int op = LDAPPersistSearchControl.ADD |
+ *         LDAPPersistSearchControl.MODIFY |
+ *         LDAPPersistSearchControl.DELETE |
+ *         LDAPPersistSearchControl.MODDN;
+ *     boolean changesOnly = true;
+ *     boolean returnControls = true;
+ *     boolean isCritical = true;
+ *     LDAPPersistSearchControl persistCtrl = new
+ *         LDAPPersistSearchControl( op, changesOnly,
+ *         returnControls, isCritical );
+ *
+ *     // Set the search constraints to use that control.
+ *     LDAPSearchConstraints cons = ld.getSearchConstraints();
+ *     cons.setBatchSize( 1 );
+ *     cons.setServerControls( persistCtrl );
+ *
+ *     // Start the persistent search.
+ *     LDAPSearchResults res = ld.search( "o=Airius.com",
+ *               LDAPv3.SCOPE_SUB, "(cn=Barbara*)", null, false, cons );
+ *
+ *     // Loop through the incoming results.
+ *     while ( res.hasMoreElements() ) {
+ *     ...
+ *     }
+ * ...
+ * }
+ * 
+ * + * @see netscape.ldap.LDAPControl + * @see netscape.ldap.controls.LDAPEntryChangeControl + */ + +public class LDAPPersistSearchControl extends LDAPControl { + + /** + * Default constructor + */ + public LDAPPersistSearchControl() + { + super(PERSISTENTSEARCH, true, null); + } + + /** + * Constructs an LDAPPersistSearchControl object + * that specifies a persistent search. + * + * @param changeTypes The change types to be monitored. You can perform + * a bitwise OR on any of the following values and specify the result as + * the change types: + *
    + *
  • LDAPPersistSearchControl.ADD (to track new entries + * added to the directory) + *
  • LDAPPersistSearchControl.DELETE (to track entries + * removed from the directory) + *
  • LDAPPersistSearchControl.MODIFY (to track entries + * that have been modified) + *
  • LDAPPersistSearchControl.MODDN (to track entries + * that have been renamed) + *
+ * @param changesOnly true if you do not want the server + * to return all existing entries in the directory that match the + * search criteria. (You just want the changed entries to be returned.) + * @param returnControls true you want the server to return + * entry change controls with each entry in the search results. + * @param isCritical true if this control is critical to + * the search operation (for example, if the server does not support + * this control, you may not want the server to perform the search + * at all.) + * @see netscape.ldap.LDAPControl + * @see netscape.ldap.controls.LDAPEntryChangeControl + */ + public LDAPPersistSearchControl(int changeTypes, boolean changesOnly, + boolean returnControls, boolean isCritical) { + super(PERSISTENTSEARCH, isCritical, null); + m_value = createPersistSearchSpecification(changeTypes, + changesOnly, returnControls); + } + + /** + * Gets the change types monitored by this control. + * @return Integer representing the change types that you want monitored. + * This value can be the bitwise OR of ADD, DELETE, MODIFY, + * and/or MODDN. If the change type is unknown, + * this method returns -1. + * @see netscape.ldap.controls.LDAPPersistSearchControl#setChangeTypes + */ + public int getChangeTypes() { + return m_changeTypes; + } + + /** + * Indicates whether you want the server to send any existing + * entries that already match the search criteria or only the + * entries that have changed. + * @return If true, the server returns only the + * entries that have changed. If false, the server + * also returns any existing entries that match the search criteria + * but have not changed. + * @see netscape.ldap.controls.LDAPPersistSearchControl#setChangesOnly + */ + public boolean getChangesOnly() { + return m_changesOnly; + } + + /** + * Indicates whether or not the server includes an "entry change + * notification" control with each entry it sends back to the client + * during the persistent search. + * @return true if the server includes "entry change + * notification" controls with the entries it sends during the + * persistent search. + * @see netscape.ldap.controls.LDAPEntryChangeControl + * @see netscape.ldap.controls.LDAPPersistSearchControl#setReturnControls + */ + public boolean getReturnControls() { + return m_returnECs; + } + + /** + * Sets the change types that you want monitored by this control. + * @param types Integer representing the change types that you want monitored. + * This value can be the bitwise OR of ADD, DELETE, MODIFY, + * and/or MODDN. + * @see netscape.ldap.controls.LDAPPersistSearchControl#getChangeTypes + */ + public void setChangeTypes(int types) { + m_changeTypes = types; + } + + /** + * Specifies whether you want the server to send any existing + * entries that already match the search criteria or only the + * entries that have changed. + * @param changesOnly If true, the server returns only the + * entries that have changed. If false, the server + * also returns any existing entries that match the search criteria + * but have not changed. + * @see netscape.ldap.controls.LDAPPersistSearchControl#getChangesOnly + */ + public void setChangesOnly(boolean changesOnly) { + m_changesOnly = changesOnly; + } + + /** + * Specifies whether you want the server to include an "entry change + * notification" control with each entry it sends back to the client + * during the persistent search. + * @param returnControls If true, the server includes + * "entry change notification" controls with the entries it sends + * during the persistent search. + * @see netscape.ldap.controls.LDAPEntryChangeControl + * @see netscape.ldap.controls.LDAPPersistSearchControl#setReturnControls + */ + public void setReturnControls(boolean returnControls) { + m_returnECs = returnControls; + } + + /** + * Takes an input byte array and extracts the ber elements, assigning + * them to appropriate fields in the entry change control. + * + * @param c Byte array that contains BER elements. + * @return The entry change control. + */ + public LDAPEntryChangeControl parseResponse(byte[] c) { + LDAPEntryChangeControl con = new LDAPEntryChangeControl(); + + ByteArrayInputStream inStream = new ByteArrayInputStream(c); + BERSequence seq = new BERSequence(); + JDAPBERTagDecoder decoder = new JDAPBERTagDecoder(); + int[] numRead = new int[1]; + numRead[0] = 0; + + try { + /* a sequence */ + BERSequence s = (BERSequence)BERElement.getElement(decoder, inStream, + numRead); + + BEREnumerated enum = (BEREnumerated)s.elementAt(0); + + con.setChangeType(enum.getValue()); + + if (s.size() > 1) { + if (s.elementAt(1) instanceof BEROctetString) { + BEROctetString str = (BEROctetString)s.elementAt(1); + con.setPreviousDN(new String(str.getValue(), "UTF8")); + } else if (s.elementAt(1) instanceof BERInteger) { + BERInteger num = (BERInteger)s.elementAt(1); + con.setChangeNumber(num.getValue()); + } + } + if (s.size() > 2) { + BERInteger num = (BERInteger)s.elementAt(2); + con.setChangeNumber(num.getValue()); + } + } catch (Throwable e) { + return null; + } + + return con; + } + + /** + * Returns an "entry change notification" control if the control is in + * the specified array of controls. Use this method to retrieve an "entry + * change notification" control included with an entry sent by the server. + *

+ * + * You can get the controls returned by the server by using the + * getResponseControls method of the + * LDAPConnection class. + *

+ * + * For example: + *

+     * ...
+     * LDAPConnection ld = new LDAPConnection();
+     * try {
+     *     // Connect to the server, set up the persistent search control,
+     *     // and set up the search constraints.
+     *     ...
+     *
+     *     // Search the directory.
+     *     LDAPSearchResults res = ld.search( "o=Airius.com",
+     *         LDAPv3.SCOPE_SUB, "(cn=Barbara*)", attrs, false, cons );
+     *
+     *     // Determine if the server sent a control back to you.
+     *     LDAPControl[] returnedControls = ld.getResponseControls();
+     *     if ( returnedControls != null ) {
+     *
+     *         // Get the entry change control.
+     *         LDAPEntryChangeControl entryCtrl =
+     *             persistCtrl.parseResponse( returnedControls );
+     *         if ( entryCtrl != null ) {
+     *
+     *             // Get and print the type of change made to the entry.
+     *             int changeType = entryCtrl.getChangeType();
+     *             if ( changeType != -1 ) {
+     *                 System.out.print( "Change made: " );
+     *                 switch ( changeType ) {
+     *                 case LDAPPersistSearchControl.ADD:
+     *                     System.out.println( "Added new entry." );
+     *             break;
+     *                 case LDAPPersistSearchControl.MODIFY:
+     *                     System.out.println( "Modified entry." );
+     *             break;
+     *                 case LDAPPersistSearchControl.DELETE:
+     *                     System.out.println( "Deleted entry." );
+     *             break;
+     *                 case LDAPPersistSearchControl.MODDN:
+     *                     System.out.println( "Renamed entry." );
+     *             break;
+     *                 }
+     *             }
+     *
+     *             // Get and print the change number corresponding
+     *             // to the change.
+     *             int changeNumber = entryCtrl.getChangeNumber();
+     *             if ( changeNumber != -1 )
+     *                 System.out.println( "Change log number: " + changeNumber);
+     *
+     *             // Get and print the previous DN of the entry,
+     *             // if the entry was renamed.
+     *             LDAPDN oldDN = entryCtrl.getPreviousDN();
+     *             if ( oldDN != null )
+     *                     System.out.println( "Previous DN: " + oldDN );
+     *
+     *         } else {
+     *
+     *             System.out.println( "No entry change control." );
+     *         }
+     *     }
+     *     ...
+     * }
+     * ...
+     *
+     * 
+ * + * @param controls An array of LDAPControl objects, + * representing the controls returned by the server + * with an entry. To get these controls, use the + * getResponseControls method of the + * LDAPConnection class. + * @return An LDAPEntryChangeControl object representing + * the entry change control sent by the server. If no entry change + * control was sent, this method returns null. + * @see netscape.ldap.controls.LDAPEntryChangeControl + * @see netscape.ldap.LDAPConnection#getResponseControls + */ + public static LDAPEntryChangeControl parseResponse(LDAPControl[] controls) { + + LDAPPersistSearchControl con = new LDAPPersistSearchControl(); + + for (int i=0; (controls != null) && (i < controls.length); i++) { + + // get the entry change control + if (controls[i].getID().equals(LDAPEntryChangeControl.ENTRYCHANGED)) { + return con.parseResponse(controls[i].getValue()); + } + } + + return null; + } + + /** + * Creates a "flattened" BER encoding of the persistent search + * specifications and returns it as a byte array. + * @param changeTypes The change types to be monitored on the server. + * @param changesOnly true to skip the initial search. + * @param returnECs true if entry change controls are to be + * returned with the search results. + * @return The BER-encoded data. + */ + private byte[] createPersistSearchSpecification(int changeTypes, + boolean changesOnly, boolean returnECs) { + + /* A sequence */ + BERSequence seq = new BERSequence(); + seq.addElement(new BERInteger(changeTypes)); + seq.addElement(new BERBoolean(changesOnly)); + seq.addElement(new BERBoolean(returnECs)); + + /* return a byte array */ + return flattenBER( seq ); + } + + private int m_changeTypes = 1; + private boolean m_changesOnly = false; + private boolean m_returnECs = false; + + /** + * Change type specifying that you want to track additions of new + * entries to the directory. You can either specify this change type + * when constructing an LDAPPersistSearchControl or + * by using the setChangeTypes method. + * @see netscape.ldap.controls.LDAPPersistSearchControl#getChangeTypes + * @see netscape.ldap.controls.LDAPPersistSearchControl#setChangeTypes + */ + public static final int ADD = 1; + + /** + * Change type specifying that you want to track removals of + * entries from the directory. You can either specify this change type + * when constructing an LDAPPersistSearchControl or + * by using the setChangeTypes method. + * @see netscape.ldap.controls.LDAPPersistSearchControl#getChangeTypes + * @see netscape.ldap.controls.LDAPPersistSearchControl#setChangeTypes + */ + public static final int DELETE = 2; + + /** + * Change type specifying that you want to track modifications of + * entries in the directory. You can either specify this change type + * when constructing an LDAPPersistSearchControl or + * by using the setChangeTypes method. + * @see netscape.ldap.controls.LDAPPersistSearchControl#getChangeTypes + * @see netscape.ldap.controls.LDAPPersistSearchControl#setChangeTypes + */ + public static final int MODIFY = 4; + + /** + * Change type specifying that you want to track modifications of the + * DNs of entries in the directory. You can either specify this change type + * when constructing an LDAPPersistSearchControl or + * by using the setChangeTypes method. + * @see netscape.ldap.controls.LDAPPersistSearchControl#getChangeTypes + * @see netscape.ldap.controls.LDAPPersistSearchControl#setChangeTypes + */ + public static final int MODDN = 8; + public final static String PERSISTENTSEARCH = "2.16.840.1.113730.3.4.3"; +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/controls/LDAPSortControl.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/controls/LDAPSortControl.java new file mode 100644 index 00000000000..66890022baf --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/controls/LDAPSortControl.java @@ -0,0 +1,491 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.controls; + +import java.io.*; +import netscape.ldap.LDAPControl; +import netscape.ldap.LDAPSortKey; +import netscape.ldap.client.JDAPBERTagDecoder; +import netscape.ldap.ber.stream.*; + +/** + * Represents an LDAP v3 server control that specifies that you want + * the server to return sorted search results. (The OID for this + * control is 1.2.840.113556.1.4.473.) + *

+ * + * When constructing an LDAPSortControl object, you can + * specify the order in which you want the results sorted. + * You can also specify whether or not this control is critical + * to the search operation. + *

+ * + * To specify the sort order, you construct an LDAPSortKey + * object and pass it to the LDAPSortControl constructor. + * The LDAPSortKey object represents a list of the attribute + * types used for sorting (a "sort key list"). + *

+ * + * You can include the control in a search request by constructing + * an LDAPSearchConstraints object and calling the + * setServerControls method. You can then pass this + * LDAPSearchConstraints object to the search + * method of an LDAPConnection object. + *

+ * + * For example: + *

+ * ...
+ * LDAPConnection ld = new LDAPConnection();
+ * try {
+ *     // Connect to server.
+ *     ld.connect( 3, hostname, portnumber, "", "" );
+ *
+ *     // Create a sort key that specifies the sort order.
+ *     LDAPSortKey sortOrder = new LDAPSortKey( attrname );
+ *
+ *     // Create a "critical" server control using that sort key.
+ *     LDAPSortControl sortCtrl = new LDAPSortControl(sortOrder,true);
+ *
+ *     // Create search constraints to use that control.
+ *     LDAPSearchConstraints cons = new LDAPSearchConstraints();
+ *     cons.setServerControls( sortCtrl );
+ *
+ *     // Send the search request.
+ *     LDAPSearchResults res = ld.search( "o=Airius.com",
+ *        LDAPv3.SCOPE_SUB, "(cn=Barbara*)", null, false, cons );
+ *
+ *     ...
+ *
+ * 
+ * + * The LDAP server sends back a sort response control to indicate + * the result of the sorting operation. (The OID for this control + * is 1.2.840.113556.1.4.474.) + *

+ * + * This control contains: + *

+ * + *

    + *
  • the result code from the sorting operation + *
  • optionally, the first attribute type in the sort key list + * that resulted in an error (for example, if the attribute does + * not exist) + *
+ *

+ * + * To parse this control, use the parseResponse method. + *

+ * + * The following table lists what kinds of results to expect from the + * LDAP server under different situations: + *

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Does the Server Support the Sorting Control?Is the Sorting Control Marked As Critical?Other ConditionsResults from LDAP Server
+ * No + * + * Yes + * + * None + * + *
    + *
  • The server does not send back any entries. + *
  • An LDAPException.UNAVAILABLE_CRITICAL_EXTENSION + * exception is thrown. + *
+ *
+ * No + * + * None + * + *
    + *
  • The server ignores the sorting control and + * returns the entries unsorted. + *
+ *

+ *

+ * Yes + * + * Yes + * + * The server cannot sort the results using the specified + * sort key list. + * + *
    + *
  • The server does not send back any entries. + *
  • An LDAPException.UNAVAILABLE_CRITICAL_EXTENSION + * exception is thrown. + *
  • The server sends back the sorting response control, which + * specifies the result code of the sort attempt and (optionally) + * the attribute type that caused the error. + *
+ *
+ * No + * + *
    + *
  • The server returns the entries unsorted. + *
  • The server sends back the sorting response control, which + * specifies the result code of the sort attempt and (optionally) + * the attribute type that caused the error. + *
+ *
+ * N/A (could either be marked as critical or not) + * + * The server successfully sorted the entries. + * + *
    + *
  • The server sends back the sorted entries. + *
  • The server sends back the sorting response control, which + * specifies the result code of the sort attempt + * (LDAPException.SUCCESS). + *
+ *
+ * The search itself failed (for any reason). + * + *
    + *
  • The server sends back a result code for the search + * operation. + *
  • The server does not send back the sorting response control. + *
+ *
+ *

+ * + * @version 1.0 + * @see netscape.ldap.LDAPSortKey + * @see netscape.ldap.LDAPControl + * @see netscape.ldap.LDAPSearchConstraints + * @see netscape.ldap.LDAPSearchConstraints#setServerControls(LDAPControl) + */ +public class LDAPSortControl extends LDAPControl { + public final static String SORTREQUEST = "1.2.840.113556.1.4.473"; + public final static String SORTRESPONSE = "1.2.840.113556.1.4.474"; + + /** + * Constructs an LDAPSortControl object with a single + * sorting key. + * @param key A single attribute to sort by. + * @param critical true if the LDAP operation should be + * discarded when the server does not support this control (in other + * words, this control is critical to the LDAP operation). + * @see netscape.ldap.LDAPControl + * @see netscape.ldap.LDAPSortKey + */ + public LDAPSortControl(LDAPSortKey key, + boolean critical) { + super( SORTREQUEST, critical, null ); + LDAPSortKey[] keys = new LDAPSortKey[1]; + keys[0] = key; + m_value = createSortSpecification( keys ); + } + + /** + * Constructs an LDAPSortControl object with an array of + * sorting keys. + * @param keys The attributes to sort by. + * @param critical true if the LDAP operation should be + * discarded when the server does not support this control (in other + * words, this control is critical to the LDAP operation). + * @see netscape.ldap.LDAPControl + * @see netscape.ldap.LDAPSortKey + */ + public LDAPSortControl(LDAPSortKey[] keys, + boolean critical) { + super( SORTREQUEST, critical, null ); + m_value = createSortSpecification( keys ); + } + + /** + * Parses the sorting response control sent by the server and + * retrieves the result code from the sorting operation and + * the attribute that caused sorting to fail (if specified by + * the server). + *

+ * + * You can get the controls returned by the server by using the + * getResponseControls method of the + * LDAPConnection class. + *

+ * + * This method returns the attribute that caused the sort operation + * to fail (or null, if the server did not specify any attribute). + * The result code of the sorting operation is returned in the + * results argument. This argument is an array of + * integers; the result code is specified in the first element of + * this array. + *

+ * + * For example: + *

+     * ...
+     * LDAPConnection ld = new LDAPConnection();
+     * try {
+     *     // Connect to the server, set up the sorting control,
+     *     // and set up the search constraints.
+     *     ...
+     *
+     *     // Search the directory.
+     *     LDAPSearchResults res = ld.search( "o=Airius.com",
+     *         LDAPv3.SCOPE_SUB, "(cn=Barbara*)", attrs, false, cons );
+     *
+     *     // Determine if the server sent a control back to you.
+     *     LDAPControl[] returnedControls = ld.getResponseControls();
+     *     if ( returnedControls != null ) {
+     *         int[] resultCodes = new int[1];
+     *         String failedAttr = LDAPSortControl.parseResponse(
+     *             returnedControls, resultCodes );
+     *
+     *         // Check if the result code indicated an error occurred.
+     *         if ( resultCodes[0] != 0 ) {
+     *             System.out.println( "Result code: " + resultCodes[0] );
+     *             if ( failedAttr != null ) {
+     *                 System.out.println( "Sorting operation failed on " +
+     *                     failedAttr );
+     *             } else {
+     *                 System.out.println( "Server did not indicate which " +
+     *                     "attribute caused sorting to fail." );
+     *             }
+     *         }
+     *     }
+     *     ...
+     * }
+     * ...
+     *
+     * 
+ * + * The following table lists some of the possible result codes + * for the sorting operation. + *

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
+ * LDAPException.SUCCESS + * + * The server successfully sorted the results. + *
+ * LDAPException.OPERATION_ERROR + * + * An internal server error occurred. + *
+ * LDAPException.TIME_LIMIT_EXCEEDED + * + * The maximum time allowed for a search was exceeded + * before the server finished sorting the results. + *
+ * LDAPException.STRONG_AUTH_REQUIRED + * + * The server refused to send back the sorted search + * results because it requires you to use a stronger + * authentication method. + *
+ * LDAPException.ADMIN_LIMIT_EXCEEDED + * + * There are too many entries for the server to sort. + *
+ * LDAPException.NO_SUCH_ATTRIBUTE + * + * The sort key list specifies an attribute that does not exist. + *
+ * LDAPException.INAPPROPRIATE_MATCHING + * + * The sort key list specifies a matching rule that is + * not recognized or appropriate + *
+ * LDAPException.INSUFFICIENT_ACCESS_RIGHTS + * + * The server did not send the sorted results because the + * client has insufficient access rights. + *
+ * LDAPException.BUSY + * + * The server is too busy to sort the results. + *
+ * LDAPException.UNWILLING_TO_PERFORM + * + * The server is unable to sort the results. + *
+ * LDAPException.OTHER + * + * This general result code indicates that the server + * failed to sort the results for a reason other than + * the ones listed above. + *
+ *

+ * + * @param controls An array of LDAPControl objects, + * representing the controls returned by the server + * after a search. To get these controls, use the + * getResponseControls method of the + * LDAPConnection class. + * @param results An array of integers. The first element of this array + * specifies the result code of the sorting operation. + * @return The attribute that caused the error, or null if the server did + * not specify which attribute caused the error. + * @see netscape.ldap.LDAPConnection#getResponseControls + */ + public static String parseResponse( LDAPControl[] controls, int[] results ) { + String attr = null; + LDAPControl sort = null; + /* See if there is a sort control in the array */ + for( int i = 0; (controls != null) && (i < controls.length); i++ ) { + if ( controls[i].getID().equals( SORTRESPONSE ) ) { + sort = controls[i]; + break; + } + } + if ( sort != null ) { + /* Suck out the data and return it */ + ByteArrayInputStream inStream = + new ByteArrayInputStream( sort.getValue() ); + BERSequence ber = new BERSequence(); + JDAPBERTagDecoder decoder = new JDAPBERTagDecoder(); + int[] nRead = new int[1]; + nRead[0] = 0; + try { + /* A sequence */ + BERSequence seq = (BERSequence)BERElement.getElement( + decoder, inStream, + nRead ); + /* First is result code */ + int result = ((BEREnumerated)seq.elementAt( 0 )).getValue(); + if ( (results != null) && (results.length > 0) ) + results[0] = result; + /* Then, possibly an attribute that failed sorting */ + /* If this is not an octet string, let there be an exception */ + BEROctetString t = (BEROctetString)seq.elementAt(1); + attr = new String(t.getValue(), "UTF8"); + } catch(Throwable x) { + } + } + return attr; + } + + /** + * Create a "flattened" BER encoding of the requested sort keys, + * and return it as a byte array. + * @param keys The attributes to sort by. + * @return The byte array of encoded data. + */ + private byte[] createSortSpecification( LDAPSortKey[] keys ) { + /* A sequence of sequences */ + BERSequence ber = new BERSequence(); + /* Add each sort key as a sequence */ + for( int i = 0; i < keys.length; i++ ) { + BERSequence seq = new BERSequence(); + /* The attribute name */ + seq.addElement(new BEROctetString(keys[i].getKey())); + /* Optional matching rule */ + if ( keys[i].getMatchRule() != null ) + seq.addElement(new BERTag( + BERTag.CONTEXT|0, + new BEROctetString(keys[i].getMatchRule()), + true)); + /* Optional reverse-order sort */ + if ( keys[i].getReverse() ) + seq.addElement(new BERTag( + BERTag.CONTEXT|1, + new BEREnumerated(LDAPSortKey.REVERSE), + true)); + ber.addElement( seq ); + } + /* Suck out the data and return it */ + return flattenBER( ber ); + } +} + diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/controls/LDAPVirtualListControl.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/controls/LDAPVirtualListControl.java new file mode 100644 index 00000000000..522ab934cfb --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/controls/LDAPVirtualListControl.java @@ -0,0 +1,393 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.controls; + +import java.io.*; +import netscape.ldap.client.JDAPBERTagDecoder; +import netscape.ldap.LDAPControl; +import netscape.ldap.ber.stream.*; + +/** + * Represents control data for returning paged results from a search. + * + * Example of usage, with JFC: + *


+ *  // Call this to initialize the list box, whenever the search
+ *  // conditions change.
+ *  // "filter" may be "objectclass=person", for example
+ *  void initListBox( String host, int port, String base, String filter ) {
+ *
+ *  // Create list box if not already done
+ *   if ( _dataList == null ) {
+ *       _dataList = new JList();
+ *       JScrollPane scrollPane = new JScrollPane(_dataList);
+ *       add( scrollPane );
+ *   }
+ *
+ *   // Create a virtual data model
+ *   vlistModel model = new vlistModel( host, port, base, filter );
+ *   // Keep a buffer of one page before and one after
+ *   model.setPageSize( getScrollVisibleSize() );
+ *   _dataList.setModel( model );
+ *  }
+ *

+ * // Data model to supply buffer list data + *class vlistModel extends AbstractListModel { + * vlistModel( String host, int port, String base, String filter ) { + * _base = base; + * _filter = filter; + * + * // Connect to the server + * try { + * _ldc = new LDAPConnection(); + * System.out.println( "Connecting to " + host + + * ":" + port ); + * _ldc.connect( host, port ); + * } catch ( LDAPException e ) { + * System.out.println( e ); + * _ldc = null; + * } + * } + * + * // Called by JList to get virtual list size + * public int getSize() { + * if ( !_initialized ) { + * _initialized = true; + * _pageControls = new LDAPControl[2]; + * // Paged results also require a sort control + * _pageControls[0] = + * new LDAPSortControl( new LDAPSortKey("cn"), + * true ); + * // Do an initial search to get the virtual list size + * // Keep one page before and one page after the start + * _beforeCount = _pageSize; + * _afterCount = _pageSize; + * // Create the initial paged results control + * LDAPVirtualListControl cont = + * new LDAPVirtualListControl( "A", + * _beforeCount, + * _afterCount ); + * _pageControls[1] = cont; + * _vlc = (LDAPVirtualListControl)_pageControls[1]; + * getPage( 0 ); + * } + * return _size; + * } + * + * // Get a page starting at first (although we may also fetch + * // some preceding entries) + * boolean getPage( int first ) { + * _vlc.setRange( first, _beforeCount, _afterCount ); + * return getPage(); + * } + * + * boolean getEntries() { + * // Specify necessary controls for vlv + * if ( _pageControls != null ) { + * try { + * _ldc.setOption( _ldc.SERVERCONTROLS, _pageControls ); + * } catch ( LDAPException e ) { + * System.out.println( e + ", setting vlv control" ); + * } + * } + * // Empty the buffer + * _entries.removeAllElements(); + * // Do a search + * try { + * String[] attrs = { "cn" }; + * LDAPSearchResults result = + * _ldc.search( _base, + * LDAPConnection.SCOPE_SUB, + * _filter, + * attrs, false ); + * while ( result.hasMoreElements() ) { + * LDAPEntry entry = (LDAPEntry)result.nextElement(); + * LDAPAttribute attr = entry.getAttribute( attrs[0] ); + * if ( attr != null ) { + * Enumeration en = attr.getStringValues(); + * while( en.hasMoreElements() ) { + * String name = (String)en.nextElement(); + * _entries.addElement( name ); + * } + * } + * } + * } catch ( LDAPException e ) { + * System.out.println( e + ", searching" ); + * return false; + * } + * return true; + * } + * + * // Fetch a buffer + * boolean getPage() { + * // Get the actual entries + * if ( !getEntries() ) + * return false; + * + * // Check if we have a control returned + * LDAPControl[] c = _ldc.getResponseControls(); + * LDAPVirtualListResponse nextCont = + * LDAPVirtualListResponse.parseResponse( c ); + * if ( nextCont != null ) { + * _selectedIndex = nextCont.getFirstPosition() - 1; + * _top = Math.max( 0, _selectedIndex - _beforeCount ); + * // Now we know the total size of the virtual list box + * _size = nextCont.getContentCount(); + * _vlc.setListSize( _size ); + * } else { + * System.out.println( "Null response control" ); + * } + * return true; + * } + * + * // Called by JList to fetch data to paint a single list item + * public Object getElementAt(int index) { + * if ( (index < _top) || (index >= _top + _entries.size()) ) { + * getPage( index ); + * } + * int offset = index - _top; + * if ( (offset < 0) || (offset >= _entries.size()) ) + * return new String( "No entry at " + index ); + * else + * return _entries.elementAt( offset ); + * } + * + * // Called by application to find out the virutal selected index + * public int getSelectedIndex() { + * return _selectedIndex; + * } + * + * // Called by application to find out the top of the buffer + * public int getFirstIndex() { + * return _top; + * } + * + * public void setPageSize( int size ) { + * _pageSize = size; + * } + * + * Vector _entries = new Vector(); + * protected boolean _initialized = false; + * private int _top = 0; + * protected int _beforeCount; + * protected int _afterCount; + * private int _pageSize = 10; + * private int _selectedIndex = 0; + * protected LDAPControl[] _pageControls = null; + * protected LDAPVirtualListControl _vlc = null; + * protected int _size = -1; + * private String _base; + * private String _filter; + * private LDAPConnection _ldc; + *} + *

+ *
+ *      VirtualListViewRequest ::= SEQUENCE {
+ *                      beforeCount    INTEGER,
+ *                      afterCount     INTEGER,
+ *                      CHOICE {
+ *                      byIndex [0] SEQUENCE {
+ *                          index           INTEGER,
+ *                          contentCount    INTEGER }
+ *                      byFilter [1] jumpTo    Substring }
+ * 
+ * + * @version 1.0 + */ + +public class LDAPVirtualListControl extends LDAPControl { + public final static String VIRTUALLIST = "2.16.840.1.113730.3.4.9"; + + /** + * Blank constructor for internal use in LDAPVirtualListControl. + * @see netscape.ldap.LDAPControl + */ + LDAPVirtualListControl() { + super( VIRTUALLIST, true, null ); + } + + /** + * Constructs a new LDAPVirtualListControl object. Use this + * constructor on an initial search operation, specifying the first + * entry to be matched, or the initial part of it. + * @param jumpTo An LDAP search expression defining the result set. + * @param beforeCount The number of results before the top/center to + * return per page. + * @param afterCount The number of results after the top/center to + * return per page. + * @see netscape.ldap.LDAPControl + */ + public LDAPVirtualListControl( String jumpTo, int beforeCount, + int afterCount ) { + super( VIRTUALLIST, true, null ); + setRange( jumpTo, beforeCount, afterCount ); + } + + /** + * Constructs a new LDAPVirtualListControl object. Use this + * constructor on a subsquent search operation, after we know the + * size of the virtual list, to fetch a subset. + * @param startIndex The index into the virtual list of an entry to + * return. + * @param beforeCount The number of results before the top/center to + * return per page. + * @param afterCount The number of results after the top/center to + * return per page. + * @see netscape.ldap.LDAPControl + */ + public LDAPVirtualListControl( int startIndex, int beforeCount, + int afterCount, int contentCount ) { + super( VIRTUALLIST, true, null ); + m_listSize = contentCount; + setRange( startIndex, beforeCount, afterCount ); + } + + /** + * Sets the starting index, and the number of entries before and after + * to return. Apply this method to a control returned from a previous + * search, to specify what result range to return on the next search. + * @param startIndex The index into the virtual list of an entry to + * return. + * @param beforeCount The number of results before startIndex to + * return per page. + * @param afterCount The number of results after startIndex to + * return per page. + * @see netscape.ldap.LDAPControl + */ + public void setRange( int startIndex, int beforeCount, int afterCount ) { + m_beforeCount = beforeCount; + m_afterCount = afterCount; + m_listIndex = startIndex; + m_value = createPageSpecification( m_listIndex, m_listSize, + m_beforeCount, m_afterCount ); + } + + /** + * Sets the search expression, and the number of entries before and after + * to return. + * @param jumpTo An LDAP search expression defining the result set. + * return. + * @param beforeCount The number of results before startIndex to + * return per page. + * @param afterCount The number of results after startIndex to + * return per page. + * @see netscape.ldap.LDAPControl + */ + public void setRange( String jumpTo, int beforeCount, int afterCount ) { + m_beforeCount = beforeCount; + m_afterCount = afterCount; + m_value = createPageSpecification( jumpTo, m_beforeCount, m_afterCount ); + } + + /** + * Gets the size of the virtual result set. + * @return The size of the virtual result set, or -1 if not known. + */ + public int getIndex() { + return m_listIndex; + } + + /** + * Gets the size of the virtual result set. + * @return The size of the virtual result set, or -1 if not known. + */ + public int getListSize() { + return m_listSize; + } + + /** + * Sets the size of the virtual result set. + * @param listSize The virtual result set size. + */ + public void setListSize( int listSize ) { + m_listSize = listSize; + } + + /** + * Gets the number of results before the top/center to return per page. + * @return The number of results before the top/center to return per page. + */ + public int getBeforeCount() { + return m_beforeCount; + } + + /** + * Gets the number of results after the top/center to return per page. + * @return The number of results after the top/center to return per page. + */ + public int getAfterCount() { + return m_afterCount; + } + + /** + * Creates a "flattened" BER encoding of the requested page + * specifications and return it as a byte array. + * @param subFilter Filter expression for generating the results. + * @param beforeCount Number of entries before first match to return. + * @param afterCount Number of entries ager first match to return. + * @return The byte array of encoded data. + */ + private byte[] createPageSpecification( String subFilter, + int beforeCount, + int afterCount ) { + /* A sequence */ + BERSequence seq = new BERSequence(); + seq.addElement( new BERInteger( beforeCount ) ); + seq.addElement( new BERInteger( afterCount ) ); + seq.addElement( new BERTag(BERTag.CONTEXT|TAG_BYFILTER, + new BEROctetString(subFilter), true) ); + /* Suck out the data and return it */ + return flattenBER( seq ); + } + + /** + * Creates a "flattened" BER encoding of the requested page + * specifications and return it as a byte array. + * @param listIndex The center or starting entry to return. + * @param listSize The virtual list size. + * @param beforeCount Number of entries before first match to return. + * @param afterCount Number of entries after first match to return. + * @return The byte array of encoded data. + */ + private byte[] createPageSpecification( int listIndex, + int listSize, + int beforeCount, + int afterCount ) { + /* A sequence */ + BERSequence seq = new BERSequence(); + seq.addElement( new BERInteger( beforeCount ) ); + seq.addElement( new BERInteger( afterCount ) ); + /* A sequence of list index and list size */ + BERSequence indexSeq = new BERSequence(); + indexSeq.addElement( new BERInteger(listIndex) ); + indexSeq.addElement( new BERInteger(listSize) ); + seq.addElement( + new BERTag(BERTag.CONTEXT|BERTag.CONSTRUCTED|TAG_BYINDEX, + indexSeq,true) ); + + /* Suck out the data and return it */ + return flattenBER( seq ); + } + + private final static int TAG_BYINDEX = 0; + private final static int TAG_BYFILTER = 1; + private int m_beforeCount = 0; + private int m_afterCount = 0; + private int m_listIndex = -1; + private int m_listSize = 0; +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/controls/LDAPVirtualListResponse.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/controls/LDAPVirtualListResponse.java new file mode 100644 index 00000000000..6229e59d7d1 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/controls/LDAPVirtualListResponse.java @@ -0,0 +1,151 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.controls; + +import java.io.*; +import netscape.ldap.client.JDAPBERTagDecoder; +import netscape.ldap.LDAPControl; +import netscape.ldap.ber.stream.*; + +/** + * Represents control data for returning paged results from a search. + * + * @version 1.0 + * + *
+ *      VirtualListViewResponse ::= SEQUENCE {
+ *               firstPosition    INTEGER,
+ *               contentCount     INTEGER,
+ *               virtualListViewResult ENUMERATED {
+ *                 success                  (0),
+ *                 unwillingToPerform       (53),
+ *                 insufficientAccessRights (50),
+ *                 operationsError          (1),
+ *                 busy                     (51),
+ *                 timeLimitExceeded        (3),
+ *                 adminLimitExceeded       (11),
+ *                 sortControlMissing       (60),
+ *                 indexRangeError          (?),
+ *               }
+ *     }
+ *
+ */ + +public class LDAPVirtualListResponse extends LDAPControl { + public final static String VIRTUALLISTRESPONSE = "2.16.840.1.113730.3.4.10"; + + /** + * Blank constructor for internal use in LDAPVirtualListResponse. + * @see netscape.ldap.LDAPControl + */ + LDAPVirtualListResponse() { + super( VIRTUALLISTRESPONSE, true, null ); + } + + /** + * Constructs a new LDAPVirtualListResponse object. + * @param value A BER encoded byte array. + * @see netscape.ldap.LDAPControl + */ + public LDAPVirtualListResponse( byte[] value ) { + super( VIRTUALLISTRESPONSE, true, null ); + m_value = value; + parseResponse(); + } + + /** + * Gets the size of the virtual result set. + * @return The size of the virtual result set, or -1 if not known. + */ + public int getContentCount() { + return m_contentCount; + } + + /** + * Gets the index of the first entry returned. + * @return The index of the first entry returned. + */ + public int getFirstPosition() { + return m_firstPosition; + } + + /** + * Gets the result code. + * @return The result code. + */ + public int getResultCode() { + return m_resultCode; + } + + /** + * Returns a control useful for subsequent paged results searches. + * "this" should be a control returned on a previous paged results + * search, so it contains information on the virtual result set + * size. + * @return A control useful for subsequent paged results searches. + */ + private void parseResponse() { + /* Suck out the data and parse it */ + ByteArrayInputStream inStream = + new ByteArrayInputStream( getValue() ); + BERSequence ber = new BERSequence(); + JDAPBERTagDecoder decoder = new JDAPBERTagDecoder(); + int[] nRead = new int[1]; + nRead[0] = 0; + try { + /* A sequence */ + BERSequence seq = (BERSequence)BERElement.getElement( + decoder, inStream, + nRead ); + /* First is firstPosition */ + m_firstPosition = ((BERInteger)seq.elementAt( 0 )).getValue(); + m_contentCount = ((BERInteger)seq.elementAt( 1 )).getValue(); + BEREnumerated enum = (BEREnumerated)seq.elementAt( 2 ); + m_resultCode = enum.getValue(); + } catch(Throwable x) { + m_firstPosition = m_contentCount = m_resultCode = -1; + } + } + + /** + * Returns a control returned on a VLV search. + * @param controls An array of controls that may include a VLV + * results control. + * @return The control, if any; otherwise null. + */ + public static LDAPVirtualListResponse parseResponse( + LDAPControl[] controls ) { + LDAPVirtualListResponse con = null; + /* See if there is a VLV response control in the array */ + for( int i = 0; (controls != null) && (i < controls.length); i++ ) { + if ( controls[i].getID().equals( VIRTUALLISTRESPONSE ) ) { + con = new LDAPVirtualListResponse( controls[i].getValue() ); + con.parseResponse(); + break; + } + } + if ( con != null ) { + con.parseResponse(); + } + return con; + } + + private int m_firstPosition = 0; + private int m_contentCount = 0; + private int m_resultCode = -1; +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/errors/ErrorCodes.props b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/errors/ErrorCodes.props new file mode 100644 index 00000000000..2f5c1fd5362 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/errors/ErrorCodes.props @@ -0,0 +1,50 @@ +0=Success +1=Operations error +2=Protocol error +3=Timelimit exceeded +4=Sizelimit exceeded +5=Compare false +6=Compare true +7=Strong authentication not supported +8=Strong authentication required +9=Partial results and referral received +10=Referral received +11=Administrative limit exceeded +12=Critical extension unavailable +13=Confidentiality required +14=SASL bind in progress +16=No such attribute +17=Undefined attribute type +18=Inappropriate matching +19=Constraint violation +20=Type or value exists +21=Invalid syntax +32=No such object +33=Alias problem +34=Invalid DN syntax +35=Object is a leaf +36=Alias dereferencing problem +48=Inappropriate authentication +49=Invalid credentials +50=Insufficient access +51=DSA is busy +52=DSA is unavailable +53=DSA is unwilling to perform +54=Loop detected +64=Naming violation +65=Object class violation +66=Operation not allowed on nonleaf +67=Operation not allowed on RDN +68=Already exists +69=Cannot modify object class +71=Affects multiple DSAs +80=Unknown error +81=Cannot contact LDAP server +89=Bad parameter to an LDAP method +91=Cannot connect to the LDAP server +92=Not supported by this version of the LDAP protocol +93=Requested LDAP control not found +94=No results returned +95=More results to return +96=Client detected loop +97=Referral hop limit exceeded diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/ByteBuf.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/ByteBuf.java new file mode 100644 index 00000000000..4f062535247 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/ByteBuf.java @@ -0,0 +1,432 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.util; + +import java.util.*; + +import java.io.FileInputStream; +import java.io.InputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintStream; +import java.io.RandomAccessFile; + +/** + * This class is similar to the java.lang.StringBuffer + * class. Instead of storing a string, an object of this class + * stores an array of bytes. (This is referred to as a "byte buffer".) + *

+ * + * This class also differs from StringBuffer in the + * following ways: + *

    + *
  • None of the methods are synchronized. You cannot share a + * byte buffer among multiple threads. + *
  • Converting to a String requires a copy of the character data. + *
  • In order to speed up memory allocation, Alloc + * and Recycle methods are provided. You can "recycle" + * any ByteBuf objects you no longer need by using the + * Recycle method. Calling the Alloc + * method will reuse objects that have been "recycled." To + * To clear out the cache of these "recycled" objects, use + * the EmptyRecycler method. + *
  • Additional "helper" methods are provided (for example, + * functions for comparing data). + *
+ */ +public final class ByteBuf { + private byte value[]; + private int count; + + /** + * Constructs an empty byte buffer with the default length of 16. + */ + public ByteBuf() { + this(16); + } + + /** + * Constructs an empty byte buffer with the specified initial length. + * @param length Initial number of bytes that this buffer should hold. + */ + public ByteBuf(int length) { + value = new byte[length]; + } + + /** + * Constructs a byte buffer with the specified initial value. + * The new byte buffer is 16 bytes longer than the initial value. + * @param str Initial value that this buffer should hold. + */ + public ByteBuf(String str) { + this(str.length() + 16); + append(str); + } + + /** + * Constructs a byte buffer with the specified length. + * An initial value is stored in this buffer, starting + * at the specified offset. + * @param bytes Array of bytes that you want to store in + * the buffer initially. + * @param offset Index in the array where you want the + * initial value to start. + * @param length Length of the buffer that you want to + * allocate. + */ + public ByteBuf(byte bytes[], int offset, int length) { + value = new byte[length]; + System.arraycopy(bytes, offset, value, 0, length); + count = length; + } + + /** + * Returns the length (character count) of the byte buffer. + */ + public int length() { + return count; + } + + /** + * Returns the current capacity of the byte buffer. The capacity + * is the amount of storage available for newly inserted bytes. + * If the capacity is exceeded, more space will be allocated. + */ + public int capacity() { + return value.length; + } + + /** + * Ensures that the capacity of the buffer is at least equal to the + * specified minimum capacity. + * @param minimumCapacity The minimum number of bytes that you want + * the byte buffer to hold. + */ + public void ensureCapacity(int minimumCapacity) { + int maxCapacity = value.length; + + if (minimumCapacity > maxCapacity) { + int newCapacity = (maxCapacity + 1) * 2; + if (minimumCapacity > newCapacity) { + newCapacity = minimumCapacity; + } + + byte newValue[] = new byte[newCapacity]; + System.arraycopy(value, 0, newValue, 0, count); + value = newValue; + } + } + + /** + * Sets the length of the byte buffer. If you set a length that is + * shorter than the current length, bytes at the end of the buffer + * are lost. If you increase the length of the buffer, the values + * of the new bytes in the buffer are set to 0. + * @param newLength The new length of the buffer + * @exception StringIndexOutOfBoundsException You have specified + * an invalid length. + */ + public void setLength(int newLength) { + if (newLength < 0) { + throw new StringIndexOutOfBoundsException(newLength); + } + if (count < newLength) { + ensureCapacity(newLength); + for (; count < newLength; count++) { + value[count] = '\0'; + } + } + count = newLength; + } + + /** + * Returns the byte at the specified index. The value of an index + * can range from 0 to length - 1. + * @param index Index of the byte you want to find. + * @exception StringIndexOutOfBoundsException You have specified an + * invalid index. + */ + public byte byteAt(int index) { + if ((index < 0) || (index >= count)) { + throw new StringIndexOutOfBoundsException(index); + } + return value[index]; + } + + /** + * Copies the bytes (from the section of the byte buffer from the index + * srcBegin to the index srcEnd - 1 ) + * into the specified byte array. The copied + * bytes are inserted in the byte array at the index specified by + * dstBegin. Both srcBegin and + * srcEnd must be valid indexes in the buffer. + * @param srcBegin Index identifying the start of the section + * of the byte buffer that you want to copy. + * @param srcEnd Index identifying the end of the section + * of the byte buffer that you want to copy. (Copy all bytes + * before the byte identified by this index.) + * @param dst The byte array to copy the data to + * @param dstBegin Index of the byte array identifying the + * location where you want the byte buffer copied to. + * @exception StringIndexOutOfBoundsException You specified an invalid index into the buffer. + */ + public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) { + if ((srcBegin < 0) || (srcBegin >= count)) { + throw new StringIndexOutOfBoundsException(srcBegin); + } + if ((srcEnd < 0) || (srcEnd > count)) { + throw new StringIndexOutOfBoundsException(srcEnd); + } + if (srcBegin < srcEnd) { + System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin); + } + } + + /** + * Sets the value of the byte at the specified index. + * @param index The index of the byte that you want to set. + * @param b The new value that you want to set. + * @exception StringIndexOutOfBoundsException You have specified + * an invalid index. + */ + public void setByteAt(int index, byte b) { + if ((index < 0) || (index >= count)) { + throw new StringIndexOutOfBoundsException(index); + } + value[index] = b; + } + + /** + * Appends an object to the end of this byte buffer. + * @param obj The object that you want appended to the buffer. + * @return The same ByteBuf object (not a new object) + * with the string representation of the specified object appended. + */ + public ByteBuf append(Object obj) { + return append(String.valueOf(obj)); + } + + /** + * Appends a string to the end of this byte buffer. + * This method appends one byte for each character in the string. + * The upper 8 bits of the character are stripped off. + *

+ * + * If you want to retain all bits in the character (not just + * the lower 8 bits), use append(String.getBytes()) + * instead. + * @param str The string that you want appended to the buffer. + * @return The same ByteBuf object (not a new object) + * with the specified string appended. + */ + public ByteBuf append(String str) { + if (str == null) { + str = String.valueOf(str); + } + + int len = str.length(); + ensureCapacity(count + len); + for (int i=0 ; iByteBuf object (not a new object) + * with the specified bytes appended. + */ + public ByteBuf append(byte str[]) { + int len = str.length; + ensureCapacity(count + len); + System.arraycopy(str, 0, value, count, len); + count += len; + return this; + } + + /** + * Appends a part of an array of bytes to the end of this byte buffer. + * @param str The array of bytes that you want appended to this buffer. + * @param offset The index in the array marking the start of the + * section that you want to copy. + * @param len The number of bytes that you want to add. + * @return The same ByteBuf object (not a new object) + * with the specified section of the byte array appended. + */ + public ByteBuf append(byte str[], int offset, int len) { + ensureCapacity(count + len); + System.arraycopy(str, offset, value, count, len); + count += len; + return this; + } + + /** + * Appends a byte buffer to the end of this byte buffer. + * @param buf The byte buffer that you want appended to this buffer. + * @return The original ByteBuf object (not a new object) + * with bytes from the specified byte buffer appended. + */ + public ByteBuf append(ByteBuf buf) { + append(buf.toBytes(), 0, buf.length()); + return this; + } + + /** + * Appends a boolean to the end of this byte buffer. + * @param b The boolean value that you want appended to this buffer. + * @return The original ByteBuf object (not a new object) + * with bytes from the string representation of the boolean value appended. + */ + public ByteBuf append(boolean b) { + return append(String.valueOf(b)); + } + + /** + * Appends a byte to the end of this byte buffer. + * @param ch The byte that you want appended to this buffer. + * @return The original ByteBuf object (not a new object) + * with the specified byte appended. + */ + public ByteBuf append(byte b) { + ensureCapacity(count + 1); + value[count++] = b; + return this; + } + + /** + * Appends an integer to the end of this byte buffer. + * @param i The integer that you want appended to this byte buffer. + * @return The original ByteBuf object (not a new object) + * with the string representation of the specified integer appended. + */ + public ByteBuf append(int i) { + return append(String.valueOf(i)); + } + + /** + * Appends a long value to the end of this byte buffer. + * @param l The long value that you want appended + * to this buffer. + * @return The original ByteBuf object (not a new object) + * with the string representation of the specified long + * value appended. + */ + public ByteBuf append(long l) { + return append(String.valueOf(l)); + } + + /** + * Appends a float to the end of this byte buffer. + * @param f The float value that you want appended + * to this buffer. + * @return The original ByteBuf object (not a new object) + * with the string representation of the specified float + * value appended. + */ + public ByteBuf append(float f) { + return append(String.valueOf(f)); + } + + /** + * Appends a double to the end of this byte buffer. + * @param d The double value that you want appended to + * this buffer. + * @return The original ByteBuf object (not a new object) + * with the string representation of the specified double + * value appended. + */ + public ByteBuf append(double d) { + return append(String.valueOf(d)); + } + + /** + * Returns the data in the byte buffer to a string. + * @return The string representation of the data in the byte buffer. + */ + public String toString() { + return new String(value, 0, count); + } + + /** + * Returns the data in the byte buffer as a byte array. + * @return The byte array containing data in the byte buffer. + */ + public byte[] toBytes() { + byte[] b = new byte[count]; + System.arraycopy(value, 0, b, 0, count); + return b; + } + + /** + * Invokes the InputStream.read method and appends the + * the bytes read to this byte buffer. + * @param file The input stream that you want to read the bytes from. + * @param max_bytes The maximum number of bytes to read into the + * byte buffer. + * @return The number of bytes read, or -1 if there is no more data + * to be read. + * @exception IOException An I/O error has occurred. + */ + public int read(InputStream file, int max_bytes) + throws IOException { + ensureCapacity(count + max_bytes); + int i = file.read(value, count, max_bytes); + if (i > 0) count += i; + return i; + } + + /** + * Invokes the RandomAccessFile.read method, appending + * the bytes read to this byte buffer. + * @param file The RandomAccessFile object that you want + * to read the bytes from. + * @param max_bytes The maximum number of bytes to read into the + * byte buffer. + * @return The number of bytes read, or -1 if there is no more data + * to be read. + * @exception IOException An I/O error has occurred. + */ + public int read(RandomAccessFile file, int max_bytes) + throws IOException { + ensureCapacity(count + max_bytes); + int i = file.read(value, count, max_bytes); + if (i > 0) count += i; + return i; + } + + /** + * Writes the contents of the byte buffer to the specified output stream. + * @param out The output stream. + * @exception IOException An I/O error has occurred. + */ + public void write(OutputStream out) throws IOException { + out.write(value, 0, count); + } + + /** + * Writes the contents of the byte buffer to the specified + * RandomAccessFile object. + * @param out The RandomAccessFile object. + * @exception IOException An I/O error has occurred. + */ + public void write(RandomAccessFile out) throws IOException { + out.write(value, 0, count); + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/DN.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/DN.java new file mode 100644 index 00000000000..b40a5c8b81d --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/DN.java @@ -0,0 +1,434 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.util; + +import java.util.*; +import java.io.*; +import java.util.StringTokenizer; + +/** + * Objects of this class represent distinguished names (DN). A + * distinguished name is used to identify an entry in a directory. + *

+ * + * The netscape.ldap.LDAPDN class uses this class + * internally. In most cases, when working with DNs in the + * LDAP Java classes, you should use the + * netscape.ldap.LDAPDN class. + *

+ * + * The following DNs are examples of the different formats + * for DNs that may appear: + *

    + *
  • uid=bjensen, ou=People, o=Airius.com + * (RFC 1485 format) + *
  • o=Airius.com/ou=People/uid=bjensen (OSF format) + *
+ *

+ * + * @version 1.0 + * @see netscape.ldap.LDAPDN + */ +public final class DN { + + /** + * List of RDNs. DN consists of one or more RDNs. + * RDNs follow RFC1485 order. + */ + Vector m_rdns = new Vector(); + + /** + * Type specifying a DN in the RFC format. + *

+ * + * @see netscape.ldap.util.DN#getDNType + * @see netscape.ldap.util.DN#setDNType + */ + public static int RFC = 0; + + /** + * Type specifying a DN in the OSF format. + *

+ * + * @see netscape.ldap.util.DN#getDNType + * @see netscape.ldap.util.DN#setDNType + */ + public static int OSF = 1; + + private int m_dnType = RFC; + + /** + * Constructs an empty DN object. + */ + public DN() { + } + + /** + * Constructs a DN object from the specified + * distinguished name. The string representation of the DN + * can be in RFC 1485 or OSF format. + *

+ * + * @param dn String representation of the distinguished name. + */ + public DN(String dn) { + if (dn == null) + return; + int index; + + // RFC1485 + if (isRFC(dn)) { + StringBuffer buffer = new StringBuffer(dn); + + int i=0; + StringBuffer rbuffer = new StringBuffer(); + boolean openQuotes = false; + while (i < buffer.length()) { + rbuffer.append(buffer.charAt(i)); + if (buffer.charAt(i) == '\\') { + char c = buffer.charAt(i+1); + for (int j=0; j= 0; i--) { + m_rdns.addElement(rdns.elementAt(i)); + } + } else if (RDN.isRDN(dn)) { + m_rdns.addElement(new RDN(dn)); + } + } + + /** + * Adds the specified relative distinguished name (RDN) to the + * beginning of the current DN. + *

+ * + * @param rdn The relative distinguished name that you want + * to add to the beginning of the current DN. + * @see netscape.ldap.utils.RDN + */ + public void addRDNToFront(RDN rdn) { + m_rdns.insertElementAt(rdn, 0); + } + + /** + * Adds the specified relative distinguished name (RDN) to the + * end of the current DN. + *

+ * + * @param rdn The relative distinguished name that you want + * to append to the current DN. + * @see netscape.ldap.utils.RDN + */ + public void addRDNToBack(RDN rdn) { + m_rdns.addElement(rdn); + } + + /** + * Adds the specified relative distinguished name (RDN) to the current DN. + * If the DN is in RFC 1485 format, the RDN is added to the beginning + * of the DN. If the DN is in OSF format, the RDN is appended to the + * end of the DN. + *

+ * + * @param rdn The relative distinguished name that you want to add to + * the current DN. + * @see netscape.ldap.utils.RDN + */ + public void addRDN(RDN rdn) { + if (m_dnType == RFC) { + addRDNToFront(rdn); + } else { + addRDNToBack(rdn); + } + } + + /** + * Sets the type of format used for the DN (RFC format or OSF format). + *

+ * + * @param type One of the following constants: DN.RFC + * (to use the RFC format) or DN.OSF (to use the OSF format). + * @see netscape.ldap.util.DN#getDNType + * @see netscape.ldap.util.DN#RFC + * @see netscape.ldap.util.DN#OSF + */ + public void setDNType(int type) { + m_dnType = type; + } + + /** + * Gets the type of format used for the DN (RFC format or OSF format). + *

+ * + * @return One of the following constants: DN.RFC + * (if the DN is in RFC format) or DN.OSF + * (if the DN is in OSF format). + * @see netscape.ldap.util.DN#setDNType + * @see netscape.ldap.util.DN#RFC + * @see netscape.ldap.util.DN#OSF + */ + public int getDNType() { + return m_dnType; + } + + /** + * Returns the number of components that make up the current DN. + * @return The number of components in this DN. + */ + public int countRDNs() { + return m_rdns.size(); + } + + /** + * Returns a list of the components (RDN objects) + * that make up the current DN. + * @return A list of the components of this DN. + * @see netscape.ldap.utils.RDN + */ + public Vector getRDNs() { + return m_rdns; + } + + /** + * Returns an array of the individual components that make up + * the current distinguished name. + * @param noTypes Specify true to remove the attribute type + * and equals sign (for example, "cn=") from each component. + */ + public String[] explodeDN(boolean noTypes) { + if (m_rdns.size() == 0) + return null; + String str[] = new String[m_rdns.size()]; + for (int i = 0; i < m_rdns.size(); i++) { + if (noTypes) + str[i] = ((RDN)m_rdns.elementAt(i)).getValue(); + else + str[i] = ((RDN)m_rdns.elementAt(i)).toString(); + } + return str; + } + + /** + * Determines if the DN is in RFC 1485 format. + * @return true if the DN is in RFC 1485 format. + */ + public boolean isRFC() { + return (m_dnType == RFC); + } + + /** + * Returns the DN in RFC 1485 format. + * @return The DN in RFC 1485 format. + */ + public String toRFCString() { + String dn = ""; + for (int i = 0; i < m_rdns.size(); i++) { + if (i != 0) + dn += ","; + dn = dn + ((RDN)m_rdns.elementAt(i)).toString(); + } + return dn; + } + + /** + * Returns the DN in OSF format. + * @return The DN in OSF format. + */ + public String toOSFString() { + String dn = ""; + for (int i = 0; i < m_rdns.size(); i++) { + if (i != 0) { + dn = "/" + dn; + } + RDN rdn = (RDN)m_rdns.elementAt(i); + dn = rdn.toString() + dn; + } + return dn; + } + + /** + * Returns the string representation of the DN + * in its original format. (For example, if the + * DN object was constructed from a DN + * in RFC 1485 format, this method returns the DN + * in RFC 1485 format. + * @return The string representation of the DN. + */ + public String toString() { + if (m_dnType == RFC) + return toRFCString(); + else + return toOSFString(); + } + + /** + * Determines if the given string is an distinguished name or + * not. + * @param dn distinguished name + * @return true or false + */ + public static boolean isDN(String dn) { + DN newdn = new DN(dn); + return (newdn.countRDNs() > 0); + } + + /** + * Determines if the current DN is equal to the specified DN. + * @param dn DN that you want to compare against the current DN. + * @return true if the two DNs are the same. + */ + public boolean equals(DN dn) { + return (dn.toRFCString().toUpperCase().equals(toRFCString().toUpperCase())); + } + + /** + * Gets the parent DN for this DN. + *

+ * + * For example, the following section of code gets the + * parent DN of "uid=bjensen, ou=People, o=Airius.com." + *

+     *    DN dn = new DN("uid=bjensen, ou=People, o=Airius.com");
+     *    DN parent = dn.getParent();
+     * 
+ * The parent DN in this example is "ou=People, o=Airius.com". + *

+ * + * @return DN of the parent of this DN. + */ + public DN getParent() { + DN newdn = new DN(); + for (int i = m_rdns.size() - 1; i > 0; i--) { + newdn.addRDN((RDN)m_rdns.elementAt(i)); + } + return newdn; + } + + /** + * Determines if the given DN is under the subtree defined by this DN. + *

+ * + * For example, the following section of code determines if the + * DN specified by dn1 is under the subtree specified + * by dn2. + *

+     *    DN dn1 = new DN("uid=bjensen, ou=People, o=Airius.com");
+     *    DN dn2 = new DN("ou=People, o=Airius.com");
+     *
+     *    boolean isContain = dn1.contains(dn2)
+     * 
+ * In this case, since "uid=bjensen, ou=People, o=Airius.com" + * is an entry under the subtree "ou=People, o=Airius.com", + * the value of isContain is true. + *

+ * + * @param dn The DN of a subtree that you want to check. + * @return true if the current DN belongs to the subtree + * specified by dn. + */ + public boolean contains(DN dn) { + + Vector rdns1 = dn.m_rdns; + + Vector rdns2 = this.m_rdns; + + for (int i=rdns1.size()-1,j=rdns2.size()-1; i>=0 && j>=0; i--, j--) { + RDN rdn1 = (RDN)rdns1.elementAt(i); + RDN rdn2 = (RDN)rdns2.elementAt(j); + if (!rdn2.equals(rdn1)) { + return false; + } + } + + return true; + } + + private boolean isRFC(String dn) { + int index =dn.indexOf(','); + /* Can't have the first or last character be the first unescaped comma */ + while ((index > 0) && (index < (dn.length() -1))) { + /* Found an unescaped comma */ + if (dn.charAt(index-1) != '\\') { + return true; + } + /* Found an escaped comma, keep searching */ + index=dn.indexOf(',',index+1); + } + return false; + } + + private boolean appendRDN(StringBuffer buffer) { + String rdn = new String(buffer); + if (RDN.isRDN(rdn)) { + m_rdns.addElement(new RDN(rdn)); + return true; + } + m_rdns.removeAllElements(); + return false; + } + + /** + * Array of the characters that may be escaped in a DN. + */ + public static final char[] ESCAPED_CHAR = {',', '+', '"', '\\', ';'}; +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/GetOpt.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/GetOpt.java new file mode 100644 index 00000000000..1217fed518c --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/GetOpt.java @@ -0,0 +1,234 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.util; +import java.util.*; + +/** + * This class is similar to the getopt() function in + * UNIX System V. You can use this class to parse command-line + * arguments. + *

+ * + * When you create an object of this class, you specify a string + * containing the command-line options that you want to check for. + * The string should contain the letters of these options. If an + * option requires an argument (for example, "-h "), + * you should add a colon after the letter in this string. + *

+ * + * For example, in the following string, the -h, + * -p, -D,, and -w options + * all require arguments. The -H option does not + * require any arguments. + *

+ * "h:p:D:w:H"
+ * 
+ * + * You can use the hasOption method to determine if + * an option has been specified and the getOptionParam + * method to get the argument specified after a particular option. + *

+ * + * If an option not specified in the string is passed in as an + * argument, the GetOpt object prints out an error + * message. Note that the object does not throw an exception or + * exit the application if an invalid option is specified. + *

+ * + * Note that you are still responsible for verifying that any + * required arguments have been specified. + *

+ * + * The following example parses the command-line arguments for + * the hostname, port number, DN, and password to use when + * connecting and authenticating to an LDAP server. + *

+ * import netscape.ldap.*;
+ * import netscape.ldap.controls.*;
+ * import netscape.ldap.util.*;
+ * import java.util.*;
+ *
+ * public class SearchDirectory {
+ *
+ *     public static void main( String[] args )
+ *     {
+ *
+ *         String usage = "Usage: java SearchDirectory -h  -p  "
+ *                      + "[-D ] [-w ]"
+ *
+ *         int portnumber = LDAPv2.DEFAULT_PORT;
+ *
+ *         // Check for these options. -H means to print out a usage message.
+ *         GetOpt options = new GetOpt( "h:p:D:w:H", args );
+ *
+ *         // Get the arguments specified for each option.
+ *         String hostname = options.getOptionParam( 'h' );
+ *         String port = options.getOptionParam( 'p' );
+ *         String bindDN = options.getOptionParam( 'D' );
+ *         String bindPW = options.getOptionParam( 'w' );
+ *
+ *         // Check to see if the hostname (which is mandatory)
+ *         // is not specified or if the user simply wants to
+ *         // see the usage message (-H).
+ *         if ( hostname == null || options.hasOption( 'H' ) ) {
+ *             System.out.println( usage );
+ *             System.exit( 1 );
+ *         }
+ *
+ *         // If a port number was specified, convert the port value
+ *         //  to an integer.
+ *         if ( port != null ) {
+ *             try {
+ *                 portnumber = java.lang.Integer.parseInt( port );
+ *             } catch ( java.lang.Exception e ) {
+ *                 System.out.println( "Invalid port number: " + port );
+ *                 System.out.println( usage );
+ *                 System.exit( 1 );
+ *             }
+ *         }
+ *
+ *         // Create a new connection.
+ *         LDAPConnection ld = new LDAPConnection();
+ *
+ *         try {
+ *             // Connect and authenticate to server.
+ *             ld.connect( 3, hostname, portnumber, bindDN, bindPW );
+ *             ...
+ *         } catch ( LDAPException e ) {
+ *             System.out.println( "Error: " + e.toString() );
+ *         }
+ *         ...
+ *     }
+ * }
+ * 
+ * + * @version 1.0 + */ +public class GetOpt { + /** + * Internal variables + */ + private int m_pos; + private String optarg; + private String m_control; + private Vector m_option; + private Vector m_ParameterList; + private Hashtable m_optionHashTable; + private Hashtable m_optionParamHashTable; + + /** + * Constructs a GetOpt object. + * @param strControl A string specifying the letters of + * all available options. If an option requires an argument + * (for example, "-h "), use a colon after the + * letter for that option (for example, "h:p:D:w:H"). + * @param args An array of strings representing the list + * of arguments that you want parsed (for example, the + * array passed into Main). + */ + public GetOpt(String strControl, String args[]) { + m_option = new Vector(); + m_control = strControl; + m_optionHashTable = new Hashtable(); + m_optionParamHashTable = new Hashtable(); + m_ParameterList = new Vector(); + + for (int i=0;i0) { + if ((sOpt.charAt(0)=='-') || + (sOpt.charAt(0)=='/')) { + if (sOpt.length()>1) { + int nIndex = m_control.indexOf(sOpt.charAt(1)); + if (nIndex == (-1)) { + System.err.println("Invalid usage. No option -" + + sOpt.charAt(1)); + } else { + char cOpt[]= new char[1]; + cOpt[0]= sOpt.charAt(1); + String sName = new String(cOpt); + m_optionHashTable.put(sName,"1"); + if ((m_control != null) && (m_control.length() > (nIndex+1))) { + if (m_control.charAt(nIndex+1)==':') { + i++; + if (i < args.length) + m_optionParamHashTable.put(sName,args[i]); + else + System.err.println("Missing argument for option "+ + sOpt); + } + } + } + } else { + System.err.println("Invalid usage."); + } + } else { + // probably parameters + m_ParameterList.addElement(args[i]); + } + } + } + } + + /** + * Determines if an option was specified. For example, + * hasOption( 'H' ) checks if the -H option + * was specified. + *

+ * + * @param c Letter of the option that you want to check. + * @return true if the option was specified. + */ + public boolean hasOption(char c) { + boolean fReturn = false; + char cOption[]=new char[1]; + cOption[0]=c; + String s = new String(cOption); + if (m_optionHashTable.get(s)=="1") { + fReturn = true; + } + return(fReturn); + } + + /** + * Gets the argument specified with an option. + * For example, getOptionParameter( 'h' ) + * gets the value of the argument specified with + * the -h option (such as "localhost" in "-h localhost"). + *

+ * + * @param c The letter of the option that you want to check. + * @return The argument specified for this option. + */ + public String getOptionParam(char c) { + char cOption[] = new char[1]; + cOption[0]=c; + String s = new String(cOption); + String sReturn=(String)m_optionParamHashTable.get(s); + return(sReturn); + } + + /** + * Gets a list of any additional parameters specified + * (not including the arguments for any options). + * @return A list of the additional parameters. + */ + public Vector getParameters() { + return(m_ParameterList); + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIF.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIF.java new file mode 100644 index 00000000000..a1056f8d876 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIF.java @@ -0,0 +1,518 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.util; + +import java.util.*; +import netscape.ldap.*; +import netscape.ldap.client.*; +import java.io.*; +import java.net.*; + +/** + * LDAP Data Interchange Format (LDIF) is a file format used to + * import and export directory data from an LDAP server and to + * describe a set of changes to be applied to data in a directory. + * This format is described in the Internet draft + * The LDAP Data Interchange Format (LDIF) - + * Technical Specification. + *

+ * + * This class implements an LDIF file parser. You can construct + * an object of this class to parse data in LDIF format and + * manipulate the data as individual LDIFRecord objects. + *

+ * + * @version 1.0 + * @see netscape.ldap.util.LDIFRecord + */ +public class LDIF { + + /** + * Internal constants + */ + private final static char COMMENT = '#'; + + /** + * Constructs an LDIF object to parse the + * LDAP data read from stdin. + * @exception IOException An I/O error has occurred. + */ + public LDIF() throws IOException { + DataInputStream ds = new DataInputStream(System.in); + BufferedReader d = new BufferedReader(new InputStreamReader(ds, "UTF8")); + m_reader = new LineReader(d); + m_source = "System.in"; + m_decoder = new MimeBase64Decoder(); + } + + /** + * Constructs an LDIF object to parse the + * LDIF data read from a specified file. + * @param file The name of the LDIF file that you want to parse. + * @exception IOException An I/O error has occurred. + */ + public LDIF(String file) throws IOException { + FileInputStream fs = new FileInputStream(file); + DataInputStream ds = new DataInputStream(fs); + BufferedReader d = new BufferedReader(new InputStreamReader(ds, "UTF8")); + m_reader = new LineReader(d); + m_source = file; + m_decoder = new MimeBase64Decoder(); + } + + /** + * Constructs an LDIF object to parse the + * LDIF data read from an input stream. + * @param ds The input stream providing the LDIF data. + * @exception IOException An I/O error has occurred. + */ + public LDIF(DataInputStream ds) throws IOException { + BufferedReader d = new BufferedReader(new InputStreamReader(ds, "UTF8")); + m_reader = new LineReader(d); + m_source = ds.toString(); + } + + /** + * Returns the next record in the LDIF data. You can call this + * method repeatedly to iterate through all records in the LDIF data. + *

+ * + * @return The next record as an LDIFRecord + * object or null if there are no more records. + * @exception IOException An I/O error has occurred. + * @see netscape.ldap.util.LDIFRecord + */ + public LDIFRecord nextRecord() throws IOException { + /* TBD: parse the version number */ + if ( m_done ) + return null; + else + return parse_ldif_record( m_reader ); + } + + /** + * Parses ldif content. The list of attributes is + * terminated by \r\n or '-'. This function is + * also used to parse the attributes in modifications. + * @param ds data input stream + */ + private LDIFRecord parse_ldif_record(LineReader d) + throws IOException { + String line = null; + String dn = null; + Vector attrs = new Vector(); + LDIFRecord rec = null; + + line = d.readLine(); + if (line == null) { + return null; + } + + if (!line.startsWith("dn:")) + throw new IOException("no dn found in <" + line + ">"); + dn = line.substring(3).trim(); + if (dn.startsWith(":") && (dn.length() > 1)) { + String substr = dn.substring(1).trim(); + dn = new String(getDecodedBytes(substr), "UTF8"); + } + + LDIFContent content = parse_ldif_content(d); + rec = new LDIFRecord(dn, content); + return rec; + } + + /** + * Parses ldif content. The list of attributes is + * terminated by \r\n or '-'. This function is + * also used to parse the attributes in modifications. + * @param ds data input stream + */ + private LDIFContent parse_ldif_content(LineReader d) + throws IOException { + String line = d.readLine(); + if ((line == null) || (line.length() < 1) || (line.equals("-"))) { + // if this is empty line, then we finish reading all the info for + // the current entry + if ((line != null) && (line.length() < 1)) + m_currEntryDone = true; + return null; + } + + if (line.startsWith("changetype:")) { + /* handles (changerecord) */ + String changetype = line.substring(11).trim(); + if (changetype.equals("modify")) { + LDIFModifyContent mc = parse_mod_spec(d); + return mc; + } else if (changetype.equals("add")) { + LDIFAddContent ac = parse_add_spec(d); + return ac; + } else if (changetype.equals("delete")) { + LDIFDeleteContent dc = parse_delete_spec(d); + return dc; + } else if (changetype.equals("moddn") || + changetype.equals("modrdn")) { + LDIFModDNContent mdnc = parse_moddn_spec(d); + return mdnc; + } else + throw new IOException("change type not supported"); + } else { + /* handles 1*(attrval-spec) */ + Hashtable ht = new Hashtable(); + String newtype; + Object val; + LDAPAttribute newAttr = null; + do { + int len = line.length(); + if ( len < 1 ) + break; + int idx = line.indexOf(':'); + /* Must have a colon */ + if (idx == -1) + throw new IOException("no ':' found in <" + line + ">"); + /* attribute type */ + newtype = line.substring(0,idx).toLowerCase(); + val = ""; + /* Could be :: for binary */ + idx++; + if ( len > idx ) { + if ( line.charAt(idx) == ':' ) { + idx++; + String substr = line.substring(idx).trim(); + val = getDecodedBytes(substr); + } else if (line.charAt(idx) == '<') { + try { + URL url = new URL(line.substring(idx+1).trim()); + String filename = url.getFile(); + val = getFileContent(filename); + } catch (MalformedURLException ex) { + throw new IOException("Exception: cannot construct url "+ + line.substring(idx+1).trim()); + } + } else { + val = line.substring(idx).trim(); + } + } + /* Is there a previous value for this attribute? */ + newAttr = (LDAPAttribute)ht.get( newtype ); + if ( newAttr == null ) { + newAttr = new LDAPAttribute( newtype ); + } + if ( val instanceof String ) { + newAttr.addValue( (String)val ); + } else { + newAttr.addValue( (byte[])val ); + } + ht.put( newtype, newAttr ); + + line = d.readLine(); + if (line == null || (line.length() < 1) || (line.equals("-"))) { + if ((line != null) && (line.length() < 1)) + m_currEntryDone = true; + break; + } + } while ( true ); + Enumeration en = ht.elements(); + LDIFAttributeContent ac = new LDIFAttributeContent(); + while( en.hasMoreElements() ) { + ac.addElement( (LDAPAttribute)en.nextElement() ); + } + ht.clear(); + ht = null; + + return ac; + } + } + + private byte[] getDecodedBytes(String line) { + ByteBuf inBuf = new ByteBuf(line); + ByteBuf decodedBuf = new ByteBuf(); + /* Translate from base 64 */ + m_decoder.translate( inBuf, decodedBuf ); + return decodedBuf.toBytes(); + } + + private byte[] getFileContent(String url) throws IOException { + StringTokenizer tokenizer = new StringTokenizer(url, "|"); + String filename = url; + int num = tokenizer.countTokens(); + if (num == 2) { + String token = (String)tokenizer.nextElement(); + int index = token.lastIndexOf("/"); + String drive = token.substring(index+1); + token = (String)tokenizer.nextElement(); + token = token.replace('/', '\\'); + filename = drive+":"+token; + } + + File file = new File(filename); + byte[] b = new byte[(int)file.length()]; + FileInputStream fi = new FileInputStream(filename); + fi.read(b); + return b; + } + + /** + * Parses add content + * @param ds data input stream + */ + private LDIFAddContent parse_add_spec(LineReader d) + throws IOException { + LDIFAttributeContent ac = (LDIFAttributeContent)parse_ldif_content(d); + if (m_currEntryDone) + m_currEntryDone = false; + LDAPAttribute attrs[] = ac.getAttributes(); + LDIFAddContent rc = new LDIFAddContent(attrs); + return rc; + } + + /** + * Parses delete content + * @param ds data input stream + */ + private LDIFDeleteContent parse_delete_spec(LineReader d) + throws IOException { + String line = d.readLine(); + if (line == null || line.equals("")) { + LDIFDeleteContent dc = new LDIFDeleteContent(); + return dc; + } else + throw new IOException("invalid SEP" ); + } + + /** + * Parses change modification. + * @param ds data input stream + */ + private LDIFModifyContent parse_mod_spec(LineReader d) + throws IOException { + + String line = null; + line = d.readLine(); + LDIFModifyContent mc = new LDIFModifyContent(); + do { + int oper = -1; + if (line.startsWith("add:")) { + oper = LDAPModification.ADD; + } else if (line.startsWith("delete:")) { + oper = LDAPModification.DELETE; + } else if (line.startsWith("replace:")) { + oper = LDAPModification.REPLACE; + } else + throw new IOException("unknown modify type"); + + LDIFAttributeContent ac = + (LDIFAttributeContent)parse_ldif_content(d); + if (ac != null) { + LDAPAttribute attrs[] = ac.getAttributes(); + for (int i = 0; i < attrs.length; i++) { + LDAPModification mod = new LDAPModification(oper, attrs[i]); + mc.addElement( mod ); + } + // if there is no attrval-spec, go into the else statement + } else { + int index = line.indexOf(":"); + if (index == -1) + throw new IOException("colon missing in "+line); + + String attrName = line.substring(index+1).trim(); + + if (oper == LDAPModification.ADD) + throw new IOException("add operation needs the value for attribute "+attrName); + LDAPAttribute attr = new LDAPAttribute(attrName); + LDAPModification mod = new LDAPModification(oper, attr); + mc.addElement(mod); + } + if (m_currEntryDone) { + m_currEntryDone = false; + break; + } + line = d.readLine(); + } while (line != null && !line.equals("")); + + return mc; + } + + /** + * Parses moddn/modrdn modification + * @param d data input stream + */ + private LDIFModDNContent parse_moddn_spec(LineReader d) + throws IOException { + String line = null; + line = d.readLine(); + LDIFModDNContent mc = new LDIFModDNContent(); + String val = null; + do { + if (line.startsWith("newrdn:") && + (line.length() > ("newrdn:".length()+1))) { + mc.setRDN(line.substring("newrdn:".length()).trim()); + } else if (line.startsWith("deleteoldrdn:") && + (line.length() > ("deleteoldrdn:".length()+1))) { + String str = line.substring("deleteoldrdn:".length()).trim(); + if (str.equals("0")) + mc.setDeleteOldRDN(false); + else if (str.equals("1")) + mc.setDeleteOldRDN(true); + else + throw new IOException("Incorrect input for deleteOldRdn "); + } else if (line.startsWith("newsuperior:") && + (line.length() > ("newsuperior:".length()+1))) { + mc.setNewParent(line.substring("newsuperior:".length()).trim()); + } + line = d.readLine(); + } while (line != null && !line.equals("")); + + return mc; + } + + /** + * Return true if all the bytes in the given array are valid for output as a + * String according to the LDIF specification. If not, the array should + * output base64-encoded. + * @return true if all the bytes in the given array are valid for output as a + * String according to the LDIF specification; otherwise, false. + * false. + */ + public static boolean isPrintable(byte[] b) { + for( int i = b.length - 1; i >= 0; i-- ) { + if ( (b[i] < ' ') || (b[i] > 127) ) { + if ( b[i] != '\t' ) + return false; + } + } + return true; + } + + /** + * Outputs the String in LDIF line-continuation format. No line will be longer + * than the given max. A continuation line starts with a single blank space. + * @param pw The printer writer. + * @param value The given string being printed out. + * @param max The maximum characters allowed in the line. + */ + public static void breakString( PrintWriter pw, String value, int max) { + int leftToGo = value.length(); + int written = 0; + int maxChars = max; + /* Limit to 77 characters per line */ + while( leftToGo > 0 ) { + int toWrite = Math.min( maxChars, leftToGo ); + String s = value.substring( written, written+toWrite); + if ( written != 0 ) { + pw.print( " " + s ); + } else { + pw.print( s ); + maxChars -= 1; + } + written += toWrite; + leftToGo -= toWrite; + /* Don't use pw.println, because it outputs an extra CR + in Win32 */ + pw.print( '\n' ); + } + } + + /** + * Gets the version of LDIF used in the data. + * @return Version of LDIF used in the data. + */ + public int getVersion() { + return m_version; + } + + /** + * Gets the string representation of the + * entire LDIF file. + * @return The string representation of the entire LDIF data. + */ + public String toString() { + return "LDIF {" + m_source + "}"; + } + + /** + * Internal variables + */ + private int m_version = 1; + private boolean m_done = false; + private LineReader m_reader = null; + private String m_source = null; + private MimeBase64Decoder m_decoder = null; + private boolean m_currEntryDone = false; + + /* Concatenate continuation lines, if present */ + class LineReader { + LineReader( BufferedReader d ) { + _d = d; + } + /** + * Reads a non-comment line. + * @return A string, or null + */ + String readLine() throws IOException { + String line = null; + String result = null; + do { + /* Leftover line from last time? */ + if ( _next != null ) { + line = _next; + _next = null; + } else { + line = _d.readLine(); + } + if (line != null) { + /* Empty line means end of record */ + if( line.length() < 1 ) { + if ( result == null ) + result = line; + else { + _next = line; + break; + } + } else if( line.charAt(0) == COMMENT ) { + /* Ignore comment lines */ + } else if( line.charAt(0) != ' ' ) { + /* Not a continuation line */ + if( result == null ) { + result = line; + } else { + _next = line; + break; + } + } else { + /* Continuation line */ + if ( result == null ) + throw new IOException("continuation out of " + + "nowhere <" + + line + ">"); + result += line.substring(1); + } + } else { + /* End of file */ + break; + } + } while ( true ); + if ( line == null ) + m_done = true; + return result; + } + private BufferedReader _d; + String _next = null; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFAddContent.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFAddContent.java new file mode 100644 index 00000000000..663dbeba809 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFAddContent.java @@ -0,0 +1,90 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.util; + +import java.util.*; +import netscape.ldap.*; +import netscape.ldap.client.*; +import java.io.*; + +/** + * + * An object of this class represents the content of an LDIF record that + * specifies a new entry to be added. This class implements the + * LDIFContent interface. + *

+ * + * To get this object from an LDIFRecord object, + * use the getContent method and cast the return value as + * LDIFAddContent. + *

+ * + * @version 1.0 + * @see netscape.ldap.util.LDIFRecord#getContent + */ +public class LDIFAddContent implements LDIFContent { + + /** + * Internal variables + */ + private LDAPAttribute m_attrs[] = null; + + /** + * Constructs a new LDIFAddContent object with + * the specified attributes. + * @param attrs An array of LDAPAttribute objects + * representing the attributes of the entry to be added. + */ + public LDIFAddContent(LDAPAttribute attrs[]) { + m_attrs = attrs; + } + + /** + * Returns the content type. You can use this with the + * getContent method of the LDIFRecord + * object to determine the type of content specified in the record. + * @return The content type (which is + * LDIFContent.ADD_CONTENT). + * @see netscape.ldap.util.LDIFRecord#getContent + */ + public int getType() { + return ADD_CONTENT; + } + + /** + * Retrieves the list of the attributes specified in the content + * of the LDIF record. + * @return An array of LDAPAttribute objects that + * represent the attributes specified in the content of the LDIF record. + */ + public LDAPAttribute[] getAttributes() { + return m_attrs; + } + + /** + * Returns the string representation of the content of the LDIF record. + * @return The string representation of the content of the LDIF record. + */ + public String toString() { + String s = ""; + for (int i = 0; i < m_attrs.length; i++) { + s = s + m_attrs[i].toString(); + } + return "LDIFAddContent {" + s + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFAttributeContent.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFAttributeContent.java new file mode 100644 index 00000000000..9e2fe3097fb --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFAttributeContent.java @@ -0,0 +1,100 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.util; + +import java.util.*; +import java.io.*; +import netscape.ldap.*; +import netscape.ldap.client.*; + +/** + * An object of this class represents the content of an LDIF record that + * specifies an entry and its attributes. This class implements the + * LDIFContent interface. + *

+ * + * To get this object from an LDIFRecord object, + * use the getContent method and cast the return value as + * LDIFAttributeContent. + *

+ * + * @version 1.0 + * @see netscape.ldap.util.LDIFRecord#getContent + */ +public class LDIFAttributeContent implements LDIFContent { + + /** + * Internal variables + */ + private Vector m_attrs = new Vector(); + + /** + * Constructs an empty LDIFAttributeContent object with + * no attributes specified. You can use the addElement + * method to add attributes to this object. + * @see netscape.ldap.util.LDIFAttributeContent#addElement + */ + public LDIFAttributeContent() { + } + + /** + * Returns the content type. You can use this with the + * getContent method of the LDIFRecord + * object to determine the type of content specified in the record. + * @return The content type (which is + * LDIFContent.ATTRIBUTE_CONTENT). + * @see netscape.ldap.util.LDIFRecord#getContent + */ + public int getType() { + return ATTRIBUTE_CONTENT; + } + + /** + * Adds an attribute to the content of the LDIF record. + * @param attr The attribute that you want to add. + */ + public void addElement(LDAPAttribute attr) { + m_attrs.addElement(attr); + } + + /** + * Retrieves the list of the attributes specified in the content + * of the LDIF record. + * @return An array of LDAPAttribute objects that + * represent the attributes specified in the content of the LDIF record. + */ + public LDAPAttribute[] getAttributes() { + LDAPAttribute attrs[] = new LDAPAttribute[m_attrs.size()]; + for (int i = 0; i < m_attrs.size(); i++) { + attrs[i] = (LDAPAttribute)m_attrs.elementAt(i); + } + return attrs; + } + + /** + * Returns the string representation of the content of the LDIF record. + * @return The string representation of the content of the LDIF record. + */ + public String toString() { + String s = ""; + for (int i = 0; i < m_attrs.size(); i++) { + s = s + ((LDAPAttribute)m_attrs.elementAt(i)).toString(); + } + return "LDIFAttributeContent {" + s + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFContent.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFContent.java new file mode 100644 index 00000000000..1730f07613a --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFContent.java @@ -0,0 +1,100 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.util; + +import java.util.*; +import netscape.ldap.client.*; +import java.io.*; + +/** + * This interface represents the content of an LDIF record. + * An LDIF record can specify an entry or modifications to be + * made to an entry. + *

+ * + * The following classes implement this interface: + *

+ * + *

    + *
  • LDIFAttributeContent (represents the content + * of an LDIF record that specifies an entry) + *
  • LDIFAddContent (represents the content + * of an LDIF record that adds a new entry) + *
  • LDIFModifyContent (represents the content + * of an LDIF record that modifies an entry) + *
  • LDIFDeleteContent (represents the content + * of an LDIF record that deletes an entry) + *
  • LDIFModDNContent (represents the content + * of an LDIF record that changes the RDN or DN of an entry) + *
+ *

+ * + * @version 1.0 + * @see netscape.ldap.LDIFRecord + * @see netscape.ldap.LDIFAttrContent + * @see netscape.ldap.LDIFAddContent + * @see netscape.ldap.LDIFModifyContent + * @see netscape.ldap.LDIFDeleteContent + * @see netscape.ldap.LDIFModDNContent + */ +public interface LDIFContent { + + /** + * The LDIF record specifies an entry and its attributes. + */ + public final static int ATTRIBUTE_CONTENT = 0; + + /** + * The LDIF record specifies a new entry to be added. + */ + public final static int ADD_CONTENT = 1; + + /** + * The LDIF record specifies an entry to be deleted. + */ + public final static int DELETE_CONTENT = 2; + + /** + * The LDIF record specifies modifications to an entry. + */ + public final static int MODIFICATION_CONTENT = 3; + + /** + * The LDIF record specifies changes to the DN or RDN of an entry. + */ + public final static int MODDN_CONTENT = 4; + + /** + * Determine the content type. + * @return The content type, identified by one of the following values: + *

    + *
  • ATTRIBUTE_CONTENT (specifies an entry and its attributes) + *
  • ADD_CONTENT (specifies a new entry to be added) + *
  • DELETE_CONTENT (specifies an entry to be deleted) + *
  • MODIFICATION_CONTENT (specifies an entry to be modified) + *
  • MODDN_CONTENT (specifies a change to the RDN or DN of an entry) + *
+ */ + public int getType(); + + /** + * Returns the string representation of the content of the LDIF record. + * @return String representation of the content of the LDIF record. + */ + public String toString(); +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFDeleteContent.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFDeleteContent.java new file mode 100644 index 00000000000..74cc1855482 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFDeleteContent.java @@ -0,0 +1,67 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.util; + +import java.util.*; +import netscape.ldap.client.*; +import java.io.*; + +/** + * An object of this class represents the content of an LDIF record that + * specifies the deletion of an entry. This class implements the + * LDIFContent interface. + *

+ * + * To get this object from an LDIFRecord object, + * use the getContent method and cast the return value as + * LDIFDeleteContent. + *

+ * + * @version 1.0 + * @see netscape.ldap.util.LDIFRecord#getContent + */ +public class LDIFDeleteContent implements LDIFContent { + /** + * Constructs an LDIFDeleteContent object + * to specify that an entry should be deleted. (The DN + * identifying the entry is part of the LDIFRecord + * object. + */ + public LDIFDeleteContent() { + } + + /** + * Returns the content type. You can use this with the + * getContent method of the LDIFRecord + * object to determine the type of content specified in the record. + * @return The content type (which is + * LDIFContent.DELETE_CONTENT). + * @see netscape.ldap.util.LDIFRecord#getContent + */ + public int getType() { + return DELETE_CONTENT; + } + + /** + * Returns the string representation of the content of the LDIF record. + * @return The string representation of the content of the LDIF record. + */ + public String toString() { + return "LDIFDeleteContent {}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFModDNContent.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFModDNContent.java new file mode 100644 index 00000000000..921f999b755 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFModDNContent.java @@ -0,0 +1,153 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.util; + +import java.util.*; +import java.io.*; +import netscape.ldap.*; +import netscape.ldap.client.*; + +/** + * An object of this class represents the content of an LDIF record that + * specifies changes to an RDN or the DN of an entry. This class + * implements the LDIFContent interface. + *

+ * + * To get this object from an LDIFRecord object, + * use the getContent method and cast the return value as + * LDIFModDNContent. + *

+ * + * @version 1.0 + * @see netscape.ldap.util.LDIFRecord#getContent + */ +public class LDIFModDNContent implements LDIFContent { + /** + * Internal variables + */ + private String m_newParent = null; + private String m_rdn = null; + private boolean m_deleteOldRDN = false; + + /** + * Constructs an empty LDIFModDNContent object. + * To specify the modifications to be made to the entry, use + * the setRDN, setNewParent, + * and setDeleteOldRDN methods. + * @see netscape.ldap.util.LDIFModDNContent#setRDN + * @see netscape.ldap.util.LDIFModDNContent#setNewParent + * @see netscape.ldap.util.LDIFModDNContent#setDeleteOldRDN + */ + public LDIFModDNContent() { + } + + /** + * Returns the content type. You can use this with the + * getContent method of the LDIFRecord + * object to determine the type of content specified in the record. + * @return The content type (which is + * LDIFContent.MODDN_CONTENT). + * @see netscape.ldap.util.LDIFRecord#getContent + */ + public int getType() { + return MODDN_CONTENT; + } + + /** + * Sets the new RDN that should be assigned to the entry. + * @param rdn The new RDN. + * @see netscape.ldap.util.LDIFModDNContent#getRDN + */ + public void setRDN(String rdn) { + m_rdn = rdn; + } + + /** + * Returns the new RDN specified in the content of the LDIF record. + * @return the new RDN. + * @see netscape.ldap.util.LDIFModDNContent#setRDN + */ + public String getRDN() { + return m_rdn; + } + + /** + * Sets the new parent DN that should be assigned to the entry. + * @param parent The new parent DN for the entry. + * @see netscape.ldap.util.LDIFModDNContent#getNewParent + */ + public void setNewParent(String parent) { + m_newParent = parent; + } + + /** + * Returns the entry's new parent DN, if specified in the content + * of the LDIF record. + * @return The new parent for the entry. + * @see netscape.ldap.util.LDIFModDNContent#setNewParent + */ + public String getNewParent() { + return m_newParent; + } + + /** + * Sets whether or not the old RDN should be removed as an + * attribute in the entry. + * @param bool If true, remove the attribute representing + * the RDN. If false, leave the attribute in the entry. + * @see netscape.ldap.util.LDIFModDNContent#getDeleteOldRDN + */ + public void setDeleteOldRDN(boolean bool) { + m_deleteOldRDN = bool; + } + + /** + * Determines if the content of the LDIF record specifies that + * the old RDN should be removed as an attribute in the entry. + * @return If true, the change specifies that the + * the attribute representing the RDN should be removed. + * If false, the change specifies that the attribute + * should be left in the entry. + * @see netscape.ldap.util.LDIFModDNContent#setDeleteOldRDN + */ + public boolean getDeleteOldRDN() { + return m_deleteOldRDN; + } + + /** + * Returns string representation of the content of the LDIF record. + * @return The string representation of the content of the LDIF record. + */ + public String toString() { + String s = ""; + if (m_newParent == null) + s = s + "new parent() "; + else + s = s + "new parent( "+m_newParent+" ), "; + if (m_deleteOldRDN) + s = s + "deleteOldRDN( true ), "; + else + s = s + "deleteOldRDN( false ), "; + if (m_rdn == null) + s = s + "new rdn()"; + else + s = s + "new rdn( "+m_rdn+" )"; + + return "LDIFModDNContent {" + s + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFModifyContent.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFModifyContent.java new file mode 100644 index 00000000000..1d30e583a38 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFModifyContent.java @@ -0,0 +1,103 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.util; + +import java.util.*; +import java.io.*; +import netscape.ldap.*; +import netscape.ldap.client.*; + +/** + * An object of this class represents the content of an LDIF record that + * specifies modifications to an entry. This class implements the + * LDIFContent interface. + *

+ * + * To get this object from an LDIFRecord object, + * use the getContent method and cast the return value as + * LDIFModifyContent. + *

+ * + * @version 1.0 + * @see netscape.ldap.util.LDIFRecord#getContent + */ +public class LDIFModifyContent implements LDIFContent { + /** + * Internal variables + */ + private Vector m_mods = new Vector(); + + /** + * Constructs an empty LDIFModifyContent object. + * To specify the modifications to be made to the entry, use + * the addElement method. + * @see netscape.ldap.util.LDIFModifyContent#addElement + */ + public LDIFModifyContent() { + } + + /** + * Returns the content type. You can use this with the + * getContent method of the LDIFRecord + * object to determine the type of content specified in the record. + * @return The content type (which is + * LDIFContent.MODIFICATION_CONTENT). + * @see netscape.ldap.util.LDIFRecord#getContent + */ + public int getType() { + return MODIFICATION_CONTENT; + } + + /** + * Specifies an additional modification that should be made to + * the entry. + * @param mod LDAPModification object representing + * the change to be made to the entry. + * @see netscape.ldap.LDAPModification + */ + public void addElement(LDAPModification mod) { + m_mods.addElement(mod); + } + + /** + * Retrieves the list of the modifications specified in the content + * of the LDIF record. + * @return An array of LDAPModification objects that + * represent the modifications specified in the content of the LDIF record. + * @see netscape.ldap.LDAPModification + */ + public LDAPModification[] getModifications() { + LDAPModification mods[] = new LDAPModification[m_mods.size()]; + for (int i = 0; i < m_mods.size(); i++) { + mods[i] = (LDAPModification)m_mods.elementAt(i); + } + return mods; + } + + /** + * Returns the string representation of the content of the LDIF record. + * @return The string representation of the content of the LDIF record. + */ + public String toString() { + String s = ""; + for (int i = 0; i < m_mods.size(); i++) { + s = s + ((LDAPModification)m_mods.elementAt(i)).toString(); + } + return "LDIFModifyContent {" + s + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFRecord.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFRecord.java new file mode 100644 index 00000000000..2b59ae4ba33 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/LDIFRecord.java @@ -0,0 +1,183 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.util; + +import java.util.*; +import netscape.ldap.client.*; +import java.io.*; + +/** + * An object of this class represents an LDIF record in an LDIF + * file (or in LDIF data). A record can contain a list of attributes + * (which describes an entry) or a list of modifications (which + * decribes the changes that need to be made to an entry). + * Each record also has a distinguished name. + *

+ * + * You can get an LDIFRecord object from LDIF data + * by calling the nextRecord method of the + * LDIF object holding the data. + *

+ * + * If you are constructing a new LDIFRecord object, + * you can specify the content of the record in one of the + * following ways: + *

+ * + *

    + *
  • To create a record that specifies an entry, use an object of + * the LDIFAttributeContent class. + *
  • To create a record that specifies a modification to be made, + * use an object of one of the following classes: + *
      + *
    • Use LDIFAddContent to add a new entry. + *
    • Use LDIFModifyContent to modify an entry. + *
    • Use LDIFDeleteContent to delete an entry. + *
    + *
+ *

+ * + * @version 1.0 + * @see netscape.ldap.util.LDIF + * @see netscape.ldap.util.LDIFAddContent + * @see netscape.ldap.util.LDIFModifyContent + * @see netscape.ldap.util.LDIFDeleteContent + * @see netscape.ldap.util.LDIFAttributeContent + */ +public class LDIFRecord { + + /** + * Internal variables + */ + private String m_dn = null; + private LDIFContent m_content = null; + + /** + * Constructs a new LDIFRecord object with the + * specified content. + * @param dn Distinguished name of the entry associated with + * the record. + * @param content Content of the LDIF record. You can specify + * an object of the LDIFAttributeContent, + * LDIFAddContent, LDIFModifyContent, + * or LDIFDeleteContent classes. + * @see netscape.ldap.util.LDIFAddContent + * @see netscape.ldap.util.LDIFModifyContent + * @see netscape.ldap.util.LDIFDeleteContent + * @see netscape.ldap.util.LDIFAttributeContent + */ + public LDIFRecord(String dn, LDIFContent content) { + m_dn = dn; + m_content = content; + } + + /** + * Retrieves the distinguished name of the LDIF record. + * @return The distinguished name of the LDIF record. + */ + public String getDN() { + return m_dn; + } + + /** + * Retrieves the content of the LDIF record. The content is + * an object of the LDIFAttributeContent, + * LDIFAddContent, LDIFModifyContent, + * or LDIFDeleteContent classes. + *

+ * + * To determine the class of the object, use the getType + * method of that object. getType returns one of + * the following values: + *

    + *
  • LDIFContent.ATTRIBUTE_CONTENT (the object is an + * LDIFAttributeContent object) + *
  • LDIFContent.ADD_CONTENT (the object is an + * LDIFAddContent object) + *
  • LDIFContent.MODIFICATION_CONTENT (the object is an + * LDIFModifyContent object) + *
  • LDIFContent.DELETE_CONTENT (the object is an + * LDIFDeleteContent object) + *
+ *

+ * + * For example: + *

+     * ...
+     * import netscape.ldap.*;
+     * import netscape.ldap.util.*;
+     * import java.io.*;
+     * import java.util.*;
+     * ...
+     *     try {
+     *         // Parse the LDIF file test.ldif.
+     *         LDIF parser = new LDIF( "test.ldif" );
+     *         // Iterate through each LDIF record in the file.
+     *         LDIFRecord nextRec = parser.nextRecord();
+     *         while ( nextRec != null ) {
+     *             // Based on the type of content in the record,
+     *             // get the content and cast it as the appropriate
+     *             // type.
+     *             switch( nextRec.getContent().getType() ) {
+     *                 case LDIFContent.ATTRIBUTE_CONTENT:
+     *                     LDIFAttributeContent attrContent =
+     *                         (LDIFAttributeContent)nextRec.getContent();
+     *                     break;
+     *                 case LDIFContent.ADD_CONTENT:
+     *                     LDIFAddContent addContent =
+     *                         (LDIFAddContent)nextRec.getContent();
+     *                     break;
+     *                 case LDIFContent.MODIFICATION_CONTENT:
+     *                     LDIFModifyContent modifyContent =
+     *                         (LDIFModifyContent)nextRec.getContent();
+     *                     break;
+     *                 case LDIFContent.DELETE_CONTENT:
+     *                     LDIFDeleteContent deleteContent =
+     *                         (LDIFDeleteContent)nextRec.getContent();
+     *                     break;
+     *             }
+     *             ...
+     *             // Iterate through each record.
+     *             nextRec = parser.nextRecord();
+     *         }
+     *     } catch ( IOException e ) {
+     *         System.out.println( "Error: " + e.toString() );
+     *         System.exit(1);
+     *     }
+     * ...
+     * 
+ * + * @return The content of the LDIF record. + * @see netscape.ldap.util.LDIFAddContent + * @see netscape.ldap.util.LDIFModifyContent + * @see netscape.ldap.util.LDIFDeleteContent + * @see netscape.ldap.util.LDIFAttributeContent + */ + public LDIFContent getContent() { + return m_content; + } + + /** + * Gets the string representation of the LDIFRecord + * object. + * @return The string representation of the LDIF record. + */ + public String toString() { + return "LDIFRecord {dn=" + m_dn + ", content=" + m_content + "}"; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/MimeBase64Decoder.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/MimeBase64Decoder.java new file mode 100644 index 00000000000..de50034c708 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/MimeBase64Decoder.java @@ -0,0 +1,173 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.util; + +/** Implements a plaintext -> Base64 encoder. + */ +public final class MimeBase64Decoder extends MimeEncoder { + + private byte token[] = new byte[4]; // input buffer + private byte bytes[] = new byte[3]; // output buffer + private int token_length = 0; // input buffer length + + static private final byte NUL = 127; // must be out of range 0-64 + static private final byte EOF = 126; // must be out of range 0-64 + + static private final byte map[] = { + NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, // 000-007 + NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, // 010-017 + NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, // 020-027 + NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, // 030-037 + NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, // 040-047 !"#$%&' + NUL, NUL, NUL, 62, NUL, NUL, NUL, 63, // 050-057 ()*+,-./ + 52, 53, 54, 55, 56, 57, 58, 59, // 060-067 01234567 + 60, 61, NUL, NUL, NUL, EOF, NUL, NUL, // 070-077 89:;<=>? + + NUL, 0, 1, 2, 3, 4, 5, 6, // 100-107 @ABCDEFG + 7, 8, 9, 10, 11, 12, 13, 14, // 110-117 HIJKLMNO + 15, 16, 17, 18, 19, 20, 21, 22, // 120-127 PQRSTUVW + 23, 24, 25, NUL, NUL, NUL, NUL, NUL, // 130-137 XYZ[\]^_ + NUL, 26, 27, 28, 29, 30, 31, 32, // 140-147 `abcdefg + 33, 34, 35, 36, 37, 38, 39, 40, // 150-157 hijklmno + 41, 42, 43, 44, 45, 46, 47, 48, // 160-167 pqrstuvw + 49, 50, 51, NUL, NUL, NUL, NUL, NUL, // 170-177 xyz{|}~ + + NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, // 200-207 + NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, // 210-217 + NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, // 220-227 + NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, // 230-237 + NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, // 240-247 + NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, // 250-257 + NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, // 260-267 + NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, // 270-277 + + NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, // 300-307 + NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, // 310-317 + NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, // 320-327 + NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, // 330-337 + NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, // 340-347 + NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, // 350-357 + NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, // 360-367 + NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, // 370-377 + }; + + + // Fast routine that assumes full 4-char tokens with no '=' in them. + // + private final void decode_token(ByteBuf out) { + int num = ((map[token[0]] << 18) | + (map[token[1]] << 12) | + (map[token[2]] << 6) | + (map[token[3]])); + + bytes[0] = (byte) (0xFF & (num >> 16)); + bytes[1] = (byte) (0xFF & (num >> 8)); + bytes[2] = (byte) (0xFF & num); + + out.append(bytes); + } + + + // Hairier routine that deals with the final token, which can have fewer + // than four characters, and that might be padded with '='. + // + private final void decode_final_token(ByteBuf out) { + + byte b0 = map[token[0]]; + byte b1 = map[token[1]]; + byte b2 = map[token[2]]; + byte b3 = map[token[3]]; + + int eq_count = 0; + + if (b0 == EOF) { b0 = 0; eq_count++; } + if (b1 == EOF) { b1 = 0; eq_count++; } + if (b2 == EOF) { b2 = 0; eq_count++; } + if (b3 == EOF) { b3 = 0; eq_count++; } + + int num = ((b0 << 18) | (b1 << 12) | (b2 << 6) | (b3)); + + // eq_count will be 0, 1, or 2. + // No "=" padding means 4 bytes mapped to 3, the normal case, + // not handled in this routine. + // "xxx=" means 3 bytes mapped to 2. + // "xx==" means 2 bytes mapped to 1. + // "x===" can't happen, because "x" would then be encoding + // only 6 bits, not 8, the minimum possible. + + out.append((byte) (num >> 16)); // byte 1, count = 0 or 1 or 2 + if (eq_count <= 1) { + out.append((byte) ((num >> 8) & 0xFF)); // byte 2, count = 0 or 1 + if (eq_count == 0) { + out.append((byte) (num & 0xFF)); // byte 3, count = 0 + } + } + } + + + /** Given a sequence of input bytes using the Base64 encoding, produces a + sequence of unencoded output bytes. Note that some (small) amount of + buffering may be necessary, if the input byte stream didn't fall on an + appropriate boundary. If there are bytes in `out' already, the new + bytes are appended, so the caller should do `out.setLength(0)' first + if that's desired. + */ + public final void translate(ByteBuf in, ByteBuf out) { + + if (token == null) // already saw eof marker? + return; + + byte inb[] = in.toBytes(); + int in_length = in.length(); + + for (int i = 0; i < in_length; i++) { + byte b = inb[i]; + int x=(b&0xff); + byte t = map[x]; + + if (t != NUL) + token[token_length++] = b; + + if (t == EOF) { + eof(out); + return; + } else if (token_length == 4) { + decode_token(out); + token_length = 0; + } + } + } + + + /** Tell the Base64 decoder that no more input data will be forthcoming. + This may result in output, as a result of flushing the internal buffer. + This object must not be used again after calling eof(). If there are + bytes in `out' already, the new bytes are appended, so the caller should + do `out.setLength(0)' first if that's desired. + */ + public final void eof(ByteBuf out) { + if (token != null && token_length != 0) { + while (token_length < 4) + token[token_length++] = '='; + decode_final_token(out); + } + token_length = 0; + token = new byte[4]; + bytes = new byte[3]; + } +} diff --git a/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/MimeBase64Encoder.java b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/MimeBase64Encoder.java new file mode 100644 index 00000000000..234db4ab986 --- /dev/null +++ b/mozilla/directory/java-sdk/ldapjdk/netscape/ldap/util/MimeBase64Encoder.java @@ -0,0 +1,128 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * The contents of this file are subject to the Netscape Public License + * Version 1.0 (the "NPL"); you may not use this file except in + * compliance with the NPL. You may obtain a copy of the NPL at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the NPL is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL + * for the specific language governing rights and limitations under the + * NPL. + * + * The Initial Developer of this code under the NPL is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1998 Netscape Communications Corporation. All Rights + * Reserved. + */ +package netscape.ldap.util; + + +/** Implements a plaintext -> Base64 encoder. + */ +public final class MimeBase64Encoder extends MimeEncoder { + + private int buf = 0; // a 24-bit quantity + private int buf_bytes = 0; // how many octets are set in it + private byte line[] = new byte[74]; // output buffer + private int line_length = 0; // output buffer fill pointer + + static private final byte crlf[] = "\r\n".getBytes(); + + static private final byte map[] = { + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', // 0-7 + 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 8-15 + 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 16-23 + 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', // 24-31 + 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', // 32-39 + 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', // 40-47 + 'w', 'x', 'y', 'z', '0', '1', '2', '3', // 48-55 + '4', '5', '6', '7', '8', '9', '+', '/', // 56-63 + }; + + private final void encode_token() { + int i = line_length; + line[i] = map[0x3F & (buf >> 18)]; // sextet 1 (octet 1) + line[i+1] = map[0x3F & (buf >> 12)]; // sextet 2 (octet 1 and 2) + line[i+2] = map[0x3F & (buf >> 6)]; // sextet 3 (octet 2 and 3) + line[i+3] = map[0x3F & buf]; // sextet 4 (octet 3) + line_length += 4; + buf = 0; + buf_bytes = 0; + } + + private final void encode_partial_token() { + int i = line_length; + line[i] = map[0x3F & (buf >> 18)]; // sextet 1 (octet 1) + line[i+1] = map[0x3F & (buf >> 12)]; // sextet 2 (octet 1 and 2) + + if (buf_bytes == 1) + line[i+2] = '='; + else + line[i+2] = map[0x3F & (buf >> 6)]; // sextet 3 (octet 2 and 3) + + if (buf_bytes <= 2) + line[i+3] = '='; + else + line[i+3] = map[0x3F & buf]; // sextet 4 (octet 3) + line_length += 4; + buf = 0; + buf_bytes = 0; + } + + private final void flush_line(ByteBuf out) { + out.append(line, 0, line_length); + line_length = 0; + } + + /** Given a sequence of input bytes, produces a sequence of output bytes + using the base64 encoding. If there are bytes in `out' already, the + new bytes are appended, so the caller should do `out.setLength(0)' + first if that's desired. + */ + public final void translate(ByteBuf in, ByteBuf out) { + + byte inb[] = in.toBytes(); + int in_length = in.length(); + + for (int i = 0; i < in_length; i++) { + if (buf_bytes == 0) + buf = (buf & 0x00FFFF) | (inb[i] << 16); + else if (buf_bytes == 1) + buf = (buf & 0xFF00FF) | ((inb[i] << 8) & 0x00FFFF); + else + buf = (buf & 0xFFFF00) | (inb[i] & 0x0000FF); + + if ((++buf_bytes) == 3) { + encode_token(); + if (line_length >= 72) { + flush_line(out); + } + } + + if (i == (in_length-1)) { + if ((buf_bytes > 0) && (buf_bytes < 3)) + encode_partial_token(); + if (line_length > 0) + flush_line(out); + } + } + + for (int i=0; i + * + * Each DN component consists of an attribute type and a value. + * For example, in "o=Airius.com", the attribute type is "o" + * and the value is "Airius.com". + *

+ * + * You can use objects of this class to add components to an + * existing DN object. + *

+ * + * @version 1.0 + * @see netscape.ldap.utils.DN + */ +public final class RDN { + + /** + * List of RDNs. DN consists of one or more RDNs. + */ + String m_type = null; + String m_value = null; + + /** + * Constructs a new RDN object from the specified + * DN component. + * @param rdn DN component. + */ + public RDN(String rdn) { + int index = rdn.indexOf("="); + + // if the rdn doesnt have = or = positions right at the beginning of the rdn + if (index <= 0) + return; + + m_type = rdn.substring(0, index).trim(); + m_value = rdn.substring(index+1).trim(); + } + + /** + * Returns the DN component as the first element in an + * array of strings. + * @param noType Specify true to ignore the attribute type and + * equals sign (for example, "cn=") and return only the value. + * @return An array of strings representing the DN component. + */ + public String[] explodeRDN(boolean noType) { + if (m_type == null) + return null; + String str[] = new String[1]; + if (noType) { + str[0] = getValue(); + } else { + str[0] = toString(); + } + return str; + } + + /** + * Returns the attribute type of the DN component. + * @return rdn The attribute type of the DN component. + */ + public String getType() { + return m_type; + } + + /** + * Returns the value of the DN component. + * @return rdn The value of the DN component. + */ + public String getValue() { + return m_value; + } + + /** + * Returns the string representation of the DN component. + * @return The string representation of the DN component. + */ + public String toString() { + return m_type + "=" + m_value; + } + + /** + * Determines if the specified string is an distinguished name component. + * @param dn The string that you want to check. + * @return true if the string is a distinguished name component. + */ + public static boolean isRDN(String rdn) { + RDN newrdn = new RDN(rdn); + return ((newrdn.getType() != null) && (newrdn.getValue() != null)); + } + + /** + * Determines if the current DN component is equal to the specified + * DN component. + * @param rdn The DN component that you want compared against the + * current DN component. + * @return true if the two DN components are equal. + */ + public boolean equals(RDN rdn) { + return(toString().toUpperCase().equals(rdn.toString().toUpperCase())); + } +} diff --git a/mozilla/directory/java-sdk/manifest.mf b/mozilla/directory/java-sdk/manifest.mf new file mode 100644 index 00000000000..ed25b728023 --- /dev/null +++ b/mozilla/directory/java-sdk/manifest.mf @@ -0,0 +1,272 @@ +Name: com/netscape/sasl/SASLClientCB.class + +Name: com/netscape/sasl/SASLClientMechanismDriver.class + +Name: com/netscape/sasl/SASLException.class + +Name: com/netscape/sasl/SASLGetLanguageCB.class + +Name: com/netscape/sasl/SASLInfoClientCB.class + +Name: com/netscape/sasl/SASLMechanismFactory.class + +Name: com/netscape/sasl/SASLNamePasswordClientCB.class + +Name: com/netscape/sasl/SASLOkayCancelClientCB.class + +Name: com/netscape/sasl/SASLPasswordClientCB.class + +Name: com/netscape/sasl/SASLSecurityLayer.class + +Name: com/netscape/sasl/SASLWarningClientCB.class + +Name: netscape/ldap/LDAPAttribute.class + +Name: netscape/ldap/LDAPAttributeSchema.class + +Name: netscape/ldap/LDAPAttributeSet.class + +Name: netscape/ldap/LDAPCache.class + +Name: netscape/ldap/LDAPCheckComm.class + +Name: netscape/ldap/LDAPCompareAttrNames.class + +Name: netscape/ldap/LDAPConnection.class + +Name: netscape/ldap/LDAPConnThread.class + +Name: netscape/ldap/LDAPControl.class + +Name: netscape/ldap/LDAPDN.class + +Name: netscape/ldap/LDAPEntry.class + +Name: netscape/ldap/LDAPEntryComparator.class + +Name: netscape/ldap/LDAPException.class + +Name: netscape/ldap/LDAPExtendedOperation.class + +Name: netscape/ldap/LDAPMatchingRuleSchema.class + +Name: netscape/ldap/LDAPModification.class + +Name: netscape/ldap/LDAPModificationSet.class + +Name: netscape/ldap/LDAPObjectClassSchema.class + +Name: netscape/ldap/LDAPRebind.class + +Name: netscape/ldap/LDAPRebindAuth.class + +Name: netscape/ldap/LDAPReferralException.class + +Name: netscape/ldap/LDAPResourceBundle.class + +Name: netscape/ldap/LDAPResponseListener.class + +Name: netscape/ldap/LDAPSchema.class + +Name: netscape/ldap/LDAPSchemaElement.class + +Name: netscape/ldap/LDAPSearchConstraints.class + +Name: netscape/ldap/LDAPSearchListener.class + +Name: netscape/ldap/LDAPSearchResults.class + +Name: netscape/ldap/LDAPSocketFactory.class + +Name: netscape/ldap/LDAPSortKey.class + +Name: netscape/ldap/LDAPSSLSocket.class + +Name: netscape/ldap/LDAPSSLSocketFactory.class + +Name: netscape/ldap/LDAPSSLSocketWrapFactory.class + +Name: netscape/ldap/LDAPUrl.class + +Name: netscape/ldap/LDAPv2.class + +Name: netscape/ldap/LDAPv3.class + +Name: netscape/ldap/Timer.class + +Name: netscape/ldap/TimerEvent.class + +Name: netscape/ldap/TimerEventListener.class + +Name: netscape/ldap/TimerRunnable.class + +Name: netscape/ldap/ber/stream/BERAny.class + +Name: netscape/ldap/ber/stream/BERBitString.class + +Name: netscape/ldap/ber/stream/BERBoolean.class + +Name: netscape/ldap/ber/stream/BERCharacterString.class + +Name: netscape/ldap/ber/stream/BERChoice.class + +Name: netscape/ldap/ber/stream/BERConstruct.class + +Name: netscape/ldap/ber/stream/BERElement.class + +Name: netscape/ldap/ber/stream/BEREnumerated.class + +Name: netscape/ldap/ber/stream/BERInteger.class + +Name: netscape/ldap/ber/stream/BERIntegral.class + +Name: netscape/ldap/ber/stream/BERNull.class + +Name: netscape/ldap/ber/stream/BERNumericString.class + +Name: netscape/ldap/ber/stream/BERObjectId.class + +Name: netscape/ldap/ber/stream/BEROctetString.class + +Name: netscape/ldap/ber/stream/BERPrintableString.class + +Name: netscape/ldap/ber/stream/BERReal.class + +Name: netscape/ldap/ber/stream/BERSequence.class + +Name: netscape/ldap/ber/stream/BERSet.class + +Name: netscape/ldap/ber/stream/BERTag.class + +Name: netscape/ldap/ber/stream/BERTagDecoder.class + +Name: netscape/ldap/ber/stream/BERUTCTime.class + +Name: netscape/ldap/ber/stream/BERVisibleString.class + +Name: netscape/ldap/client/JDAPAVA.class + +Name: netscape/ldap/client/JDAPBERTagDecoder.class + +Name: netscape/ldap/client/JDAPControl.class + +Name: netscape/ldap/client/JDAPFilter.class + +Name: netscape/ldap/client/JDAPFilterAnd.class + +Name: netscape/ldap/client/JDAPFilterApproxMatch.class + +Name: netscape/ldap/client/JDAPFilterAVA.class + +Name: netscape/ldap/client/JDAPFilterEqualityMatch.class + +Name: netscape/ldap/client/JDAPFilterExtensible.class + +Name: netscape/ldap/client/JDAPFilterGreaterOrEqual.class + +Name: netscape/ldap/client/JDAPFilterLessOrEqual.class + +Name: netscape/ldap/client/JDAPFilterNot.class + +Name: netscape/ldap/client/JDAPFilterOpers.class + +Name: netscape/ldap/client/JDAPFilterOr.class + +Name: netscape/ldap/client/JDAPFilterPresent.class + +Name: netscape/ldap/client/JDAPFilterSet.class + +Name: netscape/ldap/client/JDAPFilterSubString.class + +Name: netscape/ldap/client/JDAPMessage.class + +Name: netscape/ldap/client/opers/JDAPAbandonRequest.class + +Name: netscape/ldap/client/opers/JDAPAddRequest.class + +Name: netscape/ldap/client/opers/JDAPAddResponse.class + +Name: netscape/ldap/client/opers/JDAPBaseDNRequest.class + +Name: netscape/ldap/client/opers/JDAPBindRequest.class + +Name: netscape/ldap/client/opers/JDAPBindResponse.class + +Name: netscape/ldap/client/opers/JDAPCompareRequest.class + +Name: netscape/ldap/client/opers/JDAPCompareResponse.class + +Name: netscape/ldap/client/opers/JDAPDeleteRequest.class + +Name: netscape/ldap/client/opers/JDAPDeleteResponse.class + +Name: netscape/ldap/client/opers/JDAPExtendedRequest.class + +Name: netscape/ldap/client/opers/JDAPExtendedResponse.class + +Name: netscape/ldap/client/opers/JDAPModifyRDNRequest.class + +Name: netscape/ldap/client/opers/JDAPModifyRDNResponse.class + +Name: netscape/ldap/client/opers/JDAPModifyRequest.class + +Name: netscape/ldap/client/opers/JDAPModifyResponse.class + +Name: netscape/ldap/client/opers/JDAPProtocolOp.class + +Name: netscape/ldap/client/opers/JDAPResult.class + +Name: netscape/ldap/client/opers/JDAPSearchRequest.class + +Name: netscape/ldap/client/opers/JDAPSearchResponse.class + +Name: netscape/ldap/client/opers/JDAPSearchResult.class + +Name: netscape/ldap/client/opers/JDAPSearchResultReference.class + +Name: netscape/ldap/client/opers/JDAPUnbindRequest.class + +Name: netscape/ldap/controls/LDAPEntryChangeControl.class + +Name: netscape/ldap/controls/LDAPPersistSearchControl.class + +Name: netscape/ldap/controls/LDAPSortControl.class + +Name: netscape/ldap/controls/LDAPVirtualListControl.class + +Name: netscape/ldap/controls/LDAPVirtualListResponse.class + +Name: netscape/ldap/errors/ErrorCodes.props + +Name: netscape/ldap/util/ByteBuf.class + +Name: netscape/ldap/util/DN.class + +Name: netscape/ldap/util/GetOpt.class + +Name: netscape/ldap/util/LDIF$LineReader.class + +Name: netscape/ldap/util/LDIF.class + +Name: netscape/ldap/util/LDIFAddContent.class + +Name: netscape/ldap/util/LDIFAttributeContent.class + +Name: netscape/ldap/util/LDIFContent.class + +Name: netscape/ldap/util/LDIFDeleteContent.class + +Name: netscape/ldap/util/LDIFModDNContent.class + +Name: netscape/ldap/util/LDIFModifyContent.class + +Name: netscape/ldap/util/LDIFRecord.class + +Name: netscape/ldap/util/MimeBase64Decoder.class + +Name: netscape/ldap/util/MimeBase64Encoder.class + +Name: netscape/ldap/util/MimeEncoder.class + +Name: netscape/ldap/util/RDN.class +