You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tomee.apache.org by jl...@apache.org on 2021/06/08 10:05:51 UTC
[tomee-jakarta] 03/03: All CXF patching now happens in TomEE build
itself so it benefits the other distributions and executions (application
composer, arquillian, etc)
This is an automated email from the ASF dual-hosted git repository.
jlmonteiro pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee-jakarta.git
commit 3dd7a8680ef0e2149e1449ee73835a98c542d0ad
Author: Jean-Louis Monteiro <jl...@tomitribe.com>
AuthorDate: Tue Jun 8 12:05:37 2021 +0200
All CXF patching now happens in TomEE build itself so it benefits the other distributions and executions (application composer, arquillian, etc)
---
.../java/org/apache/cxf/annotations/Policy.java | 80 -
.../apache/cxf/annotations/WSDLDocumentation.java | 88 -
.../cxf/attachment/AttachmentDataSource.java | 107 -
.../cxf/attachment/AttachmentDeserializer.java | 462 ----
.../cxf/attachment/AttachmentSerializer.java | 345 ---
.../org/apache/cxf/attachment/AttachmentUtil.java | 572 -----
.../apache/cxf/attachment/Base64DecoderStream.java | 196 --
.../apache/cxf/attachment/ContentDisposition.java | 144 --
.../cxf/attachment/LazyAttachmentCollection.java | 362 ----
.../cxf/attachment/MimeBodyPartInputStream.java | 275 ---
.../java/org/apache/cxf/bus/CXFBusFactory.java | 47 -
.../bus/blueprint/BundleDelegatingClassLoader.java | 134 --
.../cxf/bus/blueprint/BusDefinitionParser.java | 72 -
.../apache/cxf/bus/blueprint/ConfigurerImpl.java | 180 --
.../org/apache/cxf/bus/extension/Extension.java | 291 ---
.../cxf/bus/extension/ExtensionManagerImpl.java | 381 ----
.../ServiceContractResolverRegistryImpl.java | 113 -
.../java/org/apache/cxf/bus/osgi/CXFActivator.java | 134 --
.../cxf/bus/osgi/CXFExtensionBundleListener.java | 181 --
.../org/apache/cxf/bus/osgi/OSGIBusListener.java | 224 --
.../cxf/bus/resource/ResourceManagerImpl.java | 85 -
.../apache/cxf/bus/spring/BusDefinitionParser.java | 310 ---
.../apache/cxf/bus/spring/BusEntityResolver.java | 94 -
.../cxf/bus/spring/BusExtensionPostProcessor.java | 71 -
.../cxf/bus/spring/Jsr250BeanPostProcessor.java | 164 --
.../apache/cxf/bus/spring/NamespaceHandler.java | 57 -
.../java/org/apache/cxf/bus/spring/SpringBus.java | 142 --
.../cxf/catalog/CatalogXmlSchemaURIResolver.java | 102 -
.../java/org/apache/cxf/common/i18n/Exception.java | 58 -
.../java/org/apache/cxf/common/i18n/Message.java | 91 -
.../apache/cxf/common/i18n/UncheckedException.java | 84 -
.../cxf/common/injection/ResourceInjector.java | 446 ----
.../java/org/apache/cxf/common/jaxb/JAXBUtils.java | 1180 -----------
.../common/logging/AbstractDelegatingLogger.java | 457 ----
.../org/apache/cxf/common/logging/LogUtils.java | 485 -----
.../cxf/common/logging/RegexLoggingFilter.java | 117 --
.../cxf/common/spi/ClassGeneratorClassLoader.java | 153 --
.../cxf/common/spi/NamespaceClassGenerator.java | 450 ----
.../org/apache/cxf/common/util/ASMHelperImpl.java | 273 ---
.../org/apache/cxf/common/util/Base64Utility.java | 474 -----
.../org/apache/cxf/common/util/CachedClass.java | 37 -
.../org/apache/cxf/common/util/ClassHelper.java | 140 --
.../apache/cxf/common/util/CollectionUtils.java | 126 --
.../java/org/apache/cxf/common/util/Compiler.java | 382 ----
.../common/util/ModCountCopyOnWriteArrayList.java | 156 --
.../org/apache/cxf/common/util/PackageUtils.java | 181 --
.../apache/cxf/common/util/ProxyClassLoader.java | 89 -
.../org/apache/cxf/common/util/ProxyHelper.java | 140 --
.../common/util/ReflectionInvokationHandler.java | 199 --
.../org/apache/cxf/common/util/SortedArraySet.java | 266 ---
.../cxf/common/util/SpringClassUnwrapper.java | 111 -
.../cxf/common/util/SpringClasspathScanner.java | 202 --
.../org/apache/cxf/common/util/StreamPrinter.java | 63 -
.../org/apache/cxf/common/util/URIParserUtil.java | 209 --
.../cxf/common/xmlschema/SchemaCollection.java | 389 ----
.../jsse/MultiKeyPasswordKeyManager.java | 84 -
.../configuration/jsse/TLSClientParameters.java | 258 ---
.../configuration/jsse/TLSParameterJaxBUtils.java | 420 ----
.../cxf/configuration/spring/ConfigurerImpl.java | 288 ---
.../cxf/databinding/source/SourceDataBinding.java | 104 -
.../cxf/databinding/stax/StaxDataBinding.java | 187 --
.../cxf/endpoint/AbstractConduitSelector.java | 308 ---
.../org/apache/cxf/endpoint/ClientCallback.java | 166 --
.../java/org/apache/cxf/endpoint/ClientImpl.java | 1192 -----------
.../java/org/apache/cxf/endpoint/EndpointImpl.java | 220 --
.../java/org/apache/cxf/endpoint/ServerImpl.java | 221 --
.../org/apache/cxf/feature/FastInfosetFeature.java | 110 -
.../org/apache/cxf/feature/WrappedFeature.java | 61 -
.../cxf/feature/transform/XSLTOutInterceptor.java | 210 --
.../patch/java/org/apache/cxf/headers/Header.java | 78 -
.../java/org/apache/cxf/helpers/DOMUtils.java | 895 --------
.../patch/java/org/apache/cxf/helpers/IOUtils.java | 428 ----
.../java/org/apache/cxf/helpers/ServiceUtils.java | 214 --
.../AbstractFaultChainInitiatorObserver.java | 142 --
.../interceptor/AbstractLoggingInterceptor.java | 298 ---
.../cxf/interceptor/AnnotationInterceptors.java | 151 --
.../cxf/interceptor/AttachmentInInterceptor.java | 72 -
.../cxf/interceptor/ClientOutFaultObserver.java | 68 -
.../interceptor/InFaultChainInitiatorObserver.java | 84 -
.../apache/cxf/interceptor/InterceptorChain.java | 109 -
.../org/apache/cxf/interceptor/LoggingMessage.java | 133 --
.../interceptor/OneWayProcessorInterceptor.java | 177 --
.../OutFaultChainInitiatorObserver.java | 84 -
.../security/DefaultSecurityContext.java | 188 --
.../interceptor/security/JAASLoginInterceptor.java | 233 --
.../cxf/internal/CXFAPINamespaceHandler.java | 127 --
.../apache/cxf/io/CacheAndWriteOutputStream.java | 96 -
.../patch/java/org/apache/cxf/io/CachedWriter.java | 665 ------
.../java/org/apache/cxf/io/ReaderInputStream.java | 294 ---
.../apache/cxf/io/WriteOnCloseOutputStream.java | 46 -
.../org/apache/cxf/jaxb/FactoryClassGenerator.java | 86 -
.../apache/cxf/jaxb/JAXBContextInitializer.java | 571 -----
.../java/org/apache/cxf/jaxb/JAXBDataBase.java | 192 --
.../java/org/apache/cxf/jaxb/JAXBDataBinding.java | 873 --------
.../org/apache/cxf/jaxb/JAXBEncoderDecoder.java | 1119 ----------
.../org/apache/cxf/jaxb/JAXBSchemaInitializer.java | 823 --------
.../org/apache/cxf/jaxb/io/DataReaderImpl.java | 207 --
.../org/apache/cxf/jaxb/io/DataWriterImpl.java | 321 ---
.../java/org/apache/cxf/jaxrs/JAXRSInvoker.java | 460 ----
.../apache/cxf/jaxrs/JAXRSServerFactoryBean.java | 467 ----
.../apache/cxf/jaxrs/client/ClientProxyImpl.java | 1149 ----------
.../cxf/jaxrs/client/JAXRSClientFactory.java | 414 ----
.../apache/cxf/jaxrs/client/LocalClientState.java | 185 --
.../org/apache/cxf/jaxrs/client/WebClient.java | 1349 ------------
.../client/spec/ClientRequestContextImpl.java | 186 --
.../JAXRSClientFactoryBeanDefinitionParser.java | 187 --
.../cxf/jaxrs/impl/EntityTagHeaderProvider.java | 77 -
.../cxf/jaxrs/impl/MediaTypeHeaderProvider.java | 221 --
.../org/apache/cxf/jaxrs/impl/RequestImpl.java | 388 ----
.../apache/cxf/jaxrs/impl/ResourceContextImpl.java | 67 -
.../org/apache/cxf/jaxrs/impl/ResponseImpl.java | 629 ------
.../impl/tl/ThreadLocalInvocationHandler.java | 53 -
.../cxf/jaxrs/interceptor/JAXRSInInterceptor.java | 274 ---
.../cxf/jaxrs/interceptor/JAXRSOutInterceptor.java | 498 -----
.../cxf/jaxrs/model/AbstractResourceInfo.java | 389 ----
.../apache/cxf/jaxrs/model/ClassResourceInfo.java | 366 ----
.../org/apache/cxf/jaxrs/model/URITemplate.java | 627 ------
.../cxf/jaxrs/provider/AbstractJAXBProvider.java | 993 ---------
.../jaxrs/provider/CachingMessageBodyReader.java | 100 -
.../jaxrs/provider/CachingMessageBodyWriter.java | 102 -
.../cxf/jaxrs/provider/DataSourceProvider.java | 110 -
.../cxf/jaxrs/provider/FormEncodingProvider.java | 228 --
.../jaxrs/provider/GenericArgumentComparator.java | 206 --
.../cxf/jaxrs/provider/JAXBElementProvider.java | 635 ------
.../cxf/jaxrs/provider/MultipartProvider.java | 474 -----
.../apache/cxf/jaxrs/provider/ProviderFactory.java | 1578 --------------
.../apache/cxf/jaxrs/provider/SourceProvider.java | 236 ---
.../cxf/jaxrs/provider/XSLTJaxbProvider.java | 588 ------
.../jaxrs/security/JAASAuthenticationFilter.java | 170 --
.../security/KerberosAuthenticationFilter.java | 251 ---
.../jaxrs/servlet/CXFNonSpringJaxrsServlet.java | 640 ------
.../JAXRSServerFactoryBeanDefinitionParser.java | 286 ---
.../apache/cxf/jaxrs/utils/AnnotationUtils.java | 308 ---
.../org/apache/cxf/jaxrs/utils/GenericsUtils.java | 224 --
.../java/org/apache/cxf/jaxrs/utils/HttpUtils.java | 704 -------
.../org/apache/cxf/jaxrs/utils/InjectionUtils.java | 1589 --------------
.../org/apache/cxf/jaxrs/utils/JAXRSUtils.java | 2027 ------------------
.../org/apache/cxf/jaxrs/utils/ResourceUtils.java | 1044 ---------
.../java/org/apache/cxf/message/MessageUtils.java | 261 ---
.../java/org/apache/cxf/phase/PhaseChainCache.java | 137 --
.../apache/cxf/phase/PhaseInterceptorChain.java | 857 --------
.../cxf/service/factory/FactoryBeanListener.java | 145 --
.../apache/cxf/service/invoker/FactoryInvoker.java | 70 -
.../service/model/AbstractPropertiesHolder.java | 271 ---
.../org/apache/cxf/service/model/FaultInfo.java | 61 -
.../apache/cxf/service/model/InterfaceInfo.java | 124 --
.../apache/cxf/service/model/OperationInfo.java | 242 ---
.../cxf/service/model/UnwrappedOperationInfo.java | 72 -
.../java/org/apache/cxf/staxutils/StaxUtils.java | 2222 --------------------
.../apache/cxf/staxutils/W3CDOMStreamReader.java | 429 ----
.../cxf/transport/ChainInitiationObserver.java | 197 --
.../transport/http/AbstractHTTPDestination.java | 956 ---------
.../cxf/transport/http/CXFAuthenticator.java | 177 --
.../org/apache/cxf/transport/http/HTTPConduit.java | 1952 -----------------
.../cxf/transport/http/HTTPTransportFactory.java | 297 ---
.../org/apache/cxf/transport/http/Headers.java | 583 -----
.../transport/http/HttpServletRequestSnapshot.java | 277 ---
.../transport/http/ReferencingAuthenticator.java | 234 ---
.../http/Servlet3ContinuationProvider.java | 281 ---
.../transport/http/URLConnectionHTTPConduit.java | 439 ----
.../cxf/transport/http/auth/HttpAuthHeader.java | 154 --
.../transport/https/HttpsURLConnectionFactory.java | 247 ---
.../transport/https/HttpsURLConnectionInfo.java | 168 --
.../servicelist/ServiceListJAASAuthenticator.java | 160 --
.../AbstractBeanValidationInterceptor.java | 65 -
.../cxf/workqueue/AutomaticWorkQueueImpl.java | 619 ------
.../apache/cxf/ws/addressing/MAPAggregator.java | 224 --
167 files changed, 57374 deletions(-)
diff --git a/transform/src/patch/java/org/apache/cxf/annotations/Policy.java b/transform/src/patch/java/org/apache/cxf/annotations/Policy.java
deleted file mode 100644
index a0d4a75..0000000
--- a/transform/src/patch/java/org/apache/cxf/annotations/Policy.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.annotations;
-
-import java.lang.annotation.Documented;
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Inherited;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Attaches a Policy to a service or method
- */
-@Documented
-@Retention(RetentionPolicy.RUNTIME)
-@Target({ ElementType.TYPE, ElementType.METHOD })
-@Inherited
-public @interface Policy {
-
- String uri();
-
- boolean includeInWSDL() default true;
-
-
- /**
- * The place to put the PolicyReference. The Default depends on the
- * location of the annotation. On the method in the SEI, it would be
- * the binding/operation, on the SEI, it would be the binding, on the
- * service impl, the service element.
- * @return location
- */
- Placement placement() default Placement.DEFAULT;
-
- /**
- * If Placement is PORT_TYPE_OPERATION_FAULT, or BINDING_OPERATION_FAULT,
- * return the fault class associated with this documentation
- * @return the fault class
- */
- Class<?> faultClass() default DEFAULT.class;
-
- enum Placement {
- DEFAULT,
-
- PORT_TYPE,
- PORT_TYPE_OPERATION,
- PORT_TYPE_OPERATION_INPUT,
- PORT_TYPE_OPERATION_OUTPUT,
- PORT_TYPE_OPERATION_FAULT,
-
- BINDING,
- BINDING_OPERATION,
- BINDING_OPERATION_INPUT,
- BINDING_OPERATION_OUTPUT,
- BINDING_OPERATION_FAULT,
-
- SERVICE,
- SERVICE_PORT,
- }
-
- final class DEFAULT { }
-}
-
diff --git a/transform/src/patch/java/org/apache/cxf/annotations/WSDLDocumentation.java b/transform/src/patch/java/org/apache/cxf/annotations/WSDLDocumentation.java
deleted file mode 100644
index 9116f1c..0000000
--- a/transform/src/patch/java/org/apache/cxf/annotations/WSDLDocumentation.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.annotations;
-
-
-import java.lang.annotation.Documented;
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Inherited;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-
-/**
- * Adds documentation nodes to the generated WSDL
- */
-@Documented
-@Retention(RetentionPolicy.RUNTIME)
-@Target({ ElementType.TYPE, ElementType.METHOD })
-@Inherited
-public @interface WSDLDocumentation {
- /**
- * The documentation to add
- * @return documentation string
- */
- String value();
-
- /**
- * The place to put the documentation. The Default depends on the
- * location of the annotation. On the method in the SEI, it would be
- * the portType/operation, on the SEI, it would be the portType, on the
- * service impl, the service element.
- * @return location
- */
- Placement placement() default Placement.DEFAULT;
-
- /**
- * If Placement is FAULT_MESSAGE, PORT_FAULT, or BINDING_FAULT,
- * return the fault class associated with this documentation
- * @return the fault class
- */
- Class<?> faultClass() default DEFAULT.class;
-
- enum Placement {
- DEFAULT,
- TOP,
-
- INPUT_MESSAGE,
- OUTPUT_MESSAGE,
- FAULT_MESSAGE,
-
- PORT_TYPE,
- PORT_TYPE_OPERATION,
- PORT_TYPE_OPERATION_INPUT,
- PORT_TYPE_OPERATION_OUTPUT,
- PORT_TYPE_OPERATION_FAULT,
-
- BINDING,
- BINDING_OPERATION,
- BINDING_OPERATION_INPUT,
- BINDING_OPERATION_OUTPUT,
- BINDING_OPERATION_FAULT,
-
- SERVICE,
- SERVICE_PORT,
-
- }
-
-
- final class DEFAULT { }
-}
diff --git a/transform/src/patch/java/org/apache/cxf/attachment/AttachmentDataSource.java b/transform/src/patch/java/org/apache/cxf/attachment/AttachmentDataSource.java
deleted file mode 100644
index 6e4fa1a..0000000
--- a/transform/src/patch/java/org/apache/cxf/attachment/AttachmentDataSource.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.attachment;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-import javax.activation.DataSource;
-
-import org.apache.cxf.helpers.IOUtils;
-import org.apache.cxf.io.CacheSizeExceededException;
-import org.apache.cxf.io.CachedOutputStream;
-import org.apache.cxf.message.Message;
-
-public class AttachmentDataSource implements DataSource {
-
- private final String ct;
- private CachedOutputStream cache;
- private InputStream ins;
- private DelegatingInputStream delegate;
- private String name;
-
- public AttachmentDataSource(String ctParam, InputStream inParam) {
- this.ct = ctParam;
- ins = inParam;
- }
-
- public boolean isCached() {
- return cache != null;
- }
- public void cache(Message message) throws IOException {
- if (cache == null) {
- cache = new CachedOutputStream();
- AttachmentUtil.setStreamedAttachmentProperties(message, cache);
- try {
- IOUtils.copyAndCloseInput(ins, cache);
- cache.lockOutputStream();
- if (delegate != null) {
- delegate.setInputStream(cache.getInputStream());
- }
- } catch (CacheSizeExceededException | IOException cee) {
- cache.close();
- cache = null;
- throw cee;
- } finally {
- ins = null;
- }
- }
- }
- public void hold(Message message) throws IOException {
- cache(message);
- cache.holdTempFile();
- }
- public void release() {
- if (cache != null) {
- cache.releaseTempFileHold();
- }
- }
-
- public String getContentType() {
- return ct;
- }
-
- public InputStream getInputStream() {
- try {
- if (cache != null) {
- return cache.getInputStream();
- }
- if (delegate == null) {
- delegate = new DelegatingInputStream(ins);
- }
- return delegate;
- } catch (IOException e) {
- return null;
- }
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public OutputStream getOutputStream() throws IOException {
- throw new UnsupportedOperationException();
- }
-}
diff --git a/transform/src/patch/java/org/apache/cxf/attachment/AttachmentDeserializer.java b/transform/src/patch/java/org/apache/cxf/attachment/AttachmentDeserializer.java
deleted file mode 100644
index 55a1dcc..0000000
--- a/transform/src/patch/java/org/apache/cxf/attachment/AttachmentDeserializer.java
+++ /dev/null
@@ -1,462 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.attachment;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.PushbackInputStream;
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-import java.util.logging.Logger;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import javax.activation.DataSource;
-
-import org.apache.cxf.common.logging.LogUtils;
-import org.apache.cxf.common.util.StringUtils;
-import org.apache.cxf.common.util.SystemPropertyAction;
-import org.apache.cxf.helpers.HttpHeaderHelper;
-import org.apache.cxf.helpers.IOUtils;
-import org.apache.cxf.io.CachedOutputStream;
-import org.apache.cxf.message.Attachment;
-import org.apache.cxf.message.Message;
-import org.apache.cxf.message.MessageUtils;
-
-public class AttachmentDeserializer {
- public static final String ATTACHMENT_PART_HEADERS = AttachmentDeserializer.class.getName() + ".headers";
-
- /**
- * Allowed value is any instance of {@link File} or {@link String}.
- */
- public static final String ATTACHMENT_DIRECTORY = "attachment-directory";
-
- /**
- * The memory threshold of attachments. Allowed value is any instance of {@link Number} or {@link String}.
- * The default is {@link AttachmentDeserializer#THRESHOLD}.
- */
- public static final String ATTACHMENT_MEMORY_THRESHOLD = "attachment-memory-threshold";
-
- /**
- * The maximum size of the attachment. Allowed value is any of {@link Number} or {@link String}.
- */
- public static final String ATTACHMENT_MAX_SIZE = "attachment-max-size";
-
- /**
- * The maximum number of attachments permitted in a message. The default is 50.
- */
- public static final String ATTACHMENT_MAX_COUNT = "attachment-max-count";
-
- /**
- * The maximum MIME Header Length. The default is 300.
- */
- public static final String ATTACHMENT_MAX_HEADER_SIZE = "attachment-max-header-size";
- public static final int DEFAULT_MAX_HEADER_SIZE =
- SystemPropertyAction.getInteger("org.apache.cxf.attachment-max-header-size", 300);
-
- public static final int THRESHOLD = 1024 * 100; //100K (byte unit)
-
- private static final Pattern CONTENT_TYPE_BOUNDARY_PATTERN = Pattern.compile("boundary=\"?([^\";]*)");
-
- private static final Pattern INPUT_STREAM_BOUNDARY_PATTERN =
- Pattern.compile("^--(\\S*)$", Pattern.MULTILINE);
-
- private static final Logger LOG = LogUtils.getL7dLogger(AttachmentDeserializer.class);
-
- private static final int PUSHBACK_AMOUNT = 2048;
-
- private boolean lazyLoading = true;
-
- private PushbackInputStream stream;
- private int createCount;
- private int closedCount;
- private boolean closed;
-
- private byte[] boundary;
-
- private LazyAttachmentCollection attachments;
-
- private Message message;
-
- private InputStream body;
-
- private Set<DelegatingInputStream> loaded = new HashSet<>();
- private List<String> supportedTypes;
-
- private int maxHeaderLength = DEFAULT_MAX_HEADER_SIZE;
-
- public AttachmentDeserializer(Message message) {
- this(message, Collections.singletonList("multipart/related"));
- }
-
- public AttachmentDeserializer(Message message, List<String> supportedTypes) {
- this.message = message;
- this.supportedTypes = supportedTypes;
-
- // Get the maximum Header length from configuration
- maxHeaderLength = MessageUtils.getContextualInteger(message, ATTACHMENT_MAX_HEADER_SIZE,
- DEFAULT_MAX_HEADER_SIZE);
- }
-
- public void initializeAttachments() throws IOException {
- initializeRootMessage();
-
- Object maxCountProperty = message.getContextualProperty(AttachmentDeserializer.ATTACHMENT_MAX_COUNT);
- int maxCount = 50;
- if (maxCountProperty != null) {
- if (maxCountProperty instanceof Integer) {
- maxCount = (Integer)maxCountProperty;
- } else {
- maxCount = Integer.parseInt((String)maxCountProperty);
- }
- }
-
- attachments = new LazyAttachmentCollection(this, maxCount);
- message.setAttachments(attachments);
- }
-
- protected void initializeRootMessage() throws IOException {
- String contentType = (String) message.get(Message.CONTENT_TYPE);
-
- if (contentType == null) {
- throw new IllegalStateException("Content-Type can not be empty!");
- }
-
- if (message.getContent(InputStream.class) == null) {
- throw new IllegalStateException("An InputStream must be provided!");
- }
-
- if (AttachmentUtil.isTypeSupported(contentType.toLowerCase(), supportedTypes)) {
- String boundaryString = findBoundaryFromContentType(contentType);
- if (null == boundaryString) {
- boundaryString = findBoundaryFromInputStream();
- }
- // If a boundary still wasn't found, throw an exception
- if (null == boundaryString) {
- throw new IOException("Couldn't determine the boundary from the message!");
- }
- boundary = boundaryString.getBytes(StandardCharsets.UTF_8);
-
- stream = new PushbackInputStream(message.getContent(InputStream.class), PUSHBACK_AMOUNT);
- if (!readTillFirstBoundary(stream, boundary)) {
- throw new IOException("Couldn't find MIME boundary: " + boundaryString);
- }
-
- Map<String, List<String>> ih = loadPartHeaders(stream);
- message.put(ATTACHMENT_PART_HEADERS, ih);
- String val = AttachmentUtil.getHeader(ih, "Content-Type", "; ");
- if (!StringUtils.isEmpty(val)) {
- String cs = HttpHeaderHelper.findCharset(val);
- if (!StringUtils.isEmpty(cs)) {
- message.put(Message.ENCODING, HttpHeaderHelper.mapCharset(cs));
- }
- }
- val = AttachmentUtil.getHeader(ih, "Content-Transfer-Encoding");
-
- MimeBodyPartInputStream mmps = new MimeBodyPartInputStream(stream, boundary, PUSHBACK_AMOUNT);
- InputStream ins = AttachmentUtil.decode(mmps, val);
- if (ins != mmps) {
- ih.remove("Content-Transfer-Encoding");
- }
- body = new DelegatingInputStream(ins, this);
- createCount++;
- message.setContent(InputStream.class, body);
- }
- }
-
- private String findBoundaryFromContentType(String ct) {
- // Use regex to get the boundary and return null if it's not found
- Matcher m = CONTENT_TYPE_BOUNDARY_PATTERN.matcher(ct);
- return m.find() ? "--" + m.group(1) : null;
- }
-
- private String findBoundaryFromInputStream() throws IOException {
- InputStream is = message.getContent(InputStream.class);
- //boundary should definitely be in the first 2K;
- PushbackInputStream in = new PushbackInputStream(is, 4096);
- byte[] buf = new byte[2048];
- int i = in.read(buf);
- int len = i;
- while (i > 0 && len < buf.length) {
- i = in.read(buf, len, buf.length - len);
- if (i > 0) {
- len += i;
- }
- }
- String msg = IOUtils.newStringFromBytes(buf, 0, len);
- in.unread(buf, 0, len);
-
- // Reset the input stream since we'll need it again later
- message.setContent(InputStream.class, in);
-
- // Use regex to get the boundary and return null if it's not found
- Matcher m = INPUT_STREAM_BOUNDARY_PATTERN.matcher(msg);
- return m.find() ? "--" + m.group(1) : null;
- }
-
- public AttachmentImpl readNext() throws IOException {
- // Cache any mime parts that are currently being streamed
- cacheStreamedAttachments();
- if (closed) {
- return null;
- }
-
- int v = stream.read();
- if (v == -1) {
- return null;
- }
- stream.unread(v);
-
- Map<String, List<String>> headers = loadPartHeaders(stream);
- return (AttachmentImpl)createAttachment(headers);
- }
-
- private void cacheStreamedAttachments() throws IOException {
- if (body instanceof DelegatingInputStream
- && !((DelegatingInputStream) body).isClosed()) {
-
- cache((DelegatingInputStream) body);
- }
-
- List<Attachment> atts = new ArrayList<>(attachments.getLoadedAttachments());
- for (Attachment a : atts) {
- DataSource s = a.getDataHandler().getDataSource();
- if (s instanceof AttachmentDataSource) {
- AttachmentDataSource ads = (AttachmentDataSource)s;
- if (!ads.isCached()) {
- ads.cache(message);
- }
- } else if (s.getInputStream() instanceof DelegatingInputStream) {
- cache((DelegatingInputStream) s.getInputStream());
- } else {
- //assume a normal stream that is already cached
- }
- }
- }
-
- private void cache(DelegatingInputStream input) throws IOException {
- if (loaded.contains(input)) {
- return;
- }
- loaded.add(input);
- InputStream origIn = input.getInputStream();
- try (CachedOutputStream out = new CachedOutputStream()) {
- AttachmentUtil.setStreamedAttachmentProperties(message, out);
- IOUtils.copy(input, out);
- input.setInputStream(out.getInputStream());
- origIn.close();
- }
- }
-
- /**
- * Move the read pointer to the begining of the first part read till the end
- * of first boundary
- *
- * @param pushbackInStream
- * @param boundary
- * @throws IOException
- */
- private static boolean readTillFirstBoundary(PushbackInputStream pushbackInStream,
- byte[] boundary) throws IOException {
-
- // work around a bug in PushBackInputStream where the buffer isn't
- // initialized
- // and available always returns 0.
- int value = pushbackInStream.read();
- pushbackInStream.unread(value);
- while (value != -1) {
- value = pushbackInStream.read();
- if ((byte) value == boundary[0]) {
- int boundaryIndex = 0;
- while (value != -1 && (boundaryIndex < boundary.length) && ((byte) value == boundary[boundaryIndex])) {
-
- value = pushbackInStream.read();
- if (value == -1) {
- throw new IOException("Unexpected End while searching for first Mime Boundary");
- }
- boundaryIndex++;
- }
- if (boundaryIndex == boundary.length) {
- // boundary found, read the newline
- if (value == 13) {
- pushbackInStream.read();
- }
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * Create an Attachment from the MIME stream. If there is a previous attachment
- * that is not read, cache that attachment.
- *
- * @throws IOException
- */
- private Attachment createAttachment(Map<String, List<String>> headers) throws IOException {
- InputStream partStream =
- new DelegatingInputStream(new MimeBodyPartInputStream(stream, boundary, PUSHBACK_AMOUNT),
- this);
- createCount++;
-
- return AttachmentUtil.createAttachment(partStream, headers);
- }
-
- public boolean isLazyLoading() {
- return lazyLoading;
- }
-
- public void setLazyLoading(boolean lazyLoading) {
- this.lazyLoading = lazyLoading;
- }
-
- public void markClosed(DelegatingInputStream delegatingInputStream) throws IOException {
- closedCount++;
- if (closedCount == createCount && !attachments.hasNext(false)) {
- int x = stream.read();
- while (x != -1) {
- x = stream.read();
- }
- stream.close();
- closed = true;
- }
- }
- /**
- * Check for more attachment.
- *
- * @return whether there is more attachment or not. It will not deserialize the next attachment.
- * @throws IOException
- */
- public boolean hasNext() throws IOException {
- cacheStreamedAttachments();
- if (closed) {
- return false;
- }
-
- int v = stream.read();
- if (v == -1) {
- return false;
- }
- stream.unread(v);
- return true;
- }
-
-
-
- private Map<String, List<String>> loadPartHeaders(InputStream in) throws IOException {
- StringBuilder buffer = new StringBuilder(128);
- StringBuilder b = new StringBuilder(128);
- Map<String, List<String>> heads = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
-
- // loop until we hit the end or a null line
- while (readLine(in, b)) {
- // lines beginning with white space get special handling
- char c = b.charAt(0);
- if (c == ' ' || c == '\t') {
- if (buffer.length() != 0) {
- // preserve the line break and append the continuation
- buffer.append("\r\n");
- buffer.append(b);
- }
- } else {
- // if we have a line pending in the buffer, flush it
- if (buffer.length() > 0) {
- addHeaderLine(heads, buffer);
- buffer.setLength(0);
- }
- // add this to the accumulator
- buffer.append(b);
- }
- }
-
- // if we have a line pending in the buffer, flush it
- if (buffer.length() > 0) {
- addHeaderLine(heads, buffer);
- }
- return heads;
- }
-
- private boolean readLine(InputStream in, StringBuilder buffer) throws IOException {
- if (buffer.length() != 0) {
- buffer.setLength(0);
- }
- int c;
-
- while ((c = in.read()) != -1) {
- // a linefeed is a terminator, always.
- if (c == '\n') {
- break;
- } else if (c == '\r') {
- //just ignore the CR. The next character SHOULD be an NL. If not, we're
- //just going to discard this
- continue;
- } else {
- // just add to the buffer
- buffer.append((char)c);
- }
-
- if (buffer.length() > maxHeaderLength) {
- LOG.fine("The attachment header size has exceeded the configured parameter: " + maxHeaderLength);
- throw new HeaderSizeExceededException();
- }
- }
-
- // no characters found...this was either an eof or a null line.
- return buffer.length() != 0;
- }
-
- private void addHeaderLine(Map<String, List<String>> heads, StringBuilder line) {
- // null lines are a nop
- final int size = line.length();
- if (size == 0) {
- return;
- }
- int separator = line.indexOf(":");
- final String name;
- String value = "";
- if (separator == -1) {
- name = line.toString().trim();
- } else {
- name = line.substring(0, separator);
- // step past the separator. Now we need to remove any leading white space characters.
- separator++;
-
- while (separator < size) {
- char ch = line.charAt(separator);
- if (ch != ' ' && ch != '\t' && ch != '\r' && ch != '\n') {
- break;
- }
- separator++;
- }
- value = line.substring(separator);
- }
- List<String> v = heads.computeIfAbsent(name, k -> new ArrayList<>(1));
- v.add(value);
- }
-
-}
diff --git a/transform/src/patch/java/org/apache/cxf/attachment/AttachmentSerializer.java b/transform/src/patch/java/org/apache/cxf/attachment/AttachmentSerializer.java
deleted file mode 100644
index 3e65de3..0000000
--- a/transform/src/patch/java/org/apache/cxf/attachment/AttachmentSerializer.java
+++ /dev/null
@@ -1,345 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.attachment;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.StringWriter;
-import java.io.Writer;
-import java.net.URLDecoder;
-import java.nio.charset.StandardCharsets;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.activation.DataHandler;
-
-import org.apache.cxf.common.util.Base64Utility;
-import org.apache.cxf.helpers.IOUtils;
-import org.apache.cxf.message.Attachment;
-import org.apache.cxf.message.Message;
-
-
-
-
-public class AttachmentSerializer {
- // http://tools.ietf.org/html/rfc2387
- private static final String DEFAULT_MULTIPART_TYPE = "multipart/related";
-
- private String contentTransferEncoding = AttachmentUtil.BINARY;
-
- private Message message;
- private String bodyBoundary;
- private OutputStream out;
- private String encoding;
-
- private String multipartType;
- private Map<String, List<String>> rootHeaders = Collections.emptyMap();
- private boolean xop = true;
- private boolean writeOptionalTypeParameters = true;
-
-
- public AttachmentSerializer(Message messageParam) {
- message = messageParam;
- }
-
- public AttachmentSerializer(Message messageParam,
- String multipartType,
- boolean writeOptionalTypeParameters,
- Map<String, List<String>> headers) {
- message = messageParam;
- this.multipartType = multipartType;
- this.writeOptionalTypeParameters = writeOptionalTypeParameters;
- this.rootHeaders = headers;
- }
-
- /**
- * Serialize the beginning of the attachment which includes the MIME
- * beginning and headers for the root message.
- */
- public void writeProlog() throws IOException {
- // Create boundary for body
- bodyBoundary = AttachmentUtil.getUniqueBoundaryValue();
-
- String bodyCt = (String) message.get(Message.CONTENT_TYPE);
- String bodyCtParams = null;
- String bodyCtParamsEscaped = null;
- // split the bodyCt to its head that is the type and its properties so that we
- // can insert the values at the right places based on the soap version and the mtom option
- // bodyCt will be of the form
- // soap11 -> text/xml
- // soap12 -> application/soap+xml; action="urn:ihe:iti:2007:RetrieveDocumentSet"
- if (bodyCt.indexOf(';') != -1) {
- int pos = bodyCt.indexOf(';');
- // get everything from the semi-colon
- bodyCtParams = bodyCt.substring(pos);
- bodyCtParamsEscaped = escapeQuotes(bodyCtParams);
- // keep the type/subtype part in bodyCt
- bodyCt = bodyCt.substring(0, pos);
- }
- // Set transport mime type
- String requestMimeType = multipartType == null ? DEFAULT_MULTIPART_TYPE : multipartType;
-
- StringBuilder ct = new StringBuilder(32);
- ct.append(requestMimeType);
-
- // having xop set to true implies multipart/related, but just in case...
- boolean xopOrMultipartRelated = xop
- || DEFAULT_MULTIPART_TYPE.equalsIgnoreCase(requestMimeType)
- || DEFAULT_MULTIPART_TYPE.startsWith(requestMimeType);
-
- // type is a required parameter for multipart/related only
- if (xopOrMultipartRelated
- && requestMimeType.indexOf("type=") == -1) {
- if (xop) {
- ct.append("; type=\"application/xop+xml\"");
- } else {
- ct.append("; type=\"").append(bodyCt).append('"');
- }
- }
-
- // boundary
- ct.append("; boundary=\"")
- .append(bodyBoundary)
- .append('"');
-
- String rootContentId = getHeaderValue("Content-ID", AttachmentUtil.BODY_ATTACHMENT_ID);
-
- // 'start' is a required parameter for XOP/MTOM, clearly defined
- // for simpler multipart/related payloads but is not needed for
- // multipart/mixed, multipart/form-data
- if (xopOrMultipartRelated) {
- ct.append("; start=\"<")
- .append(checkAngleBrackets(rootContentId))
- .append(">\"");
- }
-
- // start-info is a required parameter for XOP/MTOM, may be needed for
- // other WS cases but is redundant in simpler multipart/related cases
- // the parameters need to be included within the start-info's value in the escaped form
- if (writeOptionalTypeParameters || xop) {
- ct.append("; start-info=\"")
- .append(bodyCt);
- if (bodyCtParamsEscaped != null) {
- ct.append(bodyCtParamsEscaped);
- }
- ct.append('"');
- }
-
-
- message.put(Message.CONTENT_TYPE, ct.toString());
-
-
- // 2. write headers
- out = message.getContent(OutputStream.class);
- encoding = (String) message.get(Message.ENCODING);
- if (encoding == null) {
- encoding = StandardCharsets.UTF_8.name();
- }
- StringWriter writer = new StringWriter();
- writer.write("\r\n");
- writer.write("--");
- writer.write(bodyBoundary);
-
- StringBuilder mimeBodyCt = new StringBuilder();
- String bodyType = getHeaderValue("Content-Type", null);
- if (bodyType == null) {
- mimeBodyCt.append(xop ? "application/xop+xml" : bodyCt)
- .append("; charset=").append(encoding);
- if (xop) {
- mimeBodyCt.append("; type=\"").append(bodyCt);
- if (bodyCtParamsEscaped != null) {
- mimeBodyCt.append(bodyCtParamsEscaped);
- }
- mimeBodyCt.append('"');
- } else if (bodyCtParams != null) {
- mimeBodyCt.append(bodyCtParams);
- }
- } else {
- mimeBodyCt.append(bodyType);
- }
-
- writeHeaders(mimeBodyCt.toString(), rootContentId, rootHeaders, writer);
- out.write(writer.getBuffer().toString().getBytes(encoding));
- }
-
- private static String escapeQuotes(String s) {
- return s.indexOf('"') != 0 ? s.replace("\"", "\\\"") : s;
- }
-
- public void setContentTransferEncoding(String cte) {
- contentTransferEncoding = cte;
- }
-
- private String getHeaderValue(String name, String defaultValue) {
- List<String> value = rootHeaders.get(name);
- if (value == null || value.isEmpty()) {
- return defaultValue;
- }
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < value.size(); i++) {
- sb.append(value.get(i));
- if (i + 1 < value.size()) {
- sb.append(',');
- }
- }
- return sb.toString();
- }
-
- private void writeHeaders(String contentType, String attachmentId,
- Map<String, List<String>> headers, Writer writer) throws IOException {
- writer.write("\r\nContent-Type: ");
- writer.write(contentType);
- writer.write("\r\nContent-Transfer-Encoding: " + contentTransferEncoding + "\r\n");
-
- if (attachmentId != null) {
- attachmentId = checkAngleBrackets(attachmentId);
- writer.write("Content-ID: <");
- writer.write(URLDecoder.decode(attachmentId, StandardCharsets.UTF_8.name()));
- writer.write(">\r\n");
- }
- // headers like Content-Disposition need to be serialized
- for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
- String name = entry.getKey();
- if ("Content-Type".equalsIgnoreCase(name) || "Content-ID".equalsIgnoreCase(name)
- || "Content-Transfer-Encoding".equalsIgnoreCase(name)) {
- continue;
- }
- writer.write(name);
- writer.write(": ");
- List<String> values = entry.getValue();
- for (int i = 0; i < values.size(); i++) {
- writer.write(values.get(i));
- if (i + 1 < values.size()) {
- writer.write(",");
- }
- }
- writer.write("\r\n");
- }
-
- writer.write("\r\n");
- }
-
- private static String checkAngleBrackets(String value) {
- if (value.charAt(0) == '<' && value.charAt(value.length() - 1) == '>') {
- return value.substring(1, value.length() - 1);
- }
- return value;
- }
-
- /**
- * Write the end of the body boundary and any attachments included.
- * @throws IOException
- */
- public void writeAttachments() throws IOException {
- if (message.getAttachments() != null) {
- for (Attachment a : message.getAttachments()) {
- StringWriter writer = new StringWriter();
- writer.write("\r\n--");
- writer.write(bodyBoundary);
-
- final Map<String, List<String>> headers;
- Iterator<String> it = a.getHeaderNames();
- if (it.hasNext()) {
- headers = new LinkedHashMap<>();
- while (it.hasNext()) {
- String key = it.next();
- headers.put(key, Collections.singletonList(a.getHeader(key)));
- }
- } else {
- headers = Collections.emptyMap();
- }
-
-
- DataHandler handler = a.getDataHandler();
- handler.setCommandMap(AttachmentUtil.getCommandMap());
-
- writeHeaders(handler.getContentType(), a.getId(),
- headers, writer);
- out.write(writer.getBuffer().toString().getBytes(encoding));
- if ("base64".equals(contentTransferEncoding)) {
- try (InputStream inputStream = handler.getInputStream()) {
- encodeBase64(inputStream, out, IOUtils.DEFAULT_BUFFER_SIZE);
- }
- } else {
- handler.writeTo(out);
- }
- }
- }
- StringWriter writer = new StringWriter();
- writer.write("\r\n--");
- writer.write(bodyBoundary);
- writer.write("--");
- out.write(writer.getBuffer().toString().getBytes(encoding));
- out.flush();
- }
-
- private int encodeBase64(InputStream input, OutputStream output, int bufferSize) throws IOException {
- int avail = input.available();
- if (avail > 262143) {
- //must be divisible by 3
- avail = 262143;
- }
- if (avail > bufferSize) {
- bufferSize = avail;
- }
- final byte[] buffer = new byte[bufferSize];
- int n = input.read(buffer);
- int total = 0;
- while (-1 != n) {
- if (n == 0) {
- throw new IOException("0 bytes read in violation of InputStream.read(byte[])");
- }
- //make sure n is divisible by 3
- int left = n % 3;
- n -= left;
- if (n > 0) {
- Base64Utility.encodeAndStream(buffer, 0, n, output);
- total += n;
- }
- if (left != 0) {
- for (int x = 0; x < left; ++x) {
- buffer[x] = buffer[n + x];
- }
- n = input.read(buffer, left, buffer.length - left);
- if (n == -1) {
- // we've hit the end, but still have stuff left, write it out
- Base64Utility.encodeAndStream(buffer, 0, left, output);
- total += left;
- }
- } else {
- n = input.read(buffer);
- }
- }
- return total;
- }
-
- public boolean isXop() {
- return xop;
- }
-
- public void setXop(boolean xop) {
- this.xop = xop;
- }
-
-}
diff --git a/transform/src/patch/java/org/apache/cxf/attachment/AttachmentUtil.java b/transform/src/patch/java/org/apache/cxf/attachment/AttachmentUtil.java
deleted file mode 100644
index 7c72f00..0000000
--- a/transform/src/patch/java/org/apache/cxf/attachment/AttachmentUtil.java
+++ /dev/null
@@ -1,572 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.attachment;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.UnsupportedEncodingException;
-import java.net.MalformedURLException;
-import java.net.URI;
-import java.net.URL;
-import java.net.URLDecoder;
-import java.net.URLEncoder;
-import java.nio.charset.StandardCharsets;
-import java.util.AbstractMap;
-import java.util.AbstractSet;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
-import java.util.Set;
-import java.util.UUID;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.logging.Logger;
-
-import javax.activation.CommandInfo;
-import javax.activation.CommandMap;
-import javax.activation.DataContentHandler;
-import javax.activation.DataHandler;
-import javax.activation.DataSource;
-import javax.activation.FileDataSource;
-import javax.activation.MailcapCommandMap;
-import javax.activation.URLDataSource;
-
-import org.apache.cxf.common.logging.LogUtils;
-import org.apache.cxf.common.util.StringUtils;
-import org.apache.cxf.helpers.FileUtils;
-import org.apache.cxf.interceptor.Fault;
-import org.apache.cxf.io.CachedOutputStream;
-import org.apache.cxf.message.Attachment;
-import org.apache.cxf.message.Message;
-import org.apache.cxf.message.MessageUtils;
-
-public final class AttachmentUtil {
- public static final String BODY_ATTACHMENT_ID = "root.message@cxf.apache.org";
-
- static final String BINARY = "binary";
-
- private static final Logger LOG = LogUtils.getL7dLogger(AttachmentUtil.class);
-
- private static final AtomicInteger COUNTER = new AtomicInteger();
- private static final String ATT_UUID = UUID.randomUUID().toString();
-
- private static final Random BOUND_RANDOM = new Random();
- private static final CommandMap DEFAULT_COMMAND_MAP = CommandMap.getDefaultCommandMap();
- private static final MailcapCommandMap COMMAND_MAP = new EnhancedMailcapCommandMap();
-
-
- static final class EnhancedMailcapCommandMap extends MailcapCommandMap {
- @Override
- public synchronized DataContentHandler createDataContentHandler(
- String mimeType) {
- DataContentHandler dch = super.createDataContentHandler(mimeType);
- if (dch == null) {
- dch = DEFAULT_COMMAND_MAP.createDataContentHandler(mimeType);
- }
- return dch;
- }
-
- @Override
- public DataContentHandler createDataContentHandler(String mimeType,
- DataSource ds) {
- DataContentHandler dch = super.createDataContentHandler(mimeType);
- if (dch == null) {
- dch = DEFAULT_COMMAND_MAP.createDataContentHandler(mimeType, ds);
- }
- return dch;
- }
-
- @Override
- public synchronized CommandInfo[] getAllCommands(String mimeType) {
- CommandInfo[] commands = super.getAllCommands(mimeType);
- CommandInfo[] defaultCommands = DEFAULT_COMMAND_MAP.getAllCommands(mimeType);
- List<CommandInfo> cmdList = new ArrayList<>(Arrays.asList(commands));
-
- // Add CommandInfo which does not exist in current command map.
- for (CommandInfo defCmdInfo : defaultCommands) {
- String defCmdName = defCmdInfo.getCommandName();
- boolean cmdNameExist = false;
- for (CommandInfo cmdInfo : commands) {
- if (cmdInfo.getCommandName().equals(defCmdName)) {
- cmdNameExist = true;
- break;
- }
- }
- if (!cmdNameExist) {
- cmdList.add(defCmdInfo);
- }
- }
-
- CommandInfo[] allCommandArray = new CommandInfo[0];
- return cmdList.toArray(allCommandArray);
- }
-
- @Override
- public synchronized CommandInfo getCommand(String mimeType, String cmdName) {
- CommandInfo cmdInfo = super.getCommand(mimeType, cmdName);
- if (cmdInfo == null) {
- cmdInfo = DEFAULT_COMMAND_MAP.getCommand(mimeType, cmdName);
- }
- return cmdInfo;
- }
-
- /**
- * Merge current mime types and default mime types.
- */
- @Override
- public synchronized String[] getMimeTypes() {
- String[] mimeTypes = super.getMimeTypes();
- String[] defMimeTypes = DEFAULT_COMMAND_MAP.getMimeTypes();
- Set<String> mimeTypeSet = new HashSet<>();
- Collections.addAll(mimeTypeSet, mimeTypes);
- Collections.addAll(mimeTypeSet, defMimeTypes);
- String[] mimeArray = new String[0];
- return mimeTypeSet.toArray(mimeArray);
- }
- }
-
-
- private AttachmentUtil() {
-
- }
-
- static {
- COMMAND_MAP.addMailcap("image/*;;x-java-content-handler="
- + ImageDataContentHandler.class.getName());
- }
-
- public static CommandMap getCommandMap() {
- return COMMAND_MAP;
- }
-
- public static boolean isMtomEnabled(Message message) {
- return MessageUtils.getContextualBoolean(message, Message.MTOM_ENABLED, false);
- }
-
- public static void setStreamedAttachmentProperties(Message message, CachedOutputStream bos)
- throws IOException {
- Object directory = message.getContextualProperty(AttachmentDeserializer.ATTACHMENT_DIRECTORY);
- if (directory != null) {
- if (directory instanceof File) {
- bos.setOutputDir((File) directory);
- } else if (directory instanceof String) {
- bos.setOutputDir(new File((String) directory));
- } else {
- throw new IOException("The value set as " + AttachmentDeserializer.ATTACHMENT_DIRECTORY
- + " should be either an instance of File or String");
- }
- }
-
- Object threshold = message.getContextualProperty(AttachmentDeserializer.ATTACHMENT_MEMORY_THRESHOLD);
- if (threshold != null) {
- if (threshold instanceof Number) {
- long t = ((Number) threshold).longValue();
- if (t >= 0) {
- bos.setThreshold(t);
- } else {
- LOG.warning("Threshold value overflowed long. Setting default value!");
- bos.setThreshold(AttachmentDeserializer.THRESHOLD);
- }
- } else if (threshold instanceof String) {
- try {
- bos.setThreshold(Long.parseLong((String) threshold));
- } catch (NumberFormatException e) {
- throw new IOException("Provided threshold String is not a number", e);
- }
- } else {
- throw new IOException("The value set as " + AttachmentDeserializer.ATTACHMENT_MEMORY_THRESHOLD
- + " should be either an instance of Number or String");
- }
- } else if (!CachedOutputStream.isThresholdSysPropSet()) {
- // Use the default AttachmentDeserializer Threshold only if there is no system property defined
- bos.setThreshold(AttachmentDeserializer.THRESHOLD);
- }
-
- Object maxSize = message.getContextualProperty(AttachmentDeserializer.ATTACHMENT_MAX_SIZE);
- if (maxSize != null) {
- if (maxSize instanceof Number) {
- long size = ((Number) maxSize).longValue();
- if (size >= 0) {
- bos.setMaxSize(size);
- } else {
- LOG.warning("Max size value overflowed long. Do not set max size!");
- }
- } else if (maxSize instanceof String) {
- try {
- bos.setMaxSize(Long.parseLong((String) maxSize));
- } catch (NumberFormatException e) {
- throw new IOException("Provided threshold String is not a number", e);
- }
- } else {
- throw new IOException("The value set as " + AttachmentDeserializer.ATTACHMENT_MAX_SIZE
- + " should be either an instance of Number or String");
- }
- }
- }
-
- public static String createContentID(String ns) throws UnsupportedEncodingException {
- // tend to change
- String cid = "cxf.apache.org";
- if (ns != null && !ns.isEmpty()) {
- try {
- URI uri = new URI(ns);
- String host = uri.getHost();
- if (host != null) {
- cid = host;
- } else {
- cid = ns;
- }
- } catch (Exception e) {
- cid = ns;
- }
- }
- return ATT_UUID + '-' + Integer.toString(COUNTER.incrementAndGet()) + '@'
- + URLEncoder.encode(cid, StandardCharsets.UTF_8.name());
- }
-
- public static String getUniqueBoundaryValue() {
- //generate a random UUID.
- //we don't need the cryptographically secure random uuid that
- //UUID.randomUUID() will produce. Thus, use a faster
- //pseudo-random thing
- long leastSigBits;
- long mostSigBits;
- synchronized (BOUND_RANDOM) {
- mostSigBits = BOUND_RANDOM.nextLong();
- leastSigBits = BOUND_RANDOM.nextLong();
- }
-
- mostSigBits &= 0xFFFFFFFFFFFF0FFFL; //clear version
- mostSigBits |= 0x0000000000004000L; //set version
-
- leastSigBits &= 0x3FFFFFFFFFFFFFFFL; //clear the variant
- leastSigBits |= 0x8000000000000000L; //set to IETF variant
-
- UUID result = new UUID(mostSigBits, leastSigBits);
-
- return "uuid:" + result.toString();
- }
-
- public static Map<String, DataHandler> getDHMap(final Collection<Attachment> attachments) {
- Map<String, DataHandler> dataHandlers = null;
- if (attachments != null) {
- if (attachments instanceof LazyAttachmentCollection) {
- dataHandlers = ((LazyAttachmentCollection)attachments).createDataHandlerMap();
- } else {
- dataHandlers = new DHMap(attachments);
- }
- }
- return dataHandlers == null ? new LinkedHashMap<>() : dataHandlers;
- }
-
- static class DHMap extends AbstractMap<String, DataHandler> {
- final Collection<Attachment> list;
- DHMap(Collection<Attachment> l) {
- list = l;
- }
- public Set<Map.Entry<String, DataHandler>> entrySet() {
- return new AbstractSet<Map.Entry<String, DataHandler>>() {
- @Override
- public Iterator<Map.Entry<String, DataHandler>> iterator() {
- final Iterator<Attachment> it = list.iterator();
- return new Iterator<Map.Entry<String, DataHandler>>() {
- public boolean hasNext() {
- return it.hasNext();
- }
- public Map.Entry<String, DataHandler> next() {
- final Attachment a = it.next();
- return new Map.Entry<String, DataHandler>() {
- @Override
- public String getKey() {
- return a.getId();
- }
-
- @Override
- public DataHandler getValue() {
- return a.getDataHandler();
- }
-
- @Override
- public DataHandler setValue(DataHandler value) {
- return null;
- }
- };
- }
- @Override
- public void remove() {
- it.remove();
- }
- };
- }
-
- @Override
- public int size() {
- return list.size();
- }
- };
- }
-
- @Override
- public DataHandler put(String key, DataHandler value) {
- Iterator<Attachment> i = list.iterator();
- DataHandler ret = null;
- while (i.hasNext()) {
- Attachment a = i.next();
- if (a.getId().equals(key)) {
- i.remove();
- ret = a.getDataHandler();
- break;
- }
- }
- list.add(new AttachmentImpl(key, value));
- return ret;
- }
- }
-
- public static String cleanContentId(String id) {
- if (id != null) {
- if (id.startsWith("<")) {
- // strip <>
- id = id.substring(1, id.length() - 1);
- }
- // strip cid:
- if (id.startsWith("cid:")) {
- id = id.substring(4);
- }
- // urldecode. Is this bad even without cid:? What does decode do with malformed %-signs, anyhow?
- try {
- id = URLDecoder.decode(id, StandardCharsets.UTF_8.name());
- } catch (UnsupportedEncodingException e) {
- //ignore, keep id as is
- }
- }
- if (id == null) {
- //no Content-ID, set cxf default ID
- id = BODY_ATTACHMENT_ID;
- }
- return id;
- }
-
- static String getHeaderValue(List<String> v) {
- if (v != null && !v.isEmpty()) {
- return v.get(0);
- }
- return null;
- }
- static String getHeaderValue(List<String> v, String delim) {
- if (v != null && !v.isEmpty()) {
- return String.join(delim, v);
- }
- return null;
- }
- static String getHeader(Map<String, List<String>> headers, String h) {
- return getHeaderValue(headers.get(h));
- }
- static String getHeader(Map<String, List<String>> headers, String h, String delim) {
- return getHeaderValue(headers.get(h), delim);
- }
- public static Attachment createAttachment(InputStream stream, Map<String, List<String>> headers)
- throws IOException {
-
- String id = cleanContentId(getHeader(headers, "Content-ID"));
-
- AttachmentImpl att = new AttachmentImpl(id);
-
- final String ct = getHeader(headers, "Content-Type");
- String cd = getHeader(headers, "Content-Disposition");
- String fileName = getContentDispositionFileName(cd);
-
- String encoding = null;
-
- for (Map.Entry<String, List<String>> e : headers.entrySet()) {
- String name = e.getKey();
- if ("Content-Transfer-Encoding".equalsIgnoreCase(name)) {
- encoding = getHeader(headers, name);
- if (BINARY.equalsIgnoreCase(encoding)) {
- att.setXOP(true);
- }
- }
- att.setHeader(name, getHeaderValue(e.getValue()));
- }
- if (encoding == null) {
- encoding = BINARY;
- }
- InputStream ins = decode(stream, encoding);
- if (ins != stream) {
- headers.remove("Content-Transfer-Encoding");
- }
- DataSource source = new AttachmentDataSource(ct, ins);
- if (!StringUtils.isEmpty(fileName)) {
- ((AttachmentDataSource)source).setName(FileUtils.stripPath(fileName));
- }
- att.setDataHandler(new DataHandler(source));
- return att;
- }
-
- static String getContentDispositionFileName(String cd) {
- if (StringUtils.isEmpty(cd)) {
- return null;
- }
- ContentDisposition c = new ContentDisposition(cd);
- String s = c.getParameter("filename");
- if (s == null) {
- s = c.getParameter("name");
- }
- return s;
- }
-
- public static InputStream decode(InputStream in, String encoding) throws IOException {
- if (encoding == null) {
- return in;
- }
- encoding = encoding.toLowerCase();
-
- // some encodings are just pass-throughs, with no real decoding.
- if (BINARY.equals(encoding)
- || "7bit".equals(encoding)
- || "8bit".equals(encoding)) {
- return in;
- } else if ("base64".equals(encoding)) {
- return new Base64DecoderStream(in);
- } else if ("quoted-printable".equals(encoding)) {
- return new QuotedPrintableDecoderStream(in);
- } else {
- throw new IOException("Unknown encoding " + encoding);
- }
- }
- public static boolean isTypeSupported(String contentType, List<String> types) {
- if (contentType == null) {
- return false;
- }
- contentType = contentType.toLowerCase();
- for (String s : types) {
- if (contentType.indexOf(s) != -1) {
- return true;
- }
- }
- return false;
- }
-
- public static Attachment createMtomAttachment(boolean isXop, String mimeType, String elementNS,
- byte[] data, int offset, int length, int threshold) {
- if (!isXop || length <= threshold) {
- return null;
- }
- if (mimeType == null) {
- mimeType = "application/octet-stream";
- }
-
- ByteDataSource source = new ByteDataSource(data, offset, length);
- source.setContentType(mimeType);
- DataHandler handler = new DataHandler(source);
-
- String id;
- try {
- id = AttachmentUtil.createContentID(elementNS);
- } catch (UnsupportedEncodingException e) {
- throw new Fault(e);
- }
- AttachmentImpl att = new AttachmentImpl(id, handler);
- att.setXOP(isXop);
- return att;
- }
-
- public static Attachment createMtomAttachmentFromDH(
- boolean isXop, DataHandler handler, String elementNS, int threshold) {
- if (!isXop) {
- return null;
- }
-
- // The following is just wrong. Even if the DataHandler has a stream, we should still
- // apply the threshold.
- try {
- DataSource ds = handler.getDataSource();
- if (ds instanceof FileDataSource) {
- FileDataSource fds = (FileDataSource)ds;
- File file = fds.getFile();
- if (file.length() < threshold) {
- return null;
- }
- } else if (ds.getClass().getName().endsWith("ObjectDataSource")) {
- Object o = handler.getContent();
- if (o instanceof String
- && ((String)o).length() < threshold) {
- return null;
- } else if (o instanceof byte[] && ((byte[])o).length < threshold) {
- return null;
- }
- }
- } catch (IOException e1) {
- // ignore, just do the normal attachment thing
- }
-
- String id;
- try {
- id = AttachmentUtil.createContentID(elementNS);
- } catch (UnsupportedEncodingException e) {
- throw new Fault(e);
- }
- AttachmentImpl att = new AttachmentImpl(id, handler);
- if (!StringUtils.isEmpty(handler.getName())) {
- //set Content-Disposition attachment header if filename isn't null
- String file = handler.getName();
- File f = new File(file);
- if (f.exists() && f.isFile()) {
- file = f.getName();
- }
- att.setHeader("Content-Disposition", "attachment;name=\"" + file + "\"");
- }
- att.setXOP(isXop);
- return att;
- }
-
- public static DataSource getAttachmentDataSource(String contentId, Collection<Attachment> atts) {
- // Is this right? - DD
- if (contentId.startsWith("cid:")) {
- try {
- contentId = URLDecoder.decode(contentId.substring(4), StandardCharsets.UTF_8.name());
- } catch (UnsupportedEncodingException ue) {
- contentId = contentId.substring(4);
- }
- return loadDataSource(contentId, atts);
- } else if (contentId.indexOf("://") == -1) {
- return loadDataSource(contentId, atts);
- } else {
- try {
- return new URLDataSource(new URL(contentId));
- } catch (MalformedURLException e) {
- throw new Fault(e);
- }
- }
-
- }
-
- private static DataSource loadDataSource(String contentId, Collection<Attachment> atts) {
- return new LazyDataSource(contentId, atts);
- }
-
-}
diff --git a/transform/src/patch/java/org/apache/cxf/attachment/Base64DecoderStream.java b/transform/src/patch/java/org/apache/cxf/attachment/Base64DecoderStream.java
deleted file mode 100644
index 134553f..0000000
--- a/transform/src/patch/java/org/apache/cxf/attachment/Base64DecoderStream.java
+++ /dev/null
@@ -1,196 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.attachment;
-
-import java.io.FilterInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-import org.apache.cxf.common.util.Base64Exception;
-import org.apache.cxf.common.util.Base64Utility;
-
-/**
- * An implementation of a FilterInputStream that decodes the
- * stream data in BASE64 encoding format. This version does the
- * decoding "on the fly" rather than decoding a single block of
- * data. Since this version is intended for use by the MimeUtilty class,
- * it also handles line breaks in the encoded data.
- */
-public class Base64DecoderStream extends FilterInputStream {
-
- static final String MAIL_BASE64_IGNOREERRORS = "mail.mime.base64.ignoreerrors";
-
- // number of decodeable units we'll try to process at one time. We'll attempt to read that much
- // data from the input stream and decode in blocks.
- static final int BUFFERED_UNITS = 2000;
-
- // can be overridden by a system property.
- protected boolean ignoreErrors;
-
- // buffer for reading in chars for decoding (which can support larger bulk reads)
- protected char[] encodedChars = new char[BUFFERED_UNITS * 4];
- // a buffer for one decoding unit's worth of data (3 bytes).
- protected byte[] decodedChars;
- // count of characters in the buffer
- protected int decodedCount;
- // index of the next decoded character
- protected int decodedIndex;
-
-
- public Base64DecoderStream(InputStream in) {
- super(in);
- }
-
- /**
- * Test for the existance of decoded characters in our buffer
- * of decoded data.
- *
- * @return True if we currently have buffered characters.
- */
- private boolean dataAvailable() {
- return decodedCount != 0;
- }
-
- /**
- * Decode a requested number of bytes of data into a buffer.
- *
- * @return true if we were able to obtain more data, false otherwise.
- */
- private boolean decodeStreamData() throws IOException {
- decodedIndex = 0;
-
- // fill up a data buffer with input data
- int readCharacters = fillEncodedBuffer();
-
- if (readCharacters > 0) {
- try {
- decodedChars = Base64Utility.decodeChunk(encodedChars, 0, readCharacters);
- } catch (Base64Exception e) {
- throw new IOException(e);
- }
- decodedCount = decodedChars.length;
- return true;
- }
- return false;
- }
-
-
- /**
- * Retrieve a single byte from the decoded characters buffer.
- *
- * @return The decoded character or -1 if there was an EOF condition.
- */
- private int getByte() throws IOException {
- if (!dataAvailable() && !decodeStreamData()) {
- return -1;
- }
- decodedCount--;
- // we need to ensure this doesn't get sign extended
- return decodedChars[decodedIndex++] & 0xff;
- }
-
- private int getBytes(byte[] data, int offset, int length) throws IOException {
-
- int readCharacters = 0;
- while (length > 0) {
- // need data? Try to get some
- if (!dataAvailable() && !decodeStreamData()) {
- // if we can't get this, return a count of how much we did get (which may be -1).
- return readCharacters > 0 ? readCharacters : -1;
- }
-
- // now copy some of the data from the decoded buffer to the target buffer
- int copyCount = Math.min(decodedCount, length);
- System.arraycopy(decodedChars, decodedIndex, data, offset, copyCount);
- decodedIndex += copyCount;
- decodedCount -= copyCount;
- offset += copyCount;
- length -= copyCount;
- readCharacters += copyCount;
- }
- return readCharacters;
- }
-
-
- /**
- * Fill our buffer of input characters for decoding from the
- * stream. This will attempt read a full buffer, but will
- * terminate on an EOF or read error. This will filter out
- * non-Base64 encoding chars and will only return a valid
- * multiple of 4 number of bytes.
- *
- * @return The count of characters read.
- */
- private int fillEncodedBuffer() throws IOException {
- int readCharacters = 0;
-
- while (true) {
- // get the next character from the stream
- int ch = in.read();
- // did we hit an EOF condition?
- if (ch == -1) {
- // now check to see if this is normal, or potentially an error
- // if we didn't get characters as a multiple of 4, we may need to complain about this.
- if ((readCharacters % 4) != 0) {
- throw new IOException("Base64 encoding error, data truncated: " + readCharacters + " "
- + new String(encodedChars, 0, readCharacters));
- }
- // return the count.
- return readCharacters;
- } else if (Base64Utility.isValidBase64(ch)) {
- // if this character is valid in a Base64 stream, copy it to the buffer.
- encodedChars[readCharacters++] = (char)ch;
- // if we've filled up the buffer, time to quit.
- if (readCharacters >= encodedChars.length) {
- return readCharacters;
- }
- }
-
- // we're filtering out whitespace and CRLF characters, so just ignore these
- }
- }
-
-
- // in order to function as a filter, these streams need to override the different
- // read() signature.
-
- @Override
- public int read() throws IOException {
- return getByte();
- }
-
-
- @Override
- public int read(byte [] buffer, int offset, int length) throws IOException {
- return getBytes(buffer, offset, length);
- }
-
-
- @Override
- public boolean markSupported() {
- return false;
- }
-
-
- @Override
- public int available() throws IOException {
- return ((in.available() / 4) * 3) + decodedCount;
- }
-}
diff --git a/transform/src/patch/java/org/apache/cxf/attachment/ContentDisposition.java b/transform/src/patch/java/org/apache/cxf/attachment/ContentDisposition.java
deleted file mode 100644
index f9d4524..0000000
--- a/transform/src/patch/java/org/apache/cxf/attachment/ContentDisposition.java
+++ /dev/null
@@ -1,144 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.attachment;
-
-import java.io.UnsupportedEncodingException;
-import java.util.Collections;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public class ContentDisposition {
- private static final String CD_HEADER_PARAMS_EXPRESSION =
- "[\\w-]++( )?\\*?=( )?((\"[^\"]++\")|([^;]+))";
- private static final Pattern CD_HEADER_PARAMS_PATTERN =
- Pattern.compile(CD_HEADER_PARAMS_EXPRESSION);
-
- private static final String CD_HEADER_EXT_PARAMS_EXPRESSION =
- "(?i)(UTF-8|ISO-8859-1)''((?:%[0-9a-f]{2}|\\S)+)";
- private static final Pattern CD_HEADER_EXT_PARAMS_PATTERN =
- Pattern.compile(CD_HEADER_EXT_PARAMS_EXPRESSION);
- private static final Pattern CODEPOINT_ENCODED_VALUE_PATTERN = Pattern.compile("&#[0-9]{4};|\\S");
-
- private static final String FILE_NAME = "filename";
-
- private String value;
- private String type;
- private Map<String, String> params = new LinkedHashMap<>();
-
- public ContentDisposition(String value) {
- this.value = value;
-
- String tempValue = value;
-
- int index = tempValue.indexOf(';');
- if (index > 0 && (tempValue.indexOf('=') >= index)) {
- type = tempValue.substring(0, index).trim();
- tempValue = tempValue.substring(index + 1);
- }
-
- String extendedFilename = null;
- Matcher m = CD_HEADER_PARAMS_PATTERN.matcher(tempValue);
- while (m.find()) {
- final String paramName;
- String paramValue = "";
-
- String groupValue = m.group().trim();
- int eqIndex = groupValue.indexOf('=');
- if (eqIndex > 0) {
- paramName = groupValue.substring(0, eqIndex).trim();
- if (eqIndex + 1 != groupValue.length()) {
- paramValue = groupValue.substring(eqIndex + 1).trim().replace("\"", "");
- }
- } else {
- paramName = groupValue;
- }
- // filename* looks like the only CD param that is human readable
- // and worthy of the extended encoding support. Other parameters
- // can be supported if needed, see the complete list below
- /*
- http://www.iana.org/assignments/cont-disp/cont-disp.xhtml#cont-disp-2
-
- filename name to be used when creating file [RFC2183]
- creation-date date when content was created [RFC2183]
- modification-date date when content was last modified [RFC2183]
- read-date date when content was last read [RFC2183]
- size approximate size of content in octets [RFC2183]
- name original field name in form [RFC2388]
- voice type or use of audio content [RFC2421]
- handling whether or not processing is required [RFC3204]
- */
- if ("filename*".equalsIgnoreCase(paramName)) {
- // try to decode the value if it matches the spec
- try {
- Matcher matcher = CD_HEADER_EXT_PARAMS_PATTERN.matcher(paramValue);
- if (matcher.matches()) {
- String encodingScheme = matcher.group(1);
- String encodedValue = matcher.group(2);
- paramValue = Rfc5987Util.decode(encodedValue, encodingScheme);
- extendedFilename = paramValue;
- }
- } catch (UnsupportedEncodingException e) {
- // would be odd not to support UTF-8 or 8859-1
- }
- } else if (FILE_NAME.equalsIgnoreCase(paramName) && paramValue.contains("&#")) {
- Matcher matcher = CODEPOINT_ENCODED_VALUE_PATTERN.matcher(paramValue);
- StringBuilder sb = new StringBuilder();
- while (matcher.find()) {
- String matched = matcher.group();
- if (matched.startsWith("&#")) {
- int codePoint = Integer.parseInt(matched.substring(2, 6));
- sb.append(Character.toChars(codePoint));
- } else {
- sb.append(matched.charAt(0));
- }
- }
- if (sb.length() > 0) {
- paramValue = sb.toString();
- }
- }
- params.put(paramName.toLowerCase(), paramValue);
- }
- if (extendedFilename != null) {
- params.put(FILE_NAME, extendedFilename);
- }
- }
-
- public String getType() {
- return type;
- }
-
- public String getFilename() {
- return params.get(FILE_NAME);
- }
-
- public String getParameter(String name) {
- return params.get(name);
- }
-
- public Map<String, String> getParameters() {
- return Collections.unmodifiableMap(params);
- }
-
- public String toString() {
- return value;
- }
-}
diff --git a/transform/src/patch/java/org/apache/cxf/attachment/LazyAttachmentCollection.java b/transform/src/patch/java/org/apache/cxf/attachment/LazyAttachmentCollection.java
deleted file mode 100644
index 8dd4ace..0000000
--- a/transform/src/patch/java/org/apache/cxf/attachment/LazyAttachmentCollection.java
+++ /dev/null
@@ -1,362 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cxf.attachment;
-
-import java.io.IOException;
-import java.util.AbstractCollection;
-import java.util.AbstractSet;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.activation.DataHandler;
-
-import org.apache.cxf.message.Attachment;
-
-public class LazyAttachmentCollection
- implements Collection<Attachment> {
-
- private AttachmentDeserializer deserializer;
- private final List<Attachment> attachments = new ArrayList<>();
- private final int maxAttachmentCount;
-
- public LazyAttachmentCollection(AttachmentDeserializer deserializer, int maxAttachmentCount) {
- super();
- this.deserializer = deserializer;
- this.maxAttachmentCount = maxAttachmentCount;
- }
-
- public List<Attachment> getLoadedAttachments() {
- return attachments;
- }
-
- private void loadAll() {
- try {
- Attachment a = deserializer.readNext();
- int count = 0;
- while (a != null) {
- attachments.add(a);
- count++;
- if (count > maxAttachmentCount) {
- throw new IOException("The message contains more attachments than are permitted");
- }
- a = deserializer.readNext();
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- /**
- * Check for more attachments by attempting to deserialize the next attachment.
- *
- * @param shouldLoadNew if <i>false</i>, the "loaded attachments" List will not be changed.
- * @return there is more attachment or not
- * @throws IOException
- */
- public boolean hasNext(boolean shouldLoadNew) throws IOException {
- if (shouldLoadNew) {
- Attachment a = deserializer.readNext();
- if (a != null) {
- attachments.add(a);
- return true;
- }
- return false;
- }
- return deserializer.hasNext();
- }
-
- public boolean hasNext() throws IOException {
- return hasNext(true);
- }
- public Iterator<Attachment> iterator() {
- return new Iterator<Attachment>() {
- int current;
- boolean removed;
-
- public boolean hasNext() {
- if (attachments.size() > current) {
- return true;
- }
-
- // check if there is another attachment
- try {
- Attachment a = deserializer.readNext();
- if (a == null) {
- return false;
- }
- attachments.add(a);
- return true;
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public Attachment next() {
- Attachment a = attachments.get(current);
- current++;
- removed = false;
- return a;
- }
-
- @Override
- public void remove() {
- if (removed) {
- throw new IllegalStateException();
- }
- attachments.remove(--current);
- removed = true;
- }
-
- };
- }
-
- public int size() {
- loadAll();
-
- return attachments.size();
- }
-
- public boolean add(Attachment arg0) {
- return attachments.add(arg0);
- }
-
- public boolean addAll(Collection<? extends Attachment> arg0) {
- return attachments.addAll(arg0);
- }
-
- public void clear() {
- attachments.clear();
- }
-
- public boolean contains(Object arg0) {
- return attachments.contains(arg0);
- }
-
- public boolean containsAll(Collection<?> arg0) {
- return attachments.containsAll(arg0);
- }
-
- public boolean isEmpty() {
- if (attachments.isEmpty()) {
- return !iterator().hasNext();
- }
- return attachments.isEmpty();
- }
-
- public boolean remove(Object arg0) {
- return attachments.remove(arg0);
- }
-
- public boolean removeAll(Collection<?> arg0) {
- return attachments.removeAll(arg0);
- }
-
- public boolean retainAll(Collection<?> arg0) {
- return attachments.retainAll(arg0);
- }
-
- public Object[] toArray() {
- loadAll();
-
- return attachments.toArray();
- }
-
- public <T> T[] toArray(T[] arg0) {
- loadAll();
-
- return attachments.toArray(arg0);
- }
-
- public Map<String, DataHandler> createDataHandlerMap() {
- return new LazyAttachmentMap(this);
- }
-
- private static class LazyAttachmentMap implements Map<String, DataHandler> {
- LazyAttachmentCollection collection;
-
- LazyAttachmentMap(LazyAttachmentCollection c) {
- collection = c;
- }
-
- public void clear() {
- collection.clear();
- }
-
- public boolean containsKey(Object key) {
- Iterator<Attachment> it = collection.iterator();
- while (it.hasNext()) {
- Attachment at = it.next();
- if (key.equals(at.getId())) {
- return true;
- }
- }
- return false;
- }
-
- public boolean containsValue(Object value) {
- Iterator<Attachment> it = collection.iterator();
- while (it.hasNext()) {
- Attachment at = it.next();
- if (value.equals(at.getDataHandler())) {
- return true;
- }
- }
- return false;
- }
-
- public DataHandler get(Object key) {
- Iterator<Attachment> it = collection.iterator();
- while (it.hasNext()) {
- Attachment at = it.next();
- if (key.equals(at.getId())) {
- return at.getDataHandler();
- }
- }
- return null;
- }
-
- public boolean isEmpty() {
- return collection.isEmpty();
- }
- public int size() {
- return collection.size();
- }
-
- public DataHandler remove(Object key) {
- Iterator<Attachment> it = collection.iterator();
- while (it.hasNext()) {
- Attachment at = it.next();
- if (key.equals(at.getId())) {
- collection.remove(at);
- return at.getDataHandler();
- }
- }
- return null;
- }
- public DataHandler put(String key, DataHandler value) {
- Attachment at = new AttachmentImpl(key, value);
- collection.add(at);
- return value;
- }
-
- public void putAll(Map<? extends String, ? extends DataHandler> t) {
- for (Map.Entry<? extends String, ? extends DataHandler> ent : t.entrySet()) {
- put(ent.getKey(), ent.getValue());
- }
- }
-
-
- public Set<Map.Entry<String, DataHandler>> entrySet() {
- return new AbstractSet<Map.Entry<String, DataHandler>>() {
- public Iterator<Map.Entry<String, DataHandler>> iterator() {
- return new Iterator<Map.Entry<String, DataHandler>>() {
- Iterator<Attachment> it = collection.iterator();
- public boolean hasNext() {
- return it.hasNext();
- }
- public Map.Entry<String, DataHandler> next() {
- return new Map.Entry<String, DataHandler>() {
- Attachment at = it.next();
- public String getKey() {
- return at.getId();
- }
- public DataHandler getValue() {
- return at.getDataHandler();
- }
- public DataHandler setValue(DataHandler value) {
- if (at instanceof AttachmentImpl) {
- DataHandler h = at.getDataHandler();
- ((AttachmentImpl)at).setDataHandler(value);
- return h;
- }
- throw new UnsupportedOperationException();
- }
- };
- }
- @Override
- public void remove() {
- it.remove();
- }
- };
- }
- public int size() {
- return collection.size();
- }
- };
- }
-
- public Set<String> keySet() {
- return new AbstractSet<String>() {
- public Iterator<String> iterator() {
- return new Iterator<String>() {
- Iterator<Attachment> it = collection.iterator();
- public boolean hasNext() {
- return it.hasNext();
- }
-
- public String next() {
- return it.next().getId();
- }
-
- @Override
- public void remove() {
- it.remove();
- }
- };
- }
-
- public int size() {
- return collection.size();
- }
- };
- }
-
-
- public Collection<DataHandler> values() {
- return new AbstractCollection<DataHandler>() {
- public Iterator<DataHandler> iterator() {
- return new Iterator<DataHandler>() {
- Iterator<Attachment> it = collection.iterator();
- public boolean hasNext() {
- return it.hasNext();
- }
- public DataHandler next() {
- return it.next().getDataHandler();
- }
- @Override
- public void remove() {
- it.remove();
- }
- };
- }
-
- public int size() {
- return collection.size();
- }
- };
- }
-
- }
-
-
-}
diff --git a/transform/src/patch/java/org/apache/cxf/attachment/MimeBodyPartInputStream.java b/transform/src/patch/java/org/apache/cxf/attachment/MimeBodyPartInputStream.java
deleted file mode 100644
index ab80b89..0000000
--- a/transform/src/patch/java/org/apache/cxf/attachment/MimeBodyPartInputStream.java
+++ /dev/null
@@ -1,275 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cxf.attachment;
-
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.PushbackInputStream;
-
-public class MimeBodyPartInputStream extends InputStream {
-
- PushbackInputStream inStream;
-
- boolean boundaryFound;
- int pbAmount;
- byte[] boundary;
- byte[] boundaryBuffer;
-
- private boolean closed;
-
- public MimeBodyPartInputStream(PushbackInputStream inStreamParam,
- byte[] boundaryParam,
- int pbsize) {
- super();
- this.inStream = inStreamParam;
- this.boundary = boundaryParam;
- this.pbAmount = pbsize;
- }
-
- @Override
- public int read(byte[] buf, int origOff, int origLen) throws IOException {
- byte[] b = buf;
- int off = origOff;
- int len = origLen;
- if (boundaryFound || closed) {
- return -1;
- }
- if ((off < 0) || (off > b.length) || (len < 0)
- || ((off + len) > b.length) || ((off + len) < 0)) {
-
- throw new IndexOutOfBoundsException();
- }
- if (len == 0) {
- return 0;
- }
- boolean bufferCreated = false;
- if (len < boundary.length * 2) {
- //buffer is too short to detect boundaries with it. We'll need to create a larger buffer
- bufferCreated = true;
- if (boundaryBuffer == null) {
- boundaryBuffer = new byte[boundary.length * 2];
- }
- b = boundaryBuffer;
- off = 0;
- len = boundaryBuffer.length;
- }
- if (len > pbAmount) {
- len = pbAmount; //can only pushback that much so make sure we can
- }
- int read = 0;
- int idx = 0;
- while (read >= 0 && idx < len && idx < (boundary.length * 2)) {
- //make sure we read enough to detect the boundary
- read = inStream.read(b, off + idx, len - idx);
- if (read != -1) {
- idx += read;
- }
- }
- if (read == -1 && idx == 0) {
- return -1;
- }
- len = idx;
-
- int i = processBuffer(b, off, len);
- if (bufferCreated && i > 0) {
- // read more than we need, push it back
- if (origLen >= i) {
- System.arraycopy(b, 0, buf, origOff, i);
- } else {
- System.arraycopy(b, 0, buf, origOff, origLen);
- inStream.unread(b, origLen, i - origLen);
- i = origLen;
- }
- } else if (i == 0 && boundaryFound) {
- return -1;
- }
-
- return i;
- }
-
- //Has Data after encountering CRLF
- private boolean hasData(byte[] b, int initialPointer, int pointer, int off, int len)
- throws IOException {
- if (pointer < (off + len)) {
- return true;
- } else if (pointer >= 1000000000) {
- inStream.unread(b, initialPointer, (off + len) - initialPointer);
- return false;
- } else {
- int x = inStream.read();
- if (x != -1) {
- inStream.unread(x);
- inStream.unread(b, initialPointer, (off + len) - initialPointer);
- return false;
- }
- return true;
- }
- }
-
- protected int processBuffer(byte[] buffer, int off, int len) throws IOException {
- for (int i = off; i < (off + len); i++) {
- boolean needUnread0d0a = false;
- int value = buffer[i];
- int initialI = i;
- if (value == 13) {
- if (!hasData(buffer, initialI, initialI + 1, off, len)) {
- return initialI - off;
- }
- value = buffer[initialI + 1];
- if (value != 10) {
- continue;
- }
- if (!hasData(buffer, initialI, initialI + 2, off, len)) {
- return initialI - off;
- }
- value = buffer[initialI + 2];
- if ((byte) value != boundary[0]) {
- i++;
- continue;
- }
- needUnread0d0a = true;
- i += 2; //i after this points to boundary[0] element
- } else if (value != boundary[0]) {
- continue;
- }
-
- int boundaryIndex = 0;
- while ((boundaryIndex < boundary.length) && (value == boundary[boundaryIndex])) {
- if (!hasData(buffer, initialI, i + 1, off, len)) {
- return initialI - off;
- }
- value = buffer[++i];
- boundaryIndex++;
- }
- if (boundaryIndex == boundary.length) {
- // read the end of line character
- if (initialI != off) {
- i = 1000000000;
- }
- if (initialI - off != 0
- && !hasData(buffer, initialI, i + 1, off, len)) {
- return initialI - off;
- }
- boundaryFound = true;
- int j = i + 1;
- if (j < len && buffer[j] == 45 && value == 45) {
- // Last mime boundary should have a succeeding "--"
- // as we are on it, read the terminating CRLF
- i += 2;
- //last mime boundary
- }
-
- //boundary matched (may or may not be last mime boundary)
- int processed = initialI - off;
- if ((len - ((i - off) + 2)) > 0) {
- inStream.unread(buffer, i + 2, len - (i + 2) + off);
- }
- return processed;
- }
-
- // Boundary not found. Restoring bytes skipped.
- // write first skipped byte, push back the rest
- if (value != -1) { //pushing back first byte of boundary
- // Stream might have ended
- i--;
- }
- if (needUnread0d0a) { //Pushing all, returning 13
- i = i - boundaryIndex;
- i--; //for 10
-// value = 13;
- } else {
- i = i - boundaryIndex;
- i++;
-// value = boundary[0];
- }
- }
- return len;
- }
-
- public int read() throws IOException {
- boolean needUnread0d0a = false;
- if (boundaryFound) {
- return -1;
- }
-
- // read the next value from stream
- int value = inStream.read();
- // A problem occurred because all the mime parts tends to have a /r/n
- // at the end. Making it hard to transform them to correct
- // DataSources.
- // This logic introduced to handle it
- if (value == 13) {
- value = inStream.read();
- if (value != 10) {
- inStream.unread(value);
- return 13;
- }
- value = inStream.read();
- if ((byte) value != boundary[0]) {
- inStream.unread(value);
- inStream.unread(10);
- return 13;
- }
- needUnread0d0a = true;
- } else if ((byte) value != boundary[0]) {
- return value;
- }
- // read value is the first byte of the boundary. Start matching the
- // next characters to find a boundary
- int boundaryIndex = 0;
- while ((boundaryIndex < boundary.length) && ((byte) value == boundary[boundaryIndex])) {
- value = inStream.read();
- boundaryIndex++;
- }
- if (boundaryIndex == boundary.length) {
- // boundary found
- boundaryFound = true;
- int dashNext = inStream.read();
- // read the end of line character
- if (dashNext == 45 && value == 45) {
- // Last mime boundary should have a succeeding "--"
- // as we are on it, read the terminating CRLF
- inStream.read();
- inStream.read();
- }
- return -1;
- }
- // Boundary not found. Restoring bytes skipped.
- // write first skipped byte, push back the rest
- if (value != -1) {
- // Stream might have ended
- inStream.unread(value);
- }
- if (needUnread0d0a) {
- inStream.unread(boundary, 0, boundaryIndex);
- inStream.unread(10);
- value = 13;
- } else {
- inStream.unread(boundary, 1, boundaryIndex - 1);
- value = boundary[0];
- }
- return value;
- }
-
- @Override
- public void close() throws IOException {
- this.closed = true;
- }
-}
diff --git a/transform/src/patch/java/org/apache/cxf/bus/CXFBusFactory.java b/transform/src/patch/java/org/apache/cxf/bus/CXFBusFactory.java
deleted file mode 100644
index fb3a833..0000000
--- a/transform/src/patch/java/org/apache/cxf/bus/CXFBusFactory.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.bus;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.cxf.Bus;
-import org.apache.cxf.BusFactory;
-import org.apache.cxf.bus.extension.ExtensionManagerBus;
-
-public class CXFBusFactory extends BusFactory {
-
- public Bus createBus() {
- return createBus(new HashMap<>());
- }
-
- public Bus createBus(Map<Class<?>, Object> e) {
- return createBus(e, new HashMap<>());
- }
-
- public Bus createBus(Map<Class<?>, Object> e, Map<String, Object> properties) {
- ExtensionManagerBus bus = new ExtensionManagerBus(e, properties);
- possiblySetDefaultBus(bus);
- initializeBus(bus);
- bus.initialize();
- return bus;
- }
-
-}
diff --git a/transform/src/patch/java/org/apache/cxf/bus/blueprint/BundleDelegatingClassLoader.java b/transform/src/patch/java/org/apache/cxf/bus/blueprint/BundleDelegatingClassLoader.java
deleted file mode 100644
index ff957c2..0000000
--- a/transform/src/patch/java/org/apache/cxf/bus/blueprint/BundleDelegatingClassLoader.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cxf.bus.blueprint;
-
-import java.io.IOException;
-import java.net.URL;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Enumeration;
-
-import org.osgi.framework.Bundle;
-
-/**
- * A ClassLoader delegating to a given OSGi bundle.
- */
-public class BundleDelegatingClassLoader extends ClassLoader {
-
- private final Bundle bundle;
- private final ClassLoader classLoader;
-
- public BundleDelegatingClassLoader(Bundle bundle) {
- this(bundle, null);
- }
-
- public BundleDelegatingClassLoader(Bundle bundle, ClassLoader classLoader) {
- this.bundle = bundle;
- this.classLoader = classLoader;
- }
-
- @Override
- protected Class<?> findClass(final String name) throws ClassNotFoundException {
- try {
- return AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>() {
- public Class<?> run() throws ClassNotFoundException {
- return bundle.loadClass(name);
- }
- });
- } catch (PrivilegedActionException e) {
- Exception cause = e.getException();
-
- if (cause instanceof ClassNotFoundException) {
- throw (ClassNotFoundException)cause;
- }
- throw (RuntimeException)cause;
- }
- }
-
- @Override
- protected URL findResource(final String name) {
- URL resource = AccessController.doPrivileged(new PrivilegedAction<URL>() {
- public URL run() {
- return bundle.getResource(name);
- }
- });
- if (classLoader != null && resource == null) {
- resource = classLoader.getResource(name);
- }
- return resource;
- }
-
- @Override
- protected Enumeration<URL> findResources(final String name) throws IOException {
- Enumeration<URL> urls;
- try {
- urls = AccessController.doPrivileged(new PrivilegedExceptionAction<Enumeration<URL>>() {
- public Enumeration<URL> run() throws IOException {
- return bundle.getResources(name);
- }
-
- });
- } catch (PrivilegedActionException e) {
- Exception cause = e.getException();
-
- if (cause instanceof IOException) {
- throw (IOException)cause;
- }
- throw (RuntimeException)cause;
- }
-
- if (urls == null) {
- urls = Collections.enumeration(new ArrayList<>());
- }
-
- return urls;
- }
-
- @Override
- protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
- Class<?> clazz;
- try {
- clazz = findClass(name);
- } catch (ClassNotFoundException cnfe) {
- if (classLoader != null) {
- try {
- clazz = classLoader.loadClass(name);
- } catch (ClassNotFoundException e) {
- throw new ClassNotFoundException(name + " from bundle " + bundle.getBundleId()
- + " (" + bundle.getSymbolicName() + ")", cnfe);
- }
- } else {
- throw new ClassNotFoundException(name + " from bundle " + bundle.getBundleId()
- + " (" + bundle.getSymbolicName() + ")", cnfe);
- }
- }
- if (resolve) {
- resolveClass(clazz);
- }
- return clazz;
- }
-
- public Bundle getBundle() {
- return bundle;
- }
-}
diff --git a/transform/src/patch/java/org/apache/cxf/bus/blueprint/BusDefinitionParser.java b/transform/src/patch/java/org/apache/cxf/bus/blueprint/BusDefinitionParser.java
deleted file mode 100644
index baf83b7..0000000
--- a/transform/src/patch/java/org/apache/cxf/bus/blueprint/BusDefinitionParser.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.bus.blueprint;
-
-
-import org.w3c.dom.Element;
-
-import org.apache.aries.blueprint.ParserContext;
-import org.apache.aries.blueprint.mutable.MutableBeanMetadata;
-import org.apache.cxf.common.util.StringUtils;
-import org.apache.cxf.configuration.blueprint.AbstractBPBeanDefinitionParser;
-import org.osgi.service.blueprint.reflect.Metadata;
-
-public class BusDefinitionParser
- extends AbstractBPBeanDefinitionParser {
-
- public BusDefinitionParser() {
- }
-
- public Metadata parse(Element element, ParserContext context) {
- String bname = element.hasAttribute("bus") ? element.getAttribute("bus") : "cxf";
- String id = element.hasAttribute("id") ? element.getAttribute("id") : null;
- MutableBeanMetadata cxfBean = getBus(context, bname);
- parseAttributes(element, context, cxfBean);
- parseChildElements(element, context, cxfBean);
- context.getComponentDefinitionRegistry().removeComponentDefinition(bname);
- if (!StringUtils.isEmpty(id)) {
- cxfBean.addProperty("id", createValue(context, id));
- }
- return cxfBean;
- }
-
- @Override
- protected void processBusAttribute(Element element, ParserContext ctx,
- MutableBeanMetadata bean, String val) {
- //nothing
- }
-
- @Override
- protected boolean hasBusProperty() {
- return false;
- }
-
-
- @Override
- protected void mapElement(ParserContext ctx, MutableBeanMetadata bean, Element el, String name) {
- if ("inInterceptors".equals(name) || "inFaultInterceptors".equals(name)
- || "outInterceptors".equals(name) || "outFaultInterceptors".equals(name)
- || "features".equals(name)) {
- bean.addProperty(name, parseListData(ctx, bean, el));
- } else if ("properties".equals(name)) {
- bean.addProperty(name, parseMapData(ctx, bean, el));
- }
- }
-}
diff --git a/transform/src/patch/java/org/apache/cxf/bus/blueprint/ConfigurerImpl.java b/transform/src/patch/java/org/apache/cxf/bus/blueprint/ConfigurerImpl.java
deleted file mode 100644
index 37f82fe..0000000
--- a/transform/src/patch/java/org/apache/cxf/bus/blueprint/ConfigurerImpl.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.bus.blueprint;
-
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.TreeMap;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
-import org.apache.cxf.common.logging.LogUtils;
-import org.apache.cxf.configuration.Configurable;
-import org.apache.cxf.configuration.Configurer;
-import org.osgi.service.blueprint.container.BlueprintContainer;
-import org.osgi.service.blueprint.container.NoSuchComponentException;
-import org.osgi.service.blueprint.reflect.BeanMetadata;
-import org.osgi.service.blueprint.reflect.ComponentMetadata;
-
-/**
- *
- */
-public class ConfigurerImpl implements Configurer {
- private static final Logger LOG = LogUtils.getL7dLogger(ConfigurerImpl.class);
- BlueprintContainer container;
-
- private final Map<String, List<MatcherHolder>> wildCardBeanDefinitions
- = new TreeMap<>();
-
- static class MatcherHolder implements Comparable<MatcherHolder> {
- Matcher matcher;
- String wildCardId;
- MatcherHolder(String orig, Matcher matcher) {
- wildCardId = orig;
- this.matcher = matcher;
- }
- @Override
- public int compareTo(MatcherHolder mh) {
- int literalCharsLen1 = this.wildCardId.replace("*", "").length();
- int literalCharsLen2 = mh.wildCardId.replace("*", "").length();
- // The expression with more literal characters should end up on the top of the list
- return Integer.compare(literalCharsLen1, literalCharsLen2) * -1;
- }
- }
-
- public ConfigurerImpl(BlueprintContainer con) {
- container = con;
- initializeWildcardMap();
- }
- private boolean isWildcardBeanName(String bn) {
- return bn.indexOf('*') != -1 || bn.indexOf('?') != -1
- || (bn.indexOf('(') != -1 && bn.indexOf(')') != -1);
- }
-
- private void initializeWildcardMap() {
- for (String s : container.getComponentIds()) {
- if (isWildcardBeanName(s)) {
- ComponentMetadata cmd = container.getComponentMetadata(s);
- Class<?> cls = BlueprintBeanLocator.getClassForMetaData(container, cmd);
- if (cls != null) {
- final String cid = s.charAt(0) != '*' ? s
- : "." + s.replaceAll("\\.", "\\."); //old wildcard
- Matcher matcher = Pattern.compile(cid).matcher("");
- List<MatcherHolder> m = wildCardBeanDefinitions.get(cls.getName());
- if (m == null) {
- m = new ArrayList<>();
- wildCardBeanDefinitions.put(cls.getName(), m);
- }
- MatcherHolder holder = new MatcherHolder(s, matcher);
- m.add(holder);
- }
- }
- }
- }
-
- public void configureBean(Object beanInstance) {
- configureBean(null, beanInstance, true);
- }
-
- public void configureBean(String bn, Object beanInstance) {
- configureBean(bn, beanInstance, true);
- }
- public synchronized void configureBean(String bn, Object beanInstance, boolean checkWildcards) {
- if (null == bn) {
- bn = getBeanName(beanInstance);
- }
-
- if (null == bn) {
- return;
- }
- if (checkWildcards) {
- configureWithWildCard(bn, beanInstance);
- }
-
- if (container instanceof ExtendedBlueprintContainer) {
- try {
- final ComponentMetadata cm = container.getComponentMetadata(bn);
- if (cm instanceof BeanMetadata) {
- ((ExtendedBlueprintContainer)container).injectBeanInstance((BeanMetadata)cm, beanInstance);
- }
- } catch (NoSuchComponentException nsce) {
- }
- }
- }
-
- private void configureWithWildCard(String bn, Object beanInstance) {
- if (!wildCardBeanDefinitions.isEmpty()) {
- Class<?> clazz = beanInstance.getClass();
- while (!Object.class.equals(clazz)) {
- String className = clazz.getName();
- List<MatcherHolder> matchers = wildCardBeanDefinitions.get(className);
- if (matchers != null) {
- for (MatcherHolder m : matchers) {
- synchronized (m.matcher) {
- m.matcher.reset(bn);
- if (m.matcher.matches()) {
- configureBean(m.wildCardId, beanInstance, false);
- return;
- }
- }
- }
- }
- clazz = clazz.getSuperclass();
- }
- }
- }
-
- protected String getBeanName(Object beanInstance) {
- if (beanInstance instanceof Configurable) {
- return ((Configurable)beanInstance).getBeanName();
- }
- String beanName = null;
- Method m = null;
- try {
- m = beanInstance.getClass().getDeclaredMethod("getBeanName", (Class[])null);
- } catch (NoSuchMethodException ex) {
- try {
- m = beanInstance.getClass().getMethod("getBeanName", (Class[])null);
- } catch (NoSuchMethodException e) {
- //ignore
- }
- }
- if (m != null) {
- try {
- beanName = (String)(m.invoke(beanInstance));
- } catch (Exception ex) {
- LogUtils.log(LOG, Level.WARNING, "ERROR_DETERMINING_BEAN_NAME_EXC", ex);
- }
- }
-
- if (null == beanName) {
- LogUtils.log(LOG, Level.FINE, "COULD_NOT_DETERMINE_BEAN_NAME_MSG",
- beanInstance.getClass().getName());
- }
-
- return beanName;
- }
-
-}
diff --git a/transform/src/patch/java/org/apache/cxf/bus/extension/Extension.java b/transform/src/patch/java/org/apache/cxf/bus/extension/Extension.java
deleted file mode 100644
index 03f0dc6..0000000
--- a/transform/src/patch/java/org/apache/cxf/bus/extension/Extension.java
+++ /dev/null
@@ -1,291 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.bus.extension;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import org.apache.cxf.Bus;
-import org.apache.cxf.common.i18n.Message;
-import org.apache.cxf.common.logging.LogUtils;
-import org.apache.cxf.common.util.StringUtils;
-
-public class Extension {
- protected static final Logger LOG = LogUtils.getL7dLogger(Extension.class);
-
- private static final String PROBLEM_CREATING_EXTENSION_CLASS = "PROBLEM_CREATING_EXTENSION_CLASS";
-
- protected String className;
- protected ClassLoader classloader;
- protected volatile Class<?> clazz;
- protected volatile Class<?> intf;
- protected String interfaceName;
- protected boolean deferred;
- protected Collection<String> namespaces = new ArrayList<>();
- protected Object[] args;
- protected volatile Object obj;
- protected boolean optional;
- protected boolean notFound;
-
-
- public Extension() {
- }
-
- public Extension(Class<?> cls, Class<?> inf) {
- clazz = cls;
- intf = inf;
- interfaceName = inf.getName();
- className = cls.getName();
- classloader = cls.getClassLoader();
- }
- public Extension(Class<?> cls) {
- clazz = cls;
- className = cls.getName();
- classloader = cls.getClassLoader();
- }
- public Extension(ClassLoader loader) {
- classloader = loader;
- }
-
- public Extension(Extension ext) {
- className = ext.className;
- interfaceName = ext.interfaceName;
- deferred = ext.deferred;
- namespaces = ext.namespaces;
- obj = ext.obj;
- clazz = ext.clazz;
- intf = ext.intf;
- classloader = ext.classloader;
- args = ext.args;
- optional = ext.optional;
- }
-
- public void setOptional(boolean b) {
- optional = b;
- }
- public boolean isOptional() {
- return optional;
- }
-
- public String getName() {
- return StringUtils.isEmpty(interfaceName) ? className : interfaceName;
- }
- public Object getLoadedObject() {
- return obj;
- }
-
- public Extension cloneNoObject() {
- Extension ext = new Extension(this);
- ext.obj = null;
- ext.clazz = null;
- ext.intf = null;
- return ext;
- }
-
- public String toString() {
- StringBuilder buf = new StringBuilder(128);
- buf.append("class: ");
- buf.append(className);
- buf.append(", interface: ");
- buf.append(interfaceName);
- buf.append(", deferred: ");
- buf.append(deferred ? "true" : "false");
- buf.append(", namespaces: (");
- int n = 0;
- for (String ns : namespaces) {
- if (n > 0) {
- buf.append(", ");
- }
- buf.append(ns);
- n++;
- }
- buf.append(')');
- return buf.toString();
- }
-
- public String getClassname() {
- return className;
- }
-
- public void setClassname(String i) {
- clazz = null;
- notFound = false;
- className = i;
- }
-
- public String getInterfaceName() {
- return interfaceName;
- }
-
- public void setInterfaceName(String i) {
- interfaceName = i;
- notFound = false;
- }
-
- public boolean isDeferred() {
- return deferred;
- }
-
- public void setDeferred(boolean d) {
- deferred = d;
- }
-
- public Collection<String> getNamespaces() {
- return namespaces;
- }
-
- public void setArgs(Object[] a) {
- args = a;
- }
-
- protected Class<?> tryClass(String name, ClassLoader cl) {
- Throwable origEx = null;
- if (classloader != null) {
- try {
- return classloader.loadClass(name);
- } catch (Throwable nex) {
- //ignore, fall into the stuff below
- //save the exception though as this is likely the important one
- origEx = nex;
- }
- }
- try {
- return cl.loadClass(name);
- } catch (Throwable ex) {
- try {
- // using the extension classloader as a fallback
- return this.getClass().getClassLoader().loadClass(name);
- } catch (Throwable nex) {
- notFound = true;
- if (!optional) {
- throw new ExtensionException(new Message("PROBLEM_LOADING_EXTENSION_CLASS", LOG, name),
- origEx != null ? origEx : ex);
- }
- }
- }
- return null;
- }
-
- public Class<?> getClassObject(ClassLoader cl) {
- if (notFound) {
- return null;
- }
- if (clazz != null) {
- return clazz;
- }
- synchronized (this) {
- if (clazz == null) {
- clazz = tryClass(className, cl);
- }
- }
- return clazz;
- }
- public Object load(ClassLoader cl, Bus b) {
- if (obj != null) {
- return obj;
- }
- Class<?> cls = getClassObject(cl);
- try {
- if (notFound) {
- return null;
- }
- try {
- //if there is a Bus constructor, use it.
- if (b != null && args == null) {
- Constructor<?> con = cls.getConstructor(Bus.class);
- obj = con.newInstance(b);
- return obj;
- } else if (b != null && args != null) {
- try {
- obj = cls.getConstructor(Bus.class, Object[].class).newInstance(b, args);
- } catch (NoSuchMethodException ex) { // no bus
- obj = cls.getConstructor(Object[].class).newInstance(args);
- }
- return obj;
- } else if (args != null) {
- Constructor<?> con = cls.getConstructor(Object[].class);
- obj = con.newInstance(args);
- return obj;
- }
- } catch (InvocationTargetException ex) {
- throw new ExtensionException(new Message(PROBLEM_CREATING_EXTENSION_CLASS, LOG, cls.getName()),
- ex.getCause());
- } catch (InstantiationException | SecurityException ex) {
- throw new ExtensionException(new Message(PROBLEM_CREATING_EXTENSION_CLASS, LOG, cls.getName()), ex);
- } catch (NoSuchMethodException e) {
- //ignore
- }
- obj = cls.getConstructor().newInstance();
- } catch (ExtensionException ex) {
- notFound = true;
- if (!optional) {
- throw ex;
- }
- LOG.log(Level.FINE, "Could not load optional extension " + getName(), ex);
- } catch (InvocationTargetException ex) {
- notFound = true;
- if (!optional) {
- throw new ExtensionException(new Message(PROBLEM_CREATING_EXTENSION_CLASS, LOG, cls.getName()),
- ex.getCause());
- }
- LOG.log(Level.FINE, "Could not load optional extension " + getName(), ex);
- } catch (NoSuchMethodException ex) {
- notFound = true;
- List<Object> a = new ArrayList<>();
- if (b != null) {
- a.add(b);
- }
- if (args != null) {
- a.add(args);
- }
- if (!optional) {
- throw new ExtensionException(new Message("PROBLEM_FINDING_CONSTRUCTOR", LOG,
- cls.getName(), a), ex);
- }
- LOG.log(Level.FINE, "Could not load optional extension " + getName(), ex);
- } catch (Throwable e) {
- notFound = true;
- if (!optional) {
- throw new ExtensionException(new Message(PROBLEM_CREATING_EXTENSION_CLASS, LOG, cls.getName()), e);
- }
- LOG.log(Level.FINE, "Could not load optional extension " + getName(), e);
- }
- return obj;
- }
-
- public Class<?> loadInterface(ClassLoader cl) {
- if (intf != null || notFound) {
- return intf;
- }
- synchronized (this) {
- if (intf == null) {
- intf = tryClass(interfaceName, cl);
- }
- }
- return intf;
- }
-
-
-}
diff --git a/transform/src/patch/java/org/apache/cxf/bus/extension/ExtensionManagerImpl.java b/transform/src/patch/java/org/apache/cxf/bus/extension/ExtensionManagerImpl.java
deleted file mode 100644
index d4ce0be..0000000
--- a/transform/src/patch/java/org/apache/cxf/bus/extension/ExtensionManagerImpl.java
+++ /dev/null
@@ -1,381 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.bus.extension;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.lang.reflect.Method;
-import java.net.URL;
-import java.security.AccessController;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-import java.util.Collection;
-import java.util.Enumeration;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.CopyOnWriteArrayList;
-
-import org.apache.cxf.Bus;
-import org.apache.cxf.common.injection.ResourceInjector;
-import org.apache.cxf.configuration.ConfiguredBeanLocator;
-import org.apache.cxf.configuration.Configurer;
-import org.apache.cxf.resource.ObjectTypeResolver;
-import org.apache.cxf.resource.ResourceManager;
-import org.apache.cxf.resource.ResourceResolver;
-import org.apache.cxf.resource.SinglePropertyResolver;
-
-public class ExtensionManagerImpl implements ExtensionManager, ConfiguredBeanLocator {
- public static final String EXTENSIONMANAGER_PROPERTY_NAME = "extensionManager";
- public static final String ACTIVATION_NAMESPACES_PROPERTY_NAME = "activationNamespaces";
- public static final String ACTIVATION_NAMESPACES_SETTER_METHOD_NAME = "setActivationNamespaces";
- public static final String BUS_EXTENSION_RESOURCE = "META-INF/cxf/bus-extensions.txt";
-
- private final ClassLoader loader;
- private ResourceManager resourceManager;
- private Map<String, Extension> all = new ConcurrentHashMap<>();
- private List<Extension> ordered = new CopyOnWriteArrayList<>();
- private final Map<Class<?>, Object> activated;
- private final Bus bus;
-
- public ExtensionManagerImpl(ClassLoader cl, Map<Class<?>, Object> initialExtensions,
- ResourceManager rm, Bus b) {
- this(new String[] {BUS_EXTENSION_RESOURCE},
- cl, initialExtensions, rm, b);
- }
- public ExtensionManagerImpl(String resource,
- ClassLoader cl,
- Map<Class<?>, Object> initialExtensions,
- ResourceManager rm,
- Bus b) {
- this(new String[] {resource}, cl, initialExtensions, rm, b);
- }
- public ExtensionManagerImpl(String[] resources,
- ClassLoader cl,
- Map<Class<?>, Object> initialExtensions,
- ResourceManager rm,
- Bus b) {
-
- loader = cl;
- bus = b;
- activated = initialExtensions;
- resourceManager = rm;
-
- ResourceResolver extensionManagerResolver =
- new SinglePropertyResolver(EXTENSIONMANAGER_PROPERTY_NAME, this);
- resourceManager.addResourceResolver(extensionManagerResolver);
- resourceManager.addResourceResolver(new ObjectTypeResolver(this));
-
- load(resources);
- for (Map.Entry<String, Extension> ext : ExtensionRegistry.getRegisteredExtensions().entrySet()) {
- if (!all.containsKey(ext.getKey())) {
- all.put(ext.getKey(), ext.getValue());
- ordered.add(ext.getValue());
- }
- }
- }
-
- final void load(String[] resources) {
- if (resources == null) {
- return;
- }
- try {
- for (String resource : resources) {
- load(resource);
- }
- } catch (IOException ex) {
- throw new ExtensionException(ex);
- }
- }
- public void add(Extension ex) {
- all.put(ex.getName(), ex);
- ordered.add(ex);
- }
-
- public void initialize() {
- for (Extension e : ordered) {
- if (!e.isDeferred() && e.getLoadedObject() == null) {
- loadAndRegister(e);
- }
- }
- }
-
- public void removeBeansOfNames(List<String> names) {
- for (String s : names) {
- Extension ex = all.remove(s);
- if (ex != null) {
- ordered.remove(ex);
- }
- }
- }
- public void activateAll() {
- for (Extension e : ordered) {
- if (e.getLoadedObject() == null) {
- loadAndRegister(e);
- }
- }
- }
- public <T> void activateAllByType(Class<T> type) {
- for (Extension e : ordered) {
- if (e.getLoadedObject() == null) {
- Class<?> cls = e.getClassObject(loader);
- if (cls != null && type.isAssignableFrom(cls)) {
- synchronized (e) {
- loadAndRegister(e);
- }
- }
- }
- }
- }
-
- public boolean hasBeanOfName(String name) {
- return all.containsKey(name);
- }
-
- final void load(String resource) throws IOException {
- if (loader != getClass().getClassLoader()) {
- load(resource, getClass().getClassLoader());
- }
- load(resource, loader);
- }
- final synchronized void load(String resource, ClassLoader l) throws IOException {
-
- Enumeration<URL> urls = l.getResources(resource);
-
- while (urls.hasMoreElements()) {
- final URL url = urls.nextElement();
- try (InputStream is = AccessController.doPrivileged(new PrivilegedExceptionAction<InputStream>() {
- public InputStream run() throws Exception {
- return url.openStream();
- }
- })) {
- List<Extension> exts = new TextExtensionFragmentParser(loader).getExtensions(is);
- for (Extension e : exts) {
- if (loader != l) {
- e.classloader = l;
- }
- if (!all.containsKey(e.getName())) {
- all.put(e.getName(), e);
- ordered.add(e);
- }
- }
- } catch (PrivilegedActionException pae) {
- throw (IOException)pae.getException();
- }
- }
- }
-
- final void loadAndRegister(Extension e) {
- Class<?> cls;
- if (null != e.getInterfaceName() && !"".equals(e.getInterfaceName())) {
- cls = e.loadInterface(loader);
- } else {
- cls = e.getClassObject(loader);
- }
- if (null != activated && null != cls && null != activated.get(cls)) {
- return;
- }
-
- synchronized (e) {
- Object obj = e.load(loader, bus);
- if (obj == null) {
- return;
- }
-
- if (null != activated) {
- Configurer configurer = (Configurer)(activated.get(Configurer.class));
- if (null != configurer) {
- configurer.configureBean(obj);
- }
- }
-
- // let the object know for which namespaces it has been activated
- ResourceResolver namespacesResolver = null;
- if (null != e.getNamespaces()) {
- namespacesResolver = new SinglePropertyResolver(ACTIVATION_NAMESPACES_PROPERTY_NAME,
- e.getNamespaces());
- resourceManager.addResourceResolver(namespacesResolver);
- }
-
- // Since we need to support spring2.5 by removing @Resource("activationNamespaces")
- // Now we call the setActivationNamespaces method directly here
- if (e.getNamespaces() != null && !e.getNamespaces().isEmpty()) {
- invokeSetterActivationNSMethod(obj, e.getNamespaces());
- }
-
- ResourceInjector injector = new ResourceInjector(resourceManager);
-
- try {
- injector.inject(obj);
- injector.construct(obj);
- } finally {
- if (null != namespacesResolver) {
- resourceManager.removeResourceResolver(namespacesResolver);
- }
- }
-
- if (null != activated) {
- if (cls == null) {
- cls = obj.getClass();
- }
- activated.put(cls, obj);
- }
- }
- }
-
- public <T> T getExtension(String name, Class<T> type) {
- if (name == null) {
- return null;
- }
- Extension e = all.get(name);
- if (e != null) {
- Class<?> cls = e.getClassObject(loader);
- if (cls != null && type.isAssignableFrom(cls)) {
- synchronized (e) {
- if (e.getLoadedObject() == null) {
- loadAndRegister(e);
- }
- return type.cast(e.getLoadedObject());
- }
- }
- }
- return null;
- }
-
- private void invokeSetterActivationNSMethod(Object target, Object value) {
- Class<?> clazz = target.getClass();
- String methodName = ACTIVATION_NAMESPACES_SETTER_METHOD_NAME;
- while (clazz != Object.class) {
- Method[] methods = clazz.getMethods();
- for (int i = 0; i < methods.length; i++) {
- Method method = methods[i];
- Class<?>[] params = method.getParameterTypes();
- if (method.getName().equals(methodName) && params.length == 1) {
- Class<?> paramType = params[0];
- if (paramType.isInstance(value)) {
- try {
- method.invoke(target, new Object[] {value});
- } catch (Exception e) {
- // do nothing here
- }
- return;
- }
- }
- }
- clazz = clazz.getSuperclass();
- }
- }
- public List<String> getBeanNamesOfType(Class<?> type) {
- List<String> ret = new LinkedList<>();
- for (Extension ex : ordered) {
- Class<?> cls = ex.getClassObject(loader);
- if (cls != null && type.isAssignableFrom(cls)) {
- synchronized (ex) {
- ret.add(ex.getName());
- }
- }
- }
- return ret;
- }
- public <T> T getBeanOfType(String name, Class<T> type) {
- if (name == null) {
- return null;
- }
- Extension ex = all.get(name);
- if (ex != null) {
- if (ex.getLoadedObject() == null) {
- loadAndRegister(ex);
- }
- return type.cast(ex.getLoadedObject());
- }
- return null;
- }
- public <T> Collection<? extends T> getBeansOfType(Class<T> type) {
- List<T> ret = new LinkedList<>();
- Extension ext = all.get(type.getName());
- if (ext != null) {
- Class<?> cls = ext.getClassObject(loader);
- if (cls != null && type.isAssignableFrom(cls)) {
- synchronized (ext) {
- if (ext.getLoadedObject() == null) {
- loadAndRegister(ext);
- }
- if (ext.getLoadedObject() != null) {
- ret.add(type.cast(ext.getLoadedObject()));
- }
- }
- }
- }
- for (Extension ex : ordered) {
- if (ex != ext) {
- Class<?> cls = ex.getClassObject(loader);
- if (cls != null && type.isAssignableFrom(cls)) {
- synchronized (ex) {
- if (ex.getLoadedObject() == null) {
- loadAndRegister(ex);
- }
- if (ex.getLoadedObject() != null) {
- ret.add(type.cast(ex.getLoadedObject()));
- }
- }
- }
- }
- }
- return ret;
- }
- public <T> boolean loadBeansOfType(Class<T> type, BeanLoaderListener<T> listener) {
- boolean loaded = false;
- for (Extension ex : ordered) {
- Class<?> cls = ex.getClassObject(loader);
- if (cls != null
- && type.isAssignableFrom(cls)) {
- synchronized (ex) {
- if (listener.loadBean(ex.getName(), cls.asSubclass(type))) {
- if (ex.getLoadedObject() == null) {
- loadAndRegister(ex);
- }
- if (listener.beanLoaded(ex.getName(), type.cast(ex.getLoadedObject()))) {
- return true;
- }
- loaded = true;
- }
- }
- }
- }
- return loaded;
- }
- public boolean hasConfiguredPropertyValue(String beanName, String propertyName, String value) {
- if (beanName == null) {
- return false;
- }
- Extension ex = all.get(beanName);
- return ex != null && ex.getNamespaces() != null
- && ex.getNamespaces().contains(value);
- }
- public void destroyBeans() {
- for (Extension ex : ordered) {
- if (ex.getLoadedObject() != null) {
- ResourceInjector injector = new ResourceInjector(resourceManager);
- injector.destroy(ex.getLoadedObject());
- }
- }
- }
-}
diff --git a/transform/src/patch/java/org/apache/cxf/bus/managers/ServiceContractResolverRegistryImpl.java b/transform/src/patch/java/org/apache/cxf/bus/managers/ServiceContractResolverRegistryImpl.java
deleted file mode 100644
index a0f7af0..0000000
--- a/transform/src/patch/java/org/apache/cxf/bus/managers/ServiceContractResolverRegistryImpl.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.bus.managers;
-
-import java.net.URI;
-import java.util.List;
-import java.util.concurrent.CopyOnWriteArrayList;
-
-import javax.xml.namespace.QName;
-
-import org.apache.cxf.Bus;
-import org.apache.cxf.common.injection.NoJSR250Annotations;
-import org.apache.cxf.endpoint.ServiceContractResolver;
-import org.apache.cxf.endpoint.ServiceContractResolverRegistry;
-
-/**
- * A simple contract resolver registry. It maintains a list of contract resolvers in an
- * <code>ArrayList</code>.
- */
-@NoJSR250Annotations(unlessNull = "bus")
-public class ServiceContractResolverRegistryImpl implements ServiceContractResolverRegistry {
-
- private List<ServiceContractResolver> resolvers
- = new CopyOnWriteArrayList<>();
-
- public ServiceContractResolverRegistryImpl() {
-
- }
- public ServiceContractResolverRegistryImpl(Bus b) {
- setBus(b);
- }
-
-
- /**
- * Sets the bus with which the registry is associated.
- *
- * @param bus
- */
- public final void setBus(Bus bus) {
- if (bus != null) {
- bus.setExtension(this, ServiceContractResolverRegistry.class);
- }
- }
-
- /**
- * Calls each of the registered <code>ServiceContractResolver</code> instances
- * to resolve the location of the service's contract. It returns the location
- * from the first resolver that matches the QName to a location.
- *
- * @param qname QName to be resolved into a contract location
- * @return URI representing the location of the contract
- */
- public URI getContractLocation(QName qname) {
- for (ServiceContractResolver resolver : resolvers) {
- URI contractLocation = resolver.getContractLocation(qname);
- if (null != contractLocation) {
- return contractLocation;
- }
- }
- return null;
- }
-
- /**
- * Tests if a resolver is alreadey registered with this registry.
- *
- * @param resolver the contract resolver for which to searche
- * @return <code>true</code> if the resolver is registered
- */
- public boolean isRegistered(ServiceContractResolver resolver) {
- return resolvers.contains(resolver);
- }
-
- /**
- * Registers a contract resolver with this registry.
- *
- * @param resolver the contract resolver to register
- */
- public synchronized void register(ServiceContractResolver resolver) {
- resolvers.add(resolver);
- }
-
- /**
- * Removes a contract resolver from this registry.
- *
- * @param resolver the contract resolver to remove
- */
- public synchronized void unregister(ServiceContractResolver resolver) {
- resolvers.remove(resolver);
- }
-
-
- protected List<ServiceContractResolver> getResolvers() {
- return resolvers;
- }
-
-}
diff --git a/transform/src/patch/java/org/apache/cxf/bus/osgi/CXFActivator.java b/transform/src/patch/java/org/apache/cxf/bus/osgi/CXFActivator.java
deleted file mode 100644
index 6504276..0000000
--- a/transform/src/patch/java/org/apache/cxf/bus/osgi/CXFActivator.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.bus.osgi;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.cxf.bus.blueprint.BlueprintNameSpaceHandlerFactory;
-import org.apache.cxf.bus.blueprint.NamespaceHandlerRegisterer;
-import org.apache.cxf.bus.extension.Extension;
-import org.apache.cxf.bus.extension.ExtensionRegistry;
-import org.apache.cxf.common.util.CollectionUtils;
-import org.apache.cxf.internal.CXFAPINamespaceHandler;
-import org.osgi.framework.BundleActivator;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Constants;
-import org.osgi.framework.ServiceRegistration;
-import org.osgi.service.cm.ConfigurationAdmin;
-import org.osgi.service.cm.ManagedServiceFactory;
-import org.osgi.util.tracker.ServiceTracker;
-
-/**
- * Is called in OSGi on start and stop of the cxf bundle.
- * Manages
- * - CXFBundleListener
- * - Attaching ManagedWorkqueues to config admin service
- * - OsgiBusListener
- * - Blueprint namespaces
- */
-public class CXFActivator implements BundleActivator {
-
- private List<Extension> extensions;
- private ManagedWorkQueueList workQueues;
- private ServiceTracker<ConfigurationAdmin, ConfigurationAdmin> configAdminTracker;
- private CXFExtensionBundleListener cxfBundleListener;
- private ServiceRegistration<ManagedServiceFactory> workQueueServiceRegistration;
-
-
-
- /** {@inheritDoc}*/
- public void start(BundleContext context) throws Exception {
- workQueues = new ManagedWorkQueueList();
- cxfBundleListener = new CXFExtensionBundleListener(context.getBundle().getBundleId());
- context.addBundleListener(cxfBundleListener);
- cxfBundleListener.registerExistingBundles(context);
-
- configAdminTracker = new ServiceTracker<>(context, ConfigurationAdmin.class, null);
- configAdminTracker.open();
- workQueues.setConfigAdminTracker(configAdminTracker);
- workQueueServiceRegistration = registerManagedServiceFactory(context,
- ManagedServiceFactory.class,
- workQueues,
- ManagedWorkQueueList.FACTORY_PID);
-
- extensions = new ArrayList<>();
- extensions.add(createOsgiBusListenerExtension(context));
- extensions.add(createManagedWorkQueueListExtension(workQueues));
- ExtensionRegistry.addExtensions(extensions);
-
- BlueprintNameSpaceHandlerFactory factory = new BlueprintNameSpaceHandlerFactory() {
-
- @Override
- public Object createNamespaceHandler() {
- return new CXFAPINamespaceHandler();
- }
- };
- NamespaceHandlerRegisterer.register(context, factory,
- "http://cxf.apache.org/blueprint/core",
- "http://cxf.apache.org/configuration/beans",
- "http://cxf.apache.org/configuration/parameterized-types",
- "http://cxf.apache.org/configuration/security",
- "http://schemas.xmlsoap.org/wsdl/",
- "http://www.w3.org/2005/08/addressing",
- "http://schemas.xmlsoap.org/ws/2004/08/addressing");
-
- }
-
- private <T> ServiceRegistration<T> registerManagedServiceFactory(BundleContext context,
- Class<T> serviceClass,
- T service,
- String servicePid) {
- return context.registerService(serviceClass, service,
- CollectionUtils.singletonDictionary(Constants.SERVICE_PID, servicePid));
- }
-
- private Extension createOsgiBusListenerExtension(BundleContext context) {
- Extension busListener = new Extension(OSGIBusListener.class);
- busListener.setArgs(new Object[] {context});
- return busListener;
- }
-
- private static Extension createManagedWorkQueueListExtension(final ManagedWorkQueueList workQueues) {
- return new Extension(ManagedWorkQueueList.class) {
-
- @Override
- public Object getLoadedObject() {
- return workQueues;
- }
-
- @Override
- public Extension cloneNoObject() {
- return this;
- }
- };
- }
-
- /** {@inheritDoc}*/
- public void stop(BundleContext context) throws Exception {
- context.removeBundleListener(cxfBundleListener);
- cxfBundleListener.shutdown();
- workQueues.shutDown();
- workQueueServiceRegistration.unregister();
- configAdminTracker.close();
- ExtensionRegistry.removeExtensions(extensions);
- }
-
-}
diff --git a/transform/src/patch/java/org/apache/cxf/bus/osgi/CXFExtensionBundleListener.java b/transform/src/patch/java/org/apache/cxf/bus/osgi/CXFExtensionBundleListener.java
deleted file mode 100644
index ee9bb15..0000000
--- a/transform/src/patch/java/org/apache/cxf/bus/osgi/CXFExtensionBundleListener.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cxf.bus.osgi;
-
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.CopyOnWriteArrayList;
-import java.util.logging.Logger;
-
-import org.apache.cxf.Bus;
-import org.apache.cxf.bus.extension.Extension;
-import org.apache.cxf.bus.extension.ExtensionException;
-import org.apache.cxf.bus.extension.ExtensionRegistry;
-import org.apache.cxf.bus.extension.TextExtensionFragmentParser;
-import org.apache.cxf.common.i18n.Message;
-import org.apache.cxf.common.logging.LogUtils;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.BundleEvent;
-import org.osgi.framework.ServiceReference;
-import org.osgi.framework.SynchronousBundleListener;
-
-public class CXFExtensionBundleListener implements SynchronousBundleListener {
- private static final Logger LOG = LogUtils.getL7dLogger(CXFActivator.class);
- private long id;
- private ConcurrentMap<Long, List<OSGiExtension>> extensions
- = new ConcurrentHashMap<>(16, 0.75f, 4);
-
- public CXFExtensionBundleListener(long bundleId) {
- this.id = bundleId;
- }
-
- public void registerExistingBundles(BundleContext context) {
- for (Bundle bundle : context.getBundles()) {
- if ((bundle.getState() == Bundle.RESOLVED
- || bundle.getState() == Bundle.STARTING
- || bundle.getState() == Bundle.ACTIVE
- || bundle.getState() == Bundle.STOPPING)
- && bundle.getBundleId() != context.getBundle().getBundleId()) {
- register(bundle);
- }
- }
- }
-
- /** {@inheritDoc}*/
- public void bundleChanged(BundleEvent event) {
- if (event.getType() == BundleEvent.RESOLVED && id != event.getBundle().getBundleId()) {
- register(event.getBundle());
- } else if (event.getType() == BundleEvent.UNRESOLVED || event.getType() == BundleEvent.UNINSTALLED) {
- unregister(event.getBundle().getBundleId());
- }
- }
-
- protected void register(final Bundle bundle) {
- Enumeration<?> e = bundle.findEntries("META-INF/cxf/", "bus-extensions.txt", false);
- while (e != null && e.hasMoreElements()) {
- List<Extension> orig = new TextExtensionFragmentParser(null).getExtensions((URL)e.nextElement());
- addExtensions(bundle, orig);
- }
- }
-
- private boolean addExtensions(final Bundle bundle, List<Extension> orig) {
- if (orig.isEmpty()) {
- return false;
- }
-
- List<String> names = new ArrayList<>(orig.size());
- for (Extension ext : orig) {
- names.add(ext.getName());
- }
- LOG.info("Adding the extensions from bundle " + bundle.getSymbolicName()
- + " (" + bundle.getBundleId() + ") " + names);
- List<OSGiExtension> list = extensions.get(bundle.getBundleId());
- if (list == null) {
- list = new CopyOnWriteArrayList<>();
- List<OSGiExtension> preList = extensions.putIfAbsent(bundle.getBundleId(), list);
- if (preList != null) {
- list = preList;
- }
- }
- for (Extension ext : orig) {
- list.add(new OSGiExtension(ext, bundle));
- }
- ExtensionRegistry.addExtensions(list);
- return !list.isEmpty();
- }
-
- protected void unregister(final long bundleId) {
- List<OSGiExtension> list = extensions.remove(bundleId);
- if (list != null) {
- LOG.info("Removing the extensions for bundle " + bundleId);
- ExtensionRegistry.removeExtensions(list);
- }
- }
-
- public void shutdown() {
- while (!extensions.isEmpty()) {
- unregister(extensions.keySet().iterator().next());
- }
- }
-
- public class OSGiExtension extends Extension {
- final Bundle bundle;
- Object serviceObject;
- public OSGiExtension(Extension e, Bundle b) {
- super(e);
- bundle = b;
- }
-
- public void setServiceObject(Object o) {
- serviceObject = o;
- obj = o;
- }
-
- @Override
- public Object load(ClassLoader cl, Bus b) {
- if (interfaceName == null && bundle.getBundleContext() != null) {
- ServiceReference<?> ref = bundle.getBundleContext().getServiceReference(className);
- if (ref != null && ref.getBundle().getBundleId() == bundle.getBundleId()) {
- Object o = bundle.getBundleContext().getService(ref);
- serviceObject = o;
- obj = o;
- return obj;
- }
- }
- return super.load(cl, b);
- }
-
- @Override
- protected Class<?> tryClass(String name, ClassLoader cl) {
- Class<?> c = null;
- Throwable origExc = null;
- try {
- c = bundle.loadClass(className);
- } catch (Throwable e) {
- origExc = e;
- }
- if (c == null) {
- try {
- return super.tryClass(name, cl);
- } catch (ExtensionException ee) {
- if (origExc != null) {
- throw new ExtensionException(new Message("PROBLEM_LOADING_EXTENSION_CLASS",
- Extension.LOG, name),
- origExc);
- }
- throw ee;
- }
- }
- return c;
- }
-
- @Override
- public Extension cloneNoObject() {
- OSGiExtension ext = new OSGiExtension(this, bundle);
- ext.obj = serviceObject;
- return ext;
- }
-
- }
-}
diff --git a/transform/src/patch/java/org/apache/cxf/bus/osgi/OSGIBusListener.java b/transform/src/patch/java/org/apache/cxf/bus/osgi/OSGIBusListener.java
deleted file mode 100644
index aad270d..0000000
--- a/transform/src/patch/java/org/apache/cxf/bus/osgi/OSGIBusListener.java
+++ /dev/null
@@ -1,224 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cxf.bus.osgi;
-
-import java.util.Dictionary;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.regex.Pattern;
-
-import org.apache.cxf.Bus;
-import org.apache.cxf.bus.extension.ExtensionManagerImpl;
-import org.apache.cxf.buslifecycle.BusCreationListener;
-import org.apache.cxf.buslifecycle.BusLifeCycleListener;
-import org.apache.cxf.buslifecycle.BusLifeCycleManager;
-import org.apache.cxf.common.util.CollectionUtils;
-import org.apache.cxf.common.util.StringUtils;
-import org.apache.cxf.configuration.ConfiguredBeanLocator;
-import org.apache.cxf.endpoint.ClientLifeCycleListener;
-import org.apache.cxf.endpoint.ClientLifeCycleManager;
-import org.apache.cxf.endpoint.ServerLifeCycleListener;
-import org.apache.cxf.endpoint.ServerLifeCycleManager;
-import org.apache.cxf.feature.Feature;
-import org.apache.cxf.workqueue.WorkQueueManager;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Constants;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceReference;
-import org.osgi.framework.ServiceRegistration;
-import org.osgi.framework.Version;
-
-public class OSGIBusListener implements BusLifeCycleListener {
- public static final String CONTEXT_SYMBOLIC_NAME_PROPERTY = "cxf.context.symbolicname";
- public static final String CONTEXT_VERSION_PROPERTY = "cxf.context.version";
- public static final String CONTEXT_NAME_PROPERTY = "cxf.bus.id";
-
- private static final String SERVICE_PROPERTY_PRIVATE = "org.apache.cxf.bus.private.extension";
- private static final String SERVICE_PROPERTY_RESTRICTED = "org.apache.cxf.bus.restricted.extension";
- private static final String BUS_EXTENSION_BUNDLES_EXCLUDES = "bus.extension.bundles.excludes";
- Bus bus;
- ServiceRegistration<?> service;
- BundleContext defaultContext;
- private Pattern extensionBundlesExcludesPattern;
-
- public OSGIBusListener(Bus b) {
- this(b, null);
- }
- public OSGIBusListener(Bus b, Object[] args) {
- bus = b;
- if (args != null && args.length > 0
- && args[0] instanceof BundleContext) {
- defaultContext = (BundleContext)args[0];
- }
- String extExcludes = (String)bus.getProperty(BUS_EXTENSION_BUNDLES_EXCLUDES);
- if (!StringUtils.isEmpty(extExcludes)) {
- try {
- extensionBundlesExcludesPattern = Pattern.compile(extExcludes);
- } catch (IllegalArgumentException e) {
- // ignore
- }
- }
- BusLifeCycleManager manager = bus.getExtension(BusLifeCycleManager.class);
- manager.registerLifeCycleListener(this);
- registerConfiguredBeanLocator();
- registerClientLifeCycleListeners();
- registerServerLifecycleListeners();
- registerBusFeatures();
- sendBusCreatedToBusCreationListeners();
-
- }
- private void registerConfiguredBeanLocator() {
- final ConfiguredBeanLocator cbl = bus.getExtension(ConfiguredBeanLocator.class);
- if (cbl instanceof ExtensionManagerImpl) {
- // wire in the OSGi things
- bus.setExtension(new OSGiBeanLocator(cbl, defaultContext),
- ConfiguredBeanLocator.class);
- }
- }
-
- public void initComplete() {
- ManagedWorkQueueList wqList = bus.getExtension(ManagedWorkQueueList.class);
- if (wqList != null) {
- WorkQueueManager manager = bus.getExtension(WorkQueueManager.class);
- wqList.addAllToWorkQueueManager(manager);
- }
- registerBusAsService();
- }
-
-
- public void preShutdown() {
- }
-
- public void postShutdown() {
- if (service != null) {
- service.unregister();
- service = null;
- }
- }
-
- private static ServiceReference<?>[] getServiceReferences(BundleContext context, Class<?> serviceClass) {
- ServiceReference<?>[] refs = null;
- try {
- refs = context.getServiceReferences(serviceClass.getName(), null);
- } catch (InvalidSyntaxException e) {
- // ignore
- }
- if (refs == null) {
- refs = new ServiceReference<?>[]{};
- }
- return refs;
- }
-
- private void sendBusCreatedToBusCreationListeners() {
- ServiceReference<?>[] refs = getServiceReferences(defaultContext, BusCreationListener.class);
- for (ServiceReference<?> ref : refs) {
- if (!isPrivate(ref) && !isExcluded(ref)) {
- BusCreationListener listener = (BusCreationListener)defaultContext.getService(ref);
- listener.busCreated(bus);
- }
- }
- }
-
- private void registerServerLifecycleListeners() {
- ServiceReference<?>[] refs = getServiceReferences(defaultContext, ServerLifeCycleListener.class);
- ServerLifeCycleManager clcm = bus.getExtension(ServerLifeCycleManager.class);
- for (ServiceReference<?> ref : refs) {
- if (!isPrivate(ref) && !isExcluded(ref)) {
- ServerLifeCycleListener listener = (ServerLifeCycleListener)defaultContext.getService(ref);
- clcm.registerListener(listener);
- }
- }
- }
- private void registerClientLifeCycleListeners() {
- ServiceReference<?>[] refs = getServiceReferences(defaultContext, ClientLifeCycleListener.class);
- ClientLifeCycleManager clcm = bus.getExtension(ClientLifeCycleManager.class);
- for (ServiceReference<?> ref : refs) {
- if (!isPrivate(ref) && !isExcluded(ref)) {
- ClientLifeCycleListener listener = (ClientLifeCycleListener)defaultContext.getService(ref);
- clcm.registerListener(listener);
- }
- }
- }
-
- private void registerBusFeatures() {
- ServiceReference<?>[] refs = getServiceReferences(defaultContext, Feature.class);
- for (ServiceReference<?> ref : refs) {
- if (!isPrivate(ref) && !isExcluded(ref)) {
- Feature feature = (Feature)defaultContext.getService(ref);
- bus.getFeatures().add(feature);
- }
- }
- }
-
- private boolean isPrivate(ServiceReference<?> ref) {
- Object o = ref.getProperty(SERVICE_PROPERTY_PRIVATE);
-
- if (o == null) {
- return false;
- }
-
- Boolean pvt = Boolean.FALSE;
- if (o instanceof String) {
- pvt = Boolean.parseBoolean((String)o);
- } else if (o instanceof Boolean) {
- pvt = (Boolean)o;
- }
- return pvt.booleanValue();
- }
-
- private boolean isExcluded(ServiceReference<?> ref) {
- String o = (String)ref.getProperty(SERVICE_PROPERTY_RESTRICTED);
- if (!StringUtils.isEmpty(o)) {
- // if the service's restricted-regex is set, the service is excluded when the app not matching that regex
- BundleContext app = bus.getExtension(BundleContext.class);
- try {
- if (app != null && !app.getBundle().getSymbolicName().matches(o)) {
- return true;
- }
- } catch (IllegalArgumentException e) {
- // ignore
- }
- }
- // if the excludes-regex is set, the service is excluded when matching that regex.
- return extensionBundlesExcludesPattern != null
- && extensionBundlesExcludesPattern.matcher(ref.getBundle().getSymbolicName()).matches();
- }
-
- private Version getBundleVersion(Bundle bundle) {
- Dictionary<?, ?> headers = bundle.getHeaders();
- String version = (String) headers.get(Constants.BUNDLE_VERSION);
- return (version != null) ? Version.parseVersion(version) : Version.emptyVersion;
- }
-
-
-
- private void registerBusAsService() {
- BundleContext context = bus.getExtension(BundleContext.class);
- if (context != null) {
- Map<String, Object> props = new HashMap<>();
- props.put(CONTEXT_SYMBOLIC_NAME_PROPERTY, context.getBundle().getSymbolicName());
- props.put(CONTEXT_VERSION_PROPERTY, getBundleVersion(context.getBundle()));
- props.put(CONTEXT_NAME_PROPERTY, bus.getId());
-
- service = context.registerService(Bus.class.getName(), bus, CollectionUtils.toDictionary(props));
- }
- }
-
-}
\ No newline at end of file
diff --git a/transform/src/patch/java/org/apache/cxf/bus/resource/ResourceManagerImpl.java b/transform/src/patch/java/org/apache/cxf/bus/resource/ResourceManagerImpl.java
deleted file mode 100644
index 99c6ee9..0000000
--- a/transform/src/patch/java/org/apache/cxf/bus/resource/ResourceManagerImpl.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.bus.resource;
-
-import java.util.List;
-
-import javax.annotation.Resource;
-
-import org.apache.cxf.Bus;
-import org.apache.cxf.common.injection.NoJSR250Annotations;
-import org.apache.cxf.configuration.ConfiguredBeanLocator;
-import org.apache.cxf.extension.BusExtension;
-import org.apache.cxf.resource.DefaultResourceManager;
-import org.apache.cxf.resource.ObjectTypeResolver;
-import org.apache.cxf.resource.ResourceManager;
-import org.apache.cxf.resource.ResourceResolver;
-
-@NoJSR250Annotations(unlessNull = "bus")
-public class ResourceManagerImpl extends DefaultResourceManager implements BusExtension {
-
- private Bus bus;
-
- public ResourceManagerImpl() {
- }
-
- public ResourceManagerImpl(Bus b) {
- super();
- setBus(b);
- }
-
- @Override
- protected void onFirstResolve() {
- super.onFirstResolve();
- if (bus != null) {
- ConfiguredBeanLocator locator = bus.getExtension(ConfiguredBeanLocator.class);
- if (locator != null) {
- this.addResourceResolvers(locator.getBeansOfType(ResourceResolver.class));
- }
- }
- }
-
- /**
- * Set the list of resolvers for this resource manager.
- * @param resolvers
- */
- public final void setResolvers(List<? extends ResourceResolver> resolvers) {
- registeredResolvers.clear();
- registeredResolvers.addAll(resolvers);
- }
-
- @Resource
- public final void setBus(Bus b) {
- if (bus != b) {
- bus = b;
- firstCalled = false;
- super.addResourceResolver(new ObjectTypeResolver(bus));
- if (null != bus) {
- bus.setExtension(this, ResourceManager.class);
- }
- }
- }
-
- public Class<?> getRegistrationType() {
- return ResourceManager.class;
- }
-
-
-}
diff --git a/transform/src/patch/java/org/apache/cxf/bus/spring/BusDefinitionParser.java b/transform/src/patch/java/org/apache/cxf/bus/spring/BusDefinitionParser.java
deleted file mode 100644
index 9d508b6..0000000
--- a/transform/src/patch/java/org/apache/cxf/bus/spring/BusDefinitionParser.java
+++ /dev/null
@@ -1,310 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.bus.spring;
-
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.w3c.dom.Element;
-
-import org.apache.cxf.Bus;
-import org.apache.cxf.common.injection.NoJSR250Annotations;
-import org.apache.cxf.common.util.StringUtils;
-import org.apache.cxf.configuration.spring.AbstractBeanDefinitionParser;
-import org.apache.cxf.configuration.spring.BusWiringType;
-import org.apache.cxf.feature.Feature;
-import org.apache.cxf.helpers.CastUtils;
-import org.apache.cxf.interceptor.AbstractBasicInterceptorProvider;
-import org.apache.cxf.interceptor.Interceptor;
-import org.apache.cxf.message.Message;
-import org.springframework.beans.PropertyValue;
-import org.springframework.beans.factory.config.BeanDefinition;
-import org.springframework.beans.factory.support.AbstractBeanDefinition;
-import org.springframework.beans.factory.support.BeanDefinitionBuilder;
-import org.springframework.beans.factory.xml.ParserContext;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.ApplicationContextAware;
-
-public class BusDefinitionParser extends AbstractBeanDefinitionParser {
- private static AtomicInteger counter = new AtomicInteger(0);
-
- public BusDefinitionParser() {
- super();
- setBeanClass(BusConfig.class);
- }
-
- @Override
- protected void doParse(Element element, ParserContext ctx, BeanDefinitionBuilder bean) {
- String bus = element.getAttribute("bus");
- if (StringUtils.isEmpty(bus)) {
- bus = element.getAttribute("name");
- if (StringUtils.isEmpty(bus)) {
- element.setAttribute("bus", bus);
- }
- }
- element.removeAttribute("name");
- if (StringUtils.isEmpty(bus)) {
- bus = "cxf";
- }
- String id = element.getAttribute("id");
- if (!StringUtils.isEmpty(id)) {
- bean.addPropertyValue("id", id);
- }
-
- super.doParse(element, ctx, bean);
-
- if (ctx.getRegistry().containsBeanDefinition(bus)) {
- BeanDefinition def = ctx.getRegistry().getBeanDefinition(bus);
- copyProps(bean, def);
- bean.addConstructorArgValue(bus);
- } else if (!"cxf".equals(bus)) {
- bean.getRawBeanDefinition().setBeanClass(SpringBus.class);
- bean.setDestroyMethodName("shutdown");
- try {
- element.setUserData("ID", bus, null);
- bean.getRawBeanDefinition().getPropertyValues().removePropertyValue("bus");
- } catch (Throwable t) {
- //likely not DOM level 3, ignore
- }
- } else {
- addBusWiringAttribute(bean, BusWiringType.PROPERTY, bus, ctx);
- bean.getRawBeanDefinition().setAttribute(WIRE_BUS_CREATE,
- resolveId(element, null, ctx));
- bean.addConstructorArgValue(bus);
- }
- }
-
- @Override
- protected boolean processBusAttribute(Element element, ParserContext ctx,
- BeanDefinitionBuilder bean,
- String val) {
- return false;
- }
-
- private void copyProps(BeanDefinitionBuilder src, BeanDefinition def) {
- for (PropertyValue v : src.getBeanDefinition().getPropertyValues().getPropertyValues()) {
- if (!"bus".equals(v.getName())) {
- def.getPropertyValues().addPropertyValue(v.getName(), v.getValue());
- }
- src.getBeanDefinition().getPropertyValues().removePropertyValue(v);
- }
-
- }
-
- @Override
- protected void mapElement(ParserContext ctx,
- BeanDefinitionBuilder bean,
- Element e,
- String name) {
- if ("inInterceptors".equals(name) || "inFaultInterceptors".equals(name)
- || "outInterceptors".equals(name) || "outFaultInterceptors".equals(name)
- || "features".equals(name)) {
- List<?> list = ctx.getDelegate().parseListElement(e, bean.getBeanDefinition());
- bean.addPropertyValue(name, list);
- } else if ("properties".equals(name)) {
- Map<?, ?> map = ctx.getDelegate().parseMapElement(e, bean.getBeanDefinition());
- bean.addPropertyValue("properties", map);
- }
- }
- @Override
- protected String resolveId(Element element, AbstractBeanDefinition definition,
- ParserContext ctx) {
- String bus = null;
- try {
- bus = (String)element.getUserData("ID");
- } catch (Throwable t) {
- //ignore
- }
- if (bus == null) {
- bus = element.getAttribute("bus");
- if (StringUtils.isEmpty(bus)) {
- bus = element.getAttribute("name");
- }
- if (StringUtils.isEmpty(bus)) {
- bus = Bus.DEFAULT_BUS_ID + ".config" + counter.getAndIncrement();
- } else {
- bus = bus + ".config";
- }
- try {
- element.setUserData("ID", bus, null);
- } catch (Throwable t) {
- //maybe no DOM level 3, ignore, but, may have issues with the counter
- }
- }
- return bus;
- }
-
- @NoJSR250Annotations
- public static class BusConfig extends AbstractBasicInterceptorProvider
- implements ApplicationContextAware {
-
- Bus bus;
- String busName;
- String id;
- Collection<Feature> features;
- Map<String, Object> properties;
-
- public BusConfig(String busName) {
- this.busName = busName;
- }
-
- public void setBus(Bus bb) {
- if (bus == bb) {
- return;
- }
- if (properties != null) {
- bb.setProperties(properties);
- properties = null;
- }
- if (!getInInterceptors().isEmpty()) {
- bb.getInInterceptors().addAll(getInInterceptors());
- }
- if (!getOutInterceptors().isEmpty()) {
- bb.getOutInterceptors().addAll(getOutInterceptors());
- }
- if (!getInFaultInterceptors().isEmpty()) {
- bb.getInFaultInterceptors().addAll(getInFaultInterceptors());
- }
- if (!getOutFaultInterceptors().isEmpty()) {
- bb.getOutFaultInterceptors().addAll(getOutFaultInterceptors());
- }
- if (!StringUtils.isEmpty(id)) {
- bb.setId(id);
- }
- if (features != null) {
- bb.setFeatures(features);
- features = null;
- }
- bus = bb;
- }
-
- public void setApplicationContext(ApplicationContext applicationContext) {
- if (bus != null) {
- return;
- }
- }
-
- @Override
- public List<Interceptor<? extends Message>> getOutFaultInterceptors() {
- if (bus != null) {
- return bus.getOutFaultInterceptors();
- }
- return super.getOutFaultInterceptors();
- }
-
- @Override
- public List<Interceptor<? extends Message>> getInFaultInterceptors() {
- if (bus != null) {
- return bus.getInFaultInterceptors();
- }
- return super.getInFaultInterceptors();
- }
-
- @Override
- public List<Interceptor<? extends Message>> getInInterceptors() {
- if (bus != null) {
- return bus.getInInterceptors();
- }
- return super.getInInterceptors();
- }
-
- @Override
- public List<Interceptor<? extends Message>> getOutInterceptors() {
- if (bus != null) {
- return bus.getOutInterceptors();
- }
- return super.getOutInterceptors();
- }
-
- @Override
- public void setInInterceptors(List<Interceptor<? extends Message>> interceptors) {
- if (bus != null) {
- bus.getInInterceptors().addAll(interceptors);
- } else {
- super.setInInterceptors(interceptors);
- }
- }
-
- @Override
- public void setInFaultInterceptors(List<Interceptor<? extends Message>> interceptors) {
- if (bus != null) {
- bus.getInFaultInterceptors().addAll(interceptors);
- } else {
- super.setInFaultInterceptors(interceptors);
- }
- }
-
- @Override
- public void setOutInterceptors(List<Interceptor<? extends Message>> interceptors) {
- if (bus != null) {
- bus.getOutInterceptors().addAll(interceptors);
- } else {
- super.setOutInterceptors(interceptors);
- }
- }
-
- @Override
- public void setOutFaultInterceptors(List<Interceptor<? extends Message>> interceptors) {
- if (bus != null) {
- bus.getOutFaultInterceptors().addAll(interceptors);
- } else {
- super.setOutFaultInterceptors(interceptors);
- }
- }
-
- public Collection<Feature> getFeatures() {
- if (bus != null) {
- return bus.getFeatures();
- }
- return features;
- }
-
- public void setFeatures(Collection<? extends Feature> features) {
- if (bus != null) {
- bus.setFeatures(features);
- } else {
- this.features = CastUtils.cast(features);
- }
-
- }
-
- public Map<String, Object> getProperties() {
- if (bus != null) {
- return bus.getProperties();
- }
- return properties;
- }
- public void setProperties(Map<String, Object> s) {
- if (bus != null) {
- bus.setProperties(s);
- } else {
- this.properties = s;
- }
- }
-
- public void setId(String s) {
- id = s;
- }
-
-
- }
-}
diff --git a/transform/src/patch/java/org/apache/cxf/bus/spring/BusEntityResolver.java b/transform/src/patch/java/org/apache/cxf/bus/spring/BusEntityResolver.java
deleted file mode 100644
index 1e95e28..0000000
--- a/transform/src/patch/java/org/apache/cxf/bus/spring/BusEntityResolver.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.bus.spring;
-
-import java.io.IOException;
-import java.util.Map;
-import java.util.Properties;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import org.xml.sax.EntityResolver;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-
-import org.apache.cxf.common.logging.LogUtils;
-import org.springframework.beans.factory.xml.DelegatingEntityResolver;
-import org.springframework.core.io.ClassPathResource;
-import org.springframework.core.io.Resource;
-import org.springframework.core.io.support.PropertiesLoaderUtils;
-import org.springframework.util.CollectionUtils;
-
-/**
- *
- */
-public class BusEntityResolver extends DelegatingEntityResolver {
-
- private static final Logger LOG = LogUtils.getL7dLogger(BusEntityResolver.class);
-
- private EntityResolver dtdResolver;
- private EntityResolver schemaResolver;
- private Map<String, String> schemaMappings;
- private ClassLoader classLoader;
-
- public BusEntityResolver(ClassLoader loader, EntityResolver dr, EntityResolver sr) {
- super(dr, sr);
- classLoader = loader;
- dtdResolver = dr;
- schemaResolver = sr;
-
- try {
- Properties mappings = PropertiesLoaderUtils.loadAllProperties("META-INF/spring.schemas",
- classLoader);
- schemaMappings = new ConcurrentHashMap<>(mappings.size());
- CollectionUtils.mergePropertiesIntoMap(mappings, schemaMappings);
- } catch (IOException e) {
- //ignore
- }
- }
-
- @Override
- public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
- InputSource source = super.resolveEntity(publicId, systemId);
- if (null == source && null != systemId) {
- // try the schema and dtd resolver in turn, ignoring the suffix in publicId
- LOG.log(Level.FINE, "Attempting to resolve systemId {0}", systemId);
- source = schemaResolver.resolveEntity(publicId, systemId);
- if (null == source) {
- source = dtdResolver.resolveEntity(publicId, systemId);
- }
- }
-
- if (null == source) {
- return null;
- }
-
- String resourceLocation = schemaMappings.get(systemId);
- if (resourceLocation != null && publicId == null) {
- Resource resource = new ClassPathResource(resourceLocation, classLoader);
- if (resource.exists()) {
- source.setPublicId(systemId);
- source.setSystemId(resource.getURL().toString());
- }
- }
- return source;
- }
-}
diff --git a/transform/src/patch/java/org/apache/cxf/bus/spring/BusExtensionPostProcessor.java b/transform/src/patch/java/org/apache/cxf/bus/spring/BusExtensionPostProcessor.java
deleted file mode 100644
index 9389be6..0000000
--- a/transform/src/patch/java/org/apache/cxf/bus/spring/BusExtensionPostProcessor.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.bus.spring;
-
-import org.apache.cxf.Bus;
-import org.apache.cxf.common.injection.NoJSR250Annotations;
-import org.apache.cxf.extension.BusExtension;
-import org.springframework.beans.factory.config.BeanPostProcessor;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.ApplicationContextAware;
-import org.springframework.core.Ordered;
-
-@NoJSR250Annotations
-public class BusExtensionPostProcessor implements BeanPostProcessor, ApplicationContextAware, Ordered {
-
- private Bus bus;
- private ApplicationContext context;
-
- public void setApplicationContext(ApplicationContext ctx) {
- context = ctx;
- }
-
- public int getOrder() {
- return 1001;
- }
-
-
- @Override
- public Object postProcessAfterInitialization(Object bean, String beanId) {
- return bean;
- }
-
- @Override
- public Object postProcessBeforeInitialization(Object bean, String beanId) {
- if (bean instanceof BusExtension && null != getBus()) {
- Class<? extends Object> cls = ((BusExtension)bean).getRegistrationType();
- registerExt(bean, cls);
- } else if (bean instanceof Bus && Bus.DEFAULT_BUS_ID.equals(beanId)) {
- bus = (Bus)bean;
- }
- return bean;
- }
- private <T> void registerExt(Object bean, Class<T> cls) {
- getBus().setExtension(cls.cast(bean), cls);
- }
-
- private Bus getBus() {
- if (bus == null) {
- bus = (Bus)context.getBean(Bus.DEFAULT_BUS_ID);
- }
- return bus;
- }
-
-}
diff --git a/transform/src/patch/java/org/apache/cxf/bus/spring/Jsr250BeanPostProcessor.java b/transform/src/patch/java/org/apache/cxf/bus/spring/Jsr250BeanPostProcessor.java
deleted file mode 100644
index 1fb0746..0000000
--- a/transform/src/patch/java/org/apache/cxf/bus/spring/Jsr250BeanPostProcessor.java
+++ /dev/null
@@ -1,164 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.bus.spring;
-
-
-
-import org.apache.cxf.Bus;
-import org.apache.cxf.common.injection.ResourceInjector;
-import org.apache.cxf.resource.ResourceManager;
-import org.springframework.beans.factory.NoSuchBeanDefinitionException;
-import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.ApplicationContextAware;
-import org.springframework.core.Ordered;
-
-public class Jsr250BeanPostProcessor
- implements DestructionAwareBeanPostProcessor, Ordered, ApplicationContextAware {
-
- private ResourceManager resourceManager;
- private ApplicationContext context;
-
- private boolean isProcessing = true;
- //private int count;
- //private int count2;
-
- Jsr250BeanPostProcessor() {
- }
-
- public void setApplicationContext(ApplicationContext applicationContext) {
- context = applicationContext;
- try {
- Class<?> cls = Class
- .forName("org.springframework.context.annotation.CommonAnnotationBeanPostProcessor");
- isProcessing = context.getBeanNamesForType(cls, true, false).length == 0;
- } catch (ClassNotFoundException e) {
- isProcessing = true;
- }
- }
-
- public int getOrder() {
- return 1010;
- }
-
- private boolean injectable(Object bean, String beanId) {
- return !"cxf".equals(beanId) && ResourceInjector.processable(bean.getClass(), bean);
- }
- private ResourceManager getResourceManager(Object bean) {
- if (resourceManager == null) {
- boolean temp = isProcessing;
- isProcessing = false;
- if (bean instanceof ResourceManager) {
- resourceManager = (ResourceManager)bean;
- resourceManager.addResourceResolver(new BusApplicationContextResourceResolver(context));
- } else if (bean instanceof Bus) {
- Bus b = (Bus)bean;
- ResourceManager m = b.getExtension(ResourceManager.class);
- if (m != null) {
- resourceManager = m;
- if (!(b instanceof SpringBus)) {
- resourceManager
- .addResourceResolver(new BusApplicationContextResourceResolver(context));
- }
- }
- } else {
- ResourceManager m = null;
- Bus b = null;
- try {
- m = (ResourceManager)context.getBean(ResourceManager.class.getName());
- } catch (NoSuchBeanDefinitionException t) {
- //ignore - no resource manager
- }
- if (m == null) {
- b = (Bus)context.getBean("cxf");
- m = b.getExtension(ResourceManager.class);
- }
- if (m != null) {
- resourceManager = m;
- if (!(b instanceof SpringBus)) {
- resourceManager
- .addResourceResolver(new BusApplicationContextResourceResolver(context));
- }
- }
- }
- isProcessing = temp;
- }
- return resourceManager;
- }
-
- @Override
- public Object postProcessAfterInitialization(Object bean, String beanId) {
- if (!isProcessing) {
- if (resourceManager == null && bean instanceof ResourceManager) {
- resourceManager = (ResourceManager)bean;
- resourceManager.addResourceResolver(new BusApplicationContextResourceResolver(context));
- }
- return bean;
- }
- if (bean != null
- && injectable(bean, beanId)) {
- new ResourceInjector(getResourceManager(bean)).construct(bean);
- }
- return bean;
- }
-
- @Override
- public Object postProcessBeforeInitialization(Object bean, String beanId) {
- if (!isProcessing) {
- return bean;
- }
- if (bean instanceof Bus) {
- getResourceManager(bean);
- }
- /*
- if (bean.getClass().getName().contains("Corb")) {
- Thread.dumpStack();
- }
- */
-
- if (bean != null
- && injectable(bean, beanId)) {
- new ResourceInjector(getResourceManager(bean)).inject(bean);
- /*
- System.out.println("p :" + (++count) + ": " + bean.getClass().getName() + " " + beanId);
- } else if (bean != null) {
- System.out.println("np: " + (++count2)
- + ": " + bean.getClass().getName() + " " + beanId);
- */
- }
- return bean;
- }
-
- public void postProcessBeforeDestruction(Object bean, String beanId) {
- if (!isProcessing) {
- return;
- }
- if (bean != null
- && injectable(bean, beanId)) {
- new ResourceInjector(getResourceManager(bean)).destroy(bean);
- }
- }
-
- @Override
- public boolean requiresDestruction(Object bean) {
- return isProcessing;
- }
-
-}
diff --git a/transform/src/patch/java/org/apache/cxf/bus/spring/NamespaceHandler.java b/transform/src/patch/java/org/apache/cxf/bus/spring/NamespaceHandler.java
deleted file mode 100644
index 9211ea8..0000000
--- a/transform/src/patch/java/org/apache/cxf/bus/spring/NamespaceHandler.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cxf.bus.spring;
-
-import org.w3c.dom.Element;
-
-import org.apache.cxf.configuration.spring.SimpleBeanDefinitionParser;
-import org.apache.cxf.feature.FastInfosetFeature;
-import org.apache.cxf.workqueue.AutomaticWorkQueueImpl;
-import org.springframework.beans.factory.support.BeanDefinitionBuilder;
-import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
-import org.springframework.beans.factory.xml.ParserContext;
-
-public class NamespaceHandler extends NamespaceHandlerSupport {
- @SuppressWarnings("deprecation")
- public void init() {
- registerBeanDefinitionParser("bus",
- new BusDefinitionParser());
- registerBeanDefinitionParser("logging",
- new SimpleBeanDefinitionParser(org.apache.cxf.feature.LoggingFeature.class));
- registerBeanDefinitionParser("fastinfoset",
- new SimpleBeanDefinitionParser(FastInfosetFeature.class));
-
- registerBeanDefinitionParser("workqueue",
- new SimpleBeanDefinitionParser(AutomaticWorkQueueImpl.class) {
-
- @Override
- protected void processNameAttribute(Element element,
- ParserContext ctx,
- BeanDefinitionBuilder bean,
- String val) {
- bean.addPropertyValue("name", val);
- element.removeAttribute("name");
- if (!element.hasAttribute("id")) {
- element.setAttribute("id", "cxf.workqueue." + val);
- }
-
- }
- });
- }
-}
diff --git a/transform/src/patch/java/org/apache/cxf/bus/spring/SpringBus.java b/transform/src/patch/java/org/apache/cxf/bus/spring/SpringBus.java
deleted file mode 100644
index 6616c8e..0000000
--- a/transform/src/patch/java/org/apache/cxf/bus/spring/SpringBus.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.bus.spring;
-
-import org.apache.cxf.bus.extension.ExtensionManagerBus;
-import org.apache.cxf.configuration.ConfiguredBeanLocator;
-import org.apache.cxf.configuration.Configurer;
-import org.apache.cxf.configuration.spring.ConfigurerImpl;
-import org.apache.cxf.resource.ResourceManager;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.ApplicationContextAware;
-import org.springframework.context.ApplicationEvent;
-import org.springframework.context.ApplicationListener;
-import org.springframework.context.event.ContextClosedEvent;
-import org.springframework.context.event.ContextRefreshedEvent;
-import org.springframework.context.support.AbstractApplicationContext;
-
-/**
- *
- */
-public class SpringBus extends ExtensionManagerBus
- implements ApplicationContextAware {
-
- AbstractApplicationContext ctx;
- boolean closeContext;
-
- public SpringBus() {
- }
-
- public void setBusConfig(BusDefinitionParser.BusConfig bc) {
- bc.setBus(this);
- }
-
- /** {@inheritDoc}*/
- public void setApplicationContext(ApplicationContext applicationContext) {
- ctx = (AbstractApplicationContext)applicationContext;
- @SuppressWarnings("rawtypes")
- ApplicationListener listener = new ApplicationListener() {
- public void onApplicationEvent(ApplicationEvent event) {
- SpringBus.this.onApplicationEvent(event);
- }
- };
- ctx.addApplicationListener(listener);
- ApplicationContext ac = applicationContext.getParent();
- while (ac != null) {
- if (ac instanceof AbstractApplicationContext) {
- ((AbstractApplicationContext)ac).addApplicationListener(listener);
- }
- ac = ac.getParent();
- }
-
- // set the classLoader extension with the application context classLoader
- setExtension(applicationContext.getClassLoader(), ClassLoader.class);
-
- setExtension(new ConfigurerImpl(applicationContext), Configurer.class);
-
- ResourceManager m = getExtension(ResourceManager.class);
- m.addResourceResolver(new BusApplicationContextResourceResolver(applicationContext));
-
- setExtension(applicationContext, ApplicationContext.class);
- ConfiguredBeanLocator loc = getExtension(ConfiguredBeanLocator.class);
- if (!(loc instanceof SpringBeanLocator)) {
- setExtension(new SpringBeanLocator(applicationContext, this), ConfiguredBeanLocator.class);
- }
- if (getState() != BusState.RUNNING) {
- initialize();
- }
- }
-
- public void onApplicationEvent(ApplicationEvent event) {
- if (ctx == null) {
- return;
- }
- boolean doIt = false;
- ApplicationContext ac = ctx;
- while (ac != null) {
- if (event.getSource() == ac) {
- doIt = true;
- break;
- }
- ac = ac.getParent();
- }
- if (doIt) {
- if (event instanceof ContextRefreshedEvent) {
- if (getState() != BusState.RUNNING) {
- initialize();
- }
- } else if (event instanceof ContextClosedEvent && getState() == BusState.RUNNING) {
- // The bus could be create by using SpringBusFactory.createBus("/cxf.xml");
- // Just to make sure the shutdown is called rightly
- shutdown();
- }
- }
- }
-
- @Override
- public void destroyBeans() {
- if (closeContext) {
- ctx.close();
- }
- super.destroyBeans();
- }
-
- @Override
- public String getId() {
- if (id == null) {
- try {
- Class<?> clsbc = Class.forName("org.osgi.framework.BundleContext");
- Class<?> clsb = Class.forName("org.osgi.framework.Bundle");
- Object o = getExtension(clsbc);
- Object o2 = clsbc.getMethod("getBundle").invoke(o);
- String s = (String)clsb.getMethod("getSymbolicName").invoke(o2);
- id = s + '-' + DEFAULT_BUS_ID + Integer.toString(this.hashCode());
- } catch (Throwable t) {
- id = super.getId();
- }
- }
- return id;
- }
-
- public void setCloseContext(boolean b) {
- closeContext = b;
- }
-
-}
diff --git a/transform/src/patch/java/org/apache/cxf/catalog/CatalogXmlSchemaURIResolver.java b/transform/src/patch/java/org/apache/cxf/catalog/CatalogXmlSchemaURIResolver.java
deleted file mode 100644
index 15a3ce2..0000000
--- a/transform/src/patch/java/org/apache/cxf/catalog/CatalogXmlSchemaURIResolver.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cxf.catalog;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.xml.sax.InputSource;
-
-import org.apache.cxf.Bus;
-import org.apache.cxf.helpers.IOUtils;
-import org.apache.cxf.resource.ExtendedURIResolver;
-import org.apache.cxf.transport.TransportURIResolver;
-import org.apache.ws.commons.schema.XmlSchemaException;
-import org.apache.ws.commons.schema.resolver.URIResolver;
-
-/**
- * Resolves URIs using Apache Commons Resolver API.
- */
-public class CatalogXmlSchemaURIResolver implements URIResolver {
-
- private ExtendedURIResolver resolver;
- private Bus bus;
- private Map<String, String> resolved = new HashMap<>();
-
- public CatalogXmlSchemaURIResolver(Bus bus) {
- this.resolver = new TransportURIResolver(bus);
- this.bus = bus;
- }
-
- public Map<String, String> getResolvedMap() {
- return resolved;
- }
-
- public InputSource resolveEntity(String targetNamespace, String schemaLocation, String baseUri) {
- final String resolvedSchemaLocation;
- OASISCatalogManager catalogResolver = OASISCatalogManager.getCatalogManager(bus);
- try {
- resolvedSchemaLocation = new OASISCatalogManagerHelper().resolve(catalogResolver,
- schemaLocation, baseUri);
- } catch (Exception e) {
- throw new RuntimeException("Catalog resolution failed", e);
- }
-
- final InputSource in;
- if (resolvedSchemaLocation == null) {
- in = this.resolver.resolve(schemaLocation, baseUri);
- } else {
- resolved.put(schemaLocation, resolvedSchemaLocation);
- in = this.resolver.resolve(resolvedSchemaLocation, baseUri);
- }
-
- // If we return null, a NPE is raised in SchemaBuilder.
- // If we return new InputSource(), a XmlSchemaException is raised
- // but without any nice error message. So let's just throw a nice error here.
- if (in == null) {
- throw new XmlSchemaException("Unable to locate imported document "
- + "at '" + schemaLocation + "'"
- + (baseUri == null
- ? "."
- : ", relative to '" + baseUri + "'."));
- } else if (in.getByteStream() != null
- && !(in.getByteStream() instanceof ByteArrayInputStream)) {
- //workaround bug in XmlSchema - XmlSchema is not closing the InputStreams
- //that are returned for imports. Thus, with a lot of services starting up
- //or a lot of schemas imported or similar, it's easy to run out of
- //file handles. We'll just load the file into a byte[] and return that.
- try {
- InputStream ins = IOUtils.loadIntoBAIS(in.getByteStream());
- in.setByteStream(ins);
- } catch (IOException e) {
- throw new XmlSchemaException("Unable to load imported document "
- + "at '" + schemaLocation + "'"
- + (baseUri == null
- ? "."
- : ", relative to '" + baseUri + "'."),
- e);
- }
- }
-
- return in;
- }
-}
diff --git a/transform/src/patch/java/org/apache/cxf/common/i18n/Exception.java b/transform/src/patch/java/org/apache/cxf/common/i18n/Exception.java
deleted file mode 100644
index fcb38ad..0000000
--- a/transform/src/patch/java/org/apache/cxf/common/i18n/Exception.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.common.i18n;
-
-
-
-public class Exception extends java.lang.Exception {
-
- private static final long serialVersionUID = 1L;
-
- private final Message message;
-
- public Exception(Message msg) {
- message = msg;
- }
-
- public Exception(Message msg, Throwable t) {
- super(t);
- message = msg;
- }
-
- public Exception(Throwable cause) {
- super(cause);
- message = null;
- }
-
- public String getCode() {
- if (null != message) {
- return message.getCode();
- }
- return null;
- }
-
- @Override
- public String getMessage() {
- if (null != message) {
- return message.toString();
- }
- return null;
- }
-}
diff --git a/transform/src/patch/java/org/apache/cxf/common/i18n/Message.java b/transform/src/patch/java/org/apache/cxf/common/i18n/Message.java
deleted file mode 100644
index d1a65c8..0000000
--- a/transform/src/patch/java/org/apache/cxf/common/i18n/Message.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.common.i18n;
-
-import java.io.IOException;
-import java.io.Serializable;
-import java.text.MessageFormat;
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-import java.util.logging.Logger;
-
-public class Message implements Serializable {
- private static final long serialVersionUID = 42L;
-
- transient String code;
- transient Object[] parameters;
- transient ResourceBundle bundle;
-
- /**
- * Constructor.
- *
- * @param key the message catalog (resource bundle) key
- * @param logger a logger with an associated resource bundle
- * @param params the message substitution parameters
- */
- public Message(String key, Logger logger, Object...params) {
- this(key, logger.getResourceBundle(), params);
- }
-
- /**
- * Constructor.
- *
- * @param key the message catalog (resource bundle) key
- * @param catalog the resource bundle
- * @param params the message substitution parameters
- */
- public Message(String key, ResourceBundle catalog, Object...params) {
- code = key;
- bundle = catalog;
- parameters = params;
- }
-
- public String toString() {
- final String fmt;
- try {
- if (null == bundle) {
- return code;
- }
- fmt = bundle.getString(code);
- } catch (MissingResourceException ex) {
- return code;
- }
- return MessageFormat.format(fmt, parameters);
- }
-
- public String getCode() {
- return code;
- }
-
- public Object[] getParameters() {
- return parameters;
- }
-
- private void writeObject(java.io.ObjectOutputStream out)
- throws IOException {
- out.writeUTF(toString());
- }
- private void readObject(java.io.ObjectInputStream in)
- throws IOException, ClassNotFoundException {
- code = in.readUTF();
- bundle = null;
- parameters = null;
- }
-}
diff --git a/transform/src/patch/java/org/apache/cxf/common/i18n/UncheckedException.java b/transform/src/patch/java/org/apache/cxf/common/i18n/UncheckedException.java
deleted file mode 100644
index ea15fd7..0000000
--- a/transform/src/patch/java/org/apache/cxf/common/i18n/UncheckedException.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.common.i18n;
-
-import java.util.ResourceBundle;
-import java.util.logging.Logger;
-
-
-
-public class UncheckedException extends java.lang.RuntimeException {
-
- private static final long serialVersionUID = 1L;
-
- protected final Message message;
-
- public UncheckedException(Message msg) {
- message = msg;
- }
-
- public UncheckedException(Message msg, Throwable t) {
- super(t);
- message = msg;
- }
-
- public UncheckedException(Throwable cause) {
- super(cause);
- message = null;
- }
-
- public UncheckedException(Logger log, String msg, Object ... params) {
- message = new org.apache.cxf.common.i18n.Message(msg,
- log,
- params);
- }
- public UncheckedException(ResourceBundle bundle, String msg, Object ... params) {
- message = new org.apache.cxf.common.i18n.Message(msg,
- bundle,
- params);
- }
- public UncheckedException(Logger log, String msg, Throwable t, Object ... params) {
- super(t);
- message = new org.apache.cxf.common.i18n.Message(msg,
- log,
- params);
- }
- public UncheckedException(ResourceBundle bundle, String msg, Throwable t, Object ... params) {
- super(t);
- message = new org.apache.cxf.common.i18n.Message(msg,
- bundle,
- params);
- }
-
- public String getCode() {
- if (null != message) {
- return message.getCode();
- }
- return null;
- }
-
- @Override
- public String getMessage() {
- if (null != message) {
- return message.toString();
- }
- return null;
- }
-}
diff --git a/transform/src/patch/java/org/apache/cxf/common/injection/ResourceInjector.java b/transform/src/patch/java/org/apache/cxf/common/injection/ResourceInjector.java
deleted file mode 100644
index 9c420ce..0000000
--- a/transform/src/patch/java/org/apache/cxf/common/injection/ResourceInjector.java
+++ /dev/null
@@ -1,446 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.common.injection;
-
-
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Field;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import javax.annotation.PostConstruct;
-import javax.annotation.PreDestroy;
-import javax.annotation.Resource;
-import javax.annotation.Resources;
-
-
-import org.apache.cxf.common.annotation.AbstractAnnotationVisitor;
-import org.apache.cxf.common.annotation.AnnotationProcessor;
-import org.apache.cxf.common.logging.LogUtils;
-import org.apache.cxf.common.util.ClassHelper;
-import org.apache.cxf.common.util.ReflectionUtil;
-import org.apache.cxf.common.util.StringUtils;
-import org.apache.cxf.resource.ResourceManager;
-import org.apache.cxf.resource.ResourceResolver;
-
-
-/**
- * injects references specified using @Resource annotation
- *
- */
-public class ResourceInjector extends AbstractAnnotationVisitor {
-
- private static final Logger LOG = LogUtils.getL7dLogger(ResourceInjector.class);
- private static final List<Class<? extends Annotation>> ANNOTATIONS = new ArrayList<>();
-
- static {
- ANNOTATIONS.add(Resource.class);
- ANNOTATIONS.add(Resources.class);
- }
-
-
- private final ResourceManager resourceManager;
- private final List<ResourceResolver> resourceResolvers;
-
- public ResourceInjector(ResourceManager resMgr) {
- this(resMgr, resMgr == null ? null : resMgr.getResourceResolvers());
- }
-
- public ResourceInjector(ResourceManager resMgr, List<ResourceResolver> resolvers) {
- super(ANNOTATIONS);
- resourceManager = resMgr;
- resourceResolvers = resolvers;
- }
-
- private static Field getField(Class<?> cls, String name) {
- if (cls == null) {
- return null;
- }
- try {
- Field f = ReflectionUtil.getDeclaredField(cls, name);
- if (f == null) {
- f = getField(cls.getSuperclass(), name);
- }
- return f;
- } catch (Exception ex) {
- return getField(cls.getSuperclass(), name);
- }
- }
-
- public static boolean processable(Class<?> cls, Object o) {
- if (cls.getName().startsWith("java.")
- || cls.getName().startsWith("javax.")) {
- return false;
- }
- NoJSR250Annotations njsr = cls.getAnnotation(NoJSR250Annotations.class);
- if (njsr != null) {
- for (String s : njsr.unlessNull()) {
- try {
- Field f = getField(cls, s);
- ReflectionUtil.setAccessible(f);
- if (f.get(o) == null) {
- return true;
- }
- } catch (Exception ex) {
- return true;
- }
- }
- return false;
- }
- return true;
- }
-
- public void inject(Object o) {
- inject(o, o.getClass());
- }
-
- public void inject(Object o, Class<?> claz) {
- if (processable(claz, o)) {
- AnnotationProcessor processor = new AnnotationProcessor(o);
- processor.accept(this, claz);
- }
- }
-
- public void construct(Object o) {
- setTarget(o);
- if (processable(targetClass, o)) {
- invokePostConstruct();
- }
- }
- public void construct(Object o, Class<?> cls) {
- setTarget(o, cls);
- if (processable(targetClass, o)) {
- invokePostConstruct();
- }
- }
-
-
- public void destroy(Object o) {
- setTarget(o);
- if (processable(targetClass, o)) {
- invokePreDestroy();
- }
- }
-
-
- // Implementation of org.apache.cxf.common.annotation.AnnotationVisitor
-
- @Override
- public final void visitClass(final Class<?> clz, final Annotation annotation) { //NOPMD
-
- assert annotation instanceof Resource || annotation instanceof Resources : annotation;
-
- if (annotation instanceof Resource) {
- injectResourceClassLevel((Resource)annotation);
- } else if (annotation instanceof Resources) {
- Resources resources = (Resources)annotation;
- for (Resource resource : resources.value()) {
- injectResourceClassLevel(resource);
- }
- }
-
- }
-
- private void injectResourceClassLevel(Resource res) {
- if (res.name() == null || "".equals(res.name())) {
- LOG.log(Level.INFO, "RESOURCE_NAME_NOT_SPECIFIED", target.getClass().getName());
- return;
- }
-
- Object resource;
- // first find a setter that matches this resource
- Method setter = findSetterForResource(res);
- if (setter != null) {
- Class<?> type = getResourceType(res, setter);
- resource = resolveResource(res.name(), type);
- if (resource == null) {
- LOG.log(Level.INFO, "RESOURCE_RESOLVE_FAILED");
- return;
- }
-
- invokeSetter(setter, resource);
- return;
- }
-
- Field field = findFieldForResource(res);
- if (field != null) {
- Class<?> type = getResourceType(res, field);
- resource = resolveResource(res.name(), type);
- if (resource == null) {
- LOG.log(Level.INFO, "RESOURCE_RESOLVE_FAILED");
- return;
- }
- injectField(field, resource);
- return;
- }
- LOG.log(Level.SEVERE, "NO_SETTER_OR_FIELD_FOR_RESOURCE", getTarget().getClass().getName());
- }
-
- public final void visitField(final Field field, final Annotation annotation) {
-
- assert annotation instanceof Resource : annotation;
-
- Resource res = (Resource)annotation;
-
- String name = getFieldNameForResource(res, field);
- Class<?> type = getResourceType(res, field);
-
- Object resource = resolveResource(name, type);
- if (resource == null
- && "".equals(res.name())) {
- resource = resolveResource(null, type);
- }
- if (resource != null) {
- injectField(field, resource);
- } else {
- LOG.log(Level.INFO, "RESOURCE_RESOLVE_FAILED", name);
- }
- }
-
- public final void visitMethod(final Method method, final Annotation annotation) {
-
- assert annotation instanceof Resource : annotation;
-
- Resource res = (Resource)annotation;
-
- String resourceName = getResourceName(res, method);
- Class<?> clz = getResourceType(res, method);
-
- Object resource = resolveResource(resourceName, clz);
- if (resource == null
- && "".equals(res.name())) {
- resource = resolveResource(null, clz);
- }
- if (resource != null) {
- invokeSetter(method, resource);
- } else {
- LOG.log(Level.FINE, "RESOURCE_RESOLVE_FAILED", new Object[] {resourceName, clz});
- }
- }
-
- private Field findFieldForResource(Resource res) {
- assert target != null;
- assert res.name() != null;
-
- for (Field field : target.getClass().getFields()) {
- if (field.getName().equals(res.name())) {
- return field;
- }
- }
-
- for (Field field : target.getClass().getDeclaredFields()) {
- if (field.getName().equals(res.name())) {
- return field;
- }
- }
- return null;
- }
-
-
- private Method findSetterForResource(Resource res) {
- assert target != null;
-
- String setterName = resourceNameToSetter(res.name());
- Method setterMethod = null;
-
- for (Method method : getTarget().getClass().getMethods()) {
- if (setterName.equals(method.getName())) {
- setterMethod = method;
- break;
- }
- }
-
- if (setterMethod != null && setterMethod.getParameterTypes().length != 1) {
- LOG.log(Level.WARNING, "SETTER_INJECTION_WITH_INCORRECT_TYPE", setterMethod);
- }
- return setterMethod;
- }
-
- private static String resourceNameToSetter(String resName) {
- return "set" + StringUtils.capitalize(resName);
- }
-
- private void invokeSetter(Method method, Object resource) {
- try {
- ReflectionUtil.setAccessible(method);
- if (method.getDeclaringClass().isAssignableFrom(getTarget().getClass())) {
- method.invoke(getTarget(), resource);
- } else { // deal with the proxy setter method
- Method targetMethod = getTarget().getClass().getMethod(method.getName(),
- method.getParameterTypes());
- targetMethod.invoke(getTarget(), resource);
- }
- } catch (IllegalAccessException e) {
- LOG.log(Level.SEVERE, "INJECTION_SETTER_NOT_VISIBLE", method);
- } catch (InvocationTargetException | SecurityException e) {
- LogUtils.log(LOG, Level.SEVERE, "INJECTION_SETTER_RAISED_EXCEPTION", e, method);
- } catch (NoSuchMethodException e) {
- LOG.log(Level.SEVERE, "INJECTION_SETTER_METHOD_NOT_FOUND", new Object[] {method.getName()});
- }
- }
-
- private String getResourceName(Resource res, Method method) {
- assert method != null;
- assert res != null;
- assert method.getName().startsWith("set") : method;
-
- if (res.name() == null || res.name().isEmpty()) {
- String name = method.getName().substring(3);
- name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
- return method.getDeclaringClass().getCanonicalName() + '/' + name;
- }
- return res.name();
- }
-
-
-
- private void injectField(Field field, Object resource) {
- assert field != null;
- assert resource != null;
-
- boolean accessible = field.isAccessible();
- try {
- if (field.getType().isAssignableFrom(resource.getClass())) {
- ReflectionUtil.setAccessible(field);
- field.set(ClassHelper.getRealObject(getTarget()), resource);
- }
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- LOG.severe("FAILED_TO_INJECT_FIELD");
- } finally {
- ReflectionUtil.setAccessible(field, accessible);
- }
- }
-
-
- public void invokePostConstruct() {
-
- boolean accessible = false;
- for (Method method : getPostConstructMethods()) {
- PostConstruct pc = method.getAnnotation(PostConstruct.class);
- if (pc != null) {
- try {
- ReflectionUtil.setAccessible(method);
- method.invoke(target);
- } catch (IllegalAccessException e) {
- LOG.log(Level.WARNING, "INJECTION_COMPLETE_NOT_VISIBLE", method);
- } catch (InvocationTargetException e) {
- LOG.log(Level.WARNING, "INJECTION_COMPLETE_THREW_EXCEPTION", e);
- } finally {
- ReflectionUtil.setAccessible(method, accessible);
- }
- }
- }
- }
-
- public void invokePreDestroy() {
-
- boolean accessible = false;
- for (Method method : getPreDestroyMethods()) {
- PreDestroy pd = method.getAnnotation(PreDestroy.class);
- if (pd != null) {
- try {
- ReflectionUtil.setAccessible(method);
- method.invoke(target);
- } catch (IllegalAccessException e) {
- LOG.log(Level.WARNING, "PRE_DESTROY_NOT_VISIBLE", method);
- } catch (InvocationTargetException e) {
- LOG.log(Level.WARNING, "PRE_DESTROY_THREW_EXCEPTION", e);
- } finally {
- ReflectionUtil.setAccessible(method, accessible);
- }
- }
- }
- }
-
-
- private Collection<Method> getPostConstructMethods() {
- return getAnnotatedMethods(PostConstruct.class);
- }
-
- private Collection<Method> getPreDestroyMethods() {
- return getAnnotatedMethods(PreDestroy.class);
- }
-
- private Collection<Method> getAnnotatedMethods(Class<? extends Annotation> acls) {
-
- Collection<Method> methods = new LinkedList<>();
- addAnnotatedMethods(acls, getTarget().getClass().getMethods(), methods);
- addAnnotatedMethods(acls, ReflectionUtil.getDeclaredMethods(getTarget().getClass()), methods);
- if (getTargetClass() != getTarget().getClass()) {
- addAnnotatedMethods(acls, getTargetClass().getMethods(), methods);
- addAnnotatedMethods(acls, ReflectionUtil.getDeclaredMethods(getTargetClass()), methods);
- }
- return methods;
- }
-
- private void addAnnotatedMethods(Class<? extends Annotation> acls, Method[] methods,
- Collection<Method> annotatedMethods) {
- for (Method method : methods) {
- if (method.getAnnotation(acls) != null
- && !annotatedMethods.contains(method)) {
- annotatedMethods.add(method);
- }
- }
- }
-
-
- /**
- * making this protected to keep pmd happy
- */
- protected Class<?> getResourceType(Resource res, Field field) {
- assert res != null;
- Class<?> type = res.type();
- if (res.type() == null || Object.class == res.type()) {
- type = field.getType();
- }
- return type;
- }
-
-
- private Class<?> getResourceType(Resource res, Method method) {
- return res.type() != null && !Object.class.equals(res.type())
- ? res.type()
- : method.getParameterTypes()[0];
- }
-
-
- private String getFieldNameForResource(Resource res, Field field) {
- assert res != null;
- if (res.name() == null || "".equals(res.name())) {
- return field.getDeclaringClass().getCanonicalName() + "/" + field.getName();
- }
- return res.name();
- }
-
- private Object resolveResource(String resourceName, Class<?> type) {
- if (resourceManager == null) {
- return null;
- }
- return resourceManager.resolveResource(resourceName, type, resourceResolvers);
- }
-
-}
diff --git a/transform/src/patch/java/org/apache/cxf/common/jaxb/JAXBUtils.java b/transform/src/patch/java/org/apache/cxf/common/jaxb/JAXBUtils.java
deleted file mode 100644
index f018e2a..0000000
--- a/transform/src/patch/java/org/apache/cxf/common/jaxb/JAXBUtils.java
+++ /dev/null
@@ -1,1180 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.common.jaxb;
-
-
-import java.io.BufferedReader;
-import java.io.Closeable;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.lang.annotation.Annotation;
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Target;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-import java.lang.reflect.Type;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.nio.charset.StandardCharsets;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Set;
-import java.util.StringTokenizer;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBElement;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Marshaller;
-import javax.xml.bind.PropertyException;
-import javax.xml.bind.SchemaOutputResolver;
-import javax.xml.bind.Unmarshaller;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.attachment.AttachmentMarshaller;
-import javax.xml.bind.attachment.AttachmentUnmarshaller;
-import javax.xml.namespace.QName;
-import javax.xml.stream.XMLStreamReader;
-import javax.xml.stream.XMLStreamWriter;
-import javax.xml.transform.Result;
-import javax.xml.transform.Source;
-import javax.xml.transform.dom.DOMResult;
-import javax.xml.transform.stream.StreamResult;
-
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-import org.xml.sax.EntityResolver;
-import org.xml.sax.InputSource;
-
-import org.apache.cxf.Bus;
-import org.apache.cxf.common.classloader.ClassLoaderUtils;
-import org.apache.cxf.common.logging.LogUtils;
-import org.apache.cxf.common.spi.ClassLoaderService;
-import org.apache.cxf.common.util.CachedClass;
-import org.apache.cxf.common.util.PackageUtils;
-import org.apache.cxf.common.util.ProxyHelper;
-import org.apache.cxf.common.util.ReflectionInvokationHandler;
-import org.apache.cxf.common.util.ReflectionInvokationHandler.WrapReturn;
-import org.apache.cxf.common.util.ReflectionUtil;
-import org.apache.cxf.common.util.StringUtils;
-import org.apache.cxf.common.util.SystemPropertyAction;
-import org.apache.cxf.common.xmlschema.SchemaCollection;
-import org.apache.cxf.helpers.JavaUtils;
-
-public final class JAXBUtils {
- public static final String JAXB_URI = "http://java.sun.com/xml/ns/jaxb";
-
- private static final Logger LOG = LogUtils.getL7dLogger(JAXBUtils.class);
-
- public enum IdentifierType {
- CLASS,
- INTERFACE,
- GETTER,
- SETTER,
- VARIABLE,
- CONSTANT
- };
-
- private static final char[] XML_NAME_PUNCTUATION_CHARS = new char[] {
- /* hyphen */ '\u002D',
- /* period */ '\u002E',
- /* colon */'\u003A',
- /* dot */ '\u00B7',
- /* greek ano teleia */ '\u0387',
- /* arabic end of ayah */ '\u06DD',
- /* arabic start of rub el hizb */'\u06DE',
- /* underscore */ '\u005F',
- };
-
- private static final String XML_NAME_PUNCTUATION_STRING = new String(XML_NAME_PUNCTUATION_CHARS);
-
- private static final Map<String, String> BUILTIN_DATATYPES_MAP;
- private static final Map<String, Class<?>> HOLDER_TYPES_MAP;
- private static ClassLoader jaxbXjcLoader;
- private static volatile Optional<Object> jaxbMinimumEscapeHandler;
- private static volatile Optional<Object> jaxbNoEscapeHandler;
-
- static {
- BUILTIN_DATATYPES_MAP = new HashMap<>();
- BUILTIN_DATATYPES_MAP.put("string", "java.lang.String");
- BUILTIN_DATATYPES_MAP.put("integer", "java.math.BigInteger");
- BUILTIN_DATATYPES_MAP.put("int", "int");
- BUILTIN_DATATYPES_MAP.put("long", "long");
- BUILTIN_DATATYPES_MAP.put("short", "short");
- BUILTIN_DATATYPES_MAP.put("decimal", "java.math.BigDecimal");
- BUILTIN_DATATYPES_MAP.put("float", "float");
- BUILTIN_DATATYPES_MAP.put("double", "double");
- BUILTIN_DATATYPES_MAP.put("boolean", "boolean");
- BUILTIN_DATATYPES_MAP.put("byte", "byte");
- BUILTIN_DATATYPES_MAP.put("QName", "javax.xml.namespace.QName");
- BUILTIN_DATATYPES_MAP.put("dateTime", "javax.xml.datatype.XMLGregorianCalendar");
- BUILTIN_DATATYPES_MAP.put("base64Binary", "byte[]");
- BUILTIN_DATATYPES_MAP.put("hexBinary", "byte[]");
- BUILTIN_DATATYPES_MAP.put("unsignedInt", "long");
- BUILTIN_DATATYPES_MAP.put("unsignedShort", "short");
- BUILTIN_DATATYPES_MAP.put("unsignedByte", "byte");
- BUILTIN_DATATYPES_MAP.put("time", "javax.xml.datatype.XMLGregorianCalendar");
- BUILTIN_DATATYPES_MAP.put("date", "javax.xml.datatype.XMLGregorianCalendar");
- BUILTIN_DATATYPES_MAP.put("gYear", "javax.xml.datatype.XMLGregorianCalendar");
- BUILTIN_DATATYPES_MAP.put("gYearMonth", "javax.xml.datatype.XMLGregorianCalendar");
- BUILTIN_DATATYPES_MAP.put("gMonth", "javax.xml.datatype.XMLGregorianCalendar");
- BUILTIN_DATATYPES_MAP.put("gMonthDay", "javax.xml.datatype.XMLGregorianCalendar");
- BUILTIN_DATATYPES_MAP.put("gDay", "javax.xml.datatype.XMLGregorianCalendar");
- BUILTIN_DATATYPES_MAP.put("duration", "javax.xml.datatype.Duration");
- BUILTIN_DATATYPES_MAP.put("NOTATION", "javax.xml.namespace.QName");
-
- HOLDER_TYPES_MAP = new HashMap<>();
- HOLDER_TYPES_MAP.put("int", java.lang.Integer.class);
- HOLDER_TYPES_MAP.put("long", java.lang.Long.class);
- HOLDER_TYPES_MAP.put("short", java.lang.Short.class);
- HOLDER_TYPES_MAP.put("float", java.lang.Float.class);
- HOLDER_TYPES_MAP.put("double", java.lang.Double.class);
- HOLDER_TYPES_MAP.put("boolean", java.lang.Boolean.class);
- HOLDER_TYPES_MAP.put("byte", java.lang.Byte.class);
- }
-
-
- /**
- * prevents instantiation
- *
- */
- private JAXBUtils() {
- }
-
- public static void closeUnmarshaller(Unmarshaller u) {
- if (u instanceof Closeable) {
- //need to do this to clear the ThreadLocal cache
- //see https://java.net/jira/browse/JAXB-1000
-
- try {
- ((Closeable)u).close();
- } catch (IOException e) {
- //ignore
- }
- }
- }
- public static Object unmarshall(JAXBContext c, Element e) throws JAXBException {
- Unmarshaller u = c.createUnmarshaller();
- try {
- u.setEventHandler(null);
- return u.unmarshal(e);
- } finally {
- closeUnmarshaller(u);
- }
- }
- public static <T> JAXBElement<T> unmarshall(JAXBContext c, Element e, Class<T> cls) throws JAXBException {
- Unmarshaller u = c.createUnmarshaller();
- try {
- u.setEventHandler(null);
- return u.unmarshal(e, cls);
- } finally {
- closeUnmarshaller(u);
- }
- }
- public static Object unmarshall(JAXBContext c, Source s) throws JAXBException {
- Unmarshaller u = c.createUnmarshaller();
- try {
- u.setEventHandler(null);
- return u.unmarshal(s);
- } finally {
- closeUnmarshaller(u);
- }
- }
- public static <T> JAXBElement<T> unmarshall(JAXBContext c,
- XMLStreamReader reader,
- Class<T> cls) throws JAXBException {
- Unmarshaller u = c.createUnmarshaller();
- try {
- u.setEventHandler(null);
- return u.unmarshal(reader, cls);
- } finally {
- closeUnmarshaller(u);
- }
- }
- public static Object unmarshall(JAXBContext c,
- XMLStreamReader reader) throws JAXBException {
- Unmarshaller u = c.createUnmarshaller();
- try {
- u.setEventHandler(null);
- return u.unmarshal(reader);
- } finally {
- closeUnmarshaller(u);
- }
- }
-
- public static String builtInTypeToJavaType(String type) {
- return BUILTIN_DATATYPES_MAP.get(type);
- }
-
- public static Class<?> holderClass(String type) {
- return HOLDER_TYPES_MAP.get(type);
- }
-
- /**
- * Checks if the specified word is a Java keyword (as defined in JavaUtils).
- *
- * @param word the word to check.
- * @return true if the word is a keyword.
- * @see org.apache.cxf.helpers.JavaUtils
- */
- protected static boolean isJavaKeyword(String word) {
- return JavaUtils.isJavaKeyword(word);
- }
-
- /**
- * Generates a Java package name from a URI according to the
- * algorithm outlined in JAXB 2.0.
- *
- * @param namespaceURI the namespace URI.
- * @return the package name.
- */
- public static String namespaceURIToPackage(String namespaceURI) {
- try {
- return nameSpaceURIToPackage(new URI(namespaceURI));
- } catch (URISyntaxException ex) {
- return null;
- }
- }
-
- /**
- * Generates a Java package name from a URI according to the
- * algorithm outlined in Appendix D of JAXB (2.0+).
- *
- * @param uri the namespace URI.
- * @return the package name.
- */
- public static String nameSpaceURIToPackage(URI uri) {
-
- StringBuilder packageName = new StringBuilder();
- String authority = uri.getAuthority();
- String scheme = uri.getScheme();
- if (authority == null && "urn".equals(scheme)) {
- authority = uri.getSchemeSpecificPart();
- }
-
- if (null != authority && !"".equals(authority)) {
- if ("urn".equals(scheme)) {
- packageName.append(authority);
- /* JAXB 2.2 D.5.1, Rule #5 */
- for (int i = 0; i < packageName.length(); i++) {
- if (packageName.charAt(i) == '-') {
- packageName.setCharAt(i, '.');
- }
- }
- authority = packageName.toString();
- packageName.setLength(0);
-
- StringTokenizer st = new StringTokenizer(authority, ":");
- while (st.hasMoreTokens()) {
- String token = st.nextToken();
- if (packageName.length() > 0) {
- packageName.insert(0, '.');
- packageName.insert(0, normalizePackageNamePart(token));
- } else {
- packageName.insert(0, token);
- }
- }
- authority = packageName.toString();
- packageName.setLength(0);
-
- }
-
- StringTokenizer st = new StringTokenizer(authority, ".");
- if (st.hasMoreTokens()) {
- while (st.hasMoreTokens()) {
- String token = st.nextToken();
- if (packageName.length() == 0) {
- if ("www".equals(token)) {
- continue;
- }
- } else {
- packageName.insert(0, '.');
- }
- packageName.insert(0, normalizePackageNamePart(token));
- }
- }
-
- if (!("http".equalsIgnoreCase(scheme) || "urn".equalsIgnoreCase(scheme))) {
- packageName.insert(0, '.');
- packageName.insert(0, normalizePackageNamePart(scheme));
- }
-
- }
-
- String path = uri.getPath();
- if (path == null) {
- path = "";
- }
- /* JAXB 2.2 D.5.1 Rule 2 - remove trailing .??, .???, or .html only. */
- int index = path.lastIndexOf('.');
- if (index < 0) {
- index = path.length();
- } else {
- String ending = path.substring(index + 1);
- if (ending.length() < 2 || (ending.length() > 3
- && !"html".equalsIgnoreCase(ending))) {
- index = path.length();
- }
- }
- StringTokenizer st = new StringTokenizer(path.substring(0, index), "/");
- while (st.hasMoreTokens()) {
- String token = st.nextToken();
- if (packageName.length() > 0) {
- packageName.append('.');
- }
- packageName.append(normalizePackageNamePart(token));
- }
- return packageName.toString();
- }
-
- private static String normalizePackageNamePart(String name) {
- StringBuilder sname = new StringBuilder(name.toLowerCase());
-
- for (int i = 0; i < sname.length(); i++) {
- sname.setCharAt(i, Character.toLowerCase(sname.charAt(i)));
- }
-
- for (int i = 0; i < sname.length(); i++) {
- if (!Character.isJavaIdentifierPart(sname.charAt(i))) {
- sname.setCharAt(i, '_');
- }
- }
-
- if (isJavaKeyword(sname.toString())) {
- sname.insert(0, '_');
- }
-
- if (!Character.isJavaIdentifierStart(sname.charAt(0))) {
- sname.insert(0, '_');
- }
-
- return sname.toString();
- }
-
-
- /**
- * Converts an XML name to a Java identifier according to the mapping
- * algorithm outlined in the JAXB specification
- *
- * @param name the XML name
- * @return the Java identifier
- */
- public static String nameToIdentifier(String name, IdentifierType type) {
-
- if (null == name || name.length() == 0) {
- return name;
- }
-
- // algorithm will not change an XML name that is already a legal and
- // conventional (!) Java class, method, or constant identifier
-
- StringBuilder buf = new StringBuilder(name);
- boolean hasUnderscore = false;
- boolean legalIdentifier = Character.isJavaIdentifierStart(buf.charAt(0));
-
- for (int i = 1; i < name.length() && legalIdentifier; i++) {
- legalIdentifier &= Character.isJavaIdentifierPart(buf.charAt(i));
- hasUnderscore |= '_' == buf.charAt(i);
- }
-
- boolean conventionalIdentifier = isConventionalIdentifier(buf, type);
- if (legalIdentifier && conventionalIdentifier) {
- if (JAXBUtils.isJavaKeyword(name) && type == IdentifierType.VARIABLE) {
- name = normalizePackageNamePart(name);
- }
- if (!hasUnderscore || IdentifierType.CLASS != type) {
- return name;
- }
- }
-
- // split into words
-
- List<String> words = new ArrayList<>();
-
- StringTokenizer st = new StringTokenizer(name, XML_NAME_PUNCTUATION_STRING);
- while (st.hasMoreTokens()) {
- words.add(st.nextToken());
- }
-
- for (int i = 0; i < words.size(); i++) {
- splitWord(words, i);
- }
-
- return makeConventionalIdentifier(words, type);
- }
-
- private static void splitWord(List<String> words, int listIndex) {
- String word = words.get(listIndex);
- if (word.length() <= 1) {
- return;
- }
- int index = listIndex + 1;
- StringBuilder sword = new StringBuilder(word);
- int first = 0;
- char firstChar = sword.charAt(first);
- if (Character.isLowerCase(firstChar)) {
- sword.setCharAt(first, Character.toUpperCase(firstChar));
- }
- int i = 1;
-
- while (i < sword.length()) {
- if (Character.isDigit(firstChar)) {
- while (i < sword.length() && Character.isDigit(sword.charAt(i))) {
- i++;
- }
- } else if (isCasedLetter(firstChar)) {
- boolean previousIsLower = Character.isLowerCase(firstChar);
- while (i < sword.length() && isCasedLetter(sword.charAt(i))) {
- if (Character.isUpperCase(sword.charAt(i)) && previousIsLower) {
- break;
- }
- previousIsLower = Character.isLowerCase(sword.charAt(i));
- i++;
- }
- } else {
- // first must be a mark or an uncased letter
- while (i < sword.length() && (isMark(sword.charAt(i)) || !isCasedLetter(sword.charAt(i)))) {
- i++;
- }
- }
-
- // characters from first to i are all either
- // * digits
- // * upper or lower case letters, with only the first one an upper
- // * uncased letters or marks
-
-
- String newWord = sword.substring(first, i);
- words.add(index, newWord);
- index++;
- if (i >= sword.length()) {
- break;
- }
- first = i;
- firstChar = sword.charAt(first);
- }
-
- if (index > (listIndex + 1)) {
- words.remove(listIndex);
- }
- }
-
- private static boolean isMark(char c) {
- return Character.isJavaIdentifierPart(c) && !Character.isLetter(c) && !Character.isDigit(c);
- }
-
- private static boolean isCasedLetter(char c) {
- return Character.isUpperCase(c) || Character.isLowerCase(c);
- }
-
- private static boolean isConventionalIdentifier(StringBuilder buf, IdentifierType type) {
- if (null == buf || buf.length() == 0) {
- return false;
- }
- final boolean result;
- if (IdentifierType.CONSTANT == type) {
- for (int i = 0; i < buf.length(); i++) {
- if (Character.isLowerCase(buf.charAt(i))) {
- return false;
- }
- }
- result = true;
- } else if (IdentifierType.VARIABLE == type) {
- result = Character.isLowerCase(buf.charAt(0));
- } else {
- int pos = 3;
- if (IdentifierType.GETTER == type
- && !(buf.length() >= pos
- && "get".equals(buf.subSequence(0, 3)))) {
- return false;
- } else if (IdentifierType.SETTER == type
- && !(buf.length() >= pos && "set".equals(buf.subSequence(0, 3)))) {
- return false;
- } else {
- pos = 0;
- }
- result = Character.isUpperCase(buf.charAt(pos));
- }
- return result;
- }
-
- private static String makeConventionalIdentifier(List<String> words, IdentifierType type) {
- StringBuilder buf = new StringBuilder();
- boolean firstWord = true;
- if (IdentifierType.GETTER == type) {
- buf.append("get");
- } else if (IdentifierType.SETTER == type) {
- buf.append("set");
- }
- for (String w : words) {
- int l = buf.length();
- if (l > 0 && IdentifierType.CONSTANT == type) {
- buf.append('_');
- l++;
- }
- buf.append(w);
- if (IdentifierType.CONSTANT == type) {
- for (int i = l; i < buf.length(); i++) {
- if (Character.isLowerCase(buf.charAt(i))) {
- buf.setCharAt(i, Character.toUpperCase(buf.charAt(i)));
- }
- }
- } else if (IdentifierType.VARIABLE == type) {
- if (firstWord && Character.isUpperCase(buf.charAt(l))) {
- buf.setCharAt(l, Character.toLowerCase(buf.charAt(l)));
- }
- } else {
- if (firstWord && Character.isLowerCase(buf.charAt(l))) {
- buf.setCharAt(l, Character.toUpperCase(buf.charAt(l)));
- }
- }
- firstWord = false;
- }
- return buf.toString();
- }
-
- public static Class<?> getValidClass(Class<?> cls) {
- if (cls.isEnum() || cls.isArray()) {
- return cls;
- }
-
- if (cls == Object.class || cls == String.class || cls.isPrimitive() || cls.isAnnotation()
- || "javax.xml.ws.Holder".equals(cls.getName())) {
- return null;
- } else if (cls.isInterface()
- || "javax.xml.ws.wsaddressing.W3CEndpointReference".equals(cls.getName())) {
- return cls;
- }
-
- Constructor<?> cons = ReflectionUtil.getDeclaredConstructor(cls);
- if (cons == null) {
- cons = ReflectionUtil.getConstructor(cls);
- if (cons == null) {
- return null;
- }
- }
- return cls;
- }
-
- private static synchronized ClassLoader getXJCClassLoader() {
- if (jaxbXjcLoader == null) {
- try {
- Class.forName("com.sun.tools.internal.xjc.api.XJC");
- jaxbXjcLoader = ClassLoader.getSystemClassLoader();
- } catch (Exception t2) {
- //couldn't find either, probably cause tools.jar isn't on
- //the classpath. Let's see if we can find the tools jar
- String s = SystemPropertyAction.getProperty("java.home");
- if (!StringUtils.isEmpty(s)) {
- File home = new File(s);
- File jar = new File(home, "lib/tools.jar");
- if (!jar.exists()) {
- jar = new File(home, "../lib/tools.jar");
- }
- if (jar.exists()) {
- try {
- jaxbXjcLoader = new URLClassLoader(new URL[] {jar.toURI().toURL()});
- Class.forName("com.sun.tools.internal.xjc.api.XJC", false, jaxbXjcLoader);
- } catch (Exception e) {
- jaxbXjcLoader = null;
- }
- }
- }
- }
- }
- return jaxbXjcLoader;
- }
-
- public static Object setNamespaceMapper(Bus bus, final Map<String, String> nspref,
- Marshaller marshaller) throws PropertyException {
- ClassLoaderService classLoaderService = bus.getExtension(ClassLoaderService.class);
- Object mapper = classLoaderService.createNamespaceWrapperInstance(marshaller.getClass(), nspref);
- if (mapper != null) {
- if (marshaller.getClass().getName().contains(".internal.")) {
- marshaller.setProperty("com.sun.xml.internal.bind.namespacePrefixMapper",
- mapper);
- } else if (marshaller.getClass().getName().contains("com.sun")) {
- marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper",
- mapper);
- } else if (marshaller.getClass().getName().contains("eclipse")) {
- marshaller.setProperty("eclipselink.namespace-prefix-mapper",
- mapper);
- }
- }
- return mapper;
- }
- public static BridgeWrapper createBridge(Set<Class<?>> ctxClasses,
- QName qname,
- Class<?> refcls,
- Annotation[] anns) throws JAXBException {
- try {
- Class<?> cls;
- Class<?> refClass;
- String pkg = "com.sun.xml.bind.";
- try {
- cls = Class.forName("com.sun.xml.bind.api.JAXBRIContext");
- refClass = Class.forName(pkg + "api.TypeReference");
- } catch (ClassNotFoundException e) {
- cls = Class.forName("com.sun.xml.internal.bind.api.JAXBRIContext", true, getXJCClassLoader());
- pkg = "com.sun.xml.internal.bind.";
- refClass = Class.forName(pkg + "api.TypeReference", true, getXJCClassLoader());
- }
- Object ref = refClass.getConstructor(QName.class,
- Type.class,
- anns.getClass()).newInstance(qname, refcls, anns);
- List<Object> typeRefs = new ArrayList<>();
- typeRefs.add(ref);
- List<Class<?>> clses = new ArrayList<>(ctxClasses);
- clses.add(refClass.getField("type").get(ref).getClass());
- if (!refcls.isInterface()) {
- clses.add(refcls);
- }
-
- Object ctx = null;
- for (Method m : cls.getDeclaredMethods()) {
- if ("newInstance".equals(m.getName())
- && m.getParameterTypes().length == 6) {
- ctx = m.invoke(null, clses.toArray(new Class<?>[0]),
- typeRefs, null, null, true, null);
-
- }
- }
-
- if (ctx == null) {
- throw new JAXBException("No ctx found");
- }
-
- Object bridge = ctx.getClass().getMethod("createBridge", refClass).invoke(ctx, ref);
- return ReflectionInvokationHandler.createProxyWrapper(bridge,
- BridgeWrapper.class);
- } catch (Exception ex) {
- throw new JAXBException(ex);
- }
- }
- public interface BridgeWrapper {
-
- Object unmarshal(XMLStreamReader source, AttachmentUnmarshaller am) throws JAXBException;
-
- Object unmarshal(InputStream source) throws JAXBException;
-
- Object unmarshal(Node source, AttachmentUnmarshaller am) throws JAXBException;
-
- void marshal(Object elValue, XMLStreamWriter source, AttachmentMarshaller m) throws JAXBException;
-
- void marshal(Object elValue, StreamResult s1) throws JAXBException;
-
- void marshal(Object elValue, Node source, AttachmentMarshaller am) throws JAXBException;
- }
-
-
- public static SchemaCompiler createSchemaCompiler() throws JAXBException {
- try {
- Class<?> cls;
- Object sc;
- try {
- cls = Class.forName("com.sun.tools.xjc.api.XJC");
- sc = cls.getMethod("createSchemaCompiler").invoke(null);
- } catch (Throwable e) {
- cls = Class.forName("com.sun.tools.internal.xjc.api.XJC", true, getXJCClassLoader());
- sc = cls.getMethod("createSchemaCompiler").invoke(null);
- }
-
- return ReflectionInvokationHandler.createProxyWrapper(sc,
- SchemaCompiler.class);
- } catch (Exception ex) {
- throw new JAXBException(ex);
- }
- }
-
- public static SchemaCompiler createSchemaCompilerWithDefaultAllocator(Set<String> allocatorSet) {
-
- try {
- SchemaCompiler compiler = JAXBUtils.createSchemaCompiler();
- Object allocator = ReflectionInvokationHandler
- .createProxyWrapper(new DefaultClassNameAllocator(allocatorSet),
- JAXBUtils.getParamClass(compiler, "setClassNameAllocator"));
-
- compiler.setClassNameAllocator(allocator);
- return compiler;
- } catch (JAXBException e1) {
- throw new IllegalStateException("Unable to create schema compiler", e1);
- }
-
- }
-
- public static void logGeneratedClassNames(Logger logger, JCodeModel codeModel) {
- if (!logger.isLoggable(Level.FINE)) {
- return;
- }
-
- StringBuilder sb = new StringBuilder();
- boolean first = true;
- for (Iterator<JPackage> itr = codeModel.packages(); itr.hasNext();) {
- JPackage package1 = itr.next();
-
- for (Iterator<JDefinedClass> citr = package1.classes(); citr.hasNext();) {
- if (!first) {
- sb.append(", ");
- } else {
- first = false;
- }
- sb.append(citr.next().fullName());
- }
- }
-
- logger.log(Level.FINE, "Created classes: " + sb.toString());
- }
-
- public static List<String> getGeneratedClassNames(JCodeModel codeModel) {
- List<String> classes = new ArrayList<>();
- for (Iterator<JPackage> itr = codeModel.packages(); itr.hasNext();) {
- JPackage package1 = itr.next();
-
- for (Iterator<JDefinedClass> citr = package1.classes(); citr.hasNext();) {
- classes.add(citr.next().fullName());
- }
- }
- return classes;
- }
- public static Object createFileCodeWriter(File f) throws JAXBException {
- return createFileCodeWriter(f, StandardCharsets.UTF_8.name());
- }
- public static Object createFileCodeWriter(File f, String encoding) throws JAXBException {
- try {
- Class<?> cls;
- try {
- cls = Class.forName("com.sun.codemodel.writer.FileCodeWriter");
- } catch (ClassNotFoundException e) {
- cls = Class.forName("com.sun.codemodel.internal.writer.FileCodeWriter",
- true, getXJCClassLoader());
- }
- if (encoding != null) {
- try {
- return cls.getConstructor(File.class, String.class)
- .newInstance(f, encoding);
- } catch (Exception ex) {
- // try a single argument constructor
- }
- }
- return cls.getConstructor(File.class).newInstance(f);
- } catch (Exception ex) {
- throw new JAXBException(ex);
- }
- }
-
- public static Class<?> getParamClass(SchemaCompiler sc, String method) {
- Object o = ((ReflectionInvokationHandler)Proxy.getInvocationHandler(sc)).getTarget();
- for (Method m : o.getClass().getMethods()) {
- if (m.getName().equals(method) && m.getParameterTypes().length == 1) {
- return m.getParameterTypes()[0];
- }
- }
- return null;
- }
-
-
- public static List<DOMResult> generateJaxbSchemas(
- JAXBContext context, final Map<String, DOMResult> builtIns) throws IOException {
- final List<DOMResult> results = new ArrayList<>();
-
- context.generateSchema(new SchemaOutputResolver() {
- @Override
- public Result createOutput(String ns, String file) throws IOException {
- DOMResult result = new DOMResult();
-
- if (builtIns.containsKey(ns)) {
- DOMResult dr = builtIns.get(ns);
- result.setSystemId(dr.getSystemId());
- results.add(dr);
- return result;
- }
- result.setSystemId(file);
- results.add(result);
- return result;
- }
- });
- return results;
- }
-
- public static String getPackageNamespace(Class<?> cls) {
- Package p = cls.getPackage();
- if (p != null) {
- javax.xml.bind.annotation.XmlSchema schemaAnn =
- p.getAnnotation(javax.xml.bind.annotation.XmlSchema.class);
- if (schemaAnn != null) {
- return schemaAnn.namespace();
- }
- }
- return null;
- }
-
- public static void scanPackages(Set<Class<?>> classes,
- Map<Package, CachedClass> objectFactoryCache) {
- scanPackages(classes, null, objectFactoryCache);
- }
- public static void scanPackages(Set<Class<?>> classes,
- Class<?>[] extraClass,
- Map<Package, CachedClass> objectFactoryCache) {
-
- // add user extra class into jaxb context
- if (extraClass != null && extraClass.length > 0) {
- for (Class<?> clz : extraClass) {
- classes.add(clz);
- }
- }
-
- // try and read any jaxb.index files that are with the other classes.
- // This should
- // allow loading of extra classes (such as subclasses for inheritance
- // reasons)
- // that are in the same package. Also check for ObjectFactory classes
- Map<String, InputStream> packages = new HashMap<>();
- Map<String, ClassLoader> packageLoaders = new HashMap<>();
- Set<Class<?>> objectFactories = new HashSet<>();
- for (Class<?> jcls : classes) {
- String pkgName = PackageUtils.getPackageName(jcls);
- if (!packages.containsKey(pkgName)) {
- Package pkg = jcls.getPackage();
-
- packages.put(pkgName, jcls.getResourceAsStream("jaxb.index"));
- packageLoaders.put(pkgName, getClassLoader(jcls));
- String objectFactoryClassName = pkgName + "." + "ObjectFactory";
- Class<?> ofactory = null;
- CachedClass cachedFactory = null;
- if (pkg != null && objectFactoryCache != null) {
- synchronized (objectFactoryCache) {
- cachedFactory = objectFactoryCache.get(pkg);
- }
- }
- if (cachedFactory != null) {
- ofactory = cachedFactory.getCachedClass();
- }
- if (ofactory == null) {
- try {
- ofactory = Class.forName(objectFactoryClassName, false, getClassLoader(jcls));
- objectFactories.add(ofactory);
- addToObjectFactoryCache(pkg, ofactory, objectFactoryCache);
- } catch (ClassNotFoundException e) {
- addToObjectFactoryCache(pkg, null, objectFactoryCache);
- }
- } else {
- objectFactories.add(ofactory);
- }
- }
- }
- for (Map.Entry<String, InputStream> entry : packages.entrySet()) {
- if (entry.getValue() != null) {
- try (BufferedReader reader = new BufferedReader(
- new InputStreamReader(entry.getValue(), StandardCharsets.UTF_8))) {
- String pkg = entry.getKey();
- ClassLoader loader = packageLoaders.get(pkg);
- if (!StringUtils.isEmpty(pkg)) {
- pkg += ".";
- }
-
- String line = reader.readLine();
- while (line != null) {
- line = line.trim();
- if (line.indexOf('#') != -1) {
- line = line.substring(0, line.indexOf('#'));
- }
- if (!StringUtils.isEmpty(line)) {
- try {
- Class<?> ncls = Class.forName(pkg + line, false, loader);
- classes.add(ncls);
- } catch (Exception e) {
- // ignore
- }
- }
- line = reader.readLine();
- }
- } catch (IOException e) {
- // ignore
- } finally {
- try {
- entry.getValue().close();
- } catch (IOException e) {
- // ignore
- }
- }
- }
- }
- classes.addAll(objectFactories);
- }
-
- private static ClassLoader getClassLoader(final Class<?> clazz) {
- final SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
- @Override
- public ClassLoader run() {
- return clazz.getClassLoader();
- }
- });
- }
- return clazz.getClassLoader();
- }
-
- private static void addToObjectFactoryCache(Package objectFactoryPkg,
- Class<?> ofactory,
- Map<Package, CachedClass> objectFactoryCache) {
- if (objectFactoryPkg == null || objectFactoryCache == null) {
- return;
- }
- synchronized (objectFactoryCache) {
- objectFactoryCache.put(objectFactoryPkg,
- new CachedClass(ofactory));
- }
- }
-
- public static class DefaultClassNameAllocator {
- private final Set<String> typesClassNames;
-
- public DefaultClassNameAllocator() {
- this(new HashSet<>());
- }
-
- public DefaultClassNameAllocator(Set<String> set) {
- typesClassNames = set;
- }
-
- public String assignClassName(String packageName, String className) {
- String fullClassName = className;
- String fullPckClass = packageName + "." + fullClassName;
- int cnt = 0;
- while (typesClassNames.contains(fullPckClass)) {
- cnt++;
- fullClassName = className + cnt;
- fullPckClass = packageName + "." + fullClassName;
- }
- typesClassNames.add(fullPckClass);
- return fullClassName;
- }
-
- }
-
- public interface SchemaCompiler {
- void setEntityResolver(EntityResolver entityResolver);
-
- void setErrorListener(Object elForRun);
-
- void setClassNameAllocator(Object allocator);
-
- @WrapReturn(S2JJAXBModel.class)
- S2JJAXBModel bind();
-
- void parseSchema(InputSource source);
-
- void parseSchema(String key, Element el);
- void parseSchema(String key, XMLStreamReader el);
-
- @WrapReturn(Options.class)
- Options getOptions();
- }
- public interface S2JJAXBModel {
-
- @WrapReturn(JCodeModel.class)
- JCodeModel generateCode(Object object, Object elForRun);
-
- @WrapReturn(Mapping.class)
- Mapping get(QName qn);
-
- @WrapReturn(TypeAndAnnotation.class)
- TypeAndAnnotation getJavaType(QName typeQName);
- }
- public interface Mapping {
- @WrapReturn(TypeAndAnnotation.class)
- TypeAndAnnotation getType();
- }
- public interface TypeAndAnnotation {
- @WrapReturn(JType.class)
- JType getTypeClass();
- }
- public interface JType {
- boolean isArray();
-
- @WrapReturn(JType.class)
- JType elementType();
-
- boolean isPrimitive();
-
- String binaryName();
-
- String fullName();
-
- String name();
-
- @WrapReturn(value = JType.class, iterator = true)
- Iterator<JType> classes();
- }
- public interface Options {
-
- void addGrammar(InputSource is);
-
- void addBindFile(InputSource is);
-
- void parseArguments(String[] args);
-
- String getBuildID();
- }
- public interface JCodeModel {
-
- void build(Object writer) throws IOException;
-
- @WrapReturn(value = JPackage.class, iterator = true)
- Iterator<JPackage> packages();
- }
- public interface JPackage {
-
- String name();
-
- @WrapReturn(value = JDefinedClass.class, iterator = true)
- Iterator<JDefinedClass> classes();
- }
- public interface JDefinedClass {
- String name();
-
- String fullName();
- }
-
- public static boolean isJAXB22() {
- Target t = XmlElement.class.getAnnotation(Target.class);
- //JAXB 2.2 allows XmlElement on params.
- for (ElementType et : t.value()) {
- if (et == ElementType.PARAMETER) {
- return true;
- }
- }
- return false;
- }
-
- public static JAXBContextProxy createJAXBContextProxy(final JAXBContext ctx) {
- return createJAXBContextProxy(ctx, null, null);
- }
- public static JAXBContextProxy createJAXBContextProxy(final JAXBContext ctx,
- final SchemaCollection collection,
- final String defaultNs) {
- if (ctx.getClass().getName().contains("com.sun.")
- || collection == null) {
- return ReflectionInvokationHandler.createProxyWrapper(ctx, JAXBContextProxy.class);
- }
- return new SchemaCollectionContextProxy(ctx, collection, defaultNs);
- }
- public static JAXBBeanInfo getBeanInfo(JAXBContextProxy context, Class<?> cls) {
- Object o = context.getBeanInfo(cls);
- if (o == null) {
- return null;
- }
- if (o instanceof JAXBBeanInfo) {
- return (JAXBBeanInfo)o;
- }
- return ReflectionInvokationHandler.createProxyWrapper(o, JAXBBeanInfo.class);
- }
-
- private static String getPostfix(Class<?> cls) {
- String className = cls.getName();
- if (className.contains("com.sun.xml.internal")
- || className.contains("eclipse")) {
- //eclipse moxy accepts sun package CharacterEscapeHandler
- return ".internal";
- } else if (className.contains("com.sun.xml.bind")
- || className.startsWith("com.ibm.xml")) {
- return "";
- }
- return null;
- }
-
- public static void setMinimumEscapeHandler(Marshaller marshaller) {
- if (jaxbMinimumEscapeHandler == null) {
- jaxbMinimumEscapeHandler = Optional.ofNullable(createMininumEscapeHandler(marshaller.getClass()));
- }
- jaxbMinimumEscapeHandler.ifPresent(p -> setEscapeHandler(marshaller, p));
- }
-
- public static void setNoEscapeHandler(final Marshaller marshaller) {
- if (jaxbNoEscapeHandler == null) {
- jaxbNoEscapeHandler = Optional.ofNullable(createNoEscapeHandler(marshaller.getClass()));
- }
- jaxbNoEscapeHandler.ifPresent(p -> setEscapeHandler(marshaller, p));
- }
-
- public static void setEscapeHandler(Marshaller marshaller, Object escapeHandler) {
- try {
- String postFix = getPostfix(marshaller.getClass());
- if (postFix != null && escapeHandler != null) {
- marshaller.setProperty("com.sun.xml" + postFix + ".bind.characterEscapeHandler", escapeHandler);
- }
- } catch (PropertyException e) {
- LOG.log(Level.INFO, "Failed to set MinumEscapeHandler to jaxb marshaller", e);
- }
- }
-
- public static Object createMininumEscapeHandler(Class<?> cls) {
- return createEscapeHandler(cls, "MinimumEscapeHandler");
- }
-
- public static Object createNoEscapeHandler(Class<?> cls) {
- return createEscapeHandler(cls, "NoEscapeHandler");
- }
-
- private static Object createEscapeHandler(Class<?> cls, String simpleClassName) {
- try {
- String postFix = getPostfix(cls);
- if (postFix == null) {
- LOG.log(Level.WARNING, "Failed to create" + simpleClassName + " for unknown jaxb class:"
- + cls);
- return null;
- }
- Class<?> handlerClass = ClassLoaderUtils.loadClass("com.sun.xml" + postFix
- + ".bind.marshaller." + simpleClassName,
- cls);
- Class<?> handlerInterface = ClassLoaderUtils
- .loadClass("com.sun.xml" + postFix + ".bind.marshaller.CharacterEscapeHandler",
- cls);
- Object targetHandler = ReflectionUtil.getDeclaredField(handlerClass, "theInstance").get(null);
- return ProxyHelper.getProxy(cls.getClassLoader(),
- new Class[] {handlerInterface},
- new EscapeHandlerInvocationHandler(targetHandler));
- } catch (Exception e) {
- if ("NoEscapeHandler".equals(simpleClassName)) {
- //this class doesn't exist in JAXB 2.2 so expected
- LOG.log(Level.FINER, "Failed to create " + simpleClassName);
- } else {
- LOG.log(Level.INFO, "Failed to create " + simpleClassName);
- }
- }
- return null;
- }
-
-
-}
diff --git a/transform/src/patch/java/org/apache/cxf/common/logging/AbstractDelegatingLogger.java b/transform/src/patch/java/org/apache/cxf/common/logging/AbstractDelegatingLogger.java
deleted file mode 100644
index dd3cbd5..0000000
--- a/transform/src/patch/java/org/apache/cxf/common/logging/AbstractDelegatingLogger.java
+++ /dev/null
@@ -1,457 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cxf.common.logging;
-
-import java.util.Locale;
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-import java.util.logging.Filter;
-import java.util.logging.Handler;
-import java.util.logging.Level;
-import java.util.logging.LogRecord;
-import java.util.logging.Logger;
-
-/**
- * java.util.logging.Logger implementation delegating to another framework.
- * All methods can be used except:
- * setLevel
- * addHandler / getHandlers
- * setParent / getParent
- * setUseParentHandlers / getUseParentHandlers
- */
-public abstract class AbstractDelegatingLogger extends Logger {
-
- protected AbstractDelegatingLogger(String name, String resourceBundleName) {
- super(name, resourceBundleName);
- }
-
- @Override
- public void log(LogRecord record) {
- if (isLoggable(record.getLevel())) {
- doLog(record);
- }
- }
-
- @Override
- public void log(Level level, String msg) {
- if (isLoggable(level)) {
- LogRecord lr = new LogRecord(level, msg);
- doLog(lr);
- }
- }
-
- @Override
- public void log(Level level, String msg, Object param1) {
- if (isLoggable(level)) {
- LogRecord lr = new LogRecord(level, msg);
- Object[] params = {param1 };
- lr.setParameters(params);
- doLog(lr);
- }
- }
-
- @Override
- public void log(Level level, String msg, Object[] params) {
- if (isLoggable(level)) {
- LogRecord lr = new LogRecord(level, msg);
- lr.setParameters(params);
- doLog(lr);
- }
- }
-
- @Override
- public void log(Level level, String msg, Throwable thrown) {
- if (isLoggable(level)) {
- LogRecord lr = new LogRecord(level, msg);
- lr.setThrown(thrown);
- doLog(lr);
- }
- }
-
- @Override
- public void logp(Level level, String sourceClass, String sourceMethod, String msg) {
- if (isLoggable(level)) {
- LogRecord lr = new LogRecord(level, msg);
- lr.setSourceClassName(sourceClass);
- lr.setSourceMethodName(sourceMethod);
- doLog(lr);
- }
- }
-
- @Override
- public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object param1) {
- if (isLoggable(level)) {
- LogRecord lr = new LogRecord(level, msg);
- lr.setSourceClassName(sourceClass);
- lr.setSourceMethodName(sourceMethod);
- Object[] params = {param1 };
- lr.setParameters(params);
- doLog(lr);
- }
- }
-
- @Override
- public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object[] params) {
- if (isLoggable(level)) {
- LogRecord lr = new LogRecord(level, msg);
- lr.setSourceClassName(sourceClass);
- lr.setSourceMethodName(sourceMethod);
- lr.setParameters(params);
- doLog(lr);
- }
- }
-
- @Override
- public void logp(Level level, String sourceClass, String sourceMethod, String msg, Throwable thrown) {
- if (isLoggable(level)) {
- LogRecord lr = new LogRecord(level, msg);
- lr.setSourceClassName(sourceClass);
- lr.setSourceMethodName(sourceMethod);
- lr.setThrown(thrown);
- doLog(lr);
- }
- }
-
-
- @Override
- @Deprecated
- public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg) {
- if (isLoggable(level)) {
- LogRecord lr = new LogRecord(level, msg);
- lr.setSourceClassName(sourceClass);
- lr.setSourceMethodName(sourceMethod);
- doLog(lr, bundleName);
- }
- }
-
-
- @Override
- @Deprecated
- public void logrb(Level level, String sourceClass, String sourceMethod,
- String bundleName, String msg, Object param1) {
- if (isLoggable(level)) {
- LogRecord lr = new LogRecord(level, msg);
- lr.setSourceClassName(sourceClass);
- lr.setSourceMethodName(sourceMethod);
- Object[] params = {param1 };
- lr.setParameters(params);
- doLog(lr, bundleName);
- }
- }
-
-
- @Override
- @Deprecated
- public void logrb(Level level, String sourceClass, String sourceMethod,
- String bundleName, String msg, Object[] params) {
- if (isLoggable(level)) {
- LogRecord lr = new LogRecord(level, msg);
- lr.setSourceClassName(sourceClass);
- lr.setSourceMethodName(sourceMethod);
- lr.setParameters(params);
- doLog(lr, bundleName);
- }
- }
-
- @Override
- @Deprecated
- public void logrb(Level level, String sourceClass, String sourceMethod,
- String bundleName, String msg, Throwable thrown) {
- if (isLoggable(level)) {
- LogRecord lr = new LogRecord(level, msg);
- lr.setSourceClassName(sourceClass);
- lr.setSourceMethodName(sourceMethod);
- lr.setThrown(thrown);
- doLog(lr, bundleName);
- }
- }
-
- @Override
- public void entering(String sourceClass, String sourceMethod) {
- if (isLoggable(Level.FINER)) {
- logp(Level.FINER, sourceClass, sourceMethod, "ENTRY");
- }
- }
-
- @Override
- public void entering(String sourceClass, String sourceMethod, Object param1) {
- if (isLoggable(Level.FINER)) {
- Object[] params = {param1 };
- logp(Level.FINER, sourceClass, sourceMethod, "ENTRY {0}", params);
- }
- }
-
- @Override
- public void entering(String sourceClass, String sourceMethod, Object[] params) {
- if (isLoggable(Level.FINER)) {
- String msg = "ENTRY";
- if (params == null) {
- logp(Level.FINER, sourceClass, sourceMethod, msg);
- return;
- }
- StringBuilder builder = new StringBuilder(msg);
- for (int i = 0; i < params.length; i++) {
- builder.append(" {");
- builder.append(Integer.toString(i));
- builder.append('}');
- }
- logp(Level.FINER, sourceClass, sourceMethod, builder.toString(), params);
- }
- }
-
- @Override
- public void exiting(String sourceClass, String sourceMethod) {
- if (isLoggable(Level.FINER)) {
- logp(Level.FINER, sourceClass, sourceMethod, "RETURN");
- }
- }
-
- @Override
- public void exiting(String sourceClass, String sourceMethod, Object result) {
- if (isLoggable(Level.FINER)) {
- Object[] params = {result };
- logp(Level.FINER, sourceClass, sourceMethod, "RETURN {0}", params);
- }
- }
-
- @Override
- public void throwing(String sourceClass, String sourceMethod, Throwable thrown) {
- if (isLoggable(Level.FINER)) {
- LogRecord lr = new LogRecord(Level.FINER, "THROW");
- lr.setSourceClassName(sourceClass);
- lr.setSourceMethodName(sourceMethod);
- lr.setThrown(thrown);
- doLog(lr);
- }
- }
-
- @Override
- public void severe(String msg) {
- if (isLoggable(Level.SEVERE)) {
- LogRecord lr = new LogRecord(Level.SEVERE, msg);
- doLog(lr);
- }
- }
-
- @Override
- public void warning(String msg) {
- if (isLoggable(Level.WARNING)) {
- LogRecord lr = new LogRecord(Level.WARNING, msg);
- doLog(lr);
- }
- }
-
- @Override
- public void info(String msg) {
- if (isLoggable(Level.INFO)) {
- LogRecord lr = new LogRecord(Level.INFO, msg);
- doLog(lr);
- }
- }
-
- @Override
- public void config(String msg) {
- if (isLoggable(Level.CONFIG)) {
- LogRecord lr = new LogRecord(Level.CONFIG, msg);
- doLog(lr);
- }
- }
-
- @Override
- public void fine(String msg) {
- if (isLoggable(Level.FINE)) {
- LogRecord lr = new LogRecord(Level.FINE, msg);
- doLog(lr);
- }
- }
-
- @Override
- public void finer(String msg) {
- if (isLoggable(Level.FINER)) {
- LogRecord lr = new LogRecord(Level.FINER, msg);
- doLog(lr);
- }
- }
-
- @Override
- public void finest(String msg) {
- if (isLoggable(Level.FINEST)) {
- LogRecord lr = new LogRecord(Level.FINEST, msg);
- doLog(lr);
- }
- }
-
- @Override
- public void setLevel(Level newLevel) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public abstract Level getLevel();
-
- @Override
- public boolean isLoggable(Level level) {
- Level l = getLevel();
- return level.intValue() >= l.intValue() && l != Level.OFF;
- }
-
- protected boolean supportsHandlers() {
- return false;
- }
-
- @Override
- public synchronized void addHandler(Handler handler) {
- if (supportsHandlers()) {
- super.addHandler(handler);
- return;
- }
- throw new UnsupportedOperationException();
- }
-
- @Override
- public synchronized void removeHandler(Handler handler) {
- if (supportsHandlers()) {
- super.removeHandler(handler);
- return;
- }
- throw new UnsupportedOperationException();
- }
-
- @Override
- public synchronized Handler[] getHandlers() {
- if (supportsHandlers()) {
- return super.getHandlers();
- }
- throw new UnsupportedOperationException();
- }
-
- @Override
- public synchronized void setUseParentHandlers(boolean useParentHandlers) {
- if (supportsHandlers()) {
- super.setUseParentHandlers(useParentHandlers);
- return;
- }
- throw new UnsupportedOperationException();
- }
-
- @Override
- public synchronized boolean getUseParentHandlers() {
- if (supportsHandlers()) {
- return super.getUseParentHandlers();
- }
- throw new UnsupportedOperationException();
- }
-
- @Override
- public Logger getParent() {
- return null;
- }
-
- @Override
- public void setParent(Logger parent) {
- throw new UnsupportedOperationException();
- }
-
- protected void doLog(LogRecord lr) {
- lr.setLoggerName(getName());
- String rbname = getResourceBundleName();
- if (rbname != null) {
- lr.setResourceBundleName(rbname);
- lr.setResourceBundle(getResourceBundle());
- }
- internalLog(lr);
- }
-
- protected void doLog(LogRecord lr, String rbname) {
- lr.setLoggerName(getName());
- if (rbname != null) {
- lr.setResourceBundleName(rbname);
- lr.setResourceBundle(loadResourceBundle(rbname));
- }
- internalLog(lr);
- }
-
- protected void internalLog(LogRecord record) {
- Filter filter = getFilter();
- if (filter != null && !filter.isLoggable(record)) {
- return;
- }
- String msg = formatMessage(record);
- internalLogFormatted(msg, record);
- }
-
- protected abstract void internalLogFormatted(String msg, LogRecord record);
-
- protected String formatMessage(LogRecord record) {
- String format = record.getMessage();
- ResourceBundle catalog = record.getResourceBundle();
- if (catalog != null) {
- try {
- format = catalog.getString(record.getMessage());
- } catch (MissingResourceException ex) {
- format = record.getMessage();
- }
- }
- try {
- Object[] parameters = record.getParameters();
- if (parameters == null || parameters.length == 0) {
- return format;
- }
- if (format.indexOf("{0") >= 0 || format.indexOf("{1") >= 0
- || format.indexOf("{2") >= 0 || format.indexOf("{3") >= 0) {
- return java.text.MessageFormat.format(format, parameters);
- }
- return format;
- } catch (Exception ex) {
- return format;
- }
- }
-
- /**
- * Load the specified resource bundle
- *
- * @param resourceBundleName
- * the name of the resource bundle to load, cannot be null
- * @return the loaded resource bundle.
- * @throws java.util.MissingResourceException
- * If the specified resource bundle can not be loaded.
- */
- static ResourceBundle loadResourceBundle(String resourceBundleName) {
- // try context class loader to load the resource
- ClassLoader cl = Thread.currentThread().getContextClassLoader();
- if (null != cl) {
- try {
- return ResourceBundle.getBundle(resourceBundleName, Locale.getDefault(), cl);
- } catch (MissingResourceException e) {
- // Failed to load using context classloader, ignore
- }
- }
- // try system class loader to load the resource
- cl = ClassLoader.getSystemClassLoader();
- if (null != cl) {
- try {
- return ResourceBundle.getBundle(resourceBundleName, Locale.getDefault(), cl);
- } catch (MissingResourceException e) {
- // Failed to load using system classloader, ignore
- }
- }
- return null;
- }
-
-}
\ No newline at end of file
diff --git a/transform/src/patch/java/org/apache/cxf/common/logging/LogUtils.java b/transform/src/patch/java/org/apache/cxf/common/logging/LogUtils.java
deleted file mode 100644
index 09727e6..0000000
--- a/transform/src/patch/java/org/apache/cxf/common/logging/LogUtils.java
+++ /dev/null
@@ -1,485 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.common.logging;
-
-import java.io.BufferedReader;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.text.MessageFormat;
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-import java.util.logging.Level;
-import java.util.logging.LogRecord;
-import java.util.logging.Logger;
-
-import org.apache.cxf.common.i18n.BundleUtils;
-import org.apache.cxf.common.util.StringUtils;
-
-
-/**
- * A container for static utility methods related to logging.
- * By default, CXF logs to java.util.logging. An application can change this. To log to another system, the
- * application must provide an object that extends {@link AbstractDelegatingLogger}, and advertise that class
- * via one of the following mechanisms:
- * <ul>
- * <li>Create a file, in the classpath, named META-INF/cxf/org.apache.cxf.Logger.
- * This file should contain the fully-qualified name
- * of the class, with no comments, on a single line.</li>
- * <li>Call {@link #setLoggerClass(Class)} with a Class<?> reference to the logger class.</li>
- * </ul>
- * CXF provides {@link Slf4jLogger} to use slf4j instead of java.util.logging.
- */
-public final class LogUtils {
- private static final String KEY = "org.apache.cxf.Logger";
-
- private static final Object[] NO_PARAMETERS = new Object[0];
-
-
- private static Class<?> loggerClass;
-
- /**
- * Prevents instantiation.
- */
- private LogUtils() {
- }
-
- static {
- JDKBugHacks.doHacks();
-
- try {
-
- String cname = null;
- try {
- cname = AccessController.doPrivileged(new PrivilegedAction<String>() {
- public String run() {
- return System.getProperty(KEY);
- }
- });
- } catch (Throwable t) {
- //ignore - likely security exception or similar that won't allow
- //access to the system properties. We'll continue with other methods
- }
- if (StringUtils.isEmpty(cname)) {
- InputStream ins = Thread.currentThread().getContextClassLoader()
- .getResourceAsStream("META-INF/cxf/" + KEY);
- if (ins == null) {
- ins = ClassLoader.getSystemResourceAsStream("META-INF/cxf/" + KEY);
- }
- if (ins != null) {
- try (BufferedReader din = new BufferedReader(new InputStreamReader(ins))) {
- cname = din.readLine();
- }
- }
- }
- if (StringUtils.isEmpty(cname)) {
- try {
- // This Class.forName likely will barf in OSGi, but it's OK
- // as we'll just use j.u.l and pax-logging will pick it up fine
- // If we don't call this and there isn't a slf4j impl avail,
- // you get warnings printed to stderr about NOPLoggers and such
- Class.forName("org.slf4j.impl.StaticLoggerBinder");
- Class<?> cls = Class.forName("org.slf4j.LoggerFactory");
- Class<?> fcls = cls.getMethod("getILoggerFactory").invoke(null).getClass();
- String clsName = fcls.getName();
- if (clsName.contains("NOPLogger")) {
- //no real slf4j implementation, use j.u.l
- cname = null;
- } else if (clsName.contains("JDK14")
- || clsName.contains("pax.logging")) {
- //both of these we can use the appropriate j.u.l API's
- //directly and have it work properly
- cname = null;
- } else {
- // Either we cannot really detect where it's logging
- // or we don't want to use a custom logger, so we'll
- // go ahead and use the Slf4jLogger directly
- cname = "org.apache.cxf.common.logging.Slf4jLogger";
- }
- } catch (Throwable t) {
- //ignore - Slf4j not available
- }
- }
- if (!StringUtils.isEmpty(cname)) {
- try {
- loggerClass = Class.forName(cname.trim(), true,
- Thread.currentThread().getContextClassLoader());
- } catch (Throwable ex) {
- loggerClass = Class.forName(cname.trim());
- }
- getLogger(LogUtils.class).fine("Using " + loggerClass.getName() + " for logging.");
- }
- } catch (Throwable ex) {
- //ignore - if we get here, some issue prevented the logger class from being loaded.
- //maybe a ClassNotFound or NoClassDefFound or similar. Just use j.u.l
- loggerClass = null;
- }
- }
-
-
- /**
- * Specify a logger class that inherits from {@link AbstractDelegatingLogger}.
- * Enable users to use their own logger implementation.
- */
- public static void setLoggerClass(Class<? extends AbstractDelegatingLogger> cls) {
- loggerClass = cls;
- }
-
-
- /**
- * Get a Logger with the associated default resource bundle for the class.
- *
- * @param cls the Class to contain the Logger
- * @return an appropriate Logger
- */
- public static Logger getLogger(Class<?> cls) {
- return createLogger(cls, null, cls.getName());
- }
-
- /**
- * Get a Logger with an associated resource bundle.
- *
- * @param cls the Class to contain the Logger
- * @param resourcename the resource name
- * @return an appropriate Logger
- */
- public static Logger getLogger(Class<?> cls, String resourcename) {
- return createLogger(cls, resourcename, cls.getName());
- }
-
- /**
- * Get a Logger with an associated resource bundle.
- *
- * @param cls the Class to contain the Logger (to find resources)
- * @param resourcename the resource name
- * @param loggerName the full name for the logger
- * @return an appropriate Logger
- */
- public static Logger getLogger(Class<?> cls,
- String resourcename,
- String loggerName) {
- return createLogger(cls, resourcename, loggerName);
- }
-
- /**
- * Get a Logger with the associated default resource bundle for the class.
- *
- * @param cls the Class to contain the Logger
- * @return an appropriate Logger
- */
- public static Logger getL7dLogger(Class<?> cls) {
- return createLogger(cls, null, cls.getName());
- }
-
- /**
- * Get a Logger with an associated resource bundle.
- *
- * @param cls the Class to contain the Logger
- * @param resourcename the resource name
- * @return an appropriate Logger
- */
- public static Logger getL7dLogger(Class<?> cls, String resourcename) {
- return createLogger(cls, resourcename, cls.getName());
- }
-
- /**
- * Get a Logger with an associated resource bundle.
- *
- * @param cls the Class to contain the Logger (to find resources)
- * @param resourcename the resource name
- * @param loggerName the full name for the logger
- * @return an appropriate Logger
- */
- public static Logger getL7dLogger(Class<?> cls,
- String resourcename,
- String loggerName) {
- return createLogger(cls, resourcename, loggerName);
- }
-
- /**
- * Create a logger
- */
- protected static Logger createLogger(Class<?> cls,
- String name,
- String loggerName) {
- ClassLoader orig = getContextClassLoader();
- ClassLoader n = getClassLoader(cls);
- if (n != null) {
- setContextClassLoader(n);
- }
- String bundleName = name;
- try {
- ResourceBundle b = null;
- if (bundleName == null) {
- //grab the bundle prior to the call to Logger.getLogger(...) so the
- //ResourceBundle can be loaded outside the big sync block that getLogger really is
- bundleName = BundleUtils.getBundleName(cls);
- try {
- b = BundleUtils.getBundle(cls);
- } catch (MissingResourceException rex) {
- //ignore
- }
- } else {
- bundleName = BundleUtils.getBundleName(cls, bundleName);
- try {
- b = BundleUtils.getBundle(cls, bundleName);
- } catch (MissingResourceException rex) {
- //ignore
- }
- }
- if (b != null) {
- b.getLocale();
- }
-
- if (loggerClass != null) {
- try {
- Constructor<?> cns = loggerClass.getConstructor(String.class, String.class);
- if (name == null) {
- try {
- return (Logger) cns.newInstance(loggerName, bundleName);
- } catch (InvocationTargetException ite) {
- if (ite.getTargetException() instanceof MissingResourceException) {
- return (Logger) cns.newInstance(loggerName, null);
- }
- throw ite;
- }
- }
- try {
- return (Logger) cns.newInstance(loggerName, bundleName);
- } catch (InvocationTargetException ite) {
- if (ite.getTargetException() instanceof MissingResourceException) {
- throw (MissingResourceException)ite.getTargetException();
- }
- throw ite;
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- Logger logger;
- try {
- logger = Logger.getLogger(loggerName, bundleName); //NOPMD
- } catch (IllegalArgumentException | MissingResourceException ex) {
- //likely a mismatch on the bundle name, just return the default
- logger = Logger.getLogger(loggerName); //NOPMD
- }
-
- return logger;
- } finally {
- if (n != orig) {
- setContextClassLoader(orig);
- }
- }
- }
-
- private static void setContextClassLoader(final ClassLoader classLoader) {
- final SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- AccessController.doPrivileged(new PrivilegedAction<Object>() {
- public Object run() {
- Thread.currentThread().setContextClassLoader(classLoader);
- return null;
- }
- });
- } else {
- Thread.currentThread().setContextClassLoader(classLoader);
- }
- }
-
- private static ClassLoader getContextClassLoader() {
- final SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
- public ClassLoader run() {
- return Thread.currentThread().getContextClassLoader();
- }
- });
- }
- return Thread.currentThread().getContextClassLoader();
- }
-
- private static ClassLoader getClassLoader(final Class<?> clazz) {
- final SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
- public ClassLoader run() {
- return clazz.getClassLoader();
- }
- });
- }
- return clazz.getClassLoader();
- }
-
- /**
- * Allows both parameter substitution and a typed Throwable to be logged.
- *
- * @param logger the Logger the log to
- * @param level the severity level
- * @param message the log message
- * @param throwable the Throwable to log
- * @param parameter the parameter to substitute into message
- */
- public static void log(Logger logger,
- Level level,
- String message,
- Throwable throwable,
- Object parameter) {
- if (logger.isLoggable(level)) {
- final String formattedMessage =
- MessageFormat.format(localize(logger, message), parameter);
- doLog(logger, level, formattedMessage, throwable);
- }
- }
-
- /**
- * Allows both parameter substitution and a typed Throwable to be logged.
- *
- * @param logger the Logger the log to
- * @param level the severity level
- * @param message the log message
- * @param throwable the Throwable to log
- * @param parameters the parameters to substitute into message
- */
- public static void log(Logger logger,
- Level level,
- String message,
- Throwable throwable,
- Object... parameters) {
- if (logger.isLoggable(level)) {
- final String formattedMessage =
- MessageFormat.format(localize(logger, message), parameters);
- doLog(logger, level, formattedMessage, throwable);
- }
- }
-
- /**
- * Checks log level and logs
- *
- * @param logger the Logger the log to
- * @param level the severity level
- * @param message the log message
- */
- public static void log(Logger logger,
- Level level,
- String message) {
- log(logger, level, message, NO_PARAMETERS);
- }
-
- /**
- * Checks log level and logs
- *
- * @param logger the Logger the log to
- * @param level the severity level
- * @param message the log message
- * @param throwable the Throwable to log
- */
- public static void log(Logger logger,
- Level level,
- String message,
- Throwable throwable) {
- log(logger, level, message, throwable, NO_PARAMETERS);
- }
-
- /**
- * Checks log level and logs
- *
- * @param logger the Logger the log to
- * @param level the severity level
- * @param message the log message
- * @param parameter the parameter to substitute into message
- */
- public static void log(Logger logger,
- Level level,
- String message,
- Object parameter) {
- log(logger, level, message, new Object[] {parameter});
- }
-
- /**
- * Checks log level and logs
- *
- * @param logger the Logger the log to
- * @param level the severity level
- * @param message the log message
- * @param parameters the parameters to substitute into message
- */
- public static void log(Logger logger,
- Level level,
- String message,
- Object[] parameters) {
- if (logger.isLoggable(level)) {
- String msg = localize(logger, message);
- try {
- msg = MessageFormat.format(msg, parameters);
- } catch (IllegalArgumentException ex) {
- //ignore, log as is
- }
- doLog(logger, level, msg, null);
- }
- }
-
- private static void doLog(Logger log, Level level, String msg, Throwable t) {
- LogRecord record = new LogRecord(level, msg);
-
- record.setLoggerName(log.getName());
- record.setResourceBundleName(log.getResourceBundleName());
- record.setResourceBundle(log.getResourceBundle());
-
- if (t != null) {
- record.setThrown(t);
- }
-
- //try to get the right class name/method name - just trace
- //back the stack till we get out of this class
- StackTraceElement[] stack = (new Throwable()).getStackTrace();
- String cname = LogUtils.class.getName();
- for (int x = 0; x < stack.length; x++) {
- StackTraceElement frame = stack[x];
- if (!frame.getClassName().equals(cname)) {
- record.setSourceClassName(frame.getClassName());
- record.setSourceMethodName(frame.getMethodName());
- break;
- }
- }
- log.log(record);
- }
-
- /**
- * Retrieve localized message retrieved from a logger's resource
- * bundle.
- *
- * @param logger the Logger
- * @param message the message to be localized
- */
- private static String localize(Logger logger, String message) {
- ResourceBundle bundle = logger.getResourceBundle();
- try {
- return bundle != null ? bundle.getString(message) : message;
- } catch (MissingResourceException ex) {
- //string not in the bundle
- return message;
- }
- }
-
-}
diff --git a/transform/src/patch/java/org/apache/cxf/common/logging/RegexLoggingFilter.java b/transform/src/patch/java/org/apache/cxf/common/logging/RegexLoggingFilter.java
deleted file mode 100644
index 83178b9..0000000
--- a/transform/src/patch/java/org/apache/cxf/common/logging/RegexLoggingFilter.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cxf.common.logging;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public class RegexLoggingFilter {
-
- public static final String DEFAULT_REPLACEMENT = "*****";
-
- private static class ReplaceRegEx {
- private final Pattern pattern;
- private final int group;
- private final String replacement;
-
- ReplaceRegEx(String pattern, int group, String replacement) {
- this.pattern = Pattern.compile(pattern);
- this.group = group;
- this.replacement = replacement;
- }
-
- public CharSequence filter(CharSequence command) {
- Matcher m = pattern.matcher(command);
- int offset = 0;
- while (m.find()) {
- int origLen = command.length();
- command = new StringBuilder(command)
- .replace(m.start(group) + offset, m.end(group) + offset, replacement).toString();
- offset += command.length() - origLen;
- }
- return command;
- }
- }
-
- private String regPattern;
- private int regGroup = 1;
- private String regReplacement = DEFAULT_REPLACEMENT;
-
- private List<ReplaceRegEx> regexs = new ArrayList<>();
-
- public CharSequence filter(CharSequence command) {
- if (regPattern != null) {
- command = new ReplaceRegEx(regPattern, regGroup, regReplacement).filter(command);
- }
- for (ReplaceRegEx regex : regexs) {
- command = regex.filter(command);
- }
- return command;
- }
-
- public void addRegEx(String pattern) {
- addRegEx(pattern, 1);
- }
-
- public void addRegEx(String pattern, int group) {
- addRegEx(pattern, group, DEFAULT_REPLACEMENT);
- }
-
- public void addRegEx(String pattern, int group, String replacement) {
- regexs.add(new ReplaceRegEx(pattern, group, replacement));
- }
-
- public void addCommandOption(String option, String... commands) {
- StringBuilder pattern = new StringBuilder("(");
- for (String command : commands) {
- if (pattern.length() > 1) {
- pattern.append('|');
- }
- pattern.append(Pattern.quote(command));
- }
- pattern.append(") +.*?").append(Pattern.quote(option)).append(" +([^ ]+)");
- regexs.add(new ReplaceRegEx(pattern.toString(), 2, DEFAULT_REPLACEMENT));
- }
-
- public String getPattern() {
- return regPattern;
- }
-
- public void setPattern(String pattern) {
- this.regPattern = pattern;
- }
-
- public String getReplacement() {
- return regReplacement;
- }
-
- public void setReplacement(String replacement) {
- this.regReplacement = replacement;
- }
-
- public int getGroup() {
- return regGroup;
- }
-
- public void setGroup(int group) {
- this.regGroup = group;
- }
-}
diff --git a/transform/src/patch/java/org/apache/cxf/common/spi/ClassGeneratorClassLoader.java b/transform/src/patch/java/org/apache/cxf/common/spi/ClassGeneratorClassLoader.java
deleted file mode 100644
index 5906c7a..0000000
--- a/transform/src/patch/java/org/apache/cxf/common/spi/ClassGeneratorClassLoader.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.common.spi;
-
-import java.lang.ref.WeakReference;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.apache.cxf.Bus;
-import org.apache.cxf.BusFactory;
-import org.apache.cxf.common.util.StringUtils;
-import org.apache.cxf.common.util.WeakIdentityHashMap;
-
-/** Class loader used to store and retrieve class generated during runtime to avoid class generation each time.
- * inherited class use asmHelper to generate bytes and use @see #loadClass(String, Class<?>, byte[])
- * or @see #loadClass(String, ClassLoader, byte[]) to store generated class.Class can be generated during buildtime.
- * equivalent class is @see org.apache.cxf.common.spi.GeneratedClassClassLoader
- * @author olivier dufour
- */
-public class ClassGeneratorClassLoader {
- protected static final Map<Class<?>, WeakReference<TypeHelperClassLoader>> CLASS_MAP
- = new WeakIdentityHashMap<>();
- protected static final Map<ClassLoader, WeakReference<TypeHelperClassLoader>> LOADER_MAP
- = new WeakIdentityHashMap<>();
- protected final Bus bus;
-
- public ClassGeneratorClassLoader(final Bus bus) {
- this.bus = bus == null ? BusFactory.getDefaultBus() : bus;
- }
-
- protected Class<?> loadClass(String className, Class<?> cls, byte[] bytes) {
- GeneratedClassClassLoaderCapture capture = bus.getExtension(GeneratedClassClassLoaderCapture.class);
- if (capture != null) {
- capture.capture(className, bytes);
- }
- TypeHelperClassLoader loader = getOrCreateLoader(cls);
- synchronized (loader) {
- Class<?> clz = loader.lookupDefinedClass(className);
- if (clz == null) {
- return loader.defineClass(className, bytes);
- }
- return clz;
- }
- }
- protected Class<?> loadClass(String className, ClassLoader l, byte[] bytes) {
- GeneratedClassClassLoaderCapture capture = bus.getExtension(GeneratedClassClassLoaderCapture.class);
- if (capture != null) {
- capture.capture(className, bytes);
- }
- TypeHelperClassLoader loader = getOrCreateLoader(l);
- synchronized (loader) {
- Class<?> clz = loader.lookupDefinedClass(className);
- if (clz == null) {
- return loader.defineClass(className, bytes);
- }
- return clz;
- }
- }
- protected Class<?> findClass(String className, Class<?> cls) {
- return getOrCreateLoader(cls).lookupDefinedClass(className);
- }
-
- protected Class<?> findClass(String className, ClassLoader classLoader) {
- return getOrCreateLoader(classLoader).lookupDefinedClass(className);
- }
-
- private static synchronized TypeHelperClassLoader getOrCreateLoader(Class<?> cls) {
- WeakReference<TypeHelperClassLoader> ref = CLASS_MAP.get(cls);
- TypeHelperClassLoader ret;
- if (ref == null || ref.get() == null) {
- ret = new TypeHelperClassLoader(cls.getClassLoader());
- CLASS_MAP.put(cls, new WeakReference<>(ret));
- } else {
- ret = ref.get();
- }
- return ret;
- }
-
- private static synchronized TypeHelperClassLoader getOrCreateLoader(ClassLoader l) {
- WeakReference<TypeHelperClassLoader> ref = LOADER_MAP.get(l);
- TypeHelperClassLoader ret;
- if (ref == null || ref.get() == null) {
- ret = new TypeHelperClassLoader(l);
- LOADER_MAP.put(l, new WeakReference<>(ret));
- } else {
- ret = ref.get();
- }
- return ret;
- }
-
- public static class TypeHelperClassLoader extends ClassLoader {
- private final ConcurrentHashMap<String, Class<?>> defined = new ConcurrentHashMap<>();
-
- TypeHelperClassLoader(ClassLoader parent) {
- super(parent);
- }
-
- public Class<?> lookupDefinedClass(String name) {
- return defined.get(StringUtils.slashesToPeriod(name));
- }
-
- @Override
- protected Class<?> findClass(String name) throws ClassNotFoundException {
- if (name.endsWith("package-info")) {
- return getParent().loadClass(name);
- }
- return super.findClass(name);
- }
-
- public Class<?> defineClass(String name, byte[] bytes) {
- Class<?> ret = defined.get(StringUtils.slashesToPeriod(name));
- if (ret != null) {
- return ret;
- }
- if (name.endsWith("package-info")) {
- String s = name.substring(0, name.length() - 13);
- Package p = super.getPackage(s);
- if (p == null) {
- definePackage(StringUtils.slashesToPeriod(s),
- null,
- null,
- null,
- null,
- null,
- null,
- null);
- }
- }
-
- ret = defined.computeIfAbsent(StringUtils.slashesToPeriod(name),
- key -> TypeHelperClassLoader.super.defineClass(key, bytes, 0, bytes.length));
-
- return ret;
- }
- }
-}
diff --git a/transform/src/patch/java/org/apache/cxf/common/spi/NamespaceClassGenerator.java b/transform/src/patch/java/org/apache/cxf/common/spi/NamespaceClassGenerator.java
deleted file mode 100644
index 48c755b..0000000
--- a/transform/src/patch/java/org/apache/cxf/common/spi/NamespaceClassGenerator.java
+++ /dev/null
@@ -1,450 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.common.spi;
-
-import java.util.Map;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import org.apache.cxf.Bus;
-import org.apache.cxf.common.classloader.ClassLoaderUtils;
-import org.apache.cxf.common.logging.LogUtils;
-import org.apache.cxf.common.util.ASMHelper;
-import org.apache.cxf.common.util.OpcodesProxy;
-
-public class NamespaceClassGenerator extends ClassGeneratorClassLoader implements NamespaceClassCreator {
-
- private static final Logger LOG = LogUtils.getL7dLogger(ClassGeneratorClassLoader.class);
- private final ASMHelper helper;
-
- public NamespaceClassGenerator(Bus bus) {
- super(bus);
- helper = bus.getExtension(ASMHelper.class);
- }
-
- @Override
- public synchronized Class<?> createNamespaceWrapperClass(Class<?> mcls, Map<String, String> map) {
- String postFix = "";
-
- if (mcls.getName().contains("eclipse")) {
- return createEclipseNamespaceMapper();
- } else if (mcls.getName().contains(".internal")) {
- postFix = "Internal";
- } else if (mcls.getName().contains("com.sun")) {
- postFix = "RI";
- }
-
- String className = "org.apache.cxf.jaxb.NamespaceMapper";
- className += postFix;
- Class<?> cls = findClass(className, NamespaceClassCreator.class);
- Throwable t = null;
- if (cls == null) {
- try {
- byte[] bts = createNamespaceWrapperInternal(postFix);
- className = "org.apache.cxf.jaxb.NamespaceMapper" + postFix;
- return loadClass(className, NamespaceClassCreator.class, bts);
- } catch (RuntimeException ex) {
- // continue
- t = ex;
- }
- }
- if (cls == null
- && (!mcls.getName().contains(".internal.") && mcls.getName().contains("com.sun"))) {
- try {
- cls = ClassLoaderUtils.loadClass("org.apache.cxf.common.jaxb.NamespaceMapper",
- NamespaceClassCreator.class);
- } catch (Throwable ex2) {
- // ignore
- t = ex2;
- }
- }
- LOG.log(Level.INFO, "Could not create a NamespaceMapper compatible with Marshaller class " + mcls.getName(), t);
- return cls;
- }
-
- private Class<?> createEclipseNamespaceMapper() {
- String className = "org.apache.cxf.jaxb.EclipseNamespaceMapper";
- Class<?> cls = findClass(className, NamespaceClassCreator.class);
- if (cls != null) {
- return cls;
- }
- byte[] bts = doCreateEclipseNamespaceMapper();
- //previous code use mcls instead of NamespaceClassGenerator.class
- return loadClass(className, NamespaceClassCreator.class, bts);
- }
-
- /*
- // This is the "prototype" for the ASM generated class below
- public static class MapNamespacePrefixMapper2
- extends org.eclipse.persistence.internal.oxm.record.namespaces.MapNamespacePrefixMapper {
-
- String[] nsctxt;
-
- public MapNamespacePrefixMapper2(Map<String, String> foo) {
- super(foo);
- }
- public String[] getPreDeclaredNamespaceUris() {
- String[] sup = super.getPreDeclaredNamespaceUris();
- if (nsctxt == null) {
- return sup;
- }
- List<String> s = new ArrayList<>(Arrays.asList(sup));
- for (int x = 1; x < nsctxt.length; x = x + 2) {
- s.remove(nsctxt[x]);
- }
- return s.toArray(new String[s.size()]);
- }
- public void setContextualNamespaceDecls(String[] f) {
- nsctxt = f;
- }
- public String[] getContextualNamespaceDecls() {
- return nsctxt;
- }
- }
- */
- //CHECKSTYLE:OFF
- //bunch of really long ASM based methods that cannot be shortened easily
- private byte[] doCreateEclipseNamespaceMapper() {
- OpcodesProxy Opcodes = helper.getOpCodes();
- String slashedName = "org/apache/cxf/jaxb/EclipseNamespaceMapper";
- ASMHelper.ClassWriter cw = helper.createClassWriter();
- if (cw == null) {
- return null;
- }
- String superName = "org/eclipse/persistence/internal/oxm/record/namespaces/MapNamespacePrefixMapper";
- ASMHelper.FieldVisitor fv;
- ASMHelper.MethodVisitor mv;
- cw.visit(Opcodes.V1_6,
- Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER,
- slashedName, null,
- superName, null);
-
- cw.visitSource("EclipseNamespaceMapper.java", null);
-
- fv = cw.visitField(Opcodes.ACC_PRIVATE, "nsctxt", "[Ljava/lang/String;", null, null);
- fv.visitEnd();
-
-
- mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "(Ljava/util/Map;)V",
- "(Ljava/util/Map<Ljava/lang/String;Ljava/lang/String;>;)V", null);
- mv.visitCode();
- ASMHelper.Label l0 = helper.createLabel();
- mv.visitLabel(l0);
- mv.visitVarInsn(Opcodes.ALOAD, 0);
- mv.visitVarInsn(Opcodes.ALOAD, 1);
- mv.visitMethodInsn(Opcodes.INVOKESPECIAL,
- superName, "<init>", "(Ljava/util/Map;)V", false);
- ASMHelper.Label l1 = helper.createLabel();
- mv.visitLabel(l1);
- mv.visitInsn(Opcodes.RETURN);
- ASMHelper.Label l2 = helper.createLabel();
- mv.visitLabel(l2);
- mv.visitMaxs(0, 0);
- mv.visitEnd();
-
-
- mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "setContextualNamespaceDecls", "([Ljava/lang/String;)V",
- null, null);
- mv.visitCode();
- l0 = helper.createLabel();
- mv.visitLabel(l0);
- mv.visitLineNumber(47, l0);
- mv.visitVarInsn(Opcodes.ALOAD, 0);
- mv.visitVarInsn(Opcodes.ALOAD, 1);
- mv.visitFieldInsn(Opcodes.PUTFIELD, slashedName, "nsctxt", "[Ljava/lang/String;");
- l1 = helper.createLabel();
- mv.visitLabel(l1);
- mv.visitLineNumber(48, l1);
- mv.visitInsn(Opcodes.RETURN);
- l2 = helper.createLabel();
- mv.visitLabel(l2);
- mv.visitLocalVariable("this", "L" + slashedName + ";", null, l0, l2, 0);
- mv.visitLocalVariable("contextualNamespaceDecls", "[Ljava/lang/String;", null, l0, l2, 1);
- mv.visitMaxs(0, 0);
- mv.visitEnd();
-
- mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "getContextualNamespaceDecls", "()[Ljava/lang/String;", null, null);
- mv.visitCode();
- l0 = helper.createLabel();
- mv.visitLabel(l0);
- mv.visitLineNumber(51, l0);
- mv.visitVarInsn(Opcodes.ALOAD, 0);
- mv.visitFieldInsn(Opcodes.GETFIELD, slashedName, "nsctxt", "[Ljava/lang/String;");
- mv.visitInsn(Opcodes.ARETURN);
- l1 = helper.createLabel();
-
- mv.visitLabel(l1);
- mv.visitLocalVariable("this", "L" + slashedName + ";", null, l0, l1, 0);
-
- mv.visitMaxs(0, 0);
- mv.visitEnd();
-
-
- mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "getPreDeclaredNamespaceUris", "()[Ljava/lang/String;", null, null);
- mv.visitCode();
- l0 = helper.createLabel();
- mv.visitLabel(l0);
- mv.visitLineNumber(1036, l0);
- mv.visitVarInsn(Opcodes.ALOAD, 0);
- mv.visitMethodInsn(Opcodes.INVOKESPECIAL,
- superName,
- "getPreDeclaredNamespaceUris", "()[Ljava/lang/String;", false);
- mv.visitVarInsn(Opcodes.ASTORE, 1);
- l1 = helper.createLabel();
- mv.visitLabel(l1);
- mv.visitLineNumber(1037, l1);
- mv.visitVarInsn(Opcodes.ALOAD, 0);
- mv.visitFieldInsn(Opcodes.GETFIELD, slashedName, "nsctxt", "[Ljava/lang/String;");
- l2 = helper.createLabel();
- mv.visitJumpInsn(Opcodes.IFNONNULL, l2);
- ASMHelper.Label l3 = helper.createLabel();
- mv.visitLabel(l3);
- mv.visitLineNumber(1038, l3);
- mv.visitVarInsn(Opcodes.ALOAD, 1);
- mv.visitInsn(Opcodes.ARETURN);
- mv.visitLabel(l2);
- mv.visitLineNumber(1040, l2);
- mv.visitFrame(Opcodes.F_APPEND, 1, new Object[] {"[Ljava/lang/String;"}, 0, null);
- mv.visitTypeInsn(Opcodes.NEW, "java/util/ArrayList");
- mv.visitInsn(Opcodes.DUP);
- mv.visitVarInsn(Opcodes.ALOAD, 1);
- mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/Arrays", "asList",
- "([Ljava/lang/Object;)Ljava/util/List;", false);
- mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/util/ArrayList", "<init>",
- "(Ljava/util/Collection;)V", false);
- mv.visitVarInsn(Opcodes.ASTORE, 2);
- ASMHelper.Label l4 = helper.createLabel();
- mv.visitLabel(l4);
- mv.visitLineNumber(1041, l4);
- mv.visitInsn(Opcodes.ICONST_1);
- mv.visitVarInsn(Opcodes.ISTORE, 3);
- ASMHelper.Label l5 = helper.createLabel();
- mv.visitLabel(l5);
- ASMHelper.Label l6 = helper.createLabel();
- mv.visitJumpInsn(Opcodes.GOTO, l6);
- ASMHelper.Label l7 = helper.createLabel();
- mv.visitLabel(l7);
- mv.visitLineNumber(1042, l7);
- mv.visitFrame(Opcodes.F_APPEND, 2, new Object[] {"java/util/List", Opcodes.INTEGER}, 0, null);
- mv.visitVarInsn(Opcodes.ALOAD, 2);
- mv.visitVarInsn(Opcodes.ALOAD, 0);
- mv.visitFieldInsn(Opcodes.GETFIELD, slashedName, "nsctxt", "[Ljava/lang/String;");
- mv.visitVarInsn(Opcodes.ILOAD, 3);
- mv.visitInsn(Opcodes.AALOAD);
- mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/List", "remove", "(Ljava/lang/Object;)Z", true);
- mv.visitInsn(Opcodes.POP);
- ASMHelper.Label l8 = helper.createLabel();
- mv.visitLabel(l8);
- mv.visitLineNumber(1041, l8);
- mv.visitIincInsn(3, 2);
- mv.visitLabel(l6);
- mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
- mv.visitVarInsn(Opcodes.ILOAD, 3);
- mv.visitVarInsn(Opcodes.ALOAD, 0);
- mv.visitFieldInsn(Opcodes.GETFIELD,
- slashedName,
- "nsctxt", "[Ljava/lang/String;");
- mv.visitInsn(Opcodes.ARRAYLENGTH);
- mv.visitJumpInsn(Opcodes.IF_ICMPLT, l7);
- ASMHelper.Label l9 = helper.createLabel();
- mv.visitLabel(l9);
- mv.visitLineNumber(1044, l9);
- mv.visitVarInsn(Opcodes.ALOAD, 2);
- mv.visitVarInsn(Opcodes.ALOAD, 2);
- mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/List", "size", "()I", true);
- mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/String");
- mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/List",
- "toArray", "([Ljava/lang/Object;)[Ljava/lang/Object;", true);
- mv.visitTypeInsn(Opcodes.CHECKCAST, "[Ljava/lang/String;");
- mv.visitInsn(Opcodes.ARETURN);
- ASMHelper.Label l10 = helper.createLabel();
- mv.visitLabel(l10);
- mv.visitLocalVariable("this", "L" + slashedName + ";",
- null, l0, l10, 0);
- mv.visitLocalVariable("sup", "[Ljava/lang/String;", null, l1, l10, 1);
- mv.visitLocalVariable("s", "Ljava/util/List;", "Ljava/util/List<Ljava/lang/String;>;", l4, l10, 2);
- mv.visitLocalVariable("x", "I", null, l5, l9, 3);
- mv.visitMaxs(0, 0);
- mv.visitEnd();
-
- cw.visitEnd();
-
- return cw.toByteArray();
- }
-
- private byte[] createNamespaceWrapperInternal(String postFix) {
-
- String superName = "com/sun/xml/"
- + ("RI".equals(postFix) ? "" : "internal/")
- + "bind/marshaller/NamespacePrefixMapper";
- String postFixedName = "org/apache/cxf/jaxb/NamespaceMapper" + postFix;
- ASMHelper.ClassWriter cw = helper.createClassWriter();
- if (cw == null) {
- return null;
- }
- ASMHelper.FieldVisitor fv;
- ASMHelper.MethodVisitor mv;
- OpcodesProxy opcodes= helper.getOpCodes();
- cw.visit(opcodes.V1_6,
- opcodes.ACC_PUBLIC + opcodes.ACC_FINAL + opcodes.ACC_SUPER,
- postFixedName, null,
- superName, null);
-
- cw.visitSource("NamespaceMapper.java", null);
-
- fv = cw.visitField(opcodes.ACC_PRIVATE + opcodes.ACC_FINAL,
- "nspref", "Ljava/util/Map;",
- "Ljava/util/Map<Ljava/lang/String;Ljava/lang/String;>;", null);
- fv.visitEnd();
-
- fv = cw.visitField(opcodes.ACC_PRIVATE, "nsctxt", "[Ljava/lang/String;", null, null);
- fv.visitEnd();
-
- fv = cw.visitField(opcodes.ACC_PRIVATE + opcodes.ACC_FINAL + opcodes.ACC_STATIC,
- "EMPTY_STRING", "[Ljava/lang/String;", null, null);
- fv.visitEnd();
-
- mv = cw.visitMethod(opcodes.ACC_STATIC, "<clinit>", "()V", null, null);
- mv.visitCode();
- ASMHelper.Label l0 = helper.createLabel();
- mv.visitLabel(l0);
- mv.visitLineNumber(30, l0);
- mv.visitInsn(opcodes.ICONST_0);
- mv.visitTypeInsn(opcodes.ANEWARRAY, "java/lang/String");
- mv.visitFieldInsn(opcodes.PUTSTATIC, postFixedName, "EMPTY_STRING", "[Ljava/lang/String;");
- mv.visitInsn(opcodes.RETURN);
- mv.visitMaxs(0, 0);
- mv.visitEnd();
-
- mv = cw.visitMethod(opcodes.ACC_PUBLIC, "<init>",
- "(Ljava/util/Map;)V",
- "(Ljava/util/Map<Ljava/lang/String;Ljava/lang/String;>;)V", null);
- mv.visitCode();
- l0 = helper.createLabel();
- mv.visitLabel(l0);
- mv.visitLineNumber(32, l0);
- mv.visitVarInsn(opcodes.ALOAD, 0);
- mv.visitMethodInsn(opcodes.INVOKESPECIAL, superName, "<init>", "()V", false);
- ASMHelper.Label l1 = helper.createLabel();
- mv.visitLabel(l1);
- mv.visitLineNumber(29, l1);
- mv.visitVarInsn(opcodes.ALOAD, 0);
- mv.visitFieldInsn(opcodes.GETSTATIC, postFixedName, "EMPTY_STRING", "[Ljava/lang/String;");
- mv.visitFieldInsn(opcodes.PUTFIELD, postFixedName, "nsctxt", "[Ljava/lang/String;");
- ASMHelper.Label l2 = helper.createLabel();
- mv.visitLabel(l2);
- mv.visitLineNumber(33, l2);
- mv.visitVarInsn(opcodes.ALOAD, 0);
- mv.visitVarInsn(opcodes.ALOAD, 1);
- mv.visitFieldInsn(opcodes.PUTFIELD, postFixedName, "nspref", "Ljava/util/Map;");
- ASMHelper.Label l3 = helper.createLabel();
- mv.visitLabel(l3);
- mv.visitLineNumber(34, l3);
- mv.visitInsn(opcodes.RETURN);
- ASMHelper.Label l4 = helper.createLabel();
- mv.visitLabel(l4);
- mv.visitLocalVariable("this", "L" + postFixedName + ";", null, l0, l4, 0);
- mv.visitLocalVariable("nspref",
- "Ljava/util/Map;", "Ljava/util/Map<Ljava/lang/String;Ljava/lang/String;>;",
- l0, l4, 1);
- mv.visitMaxs(0, 0);
- mv.visitEnd();
-
- mv = cw.visitMethod(opcodes.ACC_PUBLIC, "getPreferredPrefix",
- "(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String;",
- null, null);
- mv.visitCode();
- l0 = helper.createLabel();
- mv.visitLabel(l0);
- mv.visitLineNumber(39, l0);
- mv.visitVarInsn(opcodes.ALOAD, 0);
- mv.visitFieldInsn(opcodes.GETFIELD, postFixedName, "nspref", "Ljava/util/Map;");
- mv.visitVarInsn(opcodes.ALOAD, 1);
- mv.visitMethodInsn(opcodes.INVOKEINTERFACE, "java/util/Map",
- "get", "(Ljava/lang/Object;)Ljava/lang/Object;", true);
- mv.visitTypeInsn(opcodes.CHECKCAST, "java/lang/String");
- mv.visitVarInsn(opcodes.ASTORE, 4);
- l1 = helper.createLabel();
- mv.visitLabel(l1);
- mv.visitLineNumber(40, l1);
- mv.visitVarInsn(opcodes.ALOAD, 4);
- l2 = helper.createLabel();
- mv.visitJumpInsn(opcodes.IFNULL, l2);
- l3 = helper.createLabel();
- mv.visitLabel(l3);
- mv.visitLineNumber(41, l3);
- mv.visitVarInsn(opcodes.ALOAD, 4);
- mv.visitInsn(opcodes.ARETURN);
- mv.visitLabel(l2);
- mv.visitLineNumber(43, l2);
- mv.visitFrame(opcodes.F_APPEND, 1, new Object[] {"java/lang/String"}, 0, null);
- mv.visitVarInsn(opcodes.ALOAD, 2);
- mv.visitInsn(opcodes.ARETURN);
- l4 = helper.createLabel();
- mv.visitLabel(l4);
- mv.visitLocalVariable("this", "L" + postFixedName + ";", null, l0, l4, 0);
- mv.visitLocalVariable("namespaceUri", "Ljava/lang/String;", null, l0, l4, 1);
- mv.visitLocalVariable("suggestion", "Ljava/lang/String;", null, l0, l4, 2);
- mv.visitLocalVariable("requirePrefix", "Z", null, l0, l4, 3);
- mv.visitLocalVariable("prefix", "Ljava/lang/String;", null, l1, l4, 4);
- mv.visitMaxs(0, 0);
- mv.visitEnd();
-
- mv = cw.visitMethod(opcodes.ACC_PUBLIC, "setContextualNamespaceDecls", "([Ljava/lang/String;)V", null, null);
- mv.visitCode();
- l0 = helper.createLabel();
- mv.visitLabel(l0);
- mv.visitLineNumber(47, l0);
- mv.visitVarInsn(opcodes.ALOAD, 0);
- mv.visitVarInsn(opcodes.ALOAD, 1);
- mv.visitFieldInsn(opcodes.PUTFIELD, postFixedName, "nsctxt", "[Ljava/lang/String;");
- l1 = helper.createLabel();
- mv.visitLabel(l1);
- mv.visitLineNumber(48, l1);
- mv.visitInsn(opcodes.RETURN);
- l2 = helper.createLabel();
- mv.visitLabel(l2);
- mv.visitLocalVariable("this", "L" + postFixedName + ";", null, l0, l2, 0);
- mv.visitLocalVariable("contextualNamespaceDecls", "[Ljava/lang/String;", null, l0, l2, 1);
- mv.visitMaxs(0, 0);
- mv.visitEnd();
-
- mv = cw.visitMethod(opcodes.ACC_PUBLIC, "getContextualNamespaceDecls", "()[Ljava/lang/String;", null, null);
- mv.visitCode();
- l0 = helper.createLabel();
- mv.visitLabel(l0);
- mv.visitLineNumber(51, l0);
- mv.visitVarInsn(opcodes.ALOAD, 0);
- mv.visitFieldInsn(opcodes.GETFIELD, postFixedName, "nsctxt", "[Ljava/lang/String;");
- mv.visitInsn(opcodes.ARETURN);
- l1 = helper.createLabel();
-
- mv.visitLabel(l1);
- mv.visitLocalVariable("this", "L" + postFixedName + ";", null, l0, l1, 0);
-
- mv.visitMaxs(0, 0);
- mv.visitEnd();
-
- cw.visitEnd();
-
- return cw.toByteArray();
- }
- //CHECKSTYLE:ON
-}
diff --git a/transform/src/patch/java/org/apache/cxf/common/util/ASMHelperImpl.java b/transform/src/patch/java/org/apache/cxf/common/util/ASMHelperImpl.java
deleted file mode 100644
index cc01f14..0000000
--- a/transform/src/patch/java/org/apache/cxf/common/util/ASMHelperImpl.java
+++ /dev/null
@@ -1,273 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.common.util;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.GenericArrayType;
-import java.lang.reflect.Method;
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.TypeVariable;
-import java.lang.reflect.WildcardType;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.cxf.common.classloader.ClassLoaderUtils;
-
-
-public class ASMHelperImpl implements ASMHelper {
- protected static final Map<Class<?>, String> PRIMITIVE_MAP = new HashMap<>();
- protected static final Map<Class<?>, String> NONPRIMITIVE_MAP = new HashMap<>();
- protected static final Map<Class<?>, Integer> PRIMITIVE_ZERO_MAP = new HashMap<>();
-
- protected boolean badASM;
- private Class<?> cwClass;
-
- public ASMHelperImpl() {
-
- }
-
- static {
- PRIMITIVE_MAP.put(Byte.TYPE, "B");
- PRIMITIVE_MAP.put(Boolean.TYPE, "Z");
- PRIMITIVE_MAP.put(Long.TYPE, "J");
- PRIMITIVE_MAP.put(Integer.TYPE, "I");
- PRIMITIVE_MAP.put(Short.TYPE, "S");
- PRIMITIVE_MAP.put(Character.TYPE, "C");
- PRIMITIVE_MAP.put(Float.TYPE, "F");
- PRIMITIVE_MAP.put(Double.TYPE, "D");
-
- NONPRIMITIVE_MAP.put(Byte.TYPE, Byte.class.getName().replaceAll("\\.", "/"));
- NONPRIMITIVE_MAP.put(Boolean.TYPE, Boolean.class.getName().replaceAll("\\.", "/"));
- NONPRIMITIVE_MAP.put(Long.TYPE, Long.class.getName().replaceAll("\\.", "/"));
- NONPRIMITIVE_MAP.put(Integer.TYPE, Integer.class.getName().replaceAll("\\.", "/"));
- NONPRIMITIVE_MAP.put(Short.TYPE, Short.class.getName().replaceAll("\\.", "/"));
- NONPRIMITIVE_MAP.put(Character.TYPE, Character.class.getName().replaceAll("\\.", "/"));
- NONPRIMITIVE_MAP.put(Float.TYPE, Float.class.getName().replaceAll("\\.", "/"));
- NONPRIMITIVE_MAP.put(Double.TYPE, Double.class.getName().replaceAll("\\.", "/"));
- }
-
- private void tryClass(String s) {
- if (cwClass == null) {
- try {
- Class<?> c2 = ClassLoaderUtils.loadClass(s, ASMHelperImpl.class);
-
- //old versions don't have this, but we need it
- Class<?> cls = ClassLoaderUtils.loadClass(c2.getPackage().getName() + ".MethodVisitor", c2);
- cls.getMethod("visitFrame", Integer.TYPE, Integer.TYPE,
- Object[].class, Integer.TYPE, Object[].class);
- cwClass = c2;
- } catch (Throwable t) {
- //ignore
- }
- }
- }
- private Class<?> getASMClassWriterClass() {
- //force this to make sure the proper OSGi import is generated
- return org.objectweb.asm.ClassWriter.class;
- }
-
- public synchronized Class<?> getASMClass() throws ClassNotFoundException {
- if (cwClass == null) {
- //try the "real" asm first, then the others
- tryClass("org.objectweb.asm.ClassWriter");
- tryClass("org.apache.xbean.asm9.ClassWriter");
- tryClass("org.apache.xbean.asm8.ClassWriter");
- tryClass("org.apache.xbean.asm7.ClassWriter");
- tryClass("org.apache.xbean.asm5.ClassWriter");
- tryClass("org.apache.xbean.asm6.ClassWriter");
- tryClass("org.apache.xbean.asm4.ClassWriter");
- tryClass("org.apache.xbean.asm.ClassWriter");
- tryClass("org.springframework.asm.ClassWriter");
- if (cwClass == null) {
- cwClass = getASMClassWriterClass();
- }
- }
- return cwClass;
- }
- public OpcodesProxy getOpCodes() {
- OpcodesProxy ops = new OpcodesProxy(this);
- PRIMITIVE_ZERO_MAP.put(Byte.TYPE, ops.ICONST_0);
- PRIMITIVE_ZERO_MAP.put(Boolean.TYPE, ops.ICONST_0);
- PRIMITIVE_ZERO_MAP.put(Long.TYPE, ops.LCONST_0);
- PRIMITIVE_ZERO_MAP.put(Integer.TYPE, ops.ICONST_0);
- PRIMITIVE_ZERO_MAP.put(Short.TYPE, ops.ICONST_0);
- PRIMITIVE_ZERO_MAP.put(Character.TYPE, ops.ICONST_0);
- PRIMITIVE_ZERO_MAP.put(Float.TYPE, ops.FCONST_0);
- PRIMITIVE_ZERO_MAP.put(Double.TYPE, ops.DCONST_0);
- return ops;
- }
- public void setBadASM(boolean b) {
- badASM = b;
- }
-
- public String getMethodSignature(Method m) {
- StringBuilder buf = new StringBuilder("(");
- for (Class<?> cl : m.getParameterTypes()) {
- buf.append(getClassCode(cl));
- }
- buf.append(')');
- buf.append(getClassCode(m.getReturnType()));
-
- return buf.toString();
- }
-
- @Override
- public String getNonPrimitive(Class<?> tp) {
- return NONPRIMITIVE_MAP.get(tp);
- }
- @Override
- public String getPrimitive(Class<?> tp) {
- return PRIMITIVE_MAP.get(tp);
- }
-
-
-
-
- public String getClassCode(Class<?> cl) {
- if (cl == Void.TYPE) {
- return "V";
- }
- if (cl.isPrimitive()) {
- return PRIMITIVE_MAP.get(cl);
- }
- if (cl.isArray()) {
- return "[" + getClassCode(cl.getComponentType());
- }
- return "L" + StringUtils.periodToSlashes(cl.getName()) + ";";
- }
- public String getClassCode(java.lang.reflect.Type type) {
- if (type instanceof Class) {
- return getClassCode((Class<?>)type);
- } else if (type instanceof GenericArrayType) {
- GenericArrayType at = (GenericArrayType)type;
- return "[" + getClassCode(at.getGenericComponentType());
- } else if (type instanceof TypeVariable) {
- TypeVariable<?> tv = (TypeVariable<?>)type;
- java.lang.reflect.Type[] bounds = tv.getBounds();
- if (bounds != null && bounds.length == 1) {
- return getClassCode(bounds[0]);
- }
- throw new IllegalArgumentException("Unable to determine type for: " + tv);
- } else if (type instanceof ParameterizedType) {
- ParameterizedType pt = (ParameterizedType)type;
- StringBuilder a = new StringBuilder(getClassCode(pt.getRawType()));
- if (!pt.getRawType().equals(Enum.class)) {
- a.setLength(a.length() - 1);
- a.append('<');
-
- for (java.lang.reflect.Type t : pt.getActualTypeArguments()) {
- a.append(getClassCode(t));
- }
- a.append(">;");
- }
- return a.toString();
- } else if (type instanceof WildcardType) {
- WildcardType wt = (WildcardType)type;
- StringBuilder a = new StringBuilder();
- java.lang.reflect.Type[] lowBounds = wt.getLowerBounds();
- java.lang.reflect.Type[] upBounds = wt.getUpperBounds();
- for (java.lang.reflect.Type t : upBounds) {
- a.append('+');
- a.append(getClassCode(t));
- }
- for (java.lang.reflect.Type t : lowBounds) {
- a.append('-');
- a.append(getClassCode(t));
- }
- return a.toString();
- }
- return null;
- }
-
- public ClassWriter createClassWriter() {
- Object newCw = null;
- if (!badASM) {
- if (cwClass == null) {
- try {
- cwClass = getASMClass();
- } catch (Throwable error) {
- badASM = true;
- throw new RuntimeException("No ASM ClassWriterFound", error);
- }
- }
- // ASM >= 3.x (since cxf is java 8 min we don't care of asm 1/2)
- try {
- Constructor<?> cons = cwClass.getConstructor(Integer.TYPE);
- int i = cwClass.getField("COMPUTE_MAXS").getInt(null);
- i |= cwClass.getField("COMPUTE_FRAMES").getInt(null);
- newCw = cons.newInstance(Integer.valueOf(i));
- } catch (Throwable e1) {
- // ignore
- }
- }
- if (newCw != null) {
- return ReflectionInvokationHandler.createProxyWrapper(newCw, ClassWriter.class);
- }
- return null;
- }
-
-
- public ASMType getType(final String type) {
- try {
- final Class<?> cls = ClassLoaderUtils.loadClass(cwClass.getPackage().getName() + ".Type", cwClass);
- final Method m = cls.getMethod("getType", String.class);
- final Method m2 = cls.getMethod("getOpcode", Integer.TYPE);
- @SuppressWarnings("unused")
- ASMType t = new ASMType() {
- Object tp = ReflectionUtil.setAccessible(m).invoke(null, type);
- public Object getValue() {
- return tp;
- }
- public Class<?> realType() {
- return cls;
- }
- public int getOpcode(int ireturn) {
- try {
- return (Integer)ReflectionUtil.setAccessible(m2).invoke(tp, ireturn);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- };
- return t;
- } catch (Exception ex) {
- throw new RuntimeException(ex);
- }
- }
- public Label createLabel() {
- try {
- final Class<?> cls = ClassLoaderUtils.loadClass(cwClass.getPackage().getName() + ".Label",
- cwClass);
- @SuppressWarnings("unused")
- Label l = new Label() {
- Object l = cls.newInstance();
- public Object getValue() {
- return l;
- }
- public Class<?> realType() {
- return cls;
- }
- };
- return l;
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-}
diff --git a/transform/src/patch/java/org/apache/cxf/common/util/Base64Utility.java b/transform/src/patch/java/org/apache/cxf/common/util/Base64Utility.java
deleted file mode 100644
index 043eba7..0000000
--- a/transform/src/patch/java/org/apache/cxf/common/util/Base64Utility.java
+++ /dev/null
@@ -1,474 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.common.util;
-
-/**
- * Base64Utility - this static class provides useful base64
- * encoding utilities.
- */
-
-// Java imports
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.Writer;
-import java.nio.CharBuffer;
-import java.nio.charset.StandardCharsets;
-import java.util.Arrays;
-import java.util.logging.Logger;
-
-import org.apache.cxf.common.i18n.Message;
-import org.apache.cxf.common.logging.LogUtils;
-
-
-/**
- * This class converts to/from base64. The alternative conversions include:
- *
- * encode:
- * byte[] into String
- * byte[] into char[]
- * byte[] into OutStream
- * byte[] into Writer
- * decode:
- * char[] into byte[]
- * String into byte[]
- * char[] into OutStream
- * String into OutStream
- *
- */
-public final class Base64Utility {
-
- private static final Logger LOG = LogUtils.getL7dLogger(Base64Utility.class);
-
-
- // base 64 character set
- //
- private static final char[] BCS = {
- 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
- 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
- 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
- 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
- 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
- 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
- '8', '9', '+', '/'
- };
-
- private static final char[] BCS_URL_SAFE = Arrays.copyOf(BCS, BCS.length);
-
- // base 64 padding
- private static final char PAD = '=';
-
- // size of base 64 decode table
- private static final int BDTSIZE = 128;
-
- // base 64 decode table
- private static final byte[] BDT = new byte[128];
-
-
- private static final int PAD_SIZE0 = 1;
- private static final int PAD_SIZE4 = 2;
- private static final int PAD_SIZE8 = 3;
-
- // class static initializer for building decode table
- static {
- for (int i = 0; i < BDTSIZE; i++) {
- BDT[i] = Byte.MAX_VALUE;
- }
-
- for (int i = 0; i < BCS.length; i++) {
- BDT[BCS[i]] = (byte)i;
- }
-
- BCS_URL_SAFE[62] = '-';
- BCS_URL_SAFE[63] = '_';
- }
-
-
- private Base64Utility() {
- //utility class, never constructed
- }
-
-
-
- /**
- * The <code>decode_chunk</code> routine decodes a chunk of data
- * into its native encoding.
- *
- * base64 encodes each 3 octets of data into 4 characters from a
- * limited 64 character set. The 3 octets are joined to form
- * 24 bits which are then split into 4 x 6bit values. Each 6 bit
- * value is then used as an index into the 64 character table of
- * base64 chars. If the total data length is not a 3 octet multiple
- * the '=' char is used as padding for the final 4 char group,
- * either 1 octet + '==' or 2 octets + '='.
- *
- * @param id The input data to be processed
- * @param o The offset from which to begin processing
- * @param l The length (bound) at which processing is to end
- * @return The decoded data
- * @exception Base64Exception Thrown is processing fails due to
- * formatting exceptions in the encoded data
- */
- public static byte[] decodeChunk(char[] id,
- int o,
- int l)
- throws Base64Exception {
-
- if (id != null && id.length == 0 && l == 0) {
- return new byte[0];
- }
-
- // Keep it simple - must be >= 4. Unpadded
- // base64 data contain < 3 octets is invalid.
- //
- if ((l - o) < 4) {
- return null;
- }
-
- char[] ib = new char[4];
- int ibcount = 0;
-
- // cryan. Calc the num of octets. Each 4 chars of base64 chars
- // (representing 24 bits) encodes 3 octets.
- //
- int octetCount = 3 * (l / 4);
-
- // Final 4 chars may contain 3 octets or padded to contain
- // 1 or 2 octets.
- //
- if (id[l - 1] == PAD) {
- // TT== means last 4 chars encode 8 bits (ie subtract 2)
- // TTT= means last 4 chars encode 16 bits (ie subtract 1)
- octetCount -= (id[l - 2] == PAD) ? 2 : 1;
- }
-
- byte[] ob = new byte[octetCount];
- int obcount = 0;
-
- for (int i = o; i < o + l && i < id.length; i++) {
- if (id[i] == PAD
- || id[i] < BDT.length
- && BDT[id[i]] != Byte.MAX_VALUE) {
-
- ib[ibcount++] = id[i];
-
- // Decode each 4 char sequence.
- //
- if (ibcount == ib.length) {
- ibcount = 0;
- obcount += processEncodeme(ib, ob, obcount);
- }
- }
- }
-
- if (obcount != ob.length) {
- byte []tmp = new byte[obcount];
- System.arraycopy(ob, 0, tmp, 0, obcount);
- ob = tmp;
- }
-
- return ob;
- }
-
- public static byte[] decode(String id) throws Base64Exception {
- return decode(id, false);
- }
-
- public static byte[] decode(String id, boolean urlSafe) throws Base64Exception {
- if (urlSafe) {
- id = id.replace('-', '+').replace('_', '/');
- switch (id.length() % 4) {
- case 0:
- break;
- case 2:
- id += "==";
- break;
- case 3:
- id += "=";
- break;
- default:
- throw new Base64Exception(new Message("BASE64_RUNTIME_EXCEPTION", LOG));
- }
- }
- try {
- char[] cd = id.toCharArray();
- return decodeChunk(cd, 0, cd.length);
- } catch (Exception e) {
- LOG.warning("Invalid base64 encoded string : " + id);
- throw new Base64Exception(new Message("BASE64_RUNTIME_EXCEPTION", LOG), e);
- }
- }
-
- public static void decode(char[] id,
- int o,
- int l,
- OutputStream ostream)
- throws Base64Exception {
-
- try {
- ostream.write(decodeChunk(id, o, l));
- } catch (Exception e) {
- LOG.warning("Invalid base64 encoded string : " + new String(id));
- throw new Base64Exception(new Message("BASE64_RUNTIME_EXCEPTION", LOG), e);
- }
- }
-
- public static void decode(String id,
- OutputStream ostream)
- throws Base64Exception {
-
- try {
- char[] cd = id.toCharArray();
- ostream.write(decodeChunk(cd, 0, cd.length));
- } catch (IOException ioe) {
- throw new Base64Exception(new Message("BASE64_DECODE_IOEXCEPTION", LOG), ioe);
- } catch (Exception e) {
- LOG.warning("Invalid base64 encoded string : " + id);
- throw new Base64Exception(new Message("BASE64_RUNTIME_EXCEPTION", LOG), e);
- }
- }
-
- // Returns base64 representation of specified byte array.
- //
- public static String encode(byte[] id) {
- return encode(id, false);
- }
-
- public static String encode(byte[] id, boolean urlSafe) {
- char[] cd = encodeChunk(id, 0, id.length);
- return new String(cd, 0, cd.length);
- }
-
- // Returns base64 representation of specified byte array.
- //
- public static char[] encodeChunk(byte[] id,
- int o,
- int l) {
- return encodeChunk(id, o, l, false);
- }
-
- public static char[] encodeChunk(byte[] id,
- int o,
- int l,
- boolean urlSafe) {
- if (id != null && id.length == 0 && l == 0) {
- return new char[0];
- } else if (l <= 0) {
- return null;
- }
-
- char[] out;
-
- // If not a multiple of 3 octets then a final padded 4 char
- // slot is needed.
- //
- if (l % 3 == 0) {
- out = new char[l / 3 * 4];
- } else {
- int finalLen = !urlSafe ? 4 : l % 3 == 1 ? 2 : 3;
- out = new char[l / 3 * 4 + finalLen];
- }
-
- int rindex = o;
- int windex = 0;
- int rest = l;
-
- final char[] base64Table = urlSafe ? BCS_URL_SAFE : BCS;
- while (rest >= 3) {
- int i = ((id[rindex] & 0xff) << 16)
- + ((id[rindex + 1] & 0xff) << 8)
- + (id[rindex + 2] & 0xff);
-
- out[windex++] = base64Table[i >> 18];
- out[windex++] = base64Table[(i >> 12) & 0x3f];
- out[windex++] = base64Table[(i >> 6) & 0x3f];
- out[windex++] = base64Table[i & 0x3f];
- rindex += 3;
- rest -= 3;
- }
-
- if (rest == 1) {
- int i = id[rindex] & 0xff;
- out[windex++] = base64Table[i >> 2];
- out[windex++] = base64Table[(i << 4) & 0x3f];
- if (!urlSafe) {
- out[windex++] = PAD;
- out[windex] = PAD;
- }
- } else if (rest == 2) {
- int i = ((id[rindex] & 0xff) << 8) + (id[rindex + 1] & 0xff);
- out[windex++] = base64Table[i >> 10];
- out[windex++] = base64Table[(i >> 4) & 0x3f];
- out[windex++] = base64Table[(i << 2) & 0x3f];
- if (!urlSafe) {
- out[windex] = PAD;
- }
- }
- return out;
- }
-
- public static void encodeAndStream(byte[] id,
- int o,
- int l,
- OutputStream os) throws IOException {
- encodeAndStream(id, o, l, false, os);
- }
-
- public static void encodeAndStream(byte[] id,
- int o,
- int l,
- boolean urlSafe,
- OutputStream os) throws IOException {
- if (l <= 0) {
- return;
- }
-
- int rindex = o;
- int rest = l;
- final char[] base64Table = urlSafe ? BCS_URL_SAFE : BCS;
-
- char[] chunk = new char[4];
- while (rest >= 3) {
- int i = ((id[rindex] & 0xff) << 16)
- + ((id[rindex + 1] & 0xff) << 8)
- + (id[rindex + 2] & 0xff);
- chunk[0] = base64Table[i >> 18];
- chunk[1] = base64Table[(i >> 12) & 0x3f];
- chunk[2] = base64Table[(i >> 6) & 0x3f];
- chunk[3] = base64Table[i & 0x3f];
- writeCharArrayToStream(chunk, 4, os);
- rindex += 3;
- rest -= 3;
- }
- if (rest == 0) {
- return;
- }
- if (rest == 1) {
- int i = id[rindex] & 0xff;
- chunk[0] = base64Table[i >> 2];
- chunk[1] = base64Table[(i << 4) & 0x3f];
- if (!urlSafe) {
- chunk[2] = PAD;
- chunk[3] = PAD;
- }
- } else if (rest == 2) {
- int i = ((id[rindex] & 0xff) << 8) + (id[rindex + 1] & 0xff);
- chunk[0] = base64Table[i >> 10];
- chunk[1] = base64Table[(i >> 4) & 0x3f];
- chunk[2] = base64Table[(i << 2) & 0x3f];
- if (!urlSafe) {
- chunk[3] = PAD;
... 48558 lines suppressed ...