X stringlengths 236 264k | y stringlengths 5 74 |
|---|---|
/*
* Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.hosted;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.stream.Collectors;
import org.graalvm.nativeimage.hosted.RuntimeReflection;
import org.graalvm.nativeimage.hosted.RuntimeResourceAccess;
import com.oracle.svm.core.feature.AutomaticallyRegisteredFeature;
import com.oracle.svm.core.feature.InternalFeature;
import com.oracle.svm.core.jdk.ServiceCatalogSupport;
import com.oracle.svm.core.option.AccumulatingLocatableMultiOptionValue;
import com.oracle.svm.core.option. [MASK] ;
import com.oracle.svm.hosted.analysis.Inflation;
import jdk.graal.compiler.options.Option;
import jdk.graal.compiler.options.OptionType;
/**
* Support for {@link ServiceLoader} on Substrate VM.
*
* Services are registered in the folder {@code "META-INF/services/"} using files whose name is the
* fully qualified service interface name. We do not know which services are going to be used by a
* native image: The parameter of {@code ServiceLoader#load} is often but not always a compile-time
* constant that we can track. But we also cannot put all registered services into the native image.
*
* We therefore use the following heuristic: We add all service loader files and service
* implementation classes when the service interfaces that are seen as reachable by the static
* analysis.
*
* Each used service implementation class is added for reflection (using
* {@link org.graalvm.nativeimage.hosted.RuntimeReflection#register(Class[])}) and for reflective
* instantiation (using {@link RuntimeReflection#registerForReflectiveInstantiation(Class[])}).
*
* For each service interface, a single service loader file is added as a resource to the image. The
* single file combines all the individual files that can come from different .jar files.
*/
@AutomaticallyRegisteredFeature
public class ServiceLoaderFeature implements InternalFeature {
public static class Options {
@Option(help = "Automatically register services for run-time lookup using ServiceLoader", type = OptionType.Expert) //
public static final [MASK] <Boolean> UseServiceLoaderFeature = new [MASK] <>(true);
@Option(help = "Comma-separated list of services that should be excluded", type = OptionType.Expert) //
public static final [MASK] <AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServices = new [MASK] <>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
@Option(help = "Comma-separated list of service providers that should be excluded", type = OptionType.Expert) //
public static final [MASK] <AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServiceProviders = new [MASK] <>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
}
private static final Set<String> SKIPPED_SERVICES = Set.of(
// image builder internal ServiceLoader interfaces
"com.oracle.svm.hosted.NativeImageClassLoaderPostProcessing",
"org.graalvm.nativeimage.Platform",
/*
* Loaded in java.util.random.RandomGeneratorFactory.FactoryMapHolder, which is
* initialized at image build time.
*/
"java.util.random.RandomGenerator",
"java.security.Provider", // see SecurityServicesFeature
"sun.util.locale.provider.LocaleDataMetaInfo", // see LocaleSubstitutions
/* Graal hotspot-specific services */
"jdk.vm.ci.hotspot.HotSpotJVMCIBackendFactory",
"jdk.graal.compiler.hotspot.CompilerConfigurationFactory",
"jdk.graal.compiler.hotspot.HotSpotBackendFactory",
"jdk.graal.compiler.hotspot.meta.DefaultHotSpotLoweringProvider$Extensions",
"jdk.graal.compiler.hotspot.meta.HotSpotInvocationPluginProvider",
"jdk.graal.compiler.truffle.hotspot.TruffleCallBoundaryInstrumentationFactory");
// NOTE: Platform class had to be added to this list since our analysis discovers that
// Platform.includedIn is reachable regardless of fact that it is constant folded at
// registerPlatformPlugins method of SubstrateGraphBuilderPlugins. This issue hasn't manifested
// before because implementation classes were instantiated using runtime reflection instead of
// ServiceLoader (and thus weren't reachable in analysis).
/**
* Services that should not be processed here, for example because they are handled by
* specialized features.
*/
private final Set<String> servicesToSkip = new HashSet<>(SKIPPED_SERVICES);
private static final Set<String> SKIPPED_PROVIDERS = Set.of(
/* Graal hotspot-specific service-providers */
"jdk.graal.compiler.hotspot.meta.HotSpotDisassemblerProvider",
/* Skip console providers until GR-44085 is fixed */
"jdk.internal.org.jline.JdkConsoleProviderImpl", "jdk.jshell.execution.impl.ConsoleImpl$ConsoleProviderImpl");
private final Set<String> serviceProvidersToSkip = new HashSet<>(SKIPPED_PROVIDERS);
@Override
public boolean isInConfiguration(IsInConfigurationAccess access) {
return Options.UseServiceLoaderFeature.getValue();
}
@Override
public void afterRegistration(AfterRegistrationAccess access) {
servicesToSkip.addAll(Options.ServiceLoaderFeatureExcludeServices.getValue().values());
serviceProvidersToSkip.addAll(Options.ServiceLoaderFeatureExcludeServiceProviders.getValue().values());
}
@Override
public void beforeAnalysis(BeforeAnalysisAccess access) {
FeatureImpl.BeforeAnalysisAccessImpl accessImpl = (FeatureImpl.BeforeAnalysisAccessImpl) access;
accessImpl.imageClassLoader.classLoaderSupport.serviceProvidersForEach((serviceName, providers) -> {
Class<?> serviceClass = access.findClassByName(serviceName);
boolean skipService = false;
/* If the service should not end up in the image, we remove all the providers with it */
Collection<String> providersToSkip = providers;
if (servicesToSkip.contains(serviceName)) {
skipService = true;
} else if (serviceClass == null || serviceClass.isArray() || serviceClass.isPrimitive()) {
skipService = true;
} else if (!accessImpl.getHostVM().platformSupported(serviceClass)) {
skipService = true;
} else {
providersToSkip = providers.stream().filter(serviceProvidersToSkip::contains).collect(Collectors.toList());
if (!providersToSkip.isEmpty()) {
skipService = true;
}
}
if (skipService) {
ServiceCatalogSupport.singleton().removeServicesFromServicesCatalog(serviceName, new HashSet<>(providersToSkip));
return;
}
access.registerReachabilityHandler(a -> handleServiceClassIsReachable(a, serviceClass, providers), serviceClass);
});
}
void handleServiceClassIsReachable(DuringAnalysisAccess access, Class<?> serviceProvider, Collection<String> providers) {
LinkedHashSet<String> registeredProviders = new LinkedHashSet<>();
for (String provider : providers) {
if (serviceProvidersToSkip.contains(provider)) {
continue;
}
/* Make provider reflectively instantiable */
Class<?> providerClass = access.findClassByName(provider);
if (providerClass == null || providerClass.isArray() || providerClass.isPrimitive()) {
continue;
}
FeatureImpl.DuringAnalysisAccessImpl accessImpl = (FeatureImpl.DuringAnalysisAccessImpl) access;
if (!accessImpl.getHostVM().platformSupported(providerClass)) {
continue;
}
if (((Inflation) accessImpl.getBigBang()).getAnnotationSubstitutionProcessor().isDeleted(providerClass)) {
/* Disallow services with implementation classes that are marked as @Deleted */
continue;
}
/*
* Find either a public static provider() method or a nullary constructor (or both).
* Skip providers that do not comply with requirements.
*
* See ServiceLoader#loadProvider and ServiceLoader#findStaticProviderMethod.
*/
Constructor<?> nullaryConstructor = null;
Method nullaryProviderMethod = null;
try {
/* Only look for a provider() method if provider class is in an explicit module. */
if (providerClass.getModule().isNamed() && !providerClass.getModule().getDescriptor().isAutomatic()) {
for (Method method : providerClass.getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers()) &&
method.getParameterCount() == 0 && method.getName().equals("provider")) {
if (nullaryProviderMethod == null) {
nullaryProviderMethod = method;
} else {
/* There must be at most one public static provider() method. */
nullaryProviderMethod = null;
break;
}
}
}
}
Constructor<?> constructor = providerClass.getDeclaredConstructor();
if (Modifier.isPublic(constructor.getModifiers())) {
nullaryConstructor = constructor;
}
} catch (NoSuchMethodException | SecurityException | LinkageError e) {
// ignore
}
if (nullaryConstructor != null || nullaryProviderMethod != null) {
RuntimeReflection.register(providerClass);
if (nullaryConstructor != null) {
/*
* Registering a constructor with
* RuntimeReflection.registerConstructorLookup(providerClass) does not produce
* the same behavior as using RuntimeReflection.register(nullaryConstructor). In
* the first case, the constructor is marked for query purposes only, so this
* if-statement cannot be eliminated.
*
*/
RuntimeReflection.register(nullaryConstructor);
} else {
/*
* If there's no nullary constructor, register it as negative lookup to avoid
* throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerConstructorLookup(providerClass);
}
if (nullaryProviderMethod != null) {
RuntimeReflection.register(nullaryProviderMethod);
} else {
/*
* If there's no declared public provider() method, register it as negative
* lookup to avoid throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerMethodLookup(providerClass, "provider");
}
}
/*
* Register the provider in both cases: when it is JCA-compliant (has a nullary
* constructor or a provider method) or when it lacks both. If neither is present, a
* ServiceConfigurationError will be thrown at runtime, consistent with HotSpot
* behavior.
*/
registeredProviders.add(provider);
}
if (!registeredProviders.isEmpty()) {
String serviceResourceLocation = "META-INF/services/" + serviceProvider.getName();
byte[] serviceFileData = registeredProviders.stream().collect(Collectors.joining("\n")).getBytes(StandardCharsets.UTF_8);
RuntimeResourceAccess.addResource(access.getApplicationClassLoader().getUnnamedModule(), serviceResourceLocation, serviceFileData);
}
}
}
| HostedOptionKey |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details. [MASK] ().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details. [MASK] ().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details. [MASK] ().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| getRelativePath |
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
*/
/*
* 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 com.sun.org.apache.xerces.internal.impl.xs;
import com.sun.org.apache.xerces.internal.impl.Constants;
import com.sun.org.apache.xerces.internal.impl.dv.SchemaDVFactory;
import com.sun.org.apache.xerces.internal.impl.dv.ValidatedInfo;
import com.sun.org.apache.xerces.internal.impl.dv.XSSimpleType;
import com.sun.org.apache.xerces.internal.impl.dv.xs.XSSimpleTypeDecl;
import com.sun.org.apache.xerces.internal.impl.xs.identity. [MASK] ;
import com.sun.org.apache.xerces.internal.impl.xs.util.ObjectListImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.SimpleLocator;
import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSNamedMap4Types;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSNamedMapImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSObjectListImpl;
import com.sun.org.apache.xerces.internal.parsers.DOMParser;
import com.sun.org.apache.xerces.internal.parsers.SAXParser;
import com.sun.org.apache.xerces.internal.parsers.XML11Configuration;
import com.sun.org.apache.xerces.internal.util.SymbolHash;
import com.sun.org.apache.xerces.internal.util.SymbolTable;
import com.sun.org.apache.xerces.internal.xni.NamespaceContext;
import com.sun.org.apache.xerces.internal.xni.grammars.XMLGrammarDescription;
import com.sun.org.apache.xerces.internal.xni.grammars.XSGrammar;
import com.sun.org.apache.xerces.internal.xs.StringList;
import com.sun.org.apache.xerces.internal.xs.XSAnnotation;
import com.sun.org.apache.xerces.internal.xs.XSAttributeDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSAttributeGroupDefinition;
import com.sun.org.apache.xerces.internal.xs.XSConstants;
import com.sun.org.apache.xerces.internal.xs.XSElementDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSIDCDefinition;
import com.sun.org.apache.xerces.internal.xs.XSModel;
import com.sun.org.apache.xerces.internal.xs.XSModelGroupDefinition;
import com.sun.org.apache.xerces.internal.xs.XSNamedMap;
import com.sun.org.apache.xerces.internal.xs.XSNamespaceItem;
import com.sun.org.apache.xerces.internal.xs.XSNotationDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSObjectList;
import com.sun.org.apache.xerces.internal.xs.XSParticle;
import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
import com.sun.org.apache.xerces.internal.xs.XSWildcard;
import com.sun.org.apache.xerces.internal.xs.datatypes.ObjectList;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.xml.sax.SAXException;
/**
* This class is to hold all schema component declaration that are declared
* within one namespace.
*
* The Grammar class this class extends contains what little
* commonality there is between XML Schema and DTD grammars. It's
* useful to distinguish grammar objects from other kinds of object
* when they exist in pools or caches.
*
* @xerces.internal
*
* @author Sandy Gao, IBM
* @author Elena Litani, IBM
*
* @LastModified: Oct 2017
*/
public class SchemaGrammar implements XSGrammar, XSNamespaceItem {
// the target namespace of grammar
String fTargetNamespace;
// global decls: map from decl name to decl object
SymbolHash fGlobalAttrDecls;
SymbolHash fGlobalAttrGrpDecls;
SymbolHash fGlobalElemDecls;
SymbolHash fGlobalGroupDecls;
SymbolHash fGlobalNotationDecls;
SymbolHash fGlobalIDConstraintDecls;
SymbolHash fGlobalTypeDecls;
// extended global decls: map from schema location + decl name to decl object
// key is location,name
SymbolHash fGlobalAttrDeclsExt;
SymbolHash fGlobalAttrGrpDeclsExt;
SymbolHash fGlobalElemDeclsExt;
SymbolHash fGlobalGroupDeclsExt;
SymbolHash fGlobalNotationDeclsExt;
SymbolHash fGlobalIDConstraintDeclsExt;
SymbolHash fGlobalTypeDeclsExt;
// A global map of all global element declarations - used for substitution group computation
// (handy when sharing components by reference, since we might end up with duplicate components
// that are not added to either of the global element declarations above)
SymbolHash fAllGlobalElemDecls;
// the XMLGrammarDescription member
XSDDescription fGrammarDescription = null;
// annotations associated with the "root" schema of this targetNamespace
XSAnnotationImpl [] fAnnotations = null;
// number of annotations declared
int fNumAnnotations;
// symbol table for constructing parsers (annotation support)
private SymbolTable fSymbolTable = null;
// parsers for annotation support
private SoftReference<SAXParser> fSAXParser = null;
private SoftReference<DOMParser> fDOMParser = null;
// is this grammar immutable? (fully constructed and not changeable)
private boolean fIsImmutable = false;
//
// Constructors
//
// needed to make BuiltinSchemaGrammar work.
protected SchemaGrammar() {}
/**
* Default constructor.
*
* @param targetNamespace
* @param grammarDesc the XMLGrammarDescription corresponding to this object
* at the least a systemId should always be known.
* @param symbolTable needed for annotation support
*/
public SchemaGrammar(String targetNamespace, XSDDescription grammarDesc,
SymbolTable symbolTable) {
fTargetNamespace = targetNamespace;
fGrammarDescription = grammarDesc;
fSymbolTable = symbolTable;
// REVISIT: the initial sizes being chosen for each SymbolHash
// may not be ideal and could still be tuned. They were chosen
// somewhat arbitrarily to reduce the initial footprint of
// SymbolHash buckets from 1,515 to 177 (about 12% of the
// default size).
fGlobalAttrDecls = new SymbolHash(12);
fGlobalAttrGrpDecls = new SymbolHash(5);
fGlobalElemDecls = new SymbolHash(25);
fGlobalGroupDecls = new SymbolHash(5);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(3);
// Extended tables
fGlobalAttrDeclsExt = new SymbolHash(12);
fGlobalAttrGrpDeclsExt = new SymbolHash(5);
fGlobalElemDeclsExt = new SymbolHash(25);
fGlobalGroupDeclsExt = new SymbolHash(5);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(3);
fGlobalTypeDeclsExt = new SymbolHash(25);
// All global elements table
fAllGlobalElemDecls = new SymbolHash(25);
// if we are parsing S4S, put built-in types in first
// they might get overwritten by the types from S4S, but that's
// considered what the application wants to do.
if (fTargetNamespace == SchemaSymbols.URI_SCHEMAFORSCHEMA) {
fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls.makeClone();
}
else {
fGlobalTypeDecls = new SymbolHash(25);
}
} // <init>(String, XSDDescription)
// Clone an existing schema grammar
public SchemaGrammar(SchemaGrammar grammar) {
fTargetNamespace = grammar.fTargetNamespace;
fGrammarDescription = grammar.fGrammarDescription.makeClone();
//fGrammarDescription.fContextType |= XSDDescription.CONTEXT_COLLISION; // REVISIT
fSymbolTable = grammar.fSymbolTable; // REVISIT
fGlobalAttrDecls = grammar.fGlobalAttrDecls.makeClone();
fGlobalAttrGrpDecls = grammar.fGlobalAttrGrpDecls.makeClone();
fGlobalElemDecls = grammar.fGlobalElemDecls.makeClone();
fGlobalGroupDecls = grammar.fGlobalGroupDecls.makeClone();
fGlobalNotationDecls = grammar.fGlobalNotationDecls.makeClone();
fGlobalIDConstraintDecls = grammar.fGlobalIDConstraintDecls.makeClone();
fGlobalTypeDecls = grammar.fGlobalTypeDecls.makeClone();
// Extended tables
fGlobalAttrDeclsExt = grammar.fGlobalAttrDeclsExt.makeClone();
fGlobalAttrGrpDeclsExt = grammar.fGlobalAttrGrpDeclsExt.makeClone();
fGlobalElemDeclsExt = grammar.fGlobalElemDeclsExt.makeClone();
fGlobalGroupDeclsExt = grammar.fGlobalGroupDeclsExt.makeClone();
fGlobalNotationDeclsExt = grammar.fGlobalNotationDeclsExt.makeClone();
fGlobalIDConstraintDeclsExt = grammar.fGlobalIDConstraintDeclsExt.makeClone();
fGlobalTypeDeclsExt = grammar.fGlobalTypeDeclsExt.makeClone();
// All global elements table
fAllGlobalElemDecls = grammar.fAllGlobalElemDecls.makeClone();
// Annotations associated with the "root" schema of this targetNamespace
fNumAnnotations = grammar.fNumAnnotations;
if (fNumAnnotations > 0) {
fAnnotations = new XSAnnotationImpl[grammar.fAnnotations.length];
System.arraycopy(grammar.fAnnotations, 0, fAnnotations, 0, fNumAnnotations);
}
// All substitution group information declared in this namespace
fSubGroupCount = grammar.fSubGroupCount;
if (fSubGroupCount > 0) {
fSubGroups = new XSElementDecl[grammar.fSubGroups.length];
System.arraycopy(grammar.fSubGroups, 0, fSubGroups, 0, fSubGroupCount);
}
// Array to store complex type decls for constraint checking
fCTCount = grammar.fCTCount;
if (fCTCount > 0) {
fComplexTypeDecls = new XSComplexTypeDecl[grammar.fComplexTypeDecls.length];
fCTLocators = new SimpleLocator[grammar.fCTLocators.length];
System.arraycopy(grammar.fComplexTypeDecls, 0, fComplexTypeDecls, 0, fCTCount);
System.arraycopy(grammar.fCTLocators, 0, fCTLocators, 0, fCTCount);
}
// Groups being redefined by restriction
fRGCount = grammar.fRGCount;
if (fRGCount > 0) {
fRedefinedGroupDecls = new XSGroupDecl[grammar.fRedefinedGroupDecls.length];
fRGLocators = new SimpleLocator[grammar.fRGLocators.length];
System.arraycopy(grammar.fRedefinedGroupDecls, 0, fRedefinedGroupDecls, 0, fRGCount);
System.arraycopy(grammar.fRGLocators, 0, fRGLocators, 0, fRGCount/2);
}
// List of imported grammars
if (grammar.fImported != null) {
fImported = new ArrayList<>();
for (int i=0; i<grammar.fImported.size(); i++) {
fImported.add(grammar.fImported.get(i));
}
}
// Locations
if (grammar.fLocations != null) {
for (int k=0; k<grammar.fLocations.size(); k++) {
addDocument(null, grammar.fLocations.get(k));
}
}
} // <init>(String, XSDDescription)
// number of built-in XSTypes we need to create for base and full
// datatype set
private static final int BASICSET_COUNT = 29;
private static final int FULLSET_COUNT = 46;
private static final int GRAMMAR_XS = 1;
private static final int GRAMMAR_XSI = 2;
// this class makes sure the static, built-in schema grammars
// are immutable.
public static class BuiltinSchemaGrammar extends SchemaGrammar {
private static final String EXTENDED_SCHEMA_FACTORY_CLASS = "com.sun.org.apache.xerces.internal.impl.dv.xs.ExtendedSchemaDVFactoryImpl";
/**
* Special constructor to create the grammars for the schema namespaces
*
* @param grammar
*/
public BuiltinSchemaGrammar(int grammar, short schemaVersion) {
SchemaDVFactory schemaFactory;
if (schemaVersion == Constants.SCHEMA_VERSION_1_0) {
schemaFactory = SchemaDVFactory.getInstance();
}
else {
schemaFactory = SchemaDVFactory.getInstance(EXTENDED_SCHEMA_FACTORY_CLASS);
}
if (grammar == GRAMMAR_XS) {
// target namespace
fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA);
// no global decls other than types
fGlobalAttrDecls = new SymbolHash(1);
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(1);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(1);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// all global element decls table
fAllGlobalElemDecls = new SymbolHash(1);
// get all built-in types
fGlobalTypeDecls = schemaFactory.getBuiltInTypes();
// assign the built-in schema grammar as the XSNamespaceItem
// for each of the built-in simple type definitions.
int length = fGlobalTypeDecls.getLength();
XSTypeDefinition [] typeDefinitions = new XSTypeDefinition[length];
fGlobalTypeDecls.getValues(typeDefinitions, 0);
for (int i = 0; i < length; ++i) {
XSTypeDefinition xtd = typeDefinitions[i];
if (xtd instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) xtd).setNamespaceItem(this);
}
}
// add anyType
fGlobalTypeDecls.put(fAnyType.getName(), fAnyType);
}
else if (grammar == GRAMMAR_XSI) {
// target namespace
fTargetNamespace = SchemaSymbols.URI_XSI;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_XSI);
// no global decls other than attributes
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(1);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
fGlobalTypeDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(1);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// no all global element decls
fAllGlobalElemDecls = new SymbolHash(1);
// 4 attributes, so initialize the size as 4*2 = 8
fGlobalAttrDecls = new SymbolHash(8);
String name = null;
String tns = null;
XSSimpleType type = null;
short scope = XSConstants.SCOPE_GLOBAL;
// xsi:type
name = SchemaSymbols.XSI_TYPE;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_QNAME);
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
// xsi:nil
name = SchemaSymbols.XSI_NIL;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_BOOLEAN);
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
XSSimpleType anyURI = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_ANYURI);
// xsi:schemaLocation
name = SchemaSymbols.XSI_SCHEMALOCATION;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.createTypeList("#AnonType_schemaLocation", SchemaSymbols.URI_XSI, (short)0, anyURI, null);
if (type instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl)type).setAnonymous(true);
}
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
// xsi:noNamespaceSchemaLocation
name = SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION;
tns = SchemaSymbols.URI_XSI;
type = anyURI;
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
}
} // <init>(int)
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription.makeClone();
} // getGrammarDescription(): XMLGrammarDescription
// override these methods solely so that these
// objects cannot be modified once they're created.
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl, String location) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
// ignore
}
public void addGlobalElementDeclAll(XSElementDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
// ignore
}
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
// ignore
}
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
// ignore
}
public synchronized void addDocument(Object document, String location) {
// ignore
}
// annotation support
synchronized DOMParser getDOMParser() {
return null;
}
synchronized SAXParser getSAXParser() {
return null;
}
}
/**
* <p>A partial schema for schemas for validating annotations.</p>
*
* @xerces.internal
*
* @author Michael Glavassevich, IBM
*/
public static final class Schema4Annotations extends SchemaGrammar {
/**
* Singleton instance.
*/
public static final Schema4Annotations INSTANCE = new Schema4Annotations();
/**
* Special constructor to create a schema
* capable of validating annotations.
*/
private Schema4Annotations() {
// target namespace
fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA);
// no global decls other than types and
// element declarations for <annotation>, <documentation> and <appinfo>.
fGlobalAttrDecls = new SymbolHash(1);
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(6);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(6);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// all global element declarations
fAllGlobalElemDecls = new SymbolHash(6);
// get all built-in types
fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls;
// create element declarations for <annotation>, <documentation> and <appinfo>
XSElementDecl annotationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_ANNOTATION);
XSElementDecl documentationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_DOCUMENTATION);
XSElementDecl appinfoDecl = createAnnotationElementDecl(SchemaSymbols.ELT_APPINFO);
// add global element declarations
fGlobalElemDecls.put(annotationDecl.fName, annotationDecl);
fGlobalElemDecls.put(documentationDecl.fName, documentationDecl);
fGlobalElemDecls.put(appinfoDecl.fName, appinfoDecl);
fGlobalElemDeclsExt.put(","+annotationDecl.fName, annotationDecl);
fGlobalElemDeclsExt.put(","+documentationDecl.fName, documentationDecl);
fGlobalElemDeclsExt.put(","+appinfoDecl.fName, appinfoDecl);
fAllGlobalElemDecls.put(annotationDecl, annotationDecl);
fAllGlobalElemDecls.put(documentationDecl, documentationDecl);
fAllGlobalElemDecls.put(appinfoDecl, appinfoDecl);
// create complex type declarations for <annotation>, <documentation> and <appinfo>
XSComplexTypeDecl annotationType = new XSComplexTypeDecl();
XSComplexTypeDecl documentationType = new XSComplexTypeDecl();
XSComplexTypeDecl appinfoType = new XSComplexTypeDecl();
// set the types on their element declarations
annotationDecl.fType = annotationType;
documentationDecl.fType = documentationType;
appinfoDecl.fType = appinfoType;
// create attribute groups for <annotation>, <documentation> and <appinfo>
XSAttributeGroupDecl annotationAttrs = new XSAttributeGroupDecl();
XSAttributeGroupDecl documentationAttrs = new XSAttributeGroupDecl();
XSAttributeGroupDecl appinfoAttrs = new XSAttributeGroupDecl();
// fill in attribute groups
{
// create and fill attribute uses for <annotation>, <documentation> and <appinfo>
XSAttributeUseImpl annotationIDAttr = new XSAttributeUseImpl();
annotationIDAttr.fAttrDecl = new XSAttributeDecl();
annotationIDAttr.fAttrDecl.setValues(SchemaSymbols.ATT_ID, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ID),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, annotationType, null);
annotationIDAttr.fUse = SchemaSymbols.USE_OPTIONAL;
annotationIDAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl documentationSourceAttr = new XSAttributeUseImpl();
documentationSourceAttr.fAttrDecl = new XSAttributeDecl();
documentationSourceAttr.fAttrDecl.setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ANYURI),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, documentationType, null);
documentationSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL;
documentationSourceAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl documentationLangAttr = new XSAttributeUseImpl();
documentationLangAttr.fAttrDecl = new XSAttributeDecl();
documentationLangAttr.fAttrDecl.setValues("lang".intern(), NamespaceContext.XML_URI, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_LANGUAGE),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, documentationType, null);
documentationLangAttr.fUse = SchemaSymbols.USE_OPTIONAL;
documentationLangAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl appinfoSourceAttr = new XSAttributeUseImpl();
appinfoSourceAttr.fAttrDecl = new XSAttributeDecl();
appinfoSourceAttr.fAttrDecl.setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ANYURI),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, appinfoType, null);
appinfoSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL;
appinfoSourceAttr.fConstraintType = XSConstants.VC_NONE;
// create lax attribute wildcard for <annotation>, <documentation> and <appinfo>
XSWildcardDecl otherAttrs = new XSWildcardDecl();
otherAttrs.fNamespaceList = new String [] {fTargetNamespace, null};
otherAttrs.fType = XSWildcard.NSCONSTRAINT_NOT;
otherAttrs.fProcessContents = XSWildcard.PC_LAX;
// add attribute uses and wildcards to attribute groups for <annotation>, <documentation> and <appinfo>
annotationAttrs.addAttributeUse(annotationIDAttr);
annotationAttrs.fAttributeWC = otherAttrs;
documentationAttrs.addAttributeUse(documentationSourceAttr);
documentationAttrs.addAttributeUse(documentationLangAttr);
documentationAttrs.fAttributeWC = otherAttrs;
appinfoAttrs.addAttributeUse(appinfoSourceAttr);
appinfoAttrs.fAttributeWC = otherAttrs;
}
// create particles for <annotation>
XSParticleDecl annotationParticle = createUnboundedModelGroupParticle();
{
XSModelGroupImpl annotationChoice = new XSModelGroupImpl();
annotationChoice.fCompositor = XSModelGroupImpl.MODELGROUP_CHOICE;
annotationChoice.fParticleCount = 2;
annotationChoice.fParticles = new XSParticleDecl[2];
annotationChoice.fParticles[0] = createChoiceElementParticle(appinfoDecl);
annotationChoice.fParticles[1] = createChoiceElementParticle(documentationDecl);
annotationParticle.fValue = annotationChoice;
}
// create wildcard particle for <documentation> and <appinfo>
XSParticleDecl anyWCSequenceParticle = createUnboundedAnyWildcardSequenceParticle();
// fill complex types
annotationType.setValues("#AnonType_" + SchemaSymbols.ELT_ANNOTATION, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_ELEMENT, false, annotationAttrs, null, annotationParticle, XSObjectListImpl.EMPTY_LIST);
annotationType.setName("#AnonType_" + SchemaSymbols.ELT_ANNOTATION);
annotationType.setIsAnonymous();
documentationType.setValues("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_MIXED, false, documentationAttrs, null, anyWCSequenceParticle, XSObjectListImpl.EMPTY_LIST);
documentationType.setName("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION);
documentationType.setIsAnonymous();
appinfoType.setValues("#AnonType_" + SchemaSymbols.ELT_APPINFO, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_MIXED, false, appinfoAttrs, null, anyWCSequenceParticle, XSObjectListImpl.EMPTY_LIST);
appinfoType.setName("#AnonType_" + SchemaSymbols.ELT_APPINFO);
appinfoType.setIsAnonymous();
} // <init>(int)
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription.makeClone();
} // getGrammarDescription(): XMLGrammarDescription
// override these methods solely so that these
// objects cannot be modified once they're created.
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
// ignore
}
public void addGlobalElementDeclAll(XSElementDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
// ignore
}
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
// ignore
}
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
// ignore
}
public synchronized void addDocument(Object document, String location) {
// ignore
}
// annotation support
synchronized DOMParser getDOMParser() {
return null;
}
synchronized SAXParser getSAXParser() {
return null;
}
//
// private helper methods
//
private XSElementDecl createAnnotationElementDecl(String localName) {
XSElementDecl eDecl = new XSElementDecl();
eDecl.fName = localName;
eDecl.fTargetNamespace = fTargetNamespace;
eDecl.setIsGlobal();
eDecl.fBlock = (XSConstants.DERIVATION_EXTENSION |
XSConstants.DERIVATION_RESTRICTION | XSConstants.DERIVATION_SUBSTITUTION);
eDecl.setConstraintType(XSConstants.VC_NONE);
return eDecl;
}
private XSParticleDecl createUnboundedModelGroupParticle() {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 0;
particle.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED;
particle.fType = XSParticleDecl.PARTICLE_MODELGROUP;
return particle;
}
private XSParticleDecl createChoiceElementParticle(XSElementDecl ref) {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 1;
particle.fMaxOccurs = 1;
particle.fType = XSParticleDecl.PARTICLE_ELEMENT;
particle.fValue = ref;
return particle;
}
private XSParticleDecl createUnboundedAnyWildcardSequenceParticle() {
XSParticleDecl particle = createUnboundedModelGroupParticle();
XSModelGroupImpl sequence = new XSModelGroupImpl();
sequence.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE;
sequence.fParticleCount = 1;
sequence.fParticles = new XSParticleDecl[1];
sequence.fParticles[0] = createAnyLaxWildcardParticle();
particle.fValue = sequence;
return particle;
}
private XSParticleDecl createAnyLaxWildcardParticle() {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 1;
particle.fMaxOccurs = 1;
particle.fType = XSParticleDecl.PARTICLE_WILDCARD;
XSWildcardDecl anyWC = new XSWildcardDecl();
anyWC.fNamespaceList = null;
anyWC.fType = XSWildcard.NSCONSTRAINT_ANY;
anyWC.fProcessContents = XSWildcard.PC_LAX;
particle.fValue = anyWC;
return particle;
}
}
// Grammar methods
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription;
} // getGrammarDescription(): XMLGrammarDescription
// DTDGrammar methods
public boolean isNamespaceAware () {
return true;
} // isNamespaceAware():boolean
List<SchemaGrammar> fImported = null;
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
fImported = importedGrammars;
}
public List<SchemaGrammar> getImportedGrammars() {
return fImported;
}
/**
* Returns this grammar's target namespace.
*/
public final String getTargetNamespace() {
return fTargetNamespace;
} // getTargetNamespace():String
/**
* register one global attribute
*/
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
fGlobalAttrDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalAttributeDecl(XSAttributeDecl decl, String location) {
fGlobalAttrDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global attribute group
*/
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
fGlobalAttrGrpDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
fGlobalAttrGrpDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global element
*/
public void addGlobalElementDeclAll(XSElementDecl decl) {
if (fAllGlobalElemDecls.get(decl) == null) {
fAllGlobalElemDecls.put(decl, decl);
// if there is a substitution group affiliation, store in an array,
// for further constraint checking: UPA, PD, EDC
if (decl.fSubGroup != null) {
if (fSubGroupCount == fSubGroups.length)
fSubGroups = resize(fSubGroups, fSubGroupCount+INC_SIZE);
fSubGroups[fSubGroupCount++] = decl;
}
}
}
public void addGlobalElementDecl(XSElementDecl decl) {
fGlobalElemDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
fGlobalElemDeclsExt.put(((location != null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global group
*/
public void addGlobalGroupDecl(XSGroupDecl decl) {
fGlobalGroupDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
fGlobalGroupDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global notation
*/
public void addGlobalNotationDecl(XSNotationDecl decl) {
fGlobalNotationDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
fGlobalNotationDeclsExt.put(((location!=null) ? location : "") + "," +decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global type
*/
public void addGlobalTypeDecl(XSTypeDefinition decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
if (decl instanceof XSComplexTypeDecl) {
((XSComplexTypeDecl) decl).setNamespaceItem(this);
}
else if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
fGlobalTypeDeclsExt.put(((location!=null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null) {
if (decl instanceof XSComplexTypeDecl) {
((XSComplexTypeDecl) decl).setNamespaceItem(this);
}
else if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
}
/**
* register one global complex type
*/
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
decl.setNamespaceItem(this);
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
fGlobalTypeDeclsExt.put(((location!=null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global simple type
*/
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
fGlobalTypeDeclsExt.put(((location != null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null && decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
/**
* register one identity constraint
*/
public final void addIDConstraintDecl(XSElementDecl elmDecl, [MASK] decl) {
elmDecl.addIDConstraint(decl);
fGlobalIDConstraintDecls.put(decl.get [MASK] Name(), decl);
}
public final void addIDConstraintDecl(XSElementDecl elmDecl, [MASK] decl, String location) {
fGlobalIDConstraintDeclsExt.put(((location != null) ? location : "") + "," + decl.get [MASK] Name(), decl);
}
/**
* get one global attribute
*/
public final XSAttributeDecl getGlobalAttributeDecl(String declName) {
return(XSAttributeDecl)fGlobalAttrDecls.get(declName);
}
public final XSAttributeDecl getGlobalAttributeDecl(String declName, String location) {
return(XSAttributeDecl)fGlobalAttrDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global attribute group
*/
public final XSAttributeGroupDecl getGlobalAttributeGroupDecl(String declName) {
return(XSAttributeGroupDecl)fGlobalAttrGrpDecls.get(declName);
}
public final XSAttributeGroupDecl getGlobalAttributeGroupDecl(String declName, String location) {
return(XSAttributeGroupDecl)fGlobalAttrGrpDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global element
*/
public final XSElementDecl getGlobalElementDecl(String declName) {
return(XSElementDecl)fGlobalElemDecls.get(declName);
}
public final XSElementDecl getGlobalElementDecl(String declName, String location) {
return(XSElementDecl)fGlobalElemDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global group
*/
public final XSGroupDecl getGlobalGroupDecl(String declName) {
return(XSGroupDecl)fGlobalGroupDecls.get(declName);
}
public final XSGroupDecl getGlobalGroupDecl(String declName, String location) {
return(XSGroupDecl)fGlobalGroupDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global notation
*/
public final XSNotationDecl getGlobalNotationDecl(String declName) {
return(XSNotationDecl)fGlobalNotationDecls.get(declName);
}
public final XSNotationDecl getGlobalNotationDecl(String declName, String location) {
return(XSNotationDecl)fGlobalNotationDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global type
*/
public final XSTypeDefinition getGlobalTypeDecl(String declName) {
return(XSTypeDefinition)fGlobalTypeDecls.get(declName);
}
public final XSTypeDefinition getGlobalTypeDecl(String declName, String location) {
return(XSTypeDefinition)fGlobalTypeDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one identity constraint
*/
public final [MASK] getIDConstraintDecl(String declName) {
return( [MASK] )fGlobalIDConstraintDecls.get(declName);
}
public final [MASK] getIDConstraintDecl(String declName, String location) {
return( [MASK] )fGlobalIDConstraintDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one identity constraint
*/
public final boolean hasIDConstraints() {
return fGlobalIDConstraintDecls.getLength() > 0;
}
// array to store complex type decls
private static final int INITIAL_SIZE = 16;
private static final int INC_SIZE = 16;
private int fCTCount = 0;
private XSComplexTypeDecl[] fComplexTypeDecls = new XSComplexTypeDecl[INITIAL_SIZE];
private SimpleLocator[] fCTLocators = new SimpleLocator[INITIAL_SIZE];
// an array to store groups being redefined by restriction
// even-numbered elements are the derived groups, odd-numbered ones their bases
private static final int REDEFINED_GROUP_INIT_SIZE = 2;
private int fRGCount = 0;
private XSGroupDecl[] fRedefinedGroupDecls = new XSGroupDecl[REDEFINED_GROUP_INIT_SIZE];
private SimpleLocator[] fRGLocators = new SimpleLocator[REDEFINED_GROUP_INIT_SIZE/2];
// a flag to indicate whether we have checked the 3 constraints on this
// grammar.
boolean fFullChecked = false;
/**
* add one complex type decl: for later constraint checking
*/
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
if (fCTCount == fComplexTypeDecls.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount+INC_SIZE);
fCTLocators = resize(fCTLocators, fCTCount+INC_SIZE);
}
fCTLocators[fCTCount] = locator;
fComplexTypeDecls[fCTCount++] = decl;
}
/**
* add a group redefined by restriction: for later constraint checking
*/
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
if (fRGCount == fRedefinedGroupDecls.length) {
// double array size each time.
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount << 1);
fRGLocators = resize(fRGLocators, fRGCount);
}
fRGLocators[fRGCount/2] = locator;
fRedefinedGroupDecls[fRGCount++] = derived;
fRedefinedGroupDecls[fRGCount++] = base;
}
/**
* get all complex type decls: for later constraint checking
*/
final XSComplexTypeDecl[] getUncheckedComplexTypeDecls() {
if (fCTCount < fComplexTypeDecls.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
return fComplexTypeDecls;
}
/**
* get the error locator of all complex type decls
*/
final SimpleLocator[] getUncheckedCTLocators() {
if (fCTCount < fCTLocators.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
return fCTLocators;
}
/**
* get all redefined groups: for later constraint checking
*/
final XSGroupDecl[] getRedefinedGroupDecls() {
if (fRGCount < fRedefinedGroupDecls.length) {
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount);
fRGLocators = resize(fRGLocators, fRGCount/2);
}
return fRedefinedGroupDecls;
}
/**
* get the error locator of all redefined groups
*/
final SimpleLocator[] getRGLocators() {
if (fRGCount < fRedefinedGroupDecls.length) {
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount);
fRGLocators = resize(fRGLocators, fRGCount/2);
}
return fRGLocators;
}
/**
* after the first-round checking, some types don't need to be checked
* against UPA again. here we trim the array to the proper size.
*/
final void setUncheckedTypeNum(int newSize) {
fCTCount = newSize;
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
// used to store all substitution group information declared in
// this namespace
private int fSubGroupCount = 0;
private XSElementDecl[] fSubGroups = new XSElementDecl[INITIAL_SIZE];
/**
* get all substitution group information: for the 3 constraint checking
*/
final XSElementDecl[] getSubstitutionGroups() {
if (fSubGroupCount < fSubGroups.length)
fSubGroups = resize(fSubGroups, fSubGroupCount);
return fSubGroups;
}
// anyType and anySimpleType: because there are so many places where
// we need direct access to these two types
public final static XSComplexTypeDecl fAnyType = new XSAnyType();
private static class XSAnyType extends XSComplexTypeDecl {
public XSAnyType () {
fName = SchemaSymbols.ATTVAL_ANYTYPE;
super.fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
fBaseType = this;
fDerivedBy = XSConstants.DERIVATION_RESTRICTION;
fContentType = XSComplexTypeDecl.CONTENTTYPE_MIXED;
fParticle = createParticle();
fAttrGrp = createAttrGrp();
}
// overridden methods
public void setValues(String name, String targetNamespace,
XSTypeDefinition baseType, short derivedBy, short schemaFinal,
short block, short contentType,
boolean isAbstract, XSAttributeGroupDecl attrGrp,
XSSimpleType simpleType, XSParticleDecl particle) {
// don't allow this.
}
public void setName(String name){
// don't allow this.
}
public void setIsAbstractType() {
// null implementation
}
public void setContainsTypeID() {
// null implementation
}
public void setIsAnonymous() {
// null implementation
}
public void reset() {
// null implementation
}
public XSObjectList getAnnotations() {
return XSObjectListImpl.EMPTY_LIST;
}
public XSNamespaceItem getNamespaceItem() {
return SG_SchemaNS;
}
private XSAttributeGroupDecl createAttrGrp() {
XSWildcardDecl wildcard = new XSWildcardDecl();
wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
XSAttributeGroupDecl attrGrp = new XSAttributeGroupDecl();
attrGrp.fAttributeWC = wildcard;
return attrGrp;
}
private XSParticleDecl createParticle() {
// the wildcard used in anyType (content and attribute)
// the spec will change strict to skip for anyType
XSWildcardDecl wildcard = new XSWildcardDecl();
wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
// the particle for the content wildcard
XSParticleDecl particleW = new XSParticleDecl();
particleW.fMinOccurs = 0;
particleW.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED;
particleW.fType = XSParticleDecl.PARTICLE_WILDCARD;
particleW.fValue = wildcard;
// the model group of a sequence of the above particle
XSModelGroupImpl group = new XSModelGroupImpl();
group.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE;
group.fParticleCount = 1;
group.fParticles = new XSParticleDecl[1];
group.fParticles[0] = particleW;
// the content of anyType: particle of the above model group
XSParticleDecl particleG = new XSParticleDecl();
particleG.fType = XSParticleDecl.PARTICLE_MODELGROUP;
particleG.fValue = group;
return particleG;
}
}
private static class BuiltinAttrDecl extends XSAttributeDecl {
public BuiltinAttrDecl(String name, String tns,
XSSimpleType type, short scope) {
fName = name;
super.fTargetNamespace = tns;
fType = type;
fScope = scope;
}
public void setValues(String name, String targetNamespace,
XSSimpleType simpleType, short constraintType, short scope,
ValidatedInfo valInfo, XSComplexTypeDecl enclosingCT) {
// ignore this call.
}
public void reset () {
// also ignore this call.
}
public XSAnnotation getAnnotation() {
return null;
}
public XSNamespaceItem getNamespaceItem() {
return SG_XSI;
}
} // class BuiltinAttrDecl
// the grammars to hold components of the schema namespace
public final static BuiltinSchemaGrammar SG_SchemaNS = new BuiltinSchemaGrammar(GRAMMAR_XS, Constants.SCHEMA_VERSION_1_0);
private final static BuiltinSchemaGrammar SG_SchemaNSExtended = new BuiltinSchemaGrammar(GRAMMAR_XS, Constants.SCHEMA_VERSION_1_0_EXTENDED);
public final static XSSimpleType fAnySimpleType = (XSSimpleType)SG_SchemaNS.getGlobalTypeDecl(SchemaSymbols.ATTVAL_ANYSIMPLETYPE);
// the grammars to hold components of the schema-instance namespace
public final static BuiltinSchemaGrammar SG_XSI = new BuiltinSchemaGrammar(GRAMMAR_XSI, Constants.SCHEMA_VERSION_1_0);
public static SchemaGrammar getS4SGrammar(short schemaVersion) {
if (schemaVersion == Constants.SCHEMA_VERSION_1_0) {
return SG_SchemaNS;
}
else {
return SG_SchemaNSExtended;
}
}
static final XSComplexTypeDecl[] resize(XSComplexTypeDecl[] oldArray, int newSize) {
XSComplexTypeDecl[] newArray = new XSComplexTypeDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final XSGroupDecl[] resize(XSGroupDecl[] oldArray, int newSize) {
XSGroupDecl[] newArray = new XSGroupDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final XSElementDecl[] resize(XSElementDecl[] oldArray, int newSize) {
XSElementDecl[] newArray = new XSElementDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final SimpleLocator[] resize(SimpleLocator[] oldArray, int newSize) {
SimpleLocator[] newArray = new SimpleLocator[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
// XSNamespaceItem methods
// the max index / the max value of XSObject type
private static final short MAX_COMP_IDX = XSTypeDefinition.SIMPLE_TYPE;
private static final boolean[] GLOBAL_COMP = {false, // null
true, // attribute
true, // element
true, // type
false, // attribute use
true, // attribute group
true, // group
false, // model group
false, // particle
false, // wildcard
true, // idc
true, // notation
false, // annotation
false, // facet
false, // multi value facet
true, // complex type
true // simple type
};
// store a certain kind of components from all namespaces
private XSNamedMap[] fComponents = null;
private ObjectList[] fComponentsExt = null;
// store the documents and their locations contributing to this namespace
// REVISIT: use StringList and XSObjectList for there fields.
// fDocuments is never used
private List<Object> fDocuments = null;
private List<String> fLocations = null;
public synchronized void addDocument(Object document, String location) {
if (fDocuments == null) {
// Parsing schema is not thread safe, synchronized may be removed
fDocuments = new CopyOnWriteArrayList<>();
fLocations = new CopyOnWriteArrayList<>();
}
fDocuments.add(document);
fLocations.add(location);
}
public synchronized void removeDocument(int index) {
if (fDocuments != null &&
index >= 0 &&
index < fDocuments.size()) {
fDocuments.remove(index);
fLocations.remove(index);
}
}
/**
* [schema namespace]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#nsi-schema_namespace">[schema namespace]</a>
* @return The target namespace of this item.
*/
public String getSchemaNamespace() {
return fTargetNamespace;
}
// annotation support
synchronized DOMParser getDOMParser() {
if (fDOMParser != null) {
DOMParser parser = fDOMParser.get();
if (parser != null) {
return parser;
}
}
// REVISIT: when schema handles XML 1.1, will need to
// revisit this (and the practice of not prepending an XML decl to the annotation string
XML11Configuration config = new XML11Configuration(fSymbolTable);
// note that this should never produce errors or require
// entity resolution, so just a barebones configuration with
// a couple of feature set will do fine
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true);
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false);
DOMParser parser = new DOMParser(config);
try {
parser.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.DEFER_NODE_EXPANSION_FEATURE, false);
}
catch (SAXException exc) {}
fDOMParser = new SoftReference<DOMParser>(parser);
return parser;
}
synchronized SAXParser getSAXParser() {
if (fSAXParser != null) {
SAXParser parser = fSAXParser.get();
if (parser != null) {
return parser;
}
}
// REVISIT: when schema handles XML 1.1, will need to
// revisit this (and the practice of not prepending an XML decl to the annotation string
XML11Configuration config = new XML11Configuration(fSymbolTable);
// note that this should never produce errors or require
// entity resolution, so just a barebones configuration with
// a couple of feature set will do fine
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true);
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false);
SAXParser parser = new SAXParser(config);
fSAXParser = new SoftReference<SAXParser>(parser);
return parser;
}
/**
* [schema components]: a list of top-level components, i.e. element
* declarations, attribute declarations, etc.
* @param objectType The type of the declaration, i.e.
* <code>ELEMENT_DECLARATION</code>. Note that
* <code>XSTypeDefinition.SIMPLE_TYPE</code> and
* <code>XSTypeDefinition.COMPLEX_TYPE</code> can also be used as the
* <code>objectType</code> to retrieve only complex types or simple
* types, instead of all types.
* @return A list of top-level definition of the specified type in
* <code>objectType</code> or an empty <code>XSNamedMap</code> if no
* such definitions exist.
*/
public synchronized XSNamedMap getComponents(short objectType) {
if (objectType <= 0 || objectType > MAX_COMP_IDX ||
!GLOBAL_COMP[objectType]) {
return XSNamedMapImpl.EMPTY_MAP;
}
if (fComponents == null)
fComponents = new XSNamedMap[MAX_COMP_IDX+1];
// get the hashtable for this type of components
if (fComponents[objectType] == null) {
SymbolHash table = null;
switch (objectType) {
case XSConstants.TYPE_DEFINITION:
case XSTypeDefinition.COMPLEX_TYPE:
case XSTypeDefinition.SIMPLE_TYPE:
table = fGlobalTypeDecls;
break;
case XSConstants.ATTRIBUTE_DECLARATION:
table = fGlobalAttrDecls;
break;
case XSConstants.ELEMENT_DECLARATION:
table = fGlobalElemDecls;
break;
case XSConstants.ATTRIBUTE_GROUP:
table = fGlobalAttrGrpDecls;
break;
case XSConstants.MODEL_GROUP_DEFINITION:
table = fGlobalGroupDecls;
break;
case XSConstants.NOTATION_DECLARATION:
table = fGlobalNotationDecls;
break;
case XSConstants.IDENTITY_CONSTRAINT:
table = this.fGlobalIDConstraintDecls;
break;
}
// for complex/simple types, create a special implementation,
// which take specific types out of the hash table
if (objectType == XSTypeDefinition.COMPLEX_TYPE ||
objectType == XSTypeDefinition.SIMPLE_TYPE) {
fComponents[objectType] = new XSNamedMap4Types(fTargetNamespace, table, objectType);
}
else {
fComponents[objectType] = new XSNamedMapImpl(fTargetNamespace, table);
}
}
return fComponents[objectType];
}
public synchronized ObjectList getComponentsExt(short objectType) {
if (objectType <= 0 || objectType > MAX_COMP_IDX ||
!GLOBAL_COMP[objectType]) {
return ObjectListImpl.EMPTY_LIST;
}
if (fComponentsExt == null)
fComponentsExt = new ObjectList[MAX_COMP_IDX+1];
// get the hashtable for this type of components
if (fComponentsExt[objectType] == null) {
SymbolHash table = null;
switch (objectType) {
case XSConstants.TYPE_DEFINITION:
case XSTypeDefinition.COMPLEX_TYPE:
case XSTypeDefinition.SIMPLE_TYPE:
table = fGlobalTypeDeclsExt;
break;
case XSConstants.ATTRIBUTE_DECLARATION:
table = fGlobalAttrDeclsExt;
break;
case XSConstants.ELEMENT_DECLARATION:
table = fGlobalElemDeclsExt;
break;
case XSConstants.ATTRIBUTE_GROUP:
table = fGlobalAttrGrpDeclsExt;
break;
case XSConstants.MODEL_GROUP_DEFINITION:
table = fGlobalGroupDeclsExt;
break;
case XSConstants.NOTATION_DECLARATION:
table = fGlobalNotationDeclsExt;
break;
case XSConstants.IDENTITY_CONSTRAINT:
table = this.fGlobalIDConstraintDeclsExt;
break;
}
Object[] entries = table.getEntries();
fComponentsExt[objectType] = new ObjectListImpl(entries, entries.length);
}
return fComponentsExt[objectType];
}
public synchronized void resetComponents() {
fComponents = null;
fComponentsExt = null;
}
/**
* Convenience method. Returns a top-level simple or complex type
* definition.
* @param name The name of the definition.
* @return An <code>XSTypeDefinition</code> or null if such definition
* does not exist.
*/
public XSTypeDefinition getTypeDefinition(String name) {
return getGlobalTypeDecl(name);
}
/**
* Convenience method. Returns a top-level attribute declaration.
* @param name The name of the declaration.
* @return A top-level attribute declaration or null if such declaration
* does not exist.
*/
public XSAttributeDeclaration getAttributeDeclaration(String name) {
return getGlobalAttributeDecl(name);
}
/**
* Convenience method. Returns a top-level element declaration.
* @param name The name of the declaration.
* @return A top-level element declaration or null if such declaration
* does not exist.
*/
public XSElementDeclaration getElementDeclaration(String name) {
return getGlobalElementDecl(name);
}
/**
* Convenience method. Returns a top-level attribute group definition.
* @param name The name of the definition.
* @return A top-level attribute group definition or null if such
* definition does not exist.
*/
public XSAttributeGroupDefinition getAttributeGroup(String name) {
return getGlobalAttributeGroupDecl(name);
}
/**
* Convenience method. Returns a top-level model group definition.
*
* @param name The name of the definition.
* @return A top-level model group definition definition or null if such
* definition does not exist.
*/
public XSModelGroupDefinition getModelGroupDefinition(String name) {
return getGlobalGroupDecl(name);
}
/**
* Convenience method. Returns a top-level notation declaration.
*
* @param name The name of the declaration.
* @return A top-level notation declaration or null if such declaration
* does not exist.
*/
public XSNotationDeclaration getNotationDeclaration(String name) {
return getGlobalNotationDecl(name);
}
public XSIDCDefinition getIDCDefinition(String name) {
return getIDConstraintDecl(name);
}
/**
* [document location]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#sd-document_location">[document location]</a>
* @return a list of document information item
*/
public StringList getDocumentLocations() {
return new StringListImpl(fLocations);
}
/**
* Return an <code>XSModel</code> that represents components in this schema
* grammar.
*
* @return an <code>XSModel</code> representing this schema grammar
*/
public XSModel toXSModel() {
return new XSModelImpl(new SchemaGrammar[]{this});
}
public XSModel toXSModel(XSGrammar[] grammars) {
if (grammars == null || grammars.length == 0)
return toXSModel();
int len = grammars.length;
boolean hasSelf = false;
for (int i = 0; i < len; i++) {
if (grammars[i] == this) {
hasSelf = true;
break;
}
}
SchemaGrammar[] gs = new SchemaGrammar[hasSelf ? len : len+1];
for (int i = 0; i < len; i++)
gs[i] = (SchemaGrammar)grammars[i];
if (!hasSelf)
gs[len] = this;
return new XSModelImpl(gs);
}
/**
* @see org.apache.xerces.xs.XSNamespaceItem#getAnnotations()
*/
public XSObjectList getAnnotations() {
if (fNumAnnotations == 0) {
return XSObjectListImpl.EMPTY_LIST;
}
return new XSObjectListImpl(fAnnotations, fNumAnnotations);
}
public void addAnnotation(XSAnnotationImpl annotation) {
if (annotation == null) {
return;
}
if (fAnnotations == null) {
fAnnotations = new XSAnnotationImpl[2];
}
else if (fNumAnnotations == fAnnotations.length) {
XSAnnotationImpl[] newArray = new XSAnnotationImpl[fNumAnnotations << 1];
System.arraycopy(fAnnotations, 0, newArray, 0, fNumAnnotations);
fAnnotations = newArray;
}
fAnnotations[fNumAnnotations++] = annotation;
}
public void setImmutable(boolean isImmutable) {
fIsImmutable = isImmutable;
}
public boolean isImmutable() {
return fIsImmutable;
}
} // class SchemaGrammar
| IdentityConstraint |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry [MASK] ) throws IOException {
prepareStoredEntry(details.open(), [MASK] );
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
[MASK] .setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry [MASK] ) throws IOException {
new CrcAndSize(input).setUpStoredEntry( [MASK] );
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| archiveEntry |
/*
* Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.hosted;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.stream.Collectors;
import org.graalvm.nativeimage.hosted.RuntimeReflection;
import org.graalvm.nativeimage.hosted.RuntimeResourceAccess;
import com.oracle.svm.core.feature.AutomaticallyRegisteredFeature;
import com.oracle.svm.core.feature.InternalFeature;
import com.oracle.svm.core.jdk.ServiceCatalogSupport;
import com.oracle.svm.core.option.AccumulatingLocatableMultiOptionValue;
import com.oracle.svm.core.option.HostedOptionKey;
import com.oracle.svm.hosted.analysis.Inflation;
import jdk.graal.compiler.options.Option;
import jdk.graal.compiler.options.OptionType;
/**
* Support for {@link ServiceLoader} on Substrate VM.
*
* Services are registered in the folder {@code "META-INF/services/"} using files whose name is the
* fully qualified service interface name. We do not know which services are going to be used by a
* native image: The parameter of {@code ServiceLoader#load} is often but not always a compile-time
* constant that we can track. But we also cannot put all registered services into the native image.
*
* We therefore use the following heuristic: We add all service loader files and service
* implementation classes when the service interfaces that are seen as reachable by the static
* analysis.
*
* Each used service implementation class is added for reflection (using
* {@link org.graalvm.nativeimage.hosted.RuntimeReflection#register(Class[])}) and for reflective
* instantiation (using {@link RuntimeReflection#registerForReflectiveInstantiation(Class[])}).
*
* For each service interface, a single service loader file is added as a resource to the image. The
* single file combines all the individual files that can come from different .jar files.
*/
@AutomaticallyRegisteredFeature
public class ServiceLoaderFeature implements InternalFeature {
public static class Options {
@Option(help = "Automatically register services for run-time lookup using ServiceLoader", type = OptionType.Expert) //
public static final HostedOptionKey<Boolean> UseServiceLoaderFeature = new HostedOptionKey<>(true);
@Option(help = "Comma-separated list of services that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServices = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
@Option(help = "Comma-separated list of service providers that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServiceProviders = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
}
private static final Set<String> SKIPPED_SERVICES = Set.of(
// image builder internal ServiceLoader interfaces
"com.oracle.svm.hosted.NativeImageClassLoaderPostProcessing",
"org.graalvm.nativeimage.Platform",
/*
* Loaded in java.util.random.RandomGeneratorFactory.FactoryMapHolder, which is
* initialized at image build time.
*/
"java.util.random.RandomGenerator",
"java.security.Provider", // see SecurityServicesFeature
"sun.util.locale.provider.LocaleDataMetaInfo", // see LocaleSubstitutions
/* Graal hotspot-specific services */
"jdk.vm.ci.hotspot.HotSpotJVMCIBackendFactory",
"jdk.graal.compiler.hotspot.CompilerConfigurationFactory",
"jdk.graal.compiler.hotspot.HotSpotBackendFactory",
"jdk.graal.compiler.hotspot.meta.DefaultHotSpotLoweringProvider$Extensions",
"jdk.graal.compiler.hotspot.meta.HotSpotInvocationPluginProvider",
"jdk.graal.compiler.truffle.hotspot.TruffleCallBoundaryInstrumentationFactory");
// NOTE: Platform class had to be added to this list since our analysis discovers that
// Platform.includedIn is reachable regardless of fact that it is constant folded at
// registerPlatformPlugins method of SubstrateGraphBuilderPlugins. This issue hasn't manifested
// before because implementation classes were instantiated using runtime reflection instead of
// ServiceLoader (and thus weren't reachable in analysis).
/**
* Services that should not be processed here, for example because they are handled by
* specialized features.
*/
private final Set<String> servicesToSkip = new HashSet<>(SKIPPED_SERVICES);
private static final Set<String> SKIPPED_PROVIDERS = Set.of(
/* Graal hotspot-specific service-providers */
"jdk.graal.compiler.hotspot.meta.HotSpotDisassemblerProvider",
/* Skip console providers until GR-44085 is fixed */
"jdk.internal.org.jline.JdkConsoleProviderImpl", "jdk.jshell.execution.impl.ConsoleImpl$ConsoleProviderImpl");
private final Set<String> serviceProvidersToSkip = new HashSet<>(SKIPPED_PROVIDERS);
@Override
public boolean isInConfiguration(IsInConfigurationAccess access) {
return Options.UseServiceLoaderFeature.getValue();
}
@Override
public void afterRegistration(AfterRegistrationAccess access) {
servicesToSkip.addAll(Options.ServiceLoaderFeatureExcludeServices.getValue().values());
serviceProvidersToSkip.addAll(Options.ServiceLoaderFeatureExcludeServiceProviders.getValue().values());
}
@Override
public void beforeAnalysis(BeforeAnalysisAccess access) {
FeatureImpl.BeforeAnalysisAccessImpl accessImpl = (FeatureImpl.BeforeAnalysisAccessImpl) access;
accessImpl.imageClassLoader.classLoaderSupport.serviceProvidersForEach((serviceName, providers) -> {
Class<?> serviceClass = access.findClassByName(serviceName);
boolean [MASK] = false;
/* If the service should not end up in the image, we remove all the providers with it */
Collection<String> providersToSkip = providers;
if (servicesToSkip.contains(serviceName)) {
[MASK] = true;
} else if (serviceClass == null || serviceClass.isArray() || serviceClass.isPrimitive()) {
[MASK] = true;
} else if (!accessImpl.getHostVM().platformSupported(serviceClass)) {
[MASK] = true;
} else {
providersToSkip = providers.stream().filter(serviceProvidersToSkip::contains).collect(Collectors.toList());
if (!providersToSkip.isEmpty()) {
[MASK] = true;
}
}
if ( [MASK] ) {
ServiceCatalogSupport.singleton().removeServicesFromServicesCatalog(serviceName, new HashSet<>(providersToSkip));
return;
}
access.registerReachabilityHandler(a -> handleServiceClassIsReachable(a, serviceClass, providers), serviceClass);
});
}
void handleServiceClassIsReachable(DuringAnalysisAccess access, Class<?> serviceProvider, Collection<String> providers) {
LinkedHashSet<String> registeredProviders = new LinkedHashSet<>();
for (String provider : providers) {
if (serviceProvidersToSkip.contains(provider)) {
continue;
}
/* Make provider reflectively instantiable */
Class<?> providerClass = access.findClassByName(provider);
if (providerClass == null || providerClass.isArray() || providerClass.isPrimitive()) {
continue;
}
FeatureImpl.DuringAnalysisAccessImpl accessImpl = (FeatureImpl.DuringAnalysisAccessImpl) access;
if (!accessImpl.getHostVM().platformSupported(providerClass)) {
continue;
}
if (((Inflation) accessImpl.getBigBang()).getAnnotationSubstitutionProcessor().isDeleted(providerClass)) {
/* Disallow services with implementation classes that are marked as @Deleted */
continue;
}
/*
* Find either a public static provider() method or a nullary constructor (or both).
* Skip providers that do not comply with requirements.
*
* See ServiceLoader#loadProvider and ServiceLoader#findStaticProviderMethod.
*/
Constructor<?> nullaryConstructor = null;
Method nullaryProviderMethod = null;
try {
/* Only look for a provider() method if provider class is in an explicit module. */
if (providerClass.getModule().isNamed() && !providerClass.getModule().getDescriptor().isAutomatic()) {
for (Method method : providerClass.getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers()) &&
method.getParameterCount() == 0 && method.getName().equals("provider")) {
if (nullaryProviderMethod == null) {
nullaryProviderMethod = method;
} else {
/* There must be at most one public static provider() method. */
nullaryProviderMethod = null;
break;
}
}
}
}
Constructor<?> constructor = providerClass.getDeclaredConstructor();
if (Modifier.isPublic(constructor.getModifiers())) {
nullaryConstructor = constructor;
}
} catch (NoSuchMethodException | SecurityException | LinkageError e) {
// ignore
}
if (nullaryConstructor != null || nullaryProviderMethod != null) {
RuntimeReflection.register(providerClass);
if (nullaryConstructor != null) {
/*
* Registering a constructor with
* RuntimeReflection.registerConstructorLookup(providerClass) does not produce
* the same behavior as using RuntimeReflection.register(nullaryConstructor). In
* the first case, the constructor is marked for query purposes only, so this
* if-statement cannot be eliminated.
*
*/
RuntimeReflection.register(nullaryConstructor);
} else {
/*
* If there's no nullary constructor, register it as negative lookup to avoid
* throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerConstructorLookup(providerClass);
}
if (nullaryProviderMethod != null) {
RuntimeReflection.register(nullaryProviderMethod);
} else {
/*
* If there's no declared public provider() method, register it as negative
* lookup to avoid throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerMethodLookup(providerClass, "provider");
}
}
/*
* Register the provider in both cases: when it is JCA-compliant (has a nullary
* constructor or a provider method) or when it lacks both. If neither is present, a
* ServiceConfigurationError will be thrown at runtime, consistent with HotSpot
* behavior.
*/
registeredProviders.add(provider);
}
if (!registeredProviders.isEmpty()) {
String serviceResourceLocation = "META-INF/services/" + serviceProvider.getName();
byte[] serviceFileData = registeredProviders.stream().collect(Collectors.joining("\n")).getBytes(StandardCharsets.UTF_8);
RuntimeResourceAccess.addResource(access.getApplicationClassLoader().getUnnamedModule(), serviceResourceLocation, serviceFileData);
}
}
}
| skipService |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot. [MASK] .tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org. [MASK] .api.GradleException;
import org. [MASK] .api.file.FileCopyDetails;
import org. [MASK] .api.file.FileTreeElement;
import org. [MASK] .api.internal.file.copy.CopyAction;
import org. [MASK] .api.internal.file.copy.CopyActionProcessingStream;
import org. [MASK] .api.java.archives.Attributes;
import org. [MASK] .api.java.archives.Manifest;
import org. [MASK] .api.specs.Spec;
import org. [MASK] .api.tasks.WorkResult;
import org. [MASK] .api.tasks.WorkResults;
import org. [MASK] .util.GradleVersion;
import org.springframework.boot. [MASK] .tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| gradle |
/*
* Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.hosted;
import java.lang. [MASK] .Constructor;
import java.lang. [MASK] .Method;
import java.lang. [MASK] .Modifier;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.stream.Collectors;
import org.graalvm.nativeimage.hosted.RuntimeReflection;
import org.graalvm.nativeimage.hosted.RuntimeResourceAccess;
import com.oracle.svm.core.feature.AutomaticallyRegisteredFeature;
import com.oracle.svm.core.feature.InternalFeature;
import com.oracle.svm.core.jdk.ServiceCatalogSupport;
import com.oracle.svm.core.option.AccumulatingLocatableMultiOptionValue;
import com.oracle.svm.core.option.HostedOptionKey;
import com.oracle.svm.hosted.analysis.Inflation;
import jdk.graal.compiler.options.Option;
import jdk.graal.compiler.options.OptionType;
/**
* Support for {@link ServiceLoader} on Substrate VM.
*
* Services are registered in the folder {@code "META-INF/services/"} using files whose name is the
* fully qualified service interface name. We do not know which services are going to be used by a
* native image: The parameter of {@code ServiceLoader#load} is often but not always a compile-time
* constant that we can track. But we also cannot put all registered services into the native image.
*
* We therefore use the following heuristic: We add all service loader files and service
* implementation classes when the service interfaces that are seen as reachable by the static
* analysis.
*
* Each used service implementation class is added for [MASK] ion (using
* {@link org.graalvm.nativeimage.hosted.RuntimeReflection#register(Class[])}) and for [MASK] ive
* instantiation (using {@link RuntimeReflection#registerForReflectiveInstantiation(Class[])}).
*
* For each service interface, a single service loader file is added as a resource to the image. The
* single file combines all the individual files that can come from different .jar files.
*/
@AutomaticallyRegisteredFeature
public class ServiceLoaderFeature implements InternalFeature {
public static class Options {
@Option(help = "Automatically register services for run-time lookup using ServiceLoader", type = OptionType.Expert) //
public static final HostedOptionKey<Boolean> UseServiceLoaderFeature = new HostedOptionKey<>(true);
@Option(help = "Comma-separated list of services that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServices = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
@Option(help = "Comma-separated list of service providers that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServiceProviders = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
}
private static final Set<String> SKIPPED_SERVICES = Set.of(
// image builder internal ServiceLoader interfaces
"com.oracle.svm.hosted.NativeImageClassLoaderPostProcessing",
"org.graalvm.nativeimage.Platform",
/*
* Loaded in java.util.random.RandomGeneratorFactory.FactoryMapHolder, which is
* initialized at image build time.
*/
"java.util.random.RandomGenerator",
"java.security.Provider", // see SecurityServicesFeature
"sun.util.locale.provider.LocaleDataMetaInfo", // see LocaleSubstitutions
/* Graal hotspot-specific services */
"jdk.vm.ci.hotspot.HotSpotJVMCIBackendFactory",
"jdk.graal.compiler.hotspot.CompilerConfigurationFactory",
"jdk.graal.compiler.hotspot.HotSpotBackendFactory",
"jdk.graal.compiler.hotspot.meta.DefaultHotSpotLoweringProvider$Extensions",
"jdk.graal.compiler.hotspot.meta.HotSpotInvocationPluginProvider",
"jdk.graal.compiler.truffle.hotspot.TruffleCallBoundaryInstrumentationFactory");
// NOTE: Platform class had to be added to this list since our analysis discovers that
// Platform.includedIn is reachable regardless of fact that it is constant folded at
// registerPlatformPlugins method of SubstrateGraphBuilderPlugins. This issue hasn't manifested
// before because implementation classes were instantiated using runtime [MASK] ion instead of
// ServiceLoader (and thus weren't reachable in analysis).
/**
* Services that should not be processed here, for example because they are handled by
* specialized features.
*/
private final Set<String> servicesToSkip = new HashSet<>(SKIPPED_SERVICES);
private static final Set<String> SKIPPED_PROVIDERS = Set.of(
/* Graal hotspot-specific service-providers */
"jdk.graal.compiler.hotspot.meta.HotSpotDisassemblerProvider",
/* Skip console providers until GR-44085 is fixed */
"jdk.internal.org.jline.JdkConsoleProviderImpl", "jdk.jshell.execution.impl.ConsoleImpl$ConsoleProviderImpl");
private final Set<String> serviceProvidersToSkip = new HashSet<>(SKIPPED_PROVIDERS);
@Override
public boolean isInConfiguration(IsInConfigurationAccess access) {
return Options.UseServiceLoaderFeature.getValue();
}
@Override
public void afterRegistration(AfterRegistrationAccess access) {
servicesToSkip.addAll(Options.ServiceLoaderFeatureExcludeServices.getValue().values());
serviceProvidersToSkip.addAll(Options.ServiceLoaderFeatureExcludeServiceProviders.getValue().values());
}
@Override
public void beforeAnalysis(BeforeAnalysisAccess access) {
FeatureImpl.BeforeAnalysisAccessImpl accessImpl = (FeatureImpl.BeforeAnalysisAccessImpl) access;
accessImpl.imageClassLoader.classLoaderSupport.serviceProvidersForEach((serviceName, providers) -> {
Class<?> serviceClass = access.findClassByName(serviceName);
boolean skipService = false;
/* If the service should not end up in the image, we remove all the providers with it */
Collection<String> providersToSkip = providers;
if (servicesToSkip.contains(serviceName)) {
skipService = true;
} else if (serviceClass == null || serviceClass.isArray() || serviceClass.isPrimitive()) {
skipService = true;
} else if (!accessImpl.getHostVM().platformSupported(serviceClass)) {
skipService = true;
} else {
providersToSkip = providers.stream().filter(serviceProvidersToSkip::contains).collect(Collectors.toList());
if (!providersToSkip.isEmpty()) {
skipService = true;
}
}
if (skipService) {
ServiceCatalogSupport.singleton().removeServicesFromServicesCatalog(serviceName, new HashSet<>(providersToSkip));
return;
}
access.registerReachabilityHandler(a -> handleServiceClassIsReachable(a, serviceClass, providers), serviceClass);
});
}
void handleServiceClassIsReachable(DuringAnalysisAccess access, Class<?> serviceProvider, Collection<String> providers) {
LinkedHashSet<String> registeredProviders = new LinkedHashSet<>();
for (String provider : providers) {
if (serviceProvidersToSkip.contains(provider)) {
continue;
}
/* Make provider [MASK] ively instantiable */
Class<?> providerClass = access.findClassByName(provider);
if (providerClass == null || providerClass.isArray() || providerClass.isPrimitive()) {
continue;
}
FeatureImpl.DuringAnalysisAccessImpl accessImpl = (FeatureImpl.DuringAnalysisAccessImpl) access;
if (!accessImpl.getHostVM().platformSupported(providerClass)) {
continue;
}
if (((Inflation) accessImpl.getBigBang()).getAnnotationSubstitutionProcessor().isDeleted(providerClass)) {
/* Disallow services with implementation classes that are marked as @Deleted */
continue;
}
/*
* Find either a public static provider() method or a nullary constructor (or both).
* Skip providers that do not comply with requirements.
*
* See ServiceLoader#loadProvider and ServiceLoader#findStaticProviderMethod.
*/
Constructor<?> nullaryConstructor = null;
Method nullaryProviderMethod = null;
try {
/* Only look for a provider() method if provider class is in an explicit module. */
if (providerClass.getModule().isNamed() && !providerClass.getModule().getDescriptor().isAutomatic()) {
for (Method method : providerClass.getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers()) &&
method.getParameterCount() == 0 && method.getName().equals("provider")) {
if (nullaryProviderMethod == null) {
nullaryProviderMethod = method;
} else {
/* There must be at most one public static provider() method. */
nullaryProviderMethod = null;
break;
}
}
}
}
Constructor<?> constructor = providerClass.getDeclaredConstructor();
if (Modifier.isPublic(constructor.getModifiers())) {
nullaryConstructor = constructor;
}
} catch (NoSuchMethodException | SecurityException | LinkageError e) {
// ignore
}
if (nullaryConstructor != null || nullaryProviderMethod != null) {
RuntimeReflection.register(providerClass);
if (nullaryConstructor != null) {
/*
* Registering a constructor with
* RuntimeReflection.registerConstructorLookup(providerClass) does not produce
* the same behavior as using RuntimeReflection.register(nullaryConstructor). In
* the first case, the constructor is marked for query purposes only, so this
* if-statement cannot be eliminated.
*
*/
RuntimeReflection.register(nullaryConstructor);
} else {
/*
* If there's no nullary constructor, register it as negative lookup to avoid
* throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerConstructorLookup(providerClass);
}
if (nullaryProviderMethod != null) {
RuntimeReflection.register(nullaryProviderMethod);
} else {
/*
* If there's no declared public provider() method, register it as negative
* lookup to avoid throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerMethodLookup(providerClass, "provider");
}
}
/*
* Register the provider in both cases: when it is JCA-compliant (has a nullary
* constructor or a provider method) or when it lacks both. If neither is present, a
* ServiceConfigurationError will be thrown at runtime, consistent with HotSpot
* behavior.
*/
registeredProviders.add(provider);
}
if (!registeredProviders.isEmpty()) {
String serviceResourceLocation = "META-INF/services/" + serviceProvider.getName();
byte[] serviceFileData = registeredProviders.stream().collect(Collectors.joining("\n")).getBytes(StandardCharsets.UTF_8);
RuntimeResourceAccess.addResource(access.getApplicationClassLoader().getUnnamedModule(), serviceResourceLocation, serviceFileData);
}
}
}
| reflect |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling. [MASK] .DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final [MASK] resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
[MASK] resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| ResolvedDependencies |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates [MASK] = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = ( [MASK] != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation( [MASK] )) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| coordinates |
/*
* Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.hosted;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.stream.Collectors;
import org.graalvm.nativeimage.hosted.RuntimeReflection;
import org.graalvm.nativeimage.hosted.RuntimeResourceAccess;
import com.oracle.svm.core.feature.AutomaticallyRegisteredFeature;
import com.oracle.svm.core.feature.InternalFeature;
import com.oracle.svm.core.jdk.ServiceCatalogSupport;
import com.oracle.svm.core.option.AccumulatingLocatableMultiOptionValue;
import com.oracle.svm.core.option.HostedOptionKey;
import com.oracle.svm.hosted.analysis.Inflation;
import jdk.graal.compiler.options.Option;
import jdk.graal.compiler.options.OptionType;
/**
* Support for {@link ServiceLoader} on Substrate VM.
*
* Services are registered in the folder {@code "META-INF/services/"} using files whose name is the
* fully qualified service interface name. We do not know which services are going to be used by a
* native image: The parameter of {@code ServiceLoader#load} is often but not always a compile-time
* constant that we can track. But we also cannot put all registered services into the native image.
*
* We therefore use the following heuristic: We add all service loader files and service
* implementation classes when the service interfaces that are seen as reachable by the static
* analysis.
*
* Each used service implementation class is added for reflection (using
* {@link org.graalvm.nativeimage.hosted.RuntimeReflection#register(Class[])}) and for reflective
* instantiation (using {@link RuntimeReflection#registerForReflectiveInstantiation(Class[])}).
*
* For each service interface, a single service loader file is added as a resource to the image. The
* single file combines all the individual files that can come from different .jar files.
*/
@AutomaticallyRegisteredFeature
public class ServiceLoaderFeature implements InternalFeature {
public static class Options {
@Option(help = "Automatically register services for run-time lookup using ServiceLoader", type = OptionType.Expert) //
public static final HostedOptionKey<Boolean> UseServiceLoaderFeature = new HostedOptionKey<>(true);
@Option(help = "Comma-separated list of services that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServices = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
@Option(help = "Comma-separated list of service providers that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServiceProviders = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
}
private static final Set<String> SKIPPED_SERVICES = Set.of(
// image builder internal ServiceLoader interfaces
"com.oracle.svm.hosted.NativeImageClassLoaderPostProcessing",
"org.graalvm.nativeimage.Platform",
/*
* Loaded in java.util.random.RandomGeneratorFactory.FactoryMapHolder, which is
* initialized at image build time.
*/
"java.util.random.RandomGenerator",
"java.security.Provider", // see SecurityServicesFeature
"sun.util.locale.provider.LocaleDataMetaInfo", // see LocaleSubstitutions
/* Graal hotspot-specific services */
"jdk.vm.ci.hotspot.HotSpotJVMCIBackendFactory",
"jdk.graal.compiler.hotspot.CompilerConfigurationFactory",
"jdk.graal.compiler.hotspot.HotSpotBackendFactory",
"jdk.graal.compiler.hotspot.meta.DefaultHotSpotLoweringProvider$Extensions",
"jdk.graal.compiler.hotspot.meta.HotSpotInvocationPluginProvider",
"jdk.graal.compiler.truffle.hotspot.TruffleCallBoundaryInstrumentationFactory");
// NOTE: Platform class had to be added to this list since our analysis discovers that
// Platform.includedIn is reachable regardless of fact that it is constant folded at
// registerPlatformPlugins method of SubstrateGraphBuilderPlugins. This issue hasn't manifested
// before because implementation classes were instantiated using runtime reflection instead of
// ServiceLoader (and thus weren't reachable in analysis).
/**
* Services that should not be processed here, for example because they are handled by
* specialized features.
*/
private final Set<String> [MASK] = new HashSet<>(SKIPPED_SERVICES);
private static final Set<String> SKIPPED_PROVIDERS = Set.of(
/* Graal hotspot-specific service-providers */
"jdk.graal.compiler.hotspot.meta.HotSpotDisassemblerProvider",
/* Skip console providers until GR-44085 is fixed */
"jdk.internal.org.jline.JdkConsoleProviderImpl", "jdk.jshell.execution.impl.ConsoleImpl$ConsoleProviderImpl");
private final Set<String> serviceProvidersToSkip = new HashSet<>(SKIPPED_PROVIDERS);
@Override
public boolean isInConfiguration(IsInConfigurationAccess access) {
return Options.UseServiceLoaderFeature.getValue();
}
@Override
public void afterRegistration(AfterRegistrationAccess access) {
[MASK] .addAll(Options.ServiceLoaderFeatureExcludeServices.getValue().values());
serviceProvidersToSkip.addAll(Options.ServiceLoaderFeatureExcludeServiceProviders.getValue().values());
}
@Override
public void beforeAnalysis(BeforeAnalysisAccess access) {
FeatureImpl.BeforeAnalysisAccessImpl accessImpl = (FeatureImpl.BeforeAnalysisAccessImpl) access;
accessImpl.imageClassLoader.classLoaderSupport.serviceProvidersForEach((serviceName, providers) -> {
Class<?> serviceClass = access.findClassByName(serviceName);
boolean skipService = false;
/* If the service should not end up in the image, we remove all the providers with it */
Collection<String> providersToSkip = providers;
if ( [MASK] .contains(serviceName)) {
skipService = true;
} else if (serviceClass == null || serviceClass.isArray() || serviceClass.isPrimitive()) {
skipService = true;
} else if (!accessImpl.getHostVM().platformSupported(serviceClass)) {
skipService = true;
} else {
providersToSkip = providers.stream().filter(serviceProvidersToSkip::contains).collect(Collectors.toList());
if (!providersToSkip.isEmpty()) {
skipService = true;
}
}
if (skipService) {
ServiceCatalogSupport.singleton().removeServicesFromServicesCatalog(serviceName, new HashSet<>(providersToSkip));
return;
}
access.registerReachabilityHandler(a -> handleServiceClassIsReachable(a, serviceClass, providers), serviceClass);
});
}
void handleServiceClassIsReachable(DuringAnalysisAccess access, Class<?> serviceProvider, Collection<String> providers) {
LinkedHashSet<String> registeredProviders = new LinkedHashSet<>();
for (String provider : providers) {
if (serviceProvidersToSkip.contains(provider)) {
continue;
}
/* Make provider reflectively instantiable */
Class<?> providerClass = access.findClassByName(provider);
if (providerClass == null || providerClass.isArray() || providerClass.isPrimitive()) {
continue;
}
FeatureImpl.DuringAnalysisAccessImpl accessImpl = (FeatureImpl.DuringAnalysisAccessImpl) access;
if (!accessImpl.getHostVM().platformSupported(providerClass)) {
continue;
}
if (((Inflation) accessImpl.getBigBang()).getAnnotationSubstitutionProcessor().isDeleted(providerClass)) {
/* Disallow services with implementation classes that are marked as @Deleted */
continue;
}
/*
* Find either a public static provider() method or a nullary constructor (or both).
* Skip providers that do not comply with requirements.
*
* See ServiceLoader#loadProvider and ServiceLoader#findStaticProviderMethod.
*/
Constructor<?> nullaryConstructor = null;
Method nullaryProviderMethod = null;
try {
/* Only look for a provider() method if provider class is in an explicit module. */
if (providerClass.getModule().isNamed() && !providerClass.getModule().getDescriptor().isAutomatic()) {
for (Method method : providerClass.getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers()) &&
method.getParameterCount() == 0 && method.getName().equals("provider")) {
if (nullaryProviderMethod == null) {
nullaryProviderMethod = method;
} else {
/* There must be at most one public static provider() method. */
nullaryProviderMethod = null;
break;
}
}
}
}
Constructor<?> constructor = providerClass.getDeclaredConstructor();
if (Modifier.isPublic(constructor.getModifiers())) {
nullaryConstructor = constructor;
}
} catch (NoSuchMethodException | SecurityException | LinkageError e) {
// ignore
}
if (nullaryConstructor != null || nullaryProviderMethod != null) {
RuntimeReflection.register(providerClass);
if (nullaryConstructor != null) {
/*
* Registering a constructor with
* RuntimeReflection.registerConstructorLookup(providerClass) does not produce
* the same behavior as using RuntimeReflection.register(nullaryConstructor). In
* the first case, the constructor is marked for query purposes only, so this
* if-statement cannot be eliminated.
*
*/
RuntimeReflection.register(nullaryConstructor);
} else {
/*
* If there's no nullary constructor, register it as negative lookup to avoid
* throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerConstructorLookup(providerClass);
}
if (nullaryProviderMethod != null) {
RuntimeReflection.register(nullaryProviderMethod);
} else {
/*
* If there's no declared public provider() method, register it as negative
* lookup to avoid throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerMethodLookup(providerClass, "provider");
}
}
/*
* Register the provider in both cases: when it is JCA-compliant (has a nullary
* constructor or a provider method) or when it lacks both. If neither is present, a
* ServiceConfigurationError will be thrown at runtime, consistent with HotSpot
* behavior.
*/
registeredProviders.add(provider);
}
if (!registeredProviders.isEmpty()) {
String serviceResourceLocation = "META-INF/services/" + serviceProvider.getName();
byte[] serviceFileData = registeredProviders.stream().collect(Collectors.joining("\n")).getBytes(StandardCharsets.UTF_8);
RuntimeResourceAccess.addResource(access.getApplicationClassLoader().getUnnamedModule(), serviceResourceLocation, serviceFileData);
}
}
}
| servicesToSkip |
/*
* Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the " [MASK] path" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.hosted;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.stream.Collectors;
import org.graalvm.nativeimage.hosted.RuntimeReflection;
import org.graalvm.nativeimage.hosted.RuntimeResourceAccess;
import com.oracle.svm.core.feature.AutomaticallyRegisteredFeature;
import com.oracle.svm.core.feature.InternalFeature;
import com.oracle.svm.core.jdk.ServiceCatalogSupport;
import com.oracle.svm.core.option.AccumulatingLocatableMultiOptionValue;
import com.oracle.svm.core.option.HostedOptionKey;
import com.oracle.svm.hosted.analysis.Inflation;
import jdk.graal.compiler.options.Option;
import jdk.graal.compiler.options.OptionType;
/**
* Support for {@link ServiceLoader} on Substrate VM.
*
* Services are registered in the folder {@code "META-INF/services/"} using files whose name is the
* fully qualified service interface name. We do not know which services are going to be used by a
* native image: The parameter of {@code ServiceLoader#load} is often but not always a compile-time
* constant that we can track. But we also cannot put all registered services into the native image.
*
* We therefore use the following heuristic: We add all service loader files and service
* implementation classes when the service interfaces that are seen as reachable by the static
* analysis.
*
* Each used service implementation class is added for reflection (using
* {@link org.graalvm.nativeimage.hosted.RuntimeReflection#register( [MASK] [])}) and for reflective
* instantiation (using {@link RuntimeReflection#registerForReflectiveInstantiation( [MASK] [])}).
*
* For each service interface, a single service loader file is added as a resource to the image. The
* single file combines all the individual files that can come from different .jar files.
*/
@AutomaticallyRegisteredFeature
public class ServiceLoaderFeature implements InternalFeature {
public static class Options {
@Option(help = "Automatically register services for run-time lookup using ServiceLoader", type = OptionType.Expert) //
public static final HostedOptionKey<Boolean> UseServiceLoaderFeature = new HostedOptionKey<>(true);
@Option(help = "Comma-separated list of services that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServices = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
@Option(help = "Comma-separated list of service providers that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServiceProviders = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
}
private static final Set<String> SKIPPED_SERVICES = Set.of(
// image builder internal ServiceLoader interfaces
"com.oracle.svm.hosted.NativeImage [MASK] LoaderPostProcessing",
"org.graalvm.nativeimage.Platform",
/*
* Loaded in java.util.random.RandomGeneratorFactory.FactoryMapHolder, which is
* initialized at image build time.
*/
"java.util.random.RandomGenerator",
"java.security.Provider", // see SecurityServicesFeature
"sun.util.locale.provider.LocaleDataMetaInfo", // see LocaleSubstitutions
/* Graal hotspot-specific services */
"jdk.vm.ci.hotspot.HotSpotJVMCIBackendFactory",
"jdk.graal.compiler.hotspot.CompilerConfigurationFactory",
"jdk.graal.compiler.hotspot.HotSpotBackendFactory",
"jdk.graal.compiler.hotspot.meta.DefaultHotSpotLoweringProvider$Extensions",
"jdk.graal.compiler.hotspot.meta.HotSpotInvocationPluginProvider",
"jdk.graal.compiler.truffle.hotspot.TruffleCallBoundaryInstrumentationFactory");
// NOTE: Platform class had to be added to this list since our analysis discovers that
// Platform.includedIn is reachable regardless of fact that it is constant folded at
// registerPlatformPlugins method of SubstrateGraphBuilderPlugins. This issue hasn't manifested
// before because implementation classes were instantiated using runtime reflection instead of
// ServiceLoader (and thus weren't reachable in analysis).
/**
* Services that should not be processed here, for example because they are handled by
* specialized features.
*/
private final Set<String> servicesToSkip = new HashSet<>(SKIPPED_SERVICES);
private static final Set<String> SKIPPED_PROVIDERS = Set.of(
/* Graal hotspot-specific service-providers */
"jdk.graal.compiler.hotspot.meta.HotSpotDisassemblerProvider",
/* Skip console providers until GR-44085 is fixed */
"jdk.internal.org.jline.JdkConsoleProviderImpl", "jdk.jshell.execution.impl.ConsoleImpl$ConsoleProviderImpl");
private final Set<String> serviceProvidersToSkip = new HashSet<>(SKIPPED_PROVIDERS);
@Override
public boolean isInConfiguration(IsInConfigurationAccess access) {
return Options.UseServiceLoaderFeature.getValue();
}
@Override
public void afterRegistration(AfterRegistrationAccess access) {
servicesToSkip.addAll(Options.ServiceLoaderFeatureExcludeServices.getValue().values());
serviceProvidersToSkip.addAll(Options.ServiceLoaderFeatureExcludeServiceProviders.getValue().values());
}
@Override
public void beforeAnalysis(BeforeAnalysisAccess access) {
FeatureImpl.BeforeAnalysisAccessImpl accessImpl = (FeatureImpl.BeforeAnalysisAccessImpl) access;
accessImpl.image [MASK] Loader.classLoaderSupport.serviceProvidersForEach((serviceName, providers) -> {
[MASK] <?> service [MASK] = access.find [MASK] ByName(serviceName);
boolean skipService = false;
/* If the service should not end up in the image, we remove all the providers with it */
Collection<String> providersToSkip = providers;
if (servicesToSkip.contains(serviceName)) {
skipService = true;
} else if (service [MASK] == null || service [MASK] .isArray() || service [MASK] .isPrimitive()) {
skipService = true;
} else if (!accessImpl.getHostVM().platformSupported(service [MASK] )) {
skipService = true;
} else {
providersToSkip = providers.stream().filter(serviceProvidersToSkip::contains).collect(Collectors.toList());
if (!providersToSkip.isEmpty()) {
skipService = true;
}
}
if (skipService) {
ServiceCatalogSupport.singleton().removeServicesFromServicesCatalog(serviceName, new HashSet<>(providersToSkip));
return;
}
access.registerReachabilityHandler(a -> handleService [MASK] IsReachable(a, service [MASK] , providers), service [MASK] );
});
}
void handleService [MASK] IsReachable(DuringAnalysisAccess access, [MASK] <?> serviceProvider, Collection<String> providers) {
LinkedHashSet<String> registeredProviders = new LinkedHashSet<>();
for (String provider : providers) {
if (serviceProvidersToSkip.contains(provider)) {
continue;
}
/* Make provider reflectively instantiable */
[MASK] <?> provider [MASK] = access.find [MASK] ByName(provider);
if (provider [MASK] == null || provider [MASK] .isArray() || provider [MASK] .isPrimitive()) {
continue;
}
FeatureImpl.DuringAnalysisAccessImpl accessImpl = (FeatureImpl.DuringAnalysisAccessImpl) access;
if (!accessImpl.getHostVM().platformSupported(provider [MASK] )) {
continue;
}
if (((Inflation) accessImpl.getBigBang()).getAnnotationSubstitutionProcessor().isDeleted(provider [MASK] )) {
/* Disallow services with implementation classes that are marked as @Deleted */
continue;
}
/*
* Find either a public static provider() method or a nullary constructor (or both).
* Skip providers that do not comply with requirements.
*
* See ServiceLoader#loadProvider and ServiceLoader#findStaticProviderMethod.
*/
Constructor<?> nullaryConstructor = null;
Method nullaryProviderMethod = null;
try {
/* Only look for a provider() method if provider class is in an explicit module. */
if (provider [MASK] .getModule().isNamed() && !provider [MASK] .getModule().getDescriptor().isAutomatic()) {
for (Method method : provider [MASK] .getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers()) &&
method.getParameterCount() == 0 && method.getName().equals("provider")) {
if (nullaryProviderMethod == null) {
nullaryProviderMethod = method;
} else {
/* There must be at most one public static provider() method. */
nullaryProviderMethod = null;
break;
}
}
}
}
Constructor<?> constructor = provider [MASK] .getDeclaredConstructor();
if (Modifier.isPublic(constructor.getModifiers())) {
nullaryConstructor = constructor;
}
} catch (NoSuchMethodException | SecurityException | LinkageError e) {
// ignore
}
if (nullaryConstructor != null || nullaryProviderMethod != null) {
RuntimeReflection.register(provider [MASK] );
if (nullaryConstructor != null) {
/*
* Registering a constructor with
* RuntimeReflection.registerConstructorLookup(provider [MASK] ) does not produce
* the same behavior as using RuntimeReflection.register(nullaryConstructor). In
* the first case, the constructor is marked for query purposes only, so this
* if-statement cannot be eliminated.
*
*/
RuntimeReflection.register(nullaryConstructor);
} else {
/*
* If there's no nullary constructor, register it as negative lookup to avoid
* throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerConstructorLookup(provider [MASK] );
}
if (nullaryProviderMethod != null) {
RuntimeReflection.register(nullaryProviderMethod);
} else {
/*
* If there's no declared public provider() method, register it as negative
* lookup to avoid throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerMethodLookup(provider [MASK] , "provider");
}
}
/*
* Register the provider in both cases: when it is JCA-compliant (has a nullary
* constructor or a provider method) or when it lacks both. If neither is present, a
* ServiceConfigurationError will be thrown at runtime, consistent with HotSpot
* behavior.
*/
registeredProviders.add(provider);
}
if (!registeredProviders.isEmpty()) {
String serviceResourceLocation = "META-INF/services/" + serviceProvider.getName();
byte[] serviceFileData = registeredProviders.stream().collect(Collectors.joining("\n")).getBytes(StandardCharsets.UTF_8);
RuntimeResourceAccess.addResource(access.getApplication [MASK] Loader().getUnnamedModule(), serviceResourceLocation, serviceFileData);
}
}
}
| Class |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www. [MASK] .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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org. [MASK] .commons.compress.archivers.zip.UnixStat;
import org. [MASK] .commons.compress.archivers.zip.ZipArchiveEntry;
import org. [MASK] .commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| apache |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io. [MASK] ;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
[MASK] writer = new [MASK] (out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| OutputStreamWriter |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies [MASK] ;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies [MASK] , boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this. [MASK] = [MASK] ;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this. [MASK]
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| resolvedDependencies |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out. [MASK] (entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out. [MASK] (entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out. [MASK] (entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out. [MASK] (entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| putArchiveEntry |
/*
* Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.hosted;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.stream.Collectors;
import org.graalvm.nativeimage.hosted.RuntimeReflection;
import org.graalvm.nativeimage.hosted.RuntimeResourceAccess;
import com.oracle.svm.core.feature.AutomaticallyRegisteredFeature;
import com.oracle.svm.core.feature.InternalFeature;
import com.oracle.svm.core.jdk.ServiceCatalogSupport;
import com.oracle.svm.core.option.AccumulatingLocatableMultiOptionValue;
import com.oracle.svm.core.option.HostedOptionKey;
import com.oracle.svm.hosted.analysis.Inflation;
import jdk.graal.compiler.options.Option;
import jdk.graal.compiler.options.OptionType;
/**
* Support for {@link ServiceLoader} on Substrate VM.
*
* Services are registered in the folder {@code "META-INF/services/"} using files whose name is the
* fully qualified service interface name. We do not know which services are going to be used by a
* native image: The parameter of {@code ServiceLoader#load} is often but not always a compile-time
* constant that we can track. But we also cannot put all registered services into the native image.
*
* We therefore use the following heuristic: We add all service loader files and service
* implementation classes when the service interfaces that are seen as reachable by the static
* analysis.
*
* Each used service implementation class is added for reflection (using
* {@link org.graalvm.nativeimage.hosted.RuntimeReflection#register(Class[])}) and for reflective
* instantiation (using {@link RuntimeReflection#registerForReflectiveInstantiation(Class[])}).
*
* For each service interface, a single service loader file is added as a resource to the image. The
* single file combines all the individual files that can come from different .jar files.
*/
@AutomaticallyRegisteredFeature
public class ServiceLoaderFeature implements InternalFeature {
public static class Options {
@Option(help = "Automatically register services for run-time lookup using ServiceLoader", type = OptionType.Expert) //
public static final HostedOptionKey<Boolean> UseServiceLoaderFeature = new HostedOptionKey<>(true);
@Option(help = "Comma-separated list of services that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue. [MASK] > ServiceLoaderFeatureExcludeServices = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue. [MASK] .buildWithCommaDelimiter());
@Option(help = "Comma-separated list of service providers that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue. [MASK] > ServiceLoaderFeatureExcludeServiceProviders = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue. [MASK] .buildWithCommaDelimiter());
}
private static final Set<String> SKIPPED_SERVICES = Set.of(
// image builder internal ServiceLoader interfaces
"com.oracle.svm.hosted.NativeImageClassLoaderPostProcessing",
"org.graalvm.nativeimage.Platform",
/*
* Loaded in java.util.random.RandomGeneratorFactory.FactoryMapHolder, which is
* initialized at image build time.
*/
"java.util.random.RandomGenerator",
"java.security.Provider", // see SecurityServicesFeature
"sun.util.locale.provider.LocaleDataMetaInfo", // see LocaleSubstitutions
/* Graal hotspot-specific services */
"jdk.vm.ci.hotspot.HotSpotJVMCIBackendFactory",
"jdk.graal.compiler.hotspot.CompilerConfigurationFactory",
"jdk.graal.compiler.hotspot.HotSpotBackendFactory",
"jdk.graal.compiler.hotspot.meta.DefaultHotSpotLoweringProvider$Extensions",
"jdk.graal.compiler.hotspot.meta.HotSpotInvocationPluginProvider",
"jdk.graal.compiler.truffle.hotspot.TruffleCallBoundaryInstrumentationFactory");
// NOTE: Platform class had to be added to this list since our analysis discovers that
// Platform.includedIn is reachable regardless of fact that it is constant folded at
// registerPlatformPlugins method of SubstrateGraphBuilderPlugins. This issue hasn't manifested
// before because implementation classes were instantiated using runtime reflection instead of
// ServiceLoader (and thus weren't reachable in analysis).
/**
* Services that should not be processed here, for example because they are handled by
* specialized features.
*/
private final Set<String> servicesToSkip = new HashSet<>(SKIPPED_SERVICES);
private static final Set<String> SKIPPED_PROVIDERS = Set.of(
/* Graal hotspot-specific service-providers */
"jdk.graal.compiler.hotspot.meta.HotSpotDisassemblerProvider",
/* Skip console providers until GR-44085 is fixed */
"jdk.internal.org.jline.JdkConsoleProviderImpl", "jdk.jshell.execution.impl.ConsoleImpl$ConsoleProviderImpl");
private final Set<String> serviceProvidersToSkip = new HashSet<>(SKIPPED_PROVIDERS);
@Override
public boolean isInConfiguration(IsInConfigurationAccess access) {
return Options.UseServiceLoaderFeature.getValue();
}
@Override
public void afterRegistration(AfterRegistrationAccess access) {
servicesToSkip.addAll(Options.ServiceLoaderFeatureExcludeServices.getValue().values());
serviceProvidersToSkip.addAll(Options.ServiceLoaderFeatureExcludeServiceProviders.getValue().values());
}
@Override
public void beforeAnalysis(BeforeAnalysisAccess access) {
FeatureImpl.BeforeAnalysisAccessImpl accessImpl = (FeatureImpl.BeforeAnalysisAccessImpl) access;
accessImpl.imageClassLoader.classLoaderSupport.serviceProvidersForEach((serviceName, providers) -> {
Class<?> serviceClass = access.findClassByName(serviceName);
boolean skipService = false;
/* If the service should not end up in the image, we remove all the providers with it */
Collection<String> providersToSkip = providers;
if (servicesToSkip.contains(serviceName)) {
skipService = true;
} else if (serviceClass == null || serviceClass.isArray() || serviceClass.isPrimitive()) {
skipService = true;
} else if (!accessImpl.getHostVM().platformSupported(serviceClass)) {
skipService = true;
} else {
providersToSkip = providers.stream().filter(serviceProvidersToSkip::contains).collect(Collectors.toList());
if (!providersToSkip.isEmpty()) {
skipService = true;
}
}
if (skipService) {
ServiceCatalogSupport.singleton().removeServicesFromServicesCatalog(serviceName, new HashSet<>(providersToSkip));
return;
}
access.registerReachabilityHandler(a -> handleServiceClassIsReachable(a, serviceClass, providers), serviceClass);
});
}
void handleServiceClassIsReachable(DuringAnalysisAccess access, Class<?> serviceProvider, Collection<String> providers) {
LinkedHashSet<String> registeredProviders = new LinkedHashSet<>();
for (String provider : providers) {
if (serviceProvidersToSkip.contains(provider)) {
continue;
}
/* Make provider reflectively instantiable */
Class<?> providerClass = access.findClassByName(provider);
if (providerClass == null || providerClass.isArray() || providerClass.isPrimitive()) {
continue;
}
FeatureImpl.DuringAnalysisAccessImpl accessImpl = (FeatureImpl.DuringAnalysisAccessImpl) access;
if (!accessImpl.getHostVM().platformSupported(providerClass)) {
continue;
}
if (((Inflation) accessImpl.getBigBang()).getAnnotationSubstitutionProcessor().isDeleted(providerClass)) {
/* Disallow services with implementation classes that are marked as @Deleted */
continue;
}
/*
* Find either a public static provider() method or a nullary constructor (or both).
* Skip providers that do not comply with requirements.
*
* See ServiceLoader#loadProvider and ServiceLoader#findStaticProviderMethod.
*/
Constructor<?> nullaryConstructor = null;
Method nullaryProviderMethod = null;
try {
/* Only look for a provider() method if provider class is in an explicit module. */
if (providerClass.getModule().isNamed() && !providerClass.getModule().getDescriptor().isAutomatic()) {
for (Method method : providerClass.getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers()) &&
method.getParameterCount() == 0 && method.getName().equals("provider")) {
if (nullaryProviderMethod == null) {
nullaryProviderMethod = method;
} else {
/* There must be at most one public static provider() method. */
nullaryProviderMethod = null;
break;
}
}
}
}
Constructor<?> constructor = providerClass.getDeclaredConstructor();
if (Modifier.isPublic(constructor.getModifiers())) {
nullaryConstructor = constructor;
}
} catch (NoSuchMethodException | SecurityException | LinkageError e) {
// ignore
}
if (nullaryConstructor != null || nullaryProviderMethod != null) {
RuntimeReflection.register(providerClass);
if (nullaryConstructor != null) {
/*
* Registering a constructor with
* RuntimeReflection.registerConstructorLookup(providerClass) does not produce
* the same behavior as using RuntimeReflection.register(nullaryConstructor). In
* the first case, the constructor is marked for query purposes only, so this
* if-statement cannot be eliminated.
*
*/
RuntimeReflection.register(nullaryConstructor);
} else {
/*
* If there's no nullary constructor, register it as negative lookup to avoid
* throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerConstructorLookup(providerClass);
}
if (nullaryProviderMethod != null) {
RuntimeReflection.register(nullaryProviderMethod);
} else {
/*
* If there's no declared public provider() method, register it as negative
* lookup to avoid throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerMethodLookup(providerClass, "provider");
}
}
/*
* Register the provider in both cases: when it is JCA-compliant (has a nullary
* constructor or a provider method) or when it lacks both. If neither is present, a
* ServiceConfigurationError will be thrown at runtime, consistent with HotSpot
* behavior.
*/
registeredProviders.add(provider);
}
if (!registeredProviders.isEmpty()) {
String serviceResourceLocation = "META-INF/services/" + serviceProvider.getName();
byte[] serviceFileData = registeredProviders.stream().collect(Collectors.joining("\n")).getBytes(StandardCharsets.UTF_8);
RuntimeResourceAccess.addResource(access.getApplicationClassLoader().getUnnamedModule(), serviceResourceLocation, serviceFileData);
}
}
}
| Strings |
/**
* Copyright © 2016-2024 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thingsboard.server.service.sync.ie.importing.impl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4. [MASK] ;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.NotificationTargetId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.notification.targets.NotificationTarget;
import org.thingsboard.server.common.data.notification.targets.NotificationTargetType;
import org.thingsboard.server.common.data.notification.targets.platform.CustomerUsersFilter;
import org.thingsboard.server.common.data.notification.targets.platform.PlatformUsersNotificationTargetConfig;
import org.thingsboard.server.common.data.notification.targets.platform.TenantAdministratorsFilter;
import org.thingsboard.server.common.data.notification.targets.platform.UserListFilter;
import org.thingsboard.server.common.data.notification.targets.platform.UsersFilter;
import org.thingsboard.server.common.data.sync.ie.EntityExportData;
import org.thingsboard.server.dao.notification.NotificationTargetService;
import org.thingsboard.server.dao.service.ConstraintValidator;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.sync.vc.data.EntitiesImportCtx;
import java.util.List;
@Service
@TbCoreComponent
@RequiredArgsConstructor
public class NotificationTargetImportService extends BaseEntityImportService<NotificationTargetId, NotificationTarget, EntityExportData<NotificationTarget>> {
private final NotificationTargetService notificationTargetService;
@Override
protected void setOwner(TenantId tenantId, NotificationTarget notificationTarget, IdProvider idProvider) {
notificationTarget.setTenantId(tenantId);
}
@Override
protected NotificationTarget prepare(EntitiesImportCtx ctx, NotificationTarget notificationTarget, NotificationTarget oldNotificationTarget, EntityExportData<NotificationTarget> exportData, IdProvider idProvider) {
if (notificationTarget.getConfiguration().getType() == NotificationTargetType.PLATFORM_USERS) {
UsersFilter usersFilter = ((PlatformUsersNotificationTargetConfig) notificationTarget.getConfiguration()).getUsersFilter();
switch (usersFilter.getType()) {
case CUSTOMER_USERS:
CustomerUsersFilter customerUsersFilter = (CustomerUsersFilter) usersFilter;
customerUsersFilter.setCustomerId(idProvider.getInternalId(new CustomerId(customerUsersFilter.getCustomerId())).getId());
break;
case USER_LIST:
UserListFilter userListFilter = (UserListFilter) usersFilter;
userListFilter.setUsersIds(List.of(ctx.getUser().getUuidId())); // user entities are not supported by VC; replacing with current user id
break;
case TENANT_ADMINISTRATORS:
if ( [MASK] .isNotEmpty(((TenantAdministratorsFilter) usersFilter).getTenantsIds()) ||
[MASK] .isNotEmpty(((TenantAdministratorsFilter) usersFilter).getTenantProfilesIds())) {
throw new IllegalArgumentException("Permission denied");
}
break;
case SYSTEM_ADMINISTRATORS:
throw new AccessDeniedException("Permission denied");
}
}
return notificationTarget;
}
@Override
protected NotificationTarget saveOrUpdate(EntitiesImportCtx ctx, NotificationTarget notificationTarget, EntityExportData<NotificationTarget> exportData, IdProvider idProvider) {
ConstraintValidator.validateFields(notificationTarget);
return notificationTargetService.saveNotificationTarget(ctx.getTenantId(), notificationTarget);
}
@Override
protected void onEntitySaved(User user, NotificationTarget savedEntity, NotificationTarget oldEntity) throws ThingsboardException {
entityActionService.logEntityAction(user, savedEntity.getId(), savedEntity, null,
oldEntity == null ? ActionType.ADDED : ActionType.UPDATED, null);
}
@Override
protected NotificationTarget deepCopy(NotificationTarget notificationTarget) {
return new NotificationTarget(notificationTarget);
}
@Override
public EntityType getEntityType() {
return EntityType.NOTIFICATION_TARGET;
}
}
| CollectionUtils |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools. [MASK] ;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if ( [MASK] .isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + [MASK] .sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| FileUtils |
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
*/
/*
* 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 com.sun.org.apache.xerces.internal.impl.xs;
import com.sun.org.apache.xerces.internal.impl.Constants;
import com.sun.org.apache.xerces.internal.impl.dv.SchemaDVFactory;
import com.sun.org.apache.xerces.internal.impl.dv.ValidatedInfo;
import com.sun.org.apache.xerces.internal.impl.dv.XSSimpleType;
import com.sun.org.apache.xerces.internal.impl.dv.xs.XSSimpleTyp [MASK] ;
import com.sun.org.apache.xerces.internal.impl.xs.identity.IdentityConstraint;
import com.sun.org.apache.xerces.internal.impl.xs.util.ObjectListImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.SimpleLocator;
import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSNamedMap4Types;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSNamedMapImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSObjectListImpl;
import com.sun.org.apache.xerces.internal.parsers.DOMParser;
import com.sun.org.apache.xerces.internal.parsers.SAXParser;
import com.sun.org.apache.xerces.internal.parsers.XML11Configuration;
import com.sun.org.apache.xerces.internal.util.SymbolHash;
import com.sun.org.apache.xerces.internal.util.SymbolTable;
import com.sun.org.apache.xerces.internal.xni.NamespaceContext;
import com.sun.org.apache.xerces.internal.xni.grammars.XMLGrammarDescription;
import com.sun.org.apache.xerces.internal.xni.grammars.XSGrammar;
import com.sun.org.apache.xerces.internal.xs.StringList;
import com.sun.org.apache.xerces.internal.xs.XSAnnotation;
import com.sun.org.apache.xerces.internal.xs.XSAttribut [MASK] aration;
import com.sun.org.apache.xerces.internal.xs.XSAttributeGroupDefinition;
import com.sun.org.apache.xerces.internal.xs.XSConstants;
import com.sun.org.apache.xerces.internal.xs.XSElementDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSIDCDefinition;
import com.sun.org.apache.xerces.internal.xs.XSModel;
import com.sun.org.apache.xerces.internal.xs.XSModelGroupDefinition;
import com.sun.org.apache.xerces.internal.xs.XSNamedMap;
import com.sun.org.apache.xerces.internal.xs.XSNamespaceItem;
import com.sun.org.apache.xerces.internal.xs.XSNotationDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSObjectList;
import com.sun.org.apache.xerces.internal.xs.XSParticle;
import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
import com.sun.org.apache.xerces.internal.xs.XSWildcard;
import com.sun.org.apache.xerces.internal.xs.datatypes.ObjectList;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.xml.sax.SAXException;
/**
* This class is to hold all schema component declaration that are declared
* within one namespace.
*
* The Grammar class this class extends contains what little
* commonality there is between XML Schema and DTD grammars. It's
* useful to distinguish grammar objects from other kinds of object
* when they exist in pools or caches.
*
* @xerces.internal
*
* @author Sandy Gao, IBM
* @author Elena Litani, IBM
*
* @LastModified: Oct 2017
*/
public class SchemaGrammar implements XSGrammar, XSNamespaceItem {
// the target namespace of grammar
String fTargetNamespace;
// global decls: map from decl name to decl object
SymbolHash fGlobalAttrDecls;
SymbolHash fGlobalAttrGrpDecls;
SymbolHash fGlobalElemDecls;
SymbolHash fGlobalGroupDecls;
SymbolHash fGlobalNotationDecls;
SymbolHash fGlobalIDConstraintDecls;
SymbolHash fGlobalTyp [MASK] s;
// extended global decls: map from schema location + decl name to decl object
// key is location,name
SymbolHash fGlobalAttrDeclsExt;
SymbolHash fGlobalAttrGrpDeclsExt;
SymbolHash fGlobalElemDeclsExt;
SymbolHash fGlobalGroupDeclsExt;
SymbolHash fGlobalNotationDeclsExt;
SymbolHash fGlobalIDConstraintDeclsExt;
SymbolHash fGlobalTyp [MASK] sExt;
// A global map of all global element declarations - used for substitution group computation
// (handy when sharing components by reference, since we might end up with duplicate components
// that are not added to either of the global element declarations above)
SymbolHash fAllGlobalElemDecls;
// the XMLGrammarDescription member
XSDDescription fGrammarDescription = null;
// annotations associated with the "root" schema of this targetNamespace
XSAnnotationImpl [] fAnnotations = null;
// number of annotations declared
int fNumAnnotations;
// symbol table for constructing parsers (annotation support)
private SymbolTable fSymbolTable = null;
// parsers for annotation support
private SoftReference<SAXParser> fSAXParser = null;
private SoftReference<DOMParser> fDOMParser = null;
// is this grammar immutable? (fully constructed and not changeable)
private boolean fIsImmutable = false;
//
// Constructors
//
// needed to make BuiltinSchemaGrammar work.
protected SchemaGrammar() {}
/**
* Default constructor.
*
* @param targetNamespace
* @param grammarDesc the XMLGrammarDescription corresponding to this object
* at the least a systemId should always be known.
* @param symbolTable needed for annotation support
*/
public SchemaGrammar(String targetNamespace, XSDDescription grammarDesc,
SymbolTable symbolTable) {
fTargetNamespace = targetNamespace;
fGrammarDescription = grammarDesc;
fSymbolTable = symbolTable;
// REVISIT: the initial sizes being chosen for each SymbolHash
// may not be ideal and could still be tuned. They were chosen
// somewhat arbitrarily to reduce the initial footprint of
// SymbolHash buckets from 1,515 to 177 (about 12% of the
// default size).
fGlobalAttrDecls = new SymbolHash(12);
fGlobalAttrGrpDecls = new SymbolHash(5);
fGlobalElemDecls = new SymbolHash(25);
fGlobalGroupDecls = new SymbolHash(5);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(3);
// Extended tables
fGlobalAttrDeclsExt = new SymbolHash(12);
fGlobalAttrGrpDeclsExt = new SymbolHash(5);
fGlobalElemDeclsExt = new SymbolHash(25);
fGlobalGroupDeclsExt = new SymbolHash(5);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(3);
fGlobalTyp [MASK] sExt = new SymbolHash(25);
// All global elements table
fAllGlobalElemDecls = new SymbolHash(25);
// if we are parsing S4S, put built-in types in first
// they might get overwritten by the types from S4S, but that's
// considered what the application wants to do.
if (fTargetNamespace == SchemaSymbols.URI_SCHEMAFORSCHEMA) {
fGlobalTyp [MASK] s = SG_SchemaNS.fGlobalTyp [MASK] s.makeClone();
}
else {
fGlobalTyp [MASK] s = new SymbolHash(25);
}
} // <init>(String, XSDDescription)
// Clone an existing schema grammar
public SchemaGrammar(SchemaGrammar grammar) {
fTargetNamespace = grammar.fTargetNamespace;
fGrammarDescription = grammar.fGrammarDescription.makeClone();
//fGrammarDescription.fContextType |= XSDDescription.CONTEXT_COLLISION; // REVISIT
fSymbolTable = grammar.fSymbolTable; // REVISIT
fGlobalAttrDecls = grammar.fGlobalAttrDecls.makeClone();
fGlobalAttrGrpDecls = grammar.fGlobalAttrGrpDecls.makeClone();
fGlobalElemDecls = grammar.fGlobalElemDecls.makeClone();
fGlobalGroupDecls = grammar.fGlobalGroupDecls.makeClone();
fGlobalNotationDecls = grammar.fGlobalNotationDecls.makeClone();
fGlobalIDConstraintDecls = grammar.fGlobalIDConstraintDecls.makeClone();
fGlobalTyp [MASK] s = grammar.fGlobalTyp [MASK] s.makeClone();
// Extended tables
fGlobalAttrDeclsExt = grammar.fGlobalAttrDeclsExt.makeClone();
fGlobalAttrGrpDeclsExt = grammar.fGlobalAttrGrpDeclsExt.makeClone();
fGlobalElemDeclsExt = grammar.fGlobalElemDeclsExt.makeClone();
fGlobalGroupDeclsExt = grammar.fGlobalGroupDeclsExt.makeClone();
fGlobalNotationDeclsExt = grammar.fGlobalNotationDeclsExt.makeClone();
fGlobalIDConstraintDeclsExt = grammar.fGlobalIDConstraintDeclsExt.makeClone();
fGlobalTyp [MASK] sExt = grammar.fGlobalTyp [MASK] sExt.makeClone();
// All global elements table
fAllGlobalElemDecls = grammar.fAllGlobalElemDecls.makeClone();
// Annotations associated with the "root" schema of this targetNamespace
fNumAnnotations = grammar.fNumAnnotations;
if (fNumAnnotations > 0) {
fAnnotations = new XSAnnotationImpl[grammar.fAnnotations.length];
System.arraycopy(grammar.fAnnotations, 0, fAnnotations, 0, fNumAnnotations);
}
// All substitution group information declared in this namespace
fSubGroupCount = grammar.fSubGroupCount;
if (fSubGroupCount > 0) {
fSubGroups = new XSElementDecl[grammar.fSubGroups.length];
System.arraycopy(grammar.fSubGroups, 0, fSubGroups, 0, fSubGroupCount);
}
// Array to store complex type decls for constraint checking
fCTCount = grammar.fCTCount;
if (fCTCount > 0) {
fComplexTyp [MASK] s = new XSComplexTyp [MASK] [grammar.fComplexTyp [MASK] s.length];
fCTLocators = new SimpleLocator[grammar.fCTLocators.length];
System.arraycopy(grammar.fComplexTyp [MASK] s, 0, fComplexTyp [MASK] s, 0, fCTCount);
System.arraycopy(grammar.fCTLocators, 0, fCTLocators, 0, fCTCount);
}
// Groups being redefined by restriction
fRGCount = grammar.fRGCount;
if (fRGCount > 0) {
fRedefinedGroupDecls = new XSGroupDecl[grammar.fRedefinedGroupDecls.length];
fRGLocators = new SimpleLocator[grammar.fRGLocators.length];
System.arraycopy(grammar.fRedefinedGroupDecls, 0, fRedefinedGroupDecls, 0, fRGCount);
System.arraycopy(grammar.fRGLocators, 0, fRGLocators, 0, fRGCount/2);
}
// List of imported grammars
if (grammar.fImported != null) {
fImported = new ArrayList<>();
for (int i=0; i<grammar.fImported.size(); i++) {
fImported.add(grammar.fImported.get(i));
}
}
// Locations
if (grammar.fLocations != null) {
for (int k=0; k<grammar.fLocations.size(); k++) {
addDocument(null, grammar.fLocations.get(k));
}
}
} // <init>(String, XSDDescription)
// number of built-in XSTypes we need to create for base and full
// datatype set
private static final int BASICSET_COUNT = 29;
private static final int FULLSET_COUNT = 46;
private static final int GRAMMAR_XS = 1;
private static final int GRAMMAR_XSI = 2;
// this class makes sure the static, built-in schema grammars
// are immutable.
public static class BuiltinSchemaGrammar extends SchemaGrammar {
private static final String EXTENDED_SCHEMA_FACTORY_CLASS = "com.sun.org.apache.xerces.internal.impl.dv.xs.ExtendedSchemaDVFactoryImpl";
/**
* Special constructor to create the grammars for the schema namespaces
*
* @param grammar
*/
public BuiltinSchemaGrammar(int grammar, short schemaVersion) {
SchemaDVFactory schemaFactory;
if (schemaVersion == Constants.SCHEMA_VERSION_1_0) {
schemaFactory = SchemaDVFactory.getInstance();
}
else {
schemaFactory = SchemaDVFactory.getInstance(EXTENDED_SCHEMA_FACTORY_CLASS);
}
if (grammar == GRAMMAR_XS) {
// target namespace
fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA);
// no global decls other than types
fGlobalAttrDecls = new SymbolHash(1);
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(1);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(1);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTyp [MASK] sExt = new SymbolHash(1);
// all global element decls table
fAllGlobalElemDecls = new SymbolHash(1);
// get all built-in types
fGlobalTyp [MASK] s = schemaFactory.getBuiltInTypes();
// assign the built-in schema grammar as the XSNamespaceItem
// for each of the built-in simple type definitions.
int length = fGlobalTyp [MASK] s.getLength();
XSTypeDefinition [] typeDefinitions = new XSTypeDefinition[length];
fGlobalTyp [MASK] s.getValues(typeDefinitions, 0);
for (int i = 0; i < length; ++i) {
XSTypeDefinition xtd = typeDefinitions[i];
if (xtd instanceof XSSimpleTyp [MASK] ) {
((XSSimpleTyp [MASK] ) xtd).setNamespaceItem(this);
}
}
// add anyType
fGlobalTyp [MASK] s.put(fAnyType.getName(), fAnyType);
}
else if (grammar == GRAMMAR_XSI) {
// target namespace
fTargetNamespace = SchemaSymbols.URI_XSI;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_XSI);
// no global decls other than attributes
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(1);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
fGlobalTyp [MASK] s = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(1);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTyp [MASK] sExt = new SymbolHash(1);
// no all global element decls
fAllGlobalElemDecls = new SymbolHash(1);
// 4 attributes, so initialize the size as 4*2 = 8
fGlobalAttrDecls = new SymbolHash(8);
String name = null;
String tns = null;
XSSimpleType type = null;
short scope = XSConstants.SCOPE_GLOBAL;
// xsi:type
name = SchemaSymbols.XSI_TYPE;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_QNAME);
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
// xsi:nil
name = SchemaSymbols.XSI_NIL;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_BOOLEAN);
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
XSSimpleType anyURI = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_ANYURI);
// xsi:schemaLocation
name = SchemaSymbols.XSI_SCHEMALOCATION;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.createTypeList("#AnonType_schemaLocation", SchemaSymbols.URI_XSI, (short)0, anyURI, null);
if (type instanceof XSSimpleTyp [MASK] ) {
((XSSimpleTyp [MASK] )type).setAnonymous(true);
}
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
// xsi:noNamespaceSchemaLocation
name = SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION;
tns = SchemaSymbols.URI_XSI;
type = anyURI;
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
}
} // <init>(int)
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription.makeClone();
} // getGrammarDescription(): XMLGrammarDescription
// override these methods solely so that these
// objects cannot be modified once they're created.
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
// ignore
}
public void addGlobalAttribut [MASK] (XSAttribut [MASK] decl) {
// ignore
}
public void addGlobalAttribut [MASK] (XSAttribut [MASK] decl, String location) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
// ignore
}
public void addGlobalElementDeclAll(XSElementDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
// ignore
}
public void addGlobalTyp [MASK] (XSTypeDefinition decl) {
// ignore
}
public void addGlobalTyp [MASK] (XSTypeDefinition decl, String location) {
// ignore
}
public void addGlobalComplexTyp [MASK] (XSComplexTyp [MASK] decl) {
// ignore
}
public void addGlobalComplexTyp [MASK] (XSComplexTyp [MASK] decl, String location) {
// ignore
}
public void addGlobalSimpleTyp [MASK] (XSSimpleType decl) {
// ignore
}
public void addGlobalSimpleTyp [MASK] (XSSimpleType decl, String location) {
// ignore
}
public void addComplexTyp [MASK] (XSComplexTyp [MASK] decl, SimpleLocator locator) {
// ignore
}
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
// ignore
}
public synchronized void addDocument(Object document, String location) {
// ignore
}
// annotation support
synchronized DOMParser getDOMParser() {
return null;
}
synchronized SAXParser getSAXParser() {
return null;
}
}
/**
* <p>A partial schema for schemas for validating annotations.</p>
*
* @xerces.internal
*
* @author Michael Glavassevich, IBM
*/
public static final class Schema4Annotations extends SchemaGrammar {
/**
* Singleton instance.
*/
public static final Schema4Annotations INSTANCE = new Schema4Annotations();
/**
* Special constructor to create a schema
* capable of validating annotations.
*/
private Schema4Annotations() {
// target namespace
fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA);
// no global decls other than types and
// element declarations for <annotation>, <documentation> and <appinfo>.
fGlobalAttrDecls = new SymbolHash(1);
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(6);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(6);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTyp [MASK] sExt = new SymbolHash(1);
// all global element declarations
fAllGlobalElemDecls = new SymbolHash(6);
// get all built-in types
fGlobalTyp [MASK] s = SG_SchemaNS.fGlobalTyp [MASK] s;
// create element declarations for <annotation>, <documentation> and <appinfo>
XSElementDecl annotationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_ANNOTATION);
XSElementDecl documentationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_DOCUMENTATION);
XSElementDecl appinfoDecl = createAnnotationElementDecl(SchemaSymbols.ELT_APPINFO);
// add global element declarations
fGlobalElemDecls.put(annotationDecl.fName, annotationDecl);
fGlobalElemDecls.put(documentationDecl.fName, documentationDecl);
fGlobalElemDecls.put(appinfoDecl.fName, appinfoDecl);
fGlobalElemDeclsExt.put(","+annotationDecl.fName, annotationDecl);
fGlobalElemDeclsExt.put(","+documentationDecl.fName, documentationDecl);
fGlobalElemDeclsExt.put(","+appinfoDecl.fName, appinfoDecl);
fAllGlobalElemDecls.put(annotationDecl, annotationDecl);
fAllGlobalElemDecls.put(documentationDecl, documentationDecl);
fAllGlobalElemDecls.put(appinfoDecl, appinfoDecl);
// create complex type declarations for <annotation>, <documentation> and <appinfo>
XSComplexTyp [MASK] annotationType = new XSComplexTyp [MASK] ();
XSComplexTyp [MASK] documentationType = new XSComplexTyp [MASK] ();
XSComplexTyp [MASK] appinfoType = new XSComplexTyp [MASK] ();
// set the types on their element declarations
annotationDecl.fType = annotationType;
documentationDecl.fType = documentationType;
appinfoDecl.fType = appinfoType;
// create attribute groups for <annotation>, <documentation> and <appinfo>
XSAttributeGroupDecl annotationAttrs = new XSAttributeGroupDecl();
XSAttributeGroupDecl documentationAttrs = new XSAttributeGroupDecl();
XSAttributeGroupDecl appinfoAttrs = new XSAttributeGroupDecl();
// fill in attribute groups
{
// create and fill attribute uses for <annotation>, <documentation> and <appinfo>
XSAttributeUseImpl annotationIDAttr = new XSAttributeUseImpl();
annotationIDAttr.fAttrDecl = new XSAttribut [MASK] ();
annotationIDAttr.fAttrDecl.setValues(SchemaSymbols.ATT_ID, null, (XSSimpleType) fGlobalTyp [MASK] s.get(SchemaSymbols.ATTVAL_ID),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, annotationType, null);
annotationIDAttr.fUse = SchemaSymbols.USE_OPTIONAL;
annotationIDAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl documentationSourceAttr = new XSAttributeUseImpl();
documentationSourceAttr.fAttrDecl = new XSAttribut [MASK] ();
documentationSourceAttr.fAttrDecl.setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTyp [MASK] s.get(SchemaSymbols.ATTVAL_ANYURI),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, documentationType, null);
documentationSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL;
documentationSourceAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl documentationLangAttr = new XSAttributeUseImpl();
documentationLangAttr.fAttrDecl = new XSAttribut [MASK] ();
documentationLangAttr.fAttrDecl.setValues("lang".intern(), NamespaceContext.XML_URI, (XSSimpleType) fGlobalTyp [MASK] s.get(SchemaSymbols.ATTVAL_LANGUAGE),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, documentationType, null);
documentationLangAttr.fUse = SchemaSymbols.USE_OPTIONAL;
documentationLangAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl appinfoSourceAttr = new XSAttributeUseImpl();
appinfoSourceAttr.fAttrDecl = new XSAttribut [MASK] ();
appinfoSourceAttr.fAttrDecl.setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTyp [MASK] s.get(SchemaSymbols.ATTVAL_ANYURI),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, appinfoType, null);
appinfoSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL;
appinfoSourceAttr.fConstraintType = XSConstants.VC_NONE;
// create lax attribute wildcard for <annotation>, <documentation> and <appinfo>
XSWildcardDecl otherAttrs = new XSWildcardDecl();
otherAttrs.fNamespaceList = new String [] {fTargetNamespace, null};
otherAttrs.fType = XSWildcard.NSCONSTRAINT_NOT;
otherAttrs.fProcessContents = XSWildcard.PC_LAX;
// add attribute uses and wildcards to attribute groups for <annotation>, <documentation> and <appinfo>
annotationAttrs.addAttributeUse(annotationIDAttr);
annotationAttrs.fAttributeWC = otherAttrs;
documentationAttrs.addAttributeUse(documentationSourceAttr);
documentationAttrs.addAttributeUse(documentationLangAttr);
documentationAttrs.fAttributeWC = otherAttrs;
appinfoAttrs.addAttributeUse(appinfoSourceAttr);
appinfoAttrs.fAttributeWC = otherAttrs;
}
// create particles for <annotation>
XSParticl [MASK] annotationParticle = createUnboundedModelGroupParticle();
{
XSModelGroupImpl annotationChoice = new XSModelGroupImpl();
annotationChoice.fCompositor = XSModelGroupImpl.MODELGROUP_CHOICE;
annotationChoice.fParticleCount = 2;
annotationChoice.fParticles = new XSParticl [MASK] [2];
annotationChoice.fParticles[0] = createChoiceElementParticle(appinfoDecl);
annotationChoice.fParticles[1] = createChoiceElementParticle(documentationDecl);
annotationParticle.fValue = annotationChoice;
}
// create wildcard particle for <documentation> and <appinfo>
XSParticl [MASK] anyWCSequenceParticle = createUnboundedAnyWildcardSequenceParticle();
// fill complex types
annotationType.setValues("#AnonType_" + SchemaSymbols.ELT_ANNOTATION, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTyp [MASK] .CONTENTTYPE_ELEMENT, false, annotationAttrs, null, annotationParticle, XSObjectListImpl.EMPTY_LIST);
annotationType.setName("#AnonType_" + SchemaSymbols.ELT_ANNOTATION);
annotationType.setIsAnonymous();
documentationType.setValues("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTyp [MASK] .CONTENTTYPE_MIXED, false, documentationAttrs, null, anyWCSequenceParticle, XSObjectListImpl.EMPTY_LIST);
documentationType.setName("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION);
documentationType.setIsAnonymous();
appinfoType.setValues("#AnonType_" + SchemaSymbols.ELT_APPINFO, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTyp [MASK] .CONTENTTYPE_MIXED, false, appinfoAttrs, null, anyWCSequenceParticle, XSObjectListImpl.EMPTY_LIST);
appinfoType.setName("#AnonType_" + SchemaSymbols.ELT_APPINFO);
appinfoType.setIsAnonymous();
} // <init>(int)
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription.makeClone();
} // getGrammarDescription(): XMLGrammarDescription
// override these methods solely so that these
// objects cannot be modified once they're created.
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
// ignore
}
public void addGlobalAttribut [MASK] (XSAttribut [MASK] decl) {
// ignore
}
public void addGlobalAttribut [MASK] (XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
// ignore
}
public void addGlobalElementDeclAll(XSElementDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
// ignore
}
public void addGlobalTyp [MASK] (XSTypeDefinition decl) {
// ignore
}
public void addGlobalTyp [MASK] (XSTypeDefinition decl, String location) {
// ignore
}
public void addGlobalComplexTyp [MASK] (XSComplexTyp [MASK] decl) {
// ignore
}
public void addGlobalComplexTyp [MASK] (XSComplexTyp [MASK] decl, String location) {
// ignore
}
public void addGlobalSimpleTyp [MASK] (XSSimpleType decl) {
// ignore
}
public void addGlobalSimpleTyp [MASK] (XSSimpleType decl, String location) {
// ignore
}
public void addComplexTyp [MASK] (XSComplexTyp [MASK] decl, SimpleLocator locator) {
// ignore
}
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
// ignore
}
public synchronized void addDocument(Object document, String location) {
// ignore
}
// annotation support
synchronized DOMParser getDOMParser() {
return null;
}
synchronized SAXParser getSAXParser() {
return null;
}
//
// private helper methods
//
private XSElementDecl createAnnotationElementDecl(String localName) {
XSElementDecl [MASK] = new XSElementDecl();
[MASK] .fName = localName;
[MASK] .fTargetNamespace = fTargetNamespace;
[MASK] .setIsGlobal();
[MASK] .fBlock = (XSConstants.DERIVATION_EXTENSION |
XSConstants.DERIVATION_RESTRICTION | XSConstants.DERIVATION_SUBSTITUTION);
[MASK] .setConstraintType(XSConstants.VC_NONE);
return [MASK] ;
}
private XSParticl [MASK] createUnboundedModelGroupParticle() {
XSParticl [MASK] particle = new XSParticl [MASK] ();
particle.fMinOccurs = 0;
particle.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED;
particle.fType = XSParticl [MASK] .PARTICLE_MODELGROUP;
return particle;
}
private XSParticl [MASK] createChoiceElementParticle(XSElementDecl ref) {
XSParticl [MASK] particle = new XSParticl [MASK] ();
particle.fMinOccurs = 1;
particle.fMaxOccurs = 1;
particle.fType = XSParticl [MASK] .PARTICLE_ELEMENT;
particle.fValue = ref;
return particle;
}
private XSParticl [MASK] createUnboundedAnyWildcardSequenceParticle() {
XSParticl [MASK] particle = createUnboundedModelGroupParticle();
XSModelGroupImpl sequence = new XSModelGroupImpl();
sequence.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE;
sequence.fParticleCount = 1;
sequence.fParticles = new XSParticl [MASK] [1];
sequence.fParticles[0] = createAnyLaxWildcardParticle();
particle.fValue = sequence;
return particle;
}
private XSParticl [MASK] createAnyLaxWildcardParticle() {
XSParticl [MASK] particle = new XSParticl [MASK] ();
particle.fMinOccurs = 1;
particle.fMaxOccurs = 1;
particle.fType = XSParticl [MASK] .PARTICLE_WILDCARD;
XSWildcardDecl anyWC = new XSWildcardDecl();
anyWC.fNamespaceList = null;
anyWC.fType = XSWildcard.NSCONSTRAINT_ANY;
anyWC.fProcessContents = XSWildcard.PC_LAX;
particle.fValue = anyWC;
return particle;
}
}
// Grammar methods
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription;
} // getGrammarDescription(): XMLGrammarDescription
// DTDGrammar methods
public boolean isNamespaceAware () {
return true;
} // isNamespaceAware():boolean
List<SchemaGrammar> fImported = null;
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
fImported = importedGrammars;
}
public List<SchemaGrammar> getImportedGrammars() {
return fImported;
}
/**
* Returns this grammar's target namespace.
*/
public final String getTargetNamespace() {
return fTargetNamespace;
} // getTargetNamespace():String
/**
* register one global attribute
*/
public void addGlobalAttribut [MASK] (XSAttribut [MASK] decl) {
fGlobalAttrDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalAttribut [MASK] (XSAttribut [MASK] decl, String location) {
fGlobalAttrDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global attribute group
*/
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
fGlobalAttrGrpDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
fGlobalAttrGrpDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global element
*/
public void addGlobalElementDeclAll(XSElementDecl decl) {
if (fAllGlobalElemDecls.get(decl) == null) {
fAllGlobalElemDecls.put(decl, decl);
// if there is a substitution group affiliation, store in an array,
// for further constraint checking: UPA, PD, EDC
if (decl.fSubGroup != null) {
if (fSubGroupCount == fSubGroups.length)
fSubGroups = resize(fSubGroups, fSubGroupCount+INC_SIZE);
fSubGroups[fSubGroupCount++] = decl;
}
}
}
public void addGlobalElementDecl(XSElementDecl decl) {
fGlobalElemDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
fGlobalElemDeclsExt.put(((location != null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global group
*/
public void addGlobalGroupDecl(XSGroupDecl decl) {
fGlobalGroupDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
fGlobalGroupDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global notation
*/
public void addGlobalNotationDecl(XSNotationDecl decl) {
fGlobalNotationDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
fGlobalNotationDeclsExt.put(((location!=null) ? location : "") + "," +decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global type
*/
public void addGlobalTyp [MASK] (XSTypeDefinition decl) {
fGlobalTyp [MASK] s.put(decl.getName(), decl);
if (decl instanceof XSComplexTyp [MASK] ) {
((XSComplexTyp [MASK] ) decl).setNamespaceItem(this);
}
else if (decl instanceof XSSimpleTyp [MASK] ) {
((XSSimpleTyp [MASK] ) decl).setNamespaceItem(this);
}
}
public void addGlobalTyp [MASK] (XSTypeDefinition decl, String location) {
fGlobalTyp [MASK] sExt.put(((location!=null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null) {
if (decl instanceof XSComplexTyp [MASK] ) {
((XSComplexTyp [MASK] ) decl).setNamespaceItem(this);
}
else if (decl instanceof XSSimpleTyp [MASK] ) {
((XSSimpleTyp [MASK] ) decl).setNamespaceItem(this);
}
}
}
/**
* register one global complex type
*/
public void addGlobalComplexTyp [MASK] (XSComplexTyp [MASK] decl) {
fGlobalTyp [MASK] s.put(decl.getName(), decl);
decl.setNamespaceItem(this);
}
public void addGlobalComplexTyp [MASK] (XSComplexTyp [MASK] decl, String location) {
fGlobalTyp [MASK] sExt.put(((location!=null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global simple type
*/
public void addGlobalSimpleTyp [MASK] (XSSimpleType decl) {
fGlobalTyp [MASK] s.put(decl.getName(), decl);
if (decl instanceof XSSimpleTyp [MASK] ) {
((XSSimpleTyp [MASK] ) decl).setNamespaceItem(this);
}
}
public void addGlobalSimpleTyp [MASK] (XSSimpleType decl, String location) {
fGlobalTyp [MASK] sExt.put(((location != null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null && decl instanceof XSSimpleTyp [MASK] ) {
((XSSimpleTyp [MASK] ) decl).setNamespaceItem(this);
}
}
/**
* register one identity constraint
*/
public final void addIDConstraintDecl(XSElementDecl elmDecl, IdentityConstraint decl) {
elmDecl.addIDConstraint(decl);
fGlobalIDConstraintDecls.put(decl.getIdentityConstraintName(), decl);
}
public final void addIDConstraintDecl(XSElementDecl elmDecl, IdentityConstraint decl, String location) {
fGlobalIDConstraintDeclsExt.put(((location != null) ? location : "") + "," + decl.getIdentityConstraintName(), decl);
}
/**
* get one global attribute
*/
public final XSAttribut [MASK] getGlobalAttribut [MASK] (String declName) {
return(XSAttribut [MASK] )fGlobalAttrDecls.get(declName);
}
public final XSAttribut [MASK] getGlobalAttribut [MASK] (String declName, String location) {
return(XSAttribut [MASK] )fGlobalAttrDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global attribute group
*/
public final XSAttributeGroupDecl getGlobalAttributeGroupDecl(String declName) {
return(XSAttributeGroupDecl)fGlobalAttrGrpDecls.get(declName);
}
public final XSAttributeGroupDecl getGlobalAttributeGroupDecl(String declName, String location) {
return(XSAttributeGroupDecl)fGlobalAttrGrpDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global element
*/
public final XSElementDecl getGlobalElementDecl(String declName) {
return(XSElementDecl)fGlobalElemDecls.get(declName);
}
public final XSElementDecl getGlobalElementDecl(String declName, String location) {
return(XSElementDecl)fGlobalElemDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global group
*/
public final XSGroupDecl getGlobalGroupDecl(String declName) {
return(XSGroupDecl)fGlobalGroupDecls.get(declName);
}
public final XSGroupDecl getGlobalGroupDecl(String declName, String location) {
return(XSGroupDecl)fGlobalGroupDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global notation
*/
public final XSNotationDecl getGlobalNotationDecl(String declName) {
return(XSNotationDecl)fGlobalNotationDecls.get(declName);
}
public final XSNotationDecl getGlobalNotationDecl(String declName, String location) {
return(XSNotationDecl)fGlobalNotationDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global type
*/
public final XSTypeDefinition getGlobalTyp [MASK] (String declName) {
return(XSTypeDefinition)fGlobalTyp [MASK] s.get(declName);
}
public final XSTypeDefinition getGlobalTyp [MASK] (String declName, String location) {
return(XSTypeDefinition)fGlobalTyp [MASK] sExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one identity constraint
*/
public final IdentityConstraint getIDConstraintDecl(String declName) {
return(IdentityConstraint)fGlobalIDConstraintDecls.get(declName);
}
public final IdentityConstraint getIDConstraintDecl(String declName, String location) {
return(IdentityConstraint)fGlobalIDConstraintDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one identity constraint
*/
public final boolean hasIDConstraints() {
return fGlobalIDConstraintDecls.getLength() > 0;
}
// array to store complex type decls
private static final int INITIAL_SIZE = 16;
private static final int INC_SIZE = 16;
private int fCTCount = 0;
private XSComplexTyp [MASK] [] fComplexTyp [MASK] s = new XSComplexTyp [MASK] [INITIAL_SIZE];
private SimpleLocator[] fCTLocators = new SimpleLocator[INITIAL_SIZE];
// an array to store groups being redefined by restriction
// even-numbered elements are the derived groups, odd-numbered ones their bases
private static final int REDEFINED_GROUP_INIT_SIZE = 2;
private int fRGCount = 0;
private XSGroupDecl[] fRedefinedGroupDecls = new XSGroupDecl[REDEFINED_GROUP_INIT_SIZE];
private SimpleLocator[] fRGLocators = new SimpleLocator[REDEFINED_GROUP_INIT_SIZE/2];
// a flag to indicate whether we have checked the 3 constraints on this
// grammar.
boolean fFullChecked = false;
/**
* add one complex type decl: for later constraint checking
*/
public void addComplexTyp [MASK] (XSComplexTyp [MASK] decl, SimpleLocator locator) {
if (fCTCount == fComplexTyp [MASK] s.length) {
fComplexTyp [MASK] s = resize(fComplexTyp [MASK] s, fCTCount+INC_SIZE);
fCTLocators = resize(fCTLocators, fCTCount+INC_SIZE);
}
fCTLocators[fCTCount] = locator;
fComplexTyp [MASK] s[fCTCount++] = decl;
}
/**
* add a group redefined by restriction: for later constraint checking
*/
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
if (fRGCount == fRedefinedGroupDecls.length) {
// double array size each time.
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount << 1);
fRGLocators = resize(fRGLocators, fRGCount);
}
fRGLocators[fRGCount/2] = locator;
fRedefinedGroupDecls[fRGCount++] = derived;
fRedefinedGroupDecls[fRGCount++] = base;
}
/**
* get all complex type decls: for later constraint checking
*/
final XSComplexTyp [MASK] [] getUncheckedComplexTyp [MASK] s() {
if (fCTCount < fComplexTyp [MASK] s.length) {
fComplexTyp [MASK] s = resize(fComplexTyp [MASK] s, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
return fComplexTyp [MASK] s;
}
/**
* get the error locator of all complex type decls
*/
final SimpleLocator[] getUncheckedCTLocators() {
if (fCTCount < fCTLocators.length) {
fComplexTyp [MASK] s = resize(fComplexTyp [MASK] s, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
return fCTLocators;
}
/**
* get all redefined groups: for later constraint checking
*/
final XSGroupDecl[] getRedefinedGroupDecls() {
if (fRGCount < fRedefinedGroupDecls.length) {
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount);
fRGLocators = resize(fRGLocators, fRGCount/2);
}
return fRedefinedGroupDecls;
}
/**
* get the error locator of all redefined groups
*/
final SimpleLocator[] getRGLocators() {
if (fRGCount < fRedefinedGroupDecls.length) {
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount);
fRGLocators = resize(fRGLocators, fRGCount/2);
}
return fRGLocators;
}
/**
* after the first-round checking, some types don't need to be checked
* against UPA again. here we trim the array to the proper size.
*/
final void setUncheckedTypeNum(int newSize) {
fCTCount = newSize;
fComplexTyp [MASK] s = resize(fComplexTyp [MASK] s, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
// used to store all substitution group information declared in
// this namespace
private int fSubGroupCount = 0;
private XSElementDecl[] fSubGroups = new XSElementDecl[INITIAL_SIZE];
/**
* get all substitution group information: for the 3 constraint checking
*/
final XSElementDecl[] getSubstitutionGroups() {
if (fSubGroupCount < fSubGroups.length)
fSubGroups = resize(fSubGroups, fSubGroupCount);
return fSubGroups;
}
// anyType and anySimpleType: because there are so many places where
// we need direct access to these two types
public final static XSComplexTyp [MASK] fAnyType = new XSAnyType();
private static class XSAnyType extends XSComplexTyp [MASK] {
public XSAnyType () {
fName = SchemaSymbols.ATTVAL_ANYTYPE;
super.fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
fBaseType = this;
fDerivedBy = XSConstants.DERIVATION_RESTRICTION;
fContentType = XSComplexTyp [MASK] .CONTENTTYPE_MIXED;
fParticle = createParticle();
fAttrGrp = createAttrGrp();
}
// overridden methods
public void setValues(String name, String targetNamespace,
XSTypeDefinition baseType, short derivedBy, short schemaFinal,
short block, short contentType,
boolean isAbstract, XSAttributeGroupDecl attrGrp,
XSSimpleType simpleType, XSParticl [MASK] particle) {
// don't allow this.
}
public void setName(String name){
// don't allow this.
}
public void setIsAbstractType() {
// null implementation
}
public void setContainsTypeID() {
// null implementation
}
public void setIsAnonymous() {
// null implementation
}
public void reset() {
// null implementation
}
public XSObjectList getAnnotations() {
return XSObjectListImpl.EMPTY_LIST;
}
public XSNamespaceItem getNamespaceItem() {
return SG_SchemaNS;
}
private XSAttributeGroupDecl createAttrGrp() {
XSWildcardDecl wildcard = new XSWildcardDecl();
wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
XSAttributeGroupDecl attrGrp = new XSAttributeGroupDecl();
attrGrp.fAttributeWC = wildcard;
return attrGrp;
}
private XSParticl [MASK] createParticle() {
// the wildcard used in anyType (content and attribute)
// the spec will change strict to skip for anyType
XSWildcardDecl wildcard = new XSWildcardDecl();
wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
// the particle for the content wildcard
XSParticl [MASK] particleW = new XSParticl [MASK] ();
particleW.fMinOccurs = 0;
particleW.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED;
particleW.fType = XSParticl [MASK] .PARTICLE_WILDCARD;
particleW.fValue = wildcard;
// the model group of a sequence of the above particle
XSModelGroupImpl group = new XSModelGroupImpl();
group.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE;
group.fParticleCount = 1;
group.fParticles = new XSParticl [MASK] [1];
group.fParticles[0] = particleW;
// the content of anyType: particle of the above model group
XSParticl [MASK] particleG = new XSParticl [MASK] ();
particleG.fType = XSParticl [MASK] .PARTICLE_MODELGROUP;
particleG.fValue = group;
return particleG;
}
}
private static class BuiltinAttrDecl extends XSAttribut [MASK] {
public BuiltinAttrDecl(String name, String tns,
XSSimpleType type, short scope) {
fName = name;
super.fTargetNamespace = tns;
fType = type;
fScope = scope;
}
public void setValues(String name, String targetNamespace,
XSSimpleType simpleType, short constraintType, short scope,
ValidatedInfo valInfo, XSComplexTyp [MASK] enclosingCT) {
// ignore this call.
}
public void reset () {
// also ignore this call.
}
public XSAnnotation getAnnotation() {
return null;
}
public XSNamespaceItem getNamespaceItem() {
return SG_XSI;
}
} // class BuiltinAttrDecl
// the grammars to hold components of the schema namespace
public final static BuiltinSchemaGrammar SG_SchemaNS = new BuiltinSchemaGrammar(GRAMMAR_XS, Constants.SCHEMA_VERSION_1_0);
private final static BuiltinSchemaGrammar SG_SchemaNSExtended = new BuiltinSchemaGrammar(GRAMMAR_XS, Constants.SCHEMA_VERSION_1_0_EXTENDED);
public final static XSSimpleType fAnySimpleType = (XSSimpleType)SG_SchemaNS.getGlobalTyp [MASK] (SchemaSymbols.ATTVAL_ANYSIMPLETYPE);
// the grammars to hold components of the schema-instance namespace
public final static BuiltinSchemaGrammar SG_XSI = new BuiltinSchemaGrammar(GRAMMAR_XSI, Constants.SCHEMA_VERSION_1_0);
public static SchemaGrammar getS4SGrammar(short schemaVersion) {
if (schemaVersion == Constants.SCHEMA_VERSION_1_0) {
return SG_SchemaNS;
}
else {
return SG_SchemaNSExtended;
}
}
static final XSComplexTyp [MASK] [] resize(XSComplexTyp [MASK] [] oldArray, int newSize) {
XSComplexTyp [MASK] [] newArray = new XSComplexTyp [MASK] [newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final XSGroupDecl[] resize(XSGroupDecl[] oldArray, int newSize) {
XSGroupDecl[] newArray = new XSGroupDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final XSElementDecl[] resize(XSElementDecl[] oldArray, int newSize) {
XSElementDecl[] newArray = new XSElementDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final SimpleLocator[] resize(SimpleLocator[] oldArray, int newSize) {
SimpleLocator[] newArray = new SimpleLocator[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
// XSNamespaceItem methods
// the max index / the max value of XSObject type
private static final short MAX_COMP_IDX = XSTypeDefinition.SIMPLE_TYPE;
private static final boolean[] GLOBAL_COMP = {false, // null
true, // attribute
true, // element
true, // type
false, // attribute use
true, // attribute group
true, // group
false, // model group
false, // particle
false, // wildcard
true, // idc
true, // notation
false, // annotation
false, // facet
false, // multi value facet
true, // complex type
true // simple type
};
// store a certain kind of components from all namespaces
private XSNamedMap[] fComponents = null;
private ObjectList[] fComponentsExt = null;
// store the documents and their locations contributing to this namespace
// REVISIT: use StringList and XSObjectList for there fields.
// fDocuments is never used
private List<Object> fDocuments = null;
private List<String> fLocations = null;
public synchronized void addDocument(Object document, String location) {
if (fDocuments == null) {
// Parsing schema is not thread safe, synchronized may be removed
fDocuments = new CopyOnWriteArrayList<>();
fLocations = new CopyOnWriteArrayList<>();
}
fDocuments.add(document);
fLocations.add(location);
}
public synchronized void removeDocument(int index) {
if (fDocuments != null &&
index >= 0 &&
index < fDocuments.size()) {
fDocuments.remove(index);
fLocations.remove(index);
}
}
/**
* [schema namespace]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#nsi-schema_namespace">[schema namespace]</a>
* @return The target namespace of this item.
*/
public String getSchemaNamespace() {
return fTargetNamespace;
}
// annotation support
synchronized DOMParser getDOMParser() {
if (fDOMParser != null) {
DOMParser parser = fDOMParser.get();
if (parser != null) {
return parser;
}
}
// REVISIT: when schema handles XML 1.1, will need to
// revisit this (and the practice of not prepending an XML decl to the annotation string
XML11Configuration config = new XML11Configuration(fSymbolTable);
// note that this should never produce errors or require
// entity resolution, so just a barebones configuration with
// a couple of feature set will do fine
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true);
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false);
DOMParser parser = new DOMParser(config);
try {
parser.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.DEFER_NODE_EXPANSION_FEATURE, false);
}
catch (SAXException exc) {}
fDOMParser = new SoftReference<DOMParser>(parser);
return parser;
}
synchronized SAXParser getSAXParser() {
if (fSAXParser != null) {
SAXParser parser = fSAXParser.get();
if (parser != null) {
return parser;
}
}
// REVISIT: when schema handles XML 1.1, will need to
// revisit this (and the practice of not prepending an XML decl to the annotation string
XML11Configuration config = new XML11Configuration(fSymbolTable);
// note that this should never produce errors or require
// entity resolution, so just a barebones configuration with
// a couple of feature set will do fine
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true);
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false);
SAXParser parser = new SAXParser(config);
fSAXParser = new SoftReference<SAXParser>(parser);
return parser;
}
/**
* [schema components]: a list of top-level components, i.e. element
* declarations, attribute declarations, etc.
* @param objectType The type of the declaration, i.e.
* <code>ELEMENT_DECLARATION</code>. Note that
* <code>XSTypeDefinition.SIMPLE_TYPE</code> and
* <code>XSTypeDefinition.COMPLEX_TYPE</code> can also be used as the
* <code>objectType</code> to retrieve only complex types or simple
* types, instead of all types.
* @return A list of top-level definition of the specified type in
* <code>objectType</code> or an empty <code>XSNamedMap</code> if no
* such definitions exist.
*/
public synchronized XSNamedMap getComponents(short objectType) {
if (objectType <= 0 || objectType > MAX_COMP_IDX ||
!GLOBAL_COMP[objectType]) {
return XSNamedMapImpl.EMPTY_MAP;
}
if (fComponents == null)
fComponents = new XSNamedMap[MAX_COMP_IDX+1];
// get the hashtable for this type of components
if (fComponents[objectType] == null) {
SymbolHash table = null;
switch (objectType) {
case XSConstants.TYPE_DEFINITION:
case XSTypeDefinition.COMPLEX_TYPE:
case XSTypeDefinition.SIMPLE_TYPE:
table = fGlobalTyp [MASK] s;
break;
case XSConstants.ATTRIBUTE_DECLARATION:
table = fGlobalAttrDecls;
break;
case XSConstants.ELEMENT_DECLARATION:
table = fGlobalElemDecls;
break;
case XSConstants.ATTRIBUTE_GROUP:
table = fGlobalAttrGrpDecls;
break;
case XSConstants.MODEL_GROUP_DEFINITION:
table = fGlobalGroupDecls;
break;
case XSConstants.NOTATION_DECLARATION:
table = fGlobalNotationDecls;
break;
case XSConstants.IDENTITY_CONSTRAINT:
table = this.fGlobalIDConstraintDecls;
break;
}
// for complex/simple types, create a special implementation,
// which take specific types out of the hash table
if (objectType == XSTypeDefinition.COMPLEX_TYPE ||
objectType == XSTypeDefinition.SIMPLE_TYPE) {
fComponents[objectType] = new XSNamedMap4Types(fTargetNamespace, table, objectType);
}
else {
fComponents[objectType] = new XSNamedMapImpl(fTargetNamespace, table);
}
}
return fComponents[objectType];
}
public synchronized ObjectList getComponentsExt(short objectType) {
if (objectType <= 0 || objectType > MAX_COMP_IDX ||
!GLOBAL_COMP[objectType]) {
return ObjectListImpl.EMPTY_LIST;
}
if (fComponentsExt == null)
fComponentsExt = new ObjectList[MAX_COMP_IDX+1];
// get the hashtable for this type of components
if (fComponentsExt[objectType] == null) {
SymbolHash table = null;
switch (objectType) {
case XSConstants.TYPE_DEFINITION:
case XSTypeDefinition.COMPLEX_TYPE:
case XSTypeDefinition.SIMPLE_TYPE:
table = fGlobalTyp [MASK] sExt;
break;
case XSConstants.ATTRIBUTE_DECLARATION:
table = fGlobalAttrDeclsExt;
break;
case XSConstants.ELEMENT_DECLARATION:
table = fGlobalElemDeclsExt;
break;
case XSConstants.ATTRIBUTE_GROUP:
table = fGlobalAttrGrpDeclsExt;
break;
case XSConstants.MODEL_GROUP_DEFINITION:
table = fGlobalGroupDeclsExt;
break;
case XSConstants.NOTATION_DECLARATION:
table = fGlobalNotationDeclsExt;
break;
case XSConstants.IDENTITY_CONSTRAINT:
table = this.fGlobalIDConstraintDeclsExt;
break;
}
Object[] entries = table.getEntries();
fComponentsExt[objectType] = new ObjectListImpl(entries, entries.length);
}
return fComponentsExt[objectType];
}
public synchronized void resetComponents() {
fComponents = null;
fComponentsExt = null;
}
/**
* Convenience method. Returns a top-level simple or complex type
* definition.
* @param name The name of the definition.
* @return An <code>XSTypeDefinition</code> or null if such definition
* does not exist.
*/
public XSTypeDefinition getTypeDefinition(String name) {
return getGlobalTyp [MASK] (name);
}
/**
* Convenience method. Returns a top-level attribute declaration.
* @param name The name of the declaration.
* @return A top-level attribute declaration or null if such declaration
* does not exist.
*/
public XSAttribut [MASK] aration getAttribut [MASK] aration(String name) {
return getGlobalAttribut [MASK] (name);
}
/**
* Convenience method. Returns a top-level element declaration.
* @param name The name of the declaration.
* @return A top-level element declaration or null if such declaration
* does not exist.
*/
public XSElementDeclaration getElementDeclaration(String name) {
return getGlobalElementDecl(name);
}
/**
* Convenience method. Returns a top-level attribute group definition.
* @param name The name of the definition.
* @return A top-level attribute group definition or null if such
* definition does not exist.
*/
public XSAttributeGroupDefinition getAttributeGroup(String name) {
return getGlobalAttributeGroupDecl(name);
}
/**
* Convenience method. Returns a top-level model group definition.
*
* @param name The name of the definition.
* @return A top-level model group definition definition or null if such
* definition does not exist.
*/
public XSModelGroupDefinition getModelGroupDefinition(String name) {
return getGlobalGroupDecl(name);
}
/**
* Convenience method. Returns a top-level notation declaration.
*
* @param name The name of the declaration.
* @return A top-level notation declaration or null if such declaration
* does not exist.
*/
public XSNotationDeclaration getNotationDeclaration(String name) {
return getGlobalNotationDecl(name);
}
public XSIDCDefinition getIDCDefinition(String name) {
return getIDConstraintDecl(name);
}
/**
* [document location]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#sd-document_location">[document location]</a>
* @return a list of document information item
*/
public StringList getDocumentLocations() {
return new StringListImpl(fLocations);
}
/**
* Return an <code>XSModel</code> that represents components in this schema
* grammar.
*
* @return an <code>XSModel</code> representing this schema grammar
*/
public XSModel toXSModel() {
return new XSModelImpl(new SchemaGrammar[]{this});
}
public XSModel toXSModel(XSGrammar[] grammars) {
if (grammars == null || grammars.length == 0)
return toXSModel();
int len = grammars.length;
boolean hasSelf = false;
for (int i = 0; i < len; i++) {
if (grammars[i] == this) {
hasSelf = true;
break;
}
}
SchemaGrammar[] gs = new SchemaGrammar[hasSelf ? len : len+1];
for (int i = 0; i < len; i++)
gs[i] = (SchemaGrammar)grammars[i];
if (!hasSelf)
gs[len] = this;
return new XSModelImpl(gs);
}
/**
* @see org.apache.xerces.xs.XSNamespaceItem#getAnnotations()
*/
public XSObjectList getAnnotations() {
if (fNumAnnotations == 0) {
return XSObjectListImpl.EMPTY_LIST;
}
return new XSObjectListImpl(fAnnotations, fNumAnnotations);
}
public void addAnnotation(XSAnnotationImpl annotation) {
if (annotation == null) {
return;
}
if (fAnnotations == null) {
fAnnotations = new XSAnnotationImpl[2];
}
else if (fNumAnnotations == fAnnotations.length) {
XSAnnotationImpl[] newArray = new XSAnnotationImpl[fNumAnnotations << 1];
System.arraycopy(fAnnotations, 0, newArray, 0, fNumAnnotations);
fAnnotations = newArray;
}
fAnnotations[fNumAnnotations++] = annotation;
}
public void setImmutable(boolean isImmutable) {
fIsImmutable = isImmutable;
}
public boolean isImmutable() {
return fIsImmutable;
}
} // class SchemaGrammar
| eDecl |
/*
* Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.hosted;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.stream.Collectors;
import org.graalvm.nativeimage.hosted.RuntimeReflection;
import org.graalvm.nativeimage.hosted.RuntimeResourceAccess;
import com.oracle.svm.core.feature.AutomaticallyRegisteredFeature;
import com.oracle.svm.core.feature.InternalFeature;
import com.oracle.svm.core.jdk.ServiceCatalogSupport;
import com.oracle.svm.core.option.AccumulatingLocatableMultiOptionValue;
import com.oracle.svm.core.option.HostedOptionKey;
import com.oracle.svm.hosted.analysis.Inflation;
import jdk.graal.compiler.options.Option;
import jdk.graal.compiler.options.OptionType;
/**
* Support for {@link ServiceLoader} on Substrate VM.
*
* Services are registered in the folder {@code "META-INF/services/"} using files whose name is the
* fully qualified service interface name. We do not know which services are going to be used by a
* native image: The parameter of {@code ServiceLoader#load} is often but not always a compile-time
* constant that we can track. But we also cannot put all registered services into the native image.
*
* We therefore use the following heuristic: We add all service loader files and service
* implementation classes when the service interfaces that are seen as reachable by the static
* analysis.
*
* Each used service implementation class is added for reflection (using
* {@link org.graalvm.nativeimage.hosted.RuntimeReflection#register(Class[])}) and for reflective
* instantiation (using {@link RuntimeReflection#registerForReflectiveInstantiation(Class[])}).
*
* For each service interface, a single service loader file is added as a resource to the image. The
* single file combines all the individual files that can come from different .jar files.
*/
@AutomaticallyRegisteredFeature
public class ServiceLoaderFeature implements InternalFeature {
public static class Options {
@Option(help = "Automatically register services for run-time lookup using ServiceLoader", type = OptionType.Expert) //
public static final HostedOptionKey<Boolean> UseServiceLoaderFeature = new HostedOptionKey<>(true);
@Option(help = "Comma-separated list of services that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServices = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
@Option(help = "Comma-separated list of service providers that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServiceProviders = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
}
private static final Set<String> SKIPPED_SERVICES = Set.of(
// image builder internal ServiceLoader interfaces
"com.oracle.svm.hosted.NativeImageClassLoaderPostProcessing",
"org.graalvm.nativeimage.Platform",
/*
* Loaded in java.util.random.RandomGeneratorFactory.FactoryMapHolder, which is
* initialized at image build time.
*/
"java.util.random.RandomGenerator",
"java.security.Provider", // see SecurityServicesFeature
"sun.util.locale.provider.LocaleDataMetaInfo", // see LocaleSubstitutions
/* Graal hotspot-specific services */
"jdk.vm.ci.hotspot.HotSpotJVMCIBackendFactory",
"jdk.graal.compiler.hotspot.CompilerConfigurationFactory",
"jdk.graal.compiler.hotspot.HotSpotBackendFactory",
"jdk.graal.compiler.hotspot.meta.DefaultHotSpotLoweringProvider$Extensions",
"jdk.graal.compiler.hotspot.meta.HotSpotInvocationPluginProvider",
"jdk.graal.compiler.truffle.hotspot.TruffleCallBoundaryInstrumentationFactory");
// NOTE: Platform class had to be added to this list since our analysis discovers that
// Platform.includedIn is reachable regardless of fact that it is constant folded at
// registerPlatformPlugins method of SubstrateGraphBuilderPlugins. This issue hasn't manifested
// before because implementation classes were instantiated using runtime reflection instead of
// ServiceLoader (and thus weren't reachable in analysis).
/**
* Services that should not be processed here, for example because they are handled by
* specialized features.
*/
private final Set<String> servicesToSkip = new HashSet<>(SKIPPED_SERVICES);
private static final Set<String> SKIPPED_PROVIDERS = Set.of(
/* Graal hotspot-specific service-providers */
"jdk.graal.compiler.hotspot.meta.HotSpotDisassemblerProvider",
/* Skip console providers until GR-44085 is fixed */
"jdk.internal.org.jline.JdkConsoleProviderImpl", "jdk.jshell.execution.impl.ConsoleImpl$ConsoleProviderImpl");
private final Set<String> serviceProvidersToSkip = new HashSet<>(SKIPPED_PROVIDERS);
@Override
public boolean isInConfiguration(IsInConfigurationAccess access) {
return Options.UseServiceLoaderFeature.getValue();
}
@Override
public void afterRegistration(AfterRegistrationAccess access) {
servicesToSkip.addAll(Options.ServiceLoaderFeatureExcludeServices.getValue().values());
serviceProvidersToSkip.addAll(Options.ServiceLoaderFeatureExcludeServiceProviders.getValue().values());
}
@Override
public void beforeAnalysis(BeforeAnalysisAccess access) {
FeatureImpl.BeforeAnalysisAccessImpl accessImpl = (FeatureImpl.BeforeAnalysisAccessImpl) access;
accessImpl.imageClassLoader.classLoaderSupport.serviceProvidersForEach((serviceName, providers) -> {
Class<?> serviceClass = access.findClassByName(serviceName);
boolean skipService = false;
/* If the service should not end up in the image, we remove all the providers with it */
Collection<String> providersToSkip = providers;
if (servicesToSkip.contains(serviceName)) {
skipService = true;
} else if (serviceClass == null || serviceClass.isArray() || serviceClass.isPrimitive()) {
skipService = true;
} else if (!accessImpl.getHostVM().platformSupported(serviceClass)) {
skipService = true;
} else {
providersToSkip = providers.stream().filter(serviceProvidersToSkip::contains).collect(Collectors.toList());
if (!providersToSkip.isEmpty()) {
skipService = true;
}
}
if (skipService) {
ServiceCatalogSupport.singleton().removeServicesFromServicesCatalog(serviceName, new HashSet<>(providersToSkip));
return;
}
access.registerReachabilityHandler(a -> handleServiceClassIsReachable(a, serviceClass, providers), serviceClass);
});
}
void handleServiceClassIsReachable(DuringAnalysisAccess access, Class<?> serviceProvider, Collection<String> providers) {
LinkedHashSet<String> registeredProviders = new LinkedHashSet<>();
for (String provider : providers) {
if (serviceProvidersToSkip.contains(provider)) {
continue;
}
/* Make provider reflectively instantiable */
Class<?> providerClass = access.findClassByName(provider);
if (providerClass == null || providerClass.isArray() || providerClass.isPrimitive()) {
continue;
}
FeatureImpl.DuringAnalysisAccessImpl accessImpl = (FeatureImpl.DuringAnalysisAccessImpl) access;
if (!accessImpl.getHostVM().platformSupported(providerClass)) {
continue;
}
if (((Inflation) accessImpl.getBigBang()).getAnnotationSubstitutionProcessor().isDeleted(providerClass)) {
/* Disallow services with implementation classes that are marked as @Deleted */
continue;
}
/*
* Find either a public static provider() method or a nullary [MASK] (or both).
* Skip providers that do not comply with requirements.
*
* See ServiceLoader#loadProvider and ServiceLoader#findStaticProviderMethod.
*/
Constructor<?> nullaryConstructor = null;
Method nullaryProviderMethod = null;
try {
/* Only look for a provider() method if provider class is in an explicit module. */
if (providerClass.getModule().isNamed() && !providerClass.getModule().getDescriptor().isAutomatic()) {
for (Method method : providerClass.getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers()) &&
method.getParameterCount() == 0 && method.getName().equals("provider")) {
if (nullaryProviderMethod == null) {
nullaryProviderMethod = method;
} else {
/* There must be at most one public static provider() method. */
nullaryProviderMethod = null;
break;
}
}
}
}
Constructor<?> [MASK] = providerClass.getDeclaredConstructor();
if (Modifier.isPublic( [MASK] .getModifiers())) {
nullaryConstructor = [MASK] ;
}
} catch (NoSuchMethodException | SecurityException | LinkageError e) {
// ignore
}
if (nullaryConstructor != null || nullaryProviderMethod != null) {
RuntimeReflection.register(providerClass);
if (nullaryConstructor != null) {
/*
* Registering a [MASK] with
* RuntimeReflection.registerConstructorLookup(providerClass) does not produce
* the same behavior as using RuntimeReflection.register(nullaryConstructor). In
* the first case, the [MASK] is marked for query purposes only, so this
* if-statement cannot be eliminated.
*
*/
RuntimeReflection.register(nullaryConstructor);
} else {
/*
* If there's no nullary [MASK] , register it as negative lookup to avoid
* throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerConstructorLookup(providerClass);
}
if (nullaryProviderMethod != null) {
RuntimeReflection.register(nullaryProviderMethod);
} else {
/*
* If there's no declared public provider() method, register it as negative
* lookup to avoid throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerMethodLookup(providerClass, "provider");
}
}
/*
* Register the provider in both cases: when it is JCA-compliant (has a nullary
* [MASK] or a provider method) or when it lacks both. If neither is present, a
* ServiceConfigurationError will be thrown at runtime, consistent with HotSpot
* behavior.
*/
registeredProviders.add(provider);
}
if (!registeredProviders.isEmpty()) {
String serviceResourceLocation = "META-INF/services/" + serviceProvider.getName();
byte[] serviceFileData = registeredProviders.stream().collect(Collectors.joining("\n")).getBytes(StandardCharsets.UTF_8);
RuntimeResourceAccess.addResource(access.getApplicationClassLoader().getUnnamedModule(), serviceResourceLocation, serviceFileData);
}
}
}
| constructor |
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
*/
/*
* 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 com.sun.org.apache.xerces.internal.impl.xs;
import com.sun.org.apache.xerces.internal.impl.Constants;
import com.sun.org.apache.xerces.internal.impl.dv.SchemaDVFactory;
import com.sun.org.apache.xerces.internal.impl.dv.ValidatedInfo;
import com.sun.org.apache.xerces.internal.impl.dv.XSSimpleType;
import com.sun.org.apache.xerces.internal.impl.dv.xs.XSSimpleTypeDecl;
import com.sun.org.apache.xerces.internal.impl.xs.identity.IdentityConstraint;
import com.sun.org.apache.xerces.internal.impl.xs.util.ObjectListImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.SimpleLocator;
import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSNamedMap4Types;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSNamedMapImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSObjectListImpl;
import com.sun.org.apache.xerces.internal.parsers.DOMParser;
import com.sun.org.apache.xerces.internal.parsers.SAXParser;
import com.sun.org.apache.xerces.internal.parsers.XML11Configuration;
import com.sun.org.apache.xerces.internal.util.SymbolHash;
import com.sun.org.apache.xerces.internal.util.SymbolTable;
import com.sun.org.apache.xerces.internal.xni.NamespaceContext;
import com.sun.org.apache.xerces.internal.xni.grammars.XMLGrammarDescription;
import com.sun.org.apache.xerces.internal.xni.grammars.XSGrammar;
import com.sun.org.apache.xerces.internal.xs.StringList;
import com.sun.org.apache.xerces.internal.xs.XSAnnotation;
import com.sun.org.apache.xerces.internal.xs.XSAttributeDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSAttributeGroupDefinition;
import com.sun.org.apache.xerces.internal.xs.XSConstants;
import com.sun.org.apache.xerces.internal.xs.XSElementDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSIDCDefinition;
import com.sun.org.apache.xerces.internal.xs.XSModel;
import com.sun.org.apache.xerces.internal.xs.XSModelGroupDefinition;
import com.sun.org.apache.xerces.internal.xs.XSNamedMap;
import com.sun.org.apache.xerces.internal.xs.XSNamespaceItem;
import com.sun.org.apache.xerces.internal.xs.XSNotationDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSObjectList;
import com.sun.org.apache.xerces.internal.xs.XSParticle;
import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
import com.sun.org.apache.xerces.internal.xs.XSWildcard;
import com.sun.org.apache.xerces.internal.xs.datatypes.ObjectList;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.xml.sax.SAXException;
/**
* This class is to hold all schema component declaration that are declared
* within one namespace.
*
* The Grammar class this class extends contains what little
* commonality there is between XML Schema and DTD grammars. It's
* useful to distinguish grammar objects from other kinds of object
* when they exist in pools or caches.
*
* @xerces.internal
*
* @author Sandy Gao, IBM
* @author Elena Litani, IBM
*
* @LastModified: Oct 2017
*/
public class SchemaGrammar implements XSGrammar, XSNamespaceItem {
// the target namespace of grammar
String fTargetNamespace;
// global decls: map from decl name to decl object
SymbolHash fGlobalAttrDecls;
SymbolHash fGlobalAttrGrpDecls;
SymbolHash fGlobalElemDecls;
SymbolHash fGlobalGroupDecls;
SymbolHash fGlobalNotationDecls;
SymbolHash fGlobalIDConstraintDecls;
SymbolHash fGlobalTypeDecls;
// extended global decls: map from schema location + decl name to decl object
// key is location,name
SymbolHash fGlobalAttrDeclsExt;
SymbolHash fGlobalAttrGrpDeclsExt;
SymbolHash fGlobalElemDeclsExt;
SymbolHash fGlobalGroupDeclsExt;
SymbolHash fGlobalNotationDeclsExt;
SymbolHash fGlobalIDConstraintDeclsExt;
SymbolHash fGlobalTypeDeclsExt;
// A global map of all global element declarations - used for substitution group computation
// (handy when sharing components by reference, since we might end up with duplicate components
// that are not added to either of the global element declarations above)
SymbolHash fAllGlobalElemDecls;
// the XMLGrammarDescription member
XSDDescription fGrammarDescription = null;
// annotations associated with the "root" schema of this targetNamespace
XSAnnotationImpl [] fAnnotations = null;
// number of annotations declared
int fNumAnnotations;
// symbol table for constructing parsers (annotation support)
private SymbolTable fSymbolTable = null;
// parsers for annotation support
private SoftReference<SAXParser> fSAXParser = null;
private SoftReference<DOMParser> fDOMParser = null;
// is this grammar immutable? (fully constructed and not changeable)
private boolean fIsImmutable = false;
//
// Constructors
//
// needed to make BuiltinSchemaGrammar work.
protected SchemaGrammar() {}
/**
* Default constructor.
*
* @param targetNamespace
* @param grammarDesc the XMLGrammarDescription corresponding to this object
* at the least a systemId should always be known.
* @param symbolTable needed for annotation support
*/
public SchemaGrammar(String targetNamespace, XSDDescription grammarDesc,
SymbolTable symbolTable) {
fTargetNamespace = targetNamespace;
fGrammarDescription = grammarDesc;
fSymbolTable = symbolTable;
// REVISIT: the initial sizes being chosen for each SymbolHash
// may not be ideal and could still be tuned. They were chosen
// somewhat arbitrarily to reduce the initial footprint of
// SymbolHash buckets from 1,515 to 177 (about 12% of the
// default size).
fGlobalAttrDecls = new SymbolHash(12);
fGlobalAttrGrpDecls = new SymbolHash(5);
fGlobalElemDecls = new SymbolHash(25);
fGlobalGroupDecls = new SymbolHash(5);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(3);
// Extended tables
fGlobalAttrDeclsExt = new SymbolHash(12);
fGlobalAttrGrpDeclsExt = new SymbolHash(5);
fGlobalElemDeclsExt = new SymbolHash(25);
fGlobalGroupDeclsExt = new SymbolHash(5);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(3);
fGlobalTypeDeclsExt = new SymbolHash(25);
// All global elements table
fAllGlobalElemDecls = new SymbolHash(25);
// if we are parsing S4S, put built-in types in first
// they might get overwritten by the types from S4S, but that's
// considered what the application wants to do.
if (fTargetNamespace == SchemaSymbols.URI_SCHEMAFORSCHEMA) {
fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls.makeClone();
}
else {
fGlobalTypeDecls = new SymbolHash(25);
}
} // <init>(String, XSDDescription)
// Clone an existing schema grammar
public SchemaGrammar(SchemaGrammar grammar) {
fTargetNamespace = grammar.fTargetNamespace;
fGrammarDescription = grammar.fGrammarDescription.makeClone();
//fGrammarDescription.fContextType |= XSDDescription.CONTEXT_COLLISION; // REVISIT
fSymbolTable = grammar.fSymbolTable; // REVISIT
fGlobalAttrDecls = grammar.fGlobalAttrDecls.makeClone();
fGlobalAttrGrpDecls = grammar.fGlobalAttrGrpDecls.makeClone();
fGlobalElemDecls = grammar.fGlobalElemDecls.makeClone();
fGlobalGroupDecls = grammar.fGlobalGroupDecls.makeClone();
fGlobalNotationDecls = grammar.fGlobalNotationDecls.makeClone();
fGlobalIDConstraintDecls = grammar.fGlobalIDConstraintDecls.makeClone();
fGlobalTypeDecls = grammar.fGlobalTypeDecls.makeClone();
// Extended tables
fGlobalAttrDeclsExt = grammar.fGlobalAttrDeclsExt.makeClone();
fGlobalAttrGrpDeclsExt = grammar.fGlobalAttrGrpDeclsExt.makeClone();
fGlobalElemDeclsExt = grammar.fGlobalElemDeclsExt.makeClone();
fGlobalGroupDeclsExt = grammar.fGlobalGroupDeclsExt.makeClone();
fGlobalNotationDeclsExt = grammar.fGlobalNotationDeclsExt.makeClone();
fGlobalIDConstraintDeclsExt = grammar.fGlobalIDConstraintDeclsExt.makeClone();
fGlobalTypeDeclsExt = grammar.fGlobalTypeDeclsExt.makeClone();
// All global elements table
fAllGlobalElemDecls = grammar.fAllGlobalElemDecls.makeClone();
// Annotations associated with the "root" schema of this targetNamespace
fNumAnnotations = grammar.fNumAnnotations;
if (fNumAnnotations > 0) {
fAnnotations = new XSAnnotationImpl[grammar.fAnnotations.length];
System.arraycopy(grammar.fAnnotations, 0, fAnnotations, 0, fNumAnnotations);
}
// All substitution group information declared in this namespace
fSubGroupCount = grammar.fSubGroupCount;
if (fSubGroupCount > 0) {
fSubGroups = new XSElementDecl[grammar.fSubGroups.length];
System.arraycopy(grammar.fSubGroups, 0, fSubGroups, 0, fSubGroupCount);
}
// Array to store complex type decls for constraint checking
fCTCount = grammar.fCTCount;
if (fCTCount > 0) {
fComplexTypeDecls = new XSComplexTypeDecl[grammar.fComplexTypeDecls.length];
fCTLocators = new SimpleLocator[grammar.fCTLocators.length];
System.arraycopy(grammar.fComplexTypeDecls, 0, fComplexTypeDecls, 0, fCTCount);
System.arraycopy(grammar.fCTLocators, 0, fCTLocators, 0, fCTCount);
}
// Groups being redefined by restriction
fRGCount = grammar.fRGCount;
if (fRGCount > 0) {
fRedefinedGroupDecls = new XSGroupDecl[grammar.fRedefinedGroupDecls.length];
fRGLocators = new SimpleLocator[grammar.fRGLocators.length];
System.arraycopy(grammar.fRedefinedGroupDecls, 0, fRedefinedGroupDecls, 0, fRGCount);
System.arraycopy(grammar.fRGLocators, 0, fRGLocators, 0, fRGCount/2);
}
// List of imported grammars
if (grammar.fImported != null) {
fImported = new ArrayList<>();
for (int i=0; i<grammar.fImported.size(); i++) {
fImported.add(grammar.fImported.get(i));
}
}
// Locations
if (grammar.fLocations != null) {
for (int k=0; k<grammar.fLocations.size(); k++) {
addDocument(null, grammar.fLocations.get(k));
}
}
} // <init>(String, XSDDescription)
// number of built-in XSTypes we need to create for base and full
// datatype set
private static final int BASICSET_COUNT = 29;
private static final int FULLSET_COUNT = 46;
private static final int GRAMMAR_XS = 1;
private static final int GRAMMAR_XSI = 2;
// this class makes sure the static, built-in schema grammars
// are immutable.
public static class BuiltinSchemaGrammar extends SchemaGrammar {
private static final String EXTENDED_SCHEMA_FACTORY_CLASS = "com.sun.org.apache.xerces.internal.impl.dv.xs.ExtendedSchemaDVFactoryImpl";
/**
* Special constructor to create the grammars for the schema namespaces
*
* @param grammar
*/
public BuiltinSchemaGrammar(int grammar, short schemaVersion) {
SchemaDVFactory schemaFactory;
if (schemaVersion == Constants.SCHEMA_VERSION_1_0) {
schemaFactory = SchemaDVFactory.getInstance();
}
else {
schemaFactory = SchemaDVFactory.getInstance(EXTENDED_SCHEMA_FACTORY_CLASS);
}
if (grammar == GRAMMAR_XS) {
// target namespace
fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA);
// no global decls other than types
fGlobalAttrDecls = new SymbolHash(1);
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(1);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(1);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// all global element decls table
fAllGlobalElemDecls = new SymbolHash(1);
// get all built-in types
fGlobalTypeDecls = schemaFactory.getBuiltInTypes();
// assign the built-in schema grammar as the XSNamespaceItem
// for each of the built-in simple type definitions.
int length = fGlobalTypeDecls.getLength();
XSTypeDefinition [] typeDefinitions = new XSTypeDefinition[length];
fGlobalTypeDecls.getValues(typeDefinitions, 0);
for (int i = 0; i < length; ++i) {
XSTypeDefinition xtd = typeDefinitions[i];
if (xtd instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) xtd).setNamespaceItem(this);
}
}
// add anyType
fGlobalTypeDecls.put(fAnyType.getName(), fAnyType);
}
else if (grammar == GRAMMAR_XSI) {
// target namespace
fTargetNamespace = SchemaSymbols.URI_XSI;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_XSI);
// no global decls other than attributes
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(1);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
fGlobalTypeDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(1);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// no all global element decls
fAllGlobalElemDecls = new SymbolHash(1);
// 4 attributes, so initialize the size as 4*2 = 8
fGlobalAttrDecls = new SymbolHash(8);
String name = null;
String tns = null;
XSSimpleType type = null;
short scope = XSConstants.SCOPE_GLOBAL;
// xsi:type
name = SchemaSymbols.XSI_TYPE;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_QNAME);
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
// xsi:nil
name = SchemaSymbols.XSI_NIL;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_BOOLEAN);
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
XSSimpleType anyURI = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_ANYURI);
// xsi:schemaLocation
name = SchemaSymbols.XSI_SCHEMALOCATION;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.createTypeList("#AnonType_schemaLocation", SchemaSymbols.URI_XSI, (short)0, anyURI, null);
if (type instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl)type).setAnonymous(true);
}
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
// xsi:noNamespaceSchemaLocation
name = SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION;
tns = SchemaSymbols.URI_XSI;
type = anyURI;
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
}
} // <init>(int)
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription.makeClone();
} // getGrammarDescription(): XMLGrammarDescription
// override these methods solely so that these
// objects cannot be modified once they're created.
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl, String location) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
// ignore
}
public void addGlobalElementDeclAll(XSElementDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
// ignore
}
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
// ignore
}
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
// ignore
}
public synchronized void addDocument(Object document, String location) {
// ignore
}
// annotation support
synchronized DOMParser getDOMParser() {
return null;
}
synchronized SAXParser getSAXParser() {
return null;
}
}
/**
* <p>A partial schema for schemas for validating annotations.</p>
*
* @xerces.internal
*
* @author Michael Glavassevich, IBM
*/
public static final class Schema4Annotations extends SchemaGrammar {
/**
* Singleton instance.
*/
public static final Schema4Annotations INSTANCE = new Schema4Annotations();
/**
* Special constructor to create a schema
* capable of validating annotations.
*/
private Schema4Annotations() {
// target namespace
fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA);
// no global decls other than types and
// element declarations for <annotation>, <documentation> and <appinfo>.
fGlobalAttrDecls = new SymbolHash(1);
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(6);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(6);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// all global element declarations
fAllGlobalElemDecls = new SymbolHash(6);
// get all built-in types
fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls;
// create element declarations for <annotation>, <documentation> and <appinfo>
XSElementDecl annotationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_ANNOTATION);
XSElementDecl documentationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_DOCUMENTATION);
XSElementDecl appinfoDecl = createAnnotationElementDecl(SchemaSymbols.ELT_APPINFO);
// add global element declarations
fGlobalElemDecls.put(annotationDecl.fName, annotationDecl);
fGlobalElemDecls.put(documentationDecl.fName, documentationDecl);
fGlobalElemDecls.put(appinfoDecl.fName, appinfoDecl);
fGlobalElemDeclsExt.put(","+annotationDecl.fName, annotationDecl);
fGlobalElemDeclsExt.put(","+documentationDecl.fName, documentationDecl);
fGlobalElemDeclsExt.put(","+appinfoDecl.fName, appinfoDecl);
fAllGlobalElemDecls.put(annotationDecl, annotationDecl);
fAllGlobalElemDecls.put(documentationDecl, documentationDecl);
fAllGlobalElemDecls.put(appinfoDecl, appinfoDecl);
// create complex type declarations for <annotation>, <documentation> and <appinfo>
XSComplexTypeDecl annotationType = new XSComplexTypeDecl();
XSComplexTypeDecl documentationType = new XSComplexTypeDecl();
XSComplexTypeDecl appinfoType = new XSComplexTypeDecl();
// set the types on their element declarations
annotationDecl.fType = annotationType;
documentationDecl.fType = documentationType;
appinfoDecl.fType = appinfoType;
// create attribute groups for <annotation>, <documentation> and <appinfo>
XSAttributeGroupDecl annotationAttrs = new XSAttributeGroupDecl();
XSAttributeGroupDecl documentationAttrs = new XSAttributeGroupDecl();
XSAttributeGroupDecl appinfoAttrs = new XSAttributeGroupDecl();
// fill in attribute groups
{
// create and fill attribute uses for <annotation>, <documentation> and <appinfo>
[MASK] annotationIDAttr = new [MASK] ();
annotationIDAttr.fAttrDecl = new XSAttributeDecl();
annotationIDAttr.fAttrDecl.setValues(SchemaSymbols.ATT_ID, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ID),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, annotationType, null);
annotationIDAttr.fUse = SchemaSymbols.USE_OPTIONAL;
annotationIDAttr.fConstraintType = XSConstants.VC_NONE;
[MASK] documentationSourceAttr = new [MASK] ();
documentationSourceAttr.fAttrDecl = new XSAttributeDecl();
documentationSourceAttr.fAttrDecl.setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ANYURI),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, documentationType, null);
documentationSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL;
documentationSourceAttr.fConstraintType = XSConstants.VC_NONE;
[MASK] documentationLangAttr = new [MASK] ();
documentationLangAttr.fAttrDecl = new XSAttributeDecl();
documentationLangAttr.fAttrDecl.setValues("lang".intern(), NamespaceContext.XML_URI, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_LANGUAGE),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, documentationType, null);
documentationLangAttr.fUse = SchemaSymbols.USE_OPTIONAL;
documentationLangAttr.fConstraintType = XSConstants.VC_NONE;
[MASK] appinfoSourceAttr = new [MASK] ();
appinfoSourceAttr.fAttrDecl = new XSAttributeDecl();
appinfoSourceAttr.fAttrDecl.setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ANYURI),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, appinfoType, null);
appinfoSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL;
appinfoSourceAttr.fConstraintType = XSConstants.VC_NONE;
// create lax attribute wildcard for <annotation>, <documentation> and <appinfo>
XSWildcardDecl otherAttrs = new XSWildcardDecl();
otherAttrs.fNamespaceList = new String [] {fTargetNamespace, null};
otherAttrs.fType = XSWildcard.NSCONSTRAINT_NOT;
otherAttrs.fProcessContents = XSWildcard.PC_LAX;
// add attribute uses and wildcards to attribute groups for <annotation>, <documentation> and <appinfo>
annotationAttrs.addAttributeUse(annotationIDAttr);
annotationAttrs.fAttributeWC = otherAttrs;
documentationAttrs.addAttributeUse(documentationSourceAttr);
documentationAttrs.addAttributeUse(documentationLangAttr);
documentationAttrs.fAttributeWC = otherAttrs;
appinfoAttrs.addAttributeUse(appinfoSourceAttr);
appinfoAttrs.fAttributeWC = otherAttrs;
}
// create particles for <annotation>
XSParticleDecl annotationParticle = createUnboundedModelGroupParticle();
{
XSModelGroupImpl annotationChoice = new XSModelGroupImpl();
annotationChoice.fCompositor = XSModelGroupImpl.MODELGROUP_CHOICE;
annotationChoice.fParticleCount = 2;
annotationChoice.fParticles = new XSParticleDecl[2];
annotationChoice.fParticles[0] = createChoiceElementParticle(appinfoDecl);
annotationChoice.fParticles[1] = createChoiceElementParticle(documentationDecl);
annotationParticle.fValue = annotationChoice;
}
// create wildcard particle for <documentation> and <appinfo>
XSParticleDecl anyWCSequenceParticle = createUnboundedAnyWildcardSequenceParticle();
// fill complex types
annotationType.setValues("#AnonType_" + SchemaSymbols.ELT_ANNOTATION, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_ELEMENT, false, annotationAttrs, null, annotationParticle, XSObjectListImpl.EMPTY_LIST);
annotationType.setName("#AnonType_" + SchemaSymbols.ELT_ANNOTATION);
annotationType.setIsAnonymous();
documentationType.setValues("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_MIXED, false, documentationAttrs, null, anyWCSequenceParticle, XSObjectListImpl.EMPTY_LIST);
documentationType.setName("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION);
documentationType.setIsAnonymous();
appinfoType.setValues("#AnonType_" + SchemaSymbols.ELT_APPINFO, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_MIXED, false, appinfoAttrs, null, anyWCSequenceParticle, XSObjectListImpl.EMPTY_LIST);
appinfoType.setName("#AnonType_" + SchemaSymbols.ELT_APPINFO);
appinfoType.setIsAnonymous();
} // <init>(int)
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription.makeClone();
} // getGrammarDescription(): XMLGrammarDescription
// override these methods solely so that these
// objects cannot be modified once they're created.
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
// ignore
}
public void addGlobalElementDeclAll(XSElementDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
// ignore
}
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
// ignore
}
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
// ignore
}
public synchronized void addDocument(Object document, String location) {
// ignore
}
// annotation support
synchronized DOMParser getDOMParser() {
return null;
}
synchronized SAXParser getSAXParser() {
return null;
}
//
// private helper methods
//
private XSElementDecl createAnnotationElementDecl(String localName) {
XSElementDecl eDecl = new XSElementDecl();
eDecl.fName = localName;
eDecl.fTargetNamespace = fTargetNamespace;
eDecl.setIsGlobal();
eDecl.fBlock = (XSConstants.DERIVATION_EXTENSION |
XSConstants.DERIVATION_RESTRICTION | XSConstants.DERIVATION_SUBSTITUTION);
eDecl.setConstraintType(XSConstants.VC_NONE);
return eDecl;
}
private XSParticleDecl createUnboundedModelGroupParticle() {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 0;
particle.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED;
particle.fType = XSParticleDecl.PARTICLE_MODELGROUP;
return particle;
}
private XSParticleDecl createChoiceElementParticle(XSElementDecl ref) {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 1;
particle.fMaxOccurs = 1;
particle.fType = XSParticleDecl.PARTICLE_ELEMENT;
particle.fValue = ref;
return particle;
}
private XSParticleDecl createUnboundedAnyWildcardSequenceParticle() {
XSParticleDecl particle = createUnboundedModelGroupParticle();
XSModelGroupImpl sequence = new XSModelGroupImpl();
sequence.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE;
sequence.fParticleCount = 1;
sequence.fParticles = new XSParticleDecl[1];
sequence.fParticles[0] = createAnyLaxWildcardParticle();
particle.fValue = sequence;
return particle;
}
private XSParticleDecl createAnyLaxWildcardParticle() {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 1;
particle.fMaxOccurs = 1;
particle.fType = XSParticleDecl.PARTICLE_WILDCARD;
XSWildcardDecl anyWC = new XSWildcardDecl();
anyWC.fNamespaceList = null;
anyWC.fType = XSWildcard.NSCONSTRAINT_ANY;
anyWC.fProcessContents = XSWildcard.PC_LAX;
particle.fValue = anyWC;
return particle;
}
}
// Grammar methods
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription;
} // getGrammarDescription(): XMLGrammarDescription
// DTDGrammar methods
public boolean isNamespaceAware () {
return true;
} // isNamespaceAware():boolean
List<SchemaGrammar> fImported = null;
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
fImported = importedGrammars;
}
public List<SchemaGrammar> getImportedGrammars() {
return fImported;
}
/**
* Returns this grammar's target namespace.
*/
public final String getTargetNamespace() {
return fTargetNamespace;
} // getTargetNamespace():String
/**
* register one global attribute
*/
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
fGlobalAttrDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalAttributeDecl(XSAttributeDecl decl, String location) {
fGlobalAttrDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global attribute group
*/
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
fGlobalAttrGrpDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
fGlobalAttrGrpDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global element
*/
public void addGlobalElementDeclAll(XSElementDecl decl) {
if (fAllGlobalElemDecls.get(decl) == null) {
fAllGlobalElemDecls.put(decl, decl);
// if there is a substitution group affiliation, store in an array,
// for further constraint checking: UPA, PD, EDC
if (decl.fSubGroup != null) {
if (fSubGroupCount == fSubGroups.length)
fSubGroups = resize(fSubGroups, fSubGroupCount+INC_SIZE);
fSubGroups[fSubGroupCount++] = decl;
}
}
}
public void addGlobalElementDecl(XSElementDecl decl) {
fGlobalElemDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
fGlobalElemDeclsExt.put(((location != null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global group
*/
public void addGlobalGroupDecl(XSGroupDecl decl) {
fGlobalGroupDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
fGlobalGroupDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global notation
*/
public void addGlobalNotationDecl(XSNotationDecl decl) {
fGlobalNotationDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
fGlobalNotationDeclsExt.put(((location!=null) ? location : "") + "," +decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global type
*/
public void addGlobalTypeDecl(XSTypeDefinition decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
if (decl instanceof XSComplexTypeDecl) {
((XSComplexTypeDecl) decl).setNamespaceItem(this);
}
else if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
fGlobalTypeDeclsExt.put(((location!=null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null) {
if (decl instanceof XSComplexTypeDecl) {
((XSComplexTypeDecl) decl).setNamespaceItem(this);
}
else if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
}
/**
* register one global complex type
*/
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
decl.setNamespaceItem(this);
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
fGlobalTypeDeclsExt.put(((location!=null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global simple type
*/
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
fGlobalTypeDeclsExt.put(((location != null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null && decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
/**
* register one identity constraint
*/
public final void addIDConstraintDecl(XSElementDecl elmDecl, IdentityConstraint decl) {
elmDecl.addIDConstraint(decl);
fGlobalIDConstraintDecls.put(decl.getIdentityConstraintName(), decl);
}
public final void addIDConstraintDecl(XSElementDecl elmDecl, IdentityConstraint decl, String location) {
fGlobalIDConstraintDeclsExt.put(((location != null) ? location : "") + "," + decl.getIdentityConstraintName(), decl);
}
/**
* get one global attribute
*/
public final XSAttributeDecl getGlobalAttributeDecl(String declName) {
return(XSAttributeDecl)fGlobalAttrDecls.get(declName);
}
public final XSAttributeDecl getGlobalAttributeDecl(String declName, String location) {
return(XSAttributeDecl)fGlobalAttrDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global attribute group
*/
public final XSAttributeGroupDecl getGlobalAttributeGroupDecl(String declName) {
return(XSAttributeGroupDecl)fGlobalAttrGrpDecls.get(declName);
}
public final XSAttributeGroupDecl getGlobalAttributeGroupDecl(String declName, String location) {
return(XSAttributeGroupDecl)fGlobalAttrGrpDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global element
*/
public final XSElementDecl getGlobalElementDecl(String declName) {
return(XSElementDecl)fGlobalElemDecls.get(declName);
}
public final XSElementDecl getGlobalElementDecl(String declName, String location) {
return(XSElementDecl)fGlobalElemDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global group
*/
public final XSGroupDecl getGlobalGroupDecl(String declName) {
return(XSGroupDecl)fGlobalGroupDecls.get(declName);
}
public final XSGroupDecl getGlobalGroupDecl(String declName, String location) {
return(XSGroupDecl)fGlobalGroupDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global notation
*/
public final XSNotationDecl getGlobalNotationDecl(String declName) {
return(XSNotationDecl)fGlobalNotationDecls.get(declName);
}
public final XSNotationDecl getGlobalNotationDecl(String declName, String location) {
return(XSNotationDecl)fGlobalNotationDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global type
*/
public final XSTypeDefinition getGlobalTypeDecl(String declName) {
return(XSTypeDefinition)fGlobalTypeDecls.get(declName);
}
public final XSTypeDefinition getGlobalTypeDecl(String declName, String location) {
return(XSTypeDefinition)fGlobalTypeDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one identity constraint
*/
public final IdentityConstraint getIDConstraintDecl(String declName) {
return(IdentityConstraint)fGlobalIDConstraintDecls.get(declName);
}
public final IdentityConstraint getIDConstraintDecl(String declName, String location) {
return(IdentityConstraint)fGlobalIDConstraintDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one identity constraint
*/
public final boolean hasIDConstraints() {
return fGlobalIDConstraintDecls.getLength() > 0;
}
// array to store complex type decls
private static final int INITIAL_SIZE = 16;
private static final int INC_SIZE = 16;
private int fCTCount = 0;
private XSComplexTypeDecl[] fComplexTypeDecls = new XSComplexTypeDecl[INITIAL_SIZE];
private SimpleLocator[] fCTLocators = new SimpleLocator[INITIAL_SIZE];
// an array to store groups being redefined by restriction
// even-numbered elements are the derived groups, odd-numbered ones their bases
private static final int REDEFINED_GROUP_INIT_SIZE = 2;
private int fRGCount = 0;
private XSGroupDecl[] fRedefinedGroupDecls = new XSGroupDecl[REDEFINED_GROUP_INIT_SIZE];
private SimpleLocator[] fRGLocators = new SimpleLocator[REDEFINED_GROUP_INIT_SIZE/2];
// a flag to indicate whether we have checked the 3 constraints on this
// grammar.
boolean fFullChecked = false;
/**
* add one complex type decl: for later constraint checking
*/
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
if (fCTCount == fComplexTypeDecls.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount+INC_SIZE);
fCTLocators = resize(fCTLocators, fCTCount+INC_SIZE);
}
fCTLocators[fCTCount] = locator;
fComplexTypeDecls[fCTCount++] = decl;
}
/**
* add a group redefined by restriction: for later constraint checking
*/
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
if (fRGCount == fRedefinedGroupDecls.length) {
// double array size each time.
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount << 1);
fRGLocators = resize(fRGLocators, fRGCount);
}
fRGLocators[fRGCount/2] = locator;
fRedefinedGroupDecls[fRGCount++] = derived;
fRedefinedGroupDecls[fRGCount++] = base;
}
/**
* get all complex type decls: for later constraint checking
*/
final XSComplexTypeDecl[] getUncheckedComplexTypeDecls() {
if (fCTCount < fComplexTypeDecls.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
return fComplexTypeDecls;
}
/**
* get the error locator of all complex type decls
*/
final SimpleLocator[] getUncheckedCTLocators() {
if (fCTCount < fCTLocators.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
return fCTLocators;
}
/**
* get all redefined groups: for later constraint checking
*/
final XSGroupDecl[] getRedefinedGroupDecls() {
if (fRGCount < fRedefinedGroupDecls.length) {
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount);
fRGLocators = resize(fRGLocators, fRGCount/2);
}
return fRedefinedGroupDecls;
}
/**
* get the error locator of all redefined groups
*/
final SimpleLocator[] getRGLocators() {
if (fRGCount < fRedefinedGroupDecls.length) {
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount);
fRGLocators = resize(fRGLocators, fRGCount/2);
}
return fRGLocators;
}
/**
* after the first-round checking, some types don't need to be checked
* against UPA again. here we trim the array to the proper size.
*/
final void setUncheckedTypeNum(int newSize) {
fCTCount = newSize;
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
// used to store all substitution group information declared in
// this namespace
private int fSubGroupCount = 0;
private XSElementDecl[] fSubGroups = new XSElementDecl[INITIAL_SIZE];
/**
* get all substitution group information: for the 3 constraint checking
*/
final XSElementDecl[] getSubstitutionGroups() {
if (fSubGroupCount < fSubGroups.length)
fSubGroups = resize(fSubGroups, fSubGroupCount);
return fSubGroups;
}
// anyType and anySimpleType: because there are so many places where
// we need direct access to these two types
public final static XSComplexTypeDecl fAnyType = new XSAnyType();
private static class XSAnyType extends XSComplexTypeDecl {
public XSAnyType () {
fName = SchemaSymbols.ATTVAL_ANYTYPE;
super.fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
fBaseType = this;
fDerivedBy = XSConstants.DERIVATION_RESTRICTION;
fContentType = XSComplexTypeDecl.CONTENTTYPE_MIXED;
fParticle = createParticle();
fAttrGrp = createAttrGrp();
}
// overridden methods
public void setValues(String name, String targetNamespace,
XSTypeDefinition baseType, short derivedBy, short schemaFinal,
short block, short contentType,
boolean isAbstract, XSAttributeGroupDecl attrGrp,
XSSimpleType simpleType, XSParticleDecl particle) {
// don't allow this.
}
public void setName(String name){
// don't allow this.
}
public void setIsAbstractType() {
// null implementation
}
public void setContainsTypeID() {
// null implementation
}
public void setIsAnonymous() {
// null implementation
}
public void reset() {
// null implementation
}
public XSObjectList getAnnotations() {
return XSObjectListImpl.EMPTY_LIST;
}
public XSNamespaceItem getNamespaceItem() {
return SG_SchemaNS;
}
private XSAttributeGroupDecl createAttrGrp() {
XSWildcardDecl wildcard = new XSWildcardDecl();
wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
XSAttributeGroupDecl attrGrp = new XSAttributeGroupDecl();
attrGrp.fAttributeWC = wildcard;
return attrGrp;
}
private XSParticleDecl createParticle() {
// the wildcard used in anyType (content and attribute)
// the spec will change strict to skip for anyType
XSWildcardDecl wildcard = new XSWildcardDecl();
wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
// the particle for the content wildcard
XSParticleDecl particleW = new XSParticleDecl();
particleW.fMinOccurs = 0;
particleW.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED;
particleW.fType = XSParticleDecl.PARTICLE_WILDCARD;
particleW.fValue = wildcard;
// the model group of a sequence of the above particle
XSModelGroupImpl group = new XSModelGroupImpl();
group.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE;
group.fParticleCount = 1;
group.fParticles = new XSParticleDecl[1];
group.fParticles[0] = particleW;
// the content of anyType: particle of the above model group
XSParticleDecl particleG = new XSParticleDecl();
particleG.fType = XSParticleDecl.PARTICLE_MODELGROUP;
particleG.fValue = group;
return particleG;
}
}
private static class BuiltinAttrDecl extends XSAttributeDecl {
public BuiltinAttrDecl(String name, String tns,
XSSimpleType type, short scope) {
fName = name;
super.fTargetNamespace = tns;
fType = type;
fScope = scope;
}
public void setValues(String name, String targetNamespace,
XSSimpleType simpleType, short constraintType, short scope,
ValidatedInfo valInfo, XSComplexTypeDecl enclosingCT) {
// ignore this call.
}
public void reset () {
// also ignore this call.
}
public XSAnnotation getAnnotation() {
return null;
}
public XSNamespaceItem getNamespaceItem() {
return SG_XSI;
}
} // class BuiltinAttrDecl
// the grammars to hold components of the schema namespace
public final static BuiltinSchemaGrammar SG_SchemaNS = new BuiltinSchemaGrammar(GRAMMAR_XS, Constants.SCHEMA_VERSION_1_0);
private final static BuiltinSchemaGrammar SG_SchemaNSExtended = new BuiltinSchemaGrammar(GRAMMAR_XS, Constants.SCHEMA_VERSION_1_0_EXTENDED);
public final static XSSimpleType fAnySimpleType = (XSSimpleType)SG_SchemaNS.getGlobalTypeDecl(SchemaSymbols.ATTVAL_ANYSIMPLETYPE);
// the grammars to hold components of the schema-instance namespace
public final static BuiltinSchemaGrammar SG_XSI = new BuiltinSchemaGrammar(GRAMMAR_XSI, Constants.SCHEMA_VERSION_1_0);
public static SchemaGrammar getS4SGrammar(short schemaVersion) {
if (schemaVersion == Constants.SCHEMA_VERSION_1_0) {
return SG_SchemaNS;
}
else {
return SG_SchemaNSExtended;
}
}
static final XSComplexTypeDecl[] resize(XSComplexTypeDecl[] oldArray, int newSize) {
XSComplexTypeDecl[] newArray = new XSComplexTypeDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final XSGroupDecl[] resize(XSGroupDecl[] oldArray, int newSize) {
XSGroupDecl[] newArray = new XSGroupDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final XSElementDecl[] resize(XSElementDecl[] oldArray, int newSize) {
XSElementDecl[] newArray = new XSElementDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final SimpleLocator[] resize(SimpleLocator[] oldArray, int newSize) {
SimpleLocator[] newArray = new SimpleLocator[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
// XSNamespaceItem methods
// the max index / the max value of XSObject type
private static final short MAX_COMP_IDX = XSTypeDefinition.SIMPLE_TYPE;
private static final boolean[] GLOBAL_COMP = {false, // null
true, // attribute
true, // element
true, // type
false, // attribute use
true, // attribute group
true, // group
false, // model group
false, // particle
false, // wildcard
true, // idc
true, // notation
false, // annotation
false, // facet
false, // multi value facet
true, // complex type
true // simple type
};
// store a certain kind of components from all namespaces
private XSNamedMap[] fComponents = null;
private ObjectList[] fComponentsExt = null;
// store the documents and their locations contributing to this namespace
// REVISIT: use StringList and XSObjectList for there fields.
// fDocuments is never used
private List<Object> fDocuments = null;
private List<String> fLocations = null;
public synchronized void addDocument(Object document, String location) {
if (fDocuments == null) {
// Parsing schema is not thread safe, synchronized may be removed
fDocuments = new CopyOnWriteArrayList<>();
fLocations = new CopyOnWriteArrayList<>();
}
fDocuments.add(document);
fLocations.add(location);
}
public synchronized void removeDocument(int index) {
if (fDocuments != null &&
index >= 0 &&
index < fDocuments.size()) {
fDocuments.remove(index);
fLocations.remove(index);
}
}
/**
* [schema namespace]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#nsi-schema_namespace">[schema namespace]</a>
* @return The target namespace of this item.
*/
public String getSchemaNamespace() {
return fTargetNamespace;
}
// annotation support
synchronized DOMParser getDOMParser() {
if (fDOMParser != null) {
DOMParser parser = fDOMParser.get();
if (parser != null) {
return parser;
}
}
// REVISIT: when schema handles XML 1.1, will need to
// revisit this (and the practice of not prepending an XML decl to the annotation string
XML11Configuration config = new XML11Configuration(fSymbolTable);
// note that this should never produce errors or require
// entity resolution, so just a barebones configuration with
// a couple of feature set will do fine
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true);
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false);
DOMParser parser = new DOMParser(config);
try {
parser.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.DEFER_NODE_EXPANSION_FEATURE, false);
}
catch (SAXException exc) {}
fDOMParser = new SoftReference<DOMParser>(parser);
return parser;
}
synchronized SAXParser getSAXParser() {
if (fSAXParser != null) {
SAXParser parser = fSAXParser.get();
if (parser != null) {
return parser;
}
}
// REVISIT: when schema handles XML 1.1, will need to
// revisit this (and the practice of not prepending an XML decl to the annotation string
XML11Configuration config = new XML11Configuration(fSymbolTable);
// note that this should never produce errors or require
// entity resolution, so just a barebones configuration with
// a couple of feature set will do fine
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true);
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false);
SAXParser parser = new SAXParser(config);
fSAXParser = new SoftReference<SAXParser>(parser);
return parser;
}
/**
* [schema components]: a list of top-level components, i.e. element
* declarations, attribute declarations, etc.
* @param objectType The type of the declaration, i.e.
* <code>ELEMENT_DECLARATION</code>. Note that
* <code>XSTypeDefinition.SIMPLE_TYPE</code> and
* <code>XSTypeDefinition.COMPLEX_TYPE</code> can also be used as the
* <code>objectType</code> to retrieve only complex types or simple
* types, instead of all types.
* @return A list of top-level definition of the specified type in
* <code>objectType</code> or an empty <code>XSNamedMap</code> if no
* such definitions exist.
*/
public synchronized XSNamedMap getComponents(short objectType) {
if (objectType <= 0 || objectType > MAX_COMP_IDX ||
!GLOBAL_COMP[objectType]) {
return XSNamedMapImpl.EMPTY_MAP;
}
if (fComponents == null)
fComponents = new XSNamedMap[MAX_COMP_IDX+1];
// get the hashtable for this type of components
if (fComponents[objectType] == null) {
SymbolHash table = null;
switch (objectType) {
case XSConstants.TYPE_DEFINITION:
case XSTypeDefinition.COMPLEX_TYPE:
case XSTypeDefinition.SIMPLE_TYPE:
table = fGlobalTypeDecls;
break;
case XSConstants.ATTRIBUTE_DECLARATION:
table = fGlobalAttrDecls;
break;
case XSConstants.ELEMENT_DECLARATION:
table = fGlobalElemDecls;
break;
case XSConstants.ATTRIBUTE_GROUP:
table = fGlobalAttrGrpDecls;
break;
case XSConstants.MODEL_GROUP_DEFINITION:
table = fGlobalGroupDecls;
break;
case XSConstants.NOTATION_DECLARATION:
table = fGlobalNotationDecls;
break;
case XSConstants.IDENTITY_CONSTRAINT:
table = this.fGlobalIDConstraintDecls;
break;
}
// for complex/simple types, create a special implementation,
// which take specific types out of the hash table
if (objectType == XSTypeDefinition.COMPLEX_TYPE ||
objectType == XSTypeDefinition.SIMPLE_TYPE) {
fComponents[objectType] = new XSNamedMap4Types(fTargetNamespace, table, objectType);
}
else {
fComponents[objectType] = new XSNamedMapImpl(fTargetNamespace, table);
}
}
return fComponents[objectType];
}
public synchronized ObjectList getComponentsExt(short objectType) {
if (objectType <= 0 || objectType > MAX_COMP_IDX ||
!GLOBAL_COMP[objectType]) {
return ObjectListImpl.EMPTY_LIST;
}
if (fComponentsExt == null)
fComponentsExt = new ObjectList[MAX_COMP_IDX+1];
// get the hashtable for this type of components
if (fComponentsExt[objectType] == null) {
SymbolHash table = null;
switch (objectType) {
case XSConstants.TYPE_DEFINITION:
case XSTypeDefinition.COMPLEX_TYPE:
case XSTypeDefinition.SIMPLE_TYPE:
table = fGlobalTypeDeclsExt;
break;
case XSConstants.ATTRIBUTE_DECLARATION:
table = fGlobalAttrDeclsExt;
break;
case XSConstants.ELEMENT_DECLARATION:
table = fGlobalElemDeclsExt;
break;
case XSConstants.ATTRIBUTE_GROUP:
table = fGlobalAttrGrpDeclsExt;
break;
case XSConstants.MODEL_GROUP_DEFINITION:
table = fGlobalGroupDeclsExt;
break;
case XSConstants.NOTATION_DECLARATION:
table = fGlobalNotationDeclsExt;
break;
case XSConstants.IDENTITY_CONSTRAINT:
table = this.fGlobalIDConstraintDeclsExt;
break;
}
Object[] entries = table.getEntries();
fComponentsExt[objectType] = new ObjectListImpl(entries, entries.length);
}
return fComponentsExt[objectType];
}
public synchronized void resetComponents() {
fComponents = null;
fComponentsExt = null;
}
/**
* Convenience method. Returns a top-level simple or complex type
* definition.
* @param name The name of the definition.
* @return An <code>XSTypeDefinition</code> or null if such definition
* does not exist.
*/
public XSTypeDefinition getTypeDefinition(String name) {
return getGlobalTypeDecl(name);
}
/**
* Convenience method. Returns a top-level attribute declaration.
* @param name The name of the declaration.
* @return A top-level attribute declaration or null if such declaration
* does not exist.
*/
public XSAttributeDeclaration getAttributeDeclaration(String name) {
return getGlobalAttributeDecl(name);
}
/**
* Convenience method. Returns a top-level element declaration.
* @param name The name of the declaration.
* @return A top-level element declaration or null if such declaration
* does not exist.
*/
public XSElementDeclaration getElementDeclaration(String name) {
return getGlobalElementDecl(name);
}
/**
* Convenience method. Returns a top-level attribute group definition.
* @param name The name of the definition.
* @return A top-level attribute group definition or null if such
* definition does not exist.
*/
public XSAttributeGroupDefinition getAttributeGroup(String name) {
return getGlobalAttributeGroupDecl(name);
}
/**
* Convenience method. Returns a top-level model group definition.
*
* @param name The name of the definition.
* @return A top-level model group definition definition or null if such
* definition does not exist.
*/
public XSModelGroupDefinition getModelGroupDefinition(String name) {
return getGlobalGroupDecl(name);
}
/**
* Convenience method. Returns a top-level notation declaration.
*
* @param name The name of the declaration.
* @return A top-level notation declaration or null if such declaration
* does not exist.
*/
public XSNotationDeclaration getNotationDeclaration(String name) {
return getGlobalNotationDecl(name);
}
public XSIDCDefinition getIDCDefinition(String name) {
return getIDConstraintDecl(name);
}
/**
* [document location]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#sd-document_location">[document location]</a>
* @return a list of document information item
*/
public StringList getDocumentLocations() {
return new StringListImpl(fLocations);
}
/**
* Return an <code>XSModel</code> that represents components in this schema
* grammar.
*
* @return an <code>XSModel</code> representing this schema grammar
*/
public XSModel toXSModel() {
return new XSModelImpl(new SchemaGrammar[]{this});
}
public XSModel toXSModel(XSGrammar[] grammars) {
if (grammars == null || grammars.length == 0)
return toXSModel();
int len = grammars.length;
boolean hasSelf = false;
for (int i = 0; i < len; i++) {
if (grammars[i] == this) {
hasSelf = true;
break;
}
}
SchemaGrammar[] gs = new SchemaGrammar[hasSelf ? len : len+1];
for (int i = 0; i < len; i++)
gs[i] = (SchemaGrammar)grammars[i];
if (!hasSelf)
gs[len] = this;
return new XSModelImpl(gs);
}
/**
* @see org.apache.xerces.xs.XSNamespaceItem#getAnnotations()
*/
public XSObjectList getAnnotations() {
if (fNumAnnotations == 0) {
return XSObjectListImpl.EMPTY_LIST;
}
return new XSObjectListImpl(fAnnotations, fNumAnnotations);
}
public void addAnnotation(XSAnnotationImpl annotation) {
if (annotation == null) {
return;
}
if (fAnnotations == null) {
fAnnotations = new XSAnnotationImpl[2];
}
else if (fNumAnnotations == fAnnotations.length) {
XSAnnotationImpl[] newArray = new XSAnnotationImpl[fNumAnnotations << 1];
System.arraycopy(fAnnotations, 0, newArray, 0, fNumAnnotations);
fAnnotations = newArray;
}
fAnnotations[fNumAnnotations++] = annotation;
}
public void setImmutable(boolean isImmutable) {
fIsImmutable = isImmutable;
}
public boolean isImmutable() {
return fIsImmutable;
}
} // class SchemaGrammar
| XSAttributeUseImpl |
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
*/
/*
* 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 com.sun.org.apache.xerces.internal.impl.xs;
import com.sun.org.apache.xerces.internal.impl.Constants;
import com.sun.org.apache.xerces.internal.impl.dv.SchemaDVFactory;
import com.sun.org.apache.xerces.internal.impl.dv.ValidatedInfo;
import com.sun.org.apache.xerces.internal.impl.dv.XSSimpleType;
import com.sun.org.apache.xerces.internal.impl.dv.xs.XSSimpleTypeDecl;
import com.sun.org.apache.xerces.internal.impl.xs.identity.IdentityConstraint;
import com.sun.org.apache.xerces.internal.impl.xs.util.ObjectListImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.SimpleLocator;
import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSNamedMap4Types;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSNamedMapImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSObjectListImpl;
import com.sun.org.apache.xerces.internal.parsers.DOMParser;
import com.sun.org.apache.xerces.internal.parsers.SAXParser;
import com.sun.org.apache.xerces.internal.parsers.XML11Configuration;
import com.sun.org.apache.xerces.internal.util.SymbolHash;
import com.sun.org.apache.xerces.internal.util.SymbolTable;
import com.sun.org.apache.xerces.internal.xni.NamespaceContext;
import com.sun.org.apache.xerces.internal.xni.grammars.XMLGrammarDescription;
import com.sun.org.apache.xerces.internal.xni.grammars.XSGrammar;
import com.sun.org.apache.xerces.internal.xs.StringList;
import com.sun.org.apache.xerces.internal.xs.XSAnnotation;
import com.sun.org.apache.xerces.internal.xs.XSAttributeDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSAttributeGroupDefinition;
import com.sun.org.apache.xerces.internal.xs.XSConstants;
import com.sun.org.apache.xerces.internal.xs.XSElementDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSIDCDefinition;
import com.sun.org.apache.xerces.internal.xs.XSModel;
import com.sun.org.apache.xerces.internal.xs.XSModelGroupDefinition;
import com.sun.org.apache.xerces.internal.xs.XSNamedMap;
import com.sun.org.apache.xerces.internal.xs.XSNamespaceItem;
import com.sun.org.apache.xerces.internal.xs.XSNotationDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSObjectList;
import com.sun.org.apache.xerces.internal.xs.XSParticle;
import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
import com.sun.org.apache.xerces.internal.xs.XSWildcard;
import com.sun.org.apache.xerces.internal.xs.datatypes.ObjectList;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.xml.sax.SAXException;
/**
* This class is to hold all schema component declaration that are declared
* within one namespace.
*
* The Grammar class this class extends contains what little
* commonality there is between XML Schema and DTD grammars. It's
* useful to distinguish grammar objects from other kinds of object
* when they exist in pools or caches.
*
* @xerces.internal
*
* @author Sandy Gao, IBM
* @author Elena Litani, IBM
*
* @LastModified: Oct 2017
*/
public class SchemaGrammar implements XSGrammar, XSNamespaceItem {
// the target namespace of grammar
String fTargetNamespace;
// global decls: map from decl name to decl object
SymbolHash fGlobalAttrDecls;
SymbolHash fGlobalAttrGrpDecls;
SymbolHash fGlobalElemDecls;
SymbolHash fGlobalGroupDecls;
SymbolHash fGlobalNotationDecls;
SymbolHash fGlobalIDConstraintDecls;
SymbolHash fGlobalTypeDecls;
// extended global decls: map from schema location + decl name to decl object
// key is location,name
SymbolHash fGlobalAttrDeclsExt;
SymbolHash fGlobalAttrGrpDeclsExt;
SymbolHash fGlobalElemDeclsExt;
SymbolHash fGlobalGroupDeclsExt;
SymbolHash fGlobalNotationDeclsExt;
SymbolHash fGlobalIDConstraintDeclsExt;
SymbolHash fGlobalTypeDeclsExt;
// A global map of all global element declarations - used for substitution group computation
// (handy when sharing components by reference, since we might end up with duplicate components
// that are not added to either of the global element declarations above)
SymbolHash fAllGlobalElemDecls;
// the XMLGrammarDescription member
XSDDescription fGrammarDescription = null;
// annotations associated with the "root" schema of this targetNamespace
XSAnnotationImpl [] fAnnotations = null;
// number of annotations declared
int fNumAnnotations;
// symbol table for constructing parsers (annotation support)
private SymbolTable fSymbolTable = null;
// parsers for annotation support
private SoftReference<SAXParser> fSAXParser = null;
private SoftReference<DOMParser> fDOMParser = null;
// is this grammar immutable? (fully constructed and not changeable)
private boolean fIsImmutable = false;
//
// Constructors
//
// needed to make BuiltinSchemaGrammar work.
protected SchemaGrammar() {}
/**
* Default constructor.
*
* @param targetNamespace
* @param grammarDesc the XMLGrammarDescription corresponding to this object
* at the least a systemId should always be known.
* @param symbolTable needed for annotation support
*/
public SchemaGrammar(String targetNamespace, XSDDescription grammarDesc,
SymbolTable symbolTable) {
fTargetNamespace = targetNamespace;
fGrammarDescription = grammarDesc;
fSymbolTable = symbolTable;
// REVISIT: the initial sizes being chosen for each SymbolHash
// may not be ideal and could still be tuned. They were chosen
// somewhat arbitrarily to reduce the initial footprint of
// SymbolHash buckets from 1,515 to 177 (about 12% of the
// default size).
fGlobalAttrDecls = new SymbolHash(12);
fGlobalAttrGrpDecls = new SymbolHash(5);
fGlobalElemDecls = new SymbolHash(25);
fGlobalGroupDecls = new SymbolHash(5);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(3);
// Extended tables
fGlobalAttrDeclsExt = new SymbolHash(12);
fGlobalAttrGrpDeclsExt = new SymbolHash(5);
fGlobalElemDeclsExt = new SymbolHash(25);
fGlobalGroupDeclsExt = new SymbolHash(5);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(3);
fGlobalTypeDeclsExt = new SymbolHash(25);
// All global elements table
fAllGlobalElemDecls = new SymbolHash(25);
// if we are parsing S4S, put built-in types in first
// they might get overwritten by the types from S4S, but that's
// considered what the application wants to do.
if (fTargetNamespace == SchemaSymbols.URI_SCHEMAFORSCHEMA) {
fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls.makeClone();
}
else {
fGlobalTypeDecls = new SymbolHash(25);
}
} // <init>(String, XSDDescription)
// Clone an existing schema grammar
public SchemaGrammar(SchemaGrammar grammar) {
fTargetNamespace = grammar.fTargetNamespace;
fGrammarDescription = grammar.fGrammarDescription.makeClone();
//fGrammarDescription.fContextType |= XSDDescription.CONTEXT_COLLISION; // REVISIT
fSymbolTable = grammar.fSymbolTable; // REVISIT
fGlobalAttrDecls = grammar.fGlobalAttrDecls.makeClone();
fGlobalAttrGrpDecls = grammar.fGlobalAttrGrpDecls.makeClone();
fGlobalElemDecls = grammar.fGlobalElemDecls.makeClone();
fGlobalGroupDecls = grammar.fGlobalGroupDecls.makeClone();
fGlobalNotationDecls = grammar.fGlobalNotationDecls.makeClone();
fGlobalIDConstraintDecls = grammar.fGlobalIDConstraintDecls.makeClone();
fGlobalTypeDecls = grammar.fGlobalTypeDecls.makeClone();
// Extended tables
fGlobalAttrDeclsExt = grammar.fGlobalAttrDeclsExt.makeClone();
fGlobalAttrGrpDeclsExt = grammar.fGlobalAttrGrpDeclsExt.makeClone();
fGlobalElemDeclsExt = grammar.fGlobalElemDeclsExt.makeClone();
fGlobalGroupDeclsExt = grammar.fGlobalGroupDeclsExt.makeClone();
fGlobalNotationDeclsExt = grammar.fGlobalNotationDeclsExt.makeClone();
fGlobalIDConstraintDeclsExt = grammar.fGlobalIDConstraintDeclsExt.makeClone();
fGlobalTypeDeclsExt = grammar.fGlobalTypeDeclsExt.makeClone();
// All global elements table
fAllGlobalElemDecls = grammar.fAllGlobalElemDecls.makeClone();
// Annotations associated with the "root" schema of this targetNamespace
fNumAnnotations = grammar.fNumAnnotations;
if (fNumAnnotations > 0) {
fAnnotations = new XSAnnotationImpl[grammar.fAnnotations.length];
System.arraycopy(grammar.fAnnotations, 0, fAnnotations, 0, fNumAnnotations);
}
// All substitution group information declared in this namespace
fSubGroupCount = grammar.fSubGroupCount;
if (fSubGroupCount > 0) {
fSubGroups = new XSElementDecl[grammar.fSubGroups.length];
System.arraycopy(grammar.fSubGroups, 0, fSubGroups, 0, fSubGroupCount);
}
// Array to store complex type decls for constraint checking
fCTCount = grammar.fCTCount;
if (fCTCount > 0) {
fComplexTypeDecls = new XSComplexTypeDecl[grammar.fComplexTypeDecls.length];
fCTLocators = new SimpleLocator[grammar.fCTLocators.length];
System.arraycopy(grammar.fComplexTypeDecls, 0, fComplexTypeDecls, 0, fCTCount);
System.arraycopy(grammar.fCTLocators, 0, fCTLocators, 0, fCTCount);
}
// Groups being redefined by restriction
fRGCount = grammar.fRGCount;
if (fRGCount > 0) {
fRedefinedGroupDecls = new XSGroupDecl[grammar.fRedefinedGroupDecls.length];
fRGLocators = new SimpleLocator[grammar.fRGLocators.length];
System.arraycopy(grammar.fRedefinedGroupDecls, 0, fRedefinedGroupDecls, 0, fRGCount);
System.arraycopy(grammar.fRGLocators, 0, fRGLocators, 0, fRGCount/2);
}
// List of imported grammars
if (grammar.fImported != null) {
fImported = new ArrayList<>();
for (int i=0; i<grammar.fImported.size(); i++) {
fImported.add(grammar.fImported.get(i));
}
}
// Locations
if (grammar.fLocations != null) {
for (int k=0; k<grammar.fLocations.size(); k++) {
addDocument(null, grammar.fLocations.get(k));
}
}
} // <init>(String, XSDDescription)
// number of built-in XSTypes we need to create for base and full
// datatype set
private static final int BASICSET_COUNT = 29;
private static final int FULLSET_COUNT = 46;
private static final int GRAMMAR_XS = 1;
private static final int GRAMMAR_XSI = 2;
// this class makes sure the static, built-in schema grammars
// are immutable.
public static class BuiltinSchemaGrammar extends SchemaGrammar {
private static final String EXTENDED_SCHEMA_FACTORY_CLASS = "com.sun.org.apache.xerces.internal.impl.dv.xs.ExtendedSchemaDVFactoryImpl";
/**
* Special constructor to create the grammars for the schema namespaces
*
* @param grammar
*/
public BuiltinSchemaGrammar(int grammar, short schemaVersion) {
SchemaDVFactory schemaFactory;
if (schemaVersion == Constants.SCHEMA_VERSION_1_0) {
schemaFactory = SchemaDVFactory.getInstance();
}
else {
schemaFactory = SchemaDVFactory.getInstance(EXTENDED_SCHEMA_FACTORY_CLASS);
}
if (grammar == GRAMMAR_XS) {
// target namespace
fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA);
// no global decls other than types
fGlobalAttrDecls = new SymbolHash(1);
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(1);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(1);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// all global element decls table
fAllGlobalElemDecls = new SymbolHash(1);
// get all built-in types
fGlobalTypeDecls = schemaFactory.getBuiltInTypes();
// assign the built-in schema grammar as the XSNamespaceItem
// for each of the built-in simple type definitions.
int length = fGlobalTypeDecls.getLength();
XSTypeDefinition [] typeDefinitions = new XSTypeDefinition[length];
fGlobalTypeDecls.getValues(typeDefinitions, 0);
for (int i = 0; i < length; ++i) {
XSTypeDefinition xtd = typeDefinitions[i];
if (xtd instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) xtd).setNamespaceItem(this);
}
}
// add anyType
fGlobalTypeDecls.put(fAnyType.getName(), fAnyType);
}
else if (grammar == GRAMMAR_XSI) {
// target namespace
fTargetNamespace = SchemaSymbols.URI_XSI;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_XSI);
// no global decls other than attributes
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(1);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
fGlobalTypeDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(1);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// no all global element decls
fAllGlobalElemDecls = new SymbolHash(1);
// 4 attributes, so initialize the size as 4*2 = 8
fGlobalAttrDecls = new SymbolHash(8);
String name = null;
String tns = null;
XSSimpleType type = null;
short scope = XSConstants.SCOPE_GLOBAL;
// xsi:type
name = SchemaSymbols.XSI_TYPE;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_QNAME);
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
// xsi:nil
name = SchemaSymbols.XSI_NIL;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_BOOLEAN);
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
XSSimpleType anyURI = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_ANYURI);
// xsi:schemaLocation
name = SchemaSymbols.XSI_SCHEMALOCATION;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.createTypeList("#AnonType_schemaLocation", SchemaSymbols.URI_XSI, (short)0, anyURI, null);
if (type instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl)type).setAnonymous(true);
}
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
// xsi:noNamespaceSchemaLocation
name = SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION;
tns = SchemaSymbols.URI_XSI;
type = anyURI;
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
}
} // <init>(int)
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription.makeClone();
} // getGrammarDescription(): XMLGrammarDescription
// override these methods solely so that these
// objects cannot be modified once they're created.
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl, String location) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
// ignore
}
public void addGlobalElementDeclAll(XSElementDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
// ignore
}
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
// ignore
}
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
// ignore
}
public synchronized void addDocument(Object document, String location) {
// ignore
}
// annotation support
synchronized DOMParser getDOMParser() {
return null;
}
synchronized SAXParser getSAXParser() {
return null;
}
}
/**
* <p>A partial schema for schemas for validating annotations.</p>
*
* @xerces.internal
*
* @author Michael Glavassevich, IBM
*/
public static final class Schema4Annotations extends SchemaGrammar {
/**
* Singleton instance.
*/
public static final Schema4Annotations INSTANCE = new Schema4Annotations();
/**
* Special constructor to create a schema
* capable of validating annotations.
*/
private Schema4Annotations() {
// target namespace
fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA);
// no global decls other than types and
// element declarations for <annotation>, <documentation> and <appinfo>.
fGlobalAttrDecls = new SymbolHash(1);
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(6);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(6);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// all global element declarations
fAllGlobalElemDecls = new SymbolHash(6);
// get all built-in types
fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls;
// create element declarations for <annotation>, <documentation> and <appinfo>
XSElementDecl annotationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_ANNOTATION);
XSElementDecl documentationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_DOCUMENTATION);
XSElementDecl appinfoDecl = createAnnotationElementDecl(SchemaSymbols.ELT_APPINFO);
// add global element declarations
fGlobalElemDecls.put(annotationDecl.fName, annotationDecl);
fGlobalElemDecls.put(documentationDecl.fName, documentationDecl);
fGlobalElemDecls.put(appinfoDecl.fName, appinfoDecl);
fGlobalElemDeclsExt.put(","+annotationDecl.fName, annotationDecl);
fGlobalElemDeclsExt.put(","+documentationDecl.fName, documentationDecl);
fGlobalElemDeclsExt.put(","+appinfoDecl.fName, appinfoDecl);
fAllGlobalElemDecls.put(annotationDecl, annotationDecl);
fAllGlobalElemDecls.put(documentationDecl, documentationDecl);
fAllGlobalElemDecls.put(appinfoDecl, appinfoDecl);
// create complex type declarations for <annotation>, <documentation> and <appinfo>
XSComplexTypeDecl annotationType = new XSComplexTypeDecl();
XSComplexTypeDecl documentationType = new XSComplexTypeDecl();
XSComplexTypeDecl appinfoType = new XSComplexTypeDecl();
// set the types on their element declarations
annotationDecl.fType = annotationType;
documentationDecl.fType = documentationType;
appinfoDecl.fType = appinfoType;
// create attribute groups for <annotation>, <documentation> and <appinfo>
XSAttributeGroupDecl annotationAttrs = new XSAttributeGroupDecl();
XSAttributeGroupDecl documentationAttrs = new XSAttributeGroupDecl();
XSAttributeGroupDecl appinfoAttrs = new XSAttributeGroupDecl();
// fill in attribute groups
{
// create and fill attribute uses for <annotation>, <documentation> and <appinfo>
XSAttributeUseImpl annotationIDAttr = new XSAttributeUseImpl();
annotationIDAttr.fAttrDecl = new XSAttributeDecl();
annotationIDAttr.fAttrDecl.setValues(SchemaSymbols.ATT_ID, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ID),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, annotationType, null);
annotationIDAttr.fUse = SchemaSymbols.USE_OPTIONAL;
annotationIDAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl documentationSourceAttr = new XSAttributeUseImpl();
documentationSourceAttr.fAttrDecl = new XSAttributeDecl();
documentationSourceAttr.fAttrDecl.setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ANYURI),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, documentationType, null);
documentationSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL;
documentationSourceAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl documentationLangAttr = new XSAttributeUseImpl();
documentationLangAttr.fAttrDecl = new XSAttributeDecl();
documentationLangAttr.fAttrDecl.setValues("lang".intern(), NamespaceContext.XML_URI, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_LANGUAGE),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, documentationType, null);
documentationLangAttr.fUse = SchemaSymbols.USE_OPTIONAL;
documentationLangAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl appinfoSourceAttr = new XSAttributeUseImpl();
appinfoSourceAttr.fAttrDecl = new XSAttributeDecl();
appinfoSourceAttr.fAttrDecl.setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ANYURI),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, appinfoType, null);
appinfoSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL;
appinfoSourceAttr.fConstraintType = XSConstants.VC_NONE;
// create lax attribute wildcard for <annotation>, <documentation> and <appinfo>
XSWildcardDecl [MASK] = new XSWildcardDecl();
[MASK] .fNamespaceList = new String [] {fTargetNamespace, null};
[MASK] .fType = XSWildcard.NSCONSTRAINT_NOT;
[MASK] .fProcessContents = XSWildcard.PC_LAX;
// add attribute uses and wildcards to attribute groups for <annotation>, <documentation> and <appinfo>
annotationAttrs.addAttributeUse(annotationIDAttr);
annotationAttrs.fAttributeWC = [MASK] ;
documentationAttrs.addAttributeUse(documentationSourceAttr);
documentationAttrs.addAttributeUse(documentationLangAttr);
documentationAttrs.fAttributeWC = [MASK] ;
appinfoAttrs.addAttributeUse(appinfoSourceAttr);
appinfoAttrs.fAttributeWC = [MASK] ;
}
// create particles for <annotation>
XSParticleDecl annotationParticle = createUnboundedModelGroupParticle();
{
XSModelGroupImpl annotationChoice = new XSModelGroupImpl();
annotationChoice.fCompositor = XSModelGroupImpl.MODELGROUP_CHOICE;
annotationChoice.fParticleCount = 2;
annotationChoice.fParticles = new XSParticleDecl[2];
annotationChoice.fParticles[0] = createChoiceElementParticle(appinfoDecl);
annotationChoice.fParticles[1] = createChoiceElementParticle(documentationDecl);
annotationParticle.fValue = annotationChoice;
}
// create wildcard particle for <documentation> and <appinfo>
XSParticleDecl anyWCSequenceParticle = createUnboundedAnyWildcardSequenceParticle();
// fill complex types
annotationType.setValues("#AnonType_" + SchemaSymbols.ELT_ANNOTATION, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_ELEMENT, false, annotationAttrs, null, annotationParticle, XSObjectListImpl.EMPTY_LIST);
annotationType.setName("#AnonType_" + SchemaSymbols.ELT_ANNOTATION);
annotationType.setIsAnonymous();
documentationType.setValues("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_MIXED, false, documentationAttrs, null, anyWCSequenceParticle, XSObjectListImpl.EMPTY_LIST);
documentationType.setName("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION);
documentationType.setIsAnonymous();
appinfoType.setValues("#AnonType_" + SchemaSymbols.ELT_APPINFO, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_MIXED, false, appinfoAttrs, null, anyWCSequenceParticle, XSObjectListImpl.EMPTY_LIST);
appinfoType.setName("#AnonType_" + SchemaSymbols.ELT_APPINFO);
appinfoType.setIsAnonymous();
} // <init>(int)
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription.makeClone();
} // getGrammarDescription(): XMLGrammarDescription
// override these methods solely so that these
// objects cannot be modified once they're created.
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
// ignore
}
public void addGlobalElementDeclAll(XSElementDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
// ignore
}
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
// ignore
}
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
// ignore
}
public synchronized void addDocument(Object document, String location) {
// ignore
}
// annotation support
synchronized DOMParser getDOMParser() {
return null;
}
synchronized SAXParser getSAXParser() {
return null;
}
//
// private helper methods
//
private XSElementDecl createAnnotationElementDecl(String localName) {
XSElementDecl eDecl = new XSElementDecl();
eDecl.fName = localName;
eDecl.fTargetNamespace = fTargetNamespace;
eDecl.setIsGlobal();
eDecl.fBlock = (XSConstants.DERIVATION_EXTENSION |
XSConstants.DERIVATION_RESTRICTION | XSConstants.DERIVATION_SUBSTITUTION);
eDecl.setConstraintType(XSConstants.VC_NONE);
return eDecl;
}
private XSParticleDecl createUnboundedModelGroupParticle() {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 0;
particle.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED;
particle.fType = XSParticleDecl.PARTICLE_MODELGROUP;
return particle;
}
private XSParticleDecl createChoiceElementParticle(XSElementDecl ref) {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 1;
particle.fMaxOccurs = 1;
particle.fType = XSParticleDecl.PARTICLE_ELEMENT;
particle.fValue = ref;
return particle;
}
private XSParticleDecl createUnboundedAnyWildcardSequenceParticle() {
XSParticleDecl particle = createUnboundedModelGroupParticle();
XSModelGroupImpl sequence = new XSModelGroupImpl();
sequence.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE;
sequence.fParticleCount = 1;
sequence.fParticles = new XSParticleDecl[1];
sequence.fParticles[0] = createAnyLaxWildcardParticle();
particle.fValue = sequence;
return particle;
}
private XSParticleDecl createAnyLaxWildcardParticle() {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 1;
particle.fMaxOccurs = 1;
particle.fType = XSParticleDecl.PARTICLE_WILDCARD;
XSWildcardDecl anyWC = new XSWildcardDecl();
anyWC.fNamespaceList = null;
anyWC.fType = XSWildcard.NSCONSTRAINT_ANY;
anyWC.fProcessContents = XSWildcard.PC_LAX;
particle.fValue = anyWC;
return particle;
}
}
// Grammar methods
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription;
} // getGrammarDescription(): XMLGrammarDescription
// DTDGrammar methods
public boolean isNamespaceAware () {
return true;
} // isNamespaceAware():boolean
List<SchemaGrammar> fImported = null;
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
fImported = importedGrammars;
}
public List<SchemaGrammar> getImportedGrammars() {
return fImported;
}
/**
* Returns this grammar's target namespace.
*/
public final String getTargetNamespace() {
return fTargetNamespace;
} // getTargetNamespace():String
/**
* register one global attribute
*/
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
fGlobalAttrDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalAttributeDecl(XSAttributeDecl decl, String location) {
fGlobalAttrDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global attribute group
*/
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
fGlobalAttrGrpDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
fGlobalAttrGrpDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global element
*/
public void addGlobalElementDeclAll(XSElementDecl decl) {
if (fAllGlobalElemDecls.get(decl) == null) {
fAllGlobalElemDecls.put(decl, decl);
// if there is a substitution group affiliation, store in an array,
// for further constraint checking: UPA, PD, EDC
if (decl.fSubGroup != null) {
if (fSubGroupCount == fSubGroups.length)
fSubGroups = resize(fSubGroups, fSubGroupCount+INC_SIZE);
fSubGroups[fSubGroupCount++] = decl;
}
}
}
public void addGlobalElementDecl(XSElementDecl decl) {
fGlobalElemDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
fGlobalElemDeclsExt.put(((location != null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global group
*/
public void addGlobalGroupDecl(XSGroupDecl decl) {
fGlobalGroupDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
fGlobalGroupDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global notation
*/
public void addGlobalNotationDecl(XSNotationDecl decl) {
fGlobalNotationDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
fGlobalNotationDeclsExt.put(((location!=null) ? location : "") + "," +decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global type
*/
public void addGlobalTypeDecl(XSTypeDefinition decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
if (decl instanceof XSComplexTypeDecl) {
((XSComplexTypeDecl) decl).setNamespaceItem(this);
}
else if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
fGlobalTypeDeclsExt.put(((location!=null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null) {
if (decl instanceof XSComplexTypeDecl) {
((XSComplexTypeDecl) decl).setNamespaceItem(this);
}
else if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
}
/**
* register one global complex type
*/
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
decl.setNamespaceItem(this);
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
fGlobalTypeDeclsExt.put(((location!=null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global simple type
*/
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
fGlobalTypeDeclsExt.put(((location != null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null && decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
/**
* register one identity constraint
*/
public final void addIDConstraintDecl(XSElementDecl elmDecl, IdentityConstraint decl) {
elmDecl.addIDConstraint(decl);
fGlobalIDConstraintDecls.put(decl.getIdentityConstraintName(), decl);
}
public final void addIDConstraintDecl(XSElementDecl elmDecl, IdentityConstraint decl, String location) {
fGlobalIDConstraintDeclsExt.put(((location != null) ? location : "") + "," + decl.getIdentityConstraintName(), decl);
}
/**
* get one global attribute
*/
public final XSAttributeDecl getGlobalAttributeDecl(String declName) {
return(XSAttributeDecl)fGlobalAttrDecls.get(declName);
}
public final XSAttributeDecl getGlobalAttributeDecl(String declName, String location) {
return(XSAttributeDecl)fGlobalAttrDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global attribute group
*/
public final XSAttributeGroupDecl getGlobalAttributeGroupDecl(String declName) {
return(XSAttributeGroupDecl)fGlobalAttrGrpDecls.get(declName);
}
public final XSAttributeGroupDecl getGlobalAttributeGroupDecl(String declName, String location) {
return(XSAttributeGroupDecl)fGlobalAttrGrpDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global element
*/
public final XSElementDecl getGlobalElementDecl(String declName) {
return(XSElementDecl)fGlobalElemDecls.get(declName);
}
public final XSElementDecl getGlobalElementDecl(String declName, String location) {
return(XSElementDecl)fGlobalElemDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global group
*/
public final XSGroupDecl getGlobalGroupDecl(String declName) {
return(XSGroupDecl)fGlobalGroupDecls.get(declName);
}
public final XSGroupDecl getGlobalGroupDecl(String declName, String location) {
return(XSGroupDecl)fGlobalGroupDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global notation
*/
public final XSNotationDecl getGlobalNotationDecl(String declName) {
return(XSNotationDecl)fGlobalNotationDecls.get(declName);
}
public final XSNotationDecl getGlobalNotationDecl(String declName, String location) {
return(XSNotationDecl)fGlobalNotationDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global type
*/
public final XSTypeDefinition getGlobalTypeDecl(String declName) {
return(XSTypeDefinition)fGlobalTypeDecls.get(declName);
}
public final XSTypeDefinition getGlobalTypeDecl(String declName, String location) {
return(XSTypeDefinition)fGlobalTypeDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one identity constraint
*/
public final IdentityConstraint getIDConstraintDecl(String declName) {
return(IdentityConstraint)fGlobalIDConstraintDecls.get(declName);
}
public final IdentityConstraint getIDConstraintDecl(String declName, String location) {
return(IdentityConstraint)fGlobalIDConstraintDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one identity constraint
*/
public final boolean hasIDConstraints() {
return fGlobalIDConstraintDecls.getLength() > 0;
}
// array to store complex type decls
private static final int INITIAL_SIZE = 16;
private static final int INC_SIZE = 16;
private int fCTCount = 0;
private XSComplexTypeDecl[] fComplexTypeDecls = new XSComplexTypeDecl[INITIAL_SIZE];
private SimpleLocator[] fCTLocators = new SimpleLocator[INITIAL_SIZE];
// an array to store groups being redefined by restriction
// even-numbered elements are the derived groups, odd-numbered ones their bases
private static final int REDEFINED_GROUP_INIT_SIZE = 2;
private int fRGCount = 0;
private XSGroupDecl[] fRedefinedGroupDecls = new XSGroupDecl[REDEFINED_GROUP_INIT_SIZE];
private SimpleLocator[] fRGLocators = new SimpleLocator[REDEFINED_GROUP_INIT_SIZE/2];
// a flag to indicate whether we have checked the 3 constraints on this
// grammar.
boolean fFullChecked = false;
/**
* add one complex type decl: for later constraint checking
*/
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
if (fCTCount == fComplexTypeDecls.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount+INC_SIZE);
fCTLocators = resize(fCTLocators, fCTCount+INC_SIZE);
}
fCTLocators[fCTCount] = locator;
fComplexTypeDecls[fCTCount++] = decl;
}
/**
* add a group redefined by restriction: for later constraint checking
*/
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
if (fRGCount == fRedefinedGroupDecls.length) {
// double array size each time.
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount << 1);
fRGLocators = resize(fRGLocators, fRGCount);
}
fRGLocators[fRGCount/2] = locator;
fRedefinedGroupDecls[fRGCount++] = derived;
fRedefinedGroupDecls[fRGCount++] = base;
}
/**
* get all complex type decls: for later constraint checking
*/
final XSComplexTypeDecl[] getUncheckedComplexTypeDecls() {
if (fCTCount < fComplexTypeDecls.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
return fComplexTypeDecls;
}
/**
* get the error locator of all complex type decls
*/
final SimpleLocator[] getUncheckedCTLocators() {
if (fCTCount < fCTLocators.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
return fCTLocators;
}
/**
* get all redefined groups: for later constraint checking
*/
final XSGroupDecl[] getRedefinedGroupDecls() {
if (fRGCount < fRedefinedGroupDecls.length) {
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount);
fRGLocators = resize(fRGLocators, fRGCount/2);
}
return fRedefinedGroupDecls;
}
/**
* get the error locator of all redefined groups
*/
final SimpleLocator[] getRGLocators() {
if (fRGCount < fRedefinedGroupDecls.length) {
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount);
fRGLocators = resize(fRGLocators, fRGCount/2);
}
return fRGLocators;
}
/**
* after the first-round checking, some types don't need to be checked
* against UPA again. here we trim the array to the proper size.
*/
final void setUncheckedTypeNum(int newSize) {
fCTCount = newSize;
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
// used to store all substitution group information declared in
// this namespace
private int fSubGroupCount = 0;
private XSElementDecl[] fSubGroups = new XSElementDecl[INITIAL_SIZE];
/**
* get all substitution group information: for the 3 constraint checking
*/
final XSElementDecl[] getSubstitutionGroups() {
if (fSubGroupCount < fSubGroups.length)
fSubGroups = resize(fSubGroups, fSubGroupCount);
return fSubGroups;
}
// anyType and anySimpleType: because there are so many places where
// we need direct access to these two types
public final static XSComplexTypeDecl fAnyType = new XSAnyType();
private static class XSAnyType extends XSComplexTypeDecl {
public XSAnyType () {
fName = SchemaSymbols.ATTVAL_ANYTYPE;
super.fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
fBaseType = this;
fDerivedBy = XSConstants.DERIVATION_RESTRICTION;
fContentType = XSComplexTypeDecl.CONTENTTYPE_MIXED;
fParticle = createParticle();
fAttrGrp = createAttrGrp();
}
// overridden methods
public void setValues(String name, String targetNamespace,
XSTypeDefinition baseType, short derivedBy, short schemaFinal,
short block, short contentType,
boolean isAbstract, XSAttributeGroupDecl attrGrp,
XSSimpleType simpleType, XSParticleDecl particle) {
// don't allow this.
}
public void setName(String name){
// don't allow this.
}
public void setIsAbstractType() {
// null implementation
}
public void setContainsTypeID() {
// null implementation
}
public void setIsAnonymous() {
// null implementation
}
public void reset() {
// null implementation
}
public XSObjectList getAnnotations() {
return XSObjectListImpl.EMPTY_LIST;
}
public XSNamespaceItem getNamespaceItem() {
return SG_SchemaNS;
}
private XSAttributeGroupDecl createAttrGrp() {
XSWildcardDecl wildcard = new XSWildcardDecl();
wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
XSAttributeGroupDecl attrGrp = new XSAttributeGroupDecl();
attrGrp.fAttributeWC = wildcard;
return attrGrp;
}
private XSParticleDecl createParticle() {
// the wildcard used in anyType (content and attribute)
// the spec will change strict to skip for anyType
XSWildcardDecl wildcard = new XSWildcardDecl();
wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
// the particle for the content wildcard
XSParticleDecl particleW = new XSParticleDecl();
particleW.fMinOccurs = 0;
particleW.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED;
particleW.fType = XSParticleDecl.PARTICLE_WILDCARD;
particleW.fValue = wildcard;
// the model group of a sequence of the above particle
XSModelGroupImpl group = new XSModelGroupImpl();
group.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE;
group.fParticleCount = 1;
group.fParticles = new XSParticleDecl[1];
group.fParticles[0] = particleW;
// the content of anyType: particle of the above model group
XSParticleDecl particleG = new XSParticleDecl();
particleG.fType = XSParticleDecl.PARTICLE_MODELGROUP;
particleG.fValue = group;
return particleG;
}
}
private static class BuiltinAttrDecl extends XSAttributeDecl {
public BuiltinAttrDecl(String name, String tns,
XSSimpleType type, short scope) {
fName = name;
super.fTargetNamespace = tns;
fType = type;
fScope = scope;
}
public void setValues(String name, String targetNamespace,
XSSimpleType simpleType, short constraintType, short scope,
ValidatedInfo valInfo, XSComplexTypeDecl enclosingCT) {
// ignore this call.
}
public void reset () {
// also ignore this call.
}
public XSAnnotation getAnnotation() {
return null;
}
public XSNamespaceItem getNamespaceItem() {
return SG_XSI;
}
} // class BuiltinAttrDecl
// the grammars to hold components of the schema namespace
public final static BuiltinSchemaGrammar SG_SchemaNS = new BuiltinSchemaGrammar(GRAMMAR_XS, Constants.SCHEMA_VERSION_1_0);
private final static BuiltinSchemaGrammar SG_SchemaNSExtended = new BuiltinSchemaGrammar(GRAMMAR_XS, Constants.SCHEMA_VERSION_1_0_EXTENDED);
public final static XSSimpleType fAnySimpleType = (XSSimpleType)SG_SchemaNS.getGlobalTypeDecl(SchemaSymbols.ATTVAL_ANYSIMPLETYPE);
// the grammars to hold components of the schema-instance namespace
public final static BuiltinSchemaGrammar SG_XSI = new BuiltinSchemaGrammar(GRAMMAR_XSI, Constants.SCHEMA_VERSION_1_0);
public static SchemaGrammar getS4SGrammar(short schemaVersion) {
if (schemaVersion == Constants.SCHEMA_VERSION_1_0) {
return SG_SchemaNS;
}
else {
return SG_SchemaNSExtended;
}
}
static final XSComplexTypeDecl[] resize(XSComplexTypeDecl[] oldArray, int newSize) {
XSComplexTypeDecl[] newArray = new XSComplexTypeDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final XSGroupDecl[] resize(XSGroupDecl[] oldArray, int newSize) {
XSGroupDecl[] newArray = new XSGroupDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final XSElementDecl[] resize(XSElementDecl[] oldArray, int newSize) {
XSElementDecl[] newArray = new XSElementDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final SimpleLocator[] resize(SimpleLocator[] oldArray, int newSize) {
SimpleLocator[] newArray = new SimpleLocator[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
// XSNamespaceItem methods
// the max index / the max value of XSObject type
private static final short MAX_COMP_IDX = XSTypeDefinition.SIMPLE_TYPE;
private static final boolean[] GLOBAL_COMP = {false, // null
true, // attribute
true, // element
true, // type
false, // attribute use
true, // attribute group
true, // group
false, // model group
false, // particle
false, // wildcard
true, // idc
true, // notation
false, // annotation
false, // facet
false, // multi value facet
true, // complex type
true // simple type
};
// store a certain kind of components from all namespaces
private XSNamedMap[] fComponents = null;
private ObjectList[] fComponentsExt = null;
// store the documents and their locations contributing to this namespace
// REVISIT: use StringList and XSObjectList for there fields.
// fDocuments is never used
private List<Object> fDocuments = null;
private List<String> fLocations = null;
public synchronized void addDocument(Object document, String location) {
if (fDocuments == null) {
// Parsing schema is not thread safe, synchronized may be removed
fDocuments = new CopyOnWriteArrayList<>();
fLocations = new CopyOnWriteArrayList<>();
}
fDocuments.add(document);
fLocations.add(location);
}
public synchronized void removeDocument(int index) {
if (fDocuments != null &&
index >= 0 &&
index < fDocuments.size()) {
fDocuments.remove(index);
fLocations.remove(index);
}
}
/**
* [schema namespace]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#nsi-schema_namespace">[schema namespace]</a>
* @return The target namespace of this item.
*/
public String getSchemaNamespace() {
return fTargetNamespace;
}
// annotation support
synchronized DOMParser getDOMParser() {
if (fDOMParser != null) {
DOMParser parser = fDOMParser.get();
if (parser != null) {
return parser;
}
}
// REVISIT: when schema handles XML 1.1, will need to
// revisit this (and the practice of not prepending an XML decl to the annotation string
XML11Configuration config = new XML11Configuration(fSymbolTable);
// note that this should never produce errors or require
// entity resolution, so just a barebones configuration with
// a couple of feature set will do fine
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true);
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false);
DOMParser parser = new DOMParser(config);
try {
parser.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.DEFER_NODE_EXPANSION_FEATURE, false);
}
catch (SAXException exc) {}
fDOMParser = new SoftReference<DOMParser>(parser);
return parser;
}
synchronized SAXParser getSAXParser() {
if (fSAXParser != null) {
SAXParser parser = fSAXParser.get();
if (parser != null) {
return parser;
}
}
// REVISIT: when schema handles XML 1.1, will need to
// revisit this (and the practice of not prepending an XML decl to the annotation string
XML11Configuration config = new XML11Configuration(fSymbolTable);
// note that this should never produce errors or require
// entity resolution, so just a barebones configuration with
// a couple of feature set will do fine
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true);
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false);
SAXParser parser = new SAXParser(config);
fSAXParser = new SoftReference<SAXParser>(parser);
return parser;
}
/**
* [schema components]: a list of top-level components, i.e. element
* declarations, attribute declarations, etc.
* @param objectType The type of the declaration, i.e.
* <code>ELEMENT_DECLARATION</code>. Note that
* <code>XSTypeDefinition.SIMPLE_TYPE</code> and
* <code>XSTypeDefinition.COMPLEX_TYPE</code> can also be used as the
* <code>objectType</code> to retrieve only complex types or simple
* types, instead of all types.
* @return A list of top-level definition of the specified type in
* <code>objectType</code> or an empty <code>XSNamedMap</code> if no
* such definitions exist.
*/
public synchronized XSNamedMap getComponents(short objectType) {
if (objectType <= 0 || objectType > MAX_COMP_IDX ||
!GLOBAL_COMP[objectType]) {
return XSNamedMapImpl.EMPTY_MAP;
}
if (fComponents == null)
fComponents = new XSNamedMap[MAX_COMP_IDX+1];
// get the hashtable for this type of components
if (fComponents[objectType] == null) {
SymbolHash table = null;
switch (objectType) {
case XSConstants.TYPE_DEFINITION:
case XSTypeDefinition.COMPLEX_TYPE:
case XSTypeDefinition.SIMPLE_TYPE:
table = fGlobalTypeDecls;
break;
case XSConstants.ATTRIBUTE_DECLARATION:
table = fGlobalAttrDecls;
break;
case XSConstants.ELEMENT_DECLARATION:
table = fGlobalElemDecls;
break;
case XSConstants.ATTRIBUTE_GROUP:
table = fGlobalAttrGrpDecls;
break;
case XSConstants.MODEL_GROUP_DEFINITION:
table = fGlobalGroupDecls;
break;
case XSConstants.NOTATION_DECLARATION:
table = fGlobalNotationDecls;
break;
case XSConstants.IDENTITY_CONSTRAINT:
table = this.fGlobalIDConstraintDecls;
break;
}
// for complex/simple types, create a special implementation,
// which take specific types out of the hash table
if (objectType == XSTypeDefinition.COMPLEX_TYPE ||
objectType == XSTypeDefinition.SIMPLE_TYPE) {
fComponents[objectType] = new XSNamedMap4Types(fTargetNamespace, table, objectType);
}
else {
fComponents[objectType] = new XSNamedMapImpl(fTargetNamespace, table);
}
}
return fComponents[objectType];
}
public synchronized ObjectList getComponentsExt(short objectType) {
if (objectType <= 0 || objectType > MAX_COMP_IDX ||
!GLOBAL_COMP[objectType]) {
return ObjectListImpl.EMPTY_LIST;
}
if (fComponentsExt == null)
fComponentsExt = new ObjectList[MAX_COMP_IDX+1];
// get the hashtable for this type of components
if (fComponentsExt[objectType] == null) {
SymbolHash table = null;
switch (objectType) {
case XSConstants.TYPE_DEFINITION:
case XSTypeDefinition.COMPLEX_TYPE:
case XSTypeDefinition.SIMPLE_TYPE:
table = fGlobalTypeDeclsExt;
break;
case XSConstants.ATTRIBUTE_DECLARATION:
table = fGlobalAttrDeclsExt;
break;
case XSConstants.ELEMENT_DECLARATION:
table = fGlobalElemDeclsExt;
break;
case XSConstants.ATTRIBUTE_GROUP:
table = fGlobalAttrGrpDeclsExt;
break;
case XSConstants.MODEL_GROUP_DEFINITION:
table = fGlobalGroupDeclsExt;
break;
case XSConstants.NOTATION_DECLARATION:
table = fGlobalNotationDeclsExt;
break;
case XSConstants.IDENTITY_CONSTRAINT:
table = this.fGlobalIDConstraintDeclsExt;
break;
}
Object[] entries = table.getEntries();
fComponentsExt[objectType] = new ObjectListImpl(entries, entries.length);
}
return fComponentsExt[objectType];
}
public synchronized void resetComponents() {
fComponents = null;
fComponentsExt = null;
}
/**
* Convenience method. Returns a top-level simple or complex type
* definition.
* @param name The name of the definition.
* @return An <code>XSTypeDefinition</code> or null if such definition
* does not exist.
*/
public XSTypeDefinition getTypeDefinition(String name) {
return getGlobalTypeDecl(name);
}
/**
* Convenience method. Returns a top-level attribute declaration.
* @param name The name of the declaration.
* @return A top-level attribute declaration or null if such declaration
* does not exist.
*/
public XSAttributeDeclaration getAttributeDeclaration(String name) {
return getGlobalAttributeDecl(name);
}
/**
* Convenience method. Returns a top-level element declaration.
* @param name The name of the declaration.
* @return A top-level element declaration or null if such declaration
* does not exist.
*/
public XSElementDeclaration getElementDeclaration(String name) {
return getGlobalElementDecl(name);
}
/**
* Convenience method. Returns a top-level attribute group definition.
* @param name The name of the definition.
* @return A top-level attribute group definition or null if such
* definition does not exist.
*/
public XSAttributeGroupDefinition getAttributeGroup(String name) {
return getGlobalAttributeGroupDecl(name);
}
/**
* Convenience method. Returns a top-level model group definition.
*
* @param name The name of the definition.
* @return A top-level model group definition definition or null if such
* definition does not exist.
*/
public XSModelGroupDefinition getModelGroupDefinition(String name) {
return getGlobalGroupDecl(name);
}
/**
* Convenience method. Returns a top-level notation declaration.
*
* @param name The name of the declaration.
* @return A top-level notation declaration or null if such declaration
* does not exist.
*/
public XSNotationDeclaration getNotationDeclaration(String name) {
return getGlobalNotationDecl(name);
}
public XSIDCDefinition getIDCDefinition(String name) {
return getIDConstraintDecl(name);
}
/**
* [document location]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#sd-document_location">[document location]</a>
* @return a list of document information item
*/
public StringList getDocumentLocations() {
return new StringListImpl(fLocations);
}
/**
* Return an <code>XSModel</code> that represents components in this schema
* grammar.
*
* @return an <code>XSModel</code> representing this schema grammar
*/
public XSModel toXSModel() {
return new XSModelImpl(new SchemaGrammar[]{this});
}
public XSModel toXSModel(XSGrammar[] grammars) {
if (grammars == null || grammars.length == 0)
return toXSModel();
int len = grammars.length;
boolean hasSelf = false;
for (int i = 0; i < len; i++) {
if (grammars[i] == this) {
hasSelf = true;
break;
}
}
SchemaGrammar[] gs = new SchemaGrammar[hasSelf ? len : len+1];
for (int i = 0; i < len; i++)
gs[i] = (SchemaGrammar)grammars[i];
if (!hasSelf)
gs[len] = this;
return new XSModelImpl(gs);
}
/**
* @see org.apache.xerces.xs.XSNamespaceItem#getAnnotations()
*/
public XSObjectList getAnnotations() {
if (fNumAnnotations == 0) {
return XSObjectListImpl.EMPTY_LIST;
}
return new XSObjectListImpl(fAnnotations, fNumAnnotations);
}
public void addAnnotation(XSAnnotationImpl annotation) {
if (annotation == null) {
return;
}
if (fAnnotations == null) {
fAnnotations = new XSAnnotationImpl[2];
}
else if (fNumAnnotations == fAnnotations.length) {
XSAnnotationImpl[] newArray = new XSAnnotationImpl[fNumAnnotations << 1];
System.arraycopy(fAnnotations, 0, newArray, 0, fNumAnnotations);
fAnnotations = newArray;
}
fAnnotations[fNumAnnotations++] = annotation;
}
public void setImmutable(boolean isImmutable) {
fIsImmutable = isImmutable;
}
public boolean isImmutable() {
return fIsImmutable;
}
} // class SchemaGrammar
| otherAttrs |
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
*/
/*
* 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 com.sun.org.apache.xerces.internal.impl.xs;
import com.sun.org.apache.xerces.internal.impl.Constants;
import com.sun.org.apache.xerces.internal.impl.dv.SchemaDVFactory;
import com.sun.org.apache.xerces.internal.impl.dv.ValidatedInfo;
import com.sun.org.apache.xerces.internal.impl.dv.XSSimpleType;
import com.sun.org.apache.xerces.internal.impl.dv.xs.XSSimpleTypeDecl;
import com.sun.org.apache.xerces.internal.impl.xs.identity.IdentityConstraint;
import com.sun.org.apache.xerces.internal.impl.xs.util.ObjectListImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.SimpleLocator;
import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSNamedMap4Types;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSNamedMapImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSObjectListImpl;
import com.sun.org.apache.xerces.internal.parsers.DOMParser;
import com.sun.org.apache.xerces.internal.parsers.SAXParser;
import com.sun.org.apache.xerces.internal.parsers.XML11Configuration;
import com.sun.org.apache.xerces.internal.util.SymbolHash;
import com.sun.org.apache.xerces.internal.util.SymbolTable;
import com.sun.org.apache.xerces.internal.xni.NamespaceContext;
import com.sun.org.apache.xerces.internal.xni.grammars.XMLGrammarDescription;
import com.sun.org.apache.xerces.internal.xni.grammars.XSGrammar;
import com.sun.org.apache.xerces.internal.xs.StringList;
import com.sun.org.apache.xerces.internal.xs.XSAnnotation;
import com.sun.org.apache.xerces.internal.xs.XSAttributeDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSAttributeGroupDefinition;
import com.sun.org.apache.xerces.internal.xs.XSConstants;
import com.sun.org.apache.xerces.internal.xs.XSElementDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSIDCDefinition;
import com.sun.org.apache.xerces.internal.xs.XSModel;
import com.sun.org.apache.xerces.internal.xs.XSModelGroupDefinition;
import com.sun.org.apache.xerces.internal.xs.XSNamedMap;
import com.sun.org.apache.xerces.internal.xs.XSNamespaceItem;
import com.sun.org.apache.xerces.internal.xs.XSNotationDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSObjectList;
import com.sun.org.apache.xerces.internal.xs.XSParticle;
import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
import com.sun.org.apache.xerces.internal.xs.XSWildcard;
import com.sun.org.apache.xerces.internal.xs.datatypes.ObjectList;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.xml.sax.SAXException;
/**
* This class is to hold all schema component declaration that are declared
* within one namespace.
*
* The Grammar class this class extends contains what little
* commonality there is between XML Schema and DTD grammars. It's
* useful to distinguish grammar objects from other kinds of object
* when they exist in pools or caches.
*
* @xerces.internal
*
* @author Sandy Gao, IBM
* @author Elena Litani, IBM
*
* @LastModified: Oct 2017
*/
public class SchemaGrammar implements XSGrammar, XSNamespaceItem {
// the target namespace of grammar
String fTargetNamespace;
// global decls: map from decl name to decl object
SymbolHash fGlobalAttrDecls;
SymbolHash fGlobalAttrGrpDecls;
SymbolHash fGlobalElemDecls;
SymbolHash fGlobalGroupDecls;
SymbolHash fGlobalNotationDecls;
SymbolHash fGlobalIDConstraintDecls;
SymbolHash fGlobalTypeDecls;
// extended global decls: map from schema location + decl name to decl object
// key is location,name
SymbolHash fGlobalAttrDeclsExt;
SymbolHash fGlobalAttrGrpDeclsExt;
SymbolHash fGlobalElemDeclsExt;
SymbolHash fGlobalGroupDeclsExt;
SymbolHash fGlobalNotationDeclsExt;
SymbolHash fGlobalIDConstraintDeclsExt;
SymbolHash fGlobalTypeDeclsExt;
// A global map of all global element declarations - used for substitution group computation
// (handy when sharing components by reference, since we might end up with duplicate components
// that are not added to either of the global element declarations above)
SymbolHash fAllGlobalElemDecls;
// the XMLGrammarDescription member
XSDDescription fGrammarDescription = null;
// annotations associated with the "root" schema of this targetNamespace
XSAnnotationImpl [] fAnnotations = null;
// number of annotations declared
int fNumAnnotations;
// symbol table for constructing parsers (annotation support)
private SymbolTable fSymbolTable = null;
// parsers for annotation support
private SoftReference<SAXParser> fSAXParser = null;
private SoftReference<DOMParser> fDOMParser = null;
// is this grammar immutable? (fully constructed and not changeable)
private boolean fIsImmutable = false;
//
// Constructors
//
// needed to make BuiltinSchemaGrammar work.
protected SchemaGrammar() {}
/**
* Default constructor.
*
* @param targetNamespace
* @param grammarDesc the XMLGrammarDescription corresponding to this object
* at the least a systemId should always be known.
* @param symbolTable needed for annotation support
*/
public SchemaGrammar(String targetNamespace, XSDDescription grammarDesc,
SymbolTable symbolTable) {
fTargetNamespace = targetNamespace;
fGrammarDescription = grammarDesc;
fSymbolTable = symbolTable;
// REVISIT: the initial sizes being chosen for each SymbolHash
// may not be ideal and could still be tuned. They were chosen
// somewhat arbitrarily to reduce the initial footprint of
// SymbolHash buckets from 1,515 to 177 (about 12% of the
// default size).
fGlobalAttrDecls = new SymbolHash(12);
fGlobalAttrGrpDecls = new SymbolHash(5);
fGlobalElemDecls = new SymbolHash(25);
fGlobalGroupDecls = new SymbolHash(5);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(3);
// Extended tables
fGlobalAttrDeclsExt = new SymbolHash(12);
fGlobalAttrGrpDeclsExt = new SymbolHash(5);
fGlobalElemDeclsExt = new SymbolHash(25);
fGlobalGroupDeclsExt = new SymbolHash(5);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(3);
fGlobalTypeDeclsExt = new SymbolHash(25);
// All global elements table
fAllGlobalElemDecls = new SymbolHash(25);
// if we are parsing S4S, put built-in types in first
// they might get overwritten by the types from S4S, but that's
// considered what the application wants to do.
if (fTargetNamespace == SchemaSymbols.URI_SCHEMAFORSCHEMA) {
fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls.makeClone();
}
else {
fGlobalTypeDecls = new SymbolHash(25);
}
} // <init>(String, XSDDescription)
// Clone an existing schema grammar
public SchemaGrammar(SchemaGrammar grammar) {
fTargetNamespace = grammar.fTargetNamespace;
fGrammarDescription = grammar.fGrammarDescription.makeClone();
//fGrammarDescription.fContextType |= XSDDescription.CONTEXT_COLLISION; // REVISIT
fSymbolTable = grammar.fSymbolTable; // REVISIT
fGlobalAttrDecls = grammar.fGlobalAttrDecls.makeClone();
fGlobalAttrGrpDecls = grammar.fGlobalAttrGrpDecls.makeClone();
fGlobalElemDecls = grammar.fGlobalElemDecls.makeClone();
fGlobalGroupDecls = grammar.fGlobalGroupDecls.makeClone();
fGlobalNotationDecls = grammar.fGlobalNotationDecls.makeClone();
fGlobalIDConstraintDecls = grammar.fGlobalIDConstraintDecls.makeClone();
fGlobalTypeDecls = grammar.fGlobalTypeDecls.makeClone();
// Extended tables
fGlobalAttrDeclsExt = grammar.fGlobalAttrDeclsExt.makeClone();
fGlobalAttrGrpDeclsExt = grammar.fGlobalAttrGrpDeclsExt.makeClone();
fGlobalElemDeclsExt = grammar.fGlobalElemDeclsExt.makeClone();
fGlobalGroupDeclsExt = grammar.fGlobalGroupDeclsExt.makeClone();
fGlobalNotationDeclsExt = grammar.fGlobalNotationDeclsExt.makeClone();
fGlobalIDConstraintDeclsExt = grammar.fGlobalIDConstraintDeclsExt.makeClone();
fGlobalTypeDeclsExt = grammar.fGlobalTypeDeclsExt.makeClone();
// All global elements table
fAllGlobalElemDecls = grammar.fAllGlobalElemDecls.makeClone();
// Annotations associated with the "root" schema of this targetNamespace
fNumAnnotations = grammar.fNumAnnotations;
if (fNumAnnotations > 0) {
fAnnotations = new XSAnnotationImpl[grammar.fAnnotations.length];
System.arraycopy(grammar.fAnnotations, 0, fAnnotations, 0, fNumAnnotations);
}
// All substitution group information declared in this namespace
fSubGroupCount = grammar.fSubGroupCount;
if (fSubGroupCount > 0) {
fSubGroups = new XSElementDecl[grammar.fSubGroups.length];
System.arraycopy(grammar.fSubGroups, 0, fSubGroups, 0, fSubGroupCount);
}
// Array to store complex type decls for constraint checking
fCTCount = grammar.fCTCount;
if (fCTCount > 0) {
fComplexTypeDecls = new XSComplexTypeDecl[grammar.fComplexTypeDecls.length];
fCTLocators = new SimpleLocator[grammar.fCTLocators.length];
System.arraycopy(grammar.fComplexTypeDecls, 0, fComplexTypeDecls, 0, fCTCount);
System.arraycopy(grammar.fCTLocators, 0, fCTLocators, 0, fCTCount);
}
// Groups being redefined by restriction
fRGCount = grammar.fRGCount;
if (fRGCount > 0) {
fRedefinedGroupDecls = new XSGroupDecl[grammar.fRedefinedGroupDecls.length];
fRGLocators = new SimpleLocator[grammar.fRGLocators.length];
System.arraycopy(grammar.fRedefinedGroupDecls, 0, fRedefinedGroupDecls, 0, fRGCount);
System.arraycopy(grammar.fRGLocators, 0, fRGLocators, 0, fRGCount/2);
}
// List of imported grammars
if (grammar.fImported != null) {
fImported = new ArrayList<>();
for (int i=0; i<grammar.fImported.size(); i++) {
fImported.add(grammar.fImported.get(i));
}
}
// Locations
if (grammar.fLocations != null) {
for (int k=0; k<grammar.fLocations.size(); k++) {
addDocument(null, grammar.fLocations.get(k));
}
}
} // <init>(String, XSDDescription)
// number of built-in XSTypes we need to create for base and full
// datatype set
private static final int BASICSET_COUNT = 29;
private static final int FULLSET_COUNT = 46;
private static final int GRAMMAR_XS = 1;
private static final int GRAMMAR_XSI = 2;
// this class makes sure the static, built-in schema grammars
// are immutable.
public static class BuiltinSchemaGrammar extends SchemaGrammar {
private static final String EXTENDED_SCHEMA_FACTORY_CLASS = "com.sun.org.apache.xerces.internal.impl.dv.xs.ExtendedSchemaDVFactoryImpl";
/**
* Special constructor to create the grammars for the schema namespaces
*
* @param grammar
*/
public BuiltinSchemaGrammar(int grammar, short schemaVersion) {
SchemaDVFactory schemaFactory;
if (schemaVersion == Constants.SCHEMA_VERSION_1_0) {
schemaFactory = SchemaDVFactory.getInstance();
}
else {
schemaFactory = SchemaDVFactory.getInstance(EXTENDED_SCHEMA_FACTORY_CLASS);
}
if (grammar == GRAMMAR_XS) {
// target namespace
fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA);
// no global decls other than types
fGlobalAttrDecls = new SymbolHash(1);
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(1);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(1);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// all global element decls table
fAllGlobalElemDecls = new SymbolHash(1);
// get all built-in types
fGlobalTypeDecls = schemaFactory.getBuiltInTypes();
// assign the built-in schema grammar as the XSNamespaceItem
// for each of the built-in simple type definitions.
int length = fGlobalTypeDecls.getLength();
XSTypeDefinition [] typeDefinitions = new XSTypeDefinition[length];
fGlobalTypeDecls.getValues(typeDefinitions, 0);
for (int i = 0; i < length; ++i) {
XSTypeDefinition xtd = typeDefinitions[i];
if (xtd instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) xtd).setNamespaceItem(this);
}
}
// add anyType
fGlobalTypeDecls.put(fAnyType.getName(), fAnyType);
}
else if (grammar == GRAMMAR_XSI) {
// target namespace
fTargetNamespace = SchemaSymbols.URI_XSI;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_XSI);
// no global decls other than attributes
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(1);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
fGlobalTypeDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(1);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// no all global element decls
fAllGlobalElemDecls = new SymbolHash(1);
// 4 attributes, so initialize the size as 4*2 = 8
fGlobalAttrDecls = new SymbolHash(8);
String name = null;
String tns = null;
XSSimpleType type = null;
short scope = XSConstants.SCOPE_GLOBAL;
// xsi:type
name = SchemaSymbols.XSI_TYPE;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_QNAME);
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
// xsi:nil
name = SchemaSymbols.XSI_NIL;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_BOOLEAN);
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
XSSimpleType anyURI = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_ANYURI);
// xsi:schemaLocation
name = SchemaSymbols.XSI_SCHEMALOCATION;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.createTypeList("#AnonType_schemaLocation", SchemaSymbols.URI_XSI, (short)0, anyURI, null);
if (type instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl)type).setAnonymous(true);
}
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
// xsi:noNamespaceSchemaLocation
name = SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION;
tns = SchemaSymbols.URI_XSI;
type = anyURI;
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
}
} // <init>(int)
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription.makeClone();
} // getGrammarDescription(): XMLGrammarDescription
// override these methods solely so that these
// objects cannot be modified once they're created.
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl, String location) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
// ignore
}
public void addGlobalElementDeclAll(XSElementDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
// ignore
}
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
// ignore
}
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
// ignore
}
public synchronized void addDocument(Object document, String location) {
// ignore
}
// annotation support
synchronized DOMParser getDOMParser() {
return null;
}
synchronized SAXParser getSAXParser() {
return null;
}
}
/**
* <p>A partial schema for schemas for validating annotations.</p>
*
* @xerces.internal
*
* @author Michael Glavassevich, IBM
*/
public static final class Schema4Annotations extends SchemaGrammar {
/**
* Singleton instance.
*/
public static final Schema4Annotations INSTANCE = new Schema4Annotations();
/**
* Special constructor to create a schema
* capable of validating annotations.
*/
private Schema4Annotations() {
// target namespace
fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA);
// no global decls other than types and
// element declarations for <annotation>, <documentation> and <appinfo>.
fGlobalAttrDecls = new SymbolHash(1);
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(6);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(6);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// all global element declarations
fAllGlobalElemDecls = new SymbolHash(6);
// get all built-in types
fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls;
// create element declarations for <annotation>, <documentation> and <appinfo>
XSElementDecl annotationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_ANNOTATION);
XSElementDecl documentationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_DOCUMENTATION);
XSElementDecl appinfoDecl = createAnnotationElementDecl(SchemaSymbols.ELT_APPINFO);
// add global element declarations
fGlobalElemDecls.put(annotationDecl.fName, annotationDecl);
fGlobalElemDecls.put(documentationDecl.fName, documentationDecl);
fGlobalElemDecls.put(appinfoDecl.fName, appinfoDecl);
fGlobalElemDeclsExt.put(","+annotationDecl.fName, annotationDecl);
fGlobalElemDeclsExt.put(","+documentationDecl.fName, documentationDecl);
fGlobalElemDeclsExt.put(","+appinfoDecl.fName, appinfoDecl);
fAllGlobalElemDecls.put(annotationDecl, annotationDecl);
fAllGlobalElemDecls.put(documentationDecl, documentationDecl);
fAllGlobalElemDecls.put(appinfoDecl, appinfoDecl);
// create complex type declarations for <annotation>, <documentation> and <appinfo>
XSComplexTypeDecl annotationType = new XSComplexTypeDecl();
XSComplexTypeDecl documentationType = new XSComplexTypeDecl();
XSComplexTypeDecl appinfoType = new XSComplexTypeDecl();
// set the types on their element declarations
annotationDecl.fType = annotationType;
documentationDecl.fType = documentationType;
appinfoDecl.fType = appinfoType;
// create attribute groups for <annotation>, <documentation> and <appinfo>
XSAttributeGroupDecl annotationAttrs = new XSAttributeGroupDecl();
XSAttributeGroupDecl documentationAttrs = new XSAttributeGroupDecl();
XSAttributeGroupDecl appinfoAttrs = new XSAttributeGroupDecl();
// fill in attribute groups
{
// create and fill attribute uses for <annotation>, <documentation> and <appinfo>
XSAttributeUseImpl annotationIDAttr = new XSAttributeUseImpl();
annotationIDAttr.fAttrDecl = new XSAttributeDecl();
annotationIDAttr.fAttrDecl.setValues(SchemaSymbols.ATT_ID, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ID),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, annotationType, null);
annotationIDAttr.fUse = SchemaSymbols.USE_OPTIONAL;
annotationIDAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl documentationSourceAttr = new XSAttributeUseImpl();
documentationSourceAttr.fAttrDecl = new XSAttributeDecl();
documentationSourceAttr.fAttrDecl.setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ANYURI),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, documentationType, null);
documentationSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL;
documentationSourceAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl documentationLangAttr = new XSAttributeUseImpl();
documentationLangAttr.fAttrDecl = new XSAttributeDecl();
documentationLangAttr.fAttrDecl.setValues("lang".intern(), NamespaceContext.XML_URI, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_LANGUAGE),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, documentationType, null);
documentationLangAttr.fUse = SchemaSymbols.USE_OPTIONAL;
documentationLangAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl appinfoSourceAttr = new XSAttributeUseImpl();
appinfoSourceAttr.fAttrDecl = new XSAttributeDecl();
appinfoSourceAttr.fAttrDecl.setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ANYURI),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, appinfoType, null);
appinfoSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL;
appinfoSourceAttr.fConstraintType = XSConstants.VC_NONE;
// create lax attribute wildcard for <annotation>, <documentation> and <appinfo>
XSWildcardDecl otherAttrs = new XSWildcardDecl();
otherAttrs.fNamespaceList = new String [] {fTargetNamespace, null};
otherAttrs.fType = XSWildcard.NSCONSTRAINT_NOT;
otherAttrs.fProcessContents = XSWildcard.PC_LAX;
// add attribute uses and wildcards to attribute groups for <annotation>, <documentation> and <appinfo>
annotationAttrs.addAttributeUse(annotationIDAttr);
annotationAttrs.fAttributeWC = otherAttrs;
documentationAttrs.addAttributeUse(documentationSourceAttr);
documentationAttrs.addAttributeUse(documentationLangAttr);
documentationAttrs.fAttributeWC = otherAttrs;
appinfoAttrs.addAttributeUse(appinfoSourceAttr);
appinfoAttrs.fAttributeWC = otherAttrs;
}
// create particles for <annotation>
XSParticleDecl annotationParticle = createUnboundedModelGroupParticle();
{
XSModelGroupImpl annotationChoice = new XSModelGroupImpl();
annotationChoice.fCompositor = XSModelGroupImpl.MODELGROUP_CHOICE;
annotationChoice.fParticleCount = 2;
annotationChoice.fParticles = new XSParticleDecl[2];
annotationChoice.fParticles[0] = createChoiceElementParticle(appinfoDecl);
annotationChoice.fParticles[1] = createChoiceElementParticle(documentationDecl);
annotationParticle.fValue = annotationChoice;
}
// create wildcard particle for <documentation> and <appinfo>
XSParticleDecl anyWCSequenceParticle = createUnboundedAnyWildcardSequenceParticle();
// fill complex types
annotationType.setValues("#AnonType_" + SchemaSymbols.ELT_ANNOTATION, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_ELEMENT, false, annotationAttrs, null, annotationParticle, XSObjectListImpl.EMPTY_LIST);
annotationType.setName("#AnonType_" + SchemaSymbols.ELT_ANNOTATION);
annotationType.setIsAnonymous();
documentationType.setValues("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_MIXED, false, documentationAttrs, null, anyWCSequenceParticle, XSObjectListImpl.EMPTY_LIST);
documentationType.setName("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION);
documentationType.setIsAnonymous();
appinfoType.setValues("#AnonType_" + SchemaSymbols.ELT_APPINFO, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_MIXED, false, appinfoAttrs, null, anyWCSequenceParticle, XSObjectListImpl.EMPTY_LIST);
appinfoType.setName("#AnonType_" + SchemaSymbols.ELT_APPINFO);
appinfoType.setIsAnonymous();
} // <init>(int)
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription.makeClone();
} // getGrammarDescription(): XMLGrammarDescription
// override these methods solely so that these
// objects cannot be modified once they're created.
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
// ignore
}
public void addGlobalElementDeclAll(XSElementDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
// ignore
}
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
// ignore
}
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
// ignore
}
public synchronized void addDocument(Object document, String location) {
// ignore
}
// annotation support
synchronized DOMParser getDOMParser() {
return null;
}
synchronized SAXParser getSAXParser() {
return null;
}
//
// private helper methods
//
private XSElementDecl createAnnotationElementDecl(String localName) {
XSElementDecl eDecl = new XSElementDecl();
eDecl.fName = localName;
eDecl.fTargetNamespace = fTargetNamespace;
eDecl.setIsGlobal();
eDecl.fBlock = (XSConstants.DERIVATION_EXTENSION |
XSConstants.DERIVATION_RESTRICTION | XSConstants.DERIVATION_SUBSTITUTION);
eDecl.setConstraintType(XSConstants.VC_NONE);
return eDecl;
}
private XSParticleDecl createUnboundedModelGroupParticle() {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 0;
particle.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED;
particle.fType = XSParticleDecl.PARTICLE_MODELGROUP;
return particle;
}
private XSParticleDecl createChoiceElementParticle(XSElementDecl ref) {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 1;
particle.fMaxOccurs = 1;
particle.fType = XSParticleDecl.PARTICLE_ELEMENT;
particle.fValue = ref;
return particle;
}
private XSParticleDecl createUnboundedAnyWildcardSequenceParticle() {
XSParticleDecl particle = createUnboundedModelGroupParticle();
XSModelGroupImpl sequence = new XSModelGroupImpl();
sequence.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE;
sequence.fParticleCount = 1;
sequence.fParticles = new XSParticleDecl[1];
sequence.fParticles[0] = createAnyLaxWildcardParticle();
particle.fValue = sequence;
return particle;
}
private XSParticleDecl createAnyLaxWildcardParticle() {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 1;
particle.fMaxOccurs = 1;
particle.fType = XSParticleDecl.PARTICLE_WILDCARD;
XSWildcardDecl anyWC = new XSWildcardDecl();
anyWC.fNamespaceList = null;
anyWC.fType = XSWildcard.NSCONSTRAINT_ANY;
anyWC.fProcessContents = XSWildcard.PC_LAX;
particle.fValue = anyWC;
return particle;
}
}
// Grammar methods
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription;
} // getGrammarDescription(): XMLGrammarDescription
// DTDGrammar methods
public boolean isNamespaceAware () {
return true;
} // isNamespaceAware():boolean
List<SchemaGrammar> fImported = null;
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
fImported = importedGrammars;
}
public List<SchemaGrammar> getImportedGrammars() {
return fImported;
}
/**
* Returns this grammar's target namespace.
*/
public final String getTargetNamespace() {
return fTargetNamespace;
} // getTargetNamespace():String
/**
* register one global attribute
*/
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
fGlobalAttrDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalAttributeDecl(XSAttributeDecl decl, String location) {
fGlobalAttrDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global attribute group
*/
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
fGlobalAttrGrpDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
fGlobalAttrGrpDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global element
*/
public void addGlobalElementDeclAll(XSElementDecl decl) {
if (fAllGlobalElemDecls.get(decl) == null) {
fAllGlobalElemDecls.put(decl, decl);
// if there is a substitution group affiliation, store in an array,
// for further constraint checking: UPA, PD, EDC
if (decl.fSubGroup != null) {
if (fSubGroupCount == fSubGroups.length)
fSubGroups = resize(fSubGroups, fSubGroupCount+INC_SIZE);
fSubGroups[fSubGroupCount++] = decl;
}
}
}
public void addGlobalElementDecl(XSElementDecl decl) {
fGlobalElemDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
fGlobalElemDeclsExt.put(((location != null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global group
*/
public void addGlobalGroupDecl(XSGroupDecl decl) {
fGlobalGroupDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
fGlobalGroupDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global notation
*/
public void addGlobalNotationDecl(XSNotationDecl decl) {
fGlobalNotationDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
fGlobalNotationDeclsExt.put(((location!=null) ? location : "") + "," +decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global type
*/
public void addGlobalTypeDecl(XSTypeDefinition decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
if (decl instanceof XSComplexTypeDecl) {
((XSComplexTypeDecl) decl).setNamespaceItem(this);
}
else if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
fGlobalTypeDeclsExt.put(((location!=null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null) {
if (decl instanceof XSComplexTypeDecl) {
((XSComplexTypeDecl) decl).setNamespaceItem(this);
}
else if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
}
/**
* register one global complex type
*/
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
decl.setNamespaceItem(this);
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
fGlobalTypeDeclsExt.put(((location!=null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global simple type
*/
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
fGlobalTypeDeclsExt.put(((location != null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null && decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
/**
* register one identity constraint
*/
public final void addIDConstraintDecl(XSElementDecl elmDecl, IdentityConstraint decl) {
elmDecl.addIDConstraint(decl);
fGlobalIDConstraintDecls.put(decl.getIdentityConstraintName(), decl);
}
public final void addIDConstraintDecl(XSElementDecl elmDecl, IdentityConstraint decl, String location) {
fGlobalIDConstraintDeclsExt.put(((location != null) ? location : "") + "," + decl.getIdentityConstraintName(), decl);
}
/**
* get one global attribute
*/
public final XSAttributeDecl getGlobalAttributeDecl(String declName) {
return(XSAttributeDecl)fGlobalAttrDecls.get(declName);
}
public final XSAttributeDecl getGlobalAttributeDecl(String declName, String location) {
return(XSAttributeDecl)fGlobalAttrDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global attribute group
*/
public final XSAttributeGroupDecl getGlobalAttributeGroupDecl(String declName) {
return(XSAttributeGroupDecl)fGlobalAttrGrpDecls.get(declName);
}
public final XSAttributeGroupDecl getGlobalAttributeGroupDecl(String declName, String location) {
return(XSAttributeGroupDecl)fGlobalAttrGrpDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global element
*/
public final XSElementDecl getGlobalElementDecl(String declName) {
return(XSElementDecl)fGlobalElemDecls.get(declName);
}
public final XSElementDecl getGlobalElementDecl(String declName, String location) {
return(XSElementDecl)fGlobalElemDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global group
*/
public final XSGroupDecl getGlobalGroupDecl(String declName) {
return(XSGroupDecl)fGlobalGroupDecls.get(declName);
}
public final XSGroupDecl getGlobalGroupDecl(String declName, String location) {
return(XSGroupDecl)fGlobalGroupDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global notation
*/
public final XSNotationDecl getGlobalNotationDecl(String declName) {
return(XSNotationDecl)fGlobalNotationDecls.get(declName);
}
public final XSNotationDecl getGlobalNotationDecl(String declName, String location) {
return(XSNotationDecl)fGlobalNotationDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global type
*/
public final XSTypeDefinition getGlobalTypeDecl(String declName) {
return(XSTypeDefinition)fGlobalTypeDecls.get(declName);
}
public final XSTypeDefinition getGlobalTypeDecl(String declName, String location) {
return(XSTypeDefinition)fGlobalTypeDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one identity constraint
*/
public final IdentityConstraint getIDConstraintDecl(String declName) {
return(IdentityConstraint)fGlobalIDConstraintDecls.get(declName);
}
public final IdentityConstraint getIDConstraintDecl(String declName, String location) {
return(IdentityConstraint)fGlobalIDConstraintDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one identity constraint
*/
public final boolean hasIDConstraints() {
return fGlobalIDConstraintDecls.getLength() > 0;
}
// array to store complex type decls
private static final int INITIAL_SIZE = 16;
private static final int INC_SIZE = 16;
private int fCTCount = 0;
private XSComplexTypeDecl[] fComplexTypeDecls = new XSComplexTypeDecl[INITIAL_SIZE];
private SimpleLocator[] fCTLocators = new SimpleLocator[INITIAL_SIZE];
// an array to store groups being redefined by restriction
// even-numbered elements are the derived groups, odd-numbered ones their bases
private static final int REDEFINED_GROUP_INIT_SIZE = 2;
private int fRGCount = 0;
private XSGroupDecl[] fRedefinedGroupDecls = new XSGroupDecl[REDEFINED_GROUP_INIT_SIZE];
private SimpleLocator[] fRGLocators = new SimpleLocator[REDEFINED_GROUP_INIT_SIZE/2];
// a flag to indicate whether we have checked the 3 constraints on this
// grammar.
boolean fFullChecked = false;
/**
* add one complex type decl: for later constraint checking
*/
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
if (fCTCount == fComplexTypeDecls.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount+INC_SIZE);
fCTLocators = resize(fCTLocators, fCTCount+INC_SIZE);
}
fCTLocators[fCTCount] = locator;
fComplexTypeDecls[fCTCount++] = decl;
}
/**
* add a group redefined by restriction: for later constraint checking
*/
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
if (fRGCount == fRedefinedGroupDecls.length) {
// double array size each time.
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount << 1);
fRGLocators = resize(fRGLocators, fRGCount);
}
fRGLocators[fRGCount/2] = locator;
fRedefinedGroupDecls[fRGCount++] = derived;
fRedefinedGroupDecls[fRGCount++] = base;
}
/**
* get all complex type decls: for later constraint checking
*/
final XSComplexTypeDecl[] getUncheckedComplexTypeDecls() {
if (fCTCount < fComplexTypeDecls.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
return fComplexTypeDecls;
}
/**
* get the error locator of all complex type decls
*/
final SimpleLocator[] getUncheckedCTLocators() {
if (fCTCount < fCTLocators.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
return fCTLocators;
}
/**
* get all redefined groups: for later constraint checking
*/
final XSGroupDecl[] getRedefinedGroupDecls() {
if (fRGCount < fRedefinedGroupDecls.length) {
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount);
fRGLocators = resize(fRGLocators, fRGCount/2);
}
return fRedefinedGroupDecls;
}
/**
* get the error locator of all redefined groups
*/
final SimpleLocator[] getRGLocators() {
if (fRGCount < fRedefinedGroupDecls.length) {
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount);
fRGLocators = resize(fRGLocators, fRGCount/2);
}
return fRGLocators;
}
/**
* after the first-round checking, some types don't need to be checked
* against UPA again. here we trim the array to the proper size.
*/
final void setUncheckedTypeNum(int newSize) {
fCTCount = newSize;
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
// used to store all substitution group information declared in
// this namespace
private int fSubGroupCount = 0;
private XSElementDecl[] fSubGroups = new XSElementDecl[INITIAL_SIZE];
/**
* get all substitution group information: for the 3 constraint checking
*/
final XSElementDecl[] getSubstitutionGroups() {
if (fSubGroupCount < fSubGroups.length)
fSubGroups = resize(fSubGroups, fSubGroupCount);
return fSubGroups;
}
// anyType and anySimpleType: because there are so many places where
// we need direct access to these two types
public final static XSComplexTypeDecl fAnyType = new XSAnyType();
private static class XSAnyType extends XSComplexTypeDecl {
public XSAnyType () {
fName = SchemaSymbols.ATTVAL_ANYTYPE;
super.fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
fBaseType = this;
fDerivedBy = XSConstants.DERIVATION_RESTRICTION;
fContentType = XSComplexTypeDecl.CONTENTTYPE_MIXED;
fParticle = createParticle();
fAttrGrp = createAttrGrp();
}
// overridden methods
public void setValues(String name, String targetNamespace,
XSTypeDefinition baseType, short derivedBy, short schemaFinal,
short block, short contentType,
boolean isAbstract, XSAttributeGroupDecl attrGrp,
XSSimpleType simpleType, XSParticleDecl particle) {
// don't allow this.
}
public void setName(String name){
// don't allow this.
}
public void setIsAbstractType() {
// null implementation
}
public void setContainsTypeID() {
// null implementation
}
public void setIsAnonymous() {
// null implementation
}
public void reset() {
// null implementation
}
public XSObjectList getAnnotations() {
return XSObjectListImpl.EMPTY_LIST;
}
public XSNamespaceItem getNamespaceItem() {
return SG_SchemaNS;
}
private XSAttributeGroupDecl createAttrGrp() {
XSWildcardDecl wildcard = new XSWildcardDecl();
wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
XSAttributeGroupDecl attrGrp = new XSAttributeGroupDecl();
attrGrp.fAttributeWC = wildcard;
return attrGrp;
}
private XSParticleDecl createParticle() {
// the wildcard used in anyType (content and attribute)
// the spec will change strict to skip for anyType
XSWildcardDecl wildcard = new XSWildcardDecl();
wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
// the particle for the content wildcard
XSParticleDecl particleW = new XSParticleDecl();
particleW.fMinOccurs = 0;
particleW.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED;
particleW.fType = XSParticleDecl.PARTICLE_WILDCARD;
particleW.fValue = wildcard;
// the model group of a sequence of the above particle
XSModelGroupImpl group = new XSModelGroupImpl();
group.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE;
group.fParticleCount = 1;
group.fParticles = new XSParticleDecl[1];
group.fParticles[0] = particleW;
// the content of anyType: particle of the above model group
XSParticleDecl particleG = new XSParticleDecl();
particleG.fType = XSParticleDecl.PARTICLE_MODELGROUP;
particleG.fValue = group;
return particleG;
}
}
private static class BuiltinAttrDecl extends XSAttributeDecl {
public BuiltinAttrDecl(String name, String tns,
XSSimpleType type, short scope) {
fName = name;
super.fTargetNamespace = tns;
fType = type;
fScope = scope;
}
public void setValues(String name, String targetNamespace,
XSSimpleType simpleType, short constraintType, short scope,
ValidatedInfo valInfo, XSComplexTypeDecl enclosingCT) {
// ignore this call.
}
public void reset () {
// also ignore this call.
}
public XSAnnotation getAnnotation() {
return null;
}
public XSNamespaceItem getNamespaceItem() {
return SG_XSI;
}
} // class BuiltinAttrDecl
// the grammars to hold components of the schema namespace
public final static BuiltinSchemaGrammar SG_SchemaNS = new BuiltinSchemaGrammar(GRAMMAR_XS, Constants.SCHEMA_VERSION_1_0);
private final static BuiltinSchemaGrammar SG_SchemaNSExtended = new BuiltinSchemaGrammar(GRAMMAR_XS, Constants.SCHEMA_VERSION_1_0_EXTENDED);
public final static XSSimpleType fAnySimpleType = (XSSimpleType)SG_SchemaNS.getGlobalTypeDecl(SchemaSymbols.ATTVAL_ANYSIMPLETYPE);
// the grammars to hold components of the schema-instance namespace
public final static BuiltinSchemaGrammar SG_XSI = new BuiltinSchemaGrammar(GRAMMAR_XSI, Constants.SCHEMA_VERSION_1_0);
public static SchemaGrammar getS4SGrammar(short schemaVersion) {
if (schemaVersion == Constants.SCHEMA_VERSION_1_0) {
return SG_SchemaNS;
}
else {
return SG_SchemaNSExtended;
}
}
static final XSComplexTypeDecl[] resize(XSComplexTypeDecl[] oldArray, int newSize) {
XSComplexTypeDecl[] newArray = new XSComplexTypeDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final XSGroupDecl[] resize(XSGroupDecl[] oldArray, int newSize) {
XSGroupDecl[] newArray = new XSGroupDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final XSElementDecl[] resize(XSElementDecl[] oldArray, int newSize) {
XSElementDecl[] newArray = new XSElementDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final SimpleLocator[] resize(SimpleLocator[] oldArray, int newSize) {
SimpleLocator[] newArray = new SimpleLocator[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
// XSNamespaceItem methods
// the max index / the max value of XSObject type
private static final short MAX_COMP_IDX = XSTypeDefinition.SIMPLE_TYPE;
private static final boolean[] GLOBAL_COMP = {false, // null
true, // attribute
true, // element
true, // type
false, // attribute use
true, // attribute group
true, // group
false, // model group
false, // particle
false, // wildcard
true, // idc
true, // notation
false, // annotation
false, // facet
false, // multi value facet
true, // complex type
true // simple type
};
// store a certain kind of components from all namespaces
private XSNamedMap[] fComponents = null;
private ObjectList[] fComponentsExt = null;
// store the documents and their locations contributing to this namespace
// REVISIT: use StringList and XSObjectList for there fields.
// [MASK] is never used
private List<Object> [MASK] = null;
private List<String> fLocations = null;
public synchronized void addDocument(Object document, String location) {
if ( [MASK] == null) {
// Parsing schema is not thread safe, synchronized may be removed
[MASK] = new CopyOnWriteArrayList<>();
fLocations = new CopyOnWriteArrayList<>();
}
[MASK] .add(document);
fLocations.add(location);
}
public synchronized void removeDocument(int index) {
if ( [MASK] != null &&
index >= 0 &&
index < [MASK] .size()) {
[MASK] .remove(index);
fLocations.remove(index);
}
}
/**
* [schema namespace]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#nsi-schema_namespace">[schema namespace]</a>
* @return The target namespace of this item.
*/
public String getSchemaNamespace() {
return fTargetNamespace;
}
// annotation support
synchronized DOMParser getDOMParser() {
if (fDOMParser != null) {
DOMParser parser = fDOMParser.get();
if (parser != null) {
return parser;
}
}
// REVISIT: when schema handles XML 1.1, will need to
// revisit this (and the practice of not prepending an XML decl to the annotation string
XML11Configuration config = new XML11Configuration(fSymbolTable);
// note that this should never produce errors or require
// entity resolution, so just a barebones configuration with
// a couple of feature set will do fine
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true);
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false);
DOMParser parser = new DOMParser(config);
try {
parser.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.DEFER_NODE_EXPANSION_FEATURE, false);
}
catch (SAXException exc) {}
fDOMParser = new SoftReference<DOMParser>(parser);
return parser;
}
synchronized SAXParser getSAXParser() {
if (fSAXParser != null) {
SAXParser parser = fSAXParser.get();
if (parser != null) {
return parser;
}
}
// REVISIT: when schema handles XML 1.1, will need to
// revisit this (and the practice of not prepending an XML decl to the annotation string
XML11Configuration config = new XML11Configuration(fSymbolTable);
// note that this should never produce errors or require
// entity resolution, so just a barebones configuration with
// a couple of feature set will do fine
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true);
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false);
SAXParser parser = new SAXParser(config);
fSAXParser = new SoftReference<SAXParser>(parser);
return parser;
}
/**
* [schema components]: a list of top-level components, i.e. element
* declarations, attribute declarations, etc.
* @param objectType The type of the declaration, i.e.
* <code>ELEMENT_DECLARATION</code>. Note that
* <code>XSTypeDefinition.SIMPLE_TYPE</code> and
* <code>XSTypeDefinition.COMPLEX_TYPE</code> can also be used as the
* <code>objectType</code> to retrieve only complex types or simple
* types, instead of all types.
* @return A list of top-level definition of the specified type in
* <code>objectType</code> or an empty <code>XSNamedMap</code> if no
* such definitions exist.
*/
public synchronized XSNamedMap getComponents(short objectType) {
if (objectType <= 0 || objectType > MAX_COMP_IDX ||
!GLOBAL_COMP[objectType]) {
return XSNamedMapImpl.EMPTY_MAP;
}
if (fComponents == null)
fComponents = new XSNamedMap[MAX_COMP_IDX+1];
// get the hashtable for this type of components
if (fComponents[objectType] == null) {
SymbolHash table = null;
switch (objectType) {
case XSConstants.TYPE_DEFINITION:
case XSTypeDefinition.COMPLEX_TYPE:
case XSTypeDefinition.SIMPLE_TYPE:
table = fGlobalTypeDecls;
break;
case XSConstants.ATTRIBUTE_DECLARATION:
table = fGlobalAttrDecls;
break;
case XSConstants.ELEMENT_DECLARATION:
table = fGlobalElemDecls;
break;
case XSConstants.ATTRIBUTE_GROUP:
table = fGlobalAttrGrpDecls;
break;
case XSConstants.MODEL_GROUP_DEFINITION:
table = fGlobalGroupDecls;
break;
case XSConstants.NOTATION_DECLARATION:
table = fGlobalNotationDecls;
break;
case XSConstants.IDENTITY_CONSTRAINT:
table = this.fGlobalIDConstraintDecls;
break;
}
// for complex/simple types, create a special implementation,
// which take specific types out of the hash table
if (objectType == XSTypeDefinition.COMPLEX_TYPE ||
objectType == XSTypeDefinition.SIMPLE_TYPE) {
fComponents[objectType] = new XSNamedMap4Types(fTargetNamespace, table, objectType);
}
else {
fComponents[objectType] = new XSNamedMapImpl(fTargetNamespace, table);
}
}
return fComponents[objectType];
}
public synchronized ObjectList getComponentsExt(short objectType) {
if (objectType <= 0 || objectType > MAX_COMP_IDX ||
!GLOBAL_COMP[objectType]) {
return ObjectListImpl.EMPTY_LIST;
}
if (fComponentsExt == null)
fComponentsExt = new ObjectList[MAX_COMP_IDX+1];
// get the hashtable for this type of components
if (fComponentsExt[objectType] == null) {
SymbolHash table = null;
switch (objectType) {
case XSConstants.TYPE_DEFINITION:
case XSTypeDefinition.COMPLEX_TYPE:
case XSTypeDefinition.SIMPLE_TYPE:
table = fGlobalTypeDeclsExt;
break;
case XSConstants.ATTRIBUTE_DECLARATION:
table = fGlobalAttrDeclsExt;
break;
case XSConstants.ELEMENT_DECLARATION:
table = fGlobalElemDeclsExt;
break;
case XSConstants.ATTRIBUTE_GROUP:
table = fGlobalAttrGrpDeclsExt;
break;
case XSConstants.MODEL_GROUP_DEFINITION:
table = fGlobalGroupDeclsExt;
break;
case XSConstants.NOTATION_DECLARATION:
table = fGlobalNotationDeclsExt;
break;
case XSConstants.IDENTITY_CONSTRAINT:
table = this.fGlobalIDConstraintDeclsExt;
break;
}
Object[] entries = table.getEntries();
fComponentsExt[objectType] = new ObjectListImpl(entries, entries.length);
}
return fComponentsExt[objectType];
}
public synchronized void resetComponents() {
fComponents = null;
fComponentsExt = null;
}
/**
* Convenience method. Returns a top-level simple or complex type
* definition.
* @param name The name of the definition.
* @return An <code>XSTypeDefinition</code> or null if such definition
* does not exist.
*/
public XSTypeDefinition getTypeDefinition(String name) {
return getGlobalTypeDecl(name);
}
/**
* Convenience method. Returns a top-level attribute declaration.
* @param name The name of the declaration.
* @return A top-level attribute declaration or null if such declaration
* does not exist.
*/
public XSAttributeDeclaration getAttributeDeclaration(String name) {
return getGlobalAttributeDecl(name);
}
/**
* Convenience method. Returns a top-level element declaration.
* @param name The name of the declaration.
* @return A top-level element declaration or null if such declaration
* does not exist.
*/
public XSElementDeclaration getElementDeclaration(String name) {
return getGlobalElementDecl(name);
}
/**
* Convenience method. Returns a top-level attribute group definition.
* @param name The name of the definition.
* @return A top-level attribute group definition or null if such
* definition does not exist.
*/
public XSAttributeGroupDefinition getAttributeGroup(String name) {
return getGlobalAttributeGroupDecl(name);
}
/**
* Convenience method. Returns a top-level model group definition.
*
* @param name The name of the definition.
* @return A top-level model group definition definition or null if such
* definition does not exist.
*/
public XSModelGroupDefinition getModelGroupDefinition(String name) {
return getGlobalGroupDecl(name);
}
/**
* Convenience method. Returns a top-level notation declaration.
*
* @param name The name of the declaration.
* @return A top-level notation declaration or null if such declaration
* does not exist.
*/
public XSNotationDeclaration getNotationDeclaration(String name) {
return getGlobalNotationDecl(name);
}
public XSIDCDefinition getIDCDefinition(String name) {
return getIDConstraintDecl(name);
}
/**
* [document location]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#sd-document_location">[document location]</a>
* @return a list of document information item
*/
public StringList getDocumentLocations() {
return new StringListImpl(fLocations);
}
/**
* Return an <code>XSModel</code> that represents components in this schema
* grammar.
*
* @return an <code>XSModel</code> representing this schema grammar
*/
public XSModel toXSModel() {
return new XSModelImpl(new SchemaGrammar[]{this});
}
public XSModel toXSModel(XSGrammar[] grammars) {
if (grammars == null || grammars.length == 0)
return toXSModel();
int len = grammars.length;
boolean hasSelf = false;
for (int i = 0; i < len; i++) {
if (grammars[i] == this) {
hasSelf = true;
break;
}
}
SchemaGrammar[] gs = new SchemaGrammar[hasSelf ? len : len+1];
for (int i = 0; i < len; i++)
gs[i] = (SchemaGrammar)grammars[i];
if (!hasSelf)
gs[len] = this;
return new XSModelImpl(gs);
}
/**
* @see org.apache.xerces.xs.XSNamespaceItem#getAnnotations()
*/
public XSObjectList getAnnotations() {
if (fNumAnnotations == 0) {
return XSObjectListImpl.EMPTY_LIST;
}
return new XSObjectListImpl(fAnnotations, fNumAnnotations);
}
public void addAnnotation(XSAnnotationImpl annotation) {
if (annotation == null) {
return;
}
if (fAnnotations == null) {
fAnnotations = new XSAnnotationImpl[2];
}
else if (fNumAnnotations == fAnnotations.length) {
XSAnnotationImpl[] newArray = new XSAnnotationImpl[fNumAnnotations << 1];
System.arraycopy(fAnnotations, 0, newArray, 0, fNumAnnotations);
fAnnotations = newArray;
}
fAnnotations[fNumAnnotations++] = annotation;
}
public void setImmutable(boolean isImmutable) {
fIsImmutable = isImmutable;
}
public boolean isImmutable() {
return fIsImmutable;
}
} // class SchemaGrammar
| fDocuments |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, [MASK] ());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), [MASK] (), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int [MASK] () {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| getDirMode |
/*
* Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www. [MASK] .com if you need additional information or have any
* questions.
*/
package com. [MASK] .svm.hosted;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.stream.Collectors;
import org.graalvm.nativeimage.hosted.RuntimeReflection;
import org.graalvm.nativeimage.hosted.RuntimeResourceAccess;
import com. [MASK] .svm.core.feature.AutomaticallyRegisteredFeature;
import com. [MASK] .svm.core.feature.InternalFeature;
import com. [MASK] .svm.core.jdk.ServiceCatalogSupport;
import com. [MASK] .svm.core.option.AccumulatingLocatableMultiOptionValue;
import com. [MASK] .svm.core.option.HostedOptionKey;
import com. [MASK] .svm.hosted.analysis.Inflation;
import jdk.graal.compiler.options.Option;
import jdk.graal.compiler.options.OptionType;
/**
* Support for {@link ServiceLoader} on Substrate VM.
*
* Services are registered in the folder {@code "META-INF/services/"} using files whose name is the
* fully qualified service interface name. We do not know which services are going to be used by a
* native image: The parameter of {@code ServiceLoader#load} is often but not always a compile-time
* constant that we can track. But we also cannot put all registered services into the native image.
*
* We therefore use the following heuristic: We add all service loader files and service
* implementation classes when the service interfaces that are seen as reachable by the static
* analysis.
*
* Each used service implementation class is added for reflection (using
* {@link org.graalvm.nativeimage.hosted.RuntimeReflection#register(Class[])}) and for reflective
* instantiation (using {@link RuntimeReflection#registerForReflectiveInstantiation(Class[])}).
*
* For each service interface, a single service loader file is added as a resource to the image. The
* single file combines all the individual files that can come from different .jar files.
*/
@AutomaticallyRegisteredFeature
public class ServiceLoaderFeature implements InternalFeature {
public static class Options {
@Option(help = "Automatically register services for run-time lookup using ServiceLoader", type = OptionType.Expert) //
public static final HostedOptionKey<Boolean> UseServiceLoaderFeature = new HostedOptionKey<>(true);
@Option(help = "Comma-separated list of services that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServices = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
@Option(help = "Comma-separated list of service providers that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServiceProviders = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
}
private static final Set<String> SKIPPED_SERVICES = Set.of(
// image builder internal ServiceLoader interfaces
"com. [MASK] .svm.hosted.NativeImageClassLoaderPostProcessing",
"org.graalvm.nativeimage.Platform",
/*
* Loaded in java.util.random.RandomGeneratorFactory.FactoryMapHolder, which is
* initialized at image build time.
*/
"java.util.random.RandomGenerator",
"java.security.Provider", // see SecurityServicesFeature
"sun.util.locale.provider.LocaleDataMetaInfo", // see LocaleSubstitutions
/* Graal hotspot-specific services */
"jdk.vm.ci.hotspot.HotSpotJVMCIBackendFactory",
"jdk.graal.compiler.hotspot.CompilerConfigurationFactory",
"jdk.graal.compiler.hotspot.HotSpotBackendFactory",
"jdk.graal.compiler.hotspot.meta.DefaultHotSpotLoweringProvider$Extensions",
"jdk.graal.compiler.hotspot.meta.HotSpotInvocationPluginProvider",
"jdk.graal.compiler.truffle.hotspot.TruffleCallBoundaryInstrumentationFactory");
// NOTE: Platform class had to be added to this list since our analysis discovers that
// Platform.includedIn is reachable regardless of fact that it is constant folded at
// registerPlatformPlugins method of SubstrateGraphBuilderPlugins. This issue hasn't manifested
// before because implementation classes were instantiated using runtime reflection instead of
// ServiceLoader (and thus weren't reachable in analysis).
/**
* Services that should not be processed here, for example because they are handled by
* specialized features.
*/
private final Set<String> servicesToSkip = new HashSet<>(SKIPPED_SERVICES);
private static final Set<String> SKIPPED_PROVIDERS = Set.of(
/* Graal hotspot-specific service-providers */
"jdk.graal.compiler.hotspot.meta.HotSpotDisassemblerProvider",
/* Skip console providers until GR-44085 is fixed */
"jdk.internal.org.jline.JdkConsoleProviderImpl", "jdk.jshell.execution.impl.ConsoleImpl$ConsoleProviderImpl");
private final Set<String> serviceProvidersToSkip = new HashSet<>(SKIPPED_PROVIDERS);
@Override
public boolean isInConfiguration(IsInConfigurationAccess access) {
return Options.UseServiceLoaderFeature.getValue();
}
@Override
public void afterRegistration(AfterRegistrationAccess access) {
servicesToSkip.addAll(Options.ServiceLoaderFeatureExcludeServices.getValue().values());
serviceProvidersToSkip.addAll(Options.ServiceLoaderFeatureExcludeServiceProviders.getValue().values());
}
@Override
public void beforeAnalysis(BeforeAnalysisAccess access) {
FeatureImpl.BeforeAnalysisAccessImpl accessImpl = (FeatureImpl.BeforeAnalysisAccessImpl) access;
accessImpl.imageClassLoader.classLoaderSupport.serviceProvidersForEach((serviceName, providers) -> {
Class<?> serviceClass = access.findClassByName(serviceName);
boolean skipService = false;
/* If the service should not end up in the image, we remove all the providers with it */
Collection<String> providersToSkip = providers;
if (servicesToSkip.contains(serviceName)) {
skipService = true;
} else if (serviceClass == null || serviceClass.isArray() || serviceClass.isPrimitive()) {
skipService = true;
} else if (!accessImpl.getHostVM().platformSupported(serviceClass)) {
skipService = true;
} else {
providersToSkip = providers.stream().filter(serviceProvidersToSkip::contains).collect(Collectors.toList());
if (!providersToSkip.isEmpty()) {
skipService = true;
}
}
if (skipService) {
ServiceCatalogSupport.singleton().removeServicesFromServicesCatalog(serviceName, new HashSet<>(providersToSkip));
return;
}
access.registerReachabilityHandler(a -> handleServiceClassIsReachable(a, serviceClass, providers), serviceClass);
});
}
void handleServiceClassIsReachable(DuringAnalysisAccess access, Class<?> serviceProvider, Collection<String> providers) {
LinkedHashSet<String> registeredProviders = new LinkedHashSet<>();
for (String provider : providers) {
if (serviceProvidersToSkip.contains(provider)) {
continue;
}
/* Make provider reflectively instantiable */
Class<?> providerClass = access.findClassByName(provider);
if (providerClass == null || providerClass.isArray() || providerClass.isPrimitive()) {
continue;
}
FeatureImpl.DuringAnalysisAccessImpl accessImpl = (FeatureImpl.DuringAnalysisAccessImpl) access;
if (!accessImpl.getHostVM().platformSupported(providerClass)) {
continue;
}
if (((Inflation) accessImpl.getBigBang()).getAnnotationSubstitutionProcessor().isDeleted(providerClass)) {
/* Disallow services with implementation classes that are marked as @Deleted */
continue;
}
/*
* Find either a public static provider() method or a nullary constructor (or both).
* Skip providers that do not comply with requirements.
*
* See ServiceLoader#loadProvider and ServiceLoader#findStaticProviderMethod.
*/
Constructor<?> nullaryConstructor = null;
Method nullaryProviderMethod = null;
try {
/* Only look for a provider() method if provider class is in an explicit module. */
if (providerClass.getModule().isNamed() && !providerClass.getModule().getDescriptor().isAutomatic()) {
for (Method method : providerClass.getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers()) &&
method.getParameterCount() == 0 && method.getName().equals("provider")) {
if (nullaryProviderMethod == null) {
nullaryProviderMethod = method;
} else {
/* There must be at most one public static provider() method. */
nullaryProviderMethod = null;
break;
}
}
}
}
Constructor<?> constructor = providerClass.getDeclaredConstructor();
if (Modifier.isPublic(constructor.getModifiers())) {
nullaryConstructor = constructor;
}
} catch (NoSuchMethodException | SecurityException | LinkageError e) {
// ignore
}
if (nullaryConstructor != null || nullaryProviderMethod != null) {
RuntimeReflection.register(providerClass);
if (nullaryConstructor != null) {
/*
* Registering a constructor with
* RuntimeReflection.registerConstructorLookup(providerClass) does not produce
* the same behavior as using RuntimeReflection.register(nullaryConstructor). In
* the first case, the constructor is marked for query purposes only, so this
* if-statement cannot be eliminated.
*
*/
RuntimeReflection.register(nullaryConstructor);
} else {
/*
* If there's no nullary constructor, register it as negative lookup to avoid
* throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerConstructorLookup(providerClass);
}
if (nullaryProviderMethod != null) {
RuntimeReflection.register(nullaryProviderMethod);
} else {
/*
* If there's no declared public provider() method, register it as negative
* lookup to avoid throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerMethodLookup(providerClass, "provider");
}
}
/*
* Register the provider in both cases: when it is JCA-compliant (has a nullary
* constructor or a provider method) or when it lacks both. If neither is present, a
* ServiceConfigurationError will be thrown at runtime, consistent with HotSpot
* behavior.
*/
registeredProviders.add(provider);
}
if (!registeredProviders.isEmpty()) {
String serviceResourceLocation = "META-INF/services/" + serviceProvider.getName();
byte[] serviceFileData = registeredProviders.stream().collect(Collectors.joining("\n")).getBytes(StandardCharsets.UTF_8);
RuntimeResourceAccess.addResource(access.getApplicationClassLoader().getUnnamedModule(), serviceResourceLocation, serviceFileData);
}
}
}
| oracle |
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
*/
/*
* 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 com.sun.org.apache.xerces. [MASK] .impl.xs;
import com.sun.org.apache.xerces. [MASK] .impl.Constants;
import com.sun.org.apache.xerces. [MASK] .impl.dv.SchemaDVFactory;
import com.sun.org.apache.xerces. [MASK] .impl.dv.ValidatedInfo;
import com.sun.org.apache.xerces. [MASK] .impl.dv.XSSimpleType;
import com.sun.org.apache.xerces. [MASK] .impl.dv.xs.XSSimpleTypeDecl;
import com.sun.org.apache.xerces. [MASK] .impl.xs.identity.IdentityConstraint;
import com.sun.org.apache.xerces. [MASK] .impl.xs.util.ObjectListImpl;
import com.sun.org.apache.xerces. [MASK] .impl.xs.util.SimpleLocator;
import com.sun.org.apache.xerces. [MASK] .impl.xs.util.StringListImpl;
import com.sun.org.apache.xerces. [MASK] .impl.xs.util.XSNamedMap4Types;
import com.sun.org.apache.xerces. [MASK] .impl.xs.util.XSNamedMapImpl;
import com.sun.org.apache.xerces. [MASK] .impl.xs.util.XSObjectListImpl;
import com.sun.org.apache.xerces. [MASK] .parsers.DOMParser;
import com.sun.org.apache.xerces. [MASK] .parsers.SAXParser;
import com.sun.org.apache.xerces. [MASK] .parsers.XML11Configuration;
import com.sun.org.apache.xerces. [MASK] .util.SymbolHash;
import com.sun.org.apache.xerces. [MASK] .util.SymbolTable;
import com.sun.org.apache.xerces. [MASK] .xni.NamespaceContext;
import com.sun.org.apache.xerces. [MASK] .xni.grammars.XMLGrammarDescription;
import com.sun.org.apache.xerces. [MASK] .xni.grammars.XSGrammar;
import com.sun.org.apache.xerces. [MASK] .xs.StringList;
import com.sun.org.apache.xerces. [MASK] .xs.XSAnnotation;
import com.sun.org.apache.xerces. [MASK] .xs.XSAttributeDeclaration;
import com.sun.org.apache.xerces. [MASK] .xs.XSAttributeGroupDefinition;
import com.sun.org.apache.xerces. [MASK] .xs.XSConstants;
import com.sun.org.apache.xerces. [MASK] .xs.XSElementDeclaration;
import com.sun.org.apache.xerces. [MASK] .xs.XSIDCDefinition;
import com.sun.org.apache.xerces. [MASK] .xs.XSModel;
import com.sun.org.apache.xerces. [MASK] .xs.XSModelGroupDefinition;
import com.sun.org.apache.xerces. [MASK] .xs.XSNamedMap;
import com.sun.org.apache.xerces. [MASK] .xs.XSNamespaceItem;
import com.sun.org.apache.xerces. [MASK] .xs.XSNotationDeclaration;
import com.sun.org.apache.xerces. [MASK] .xs.XSObjectList;
import com.sun.org.apache.xerces. [MASK] .xs.XSParticle;
import com.sun.org.apache.xerces. [MASK] .xs.XSTypeDefinition;
import com.sun.org.apache.xerces. [MASK] .xs.XSWildcard;
import com.sun.org.apache.xerces. [MASK] .xs.datatypes.ObjectList;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.xml.sax.SAXException;
/**
* This class is to hold all schema component declaration that are declared
* within one namespace.
*
* The Grammar class this class extends contains what little
* commonality there is between XML Schema and DTD grammars. It's
* useful to distinguish grammar objects from other kinds of object
* when they exist in pools or caches.
*
* @xerces. [MASK]
*
* @author Sandy Gao, IBM
* @author Elena Litani, IBM
*
* @LastModified: Oct 2017
*/
public class SchemaGrammar implements XSGrammar, XSNamespaceItem {
// the target namespace of grammar
String fTargetNamespace;
// global decls: map from decl name to decl object
SymbolHash fGlobalAttrDecls;
SymbolHash fGlobalAttrGrpDecls;
SymbolHash fGlobalElemDecls;
SymbolHash fGlobalGroupDecls;
SymbolHash fGlobalNotationDecls;
SymbolHash fGlobalIDConstraintDecls;
SymbolHash fGlobalTypeDecls;
// extended global decls: map from schema location + decl name to decl object
// key is location,name
SymbolHash fGlobalAttrDeclsExt;
SymbolHash fGlobalAttrGrpDeclsExt;
SymbolHash fGlobalElemDeclsExt;
SymbolHash fGlobalGroupDeclsExt;
SymbolHash fGlobalNotationDeclsExt;
SymbolHash fGlobalIDConstraintDeclsExt;
SymbolHash fGlobalTypeDeclsExt;
// A global map of all global element declarations - used for substitution group computation
// (handy when sharing components by reference, since we might end up with duplicate components
// that are not added to either of the global element declarations above)
SymbolHash fAllGlobalElemDecls;
// the XMLGrammarDescription member
XSDDescription fGrammarDescription = null;
// annotations associated with the "root" schema of this targetNamespace
XSAnnotationImpl [] fAnnotations = null;
// number of annotations declared
int fNumAnnotations;
// symbol table for constructing parsers (annotation support)
private SymbolTable fSymbolTable = null;
// parsers for annotation support
private SoftReference<SAXParser> fSAXParser = null;
private SoftReference<DOMParser> fDOMParser = null;
// is this grammar immutable? (fully constructed and not changeable)
private boolean fIsImmutable = false;
//
// Constructors
//
// needed to make BuiltinSchemaGrammar work.
protected SchemaGrammar() {}
/**
* Default constructor.
*
* @param targetNamespace
* @param grammarDesc the XMLGrammarDescription corresponding to this object
* at the least a systemId should always be known.
* @param symbolTable needed for annotation support
*/
public SchemaGrammar(String targetNamespace, XSDDescription grammarDesc,
SymbolTable symbolTable) {
fTargetNamespace = targetNamespace;
fGrammarDescription = grammarDesc;
fSymbolTable = symbolTable;
// REVISIT: the initial sizes being chosen for each SymbolHash
// may not be ideal and could still be tuned. They were chosen
// somewhat arbitrarily to reduce the initial footprint of
// SymbolHash buckets from 1,515 to 177 (about 12% of the
// default size).
fGlobalAttrDecls = new SymbolHash(12);
fGlobalAttrGrpDecls = new SymbolHash(5);
fGlobalElemDecls = new SymbolHash(25);
fGlobalGroupDecls = new SymbolHash(5);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(3);
// Extended tables
fGlobalAttrDeclsExt = new SymbolHash(12);
fGlobalAttrGrpDeclsExt = new SymbolHash(5);
fGlobalElemDeclsExt = new SymbolHash(25);
fGlobalGroupDeclsExt = new SymbolHash(5);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(3);
fGlobalTypeDeclsExt = new SymbolHash(25);
// All global elements table
fAllGlobalElemDecls = new SymbolHash(25);
// if we are parsing S4S, put built-in types in first
// they might get overwritten by the types from S4S, but that's
// considered what the application wants to do.
if (fTargetNamespace == SchemaSymbols.URI_SCHEMAFORSCHEMA) {
fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls.makeClone();
}
else {
fGlobalTypeDecls = new SymbolHash(25);
}
} // <init>(String, XSDDescription)
// Clone an existing schema grammar
public SchemaGrammar(SchemaGrammar grammar) {
fTargetNamespace = grammar.fTargetNamespace;
fGrammarDescription = grammar.fGrammarDescription.makeClone();
//fGrammarDescription.fContextType |= XSDDescription.CONTEXT_COLLISION; // REVISIT
fSymbolTable = grammar.fSymbolTable; // REVISIT
fGlobalAttrDecls = grammar.fGlobalAttrDecls.makeClone();
fGlobalAttrGrpDecls = grammar.fGlobalAttrGrpDecls.makeClone();
fGlobalElemDecls = grammar.fGlobalElemDecls.makeClone();
fGlobalGroupDecls = grammar.fGlobalGroupDecls.makeClone();
fGlobalNotationDecls = grammar.fGlobalNotationDecls.makeClone();
fGlobalIDConstraintDecls = grammar.fGlobalIDConstraintDecls.makeClone();
fGlobalTypeDecls = grammar.fGlobalTypeDecls.makeClone();
// Extended tables
fGlobalAttrDeclsExt = grammar.fGlobalAttrDeclsExt.makeClone();
fGlobalAttrGrpDeclsExt = grammar.fGlobalAttrGrpDeclsExt.makeClone();
fGlobalElemDeclsExt = grammar.fGlobalElemDeclsExt.makeClone();
fGlobalGroupDeclsExt = grammar.fGlobalGroupDeclsExt.makeClone();
fGlobalNotationDeclsExt = grammar.fGlobalNotationDeclsExt.makeClone();
fGlobalIDConstraintDeclsExt = grammar.fGlobalIDConstraintDeclsExt.makeClone();
fGlobalTypeDeclsExt = grammar.fGlobalTypeDeclsExt.makeClone();
// All global elements table
fAllGlobalElemDecls = grammar.fAllGlobalElemDecls.makeClone();
// Annotations associated with the "root" schema of this targetNamespace
fNumAnnotations = grammar.fNumAnnotations;
if (fNumAnnotations > 0) {
fAnnotations = new XSAnnotationImpl[grammar.fAnnotations.length];
System.arraycopy(grammar.fAnnotations, 0, fAnnotations, 0, fNumAnnotations);
}
// All substitution group information declared in this namespace
fSubGroupCount = grammar.fSubGroupCount;
if (fSubGroupCount > 0) {
fSubGroups = new XSElementDecl[grammar.fSubGroups.length];
System.arraycopy(grammar.fSubGroups, 0, fSubGroups, 0, fSubGroupCount);
}
// Array to store complex type decls for constraint checking
fCTCount = grammar.fCTCount;
if (fCTCount > 0) {
fComplexTypeDecls = new XSComplexTypeDecl[grammar.fComplexTypeDecls.length];
fCTLocators = new SimpleLocator[grammar.fCTLocators.length];
System.arraycopy(grammar.fComplexTypeDecls, 0, fComplexTypeDecls, 0, fCTCount);
System.arraycopy(grammar.fCTLocators, 0, fCTLocators, 0, fCTCount);
}
// Groups being redefined by restriction
fRGCount = grammar.fRGCount;
if (fRGCount > 0) {
fRedefinedGroupDecls = new XSGroupDecl[grammar.fRedefinedGroupDecls.length];
fRGLocators = new SimpleLocator[grammar.fRGLocators.length];
System.arraycopy(grammar.fRedefinedGroupDecls, 0, fRedefinedGroupDecls, 0, fRGCount);
System.arraycopy(grammar.fRGLocators, 0, fRGLocators, 0, fRGCount/2);
}
// List of imported grammars
if (grammar.fImported != null) {
fImported = new ArrayList<>();
for (int i=0; i<grammar.fImported.size(); i++) {
fImported.add(grammar.fImported.get(i));
}
}
// Locations
if (grammar.fLocations != null) {
for (int k=0; k<grammar.fLocations.size(); k++) {
addDocument(null, grammar.fLocations.get(k));
}
}
} // <init>(String, XSDDescription)
// number of built-in XSTypes we need to create for base and full
// datatype set
private static final int BASICSET_COUNT = 29;
private static final int FULLSET_COUNT = 46;
private static final int GRAMMAR_XS = 1;
private static final int GRAMMAR_XSI = 2;
// this class makes sure the static, built-in schema grammars
// are immutable.
public static class BuiltinSchemaGrammar extends SchemaGrammar {
private static final String EXTENDED_SCHEMA_FACTORY_CLASS = "com.sun.org.apache.xerces. [MASK] .impl.dv.xs.ExtendedSchemaDVFactoryImpl";
/**
* Special constructor to create the grammars for the schema namespaces
*
* @param grammar
*/
public BuiltinSchemaGrammar(int grammar, short schemaVersion) {
SchemaDVFactory schemaFactory;
if (schemaVersion == Constants.SCHEMA_VERSION_1_0) {
schemaFactory = SchemaDVFactory.getInstance();
}
else {
schemaFactory = SchemaDVFactory.getInstance(EXTENDED_SCHEMA_FACTORY_CLASS);
}
if (grammar == GRAMMAR_XS) {
// target namespace
fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA);
// no global decls other than types
fGlobalAttrDecls = new SymbolHash(1);
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(1);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(1);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// all global element decls table
fAllGlobalElemDecls = new SymbolHash(1);
// get all built-in types
fGlobalTypeDecls = schemaFactory.getBuiltInTypes();
// assign the built-in schema grammar as the XSNamespaceItem
// for each of the built-in simple type definitions.
int length = fGlobalTypeDecls.getLength();
XSTypeDefinition [] typeDefinitions = new XSTypeDefinition[length];
fGlobalTypeDecls.getValues(typeDefinitions, 0);
for (int i = 0; i < length; ++i) {
XSTypeDefinition xtd = typeDefinitions[i];
if (xtd instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) xtd).setNamespaceItem(this);
}
}
// add anyType
fGlobalTypeDecls.put(fAnyType.getName(), fAnyType);
}
else if (grammar == GRAMMAR_XSI) {
// target namespace
fTargetNamespace = SchemaSymbols.URI_XSI;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_XSI);
// no global decls other than attributes
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(1);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
fGlobalTypeDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(1);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// no all global element decls
fAllGlobalElemDecls = new SymbolHash(1);
// 4 attributes, so initialize the size as 4*2 = 8
fGlobalAttrDecls = new SymbolHash(8);
String name = null;
String tns = null;
XSSimpleType type = null;
short scope = XSConstants.SCOPE_GLOBAL;
// xsi:type
name = SchemaSymbols.XSI_TYPE;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_QNAME);
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
// xsi:nil
name = SchemaSymbols.XSI_NIL;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_BOOLEAN);
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
XSSimpleType anyURI = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_ANYURI);
// xsi:schemaLocation
name = SchemaSymbols.XSI_SCHEMALOCATION;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.createTypeList("#AnonType_schemaLocation", SchemaSymbols.URI_XSI, (short)0, anyURI, null);
if (type instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl)type).setAnonymous(true);
}
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
// xsi:noNamespaceSchemaLocation
name = SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION;
tns = SchemaSymbols.URI_XSI;
type = anyURI;
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
}
} // <init>(int)
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription.makeClone();
} // getGrammarDescription(): XMLGrammarDescription
// override these methods solely so that these
// objects cannot be modified once they're created.
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl, String location) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
// ignore
}
public void addGlobalElementDeclAll(XSElementDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
// ignore
}
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
// ignore
}
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
// ignore
}
public synchronized void addDocument(Object document, String location) {
// ignore
}
// annotation support
synchronized DOMParser getDOMParser() {
return null;
}
synchronized SAXParser getSAXParser() {
return null;
}
}
/**
* <p>A partial schema for schemas for validating annotations.</p>
*
* @xerces. [MASK]
*
* @author Michael Glavassevich, IBM
*/
public static final class Schema4Annotations extends SchemaGrammar {
/**
* Singleton instance.
*/
public static final Schema4Annotations INSTANCE = new Schema4Annotations();
/**
* Special constructor to create a schema
* capable of validating annotations.
*/
private Schema4Annotations() {
// target namespace
fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA);
// no global decls other than types and
// element declarations for <annotation>, <documentation> and <appinfo>.
fGlobalAttrDecls = new SymbolHash(1);
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(6);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(6);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// all global element declarations
fAllGlobalElemDecls = new SymbolHash(6);
// get all built-in types
fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls;
// create element declarations for <annotation>, <documentation> and <appinfo>
XSElementDecl annotationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_ANNOTATION);
XSElementDecl documentationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_DOCUMENTATION);
XSElementDecl appinfoDecl = createAnnotationElementDecl(SchemaSymbols.ELT_APPINFO);
// add global element declarations
fGlobalElemDecls.put(annotationDecl.fName, annotationDecl);
fGlobalElemDecls.put(documentationDecl.fName, documentationDecl);
fGlobalElemDecls.put(appinfoDecl.fName, appinfoDecl);
fGlobalElemDeclsExt.put(","+annotationDecl.fName, annotationDecl);
fGlobalElemDeclsExt.put(","+documentationDecl.fName, documentationDecl);
fGlobalElemDeclsExt.put(","+appinfoDecl.fName, appinfoDecl);
fAllGlobalElemDecls.put(annotationDecl, annotationDecl);
fAllGlobalElemDecls.put(documentationDecl, documentationDecl);
fAllGlobalElemDecls.put(appinfoDecl, appinfoDecl);
// create complex type declarations for <annotation>, <documentation> and <appinfo>
XSComplexTypeDecl annotationType = new XSComplexTypeDecl();
XSComplexTypeDecl documentationType = new XSComplexTypeDecl();
XSComplexTypeDecl appinfoType = new XSComplexTypeDecl();
// set the types on their element declarations
annotationDecl.fType = annotationType;
documentationDecl.fType = documentationType;
appinfoDecl.fType = appinfoType;
// create attribute groups for <annotation>, <documentation> and <appinfo>
XSAttributeGroupDecl annotationAttrs = new XSAttributeGroupDecl();
XSAttributeGroupDecl documentationAttrs = new XSAttributeGroupDecl();
XSAttributeGroupDecl appinfoAttrs = new XSAttributeGroupDecl();
// fill in attribute groups
{
// create and fill attribute uses for <annotation>, <documentation> and <appinfo>
XSAttributeUseImpl annotationIDAttr = new XSAttributeUseImpl();
annotationIDAttr.fAttrDecl = new XSAttributeDecl();
annotationIDAttr.fAttrDecl.setValues(SchemaSymbols.ATT_ID, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ID),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, annotationType, null);
annotationIDAttr.fUse = SchemaSymbols.USE_OPTIONAL;
annotationIDAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl documentationSourceAttr = new XSAttributeUseImpl();
documentationSourceAttr.fAttrDecl = new XSAttributeDecl();
documentationSourceAttr.fAttrDecl.setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ANYURI),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, documentationType, null);
documentationSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL;
documentationSourceAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl documentationLangAttr = new XSAttributeUseImpl();
documentationLangAttr.fAttrDecl = new XSAttributeDecl();
documentationLangAttr.fAttrDecl.setValues("lang".intern(), NamespaceContext.XML_URI, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_LANGUAGE),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, documentationType, null);
documentationLangAttr.fUse = SchemaSymbols.USE_OPTIONAL;
documentationLangAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl appinfoSourceAttr = new XSAttributeUseImpl();
appinfoSourceAttr.fAttrDecl = new XSAttributeDecl();
appinfoSourceAttr.fAttrDecl.setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ANYURI),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, appinfoType, null);
appinfoSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL;
appinfoSourceAttr.fConstraintType = XSConstants.VC_NONE;
// create lax attribute wildcard for <annotation>, <documentation> and <appinfo>
XSWildcardDecl otherAttrs = new XSWildcardDecl();
otherAttrs.fNamespaceList = new String [] {fTargetNamespace, null};
otherAttrs.fType = XSWildcard.NSCONSTRAINT_NOT;
otherAttrs.fProcessContents = XSWildcard.PC_LAX;
// add attribute uses and wildcards to attribute groups for <annotation>, <documentation> and <appinfo>
annotationAttrs.addAttributeUse(annotationIDAttr);
annotationAttrs.fAttributeWC = otherAttrs;
documentationAttrs.addAttributeUse(documentationSourceAttr);
documentationAttrs.addAttributeUse(documentationLangAttr);
documentationAttrs.fAttributeWC = otherAttrs;
appinfoAttrs.addAttributeUse(appinfoSourceAttr);
appinfoAttrs.fAttributeWC = otherAttrs;
}
// create particles for <annotation>
XSParticleDecl annotationParticle = createUnboundedModelGroupParticle();
{
XSModelGroupImpl annotationChoice = new XSModelGroupImpl();
annotationChoice.fCompositor = XSModelGroupImpl.MODELGROUP_CHOICE;
annotationChoice.fParticleCount = 2;
annotationChoice.fParticles = new XSParticleDecl[2];
annotationChoice.fParticles[0] = createChoiceElementParticle(appinfoDecl);
annotationChoice.fParticles[1] = createChoiceElementParticle(documentationDecl);
annotationParticle.fValue = annotationChoice;
}
// create wildcard particle for <documentation> and <appinfo>
XSParticleDecl anyWCSequenceParticle = createUnboundedAnyWildcardSequenceParticle();
// fill complex types
annotationType.setValues("#AnonType_" + SchemaSymbols.ELT_ANNOTATION, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_ELEMENT, false, annotationAttrs, null, annotationParticle, XSObjectListImpl.EMPTY_LIST);
annotationType.setName("#AnonType_" + SchemaSymbols.ELT_ANNOTATION);
annotationType.setIsAnonymous();
documentationType.setValues("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_MIXED, false, documentationAttrs, null, anyWCSequenceParticle, XSObjectListImpl.EMPTY_LIST);
documentationType.setName("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION);
documentationType.setIsAnonymous();
appinfoType.setValues("#AnonType_" + SchemaSymbols.ELT_APPINFO, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_MIXED, false, appinfoAttrs, null, anyWCSequenceParticle, XSObjectListImpl.EMPTY_LIST);
appinfoType.setName("#AnonType_" + SchemaSymbols.ELT_APPINFO);
appinfoType.setIsAnonymous();
} // <init>(int)
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription.makeClone();
} // getGrammarDescription(): XMLGrammarDescription
// override these methods solely so that these
// objects cannot be modified once they're created.
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
// ignore
}
public void addGlobalElementDeclAll(XSElementDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
// ignore
}
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
// ignore
}
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
// ignore
}
public synchronized void addDocument(Object document, String location) {
// ignore
}
// annotation support
synchronized DOMParser getDOMParser() {
return null;
}
synchronized SAXParser getSAXParser() {
return null;
}
//
// private helper methods
//
private XSElementDecl createAnnotationElementDecl(String localName) {
XSElementDecl eDecl = new XSElementDecl();
eDecl.fName = localName;
eDecl.fTargetNamespace = fTargetNamespace;
eDecl.setIsGlobal();
eDecl.fBlock = (XSConstants.DERIVATION_EXTENSION |
XSConstants.DERIVATION_RESTRICTION | XSConstants.DERIVATION_SUBSTITUTION);
eDecl.setConstraintType(XSConstants.VC_NONE);
return eDecl;
}
private XSParticleDecl createUnboundedModelGroupParticle() {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 0;
particle.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED;
particle.fType = XSParticleDecl.PARTICLE_MODELGROUP;
return particle;
}
private XSParticleDecl createChoiceElementParticle(XSElementDecl ref) {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 1;
particle.fMaxOccurs = 1;
particle.fType = XSParticleDecl.PARTICLE_ELEMENT;
particle.fValue = ref;
return particle;
}
private XSParticleDecl createUnboundedAnyWildcardSequenceParticle() {
XSParticleDecl particle = createUnboundedModelGroupParticle();
XSModelGroupImpl sequence = new XSModelGroupImpl();
sequence.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE;
sequence.fParticleCount = 1;
sequence.fParticles = new XSParticleDecl[1];
sequence.fParticles[0] = createAnyLaxWildcardParticle();
particle.fValue = sequence;
return particle;
}
private XSParticleDecl createAnyLaxWildcardParticle() {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 1;
particle.fMaxOccurs = 1;
particle.fType = XSParticleDecl.PARTICLE_WILDCARD;
XSWildcardDecl anyWC = new XSWildcardDecl();
anyWC.fNamespaceList = null;
anyWC.fType = XSWildcard.NSCONSTRAINT_ANY;
anyWC.fProcessContents = XSWildcard.PC_LAX;
particle.fValue = anyWC;
return particle;
}
}
// Grammar methods
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription;
} // getGrammarDescription(): XMLGrammarDescription
// DTDGrammar methods
public boolean isNamespaceAware () {
return true;
} // isNamespaceAware():boolean
List<SchemaGrammar> fImported = null;
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
fImported = importedGrammars;
}
public List<SchemaGrammar> getImportedGrammars() {
return fImported;
}
/**
* Returns this grammar's target namespace.
*/
public final String getTargetNamespace() {
return fTargetNamespace;
} // getTargetNamespace():String
/**
* register one global attribute
*/
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
fGlobalAttrDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalAttributeDecl(XSAttributeDecl decl, String location) {
fGlobalAttrDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global attribute group
*/
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
fGlobalAttrGrpDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
fGlobalAttrGrpDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global element
*/
public void addGlobalElementDeclAll(XSElementDecl decl) {
if (fAllGlobalElemDecls.get(decl) == null) {
fAllGlobalElemDecls.put(decl, decl);
// if there is a substitution group affiliation, store in an array,
// for further constraint checking: UPA, PD, EDC
if (decl.fSubGroup != null) {
if (fSubGroupCount == fSubGroups.length)
fSubGroups = resize(fSubGroups, fSubGroupCount+INC_SIZE);
fSubGroups[fSubGroupCount++] = decl;
}
}
}
public void addGlobalElementDecl(XSElementDecl decl) {
fGlobalElemDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
fGlobalElemDeclsExt.put(((location != null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global group
*/
public void addGlobalGroupDecl(XSGroupDecl decl) {
fGlobalGroupDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
fGlobalGroupDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global notation
*/
public void addGlobalNotationDecl(XSNotationDecl decl) {
fGlobalNotationDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
fGlobalNotationDeclsExt.put(((location!=null) ? location : "") + "," +decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global type
*/
public void addGlobalTypeDecl(XSTypeDefinition decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
if (decl instanceof XSComplexTypeDecl) {
((XSComplexTypeDecl) decl).setNamespaceItem(this);
}
else if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
fGlobalTypeDeclsExt.put(((location!=null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null) {
if (decl instanceof XSComplexTypeDecl) {
((XSComplexTypeDecl) decl).setNamespaceItem(this);
}
else if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
}
/**
* register one global complex type
*/
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
decl.setNamespaceItem(this);
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
fGlobalTypeDeclsExt.put(((location!=null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global simple type
*/
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
fGlobalTypeDeclsExt.put(((location != null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null && decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
/**
* register one identity constraint
*/
public final void addIDConstraintDecl(XSElementDecl elmDecl, IdentityConstraint decl) {
elmDecl.addIDConstraint(decl);
fGlobalIDConstraintDecls.put(decl.getIdentityConstraintName(), decl);
}
public final void addIDConstraintDecl(XSElementDecl elmDecl, IdentityConstraint decl, String location) {
fGlobalIDConstraintDeclsExt.put(((location != null) ? location : "") + "," + decl.getIdentityConstraintName(), decl);
}
/**
* get one global attribute
*/
public final XSAttributeDecl getGlobalAttributeDecl(String declName) {
return(XSAttributeDecl)fGlobalAttrDecls.get(declName);
}
public final XSAttributeDecl getGlobalAttributeDecl(String declName, String location) {
return(XSAttributeDecl)fGlobalAttrDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global attribute group
*/
public final XSAttributeGroupDecl getGlobalAttributeGroupDecl(String declName) {
return(XSAttributeGroupDecl)fGlobalAttrGrpDecls.get(declName);
}
public final XSAttributeGroupDecl getGlobalAttributeGroupDecl(String declName, String location) {
return(XSAttributeGroupDecl)fGlobalAttrGrpDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global element
*/
public final XSElementDecl getGlobalElementDecl(String declName) {
return(XSElementDecl)fGlobalElemDecls.get(declName);
}
public final XSElementDecl getGlobalElementDecl(String declName, String location) {
return(XSElementDecl)fGlobalElemDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global group
*/
public final XSGroupDecl getGlobalGroupDecl(String declName) {
return(XSGroupDecl)fGlobalGroupDecls.get(declName);
}
public final XSGroupDecl getGlobalGroupDecl(String declName, String location) {
return(XSGroupDecl)fGlobalGroupDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global notation
*/
public final XSNotationDecl getGlobalNotationDecl(String declName) {
return(XSNotationDecl)fGlobalNotationDecls.get(declName);
}
public final XSNotationDecl getGlobalNotationDecl(String declName, String location) {
return(XSNotationDecl)fGlobalNotationDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global type
*/
public final XSTypeDefinition getGlobalTypeDecl(String declName) {
return(XSTypeDefinition)fGlobalTypeDecls.get(declName);
}
public final XSTypeDefinition getGlobalTypeDecl(String declName, String location) {
return(XSTypeDefinition)fGlobalTypeDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one identity constraint
*/
public final IdentityConstraint getIDConstraintDecl(String declName) {
return(IdentityConstraint)fGlobalIDConstraintDecls.get(declName);
}
public final IdentityConstraint getIDConstraintDecl(String declName, String location) {
return(IdentityConstraint)fGlobalIDConstraintDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one identity constraint
*/
public final boolean hasIDConstraints() {
return fGlobalIDConstraintDecls.getLength() > 0;
}
// array to store complex type decls
private static final int INITIAL_SIZE = 16;
private static final int INC_SIZE = 16;
private int fCTCount = 0;
private XSComplexTypeDecl[] fComplexTypeDecls = new XSComplexTypeDecl[INITIAL_SIZE];
private SimpleLocator[] fCTLocators = new SimpleLocator[INITIAL_SIZE];
// an array to store groups being redefined by restriction
// even-numbered elements are the derived groups, odd-numbered ones their bases
private static final int REDEFINED_GROUP_INIT_SIZE = 2;
private int fRGCount = 0;
private XSGroupDecl[] fRedefinedGroupDecls = new XSGroupDecl[REDEFINED_GROUP_INIT_SIZE];
private SimpleLocator[] fRGLocators = new SimpleLocator[REDEFINED_GROUP_INIT_SIZE/2];
// a flag to indicate whether we have checked the 3 constraints on this
// grammar.
boolean fFullChecked = false;
/**
* add one complex type decl: for later constraint checking
*/
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
if (fCTCount == fComplexTypeDecls.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount+INC_SIZE);
fCTLocators = resize(fCTLocators, fCTCount+INC_SIZE);
}
fCTLocators[fCTCount] = locator;
fComplexTypeDecls[fCTCount++] = decl;
}
/**
* add a group redefined by restriction: for later constraint checking
*/
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
if (fRGCount == fRedefinedGroupDecls.length) {
// double array size each time.
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount << 1);
fRGLocators = resize(fRGLocators, fRGCount);
}
fRGLocators[fRGCount/2] = locator;
fRedefinedGroupDecls[fRGCount++] = derived;
fRedefinedGroupDecls[fRGCount++] = base;
}
/**
* get all complex type decls: for later constraint checking
*/
final XSComplexTypeDecl[] getUncheckedComplexTypeDecls() {
if (fCTCount < fComplexTypeDecls.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
return fComplexTypeDecls;
}
/**
* get the error locator of all complex type decls
*/
final SimpleLocator[] getUncheckedCTLocators() {
if (fCTCount < fCTLocators.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
return fCTLocators;
}
/**
* get all redefined groups: for later constraint checking
*/
final XSGroupDecl[] getRedefinedGroupDecls() {
if (fRGCount < fRedefinedGroupDecls.length) {
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount);
fRGLocators = resize(fRGLocators, fRGCount/2);
}
return fRedefinedGroupDecls;
}
/**
* get the error locator of all redefined groups
*/
final SimpleLocator[] getRGLocators() {
if (fRGCount < fRedefinedGroupDecls.length) {
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount);
fRGLocators = resize(fRGLocators, fRGCount/2);
}
return fRGLocators;
}
/**
* after the first-round checking, some types don't need to be checked
* against UPA again. here we trim the array to the proper size.
*/
final void setUncheckedTypeNum(int newSize) {
fCTCount = newSize;
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
// used to store all substitution group information declared in
// this namespace
private int fSubGroupCount = 0;
private XSElementDecl[] fSubGroups = new XSElementDecl[INITIAL_SIZE];
/**
* get all substitution group information: for the 3 constraint checking
*/
final XSElementDecl[] getSubstitutionGroups() {
if (fSubGroupCount < fSubGroups.length)
fSubGroups = resize(fSubGroups, fSubGroupCount);
return fSubGroups;
}
// anyType and anySimpleType: because there are so many places where
// we need direct access to these two types
public final static XSComplexTypeDecl fAnyType = new XSAnyType();
private static class XSAnyType extends XSComplexTypeDecl {
public XSAnyType () {
fName = SchemaSymbols.ATTVAL_ANYTYPE;
super.fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
fBaseType = this;
fDerivedBy = XSConstants.DERIVATION_RESTRICTION;
fContentType = XSComplexTypeDecl.CONTENTTYPE_MIXED;
fParticle = createParticle();
fAttrGrp = createAttrGrp();
}
// overridden methods
public void setValues(String name, String targetNamespace,
XSTypeDefinition baseType, short derivedBy, short schemaFinal,
short block, short contentType,
boolean isAbstract, XSAttributeGroupDecl attrGrp,
XSSimpleType simpleType, XSParticleDecl particle) {
// don't allow this.
}
public void setName(String name){
// don't allow this.
}
public void setIsAbstractType() {
// null implementation
}
public void setContainsTypeID() {
// null implementation
}
public void setIsAnonymous() {
// null implementation
}
public void reset() {
// null implementation
}
public XSObjectList getAnnotations() {
return XSObjectListImpl.EMPTY_LIST;
}
public XSNamespaceItem getNamespaceItem() {
return SG_SchemaNS;
}
private XSAttributeGroupDecl createAttrGrp() {
XSWildcardDecl wildcard = new XSWildcardDecl();
wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
XSAttributeGroupDecl attrGrp = new XSAttributeGroupDecl();
attrGrp.fAttributeWC = wildcard;
return attrGrp;
}
private XSParticleDecl createParticle() {
// the wildcard used in anyType (content and attribute)
// the spec will change strict to skip for anyType
XSWildcardDecl wildcard = new XSWildcardDecl();
wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
// the particle for the content wildcard
XSParticleDecl particleW = new XSParticleDecl();
particleW.fMinOccurs = 0;
particleW.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED;
particleW.fType = XSParticleDecl.PARTICLE_WILDCARD;
particleW.fValue = wildcard;
// the model group of a sequence of the above particle
XSModelGroupImpl group = new XSModelGroupImpl();
group.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE;
group.fParticleCount = 1;
group.fParticles = new XSParticleDecl[1];
group.fParticles[0] = particleW;
// the content of anyType: particle of the above model group
XSParticleDecl particleG = new XSParticleDecl();
particleG.fType = XSParticleDecl.PARTICLE_MODELGROUP;
particleG.fValue = group;
return particleG;
}
}
private static class BuiltinAttrDecl extends XSAttributeDecl {
public BuiltinAttrDecl(String name, String tns,
XSSimpleType type, short scope) {
fName = name;
super.fTargetNamespace = tns;
fType = type;
fScope = scope;
}
public void setValues(String name, String targetNamespace,
XSSimpleType simpleType, short constraintType, short scope,
ValidatedInfo valInfo, XSComplexTypeDecl enclosingCT) {
// ignore this call.
}
public void reset () {
// also ignore this call.
}
public XSAnnotation getAnnotation() {
return null;
}
public XSNamespaceItem getNamespaceItem() {
return SG_XSI;
}
} // class BuiltinAttrDecl
// the grammars to hold components of the schema namespace
public final static BuiltinSchemaGrammar SG_SchemaNS = new BuiltinSchemaGrammar(GRAMMAR_XS, Constants.SCHEMA_VERSION_1_0);
private final static BuiltinSchemaGrammar SG_SchemaNSExtended = new BuiltinSchemaGrammar(GRAMMAR_XS, Constants.SCHEMA_VERSION_1_0_EXTENDED);
public final static XSSimpleType fAnySimpleType = (XSSimpleType)SG_SchemaNS.getGlobalTypeDecl(SchemaSymbols.ATTVAL_ANYSIMPLETYPE);
// the grammars to hold components of the schema-instance namespace
public final static BuiltinSchemaGrammar SG_XSI = new BuiltinSchemaGrammar(GRAMMAR_XSI, Constants.SCHEMA_VERSION_1_0);
public static SchemaGrammar getS4SGrammar(short schemaVersion) {
if (schemaVersion == Constants.SCHEMA_VERSION_1_0) {
return SG_SchemaNS;
}
else {
return SG_SchemaNSExtended;
}
}
static final XSComplexTypeDecl[] resize(XSComplexTypeDecl[] oldArray, int newSize) {
XSComplexTypeDecl[] newArray = new XSComplexTypeDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final XSGroupDecl[] resize(XSGroupDecl[] oldArray, int newSize) {
XSGroupDecl[] newArray = new XSGroupDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final XSElementDecl[] resize(XSElementDecl[] oldArray, int newSize) {
XSElementDecl[] newArray = new XSElementDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final SimpleLocator[] resize(SimpleLocator[] oldArray, int newSize) {
SimpleLocator[] newArray = new SimpleLocator[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
// XSNamespaceItem methods
// the max index / the max value of XSObject type
private static final short MAX_COMP_IDX = XSTypeDefinition.SIMPLE_TYPE;
private static final boolean[] GLOBAL_COMP = {false, // null
true, // attribute
true, // element
true, // type
false, // attribute use
true, // attribute group
true, // group
false, // model group
false, // particle
false, // wildcard
true, // idc
true, // notation
false, // annotation
false, // facet
false, // multi value facet
true, // complex type
true // simple type
};
// store a certain kind of components from all namespaces
private XSNamedMap[] fComponents = null;
private ObjectList[] fComponentsExt = null;
// store the documents and their locations contributing to this namespace
// REVISIT: use StringList and XSObjectList for there fields.
// fDocuments is never used
private List<Object> fDocuments = null;
private List<String> fLocations = null;
public synchronized void addDocument(Object document, String location) {
if (fDocuments == null) {
// Parsing schema is not thread safe, synchronized may be removed
fDocuments = new CopyOnWriteArrayList<>();
fLocations = new CopyOnWriteArrayList<>();
}
fDocuments.add(document);
fLocations.add(location);
}
public synchronized void removeDocument(int index) {
if (fDocuments != null &&
index >= 0 &&
index < fDocuments.size()) {
fDocuments.remove(index);
fLocations.remove(index);
}
}
/**
* [schema namespace]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#nsi-schema_namespace">[schema namespace]</a>
* @return The target namespace of this item.
*/
public String getSchemaNamespace() {
return fTargetNamespace;
}
// annotation support
synchronized DOMParser getDOMParser() {
if (fDOMParser != null) {
DOMParser parser = fDOMParser.get();
if (parser != null) {
return parser;
}
}
// REVISIT: when schema handles XML 1.1, will need to
// revisit this (and the practice of not prepending an XML decl to the annotation string
XML11Configuration config = new XML11Configuration(fSymbolTable);
// note that this should never produce errors or require
// entity resolution, so just a barebones configuration with
// a couple of feature set will do fine
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true);
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false);
DOMParser parser = new DOMParser(config);
try {
parser.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.DEFER_NODE_EXPANSION_FEATURE, false);
}
catch (SAXException exc) {}
fDOMParser = new SoftReference<DOMParser>(parser);
return parser;
}
synchronized SAXParser getSAXParser() {
if (fSAXParser != null) {
SAXParser parser = fSAXParser.get();
if (parser != null) {
return parser;
}
}
// REVISIT: when schema handles XML 1.1, will need to
// revisit this (and the practice of not prepending an XML decl to the annotation string
XML11Configuration config = new XML11Configuration(fSymbolTable);
// note that this should never produce errors or require
// entity resolution, so just a barebones configuration with
// a couple of feature set will do fine
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true);
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false);
SAXParser parser = new SAXParser(config);
fSAXParser = new SoftReference<SAXParser>(parser);
return parser;
}
/**
* [schema components]: a list of top-level components, i.e. element
* declarations, attribute declarations, etc.
* @param objectType The type of the declaration, i.e.
* <code>ELEMENT_DECLARATION</code>. Note that
* <code>XSTypeDefinition.SIMPLE_TYPE</code> and
* <code>XSTypeDefinition.COMPLEX_TYPE</code> can also be used as the
* <code>objectType</code> to retrieve only complex types or simple
* types, instead of all types.
* @return A list of top-level definition of the specified type in
* <code>objectType</code> or an empty <code>XSNamedMap</code> if no
* such definitions exist.
*/
public synchronized XSNamedMap getComponents(short objectType) {
if (objectType <= 0 || objectType > MAX_COMP_IDX ||
!GLOBAL_COMP[objectType]) {
return XSNamedMapImpl.EMPTY_MAP;
}
if (fComponents == null)
fComponents = new XSNamedMap[MAX_COMP_IDX+1];
// get the hashtable for this type of components
if (fComponents[objectType] == null) {
SymbolHash table = null;
switch (objectType) {
case XSConstants.TYPE_DEFINITION:
case XSTypeDefinition.COMPLEX_TYPE:
case XSTypeDefinition.SIMPLE_TYPE:
table = fGlobalTypeDecls;
break;
case XSConstants.ATTRIBUTE_DECLARATION:
table = fGlobalAttrDecls;
break;
case XSConstants.ELEMENT_DECLARATION:
table = fGlobalElemDecls;
break;
case XSConstants.ATTRIBUTE_GROUP:
table = fGlobalAttrGrpDecls;
break;
case XSConstants.MODEL_GROUP_DEFINITION:
table = fGlobalGroupDecls;
break;
case XSConstants.NOTATION_DECLARATION:
table = fGlobalNotationDecls;
break;
case XSConstants.IDENTITY_CONSTRAINT:
table = this.fGlobalIDConstraintDecls;
break;
}
// for complex/simple types, create a special implementation,
// which take specific types out of the hash table
if (objectType == XSTypeDefinition.COMPLEX_TYPE ||
objectType == XSTypeDefinition.SIMPLE_TYPE) {
fComponents[objectType] = new XSNamedMap4Types(fTargetNamespace, table, objectType);
}
else {
fComponents[objectType] = new XSNamedMapImpl(fTargetNamespace, table);
}
}
return fComponents[objectType];
}
public synchronized ObjectList getComponentsExt(short objectType) {
if (objectType <= 0 || objectType > MAX_COMP_IDX ||
!GLOBAL_COMP[objectType]) {
return ObjectListImpl.EMPTY_LIST;
}
if (fComponentsExt == null)
fComponentsExt = new ObjectList[MAX_COMP_IDX+1];
// get the hashtable for this type of components
if (fComponentsExt[objectType] == null) {
SymbolHash table = null;
switch (objectType) {
case XSConstants.TYPE_DEFINITION:
case XSTypeDefinition.COMPLEX_TYPE:
case XSTypeDefinition.SIMPLE_TYPE:
table = fGlobalTypeDeclsExt;
break;
case XSConstants.ATTRIBUTE_DECLARATION:
table = fGlobalAttrDeclsExt;
break;
case XSConstants.ELEMENT_DECLARATION:
table = fGlobalElemDeclsExt;
break;
case XSConstants.ATTRIBUTE_GROUP:
table = fGlobalAttrGrpDeclsExt;
break;
case XSConstants.MODEL_GROUP_DEFINITION:
table = fGlobalGroupDeclsExt;
break;
case XSConstants.NOTATION_DECLARATION:
table = fGlobalNotationDeclsExt;
break;
case XSConstants.IDENTITY_CONSTRAINT:
table = this.fGlobalIDConstraintDeclsExt;
break;
}
Object[] entries = table.getEntries();
fComponentsExt[objectType] = new ObjectListImpl(entries, entries.length);
}
return fComponentsExt[objectType];
}
public synchronized void resetComponents() {
fComponents = null;
fComponentsExt = null;
}
/**
* Convenience method. Returns a top-level simple or complex type
* definition.
* @param name The name of the definition.
* @return An <code>XSTypeDefinition</code> or null if such definition
* does not exist.
*/
public XSTypeDefinition getTypeDefinition(String name) {
return getGlobalTypeDecl(name);
}
/**
* Convenience method. Returns a top-level attribute declaration.
* @param name The name of the declaration.
* @return A top-level attribute declaration or null if such declaration
* does not exist.
*/
public XSAttributeDeclaration getAttributeDeclaration(String name) {
return getGlobalAttributeDecl(name);
}
/**
* Convenience method. Returns a top-level element declaration.
* @param name The name of the declaration.
* @return A top-level element declaration or null if such declaration
* does not exist.
*/
public XSElementDeclaration getElementDeclaration(String name) {
return getGlobalElementDecl(name);
}
/**
* Convenience method. Returns a top-level attribute group definition.
* @param name The name of the definition.
* @return A top-level attribute group definition or null if such
* definition does not exist.
*/
public XSAttributeGroupDefinition getAttributeGroup(String name) {
return getGlobalAttributeGroupDecl(name);
}
/**
* Convenience method. Returns a top-level model group definition.
*
* @param name The name of the definition.
* @return A top-level model group definition definition or null if such
* definition does not exist.
*/
public XSModelGroupDefinition getModelGroupDefinition(String name) {
return getGlobalGroupDecl(name);
}
/**
* Convenience method. Returns a top-level notation declaration.
*
* @param name The name of the declaration.
* @return A top-level notation declaration or null if such declaration
* does not exist.
*/
public XSNotationDeclaration getNotationDeclaration(String name) {
return getGlobalNotationDecl(name);
}
public XSIDCDefinition getIDCDefinition(String name) {
return getIDConstraintDecl(name);
}
/**
* [document location]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#sd-document_location">[document location]</a>
* @return a list of document information item
*/
public StringList getDocumentLocations() {
return new StringListImpl(fLocations);
}
/**
* Return an <code>XSModel</code> that represents components in this schema
* grammar.
*
* @return an <code>XSModel</code> representing this schema grammar
*/
public XSModel toXSModel() {
return new XSModelImpl(new SchemaGrammar[]{this});
}
public XSModel toXSModel(XSGrammar[] grammars) {
if (grammars == null || grammars.length == 0)
return toXSModel();
int len = grammars.length;
boolean hasSelf = false;
for (int i = 0; i < len; i++) {
if (grammars[i] == this) {
hasSelf = true;
break;
}
}
SchemaGrammar[] gs = new SchemaGrammar[hasSelf ? len : len+1];
for (int i = 0; i < len; i++)
gs[i] = (SchemaGrammar)grammars[i];
if (!hasSelf)
gs[len] = this;
return new XSModelImpl(gs);
}
/**
* @see org.apache.xerces.xs.XSNamespaceItem#getAnnotations()
*/
public XSObjectList getAnnotations() {
if (fNumAnnotations == 0) {
return XSObjectListImpl.EMPTY_LIST;
}
return new XSObjectListImpl(fAnnotations, fNumAnnotations);
}
public void addAnnotation(XSAnnotationImpl annotation) {
if (annotation == null) {
return;
}
if (fAnnotations == null) {
fAnnotations = new XSAnnotationImpl[2];
}
else if (fNumAnnotations == fAnnotations.length) {
XSAnnotationImpl[] newArray = new XSAnnotationImpl[fNumAnnotations << 1];
System.arraycopy(fAnnotations, 0, newArray, 0, fNumAnnotations);
fAnnotations = newArray;
}
fAnnotations[fNumAnnotations++] = annotation;
}
public void setImmutable(boolean isImmutable) {
fIsImmutable = isImmutable;
}
public boolean isImmutable() {
return fIsImmutable;
}
} // class SchemaGrammar
| internal |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex [MASK] ;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this. [MASK] = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this. [MASK] .add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this. [MASK] .add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this. [MASK] .add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this. [MASK] .add(layer, name);
writeEntry(name, this. [MASK] ::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this. [MASK] .add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| layerIndex |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api. [MASK] ;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new [MASK] ("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new [MASK] ("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new [MASK] ("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| GradleException |
/*
* Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.hosted;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.stream.Collectors;
import org.graalvm.nativeimage.hosted.RuntimeReflection;
import org.graalvm.nativeimage.hosted.RuntimeResourceAccess;
import com.oracle.svm.core.feature.AutomaticallyRegisteredFeature;
import com.oracle.svm.core.feature.InternalFeature;
import com.oracle.svm.core.jdk.ServiceCatalogSupport;
import com.oracle.svm.core.option.AccumulatingLocatableMultiOptionValue;
import com.oracle.svm.core.option.HostedOptionKey;
import com.oracle.svm.hosted.analysis.Inflation;
import jdk.graal.compiler.options.Option;
import jdk.graal.compiler.options.OptionType;
/**
* Support for {@link ServiceLoader} on Substrate VM.
*
* Services are registered in the folder {@code "META-INF/services/"} using files whose name is the
* fully qualified service interface name. We do not know which services are going to be used by a
* native image: The parameter of {@code ServiceLoader#load} is often but not always a compile-time
* constant that we can track. But we also cannot put all registered services into the native image.
*
* We therefore use the following heuristic: We add all service loader files and service
* implementation classes when the service interfaces that are seen as reachable by the static
* analysis.
*
* Each used service implementation class is added for reflection (using
* {@link org.graalvm.nativeimage.hosted.RuntimeReflection#register(Class[])}) and for reflective
* instantiation (using {@link RuntimeReflection#registerForReflectiveInstantiation(Class[])}).
*
* For each service interface, a single service loader file is added as a resource to the image. The
* single file combines all the individual files that can come from different .jar files.
*/
@AutomaticallyRegisteredFeature
public class ServiceLoaderFeature implements InternalFeature {
public static class [MASK] {
@Option(help = "Automatically register services for run-time lookup using ServiceLoader", type = OptionType.Expert) //
public static final HostedOptionKey<Boolean> UseServiceLoaderFeature = new HostedOptionKey<>(true);
@Option(help = "Comma-separated list of services that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServices = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
@Option(help = "Comma-separated list of service providers that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServiceProviders = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
}
private static final Set<String> SKIPPED_SERVICES = Set.of(
// image builder internal ServiceLoader interfaces
"com.oracle.svm.hosted.NativeImageClassLoaderPostProcessing",
"org.graalvm.nativeimage.Platform",
/*
* Loaded in java.util.random.RandomGeneratorFactory.FactoryMapHolder, which is
* initialized at image build time.
*/
"java.util.random.RandomGenerator",
"java.security.Provider", // see SecurityServicesFeature
"sun.util.locale.provider.LocaleDataMetaInfo", // see LocaleSubstitutions
/* Graal hotspot-specific services */
"jdk.vm.ci.hotspot.HotSpotJVMCIBackendFactory",
"jdk.graal.compiler.hotspot.CompilerConfigurationFactory",
"jdk.graal.compiler.hotspot.HotSpotBackendFactory",
"jdk.graal.compiler.hotspot.meta.DefaultHotSpotLoweringProvider$Extensions",
"jdk.graal.compiler.hotspot.meta.HotSpotInvocationPluginProvider",
"jdk.graal.compiler.truffle.hotspot.TruffleCallBoundaryInstrumentationFactory");
// NOTE: Platform class had to be added to this list since our analysis discovers that
// Platform.includedIn is reachable regardless of fact that it is constant folded at
// registerPlatformPlugins method of SubstrateGraphBuilderPlugins. This issue hasn't manifested
// before because implementation classes were instantiated using runtime reflection instead of
// ServiceLoader (and thus weren't reachable in analysis).
/**
* Services that should not be processed here, for example because they are handled by
* specialized features.
*/
private final Set<String> servicesToSkip = new HashSet<>(SKIPPED_SERVICES);
private static final Set<String> SKIPPED_PROVIDERS = Set.of(
/* Graal hotspot-specific service-providers */
"jdk.graal.compiler.hotspot.meta.HotSpotDisassemblerProvider",
/* Skip console providers until GR-44085 is fixed */
"jdk.internal.org.jline.JdkConsoleProviderImpl", "jdk.jshell.execution.impl.ConsoleImpl$ConsoleProviderImpl");
private final Set<String> serviceProvidersToSkip = new HashSet<>(SKIPPED_PROVIDERS);
@Override
public boolean isInConfiguration(IsInConfigurationAccess access) {
return [MASK] .UseServiceLoaderFeature.getValue();
}
@Override
public void afterRegistration(AfterRegistrationAccess access) {
servicesToSkip.addAll( [MASK] .ServiceLoaderFeatureExcludeServices.getValue().values());
serviceProvidersToSkip.addAll( [MASK] .ServiceLoaderFeatureExcludeServiceProviders.getValue().values());
}
@Override
public void beforeAnalysis(BeforeAnalysisAccess access) {
FeatureImpl.BeforeAnalysisAccessImpl accessImpl = (FeatureImpl.BeforeAnalysisAccessImpl) access;
accessImpl.imageClassLoader.classLoaderSupport.serviceProvidersForEach((serviceName, providers) -> {
Class<?> serviceClass = access.findClassByName(serviceName);
boolean skipService = false;
/* If the service should not end up in the image, we remove all the providers with it */
Collection<String> providersToSkip = providers;
if (servicesToSkip.contains(serviceName)) {
skipService = true;
} else if (serviceClass == null || serviceClass.isArray() || serviceClass.isPrimitive()) {
skipService = true;
} else if (!accessImpl.getHostVM().platformSupported(serviceClass)) {
skipService = true;
} else {
providersToSkip = providers.stream().filter(serviceProvidersToSkip::contains).collect(Collectors.toList());
if (!providersToSkip.isEmpty()) {
skipService = true;
}
}
if (skipService) {
ServiceCatalogSupport.singleton().removeServicesFromServicesCatalog(serviceName, new HashSet<>(providersToSkip));
return;
}
access.registerReachabilityHandler(a -> handleServiceClassIsReachable(a, serviceClass, providers), serviceClass);
});
}
void handleServiceClassIsReachable(DuringAnalysisAccess access, Class<?> serviceProvider, Collection<String> providers) {
LinkedHashSet<String> registeredProviders = new LinkedHashSet<>();
for (String provider : providers) {
if (serviceProvidersToSkip.contains(provider)) {
continue;
}
/* Make provider reflectively instantiable */
Class<?> providerClass = access.findClassByName(provider);
if (providerClass == null || providerClass.isArray() || providerClass.isPrimitive()) {
continue;
}
FeatureImpl.DuringAnalysisAccessImpl accessImpl = (FeatureImpl.DuringAnalysisAccessImpl) access;
if (!accessImpl.getHostVM().platformSupported(providerClass)) {
continue;
}
if (((Inflation) accessImpl.getBigBang()).getAnnotationSubstitutionProcessor().isDeleted(providerClass)) {
/* Disallow services with implementation classes that are marked as @Deleted */
continue;
}
/*
* Find either a public static provider() method or a nullary constructor (or both).
* Skip providers that do not comply with requirements.
*
* See ServiceLoader#loadProvider and ServiceLoader#findStaticProviderMethod.
*/
Constructor<?> nullaryConstructor = null;
Method nullaryProviderMethod = null;
try {
/* Only look for a provider() method if provider class is in an explicit module. */
if (providerClass.getModule().isNamed() && !providerClass.getModule().getDescriptor().isAutomatic()) {
for (Method method : providerClass.getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers()) &&
method.getParameterCount() == 0 && method.getName().equals("provider")) {
if (nullaryProviderMethod == null) {
nullaryProviderMethod = method;
} else {
/* There must be at most one public static provider() method. */
nullaryProviderMethod = null;
break;
}
}
}
}
Constructor<?> constructor = providerClass.getDeclaredConstructor();
if (Modifier.isPublic(constructor.getModifiers())) {
nullaryConstructor = constructor;
}
} catch (NoSuchMethodException | SecurityException | LinkageError e) {
// ignore
}
if (nullaryConstructor != null || nullaryProviderMethod != null) {
RuntimeReflection.register(providerClass);
if (nullaryConstructor != null) {
/*
* Registering a constructor with
* RuntimeReflection.registerConstructorLookup(providerClass) does not produce
* the same behavior as using RuntimeReflection.register(nullaryConstructor). In
* the first case, the constructor is marked for query purposes only, so this
* if-statement cannot be eliminated.
*
*/
RuntimeReflection.register(nullaryConstructor);
} else {
/*
* If there's no nullary constructor, register it as negative lookup to avoid
* throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerConstructorLookup(providerClass);
}
if (nullaryProviderMethod != null) {
RuntimeReflection.register(nullaryProviderMethod);
} else {
/*
* If there's no declared public provider() method, register it as negative
* lookup to avoid throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerMethodLookup(providerClass, "provider");
}
}
/*
* Register the provider in both cases: when it is JCA-compliant (has a nullary
* constructor or a provider method) or when it lacks both. If neither is present, a
* ServiceConfigurationError will be thrown at runtime, consistent with HotSpot
* behavior.
*/
registeredProviders.add(provider);
}
if (!registeredProviders.isEmpty()) {
String serviceResourceLocation = "META-INF/services/" + serviceProvider.getName();
byte[] serviceFileData = registeredProviders.stream().collect(Collectors.joining("\n")).getBytes(StandardCharsets.UTF_8);
RuntimeResourceAccess.addResource(access.getApplicationClassLoader().getUnnamedModule(), serviceResourceLocation, serviceFileData);
}
}
}
| Options |
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
*/
/*
* 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 com.sun.org.apache.xerces.internal.impl.xs;
import com.sun.org.apache.xerces.internal.impl.Constants;
import com.sun.org.apache.xerces.internal.impl.dv.SchemaDVFactory;
import com.sun.org.apache.xerces.internal.impl.dv.ValidatedInfo;
import com.sun.org.apache.xerces.internal.impl.dv.XSSimpleType;
import com.sun.org.apache.xerces.internal.impl.dv.xs.XSSimpleTypeDecl;
import com.sun.org.apache.xerces.internal.impl.xs.identity.IdentityConstraint;
import com.sun.org.apache.xerces.internal.impl.xs.util.ObjectListImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.SimpleLocator;
import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSNamedMap4Types;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSNamedMapImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSObjectListImpl;
import com.sun.org.apache.xerces.internal.parsers.DOMParser;
import com.sun.org.apache.xerces.internal.parsers.SAXParser;
import com.sun.org.apache.xerces.internal.parsers.XML11Configuration;
import com.sun.org.apache.xerces.internal.util.SymbolHash;
import com.sun.org.apache.xerces.internal.util.SymbolTable;
import com.sun.org.apache.xerces.internal.xni.NamespaceContext;
import com.sun.org.apache.xerces.internal.xni.grammars.XMLGrammarDescription;
import com.sun.org.apache.xerces.internal.xni.grammars.XSGrammar;
import com.sun.org.apache.xerces.internal.xs.StringList;
import com.sun.org.apache.xerces.internal.xs.XSAnnotation;
import com.sun.org.apache.xerces.internal.xs.XSAttributeDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSAttributeGroupDefinition;
import com.sun.org.apache.xerces.internal.xs.XSConstants;
import com.sun.org.apache.xerces.internal.xs.XSElementDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSIDCDefinition;
import com.sun.org.apache.xerces.internal.xs.XSModel;
import com.sun.org.apache.xerces.internal.xs.XSModelGroupDefinition;
import com.sun.org.apache.xerces.internal.xs.XSNamedMap;
import com.sun.org.apache.xerces.internal.xs.XSNamespaceItem;
import com.sun.org.apache.xerces.internal.xs.XSNotationDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSObjectList;
import com.sun.org.apache.xerces.internal.xs.XSParticle;
import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
import com.sun.org.apache.xerces.internal.xs.XSWildcard;
import com.sun.org.apache.xerces.internal.xs.datatypes.ObjectList;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.xml.sax.SAXException;
/**
* This class is to hold all schema component declaration that are declared
* within one namespace.
*
* The Grammar class this class extends contains what little
* commonality there is between XML Schema and DTD grammars. It's
* useful to distinguish grammar objects from other kinds of object
* when they exist in pools or caches.
*
* @xerces.internal
*
* @author Sandy Gao, IBM
* @author Elena Litani, IBM
*
* @LastModified: Oct 2017
*/
public class SchemaGrammar implements XSGrammar, XSNamespaceItem {
// the target namespace of grammar
String fTargetNamespace;
// global decls: map from decl name to decl object
SymbolHash fGlobalAttrDecls;
SymbolHash fGlobalAttrGrpDecls;
SymbolHash fGlobalElemDecls;
SymbolHash fGlobalGroupDecls;
SymbolHash fGlobalNotationDecls;
SymbolHash fGlobalIDConstraintDecls;
SymbolHash fGlobalTypeDecls;
// extended global decls: map from schema location + decl name to decl object
// key is location,name
SymbolHash fGlobalAttrDeclsExt;
SymbolHash fGlobalAttrGrpDeclsExt;
SymbolHash fGlobalElemDeclsExt;
SymbolHash fGlobalGroupDeclsExt;
SymbolHash fGlobalNotationDeclsExt;
SymbolHash fGlobalIDConstraintDeclsExt;
SymbolHash fGlobalTypeDeclsExt;
// A global map of all global element declarations - used for substitution group computation
// (handy when sharing components by reference, since we might end up with duplicate components
// that are not added to either of the global element declarations above)
SymbolHash fAllGlobalElemDecls;
// the XMLGrammarDescription member
XSDDescription fGrammarDescription = null;
// annotations associated with the "root" schema of this targetNamespace
XSAnnotationImpl [] fAnnotations = null;
// number of annotations declared
int fNumAnnotations;
// symbol table for constructing parsers (annotation support)
private SymbolTable fSymbolTable = null;
// parsers for annotation support
private SoftReference<SAXParser> fSAXParser = null;
private SoftReference<DOMParser> fDOMParser = null;
// is this grammar immutable? (fully constructed and not changeable)
private boolean fIsImmutable = false;
//
// Constructors
//
// needed to make BuiltinSchemaGrammar work.
protected SchemaGrammar() {}
/**
* Default constructor.
*
* @param targetNamespace
* @param grammarDesc the XMLGrammarDescription corresponding to this object
* at the least a systemId should always be known.
* @param symbolTable needed for annotation support
*/
public SchemaGrammar(String targetNamespace, XSDDescription grammarDesc,
SymbolTable symbolTable) {
fTargetNamespace = targetNamespace;
fGrammarDescription = grammarDesc;
fSymbolTable = symbolTable;
// REVISIT: the initial sizes being chosen for each SymbolHash
// may not be ideal and could still be tuned. They were chosen
// somewhat arbitrarily to reduce the initial footprint of
// SymbolHash buckets from 1,515 to 177 (about 12% of the
// default size).
fGlobalAttrDecls = new SymbolHash(12);
fGlobalAttrGrpDecls = new SymbolHash(5);
fGlobalElemDecls = new SymbolHash(25);
fGlobalGroupDecls = new SymbolHash(5);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(3);
// Extended tables
fGlobalAttrDeclsExt = new SymbolHash(12);
fGlobalAttrGrpDeclsExt = new SymbolHash(5);
fGlobalElemDeclsExt = new SymbolHash(25);
fGlobalGroupDeclsExt = new SymbolHash(5);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(3);
fGlobalTypeDeclsExt = new SymbolHash(25);
// All global elements table
fAllGlobalElemDecls = new SymbolHash(25);
// if we are parsing S4S, put built-in types in first
// they might get overwritten by the types from S4S, but that's
// considered what the application wants to do.
if (fTargetNamespace == SchemaSymbols.URI_SCHEMAFORSCHEMA) {
fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls.makeClone();
}
else {
fGlobalTypeDecls = new SymbolHash(25);
}
} // <init>(String, XSDDescription)
// Clone an existing schema grammar
public SchemaGrammar(SchemaGrammar grammar) {
fTargetNamespace = grammar.fTargetNamespace;
fGrammarDescription = grammar.fGrammarDescription.makeClone();
//fGrammarDescription.fContextType |= XSDDescription.CONTEXT_COLLISION; // REVISIT
fSymbolTable = grammar.fSymbolTable; // REVISIT
fGlobalAttrDecls = grammar.fGlobalAttrDecls.makeClone();
fGlobalAttrGrpDecls = grammar.fGlobalAttrGrpDecls.makeClone();
fGlobalElemDecls = grammar.fGlobalElemDecls.makeClone();
fGlobalGroupDecls = grammar.fGlobalGroupDecls.makeClone();
fGlobalNotationDecls = grammar.fGlobalNotationDecls.makeClone();
fGlobalIDConstraintDecls = grammar.fGlobalIDConstraintDecls.makeClone();
fGlobalTypeDecls = grammar.fGlobalTypeDecls.makeClone();
// Extended tables
fGlobalAttrDeclsExt = grammar.fGlobalAttrDeclsExt.makeClone();
fGlobalAttrGrpDeclsExt = grammar.fGlobalAttrGrpDeclsExt.makeClone();
fGlobalElemDeclsExt = grammar.fGlobalElemDeclsExt.makeClone();
fGlobalGroupDeclsExt = grammar.fGlobalGroupDeclsExt.makeClone();
fGlobalNotationDeclsExt = grammar.fGlobalNotationDeclsExt.makeClone();
fGlobalIDConstraintDeclsExt = grammar.fGlobalIDConstraintDeclsExt.makeClone();
fGlobalTypeDeclsExt = grammar.fGlobalTypeDeclsExt.makeClone();
// All global elements table
fAllGlobalElemDecls = grammar.fAllGlobalElemDecls.makeClone();
// Annotations associated with the "root" schema of this targetNamespace
fNumAnnotations = grammar.fNumAnnotations;
if (fNumAnnotations > 0) {
fAnnotations = new XSAnnotationImpl[grammar.fAnnotations.length];
System.arraycopy(grammar.fAnnotations, 0, fAnnotations, 0, fNumAnnotations);
}
// All substitution group information declared in this namespace
fSubGroupCount = grammar.fSubGroupCount;
if (fSubGroupCount > 0) {
fSubGroups = new XSElementDecl[grammar.fSubGroups.length];
System.arraycopy(grammar.fSubGroups, 0, fSubGroups, 0, fSubGroupCount);
}
// Array to store complex type decls for constraint checking
fCTCount = grammar.fCTCount;
if (fCTCount > 0) {
fComplexTypeDecls = new XSComplexTypeDecl[grammar.fComplexTypeDecls.length];
fCTLocators = new SimpleLocator[grammar.fCTLocators.length];
System.arraycopy(grammar.fComplexTypeDecls, 0, fComplexTypeDecls, 0, fCTCount);
System.arraycopy(grammar.fCTLocators, 0, fCTLocators, 0, fCTCount);
}
// Groups being redefined by restriction
fRGCount = grammar.fRGCount;
if (fRGCount > 0) {
fRedefinedGroupDecls = new XSGroupDecl[grammar.fRedefinedGroupDecls.length];
fRGLocators = new SimpleLocator[grammar.fRGLocators.length];
System.arraycopy(grammar.fRedefinedGroupDecls, 0, fRedefinedGroupDecls, 0, fRGCount);
System.arraycopy(grammar.fRGLocators, 0, fRGLocators, 0, fRGCount/2);
}
// List of imported grammars
if (grammar.fImported != null) {
fImported = new ArrayList<>();
for (int i=0; i<grammar.fImported.size(); i++) {
fImported.add(grammar.fImported.get(i));
}
}
// Locations
if (grammar.fLocations != null) {
for (int k=0; k<grammar.fLocations.size(); k++) {
addDocument(null, grammar.fLocations.get(k));
}
}
} // <init>(String, XSDDescription)
// number of built-in XSTypes we need to create for base and full
// datatype set
private static final int BASICSET_COUNT = 29;
private static final int FULLSET_COUNT = 46;
private static final int GRAMMAR_XS = 1;
private static final int GRAMMAR_XSI = 2;
// this class makes sure the static, built-in schema grammars
// are immutable.
public static class BuiltinSchemaGrammar extends SchemaGrammar {
private static final String EXTENDED_SCHEMA_FACTORY_CLASS = "com.sun.org.apache.xerces.internal.impl.dv.xs.ExtendedSchemaDVFactoryImpl";
/**
* Special constructor to create the grammars for the schema namespaces
*
* @param grammar
*/
public BuiltinSchemaGrammar(int grammar, short schemaVersion) {
SchemaDVFactory schemaFactory;
if (schemaVersion == Constants.SCHEMA_VERSION_1_0) {
schemaFactory = SchemaDVFactory.getInstance();
}
else {
schemaFactory = SchemaDVFactory.getInstance(EXTENDED_SCHEMA_FACTORY_CLASS);
}
if (grammar == GRAMMAR_XS) {
// target namespace
fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA);
// no global decls other than types
fGlobalAttrDecls = new SymbolHash(1);
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(1);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(1);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// all global element decls table
fAllGlobalElemDecls = new SymbolHash(1);
// get all built-in types
fGlobalTypeDecls = schemaFactory.getBuiltInTypes();
// assign the built-in schema grammar as the XSNamespaceItem
// for each of the built-in simple type definitions.
int length = fGlobalTypeDecls.getLength();
XSTypeDefinition [] typeDefinitions = new XSTypeDefinition[length];
fGlobalTypeDecls.getValues(typeDefinitions, 0);
for (int i = 0; i < length; ++i) {
XSTypeDefinition xtd = typeDefinitions[i];
if (xtd instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) xtd).setNamespaceItem(this);
}
}
// add anyType
fGlobalTypeDecls.put(fAnyType.getName(), fAnyType);
}
else if (grammar == GRAMMAR_XSI) {
// target namespace
fTargetNamespace = SchemaSymbols.URI_XSI;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_XSI);
// no global decls other than attributes
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(1);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
fGlobalTypeDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(1);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// no all global element decls
fAllGlobalElemDecls = new SymbolHash(1);
// 4 attributes, so initialize the size as 4*2 = 8
fGlobalAttrDecls = new SymbolHash(8);
String name = null;
String tns = null;
XSSimpleType type = null;
short scope = XSConstants.SCOPE_GLOBAL;
// xsi:type
name = SchemaSymbols.XSI_TYPE;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_QNAME);
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
// xsi:nil
name = SchemaSymbols.XSI_NIL;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_BOOLEAN);
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
XSSimpleType anyURI = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_ANYURI);
// xsi:schemaLocation
name = SchemaSymbols.XSI_SCHEMALOCATION;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.createTypeList("#AnonType_schemaLocation", SchemaSymbols.URI_XSI, (short)0, anyURI, null);
if (type instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl)type).setAnonymous(true);
}
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
// xsi:noNamespaceSchemaLocation
name = SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION;
tns = SchemaSymbols.URI_XSI;
type = anyURI;
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
}
} // <init>(int)
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription.makeClone();
} // getGrammarDescription(): XMLGrammarDescription
// override these methods solely so that these
// objects cannot be modified once they're created.
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl, String location) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
// ignore
}
public void addGlobalElementDeclAll(XSElementDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
// ignore
}
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
// ignore
}
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
// ignore
}
public synchronized void addDocument(Object document, String location) {
// ignore
}
// annotation support
synchronized DOMParser getDOMParser() {
return null;
}
synchronized SAXParser getSAXParser() {
return null;
}
}
/**
* <p>A partial schema for schemas for validating annotations.</p>
*
* @xerces.internal
*
* @author Michael Glavassevich, IBM
*/
public static final class Schema4Annotations extends SchemaGrammar {
/**
* Singleton instance.
*/
public static final Schema4Annotations INSTANCE = new Schema4Annotations();
/**
* Special constructor to create a schema
* capable of validating annotations.
*/
private Schema4Annotations() {
// target namespace
fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA);
// no global decls other than types and
// element declarations for <annotation>, <documentation> and <appinfo>.
fGlobalAttrDecls = new SymbolHash(1);
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(6);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(6);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// all global element declarations
fAllGlobalElemDecls = new SymbolHash(6);
// get all built-in types
fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls;
// create element declarations for <annotation>, <documentation> and <appinfo>
XSElementDecl annotationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_ANNOTATION);
XSElementDecl documentationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_DOCUMENTATION);
XSElementDecl appinfoDecl = createAnnotationElementDecl(SchemaSymbols.ELT_APPINFO);
// add global element declarations
fGlobalElemDecls.put(annotationDecl.fName, annotationDecl);
fGlobalElemDecls.put(documentationDecl.fName, documentationDecl);
fGlobalElemDecls.put(appinfoDecl.fName, appinfoDecl);
fGlobalElemDeclsExt.put(","+annotationDecl.fName, annotationDecl);
fGlobalElemDeclsExt.put(","+documentationDecl.fName, documentationDecl);
fGlobalElemDeclsExt.put(","+appinfoDecl.fName, appinfoDecl);
fAllGlobalElemDecls.put(annotationDecl, annotationDecl);
fAllGlobalElemDecls.put(documentationDecl, documentationDecl);
fAllGlobalElemDecls.put(appinfoDecl, appinfoDecl);
// create complex type declarations for <annotation>, <documentation> and <appinfo>
XSComplexTypeDecl annotationType = new XSComplexTypeDecl();
XSComplexTypeDecl documentationType = new XSComplexTypeDecl();
XSComplexTypeDecl appinfoType = new XSComplexTypeDecl();
// set the types on their element declarations
annotationDecl.fType = annotationType;
documentationDecl.fType = documentationType;
appinfoDecl.fType = appinfoType;
// create attribute groups for <annotation>, <documentation> and <appinfo>
XSAttributeGroupDecl annotationAttrs = new XSAttributeGroupDecl();
XSAttributeGroupDecl documentationAttrs = new XSAttributeGroupDecl();
XSAttributeGroupDecl appinfoAttrs = new XSAttributeGroupDecl();
// fill in attribute groups
{
// create and fill attribute uses for <annotation>, <documentation> and <appinfo>
XSAttributeUseImpl annotationIDAttr = new XSAttributeUseImpl();
annotationIDAttr.fAttrDecl = new XSAttributeDecl();
annotationIDAttr.fAttrDecl.setValues(SchemaSymbols.ATT_ID, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ID),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, annotationType, null);
annotationIDAttr.fUse = SchemaSymbols.USE_OPTIONAL;
annotationIDAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl documentationSourceAttr = new XSAttributeUseImpl();
documentationSourceAttr.fAttrDecl = new XSAttributeDecl();
documentationSourceAttr.fAttrDecl.setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ANYURI),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, documentationType, null);
documentationSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL;
documentationSourceAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl documentationLangAttr = new XSAttributeUseImpl();
documentationLangAttr.fAttrDecl = new XSAttributeDecl();
documentationLangAttr.fAttrDecl.setValues("lang".intern(), NamespaceContext.XML_URI, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_LANGUAGE),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, documentationType, null);
documentationLangAttr.fUse = SchemaSymbols.USE_OPTIONAL;
documentationLangAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl appinfoSourceAttr = new XSAttributeUseImpl();
appinfoSourceAttr.fAttrDecl = new XSAttributeDecl();
appinfoSourceAttr.fAttrDecl.setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ANYURI),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, appinfoType, null);
appinfoSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL;
appinfoSourceAttr.fConstraintType = XSConstants.VC_NONE;
// create lax attribute wildcard for <annotation>, <documentation> and <appinfo>
XSWildcardDecl otherAttrs = new XSWildcardDecl();
otherAttrs.fNamespaceList = new String [] {fTargetNamespace, null};
otherAttrs.fType = XSWildcard.NSCONSTRAINT_NOT;
otherAttrs.fProcessContents = XSWildcard.PC_LAX;
// add attribute uses and wildcards to attribute groups for <annotation>, <documentation> and <appinfo>
annotationAttrs.addAttributeUse(annotationIDAttr);
annotationAttrs.fAttributeWC = otherAttrs;
documentationAttrs.addAttributeUse(documentationSourceAttr);
documentationAttrs.addAttributeUse(documentationLangAttr);
documentationAttrs.fAttributeWC = otherAttrs;
appinfoAttrs.addAttributeUse(appinfoSourceAttr);
appinfoAttrs.fAttributeWC = otherAttrs;
}
// create particles for <annotation>
XSParticleDecl annotationParticle = createUnboundedModelGroupParticle();
{
XSModelGroupImpl annotationChoice = new XSModelGroupImpl();
annotationChoice.fCompositor = XSModelGroupImpl.MODELGROUP_CHOICE;
annotationChoice.fParticleCount = 2;
annotationChoice. [MASK] = new XSParticleDecl[2];
annotationChoice. [MASK] [0] = createChoiceElementParticle(appinfoDecl);
annotationChoice. [MASK] [1] = createChoiceElementParticle(documentationDecl);
annotationParticle.fValue = annotationChoice;
}
// create wildcard particle for <documentation> and <appinfo>
XSParticleDecl anyWCSequenceParticle = createUnboundedAnyWildcardSequenceParticle();
// fill complex types
annotationType.setValues("#AnonType_" + SchemaSymbols.ELT_ANNOTATION, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_ELEMENT, false, annotationAttrs, null, annotationParticle, XSObjectListImpl.EMPTY_LIST);
annotationType.setName("#AnonType_" + SchemaSymbols.ELT_ANNOTATION);
annotationType.setIsAnonymous();
documentationType.setValues("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_MIXED, false, documentationAttrs, null, anyWCSequenceParticle, XSObjectListImpl.EMPTY_LIST);
documentationType.setName("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION);
documentationType.setIsAnonymous();
appinfoType.setValues("#AnonType_" + SchemaSymbols.ELT_APPINFO, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_MIXED, false, appinfoAttrs, null, anyWCSequenceParticle, XSObjectListImpl.EMPTY_LIST);
appinfoType.setName("#AnonType_" + SchemaSymbols.ELT_APPINFO);
appinfoType.setIsAnonymous();
} // <init>(int)
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription.makeClone();
} // getGrammarDescription(): XMLGrammarDescription
// override these methods solely so that these
// objects cannot be modified once they're created.
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
// ignore
}
public void addGlobalElementDeclAll(XSElementDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
// ignore
}
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
// ignore
}
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
// ignore
}
public synchronized void addDocument(Object document, String location) {
// ignore
}
// annotation support
synchronized DOMParser getDOMParser() {
return null;
}
synchronized SAXParser getSAXParser() {
return null;
}
//
// private helper methods
//
private XSElementDecl createAnnotationElementDecl(String localName) {
XSElementDecl eDecl = new XSElementDecl();
eDecl.fName = localName;
eDecl.fTargetNamespace = fTargetNamespace;
eDecl.setIsGlobal();
eDecl.fBlock = (XSConstants.DERIVATION_EXTENSION |
XSConstants.DERIVATION_RESTRICTION | XSConstants.DERIVATION_SUBSTITUTION);
eDecl.setConstraintType(XSConstants.VC_NONE);
return eDecl;
}
private XSParticleDecl createUnboundedModelGroupParticle() {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 0;
particle.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED;
particle.fType = XSParticleDecl.PARTICLE_MODELGROUP;
return particle;
}
private XSParticleDecl createChoiceElementParticle(XSElementDecl ref) {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 1;
particle.fMaxOccurs = 1;
particle.fType = XSParticleDecl.PARTICLE_ELEMENT;
particle.fValue = ref;
return particle;
}
private XSParticleDecl createUnboundedAnyWildcardSequenceParticle() {
XSParticleDecl particle = createUnboundedModelGroupParticle();
XSModelGroupImpl sequence = new XSModelGroupImpl();
sequence.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE;
sequence.fParticleCount = 1;
sequence. [MASK] = new XSParticleDecl[1];
sequence. [MASK] [0] = createAnyLaxWildcardParticle();
particle.fValue = sequence;
return particle;
}
private XSParticleDecl createAnyLaxWildcardParticle() {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 1;
particle.fMaxOccurs = 1;
particle.fType = XSParticleDecl.PARTICLE_WILDCARD;
XSWildcardDecl anyWC = new XSWildcardDecl();
anyWC.fNamespaceList = null;
anyWC.fType = XSWildcard.NSCONSTRAINT_ANY;
anyWC.fProcessContents = XSWildcard.PC_LAX;
particle.fValue = anyWC;
return particle;
}
}
// Grammar methods
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription;
} // getGrammarDescription(): XMLGrammarDescription
// DTDGrammar methods
public boolean isNamespaceAware () {
return true;
} // isNamespaceAware():boolean
List<SchemaGrammar> fImported = null;
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
fImported = importedGrammars;
}
public List<SchemaGrammar> getImportedGrammars() {
return fImported;
}
/**
* Returns this grammar's target namespace.
*/
public final String getTargetNamespace() {
return fTargetNamespace;
} // getTargetNamespace():String
/**
* register one global attribute
*/
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
fGlobalAttrDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalAttributeDecl(XSAttributeDecl decl, String location) {
fGlobalAttrDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global attribute group
*/
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
fGlobalAttrGrpDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
fGlobalAttrGrpDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global element
*/
public void addGlobalElementDeclAll(XSElementDecl decl) {
if (fAllGlobalElemDecls.get(decl) == null) {
fAllGlobalElemDecls.put(decl, decl);
// if there is a substitution group affiliation, store in an array,
// for further constraint checking: UPA, PD, EDC
if (decl.fSubGroup != null) {
if (fSubGroupCount == fSubGroups.length)
fSubGroups = resize(fSubGroups, fSubGroupCount+INC_SIZE);
fSubGroups[fSubGroupCount++] = decl;
}
}
}
public void addGlobalElementDecl(XSElementDecl decl) {
fGlobalElemDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
fGlobalElemDeclsExt.put(((location != null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global group
*/
public void addGlobalGroupDecl(XSGroupDecl decl) {
fGlobalGroupDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
fGlobalGroupDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global notation
*/
public void addGlobalNotationDecl(XSNotationDecl decl) {
fGlobalNotationDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
fGlobalNotationDeclsExt.put(((location!=null) ? location : "") + "," +decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global type
*/
public void addGlobalTypeDecl(XSTypeDefinition decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
if (decl instanceof XSComplexTypeDecl) {
((XSComplexTypeDecl) decl).setNamespaceItem(this);
}
else if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
fGlobalTypeDeclsExt.put(((location!=null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null) {
if (decl instanceof XSComplexTypeDecl) {
((XSComplexTypeDecl) decl).setNamespaceItem(this);
}
else if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
}
/**
* register one global complex type
*/
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
decl.setNamespaceItem(this);
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
fGlobalTypeDeclsExt.put(((location!=null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global simple type
*/
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
fGlobalTypeDeclsExt.put(((location != null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null && decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
/**
* register one identity constraint
*/
public final void addIDConstraintDecl(XSElementDecl elmDecl, IdentityConstraint decl) {
elmDecl.addIDConstraint(decl);
fGlobalIDConstraintDecls.put(decl.getIdentityConstraintName(), decl);
}
public final void addIDConstraintDecl(XSElementDecl elmDecl, IdentityConstraint decl, String location) {
fGlobalIDConstraintDeclsExt.put(((location != null) ? location : "") + "," + decl.getIdentityConstraintName(), decl);
}
/**
* get one global attribute
*/
public final XSAttributeDecl getGlobalAttributeDecl(String declName) {
return(XSAttributeDecl)fGlobalAttrDecls.get(declName);
}
public final XSAttributeDecl getGlobalAttributeDecl(String declName, String location) {
return(XSAttributeDecl)fGlobalAttrDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global attribute group
*/
public final XSAttributeGroupDecl getGlobalAttributeGroupDecl(String declName) {
return(XSAttributeGroupDecl)fGlobalAttrGrpDecls.get(declName);
}
public final XSAttributeGroupDecl getGlobalAttributeGroupDecl(String declName, String location) {
return(XSAttributeGroupDecl)fGlobalAttrGrpDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global element
*/
public final XSElementDecl getGlobalElementDecl(String declName) {
return(XSElementDecl)fGlobalElemDecls.get(declName);
}
public final XSElementDecl getGlobalElementDecl(String declName, String location) {
return(XSElementDecl)fGlobalElemDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global group
*/
public final XSGroupDecl getGlobalGroupDecl(String declName) {
return(XSGroupDecl)fGlobalGroupDecls.get(declName);
}
public final XSGroupDecl getGlobalGroupDecl(String declName, String location) {
return(XSGroupDecl)fGlobalGroupDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global notation
*/
public final XSNotationDecl getGlobalNotationDecl(String declName) {
return(XSNotationDecl)fGlobalNotationDecls.get(declName);
}
public final XSNotationDecl getGlobalNotationDecl(String declName, String location) {
return(XSNotationDecl)fGlobalNotationDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global type
*/
public final XSTypeDefinition getGlobalTypeDecl(String declName) {
return(XSTypeDefinition)fGlobalTypeDecls.get(declName);
}
public final XSTypeDefinition getGlobalTypeDecl(String declName, String location) {
return(XSTypeDefinition)fGlobalTypeDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one identity constraint
*/
public final IdentityConstraint getIDConstraintDecl(String declName) {
return(IdentityConstraint)fGlobalIDConstraintDecls.get(declName);
}
public final IdentityConstraint getIDConstraintDecl(String declName, String location) {
return(IdentityConstraint)fGlobalIDConstraintDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one identity constraint
*/
public final boolean hasIDConstraints() {
return fGlobalIDConstraintDecls.getLength() > 0;
}
// array to store complex type decls
private static final int INITIAL_SIZE = 16;
private static final int INC_SIZE = 16;
private int fCTCount = 0;
private XSComplexTypeDecl[] fComplexTypeDecls = new XSComplexTypeDecl[INITIAL_SIZE];
private SimpleLocator[] fCTLocators = new SimpleLocator[INITIAL_SIZE];
// an array to store groups being redefined by restriction
// even-numbered elements are the derived groups, odd-numbered ones their bases
private static final int REDEFINED_GROUP_INIT_SIZE = 2;
private int fRGCount = 0;
private XSGroupDecl[] fRedefinedGroupDecls = new XSGroupDecl[REDEFINED_GROUP_INIT_SIZE];
private SimpleLocator[] fRGLocators = new SimpleLocator[REDEFINED_GROUP_INIT_SIZE/2];
// a flag to indicate whether we have checked the 3 constraints on this
// grammar.
boolean fFullChecked = false;
/**
* add one complex type decl: for later constraint checking
*/
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
if (fCTCount == fComplexTypeDecls.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount+INC_SIZE);
fCTLocators = resize(fCTLocators, fCTCount+INC_SIZE);
}
fCTLocators[fCTCount] = locator;
fComplexTypeDecls[fCTCount++] = decl;
}
/**
* add a group redefined by restriction: for later constraint checking
*/
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
if (fRGCount == fRedefinedGroupDecls.length) {
// double array size each time.
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount << 1);
fRGLocators = resize(fRGLocators, fRGCount);
}
fRGLocators[fRGCount/2] = locator;
fRedefinedGroupDecls[fRGCount++] = derived;
fRedefinedGroupDecls[fRGCount++] = base;
}
/**
* get all complex type decls: for later constraint checking
*/
final XSComplexTypeDecl[] getUncheckedComplexTypeDecls() {
if (fCTCount < fComplexTypeDecls.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
return fComplexTypeDecls;
}
/**
* get the error locator of all complex type decls
*/
final SimpleLocator[] getUncheckedCTLocators() {
if (fCTCount < fCTLocators.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
return fCTLocators;
}
/**
* get all redefined groups: for later constraint checking
*/
final XSGroupDecl[] getRedefinedGroupDecls() {
if (fRGCount < fRedefinedGroupDecls.length) {
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount);
fRGLocators = resize(fRGLocators, fRGCount/2);
}
return fRedefinedGroupDecls;
}
/**
* get the error locator of all redefined groups
*/
final SimpleLocator[] getRGLocators() {
if (fRGCount < fRedefinedGroupDecls.length) {
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount);
fRGLocators = resize(fRGLocators, fRGCount/2);
}
return fRGLocators;
}
/**
* after the first-round checking, some types don't need to be checked
* against UPA again. here we trim the array to the proper size.
*/
final void setUncheckedTypeNum(int newSize) {
fCTCount = newSize;
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
// used to store all substitution group information declared in
// this namespace
private int fSubGroupCount = 0;
private XSElementDecl[] fSubGroups = new XSElementDecl[INITIAL_SIZE];
/**
* get all substitution group information: for the 3 constraint checking
*/
final XSElementDecl[] getSubstitutionGroups() {
if (fSubGroupCount < fSubGroups.length)
fSubGroups = resize(fSubGroups, fSubGroupCount);
return fSubGroups;
}
// anyType and anySimpleType: because there are so many places where
// we need direct access to these two types
public final static XSComplexTypeDecl fAnyType = new XSAnyType();
private static class XSAnyType extends XSComplexTypeDecl {
public XSAnyType () {
fName = SchemaSymbols.ATTVAL_ANYTYPE;
super.fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
fBaseType = this;
fDerivedBy = XSConstants.DERIVATION_RESTRICTION;
fContentType = XSComplexTypeDecl.CONTENTTYPE_MIXED;
fParticle = createParticle();
fAttrGrp = createAttrGrp();
}
// overridden methods
public void setValues(String name, String targetNamespace,
XSTypeDefinition baseType, short derivedBy, short schemaFinal,
short block, short contentType,
boolean isAbstract, XSAttributeGroupDecl attrGrp,
XSSimpleType simpleType, XSParticleDecl particle) {
// don't allow this.
}
public void setName(String name){
// don't allow this.
}
public void setIsAbstractType() {
// null implementation
}
public void setContainsTypeID() {
// null implementation
}
public void setIsAnonymous() {
// null implementation
}
public void reset() {
// null implementation
}
public XSObjectList getAnnotations() {
return XSObjectListImpl.EMPTY_LIST;
}
public XSNamespaceItem getNamespaceItem() {
return SG_SchemaNS;
}
private XSAttributeGroupDecl createAttrGrp() {
XSWildcardDecl wildcard = new XSWildcardDecl();
wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
XSAttributeGroupDecl attrGrp = new XSAttributeGroupDecl();
attrGrp.fAttributeWC = wildcard;
return attrGrp;
}
private XSParticleDecl createParticle() {
// the wildcard used in anyType (content and attribute)
// the spec will change strict to skip for anyType
XSWildcardDecl wildcard = new XSWildcardDecl();
wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
// the particle for the content wildcard
XSParticleDecl particleW = new XSParticleDecl();
particleW.fMinOccurs = 0;
particleW.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED;
particleW.fType = XSParticleDecl.PARTICLE_WILDCARD;
particleW.fValue = wildcard;
// the model group of a sequence of the above particle
XSModelGroupImpl group = new XSModelGroupImpl();
group.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE;
group.fParticleCount = 1;
group. [MASK] = new XSParticleDecl[1];
group. [MASK] [0] = particleW;
// the content of anyType: particle of the above model group
XSParticleDecl particleG = new XSParticleDecl();
particleG.fType = XSParticleDecl.PARTICLE_MODELGROUP;
particleG.fValue = group;
return particleG;
}
}
private static class BuiltinAttrDecl extends XSAttributeDecl {
public BuiltinAttrDecl(String name, String tns,
XSSimpleType type, short scope) {
fName = name;
super.fTargetNamespace = tns;
fType = type;
fScope = scope;
}
public void setValues(String name, String targetNamespace,
XSSimpleType simpleType, short constraintType, short scope,
ValidatedInfo valInfo, XSComplexTypeDecl enclosingCT) {
// ignore this call.
}
public void reset () {
// also ignore this call.
}
public XSAnnotation getAnnotation() {
return null;
}
public XSNamespaceItem getNamespaceItem() {
return SG_XSI;
}
} // class BuiltinAttrDecl
// the grammars to hold components of the schema namespace
public final static BuiltinSchemaGrammar SG_SchemaNS = new BuiltinSchemaGrammar(GRAMMAR_XS, Constants.SCHEMA_VERSION_1_0);
private final static BuiltinSchemaGrammar SG_SchemaNSExtended = new BuiltinSchemaGrammar(GRAMMAR_XS, Constants.SCHEMA_VERSION_1_0_EXTENDED);
public final static XSSimpleType fAnySimpleType = (XSSimpleType)SG_SchemaNS.getGlobalTypeDecl(SchemaSymbols.ATTVAL_ANYSIMPLETYPE);
// the grammars to hold components of the schema-instance namespace
public final static BuiltinSchemaGrammar SG_XSI = new BuiltinSchemaGrammar(GRAMMAR_XSI, Constants.SCHEMA_VERSION_1_0);
public static SchemaGrammar getS4SGrammar(short schemaVersion) {
if (schemaVersion == Constants.SCHEMA_VERSION_1_0) {
return SG_SchemaNS;
}
else {
return SG_SchemaNSExtended;
}
}
static final XSComplexTypeDecl[] resize(XSComplexTypeDecl[] oldArray, int newSize) {
XSComplexTypeDecl[] newArray = new XSComplexTypeDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final XSGroupDecl[] resize(XSGroupDecl[] oldArray, int newSize) {
XSGroupDecl[] newArray = new XSGroupDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final XSElementDecl[] resize(XSElementDecl[] oldArray, int newSize) {
XSElementDecl[] newArray = new XSElementDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final SimpleLocator[] resize(SimpleLocator[] oldArray, int newSize) {
SimpleLocator[] newArray = new SimpleLocator[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
// XSNamespaceItem methods
// the max index / the max value of XSObject type
private static final short MAX_COMP_IDX = XSTypeDefinition.SIMPLE_TYPE;
private static final boolean[] GLOBAL_COMP = {false, // null
true, // attribute
true, // element
true, // type
false, // attribute use
true, // attribute group
true, // group
false, // model group
false, // particle
false, // wildcard
true, // idc
true, // notation
false, // annotation
false, // facet
false, // multi value facet
true, // complex type
true // simple type
};
// store a certain kind of components from all namespaces
private XSNamedMap[] fComponents = null;
private ObjectList[] fComponentsExt = null;
// store the documents and their locations contributing to this namespace
// REVISIT: use StringList and XSObjectList for there fields.
// fDocuments is never used
private List<Object> fDocuments = null;
private List<String> fLocations = null;
public synchronized void addDocument(Object document, String location) {
if (fDocuments == null) {
// Parsing schema is not thread safe, synchronized may be removed
fDocuments = new CopyOnWriteArrayList<>();
fLocations = new CopyOnWriteArrayList<>();
}
fDocuments.add(document);
fLocations.add(location);
}
public synchronized void removeDocument(int index) {
if (fDocuments != null &&
index >= 0 &&
index < fDocuments.size()) {
fDocuments.remove(index);
fLocations.remove(index);
}
}
/**
* [schema namespace]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#nsi-schema_namespace">[schema namespace]</a>
* @return The target namespace of this item.
*/
public String getSchemaNamespace() {
return fTargetNamespace;
}
// annotation support
synchronized DOMParser getDOMParser() {
if (fDOMParser != null) {
DOMParser parser = fDOMParser.get();
if (parser != null) {
return parser;
}
}
// REVISIT: when schema handles XML 1.1, will need to
// revisit this (and the practice of not prepending an XML decl to the annotation string
XML11Configuration config = new XML11Configuration(fSymbolTable);
// note that this should never produce errors or require
// entity resolution, so just a barebones configuration with
// a couple of feature set will do fine
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true);
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false);
DOMParser parser = new DOMParser(config);
try {
parser.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.DEFER_NODE_EXPANSION_FEATURE, false);
}
catch (SAXException exc) {}
fDOMParser = new SoftReference<DOMParser>(parser);
return parser;
}
synchronized SAXParser getSAXParser() {
if (fSAXParser != null) {
SAXParser parser = fSAXParser.get();
if (parser != null) {
return parser;
}
}
// REVISIT: when schema handles XML 1.1, will need to
// revisit this (and the practice of not prepending an XML decl to the annotation string
XML11Configuration config = new XML11Configuration(fSymbolTable);
// note that this should never produce errors or require
// entity resolution, so just a barebones configuration with
// a couple of feature set will do fine
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true);
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false);
SAXParser parser = new SAXParser(config);
fSAXParser = new SoftReference<SAXParser>(parser);
return parser;
}
/**
* [schema components]: a list of top-level components, i.e. element
* declarations, attribute declarations, etc.
* @param objectType The type of the declaration, i.e.
* <code>ELEMENT_DECLARATION</code>. Note that
* <code>XSTypeDefinition.SIMPLE_TYPE</code> and
* <code>XSTypeDefinition.COMPLEX_TYPE</code> can also be used as the
* <code>objectType</code> to retrieve only complex types or simple
* types, instead of all types.
* @return A list of top-level definition of the specified type in
* <code>objectType</code> or an empty <code>XSNamedMap</code> if no
* such definitions exist.
*/
public synchronized XSNamedMap getComponents(short objectType) {
if (objectType <= 0 || objectType > MAX_COMP_IDX ||
!GLOBAL_COMP[objectType]) {
return XSNamedMapImpl.EMPTY_MAP;
}
if (fComponents == null)
fComponents = new XSNamedMap[MAX_COMP_IDX+1];
// get the hashtable for this type of components
if (fComponents[objectType] == null) {
SymbolHash table = null;
switch (objectType) {
case XSConstants.TYPE_DEFINITION:
case XSTypeDefinition.COMPLEX_TYPE:
case XSTypeDefinition.SIMPLE_TYPE:
table = fGlobalTypeDecls;
break;
case XSConstants.ATTRIBUTE_DECLARATION:
table = fGlobalAttrDecls;
break;
case XSConstants.ELEMENT_DECLARATION:
table = fGlobalElemDecls;
break;
case XSConstants.ATTRIBUTE_GROUP:
table = fGlobalAttrGrpDecls;
break;
case XSConstants.MODEL_GROUP_DEFINITION:
table = fGlobalGroupDecls;
break;
case XSConstants.NOTATION_DECLARATION:
table = fGlobalNotationDecls;
break;
case XSConstants.IDENTITY_CONSTRAINT:
table = this.fGlobalIDConstraintDecls;
break;
}
// for complex/simple types, create a special implementation,
// which take specific types out of the hash table
if (objectType == XSTypeDefinition.COMPLEX_TYPE ||
objectType == XSTypeDefinition.SIMPLE_TYPE) {
fComponents[objectType] = new XSNamedMap4Types(fTargetNamespace, table, objectType);
}
else {
fComponents[objectType] = new XSNamedMapImpl(fTargetNamespace, table);
}
}
return fComponents[objectType];
}
public synchronized ObjectList getComponentsExt(short objectType) {
if (objectType <= 0 || objectType > MAX_COMP_IDX ||
!GLOBAL_COMP[objectType]) {
return ObjectListImpl.EMPTY_LIST;
}
if (fComponentsExt == null)
fComponentsExt = new ObjectList[MAX_COMP_IDX+1];
// get the hashtable for this type of components
if (fComponentsExt[objectType] == null) {
SymbolHash table = null;
switch (objectType) {
case XSConstants.TYPE_DEFINITION:
case XSTypeDefinition.COMPLEX_TYPE:
case XSTypeDefinition.SIMPLE_TYPE:
table = fGlobalTypeDeclsExt;
break;
case XSConstants.ATTRIBUTE_DECLARATION:
table = fGlobalAttrDeclsExt;
break;
case XSConstants.ELEMENT_DECLARATION:
table = fGlobalElemDeclsExt;
break;
case XSConstants.ATTRIBUTE_GROUP:
table = fGlobalAttrGrpDeclsExt;
break;
case XSConstants.MODEL_GROUP_DEFINITION:
table = fGlobalGroupDeclsExt;
break;
case XSConstants.NOTATION_DECLARATION:
table = fGlobalNotationDeclsExt;
break;
case XSConstants.IDENTITY_CONSTRAINT:
table = this.fGlobalIDConstraintDeclsExt;
break;
}
Object[] entries = table.getEntries();
fComponentsExt[objectType] = new ObjectListImpl(entries, entries.length);
}
return fComponentsExt[objectType];
}
public synchronized void resetComponents() {
fComponents = null;
fComponentsExt = null;
}
/**
* Convenience method. Returns a top-level simple or complex type
* definition.
* @param name The name of the definition.
* @return An <code>XSTypeDefinition</code> or null if such definition
* does not exist.
*/
public XSTypeDefinition getTypeDefinition(String name) {
return getGlobalTypeDecl(name);
}
/**
* Convenience method. Returns a top-level attribute declaration.
* @param name The name of the declaration.
* @return A top-level attribute declaration or null if such declaration
* does not exist.
*/
public XSAttributeDeclaration getAttributeDeclaration(String name) {
return getGlobalAttributeDecl(name);
}
/**
* Convenience method. Returns a top-level element declaration.
* @param name The name of the declaration.
* @return A top-level element declaration or null if such declaration
* does not exist.
*/
public XSElementDeclaration getElementDeclaration(String name) {
return getGlobalElementDecl(name);
}
/**
* Convenience method. Returns a top-level attribute group definition.
* @param name The name of the definition.
* @return A top-level attribute group definition or null if such
* definition does not exist.
*/
public XSAttributeGroupDefinition getAttributeGroup(String name) {
return getGlobalAttributeGroupDecl(name);
}
/**
* Convenience method. Returns a top-level model group definition.
*
* @param name The name of the definition.
* @return A top-level model group definition definition or null if such
* definition does not exist.
*/
public XSModelGroupDefinition getModelGroupDefinition(String name) {
return getGlobalGroupDecl(name);
}
/**
* Convenience method. Returns a top-level notation declaration.
*
* @param name The name of the declaration.
* @return A top-level notation declaration or null if such declaration
* does not exist.
*/
public XSNotationDeclaration getNotationDeclaration(String name) {
return getGlobalNotationDecl(name);
}
public XSIDCDefinition getIDCDefinition(String name) {
return getIDConstraintDecl(name);
}
/**
* [document location]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#sd-document_location">[document location]</a>
* @return a list of document information item
*/
public StringList getDocumentLocations() {
return new StringListImpl(fLocations);
}
/**
* Return an <code>XSModel</code> that represents components in this schema
* grammar.
*
* @return an <code>XSModel</code> representing this schema grammar
*/
public XSModel toXSModel() {
return new XSModelImpl(new SchemaGrammar[]{this});
}
public XSModel toXSModel(XSGrammar[] grammars) {
if (grammars == null || grammars.length == 0)
return toXSModel();
int len = grammars.length;
boolean hasSelf = false;
for (int i = 0; i < len; i++) {
if (grammars[i] == this) {
hasSelf = true;
break;
}
}
SchemaGrammar[] gs = new SchemaGrammar[hasSelf ? len : len+1];
for (int i = 0; i < len; i++)
gs[i] = (SchemaGrammar)grammars[i];
if (!hasSelf)
gs[len] = this;
return new XSModelImpl(gs);
}
/**
* @see org.apache.xerces.xs.XSNamespaceItem#getAnnotations()
*/
public XSObjectList getAnnotations() {
if (fNumAnnotations == 0) {
return XSObjectListImpl.EMPTY_LIST;
}
return new XSObjectListImpl(fAnnotations, fNumAnnotations);
}
public void addAnnotation(XSAnnotationImpl annotation) {
if (annotation == null) {
return;
}
if (fAnnotations == null) {
fAnnotations = new XSAnnotationImpl[2];
}
else if (fNumAnnotations == fAnnotations.length) {
XSAnnotationImpl[] newArray = new XSAnnotationImpl[fNumAnnotations << 1];
System.arraycopy(fAnnotations, 0, newArray, 0, fNumAnnotations);
fAnnotations = newArray;
}
fAnnotations[fNumAnnotations++] = annotation;
}
public void setImmutable(boolean isImmutable) {
fIsImmutable = isImmutable;
}
public boolean isImmutable() {
return fIsImmutable;
}
} // class SchemaGrammar
| fParticles |
/*
* Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.hosted;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.stream.Collectors;
import org.graalvm.nativeimage.hosted.RuntimeReflection;
import org.graalvm.nativeimage.hosted.RuntimeResourceAccess;
import com.oracle.svm.core.feature.AutomaticallyRegisteredFeature;
import com.oracle.svm.core.feature.InternalFeature;
import com.oracle.svm.core.jdk.ServiceCatalogSupport;
import com.oracle.svm.core.option.AccumulatingLocatableMultiOptionValue;
import com.oracle.svm.core.option.HostedOptionKey;
import com.oracle.svm.hosted.analysis.Inflation;
import jdk.graal.compiler.options.Option;
import jdk.graal.compiler.options.OptionType;
/**
* Support for {@link ServiceLoader} on Substrate VM.
*
* Services are registered in the folder {@code "META-INF/services/"} using files whose name is the
* fully qualified service interface name. We do not know which services are going to be used by a
* native image: The parameter of {@code ServiceLoader#load} is often but not always a compile-time
* constant that we can track. But we also cannot put all registered services into the native image.
*
* We therefore use the following heuristic: We add all service loader files and service
* implementation classes when the service interfaces that are seen as reachable by the static
* analysis.
*
* Each used service implementation class is added for reflection (using
* {@link org.graalvm.nativeimage.hosted.RuntimeReflection#register(Class[])}) and for reflective
* instantiation (using {@link RuntimeReflection#registerForReflectiveInstantiation(Class[])}).
*
* For each service interface, a single service loader file is added as a resource to the image. The
* single file combines all the individual files that can come from different .jar files.
*/
@AutomaticallyRegisteredFeature
public class ServiceLoaderFeature implements InternalFeature {
public static class Options {
@Option(help = "Automatically register services for run-time lookup using ServiceLoader", type = OptionType.Expert) //
public static final HostedOptionKey<Boolean> UseServiceLoaderFeature = new HostedOptionKey<>(true);
@Option(help = "Comma-separated list of services that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServices = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
@Option(help = "Comma-separated list of service [MASK] that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServiceProviders = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
}
private static final Set<String> SKIPPED_SERVICES = Set.of(
// image builder internal ServiceLoader interfaces
"com.oracle.svm.hosted.NativeImageClassLoaderPostProcessing",
"org.graalvm.nativeimage.Platform",
/*
* Loaded in java.util.random.RandomGeneratorFactory.FactoryMapHolder, which is
* initialized at image build time.
*/
"java.util.random.RandomGenerator",
"java.security.Provider", // see SecurityServicesFeature
"sun.util.locale.provider.LocaleDataMetaInfo", // see LocaleSubstitutions
/* Graal hotspot-specific services */
"jdk.vm.ci.hotspot.HotSpotJVMCIBackendFactory",
"jdk.graal.compiler.hotspot.CompilerConfigurationFactory",
"jdk.graal.compiler.hotspot.HotSpotBackendFactory",
"jdk.graal.compiler.hotspot.meta.DefaultHotSpotLoweringProvider$Extensions",
"jdk.graal.compiler.hotspot.meta.HotSpotInvocationPluginProvider",
"jdk.graal.compiler.truffle.hotspot.TruffleCallBoundaryInstrumentationFactory");
// NOTE: Platform class had to be added to this list since our analysis discovers that
// Platform.includedIn is reachable regardless of fact that it is constant folded at
// registerPlatformPlugins method of SubstrateGraphBuilderPlugins. This issue hasn't manifested
// before because implementation classes were instantiated using runtime reflection instead of
// ServiceLoader (and thus weren't reachable in analysis).
/**
* Services that should not be processed here, for example because they are handled by
* specialized features.
*/
private final Set<String> servicesToSkip = new HashSet<>(SKIPPED_SERVICES);
private static final Set<String> SKIPPED_PROVIDERS = Set.of(
/* Graal hotspot-specific service- [MASK] */
"jdk.graal.compiler.hotspot.meta.HotSpotDisassemblerProvider",
/* Skip console [MASK] until GR-44085 is fixed */
"jdk.internal.org.jline.JdkConsoleProviderImpl", "jdk.jshell.execution.impl.ConsoleImpl$ConsoleProviderImpl");
private final Set<String> serviceProvidersToSkip = new HashSet<>(SKIPPED_PROVIDERS);
@Override
public boolean isInConfiguration(IsInConfigurationAccess access) {
return Options.UseServiceLoaderFeature.getValue();
}
@Override
public void afterRegistration(AfterRegistrationAccess access) {
servicesToSkip.addAll(Options.ServiceLoaderFeatureExcludeServices.getValue().values());
serviceProvidersToSkip.addAll(Options.ServiceLoaderFeatureExcludeServiceProviders.getValue().values());
}
@Override
public void beforeAnalysis(BeforeAnalysisAccess access) {
FeatureImpl.BeforeAnalysisAccessImpl accessImpl = (FeatureImpl.BeforeAnalysisAccessImpl) access;
accessImpl.imageClassLoader.classLoaderSupport.serviceProvidersForEach((serviceName, [MASK] ) -> {
Class<?> serviceClass = access.findClassByName(serviceName);
boolean skipService = false;
/* If the service should not end up in the image, we remove all the [MASK] with it */
Collection<String> [MASK] ToSkip = [MASK] ;
if (servicesToSkip.contains(serviceName)) {
skipService = true;
} else if (serviceClass == null || serviceClass.isArray() || serviceClass.isPrimitive()) {
skipService = true;
} else if (!accessImpl.getHostVM().platformSupported(serviceClass)) {
skipService = true;
} else {
[MASK] ToSkip = [MASK] .stream().filter(serviceProvidersToSkip::contains).collect(Collectors.toList());
if (! [MASK] ToSkip.isEmpty()) {
skipService = true;
}
}
if (skipService) {
ServiceCatalogSupport.singleton().removeServicesFromServicesCatalog(serviceName, new HashSet<>( [MASK] ToSkip));
return;
}
access.registerReachabilityHandler(a -> handleServiceClassIsReachable(a, serviceClass, [MASK] ), serviceClass);
});
}
void handleServiceClassIsReachable(DuringAnalysisAccess access, Class<?> serviceProvider, Collection<String> [MASK] ) {
LinkedHashSet<String> registeredProviders = new LinkedHashSet<>();
for (String provider : [MASK] ) {
if (serviceProvidersToSkip.contains(provider)) {
continue;
}
/* Make provider reflectively instantiable */
Class<?> providerClass = access.findClassByName(provider);
if (providerClass == null || providerClass.isArray() || providerClass.isPrimitive()) {
continue;
}
FeatureImpl.DuringAnalysisAccessImpl accessImpl = (FeatureImpl.DuringAnalysisAccessImpl) access;
if (!accessImpl.getHostVM().platformSupported(providerClass)) {
continue;
}
if (((Inflation) accessImpl.getBigBang()).getAnnotationSubstitutionProcessor().isDeleted(providerClass)) {
/* Disallow services with implementation classes that are marked as @Deleted */
continue;
}
/*
* Find either a public static provider() method or a nullary constructor (or both).
* Skip [MASK] that do not comply with requirements.
*
* See ServiceLoader#loadProvider and ServiceLoader#findStaticProviderMethod.
*/
Constructor<?> nullaryConstructor = null;
Method nullaryProviderMethod = null;
try {
/* Only look for a provider() method if provider class is in an explicit module. */
if (providerClass.getModule().isNamed() && !providerClass.getModule().getDescriptor().isAutomatic()) {
for (Method method : providerClass.getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers()) &&
method.getParameterCount() == 0 && method.getName().equals("provider")) {
if (nullaryProviderMethod == null) {
nullaryProviderMethod = method;
} else {
/* There must be at most one public static provider() method. */
nullaryProviderMethod = null;
break;
}
}
}
}
Constructor<?> constructor = providerClass.getDeclaredConstructor();
if (Modifier.isPublic(constructor.getModifiers())) {
nullaryConstructor = constructor;
}
} catch (NoSuchMethodException | SecurityException | LinkageError e) {
// ignore
}
if (nullaryConstructor != null || nullaryProviderMethod != null) {
RuntimeReflection.register(providerClass);
if (nullaryConstructor != null) {
/*
* Registering a constructor with
* RuntimeReflection.registerConstructorLookup(providerClass) does not produce
* the same behavior as using RuntimeReflection.register(nullaryConstructor). In
* the first case, the constructor is marked for query purposes only, so this
* if-statement cannot be eliminated.
*
*/
RuntimeReflection.register(nullaryConstructor);
} else {
/*
* If there's no nullary constructor, register it as negative lookup to avoid
* throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerConstructorLookup(providerClass);
}
if (nullaryProviderMethod != null) {
RuntimeReflection.register(nullaryProviderMethod);
} else {
/*
* If there's no declared public provider() method, register it as negative
* lookup to avoid throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerMethodLookup(providerClass, "provider");
}
}
/*
* Register the provider in both cases: when it is JCA-compliant (has a nullary
* constructor or a provider method) or when it lacks both. If neither is present, a
* ServiceConfigurationError will be thrown at runtime, consistent with HotSpot
* behavior.
*/
registeredProviders.add(provider);
}
if (!registeredProviders.isEmpty()) {
String serviceResourceLocation = "META-INF/services/" + serviceProvider.getName();
byte[] serviceFileData = registeredProviders.stream().collect(Collectors.joining("\n")).getBytes(StandardCharsets.UTF_8);
RuntimeResourceAccess.addResource(access.getApplicationClassLoader().getUnnamedModule(), serviceResourceLocation, serviceFileData);
}
}
}
| providers |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> [MASK] ;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> [MASK] ,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this. [MASK] = [MASK] ;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this. [MASK] .isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| requiresUnpack |
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
*/
/*
* 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 com.sun.org.apache.xerces.internal.impl.xs;
import com.sun.org.apache.xerces.internal.impl.Constants;
import com.sun.org.apache.xerces.internal.impl.dv.SchemaDVFactory;
import com.sun.org.apache.xerces.internal.impl.dv.ValidatedInfo;
import com.sun.org.apache.xerces.internal.impl.dv.XSSimpleType;
import com.sun.org.apache.xerces.internal.impl.dv.xs.XSSimpleTypeDecl;
import com.sun.org.apache.xerces.internal.impl.xs.identity.IdentityConstraint;
import com.sun.org.apache.xerces.internal.impl.xs.util.ObjectListImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.SimpleLocator;
import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSNamedMap4Types;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSNamedMapImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSObjectListImpl;
import com.sun.org.apache.xerces.internal.parsers.DOMParser;
import com.sun.org.apache.xerces.internal.parsers.SAXParser;
import com.sun.org.apache.xerces.internal.parsers.XML11Configuration;
import com.sun.org.apache.xerces.internal.util.SymbolHash;
import com.sun.org.apache.xerces.internal.util.SymbolTable;
import com.sun.org.apache.xerces.internal.xni.NamespaceContext;
import com.sun.org.apache.xerces.internal.xni.grammars.XMLGrammarDescription;
import com.sun.org.apache.xerces.internal.xni.grammars.XSGrammar;
import com.sun.org.apache.xerces.internal.xs.StringList;
import com.sun.org.apache.xerces.internal.xs.XSAnnotation;
import com.sun.org.apache.xerces.internal.xs.XSAttributeDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSAttributeGroupDefinition;
import com.sun.org.apache.xerces.internal.xs.XSConstants;
import com.sun.org.apache.xerces.internal.xs.XSElementDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSIDCDefinition;
import com.sun.org.apache.xerces.internal.xs.XSModel;
import com.sun.org.apache.xerces.internal.xs.XSModelGroupDefinition;
import com.sun.org.apache.xerces.internal.xs.XSNamedMap;
import com.sun.org.apache.xerces.internal.xs.XSNamespaceItem;
import com.sun.org.apache.xerces.internal.xs.XSNotationDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSObjectList;
import com.sun.org.apache.xerces.internal.xs.XSParticle;
import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
import com.sun.org.apache.xerces.internal.xs.XSWildcard;
import com.sun.org.apache.xerces.internal.xs.datatypes.ObjectList;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.xml.sax.SAXException;
/**
* This class is to hold all schema component declaration that are declared
* within one namespace.
*
* The Grammar class this class extends contains what little
* commonality there is between XML Schema and DTD grammars. It's
* useful to distinguish grammar objects from other kinds of object
* when they exist in pools or caches.
*
* @xerces.internal
*
* @author Sandy Gao, IBM
* @author Elena Litani, IBM
*
* @LastModified: Oct 2017
*/
public class SchemaGrammar implements XSGrammar, XSNamespaceItem {
// the target namespace of grammar
String fTargetNamespace;
// global decls: map from decl name to decl object
SymbolHash fGlobalAttrDecls;
SymbolHash fGlobalAttrGrpDecls;
SymbolHash fGlobalElemDecls;
SymbolHash fGlobalGroupDecls;
SymbolHash fGlobalNotationDecls;
SymbolHash fGlobalIDConstraintDecls;
SymbolHash fGlobalTypeDecls;
// extended global decls: map from schema location + decl name to decl object
// key is location,name
SymbolHash fGlobalAttrDeclsExt;
SymbolHash fGlobalAttrGrpDeclsExt;
SymbolHash fGlobalElemDeclsExt;
SymbolHash fGlobalGroupDeclsExt;
SymbolHash fGlobalNotationDeclsExt;
SymbolHash fGlobalIDConstraintDeclsExt;
SymbolHash fGlobalTypeDeclsExt;
// A global map of all global element declarations - used for substitution group computation
// (handy when sharing components by reference, since we might end up with duplicate components
// that are not added to either of the global element declarations above)
SymbolHash fAllGlobalElemDecls;
// the XMLGrammarDescription member
XSDDescription fGrammarDescription = null;
// annotations associated with the "root" schema of this targetNamespace
XSAnnotationImpl [] fAnnotations = null;
// number of annotations declared
int fNumAnnotations;
// symbol table for constructing parsers (annotation support)
private SymbolTable fSymbolTable = null;
// parsers for annotation support
private SoftReference<SAXParser> fSAXParser = null;
private SoftReference<DOMParser> fDOMParser = null;
// is this grammar immutable? (fully constructed and not changeable)
private boolean fIsImmutable = false;
//
// Constructors
//
// needed to make BuiltinSchemaGrammar work.
protected SchemaGrammar() {}
/**
* Default constructor.
*
* @param targetNamespace
* @param grammarDesc the XMLGrammarDescription corresponding to this object
* at the least a systemId should always be known.
* @param symbolTable needed for annotation support
*/
public SchemaGrammar(String targetNamespace, XSDDescription grammarDesc,
SymbolTable symbolTable) {
fTargetNamespace = targetNamespace;
fGrammarDescription = grammarDesc;
fSymbolTable = symbolTable;
// REVISIT: the initial sizes being chosen for each SymbolHash
// may not be ideal and could still be tuned. They were chosen
// somewhat arbitrarily to reduce the initial footprint of
// SymbolHash buckets from 1,515 to 177 (about 12% of the
// default size).
fGlobalAttrDecls = new SymbolHash(12);
fGlobalAttrGrpDecls = new SymbolHash(5);
fGlobalElemDecls = new SymbolHash(25);
fGlobalGroupDecls = new SymbolHash(5);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(3);
// Extended tables
fGlobalAttrDeclsExt = new SymbolHash(12);
fGlobalAttrGrpDeclsExt = new SymbolHash(5);
fGlobalElemDeclsExt = new SymbolHash(25);
fGlobalGroupDeclsExt = new SymbolHash(5);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(3);
fGlobalTypeDeclsExt = new SymbolHash(25);
// All global elements table
fAllGlobalElemDecls = new SymbolHash(25);
// if we are parsing S4S, put built-in types in first
// they might get overwritten by the types from S4S, but that's
// considered what the application wants to do.
if (fTargetNamespace == SchemaSymbols.URI_SCHEMAFORSCHEMA) {
fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls.makeClone();
}
else {
fGlobalTypeDecls = new SymbolHash(25);
}
} // <init>(String, XSDDescription)
// Clone an existing schema grammar
public SchemaGrammar(SchemaGrammar grammar) {
fTargetNamespace = grammar.fTargetNamespace;
fGrammarDescription = grammar.fGrammarDescription.makeClone();
//fGrammarDescription.fContextType |= XSDDescription.CONTEXT_COLLISION; // REVISIT
fSymbolTable = grammar.fSymbolTable; // REVISIT
fGlobalAttrDecls = grammar.fGlobalAttrDecls.makeClone();
fGlobalAttrGrpDecls = grammar.fGlobalAttrGrpDecls.makeClone();
fGlobalElemDecls = grammar.fGlobalElemDecls.makeClone();
fGlobalGroupDecls = grammar.fGlobalGroupDecls.makeClone();
fGlobalNotationDecls = grammar.fGlobalNotationDecls.makeClone();
fGlobalIDConstraintDecls = grammar.fGlobalIDConstraintDecls.makeClone();
fGlobalTypeDecls = grammar.fGlobalTypeDecls.makeClone();
// Extended tables
fGlobalAttrDeclsExt = grammar.fGlobalAttrDeclsExt.makeClone();
fGlobalAttrGrpDeclsExt = grammar.fGlobalAttrGrpDeclsExt.makeClone();
fGlobalElemDeclsExt = grammar.fGlobalElemDeclsExt.makeClone();
fGlobalGroupDeclsExt = grammar.fGlobalGroupDeclsExt.makeClone();
fGlobalNotationDeclsExt = grammar.fGlobalNotationDeclsExt.makeClone();
fGlobalIDConstraintDeclsExt = grammar.fGlobalIDConstraintDeclsExt.makeClone();
fGlobalTypeDeclsExt = grammar.fGlobalTypeDeclsExt.makeClone();
// All global elements table
fAllGlobalElemDecls = grammar.fAllGlobalElemDecls.makeClone();
// Annotations associated with the "root" schema of this targetNamespace
fNumAnnotations = grammar.fNumAnnotations;
if (fNumAnnotations > 0) {
fAnnotations = new XSAnnotationImpl[grammar.fAnnotations.length];
System.arraycopy(grammar.fAnnotations, 0, fAnnotations, 0, fNumAnnotations);
}
// All substitution group information declared in this namespace
fSubGroupCount = grammar.fSubGroupCount;
if (fSubGroupCount > 0) {
fSubGroups = new XSElementDecl[grammar.fSubGroups.length];
System.arraycopy(grammar.fSubGroups, 0, fSubGroups, 0, fSubGroupCount);
}
// Array to store complex type decls for constraint checking
fCTCount = grammar.fCTCount;
if (fCTCount > 0) {
fComplexTypeDecls = new XSComplexTypeDecl[grammar.fComplexTypeDecls.length];
fCTLocators = new SimpleLocator[grammar.fCTLocators.length];
System.arraycopy(grammar.fComplexTypeDecls, 0, fComplexTypeDecls, 0, fCTCount);
System.arraycopy(grammar.fCTLocators, 0, fCTLocators, 0, fCTCount);
}
// Groups being redefined by restriction
fRGCount = grammar.fRGCount;
if (fRGCount > 0) {
fRedefinedGroupDecls = new XSGroupDecl[grammar.fRedefinedGroupDecls.length];
fRGLocators = new SimpleLocator[grammar.fRGLocators.length];
System.arraycopy(grammar.fRedefinedGroupDecls, 0, fRedefinedGroupDecls, 0, fRGCount);
System.arraycopy(grammar.fRGLocators, 0, fRGLocators, 0, fRGCount/2);
}
// List of imported grammars
if (grammar.fImported != null) {
fImported = new ArrayList<>();
for (int i=0; i<grammar.fImported.size(); i++) {
fImported.add(grammar.fImported.get(i));
}
}
// Locations
if (grammar.fLocations != null) {
for (int k=0; k<grammar.fLocations.size(); k++) {
addDocument(null, grammar.fLocations.get(k));
}
}
} // <init>(String, XSDDescription)
// number of built-in XSTypes we need to create for base and full
// datatype set
private static final int BASICSET_COUNT = 29;
private static final int FULLSET_COUNT = 46;
private static final int GRAMMAR_XS = 1;
private static final int GRAMMAR_XSI = 2;
// this class makes sure the static, built-in schema grammars
// are immutable.
public static class BuiltinSchemaGrammar extends SchemaGrammar {
private static final String EXTENDED_SCHEMA_FACTORY_CLASS = "com.sun.org.apache.xerces.internal.impl.dv.xs.ExtendedSchemaDVFactoryImpl";
/**
* Special constructor to create the grammars for the schema namespaces
*
* @param grammar
*/
public BuiltinSchemaGrammar(int grammar, short schemaVersion) {
SchemaDVFactory schemaFactory;
if (schemaVersion == Constants.SCHEMA_VERSION_1_0) {
schemaFactory = SchemaDVFactory.getInstance();
}
else {
schemaFactory = SchemaDVFactory.getInstance(EXTENDED_SCHEMA_FACTORY_CLASS);
}
if (grammar == GRAMMAR_XS) {
// target namespace
fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA);
// no global decls other than types
fGlobalAttrDecls = new SymbolHash(1);
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(1);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(1);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// all global element decls table
fAllGlobalElemDecls = new SymbolHash(1);
// get all built-in types
fGlobalTypeDecls = schemaFactory.getBuiltInTypes();
// assign the built-in schema grammar as the XSNamespaceItem
// for each of the built-in simple type definitions.
int length = fGlobalTypeDecls.getLength();
XSTypeDefinition [] typeDefinitions = new XSTypeDefinition[length];
fGlobalTypeDecls.getValues(typeDefinitions, 0);
for (int i = 0; i < length; ++i) {
XSTypeDefinition xtd = typeDefinitions[i];
if (xtd instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) xtd).setNamespaceItem(this);
}
}
// add anyType
fGlobalTypeDecls.put(fAnyType.getName(), fAnyType);
}
else if (grammar == GRAMMAR_XSI) {
// target namespace
fTargetNamespace = SchemaSymbols.URI_XSI;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_XSI);
// no global decls other than attributes
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(1);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
fGlobalTypeDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(1);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// no all global element decls
fAllGlobalElemDecls = new SymbolHash(1);
// 4 attributes, so initialize the size as 4*2 = 8
fGlobalAttrDecls = new SymbolHash(8);
String name = null;
String tns = null;
XSSimpleType type = null;
short scope = XSConstants.SCOPE_GLOBAL;
// xsi:type
name = SchemaSymbols.XSI_TYPE;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_QNAME);
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
// xsi:nil
name = SchemaSymbols.XSI_NIL;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_BOOLEAN);
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
XSSimpleType anyURI = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_ANYURI);
// xsi:schemaLocation
name = SchemaSymbols.XSI_SCHEMALOCATION;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.createTypeList("#AnonType_schemaLocation", SchemaSymbols.URI_XSI, (short)0, anyURI, null);
if (type instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl)type).setAnonymous(true);
}
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
// xsi:noNamespaceSchemaLocation
name = SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION;
tns = SchemaSymbols.URI_XSI;
type = anyURI;
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
}
} // <init>(int)
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription.makeClone();
} // getGrammarDescription(): XMLGrammarDescription
// override these methods solely so that these
// objects cannot be modified once they're created.
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl, String location) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
// ignore
}
public void addGlobalElementDeclAll(XSElementDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
// ignore
}
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
// ignore
}
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
// ignore
}
public synchronized void addDocument(Object document, String location) {
// ignore
}
// annotation support
synchronized DOMParser getDOMParser() {
return null;
}
synchronized SAXParser getSAXParser() {
return null;
}
}
/**
* <p>A partial schema for schemas for validating annotations.</p>
*
* @xerces.internal
*
* @author Michael Glavassevich, IBM
*/
public static final class Schema4Annotations extends SchemaGrammar {
/**
* Singleton instance.
*/
public static final Schema4Annotations INSTANCE = new Schema4Annotations();
/**
* Special constructor to create a schema
* capable of validating annotations.
*/
private Schema4Annotations() {
// target namespace
fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA);
// no global decls other than types and
// element declarations for <annotation>, <documentation> and <appinfo>.
fGlobalAttrDecls = new SymbolHash(1);
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(6);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(6);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// all global element declarations
fAllGlobalElemDecls = new SymbolHash(6);
// get all built-in types
fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls;
// create element declarations for <annotation>, <documentation> and <appinfo>
XSElementDecl annotationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_ANNOTATION);
XSElementDecl documentationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_DOCUMENTATION);
XSElementDecl appinfoDecl = createAnnotationElementDecl(SchemaSymbols.ELT_APPINFO);
// add global element declarations
fGlobalElemDecls.put(annotationDecl.fName, annotationDecl);
fGlobalElemDecls.put(documentationDecl.fName, documentationDecl);
fGlobalElemDecls.put(appinfoDecl.fName, appinfoDecl);
fGlobalElemDeclsExt.put(","+annotationDecl.fName, annotationDecl);
fGlobalElemDeclsExt.put(","+documentationDecl.fName, documentationDecl);
fGlobalElemDeclsExt.put(","+appinfoDecl.fName, appinfoDecl);
fAllGlobalElemDecls.put(annotationDecl, annotationDecl);
fAllGlobalElemDecls.put(documentationDecl, documentationDecl);
fAllGlobalElemDecls.put(appinfoDecl, appinfoDecl);
// create complex type declarations for <annotation>, <documentation> and <appinfo>
XSComplexTypeDecl annotationType = new XSComplexTypeDecl();
XSComplexTypeDecl [MASK] = new XSComplexTypeDecl();
XSComplexTypeDecl appinfoType = new XSComplexTypeDecl();
// set the types on their element declarations
annotationDecl.fType = annotationType;
documentationDecl.fType = [MASK] ;
appinfoDecl.fType = appinfoType;
// create attribute groups for <annotation>, <documentation> and <appinfo>
XSAttributeGroupDecl annotationAttrs = new XSAttributeGroupDecl();
XSAttributeGroupDecl documentationAttrs = new XSAttributeGroupDecl();
XSAttributeGroupDecl appinfoAttrs = new XSAttributeGroupDecl();
// fill in attribute groups
{
// create and fill attribute uses for <annotation>, <documentation> and <appinfo>
XSAttributeUseImpl annotationIDAttr = new XSAttributeUseImpl();
annotationIDAttr.fAttrDecl = new XSAttributeDecl();
annotationIDAttr.fAttrDecl.setValues(SchemaSymbols.ATT_ID, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ID),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, annotationType, null);
annotationIDAttr.fUse = SchemaSymbols.USE_OPTIONAL;
annotationIDAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl documentationSourceAttr = new XSAttributeUseImpl();
documentationSourceAttr.fAttrDecl = new XSAttributeDecl();
documentationSourceAttr.fAttrDecl.setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ANYURI),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, [MASK] , null);
documentationSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL;
documentationSourceAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl documentationLangAttr = new XSAttributeUseImpl();
documentationLangAttr.fAttrDecl = new XSAttributeDecl();
documentationLangAttr.fAttrDecl.setValues("lang".intern(), NamespaceContext.XML_URI, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_LANGUAGE),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, [MASK] , null);
documentationLangAttr.fUse = SchemaSymbols.USE_OPTIONAL;
documentationLangAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl appinfoSourceAttr = new XSAttributeUseImpl();
appinfoSourceAttr.fAttrDecl = new XSAttributeDecl();
appinfoSourceAttr.fAttrDecl.setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ANYURI),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, appinfoType, null);
appinfoSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL;
appinfoSourceAttr.fConstraintType = XSConstants.VC_NONE;
// create lax attribute wildcard for <annotation>, <documentation> and <appinfo>
XSWildcardDecl otherAttrs = new XSWildcardDecl();
otherAttrs.fNamespaceList = new String [] {fTargetNamespace, null};
otherAttrs.fType = XSWildcard.NSCONSTRAINT_NOT;
otherAttrs.fProcessContents = XSWildcard.PC_LAX;
// add attribute uses and wildcards to attribute groups for <annotation>, <documentation> and <appinfo>
annotationAttrs.addAttributeUse(annotationIDAttr);
annotationAttrs.fAttributeWC = otherAttrs;
documentationAttrs.addAttributeUse(documentationSourceAttr);
documentationAttrs.addAttributeUse(documentationLangAttr);
documentationAttrs.fAttributeWC = otherAttrs;
appinfoAttrs.addAttributeUse(appinfoSourceAttr);
appinfoAttrs.fAttributeWC = otherAttrs;
}
// create particles for <annotation>
XSParticleDecl annotationParticle = createUnboundedModelGroupParticle();
{
XSModelGroupImpl annotationChoice = new XSModelGroupImpl();
annotationChoice.fCompositor = XSModelGroupImpl.MODELGROUP_CHOICE;
annotationChoice.fParticleCount = 2;
annotationChoice.fParticles = new XSParticleDecl[2];
annotationChoice.fParticles[0] = createChoiceElementParticle(appinfoDecl);
annotationChoice.fParticles[1] = createChoiceElementParticle(documentationDecl);
annotationParticle.fValue = annotationChoice;
}
// create wildcard particle for <documentation> and <appinfo>
XSParticleDecl anyWCSequenceParticle = createUnboundedAnyWildcardSequenceParticle();
// fill complex types
annotationType.setValues("#AnonType_" + SchemaSymbols.ELT_ANNOTATION, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_ELEMENT, false, annotationAttrs, null, annotationParticle, XSObjectListImpl.EMPTY_LIST);
annotationType.setName("#AnonType_" + SchemaSymbols.ELT_ANNOTATION);
annotationType.setIsAnonymous();
[MASK] .setValues("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_MIXED, false, documentationAttrs, null, anyWCSequenceParticle, XSObjectListImpl.EMPTY_LIST);
[MASK] .setName("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION);
[MASK] .setIsAnonymous();
appinfoType.setValues("#AnonType_" + SchemaSymbols.ELT_APPINFO, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_MIXED, false, appinfoAttrs, null, anyWCSequenceParticle, XSObjectListImpl.EMPTY_LIST);
appinfoType.setName("#AnonType_" + SchemaSymbols.ELT_APPINFO);
appinfoType.setIsAnonymous();
} // <init>(int)
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription.makeClone();
} // getGrammarDescription(): XMLGrammarDescription
// override these methods solely so that these
// objects cannot be modified once they're created.
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
// ignore
}
public void addGlobalElementDeclAll(XSElementDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
// ignore
}
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
// ignore
}
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
// ignore
}
public synchronized void addDocument(Object document, String location) {
// ignore
}
// annotation support
synchronized DOMParser getDOMParser() {
return null;
}
synchronized SAXParser getSAXParser() {
return null;
}
//
// private helper methods
//
private XSElementDecl createAnnotationElementDecl(String localName) {
XSElementDecl eDecl = new XSElementDecl();
eDecl.fName = localName;
eDecl.fTargetNamespace = fTargetNamespace;
eDecl.setIsGlobal();
eDecl.fBlock = (XSConstants.DERIVATION_EXTENSION |
XSConstants.DERIVATION_RESTRICTION | XSConstants.DERIVATION_SUBSTITUTION);
eDecl.setConstraintType(XSConstants.VC_NONE);
return eDecl;
}
private XSParticleDecl createUnboundedModelGroupParticle() {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 0;
particle.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED;
particle.fType = XSParticleDecl.PARTICLE_MODELGROUP;
return particle;
}
private XSParticleDecl createChoiceElementParticle(XSElementDecl ref) {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 1;
particle.fMaxOccurs = 1;
particle.fType = XSParticleDecl.PARTICLE_ELEMENT;
particle.fValue = ref;
return particle;
}
private XSParticleDecl createUnboundedAnyWildcardSequenceParticle() {
XSParticleDecl particle = createUnboundedModelGroupParticle();
XSModelGroupImpl sequence = new XSModelGroupImpl();
sequence.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE;
sequence.fParticleCount = 1;
sequence.fParticles = new XSParticleDecl[1];
sequence.fParticles[0] = createAnyLaxWildcardParticle();
particle.fValue = sequence;
return particle;
}
private XSParticleDecl createAnyLaxWildcardParticle() {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 1;
particle.fMaxOccurs = 1;
particle.fType = XSParticleDecl.PARTICLE_WILDCARD;
XSWildcardDecl anyWC = new XSWildcardDecl();
anyWC.fNamespaceList = null;
anyWC.fType = XSWildcard.NSCONSTRAINT_ANY;
anyWC.fProcessContents = XSWildcard.PC_LAX;
particle.fValue = anyWC;
return particle;
}
}
// Grammar methods
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription;
} // getGrammarDescription(): XMLGrammarDescription
// DTDGrammar methods
public boolean isNamespaceAware () {
return true;
} // isNamespaceAware():boolean
List<SchemaGrammar> fImported = null;
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
fImported = importedGrammars;
}
public List<SchemaGrammar> getImportedGrammars() {
return fImported;
}
/**
* Returns this grammar's target namespace.
*/
public final String getTargetNamespace() {
return fTargetNamespace;
} // getTargetNamespace():String
/**
* register one global attribute
*/
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
fGlobalAttrDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalAttributeDecl(XSAttributeDecl decl, String location) {
fGlobalAttrDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global attribute group
*/
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
fGlobalAttrGrpDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
fGlobalAttrGrpDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global element
*/
public void addGlobalElementDeclAll(XSElementDecl decl) {
if (fAllGlobalElemDecls.get(decl) == null) {
fAllGlobalElemDecls.put(decl, decl);
// if there is a substitution group affiliation, store in an array,
// for further constraint checking: UPA, PD, EDC
if (decl.fSubGroup != null) {
if (fSubGroupCount == fSubGroups.length)
fSubGroups = resize(fSubGroups, fSubGroupCount+INC_SIZE);
fSubGroups[fSubGroupCount++] = decl;
}
}
}
public void addGlobalElementDecl(XSElementDecl decl) {
fGlobalElemDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
fGlobalElemDeclsExt.put(((location != null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global group
*/
public void addGlobalGroupDecl(XSGroupDecl decl) {
fGlobalGroupDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
fGlobalGroupDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global notation
*/
public void addGlobalNotationDecl(XSNotationDecl decl) {
fGlobalNotationDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
fGlobalNotationDeclsExt.put(((location!=null) ? location : "") + "," +decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global type
*/
public void addGlobalTypeDecl(XSTypeDefinition decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
if (decl instanceof XSComplexTypeDecl) {
((XSComplexTypeDecl) decl).setNamespaceItem(this);
}
else if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
fGlobalTypeDeclsExt.put(((location!=null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null) {
if (decl instanceof XSComplexTypeDecl) {
((XSComplexTypeDecl) decl).setNamespaceItem(this);
}
else if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
}
/**
* register one global complex type
*/
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
decl.setNamespaceItem(this);
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
fGlobalTypeDeclsExt.put(((location!=null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global simple type
*/
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
fGlobalTypeDeclsExt.put(((location != null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null && decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
/**
* register one identity constraint
*/
public final void addIDConstraintDecl(XSElementDecl elmDecl, IdentityConstraint decl) {
elmDecl.addIDConstraint(decl);
fGlobalIDConstraintDecls.put(decl.getIdentityConstraintName(), decl);
}
public final void addIDConstraintDecl(XSElementDecl elmDecl, IdentityConstraint decl, String location) {
fGlobalIDConstraintDeclsExt.put(((location != null) ? location : "") + "," + decl.getIdentityConstraintName(), decl);
}
/**
* get one global attribute
*/
public final XSAttributeDecl getGlobalAttributeDecl(String declName) {
return(XSAttributeDecl)fGlobalAttrDecls.get(declName);
}
public final XSAttributeDecl getGlobalAttributeDecl(String declName, String location) {
return(XSAttributeDecl)fGlobalAttrDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global attribute group
*/
public final XSAttributeGroupDecl getGlobalAttributeGroupDecl(String declName) {
return(XSAttributeGroupDecl)fGlobalAttrGrpDecls.get(declName);
}
public final XSAttributeGroupDecl getGlobalAttributeGroupDecl(String declName, String location) {
return(XSAttributeGroupDecl)fGlobalAttrGrpDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global element
*/
public final XSElementDecl getGlobalElementDecl(String declName) {
return(XSElementDecl)fGlobalElemDecls.get(declName);
}
public final XSElementDecl getGlobalElementDecl(String declName, String location) {
return(XSElementDecl)fGlobalElemDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global group
*/
public final XSGroupDecl getGlobalGroupDecl(String declName) {
return(XSGroupDecl)fGlobalGroupDecls.get(declName);
}
public final XSGroupDecl getGlobalGroupDecl(String declName, String location) {
return(XSGroupDecl)fGlobalGroupDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global notation
*/
public final XSNotationDecl getGlobalNotationDecl(String declName) {
return(XSNotationDecl)fGlobalNotationDecls.get(declName);
}
public final XSNotationDecl getGlobalNotationDecl(String declName, String location) {
return(XSNotationDecl)fGlobalNotationDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global type
*/
public final XSTypeDefinition getGlobalTypeDecl(String declName) {
return(XSTypeDefinition)fGlobalTypeDecls.get(declName);
}
public final XSTypeDefinition getGlobalTypeDecl(String declName, String location) {
return(XSTypeDefinition)fGlobalTypeDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one identity constraint
*/
public final IdentityConstraint getIDConstraintDecl(String declName) {
return(IdentityConstraint)fGlobalIDConstraintDecls.get(declName);
}
public final IdentityConstraint getIDConstraintDecl(String declName, String location) {
return(IdentityConstraint)fGlobalIDConstraintDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one identity constraint
*/
public final boolean hasIDConstraints() {
return fGlobalIDConstraintDecls.getLength() > 0;
}
// array to store complex type decls
private static final int INITIAL_SIZE = 16;
private static final int INC_SIZE = 16;
private int fCTCount = 0;
private XSComplexTypeDecl[] fComplexTypeDecls = new XSComplexTypeDecl[INITIAL_SIZE];
private SimpleLocator[] fCTLocators = new SimpleLocator[INITIAL_SIZE];
// an array to store groups being redefined by restriction
// even-numbered elements are the derived groups, odd-numbered ones their bases
private static final int REDEFINED_GROUP_INIT_SIZE = 2;
private int fRGCount = 0;
private XSGroupDecl[] fRedefinedGroupDecls = new XSGroupDecl[REDEFINED_GROUP_INIT_SIZE];
private SimpleLocator[] fRGLocators = new SimpleLocator[REDEFINED_GROUP_INIT_SIZE/2];
// a flag to indicate whether we have checked the 3 constraints on this
// grammar.
boolean fFullChecked = false;
/**
* add one complex type decl: for later constraint checking
*/
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
if (fCTCount == fComplexTypeDecls.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount+INC_SIZE);
fCTLocators = resize(fCTLocators, fCTCount+INC_SIZE);
}
fCTLocators[fCTCount] = locator;
fComplexTypeDecls[fCTCount++] = decl;
}
/**
* add a group redefined by restriction: for later constraint checking
*/
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
if (fRGCount == fRedefinedGroupDecls.length) {
// double array size each time.
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount << 1);
fRGLocators = resize(fRGLocators, fRGCount);
}
fRGLocators[fRGCount/2] = locator;
fRedefinedGroupDecls[fRGCount++] = derived;
fRedefinedGroupDecls[fRGCount++] = base;
}
/**
* get all complex type decls: for later constraint checking
*/
final XSComplexTypeDecl[] getUncheckedComplexTypeDecls() {
if (fCTCount < fComplexTypeDecls.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
return fComplexTypeDecls;
}
/**
* get the error locator of all complex type decls
*/
final SimpleLocator[] getUncheckedCTLocators() {
if (fCTCount < fCTLocators.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
return fCTLocators;
}
/**
* get all redefined groups: for later constraint checking
*/
final XSGroupDecl[] getRedefinedGroupDecls() {
if (fRGCount < fRedefinedGroupDecls.length) {
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount);
fRGLocators = resize(fRGLocators, fRGCount/2);
}
return fRedefinedGroupDecls;
}
/**
* get the error locator of all redefined groups
*/
final SimpleLocator[] getRGLocators() {
if (fRGCount < fRedefinedGroupDecls.length) {
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount);
fRGLocators = resize(fRGLocators, fRGCount/2);
}
return fRGLocators;
}
/**
* after the first-round checking, some types don't need to be checked
* against UPA again. here we trim the array to the proper size.
*/
final void setUncheckedTypeNum(int newSize) {
fCTCount = newSize;
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
// used to store all substitution group information declared in
// this namespace
private int fSubGroupCount = 0;
private XSElementDecl[] fSubGroups = new XSElementDecl[INITIAL_SIZE];
/**
* get all substitution group information: for the 3 constraint checking
*/
final XSElementDecl[] getSubstitutionGroups() {
if (fSubGroupCount < fSubGroups.length)
fSubGroups = resize(fSubGroups, fSubGroupCount);
return fSubGroups;
}
// anyType and anySimpleType: because there are so many places where
// we need direct access to these two types
public final static XSComplexTypeDecl fAnyType = new XSAnyType();
private static class XSAnyType extends XSComplexTypeDecl {
public XSAnyType () {
fName = SchemaSymbols.ATTVAL_ANYTYPE;
super.fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
fBaseType = this;
fDerivedBy = XSConstants.DERIVATION_RESTRICTION;
fContentType = XSComplexTypeDecl.CONTENTTYPE_MIXED;
fParticle = createParticle();
fAttrGrp = createAttrGrp();
}
// overridden methods
public void setValues(String name, String targetNamespace,
XSTypeDefinition baseType, short derivedBy, short schemaFinal,
short block, short contentType,
boolean isAbstract, XSAttributeGroupDecl attrGrp,
XSSimpleType simpleType, XSParticleDecl particle) {
// don't allow this.
}
public void setName(String name){
// don't allow this.
}
public void setIsAbstractType() {
// null implementation
}
public void setContainsTypeID() {
// null implementation
}
public void setIsAnonymous() {
// null implementation
}
public void reset() {
// null implementation
}
public XSObjectList getAnnotations() {
return XSObjectListImpl.EMPTY_LIST;
}
public XSNamespaceItem getNamespaceItem() {
return SG_SchemaNS;
}
private XSAttributeGroupDecl createAttrGrp() {
XSWildcardDecl wildcard = new XSWildcardDecl();
wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
XSAttributeGroupDecl attrGrp = new XSAttributeGroupDecl();
attrGrp.fAttributeWC = wildcard;
return attrGrp;
}
private XSParticleDecl createParticle() {
// the wildcard used in anyType (content and attribute)
// the spec will change strict to skip for anyType
XSWildcardDecl wildcard = new XSWildcardDecl();
wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
// the particle for the content wildcard
XSParticleDecl particleW = new XSParticleDecl();
particleW.fMinOccurs = 0;
particleW.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED;
particleW.fType = XSParticleDecl.PARTICLE_WILDCARD;
particleW.fValue = wildcard;
// the model group of a sequence of the above particle
XSModelGroupImpl group = new XSModelGroupImpl();
group.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE;
group.fParticleCount = 1;
group.fParticles = new XSParticleDecl[1];
group.fParticles[0] = particleW;
// the content of anyType: particle of the above model group
XSParticleDecl particleG = new XSParticleDecl();
particleG.fType = XSParticleDecl.PARTICLE_MODELGROUP;
particleG.fValue = group;
return particleG;
}
}
private static class BuiltinAttrDecl extends XSAttributeDecl {
public BuiltinAttrDecl(String name, String tns,
XSSimpleType type, short scope) {
fName = name;
super.fTargetNamespace = tns;
fType = type;
fScope = scope;
}
public void setValues(String name, String targetNamespace,
XSSimpleType simpleType, short constraintType, short scope,
ValidatedInfo valInfo, XSComplexTypeDecl enclosingCT) {
// ignore this call.
}
public void reset () {
// also ignore this call.
}
public XSAnnotation getAnnotation() {
return null;
}
public XSNamespaceItem getNamespaceItem() {
return SG_XSI;
}
} // class BuiltinAttrDecl
// the grammars to hold components of the schema namespace
public final static BuiltinSchemaGrammar SG_SchemaNS = new BuiltinSchemaGrammar(GRAMMAR_XS, Constants.SCHEMA_VERSION_1_0);
private final static BuiltinSchemaGrammar SG_SchemaNSExtended = new BuiltinSchemaGrammar(GRAMMAR_XS, Constants.SCHEMA_VERSION_1_0_EXTENDED);
public final static XSSimpleType fAnySimpleType = (XSSimpleType)SG_SchemaNS.getGlobalTypeDecl(SchemaSymbols.ATTVAL_ANYSIMPLETYPE);
// the grammars to hold components of the schema-instance namespace
public final static BuiltinSchemaGrammar SG_XSI = new BuiltinSchemaGrammar(GRAMMAR_XSI, Constants.SCHEMA_VERSION_1_0);
public static SchemaGrammar getS4SGrammar(short schemaVersion) {
if (schemaVersion == Constants.SCHEMA_VERSION_1_0) {
return SG_SchemaNS;
}
else {
return SG_SchemaNSExtended;
}
}
static final XSComplexTypeDecl[] resize(XSComplexTypeDecl[] oldArray, int newSize) {
XSComplexTypeDecl[] newArray = new XSComplexTypeDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final XSGroupDecl[] resize(XSGroupDecl[] oldArray, int newSize) {
XSGroupDecl[] newArray = new XSGroupDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final XSElementDecl[] resize(XSElementDecl[] oldArray, int newSize) {
XSElementDecl[] newArray = new XSElementDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final SimpleLocator[] resize(SimpleLocator[] oldArray, int newSize) {
SimpleLocator[] newArray = new SimpleLocator[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
// XSNamespaceItem methods
// the max index / the max value of XSObject type
private static final short MAX_COMP_IDX = XSTypeDefinition.SIMPLE_TYPE;
private static final boolean[] GLOBAL_COMP = {false, // null
true, // attribute
true, // element
true, // type
false, // attribute use
true, // attribute group
true, // group
false, // model group
false, // particle
false, // wildcard
true, // idc
true, // notation
false, // annotation
false, // facet
false, // multi value facet
true, // complex type
true // simple type
};
// store a certain kind of components from all namespaces
private XSNamedMap[] fComponents = null;
private ObjectList[] fComponentsExt = null;
// store the documents and their locations contributing to this namespace
// REVISIT: use StringList and XSObjectList for there fields.
// fDocuments is never used
private List<Object> fDocuments = null;
private List<String> fLocations = null;
public synchronized void addDocument(Object document, String location) {
if (fDocuments == null) {
// Parsing schema is not thread safe, synchronized may be removed
fDocuments = new CopyOnWriteArrayList<>();
fLocations = new CopyOnWriteArrayList<>();
}
fDocuments.add(document);
fLocations.add(location);
}
public synchronized void removeDocument(int index) {
if (fDocuments != null &&
index >= 0 &&
index < fDocuments.size()) {
fDocuments.remove(index);
fLocations.remove(index);
}
}
/**
* [schema namespace]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#nsi-schema_namespace">[schema namespace]</a>
* @return The target namespace of this item.
*/
public String getSchemaNamespace() {
return fTargetNamespace;
}
// annotation support
synchronized DOMParser getDOMParser() {
if (fDOMParser != null) {
DOMParser parser = fDOMParser.get();
if (parser != null) {
return parser;
}
}
// REVISIT: when schema handles XML 1.1, will need to
// revisit this (and the practice of not prepending an XML decl to the annotation string
XML11Configuration config = new XML11Configuration(fSymbolTable);
// note that this should never produce errors or require
// entity resolution, so just a barebones configuration with
// a couple of feature set will do fine
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true);
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false);
DOMParser parser = new DOMParser(config);
try {
parser.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.DEFER_NODE_EXPANSION_FEATURE, false);
}
catch (SAXException exc) {}
fDOMParser = new SoftReference<DOMParser>(parser);
return parser;
}
synchronized SAXParser getSAXParser() {
if (fSAXParser != null) {
SAXParser parser = fSAXParser.get();
if (parser != null) {
return parser;
}
}
// REVISIT: when schema handles XML 1.1, will need to
// revisit this (and the practice of not prepending an XML decl to the annotation string
XML11Configuration config = new XML11Configuration(fSymbolTable);
// note that this should never produce errors or require
// entity resolution, so just a barebones configuration with
// a couple of feature set will do fine
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true);
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false);
SAXParser parser = new SAXParser(config);
fSAXParser = new SoftReference<SAXParser>(parser);
return parser;
}
/**
* [schema components]: a list of top-level components, i.e. element
* declarations, attribute declarations, etc.
* @param objectType The type of the declaration, i.e.
* <code>ELEMENT_DECLARATION</code>. Note that
* <code>XSTypeDefinition.SIMPLE_TYPE</code> and
* <code>XSTypeDefinition.COMPLEX_TYPE</code> can also be used as the
* <code>objectType</code> to retrieve only complex types or simple
* types, instead of all types.
* @return A list of top-level definition of the specified type in
* <code>objectType</code> or an empty <code>XSNamedMap</code> if no
* such definitions exist.
*/
public synchronized XSNamedMap getComponents(short objectType) {
if (objectType <= 0 || objectType > MAX_COMP_IDX ||
!GLOBAL_COMP[objectType]) {
return XSNamedMapImpl.EMPTY_MAP;
}
if (fComponents == null)
fComponents = new XSNamedMap[MAX_COMP_IDX+1];
// get the hashtable for this type of components
if (fComponents[objectType] == null) {
SymbolHash table = null;
switch (objectType) {
case XSConstants.TYPE_DEFINITION:
case XSTypeDefinition.COMPLEX_TYPE:
case XSTypeDefinition.SIMPLE_TYPE:
table = fGlobalTypeDecls;
break;
case XSConstants.ATTRIBUTE_DECLARATION:
table = fGlobalAttrDecls;
break;
case XSConstants.ELEMENT_DECLARATION:
table = fGlobalElemDecls;
break;
case XSConstants.ATTRIBUTE_GROUP:
table = fGlobalAttrGrpDecls;
break;
case XSConstants.MODEL_GROUP_DEFINITION:
table = fGlobalGroupDecls;
break;
case XSConstants.NOTATION_DECLARATION:
table = fGlobalNotationDecls;
break;
case XSConstants.IDENTITY_CONSTRAINT:
table = this.fGlobalIDConstraintDecls;
break;
}
// for complex/simple types, create a special implementation,
// which take specific types out of the hash table
if (objectType == XSTypeDefinition.COMPLEX_TYPE ||
objectType == XSTypeDefinition.SIMPLE_TYPE) {
fComponents[objectType] = new XSNamedMap4Types(fTargetNamespace, table, objectType);
}
else {
fComponents[objectType] = new XSNamedMapImpl(fTargetNamespace, table);
}
}
return fComponents[objectType];
}
public synchronized ObjectList getComponentsExt(short objectType) {
if (objectType <= 0 || objectType > MAX_COMP_IDX ||
!GLOBAL_COMP[objectType]) {
return ObjectListImpl.EMPTY_LIST;
}
if (fComponentsExt == null)
fComponentsExt = new ObjectList[MAX_COMP_IDX+1];
// get the hashtable for this type of components
if (fComponentsExt[objectType] == null) {
SymbolHash table = null;
switch (objectType) {
case XSConstants.TYPE_DEFINITION:
case XSTypeDefinition.COMPLEX_TYPE:
case XSTypeDefinition.SIMPLE_TYPE:
table = fGlobalTypeDeclsExt;
break;
case XSConstants.ATTRIBUTE_DECLARATION:
table = fGlobalAttrDeclsExt;
break;
case XSConstants.ELEMENT_DECLARATION:
table = fGlobalElemDeclsExt;
break;
case XSConstants.ATTRIBUTE_GROUP:
table = fGlobalAttrGrpDeclsExt;
break;
case XSConstants.MODEL_GROUP_DEFINITION:
table = fGlobalGroupDeclsExt;
break;
case XSConstants.NOTATION_DECLARATION:
table = fGlobalNotationDeclsExt;
break;
case XSConstants.IDENTITY_CONSTRAINT:
table = this.fGlobalIDConstraintDeclsExt;
break;
}
Object[] entries = table.getEntries();
fComponentsExt[objectType] = new ObjectListImpl(entries, entries.length);
}
return fComponentsExt[objectType];
}
public synchronized void resetComponents() {
fComponents = null;
fComponentsExt = null;
}
/**
* Convenience method. Returns a top-level simple or complex type
* definition.
* @param name The name of the definition.
* @return An <code>XSTypeDefinition</code> or null if such definition
* does not exist.
*/
public XSTypeDefinition getTypeDefinition(String name) {
return getGlobalTypeDecl(name);
}
/**
* Convenience method. Returns a top-level attribute declaration.
* @param name The name of the declaration.
* @return A top-level attribute declaration or null if such declaration
* does not exist.
*/
public XSAttributeDeclaration getAttributeDeclaration(String name) {
return getGlobalAttributeDecl(name);
}
/**
* Convenience method. Returns a top-level element declaration.
* @param name The name of the declaration.
* @return A top-level element declaration or null if such declaration
* does not exist.
*/
public XSElementDeclaration getElementDeclaration(String name) {
return getGlobalElementDecl(name);
}
/**
* Convenience method. Returns a top-level attribute group definition.
* @param name The name of the definition.
* @return A top-level attribute group definition or null if such
* definition does not exist.
*/
public XSAttributeGroupDefinition getAttributeGroup(String name) {
return getGlobalAttributeGroupDecl(name);
}
/**
* Convenience method. Returns a top-level model group definition.
*
* @param name The name of the definition.
* @return A top-level model group definition definition or null if such
* definition does not exist.
*/
public XSModelGroupDefinition getModelGroupDefinition(String name) {
return getGlobalGroupDecl(name);
}
/**
* Convenience method. Returns a top-level notation declaration.
*
* @param name The name of the declaration.
* @return A top-level notation declaration or null if such declaration
* does not exist.
*/
public XSNotationDeclaration getNotationDeclaration(String name) {
return getGlobalNotationDecl(name);
}
public XSIDCDefinition getIDCDefinition(String name) {
return getIDConstraintDecl(name);
}
/**
* [document location]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#sd-document_location">[document location]</a>
* @return a list of document information item
*/
public StringList getDocumentLocations() {
return new StringListImpl(fLocations);
}
/**
* Return an <code>XSModel</code> that represents components in this schema
* grammar.
*
* @return an <code>XSModel</code> representing this schema grammar
*/
public XSModel toXSModel() {
return new XSModelImpl(new SchemaGrammar[]{this});
}
public XSModel toXSModel(XSGrammar[] grammars) {
if (grammars == null || grammars.length == 0)
return toXSModel();
int len = grammars.length;
boolean hasSelf = false;
for (int i = 0; i < len; i++) {
if (grammars[i] == this) {
hasSelf = true;
break;
}
}
SchemaGrammar[] gs = new SchemaGrammar[hasSelf ? len : len+1];
for (int i = 0; i < len; i++)
gs[i] = (SchemaGrammar)grammars[i];
if (!hasSelf)
gs[len] = this;
return new XSModelImpl(gs);
}
/**
* @see org.apache.xerces.xs.XSNamespaceItem#getAnnotations()
*/
public XSObjectList getAnnotations() {
if (fNumAnnotations == 0) {
return XSObjectListImpl.EMPTY_LIST;
}
return new XSObjectListImpl(fAnnotations, fNumAnnotations);
}
public void addAnnotation(XSAnnotationImpl annotation) {
if (annotation == null) {
return;
}
if (fAnnotations == null) {
fAnnotations = new XSAnnotationImpl[2];
}
else if (fNumAnnotations == fAnnotations.length) {
XSAnnotationImpl[] newArray = new XSAnnotationImpl[fNumAnnotations << 1];
System.arraycopy(fAnnotations, 0, newArray, 0, fNumAnnotations);
fAnnotations = newArray;
}
fAnnotations[fNumAnnotations++] = annotation;
}
public void setImmutable(boolean isImmutable) {
fIsImmutable = isImmutable;
}
public boolean isImmutable() {
return fIsImmutable;
}
} // class SchemaGrammar
| documentationType |
/**
* Copyright © 2016-2024 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thingsboard.server.service.sync.ie.importing.impl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.NotificationTargetId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.notification.targets.NotificationTarget;
import org.thingsboard.server.common.data.notification.targets.NotificationTargetType;
import org.thingsboard.server.common.data.notification.targets.platform.CustomerUsersFilter;
import org.thingsboard.server.common.data.notification.targets.platform.PlatformUsersNotificationTargetConfig;
import org.thingsboard.server.common.data.notification.targets.platform.TenantAdministratorsFilter;
import org.thingsboard.server.common.data.notification.targets.platform.UserListFilter;
import org.thingsboard.server.common.data.notification.targets.platform.UsersFilter;
import org.thingsboard.server.common.data.sync.ie.EntityExportData;
import org.thingsboard.server.dao.notification.NotificationTargetService;
import org.thingsboard.server.dao.service.ConstraintValidator;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.sync.vc.data.EntitiesImportCtx;
import java.util.List;
@Service
@TbCoreComponent
@RequiredArgsConstructor
public class NotificationTargetImportService extends BaseEntityImportService<NotificationTargetId, NotificationTarget, EntityExportData<NotificationTarget>> {
private final NotificationTargetService notificationTargetService;
@Override
protected void setOwner(TenantId tenantId, NotificationTarget notificationTarget, [MASK] idProvider) {
notificationTarget.setTenantId(tenantId);
}
@Override
protected NotificationTarget prepare(EntitiesImportCtx ctx, NotificationTarget notificationTarget, NotificationTarget oldNotificationTarget, EntityExportData<NotificationTarget> exportData, [MASK] idProvider) {
if (notificationTarget.getConfiguration().getType() == NotificationTargetType.PLATFORM_USERS) {
UsersFilter usersFilter = ((PlatformUsersNotificationTargetConfig) notificationTarget.getConfiguration()).getUsersFilter();
switch (usersFilter.getType()) {
case CUSTOMER_USERS:
CustomerUsersFilter customerUsersFilter = (CustomerUsersFilter) usersFilter;
customerUsersFilter.setCustomerId(idProvider.getInternalId(new CustomerId(customerUsersFilter.getCustomerId())).getId());
break;
case USER_LIST:
UserListFilter userListFilter = (UserListFilter) usersFilter;
userListFilter.setUsersIds(List.of(ctx.getUser().getUuidId())); // user entities are not supported by VC; replacing with current user id
break;
case TENANT_ADMINISTRATORS:
if (CollectionUtils.isNotEmpty(((TenantAdministratorsFilter) usersFilter).getTenantsIds()) ||
CollectionUtils.isNotEmpty(((TenantAdministratorsFilter) usersFilter).getTenantProfilesIds())) {
throw new IllegalArgumentException("Permission denied");
}
break;
case SYSTEM_ADMINISTRATORS:
throw new AccessDeniedException("Permission denied");
}
}
return notificationTarget;
}
@Override
protected NotificationTarget saveOrUpdate(EntitiesImportCtx ctx, NotificationTarget notificationTarget, EntityExportData<NotificationTarget> exportData, [MASK] idProvider) {
ConstraintValidator.validateFields(notificationTarget);
return notificationTargetService.saveNotificationTarget(ctx.getTenantId(), notificationTarget);
}
@Override
protected void onEntitySaved(User user, NotificationTarget savedEntity, NotificationTarget oldEntity) throws ThingsboardException {
entityActionService.logEntityAction(user, savedEntity.getId(), savedEntity, null,
oldEntity == null ? ActionType.ADDED : ActionType.UPDATED, null);
}
@Override
protected NotificationTarget deepCopy(NotificationTarget notificationTarget) {
return new NotificationTarget(notificationTarget);
}
@Override
public EntityType getEntityType() {
return EntityType.NOTIFICATION_TARGET;
}
}
| IdProvider |
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
*/
/*
* 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 com.sun.org.apache.xerces.internal.impl.xs;
import com.sun.org.apache.xerces.internal.impl.Constants;
import com.sun.org.apache.xerces.internal.impl.dv.SchemaDVFactory;
import com.sun.org.apache.xerces.internal.impl.dv.ValidatedInfo;
import com.sun.org.apache.xerces.internal.impl.dv.XSSimpleType;
import com.sun.org.apache.xerces.internal.impl.dv.xs.XSSimpleTypeDecl;
import com.sun.org.apache.xerces.internal.impl.xs.identity.IdentityConstraint;
import com.sun.org.apache.xerces.internal.impl.xs.util.ObjectListImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.SimpleLocator;
import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSNamedMap4Types;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSNamedMapImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSObjectListImpl;
import com.sun.org.apache.xerces.internal.parsers.DOMParser;
import com.sun.org.apache.xerces.internal.parsers.SAXParser;
import com.sun.org.apache.xerces.internal.parsers.XML11Configuration;
import com.sun.org.apache.xerces.internal.util.SymbolHash;
import com.sun.org.apache.xerces.internal.util.SymbolTable;
import com.sun.org.apache.xerces.internal.xni.NamespaceContext;
import com.sun.org.apache.xerces.internal.xni.grammars.XMLGrammarDescription;
import com.sun.org.apache.xerces.internal.xni.grammars.XSGrammar;
import com.sun.org.apache.xerces.internal.xs.StringList;
import com.sun.org.apache.xerces.internal.xs.XSAnnotation;
import com.sun.org.apache.xerces.internal.xs.XSAttributeDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSAttributeGroupDefinition;
import com.sun.org.apache.xerces.internal.xs.XSConstants;
import com.sun.org.apache.xerces.internal.xs.XSElementDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSIDCDefinition;
import com.sun.org.apache.xerces.internal.xs.XSModel;
import com.sun.org.apache.xerces.internal.xs.XSModelGroupDefinition;
import com.sun.org.apache.xerces.internal.xs.XSNamedMap;
import com.sun.org.apache.xerces.internal.xs.XSNamespaceItem;
import com.sun.org.apache.xerces.internal.xs.XSNotationDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSObjectList;
import com.sun.org.apache.xerces.internal.xs.XSParticle;
import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
import com.sun.org.apache.xerces.internal.xs.XSWildcard;
import com.sun.org.apache.xerces.internal.xs.datatypes.ObjectList;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.xml.sax.SAXException;
/**
* This class is to hold all schema component declaration that are declared
* within one namespace.
*
* The Grammar class this class extends contains what little
* commonality there is between XML Schema and DTD grammars. It's
* useful to distinguish grammar objects from other kinds of object
* when they exist in pools or caches.
*
* @xerces.internal
*
* @author Sandy Gao, IBM
* @author Elena Litani, IBM
*
* @LastModified: Oct 2017
*/
public class SchemaGrammar implements XSGrammar, XSNamespaceItem {
// the target namespace of grammar
String fTargetNamespace;
// global decls: map from decl name to decl object
SymbolHash fGlobalAttrDecls;
SymbolHash fGlobalAttrGrpDecls;
SymbolHash fGlobalElemDecls;
SymbolHash fGlobalGroupDecls;
SymbolHash fGlobalNotationDecls;
SymbolHash fGlobalIDConstraintDecls;
SymbolHash fGlobalTypeDecls;
// extended global decls: map from schema location + decl name to decl object
// key is location,name
SymbolHash fGlobalAttrDeclsExt;
SymbolHash fGlobalAttrGrpDeclsExt;
SymbolHash fGlobalElemDeclsExt;
SymbolHash fGlobalGroupDeclsExt;
SymbolHash fGlobalNotationDeclsExt;
SymbolHash fGlobalIDConstraintDeclsExt;
SymbolHash fGlobalTypeDeclsExt;
// A global map of all global element declarations - used for substitution group computation
// (handy when sharing components by reference, since we might end up with duplicate components
// that are not added to either of the global element declarations above)
SymbolHash fAllGlobalElemDecls;
// the XMLGrammarDescription member
XSDDescription fGrammarDescription = null;
// annotations associated with the "root" schema of this targetNamespace
XSAnnotationImpl [] fAnnotations = null;
// number of annotations declared
int fNumAnnotations;
// symbol table for constructing parsers (annotation support)
private SymbolTable fSymbolTable = null;
// parsers for annotation support
private SoftReference<SAXParser> fSAXParser = null;
private SoftReference<DOMParser> fDOMParser = null;
// is this grammar immutable? (fully constructed and not changeable)
private boolean fIsImmutable = false;
//
// Constructors
//
// needed to make BuiltinSchemaGrammar work.
protected SchemaGrammar() {}
/**
* Default constructor.
*
* @param targetNamespace
* @param grammarDesc the XMLGrammarDescription corresponding to this object
* at the least a systemId should always be known.
* @param symbolTable needed for annotation support
*/
public SchemaGrammar(String targetNamespace, XSDDescription grammarDesc,
SymbolTable symbolTable) {
fTargetNamespace = targetNamespace;
fGrammarDescription = grammarDesc;
fSymbolTable = symbolTable;
// REVISIT: the initial sizes being chosen for each SymbolHash
// may not be ideal and could still be tuned. They were chosen
// somewhat arbitrarily to reduce the initial footprint of
// SymbolHash buckets from 1,515 to 177 (about 12% of the
// default size).
fGlobalAttrDecls = new SymbolHash(12);
fGlobalAttrGrpDecls = new SymbolHash(5);
fGlobalElemDecls = new SymbolHash(25);
fGlobalGroupDecls = new SymbolHash(5);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(3);
// Extended tables
fGlobalAttrDeclsExt = new SymbolHash(12);
fGlobalAttrGrpDeclsExt = new SymbolHash(5);
fGlobalElemDeclsExt = new SymbolHash(25);
fGlobalGroupDeclsExt = new SymbolHash(5);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(3);
fGlobalTypeDeclsExt = new SymbolHash(25);
// All global elements table
fAllGlobalElemDecls = new SymbolHash(25);
// if we are parsing S4S, put built-in types in first
// they might get overwritten by the types from S4S, but that's
// considered what the application wants to do.
if (fTargetNamespace == SchemaSymbols.URI_SCHEMAFORSCHEMA) {
fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls.makeClone();
}
else {
fGlobalTypeDecls = new SymbolHash(25);
}
} // <init>(String, XSDDescription)
// Clone an existing schema grammar
public SchemaGrammar(SchemaGrammar grammar) {
fTargetNamespace = grammar.fTargetNamespace;
fGrammarDescription = grammar.fGrammarDescription.makeClone();
//fGrammarDescription.fContextType |= XSDDescription.CONTEXT_COLLISION; // REVISIT
fSymbolTable = grammar.fSymbolTable; // REVISIT
fGlobalAttrDecls = grammar.fGlobalAttrDecls.makeClone();
fGlobalAttrGrpDecls = grammar.fGlobalAttrGrpDecls.makeClone();
fGlobalElemDecls = grammar.fGlobalElemDecls.makeClone();
fGlobalGroupDecls = grammar.fGlobalGroupDecls.makeClone();
fGlobalNotationDecls = grammar.fGlobalNotationDecls.makeClone();
fGlobalIDConstraintDecls = grammar.fGlobalIDConstraintDecls.makeClone();
fGlobalTypeDecls = grammar.fGlobalTypeDecls.makeClone();
// Extended tables
fGlobalAttrDeclsExt = grammar.fGlobalAttrDeclsExt.makeClone();
fGlobalAttrGrpDeclsExt = grammar.fGlobalAttrGrpDeclsExt.makeClone();
fGlobalElemDeclsExt = grammar.fGlobalElemDeclsExt.makeClone();
fGlobalGroupDeclsExt = grammar.fGlobalGroupDeclsExt.makeClone();
fGlobalNotationDeclsExt = grammar.fGlobalNotationDeclsExt.makeClone();
fGlobalIDConstraintDeclsExt = grammar.fGlobalIDConstraintDeclsExt.makeClone();
fGlobalTypeDeclsExt = grammar.fGlobalTypeDeclsExt.makeClone();
// All global elements table
fAllGlobalElemDecls = grammar.fAllGlobalElemDecls.makeClone();
// Annotations associated with the "root" schema of this targetNamespace
fNumAnnotations = grammar.fNumAnnotations;
if (fNumAnnotations > 0) {
fAnnotations = new XSAnnotationImpl[grammar.fAnnotations.length];
System.arraycopy(grammar.fAnnotations, 0, fAnnotations, 0, fNumAnnotations);
}
// All substitution group information declared in this namespace
fSubGroupCount = grammar.fSubGroupCount;
if (fSubGroupCount > 0) {
fSubGroups = new XSElementDecl[grammar.fSubGroups.length];
System.arraycopy(grammar.fSubGroups, 0, fSubGroups, 0, fSubGroupCount);
}
// Array to store complex type decls for constraint checking
fCTCount = grammar.fCTCount;
if (fCTCount > 0) {
fComplexTypeDecls = new XSComplexTypeDecl[grammar.fComplexTypeDecls.length];
fCTLocators = new SimpleLocator[grammar.fCTLocators.length];
System.arraycopy(grammar.fComplexTypeDecls, 0, fComplexTypeDecls, 0, fCTCount);
System.arraycopy(grammar.fCTLocators, 0, fCTLocators, 0, fCTCount);
}
// Groups being redefined by restriction
fRGCount = grammar.fRGCount;
if (fRGCount > 0) {
fRedefinedGroupDecls = new XSGroupDecl[grammar.fRedefinedGroupDecls.length];
fRGLocators = new SimpleLocator[grammar.fRGLocators.length];
System.arraycopy(grammar.fRedefinedGroupDecls, 0, fRedefinedGroupDecls, 0, fRGCount);
System.arraycopy(grammar.fRGLocators, 0, fRGLocators, 0, fRGCount/2);
}
// List of imported grammars
if (grammar.fImported != null) {
fImported = new ArrayList<>();
for (int i=0; i<grammar.fImported.size(); i++) {
fImported.add(grammar.fImported.get(i));
}
}
// Locations
if (grammar.fLocations != null) {
for (int k=0; k<grammar.fLocations.size(); k++) {
addDocument(null, grammar.fLocations.get(k));
}
}
} // <init>(String, XSDDescription)
// number of built-in XSTypes we need to create for base and full
// datatype set
private static final int BASICSET_COUNT = 29;
private static final int FULLSET_COUNT = 46;
private static final int GRAMMAR_XS = 1;
private static final int GRAMMAR_XSI = 2;
// this class makes sure the static, built-in schema grammars
// are immutable.
public static class BuiltinSchemaGrammar extends SchemaGrammar {
private static final String EXTENDED_SCHEMA_FACTORY_CLASS = "com.sun.org.apache.xerces.internal.impl.dv.xs.ExtendedSchemaDVFactoryImpl";
/**
* Special constructor to create the grammars for the schema namespaces
*
* @param grammar
*/
public BuiltinSchemaGrammar(int grammar, short schemaVersion) {
SchemaDVFactory schemaFactory;
if (schemaVersion == Constants.SCHEMA_VERSION_1_0) {
schemaFactory = SchemaDVFactory.getInstance();
}
else {
schemaFactory = SchemaDVFactory.getInstance(EXTENDED_SCHEMA_FACTORY_CLASS);
}
if (grammar == GRAMMAR_XS) {
// target namespace
fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA);
// no global decls other than types
fGlobalAttrDecls = new SymbolHash(1);
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(1);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(1);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// all global element decls table
fAllGlobalElemDecls = new SymbolHash(1);
// get all built-in types
fGlobalTypeDecls = schemaFactory.getBuiltInTypes();
// assign the built-in schema grammar as the XSNamespaceItem
// for each of the built-in simple type definitions.
int length = fGlobalTypeDecls.getLength();
XSTypeDefinition [] typeDefinitions = new XSTypeDefinition[length];
fGlobalTypeDecls.getValues(typeDefinitions, 0);
for (int i = 0; i < length; ++i) {
XSTypeDefinition xtd = typeDefinitions[i];
if (xtd instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) xtd).setNamespaceItem(this);
}
}
// add anyType
fGlobalTypeDecls.put(fAnyType.getName(), fAnyType);
}
else if (grammar == GRAMMAR_XSI) {
// target namespace
fTargetNamespace = SchemaSymbols.URI_XSI;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_XSI);
// no global decls other than attributes
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(1);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
fGlobalTypeDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(1);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// no all global element decls
fAllGlobalElemDecls = new SymbolHash(1);
// 4 attributes, so initialize the size as 4*2 = 8
fGlobalAttrDecls = new SymbolHash(8);
String name = null;
String tns = null;
XSSimpleType type = null;
short scope = XSConstants.SCOPE_GLOBAL;
// xsi:type
name = SchemaSymbols.XSI_TYPE;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_QNAME);
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
// xsi:nil
name = SchemaSymbols.XSI_NIL;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_BOOLEAN);
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
XSSimpleType anyURI = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_ANYURI);
// xsi:schemaLocation
name = SchemaSymbols.XSI_SCHEMALOCATION;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.createTypeList("#AnonType_schemaLocation", SchemaSymbols.URI_XSI, (short)0, anyURI, null);
if (type instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl)type).setAnonymous(true);
}
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
// xsi:noNamespaceSchemaLocation
name = SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION;
tns = SchemaSymbols.URI_XSI;
type = anyURI;
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
}
} // <init>(int)
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription.makeClone();
} // getGrammarDescription(): XMLGrammarDescription
// override these methods solely so that these
// objects cannot be modified once they're created.
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl, String location) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
// ignore
}
public void addGlobalElementDeclAll(XSElementDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
// ignore
}
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
// ignore
}
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
// ignore
}
public synchronized void addDocument(Object document, String location) {
// ignore
}
// annotation support
synchronized DOMParser getDOMParser() {
return null;
}
synchronized SAXParser getSAXParser() {
return null;
}
}
/**
* <p>A partial schema for schemas for validating annotations.</p>
*
* @xerces.internal
*
* @author Michael Glavassevich, IBM
*/
public static final class Schema4Annotations extends SchemaGrammar {
/**
* Singleton instance.
*/
public static final Schema4Annotations INSTANCE = new Schema4Annotations();
/**
* Special constructor to create a schema
* capable of validating annotations.
*/
private Schema4Annotations() {
// target namespace
fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA);
// no global decls other than types and
// element declarations for <annotation>, <documentation> and <appinfo>.
fGlobalAttrDecls = new SymbolHash(1);
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(6);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(6);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// all global element declarations
fAllGlobalElemDecls = new SymbolHash(6);
// get all built-in types
fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls;
// create element declarations for <annotation>, <documentation> and <appinfo>
XSElementDecl annotationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_ANNOTATION);
XSElementDecl documentationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_DOCUMENTATION);
XSElementDecl appinfoDecl = createAnnotationElementDecl(SchemaSymbols.ELT_APPINFO);
// add global element declarations
fGlobalElemDecls.put(annotationDecl.fName, annotationDecl);
fGlobalElemDecls.put(documentationDecl.fName, documentationDecl);
fGlobalElemDecls.put(appinfoDecl.fName, appinfoDecl);
fGlobalElemDeclsExt.put(","+annotationDecl.fName, annotationDecl);
fGlobalElemDeclsExt.put(","+documentationDecl.fName, documentationDecl);
fGlobalElemDeclsExt.put(","+appinfoDecl.fName, appinfoDecl);
fAllGlobalElemDecls.put(annotationDecl, annotationDecl);
fAllGlobalElemDecls.put(documentationDecl, documentationDecl);
fAllGlobalElemDecls.put(appinfoDecl, appinfoDecl);
// create complex type declarations for <annotation>, <documentation> and <appinfo>
XSComplexTypeDecl annotationType = new XSComplexTypeDecl();
XSComplexTypeDecl documentationType = new XSComplexTypeDecl();
XSComplexTypeDecl appinfoType = new XSComplexTypeDecl();
// set the types on their element declarations
annotationDecl.fType = annotationType;
documentationDecl.fType = documentationType;
appinfoDecl.fType = appinfoType;
// create attribute groups for <annotation>, <documentation> and <appinfo>
XSAttributeGroupDecl annotationAttrs = new XSAttributeGroupDecl();
XSAttributeGroupDecl documentationAttrs = new XSAttributeGroupDecl();
XSAttributeGroupDecl appinfoAttrs = new XSAttributeGroupDecl();
// fill in attribute groups
{
// create and fill attribute uses for <annotation>, <documentation> and <appinfo>
XSAttributeUseImpl annotationIDAttr = new XSAttributeUseImpl();
annotationIDAttr. [MASK] = new XSAttributeDecl();
annotationIDAttr. [MASK] .setValues(SchemaSymbols.ATT_ID, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ID),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, annotationType, null);
annotationIDAttr.fUse = SchemaSymbols.USE_OPTIONAL;
annotationIDAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl documentationSourceAttr = new XSAttributeUseImpl();
documentationSourceAttr. [MASK] = new XSAttributeDecl();
documentationSourceAttr. [MASK] .setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ANYURI),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, documentationType, null);
documentationSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL;
documentationSourceAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl documentationLangAttr = new XSAttributeUseImpl();
documentationLangAttr. [MASK] = new XSAttributeDecl();
documentationLangAttr. [MASK] .setValues("lang".intern(), NamespaceContext.XML_URI, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_LANGUAGE),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, documentationType, null);
documentationLangAttr.fUse = SchemaSymbols.USE_OPTIONAL;
documentationLangAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl appinfoSourceAttr = new XSAttributeUseImpl();
appinfoSourceAttr. [MASK] = new XSAttributeDecl();
appinfoSourceAttr. [MASK] .setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ANYURI),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, appinfoType, null);
appinfoSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL;
appinfoSourceAttr.fConstraintType = XSConstants.VC_NONE;
// create lax attribute wildcard for <annotation>, <documentation> and <appinfo>
XSWildcardDecl otherAttrs = new XSWildcardDecl();
otherAttrs.fNamespaceList = new String [] {fTargetNamespace, null};
otherAttrs.fType = XSWildcard.NSCONSTRAINT_NOT;
otherAttrs.fProcessContents = XSWildcard.PC_LAX;
// add attribute uses and wildcards to attribute groups for <annotation>, <documentation> and <appinfo>
annotationAttrs.addAttributeUse(annotationIDAttr);
annotationAttrs.fAttributeWC = otherAttrs;
documentationAttrs.addAttributeUse(documentationSourceAttr);
documentationAttrs.addAttributeUse(documentationLangAttr);
documentationAttrs.fAttributeWC = otherAttrs;
appinfoAttrs.addAttributeUse(appinfoSourceAttr);
appinfoAttrs.fAttributeWC = otherAttrs;
}
// create particles for <annotation>
XSParticleDecl annotationParticle = createUnboundedModelGroupParticle();
{
XSModelGroupImpl annotationChoice = new XSModelGroupImpl();
annotationChoice.fCompositor = XSModelGroupImpl.MODELGROUP_CHOICE;
annotationChoice.fParticleCount = 2;
annotationChoice.fParticles = new XSParticleDecl[2];
annotationChoice.fParticles[0] = createChoiceElementParticle(appinfoDecl);
annotationChoice.fParticles[1] = createChoiceElementParticle(documentationDecl);
annotationParticle.fValue = annotationChoice;
}
// create wildcard particle for <documentation> and <appinfo>
XSParticleDecl anyWCSequenceParticle = createUnboundedAnyWildcardSequenceParticle();
// fill complex types
annotationType.setValues("#AnonType_" + SchemaSymbols.ELT_ANNOTATION, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_ELEMENT, false, annotationAttrs, null, annotationParticle, XSObjectListImpl.EMPTY_LIST);
annotationType.setName("#AnonType_" + SchemaSymbols.ELT_ANNOTATION);
annotationType.setIsAnonymous();
documentationType.setValues("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_MIXED, false, documentationAttrs, null, anyWCSequenceParticle, XSObjectListImpl.EMPTY_LIST);
documentationType.setName("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION);
documentationType.setIsAnonymous();
appinfoType.setValues("#AnonType_" + SchemaSymbols.ELT_APPINFO, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_MIXED, false, appinfoAttrs, null, anyWCSequenceParticle, XSObjectListImpl.EMPTY_LIST);
appinfoType.setName("#AnonType_" + SchemaSymbols.ELT_APPINFO);
appinfoType.setIsAnonymous();
} // <init>(int)
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription.makeClone();
} // getGrammarDescription(): XMLGrammarDescription
// override these methods solely so that these
// objects cannot be modified once they're created.
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
// ignore
}
public void addGlobalElementDeclAll(XSElementDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
// ignore
}
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
// ignore
}
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
// ignore
}
public synchronized void addDocument(Object document, String location) {
// ignore
}
// annotation support
synchronized DOMParser getDOMParser() {
return null;
}
synchronized SAXParser getSAXParser() {
return null;
}
//
// private helper methods
//
private XSElementDecl createAnnotationElementDecl(String localName) {
XSElementDecl eDecl = new XSElementDecl();
eDecl.fName = localName;
eDecl.fTargetNamespace = fTargetNamespace;
eDecl.setIsGlobal();
eDecl.fBlock = (XSConstants.DERIVATION_EXTENSION |
XSConstants.DERIVATION_RESTRICTION | XSConstants.DERIVATION_SUBSTITUTION);
eDecl.setConstraintType(XSConstants.VC_NONE);
return eDecl;
}
private XSParticleDecl createUnboundedModelGroupParticle() {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 0;
particle.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED;
particle.fType = XSParticleDecl.PARTICLE_MODELGROUP;
return particle;
}
private XSParticleDecl createChoiceElementParticle(XSElementDecl ref) {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 1;
particle.fMaxOccurs = 1;
particle.fType = XSParticleDecl.PARTICLE_ELEMENT;
particle.fValue = ref;
return particle;
}
private XSParticleDecl createUnboundedAnyWildcardSequenceParticle() {
XSParticleDecl particle = createUnboundedModelGroupParticle();
XSModelGroupImpl sequence = new XSModelGroupImpl();
sequence.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE;
sequence.fParticleCount = 1;
sequence.fParticles = new XSParticleDecl[1];
sequence.fParticles[0] = createAnyLaxWildcardParticle();
particle.fValue = sequence;
return particle;
}
private XSParticleDecl createAnyLaxWildcardParticle() {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 1;
particle.fMaxOccurs = 1;
particle.fType = XSParticleDecl.PARTICLE_WILDCARD;
XSWildcardDecl anyWC = new XSWildcardDecl();
anyWC.fNamespaceList = null;
anyWC.fType = XSWildcard.NSCONSTRAINT_ANY;
anyWC.fProcessContents = XSWildcard.PC_LAX;
particle.fValue = anyWC;
return particle;
}
}
// Grammar methods
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription;
} // getGrammarDescription(): XMLGrammarDescription
// DTDGrammar methods
public boolean isNamespaceAware () {
return true;
} // isNamespaceAware():boolean
List<SchemaGrammar> fImported = null;
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
fImported = importedGrammars;
}
public List<SchemaGrammar> getImportedGrammars() {
return fImported;
}
/**
* Returns this grammar's target namespace.
*/
public final String getTargetNamespace() {
return fTargetNamespace;
} // getTargetNamespace():String
/**
* register one global attribute
*/
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
fGlobalAttrDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalAttributeDecl(XSAttributeDecl decl, String location) {
fGlobalAttrDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global attribute group
*/
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
fGlobalAttrGrpDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
fGlobalAttrGrpDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global element
*/
public void addGlobalElementDeclAll(XSElementDecl decl) {
if (fAllGlobalElemDecls.get(decl) == null) {
fAllGlobalElemDecls.put(decl, decl);
// if there is a substitution group affiliation, store in an array,
// for further constraint checking: UPA, PD, EDC
if (decl.fSubGroup != null) {
if (fSubGroupCount == fSubGroups.length)
fSubGroups = resize(fSubGroups, fSubGroupCount+INC_SIZE);
fSubGroups[fSubGroupCount++] = decl;
}
}
}
public void addGlobalElementDecl(XSElementDecl decl) {
fGlobalElemDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
fGlobalElemDeclsExt.put(((location != null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global group
*/
public void addGlobalGroupDecl(XSGroupDecl decl) {
fGlobalGroupDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
fGlobalGroupDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global notation
*/
public void addGlobalNotationDecl(XSNotationDecl decl) {
fGlobalNotationDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
fGlobalNotationDeclsExt.put(((location!=null) ? location : "") + "," +decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global type
*/
public void addGlobalTypeDecl(XSTypeDefinition decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
if (decl instanceof XSComplexTypeDecl) {
((XSComplexTypeDecl) decl).setNamespaceItem(this);
}
else if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
fGlobalTypeDeclsExt.put(((location!=null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null) {
if (decl instanceof XSComplexTypeDecl) {
((XSComplexTypeDecl) decl).setNamespaceItem(this);
}
else if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
}
/**
* register one global complex type
*/
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
decl.setNamespaceItem(this);
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
fGlobalTypeDeclsExt.put(((location!=null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global simple type
*/
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
fGlobalTypeDeclsExt.put(((location != null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null && decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
/**
* register one identity constraint
*/
public final void addIDConstraintDecl(XSElementDecl elmDecl, IdentityConstraint decl) {
elmDecl.addIDConstraint(decl);
fGlobalIDConstraintDecls.put(decl.getIdentityConstraintName(), decl);
}
public final void addIDConstraintDecl(XSElementDecl elmDecl, IdentityConstraint decl, String location) {
fGlobalIDConstraintDeclsExt.put(((location != null) ? location : "") + "," + decl.getIdentityConstraintName(), decl);
}
/**
* get one global attribute
*/
public final XSAttributeDecl getGlobalAttributeDecl(String declName) {
return(XSAttributeDecl)fGlobalAttrDecls.get(declName);
}
public final XSAttributeDecl getGlobalAttributeDecl(String declName, String location) {
return(XSAttributeDecl)fGlobalAttrDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global attribute group
*/
public final XSAttributeGroupDecl getGlobalAttributeGroupDecl(String declName) {
return(XSAttributeGroupDecl)fGlobalAttrGrpDecls.get(declName);
}
public final XSAttributeGroupDecl getGlobalAttributeGroupDecl(String declName, String location) {
return(XSAttributeGroupDecl)fGlobalAttrGrpDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global element
*/
public final XSElementDecl getGlobalElementDecl(String declName) {
return(XSElementDecl)fGlobalElemDecls.get(declName);
}
public final XSElementDecl getGlobalElementDecl(String declName, String location) {
return(XSElementDecl)fGlobalElemDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global group
*/
public final XSGroupDecl getGlobalGroupDecl(String declName) {
return(XSGroupDecl)fGlobalGroupDecls.get(declName);
}
public final XSGroupDecl getGlobalGroupDecl(String declName, String location) {
return(XSGroupDecl)fGlobalGroupDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global notation
*/
public final XSNotationDecl getGlobalNotationDecl(String declName) {
return(XSNotationDecl)fGlobalNotationDecls.get(declName);
}
public final XSNotationDecl getGlobalNotationDecl(String declName, String location) {
return(XSNotationDecl)fGlobalNotationDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global type
*/
public final XSTypeDefinition getGlobalTypeDecl(String declName) {
return(XSTypeDefinition)fGlobalTypeDecls.get(declName);
}
public final XSTypeDefinition getGlobalTypeDecl(String declName, String location) {
return(XSTypeDefinition)fGlobalTypeDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one identity constraint
*/
public final IdentityConstraint getIDConstraintDecl(String declName) {
return(IdentityConstraint)fGlobalIDConstraintDecls.get(declName);
}
public final IdentityConstraint getIDConstraintDecl(String declName, String location) {
return(IdentityConstraint)fGlobalIDConstraintDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one identity constraint
*/
public final boolean hasIDConstraints() {
return fGlobalIDConstraintDecls.getLength() > 0;
}
// array to store complex type decls
private static final int INITIAL_SIZE = 16;
private static final int INC_SIZE = 16;
private int fCTCount = 0;
private XSComplexTypeDecl[] fComplexTypeDecls = new XSComplexTypeDecl[INITIAL_SIZE];
private SimpleLocator[] fCTLocators = new SimpleLocator[INITIAL_SIZE];
// an array to store groups being redefined by restriction
// even-numbered elements are the derived groups, odd-numbered ones their bases
private static final int REDEFINED_GROUP_INIT_SIZE = 2;
private int fRGCount = 0;
private XSGroupDecl[] fRedefinedGroupDecls = new XSGroupDecl[REDEFINED_GROUP_INIT_SIZE];
private SimpleLocator[] fRGLocators = new SimpleLocator[REDEFINED_GROUP_INIT_SIZE/2];
// a flag to indicate whether we have checked the 3 constraints on this
// grammar.
boolean fFullChecked = false;
/**
* add one complex type decl: for later constraint checking
*/
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
if (fCTCount == fComplexTypeDecls.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount+INC_SIZE);
fCTLocators = resize(fCTLocators, fCTCount+INC_SIZE);
}
fCTLocators[fCTCount] = locator;
fComplexTypeDecls[fCTCount++] = decl;
}
/**
* add a group redefined by restriction: for later constraint checking
*/
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
if (fRGCount == fRedefinedGroupDecls.length) {
// double array size each time.
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount << 1);
fRGLocators = resize(fRGLocators, fRGCount);
}
fRGLocators[fRGCount/2] = locator;
fRedefinedGroupDecls[fRGCount++] = derived;
fRedefinedGroupDecls[fRGCount++] = base;
}
/**
* get all complex type decls: for later constraint checking
*/
final XSComplexTypeDecl[] getUncheckedComplexTypeDecls() {
if (fCTCount < fComplexTypeDecls.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
return fComplexTypeDecls;
}
/**
* get the error locator of all complex type decls
*/
final SimpleLocator[] getUncheckedCTLocators() {
if (fCTCount < fCTLocators.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
return fCTLocators;
}
/**
* get all redefined groups: for later constraint checking
*/
final XSGroupDecl[] getRedefinedGroupDecls() {
if (fRGCount < fRedefinedGroupDecls.length) {
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount);
fRGLocators = resize(fRGLocators, fRGCount/2);
}
return fRedefinedGroupDecls;
}
/**
* get the error locator of all redefined groups
*/
final SimpleLocator[] getRGLocators() {
if (fRGCount < fRedefinedGroupDecls.length) {
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount);
fRGLocators = resize(fRGLocators, fRGCount/2);
}
return fRGLocators;
}
/**
* after the first-round checking, some types don't need to be checked
* against UPA again. here we trim the array to the proper size.
*/
final void setUncheckedTypeNum(int newSize) {
fCTCount = newSize;
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
// used to store all substitution group information declared in
// this namespace
private int fSubGroupCount = 0;
private XSElementDecl[] fSubGroups = new XSElementDecl[INITIAL_SIZE];
/**
* get all substitution group information: for the 3 constraint checking
*/
final XSElementDecl[] getSubstitutionGroups() {
if (fSubGroupCount < fSubGroups.length)
fSubGroups = resize(fSubGroups, fSubGroupCount);
return fSubGroups;
}
// anyType and anySimpleType: because there are so many places where
// we need direct access to these two types
public final static XSComplexTypeDecl fAnyType = new XSAnyType();
private static class XSAnyType extends XSComplexTypeDecl {
public XSAnyType () {
fName = SchemaSymbols.ATTVAL_ANYTYPE;
super.fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
fBaseType = this;
fDerivedBy = XSConstants.DERIVATION_RESTRICTION;
fContentType = XSComplexTypeDecl.CONTENTTYPE_MIXED;
fParticle = createParticle();
fAttrGrp = createAttrGrp();
}
// overridden methods
public void setValues(String name, String targetNamespace,
XSTypeDefinition baseType, short derivedBy, short schemaFinal,
short block, short contentType,
boolean isAbstract, XSAttributeGroupDecl attrGrp,
XSSimpleType simpleType, XSParticleDecl particle) {
// don't allow this.
}
public void setName(String name){
// don't allow this.
}
public void setIsAbstractType() {
// null implementation
}
public void setContainsTypeID() {
// null implementation
}
public void setIsAnonymous() {
// null implementation
}
public void reset() {
// null implementation
}
public XSObjectList getAnnotations() {
return XSObjectListImpl.EMPTY_LIST;
}
public XSNamespaceItem getNamespaceItem() {
return SG_SchemaNS;
}
private XSAttributeGroupDecl createAttrGrp() {
XSWildcardDecl wildcard = new XSWildcardDecl();
wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
XSAttributeGroupDecl attrGrp = new XSAttributeGroupDecl();
attrGrp.fAttributeWC = wildcard;
return attrGrp;
}
private XSParticleDecl createParticle() {
// the wildcard used in anyType (content and attribute)
// the spec will change strict to skip for anyType
XSWildcardDecl wildcard = new XSWildcardDecl();
wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
// the particle for the content wildcard
XSParticleDecl particleW = new XSParticleDecl();
particleW.fMinOccurs = 0;
particleW.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED;
particleW.fType = XSParticleDecl.PARTICLE_WILDCARD;
particleW.fValue = wildcard;
// the model group of a sequence of the above particle
XSModelGroupImpl group = new XSModelGroupImpl();
group.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE;
group.fParticleCount = 1;
group.fParticles = new XSParticleDecl[1];
group.fParticles[0] = particleW;
// the content of anyType: particle of the above model group
XSParticleDecl particleG = new XSParticleDecl();
particleG.fType = XSParticleDecl.PARTICLE_MODELGROUP;
particleG.fValue = group;
return particleG;
}
}
private static class BuiltinAttrDecl extends XSAttributeDecl {
public BuiltinAttrDecl(String name, String tns,
XSSimpleType type, short scope) {
fName = name;
super.fTargetNamespace = tns;
fType = type;
fScope = scope;
}
public void setValues(String name, String targetNamespace,
XSSimpleType simpleType, short constraintType, short scope,
ValidatedInfo valInfo, XSComplexTypeDecl enclosingCT) {
// ignore this call.
}
public void reset () {
// also ignore this call.
}
public XSAnnotation getAnnotation() {
return null;
}
public XSNamespaceItem getNamespaceItem() {
return SG_XSI;
}
} // class BuiltinAttrDecl
// the grammars to hold components of the schema namespace
public final static BuiltinSchemaGrammar SG_SchemaNS = new BuiltinSchemaGrammar(GRAMMAR_XS, Constants.SCHEMA_VERSION_1_0);
private final static BuiltinSchemaGrammar SG_SchemaNSExtended = new BuiltinSchemaGrammar(GRAMMAR_XS, Constants.SCHEMA_VERSION_1_0_EXTENDED);
public final static XSSimpleType fAnySimpleType = (XSSimpleType)SG_SchemaNS.getGlobalTypeDecl(SchemaSymbols.ATTVAL_ANYSIMPLETYPE);
// the grammars to hold components of the schema-instance namespace
public final static BuiltinSchemaGrammar SG_XSI = new BuiltinSchemaGrammar(GRAMMAR_XSI, Constants.SCHEMA_VERSION_1_0);
public static SchemaGrammar getS4SGrammar(short schemaVersion) {
if (schemaVersion == Constants.SCHEMA_VERSION_1_0) {
return SG_SchemaNS;
}
else {
return SG_SchemaNSExtended;
}
}
static final XSComplexTypeDecl[] resize(XSComplexTypeDecl[] oldArray, int newSize) {
XSComplexTypeDecl[] newArray = new XSComplexTypeDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final XSGroupDecl[] resize(XSGroupDecl[] oldArray, int newSize) {
XSGroupDecl[] newArray = new XSGroupDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final XSElementDecl[] resize(XSElementDecl[] oldArray, int newSize) {
XSElementDecl[] newArray = new XSElementDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final SimpleLocator[] resize(SimpleLocator[] oldArray, int newSize) {
SimpleLocator[] newArray = new SimpleLocator[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
// XSNamespaceItem methods
// the max index / the max value of XSObject type
private static final short MAX_COMP_IDX = XSTypeDefinition.SIMPLE_TYPE;
private static final boolean[] GLOBAL_COMP = {false, // null
true, // attribute
true, // element
true, // type
false, // attribute use
true, // attribute group
true, // group
false, // model group
false, // particle
false, // wildcard
true, // idc
true, // notation
false, // annotation
false, // facet
false, // multi value facet
true, // complex type
true // simple type
};
// store a certain kind of components from all namespaces
private XSNamedMap[] fComponents = null;
private ObjectList[] fComponentsExt = null;
// store the documents and their locations contributing to this namespace
// REVISIT: use StringList and XSObjectList for there fields.
// fDocuments is never used
private List<Object> fDocuments = null;
private List<String> fLocations = null;
public synchronized void addDocument(Object document, String location) {
if (fDocuments == null) {
// Parsing schema is not thread safe, synchronized may be removed
fDocuments = new CopyOnWriteArrayList<>();
fLocations = new CopyOnWriteArrayList<>();
}
fDocuments.add(document);
fLocations.add(location);
}
public synchronized void removeDocument(int index) {
if (fDocuments != null &&
index >= 0 &&
index < fDocuments.size()) {
fDocuments.remove(index);
fLocations.remove(index);
}
}
/**
* [schema namespace]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#nsi-schema_namespace">[schema namespace]</a>
* @return The target namespace of this item.
*/
public String getSchemaNamespace() {
return fTargetNamespace;
}
// annotation support
synchronized DOMParser getDOMParser() {
if (fDOMParser != null) {
DOMParser parser = fDOMParser.get();
if (parser != null) {
return parser;
}
}
// REVISIT: when schema handles XML 1.1, will need to
// revisit this (and the practice of not prepending an XML decl to the annotation string
XML11Configuration config = new XML11Configuration(fSymbolTable);
// note that this should never produce errors or require
// entity resolution, so just a barebones configuration with
// a couple of feature set will do fine
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true);
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false);
DOMParser parser = new DOMParser(config);
try {
parser.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.DEFER_NODE_EXPANSION_FEATURE, false);
}
catch (SAXException exc) {}
fDOMParser = new SoftReference<DOMParser>(parser);
return parser;
}
synchronized SAXParser getSAXParser() {
if (fSAXParser != null) {
SAXParser parser = fSAXParser.get();
if (parser != null) {
return parser;
}
}
// REVISIT: when schema handles XML 1.1, will need to
// revisit this (and the practice of not prepending an XML decl to the annotation string
XML11Configuration config = new XML11Configuration(fSymbolTable);
// note that this should never produce errors or require
// entity resolution, so just a barebones configuration with
// a couple of feature set will do fine
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true);
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false);
SAXParser parser = new SAXParser(config);
fSAXParser = new SoftReference<SAXParser>(parser);
return parser;
}
/**
* [schema components]: a list of top-level components, i.e. element
* declarations, attribute declarations, etc.
* @param objectType The type of the declaration, i.e.
* <code>ELEMENT_DECLARATION</code>. Note that
* <code>XSTypeDefinition.SIMPLE_TYPE</code> and
* <code>XSTypeDefinition.COMPLEX_TYPE</code> can also be used as the
* <code>objectType</code> to retrieve only complex types or simple
* types, instead of all types.
* @return A list of top-level definition of the specified type in
* <code>objectType</code> or an empty <code>XSNamedMap</code> if no
* such definitions exist.
*/
public synchronized XSNamedMap getComponents(short objectType) {
if (objectType <= 0 || objectType > MAX_COMP_IDX ||
!GLOBAL_COMP[objectType]) {
return XSNamedMapImpl.EMPTY_MAP;
}
if (fComponents == null)
fComponents = new XSNamedMap[MAX_COMP_IDX+1];
// get the hashtable for this type of components
if (fComponents[objectType] == null) {
SymbolHash table = null;
switch (objectType) {
case XSConstants.TYPE_DEFINITION:
case XSTypeDefinition.COMPLEX_TYPE:
case XSTypeDefinition.SIMPLE_TYPE:
table = fGlobalTypeDecls;
break;
case XSConstants.ATTRIBUTE_DECLARATION:
table = fGlobalAttrDecls;
break;
case XSConstants.ELEMENT_DECLARATION:
table = fGlobalElemDecls;
break;
case XSConstants.ATTRIBUTE_GROUP:
table = fGlobalAttrGrpDecls;
break;
case XSConstants.MODEL_GROUP_DEFINITION:
table = fGlobalGroupDecls;
break;
case XSConstants.NOTATION_DECLARATION:
table = fGlobalNotationDecls;
break;
case XSConstants.IDENTITY_CONSTRAINT:
table = this.fGlobalIDConstraintDecls;
break;
}
// for complex/simple types, create a special implementation,
// which take specific types out of the hash table
if (objectType == XSTypeDefinition.COMPLEX_TYPE ||
objectType == XSTypeDefinition.SIMPLE_TYPE) {
fComponents[objectType] = new XSNamedMap4Types(fTargetNamespace, table, objectType);
}
else {
fComponents[objectType] = new XSNamedMapImpl(fTargetNamespace, table);
}
}
return fComponents[objectType];
}
public synchronized ObjectList getComponentsExt(short objectType) {
if (objectType <= 0 || objectType > MAX_COMP_IDX ||
!GLOBAL_COMP[objectType]) {
return ObjectListImpl.EMPTY_LIST;
}
if (fComponentsExt == null)
fComponentsExt = new ObjectList[MAX_COMP_IDX+1];
// get the hashtable for this type of components
if (fComponentsExt[objectType] == null) {
SymbolHash table = null;
switch (objectType) {
case XSConstants.TYPE_DEFINITION:
case XSTypeDefinition.COMPLEX_TYPE:
case XSTypeDefinition.SIMPLE_TYPE:
table = fGlobalTypeDeclsExt;
break;
case XSConstants.ATTRIBUTE_DECLARATION:
table = fGlobalAttrDeclsExt;
break;
case XSConstants.ELEMENT_DECLARATION:
table = fGlobalElemDeclsExt;
break;
case XSConstants.ATTRIBUTE_GROUP:
table = fGlobalAttrGrpDeclsExt;
break;
case XSConstants.MODEL_GROUP_DEFINITION:
table = fGlobalGroupDeclsExt;
break;
case XSConstants.NOTATION_DECLARATION:
table = fGlobalNotationDeclsExt;
break;
case XSConstants.IDENTITY_CONSTRAINT:
table = this.fGlobalIDConstraintDeclsExt;
break;
}
Object[] entries = table.getEntries();
fComponentsExt[objectType] = new ObjectListImpl(entries, entries.length);
}
return fComponentsExt[objectType];
}
public synchronized void resetComponents() {
fComponents = null;
fComponentsExt = null;
}
/**
* Convenience method. Returns a top-level simple or complex type
* definition.
* @param name The name of the definition.
* @return An <code>XSTypeDefinition</code> or null if such definition
* does not exist.
*/
public XSTypeDefinition getTypeDefinition(String name) {
return getGlobalTypeDecl(name);
}
/**
* Convenience method. Returns a top-level attribute declaration.
* @param name The name of the declaration.
* @return A top-level attribute declaration or null if such declaration
* does not exist.
*/
public XSAttributeDeclaration getAttributeDeclaration(String name) {
return getGlobalAttributeDecl(name);
}
/**
* Convenience method. Returns a top-level element declaration.
* @param name The name of the declaration.
* @return A top-level element declaration or null if such declaration
* does not exist.
*/
public XSElementDeclaration getElementDeclaration(String name) {
return getGlobalElementDecl(name);
}
/**
* Convenience method. Returns a top-level attribute group definition.
* @param name The name of the definition.
* @return A top-level attribute group definition or null if such
* definition does not exist.
*/
public XSAttributeGroupDefinition getAttributeGroup(String name) {
return getGlobalAttributeGroupDecl(name);
}
/**
* Convenience method. Returns a top-level model group definition.
*
* @param name The name of the definition.
* @return A top-level model group definition definition or null if such
* definition does not exist.
*/
public XSModelGroupDefinition getModelGroupDefinition(String name) {
return getGlobalGroupDecl(name);
}
/**
* Convenience method. Returns a top-level notation declaration.
*
* @param name The name of the declaration.
* @return A top-level notation declaration or null if such declaration
* does not exist.
*/
public XSNotationDeclaration getNotationDeclaration(String name) {
return getGlobalNotationDecl(name);
}
public XSIDCDefinition getIDCDefinition(String name) {
return getIDConstraintDecl(name);
}
/**
* [document location]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#sd-document_location">[document location]</a>
* @return a list of document information item
*/
public StringList getDocumentLocations() {
return new StringListImpl(fLocations);
}
/**
* Return an <code>XSModel</code> that represents components in this schema
* grammar.
*
* @return an <code>XSModel</code> representing this schema grammar
*/
public XSModel toXSModel() {
return new XSModelImpl(new SchemaGrammar[]{this});
}
public XSModel toXSModel(XSGrammar[] grammars) {
if (grammars == null || grammars.length == 0)
return toXSModel();
int len = grammars.length;
boolean hasSelf = false;
for (int i = 0; i < len; i++) {
if (grammars[i] == this) {
hasSelf = true;
break;
}
}
SchemaGrammar[] gs = new SchemaGrammar[hasSelf ? len : len+1];
for (int i = 0; i < len; i++)
gs[i] = (SchemaGrammar)grammars[i];
if (!hasSelf)
gs[len] = this;
return new XSModelImpl(gs);
}
/**
* @see org.apache.xerces.xs.XSNamespaceItem#getAnnotations()
*/
public XSObjectList getAnnotations() {
if (fNumAnnotations == 0) {
return XSObjectListImpl.EMPTY_LIST;
}
return new XSObjectListImpl(fAnnotations, fNumAnnotations);
}
public void addAnnotation(XSAnnotationImpl annotation) {
if (annotation == null) {
return;
}
if (fAnnotations == null) {
fAnnotations = new XSAnnotationImpl[2];
}
else if (fNumAnnotations == fAnnotations.length) {
XSAnnotationImpl[] newArray = new XSAnnotationImpl[fNumAnnotations << 1];
System.arraycopy(fAnnotations, 0, newArray, 0, fNumAnnotations);
fAnnotations = newArray;
}
fAnnotations[fNumAnnotations++] = annotation;
}
public void setImmutable(boolean isImmutable) {
fIsImmutable = isImmutable;
}
public boolean isImmutable() {
return fIsImmutable;
}
} // class SchemaGrammar
| fAttrDecl |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer [MASK] ;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer [MASK] ,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this. [MASK] = [MASK] ;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this. [MASK] != null) ? BootZipCopyAction.this. [MASK]
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this. [MASK] != null) ? BootZipCopyAction.this. [MASK]
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| fileMode |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools. [MASK] ;
import org.springframework.boot.loader.tools. [MASK] sIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final [MASK] Resolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, [MASK] Resolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final [MASK] sIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new [MASK] sIndex(BootZipCopyAction.this.layerResolver.get [MASK] s()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
[MASK] layer = BootZipCopyAction.this.layerResolver.get [MASK] (details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
write [MASK] sIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
[MASK] layer = BootZipCopyAction.this.layerResolver.get [MASK] (name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
[MASK] layer = BootZipCopyAction.this.layerResolver.get [MASK] (library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void write [MASK] sIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot- [MASK] s-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
[MASK] layer = BootZipCopyAction.this.layerResolver.get [MASK] (name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addTo [MASK] Index)
throws IOException {
writeEntry(name, entryWriter, addTo [MASK] Index, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addTo [MASK] Index,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addTo [MASK] Index && BootZipCopyAction.this.layerResolver != null) {
[MASK] layer = BootZipCopyAction.this.layerResolver.get [MASK] (name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| Layer |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle. [MASK] .bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api. [MASK] .WorkResult;
import org.gradle.api. [MASK] .WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle. [MASK] .bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| tasks |
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.core.utils;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* ReuseHttpRequest.
*
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public interface ReuseHttpRequest extends HttpServletRequest {
/**
* get request body.
*
* @return object
* @throws Exception exception
*/
Object getBody() throws Exception;
/**
* Remove duplicate values from the array.
*
* @param request {@link HttpServletRequest}
* @return {@link Map}
*/
default Map< [MASK] , [MASK] []> toDuplication(HttpServletRequest request) {
Map< [MASK] , [MASK] []> tmp = request.getParameterMap();
Map< [MASK] , [MASK] []> result = new HashMap<>(tmp.size());
Set< [MASK] > set = new HashSet<>();
for (Map.Entry< [MASK] , [MASK] []> entry : tmp.entrySet()) {
set.addAll(Arrays.asList(entry.getValue()));
result.put(entry.getKey(), set.toArray(new [MASK] [0]));
set.clear();
}
return result;
}
}
| String |
/*
* Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.hosted;
import java.lang.reflect.Constructor;
import java.lang.reflect. [MASK] ;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.stream.Collectors;
import org.graalvm.nativeimage.hosted.RuntimeReflection;
import org.graalvm.nativeimage.hosted.RuntimeResourceAccess;
import com.oracle.svm.core.feature.AutomaticallyRegisteredFeature;
import com.oracle.svm.core.feature.InternalFeature;
import com.oracle.svm.core.jdk.ServiceCatalogSupport;
import com.oracle.svm.core.option.AccumulatingLocatableMultiOptionValue;
import com.oracle.svm.core.option.HostedOptionKey;
import com.oracle.svm.hosted.analysis.Inflation;
import jdk.graal.compiler.options.Option;
import jdk.graal.compiler.options.OptionType;
/**
* Support for {@link ServiceLoader} on Substrate VM.
*
* Services are registered in the folder {@code "META-INF/services/"} using files whose name is the
* fully qualified service interface name. We do not know which services are going to be used by a
* native image: The parameter of {@code ServiceLoader#load} is often but not always a compile-time
* constant that we can track. But we also cannot put all registered services into the native image.
*
* We therefore use the following heuristic: We add all service loader files and service
* implementation classes when the service interfaces that are seen as reachable by the static
* analysis.
*
* Each used service implementation class is added for reflection (using
* {@link org.graalvm.nativeimage.hosted.RuntimeReflection#register(Class[])}) and for reflective
* instantiation (using {@link RuntimeReflection#registerForReflectiveInstantiation(Class[])}).
*
* For each service interface, a single service loader file is added as a resource to the image. The
* single file combines all the individual files that can come from different .jar files.
*/
@AutomaticallyRegisteredFeature
public class ServiceLoaderFeature implements InternalFeature {
public static class Options {
@Option(help = "Automatically register services for run-time lookup using ServiceLoader", type = OptionType.Expert) //
public static final HostedOptionKey<Boolean> UseServiceLoaderFeature = new HostedOptionKey<>(true);
@Option(help = "Comma-separated list of services that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServices = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
@Option(help = "Comma-separated list of service providers that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServiceProviders = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
}
private static final Set<String> SKIPPED_SERVICES = Set.of(
// image builder internal ServiceLoader interfaces
"com.oracle.svm.hosted.NativeImageClassLoaderPostProcessing",
"org.graalvm.nativeimage.Platform",
/*
* Loaded in java.util.random.RandomGeneratorFactory.FactoryMapHolder, which is
* initialized at image build time.
*/
"java.util.random.RandomGenerator",
"java.security.Provider", // see SecurityServicesFeature
"sun.util.locale.provider.LocaleDataMetaInfo", // see LocaleSubstitutions
/* Graal hotspot-specific services */
"jdk.vm.ci.hotspot.HotSpotJVMCIBackendFactory",
"jdk.graal.compiler.hotspot.CompilerConfigurationFactory",
"jdk.graal.compiler.hotspot.HotSpotBackendFactory",
"jdk.graal.compiler.hotspot.meta.DefaultHotSpotLoweringProvider$Extensions",
"jdk.graal.compiler.hotspot.meta.HotSpotInvocationPluginProvider",
"jdk.graal.compiler.truffle.hotspot.TruffleCallBoundaryInstrumentationFactory");
// NOTE: Platform class had to be added to this list since our analysis discovers that
// Platform.includedIn is reachable regardless of fact that it is constant folded at
// registerPlatformPlugins method of SubstrateGraphBuilderPlugins. This issue hasn't manifested
// before because implementation classes were instantiated using runtime reflection instead of
// ServiceLoader (and thus weren't reachable in analysis).
/**
* Services that should not be processed here, for example because they are handled by
* specialized features.
*/
private final Set<String> servicesToSkip = new HashSet<>(SKIPPED_SERVICES);
private static final Set<String> SKIPPED_PROVIDERS = Set.of(
/* Graal hotspot-specific service-providers */
"jdk.graal.compiler.hotspot.meta.HotSpotDisassemblerProvider",
/* Skip console providers until GR-44085 is fixed */
"jdk.internal.org.jline.JdkConsoleProviderImpl", "jdk.jshell.execution.impl.ConsoleImpl$ConsoleProviderImpl");
private final Set<String> serviceProvidersToSkip = new HashSet<>(SKIPPED_PROVIDERS);
@Override
public boolean isInConfiguration(IsInConfigurationAccess access) {
return Options.UseServiceLoaderFeature.getValue();
}
@Override
public void afterRegistration(AfterRegistrationAccess access) {
servicesToSkip.addAll(Options.ServiceLoaderFeatureExcludeServices.getValue().values());
serviceProvidersToSkip.addAll(Options.ServiceLoaderFeatureExcludeServiceProviders.getValue().values());
}
@Override
public void beforeAnalysis(BeforeAnalysisAccess access) {
FeatureImpl.BeforeAnalysisAccessImpl accessImpl = (FeatureImpl.BeforeAnalysisAccessImpl) access;
accessImpl.imageClassLoader.classLoaderSupport.serviceProvidersForEach((serviceName, providers) -> {
Class<?> serviceClass = access.findClassByName(serviceName);
boolean skipService = false;
/* If the service should not end up in the image, we remove all the providers with it */
Collection<String> providersToSkip = providers;
if (servicesToSkip.contains(serviceName)) {
skipService = true;
} else if (serviceClass == null || serviceClass.isArray() || serviceClass.isPrimitive()) {
skipService = true;
} else if (!accessImpl.getHostVM().platformSupported(serviceClass)) {
skipService = true;
} else {
providersToSkip = providers.stream().filter(serviceProvidersToSkip::contains).collect(Collectors.toList());
if (!providersToSkip.isEmpty()) {
skipService = true;
}
}
if (skipService) {
ServiceCatalogSupport.singleton().removeServicesFromServicesCatalog(serviceName, new HashSet<>(providersToSkip));
return;
}
access.registerReachabilityHandler(a -> handleServiceClassIsReachable(a, serviceClass, providers), serviceClass);
});
}
void handleServiceClassIsReachable(DuringAnalysisAccess access, Class<?> serviceProvider, Collection<String> providers) {
LinkedHashSet<String> registeredProviders = new LinkedHashSet<>();
for (String provider : providers) {
if (serviceProvidersToSkip.contains(provider)) {
continue;
}
/* Make provider reflectively instantiable */
Class<?> providerClass = access.findClassByName(provider);
if (providerClass == null || providerClass.isArray() || providerClass.isPrimitive()) {
continue;
}
FeatureImpl.DuringAnalysisAccessImpl accessImpl = (FeatureImpl.DuringAnalysisAccessImpl) access;
if (!accessImpl.getHostVM().platformSupported(providerClass)) {
continue;
}
if (((Inflation) accessImpl.getBigBang()).getAnnotationSubstitutionProcessor().isDeleted(providerClass)) {
/* Disallow services with implementation classes that are marked as @Deleted */
continue;
}
/*
* Find either a public static provider() method or a nullary constructor (or both).
* Skip providers that do not comply with requirements.
*
* See ServiceLoader#loadProvider and ServiceLoader#findStaticProvider [MASK] .
*/
Constructor<?> nullaryConstructor = null;
[MASK] nullaryProvider [MASK] = null;
try {
/* Only look for a provider() method if provider class is in an explicit module. */
if (providerClass.getModule().isNamed() && !providerClass.getModule().getDescriptor().isAutomatic()) {
for ( [MASK] method : providerClass.getDeclared [MASK] s()) {
if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers()) &&
method.getParameterCount() == 0 && method.getName().equals("provider")) {
if (nullaryProvider [MASK] == null) {
nullaryProvider [MASK] = method;
} else {
/* There must be at most one public static provider() method. */
nullaryProvider [MASK] = null;
break;
}
}
}
}
Constructor<?> constructor = providerClass.getDeclaredConstructor();
if (Modifier.isPublic(constructor.getModifiers())) {
nullaryConstructor = constructor;
}
} catch (NoSuch [MASK] Exception | SecurityException | LinkageError e) {
// ignore
}
if (nullaryConstructor != null || nullaryProvider [MASK] != null) {
RuntimeReflection.register(providerClass);
if (nullaryConstructor != null) {
/*
* Registering a constructor with
* RuntimeReflection.registerConstructorLookup(providerClass) does not produce
* the same behavior as using RuntimeReflection.register(nullaryConstructor). In
* the first case, the constructor is marked for query purposes only, so this
* if-statement cannot be eliminated.
*
*/
RuntimeReflection.register(nullaryConstructor);
} else {
/*
* If there's no nullary constructor, register it as negative lookup to avoid
* throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerConstructorLookup(providerClass);
}
if (nullaryProvider [MASK] != null) {
RuntimeReflection.register(nullaryProvider [MASK] );
} else {
/*
* If there's no declared public provider() method, register it as negative
* lookup to avoid throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.register [MASK] Lookup(providerClass, "provider");
}
}
/*
* Register the provider in both cases: when it is JCA-compliant (has a nullary
* constructor or a provider method) or when it lacks both. If neither is present, a
* ServiceConfigurationError will be thrown at runtime, consistent with HotSpot
* behavior.
*/
registeredProviders.add(provider);
}
if (!registeredProviders.isEmpty()) {
String serviceResourceLocation = "META-INF/services/" + serviceProvider.getName();
byte[] serviceFileData = registeredProviders.stream().collect(Collectors.joining("\n")).getBytes(StandardCharsets.UTF_8);
RuntimeResourceAccess.addResource(access.getApplicationClassLoader().getUnnamedModule(), serviceResourceLocation, serviceFileData);
}
}
}
| Method |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives. [MASK] ;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final [MASK] manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, [MASK] manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| Manifest |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String [MASK] = getParentDirectory(name);
if ( [MASK] != null && this.writtenDirectories.add( [MASK] )) {
ZipArchiveEntry entry = new ZipArchiveEntry( [MASK] + '/');
prepareEntry(entry, [MASK] , time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| parentDirectory |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> [MASK] = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this. [MASK] .put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this. [MASK]
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| reachabilityMetadataProperties |
/**
* Copyright © 2016-2024 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thingsboard.server.service.sync.ie.importing.impl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.NotificationTargetId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.notification.targets.NotificationTarget;
import org.thingsboard.server.common.data.notification.targets.NotificationTargetType;
import org.thingsboard.server.common.data.notification.targets.platform.CustomerUsersFilter;
import org.thingsboard.server.common.data.notification.targets.platform.PlatformUsersNotificationTargetConfig;
import org.thingsboard.server.common.data.notification.targets.platform.TenantAdministratorsFilter;
import org.thingsboard.server.common.data.notification.targets.platform.UserListFilter;
import org.thingsboard.server.common.data.notification.targets.platform.UsersFilter;
import org.thingsboard.server.common.data.sync.ie.EntityExportData;
import org.thingsboard.server.dao.notification.NotificationTargetService;
import org.thingsboard.server.dao.service.ConstraintValidator;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.sync.vc.data.EntitiesImportCtx;
import java.util.List;
@Service
@TbCoreComponent
@RequiredArgsConstructor
public class NotificationTargetImportService extends BaseEntityImportService<NotificationTargetId, NotificationTarget, EntityExportData<NotificationTarget>> {
private final NotificationTargetService notificationTargetService;
@ [MASK]
protected void setOwner(TenantId tenantId, NotificationTarget notificationTarget, IdProvider idProvider) {
notificationTarget.setTenantId(tenantId);
}
@ [MASK]
protected NotificationTarget prepare(EntitiesImportCtx ctx, NotificationTarget notificationTarget, NotificationTarget oldNotificationTarget, EntityExportData<NotificationTarget> exportData, IdProvider idProvider) {
if (notificationTarget.getConfiguration().getType() == NotificationTargetType.PLATFORM_USERS) {
UsersFilter usersFilter = ((PlatformUsersNotificationTargetConfig) notificationTarget.getConfiguration()).getUsersFilter();
switch (usersFilter.getType()) {
case CUSTOMER_USERS:
CustomerUsersFilter customerUsersFilter = (CustomerUsersFilter) usersFilter;
customerUsersFilter.setCustomerId(idProvider.getInternalId(new CustomerId(customerUsersFilter.getCustomerId())).getId());
break;
case USER_LIST:
UserListFilter userListFilter = (UserListFilter) usersFilter;
userListFilter.setUsersIds(List.of(ctx.getUser().getUuidId())); // user entities are not supported by VC; replacing with current user id
break;
case TENANT_ADMINISTRATORS:
if (CollectionUtils.isNotEmpty(((TenantAdministratorsFilter) usersFilter).getTenantsIds()) ||
CollectionUtils.isNotEmpty(((TenantAdministratorsFilter) usersFilter).getTenantProfilesIds())) {
throw new IllegalArgumentException("Permission denied");
}
break;
case SYSTEM_ADMINISTRATORS:
throw new AccessDeniedException("Permission denied");
}
}
return notificationTarget;
}
@ [MASK]
protected NotificationTarget saveOrUpdate(EntitiesImportCtx ctx, NotificationTarget notificationTarget, EntityExportData<NotificationTarget> exportData, IdProvider idProvider) {
ConstraintValidator.validateFields(notificationTarget);
return notificationTargetService.saveNotificationTarget(ctx.getTenantId(), notificationTarget);
}
@ [MASK]
protected void onEntitySaved(User user, NotificationTarget savedEntity, NotificationTarget oldEntity) throws ThingsboardException {
entityActionService.logEntityAction(user, savedEntity.getId(), savedEntity, null,
oldEntity == null ? ActionType.ADDED : ActionType.UPDATED, null);
}
@ [MASK]
protected NotificationTarget deepCopy(NotificationTarget notificationTarget) {
return new NotificationTarget(notificationTarget);
}
@ [MASK]
public EntityType getEntityType() {
return EntityType.NOTIFICATION_TARGET;
}
}
| Override |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String [MASK] ;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String [MASK] ,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this. [MASK] = [MASK] ;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this. [MASK] != null) {
zipOutputStream.setEncoding(this. [MASK] );
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this. [MASK] , lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this. [MASK] , lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param [MASK] the required character [MASK]
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String [MASK] , Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, [MASK] );
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| encoding |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function. [MASK] ;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final [MASK] <FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
[MASK] <FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@ [MASK] alInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@ [MASK] alInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| Function |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache. [MASK] .compress.archivers.zip.UnixStat;
import org.apache. [MASK] .compress.archivers.zip.ZipArchiveEntry;
import org.apache. [MASK] .compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| commons |
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
*/
/*
* 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 com.sun.org.apache.xerces.internal.impl.xs;
import com.sun.org.apache.xerces.internal.impl.Constants;
import com.sun.org.apache.xerces.internal.impl.dv.SchemaDVFactory;
import com.sun.org.apache.xerces.internal.impl.dv.ValidatedInfo;
import com.sun.org.apache.xerces.internal.impl.dv.XSSimpleType;
import com.sun.org.apache.xerces.internal.impl.dv.xs.XSSimpleTypeDecl;
import com.sun.org.apache.xerces.internal.impl.xs.identity.IdentityConstraint;
import com.sun.org.apache.xerces.internal.impl.xs.util.ObjectListImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.SimpleLocator;
import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSNamedMap4Types;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSNamedMapImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util. [MASK] ;
import com.sun.org.apache.xerces.internal.parsers.DOMParser;
import com.sun.org.apache.xerces.internal.parsers.SAXParser;
import com.sun.org.apache.xerces.internal.parsers.XML11Configuration;
import com.sun.org.apache.xerces.internal.util.SymbolHash;
import com.sun.org.apache.xerces.internal.util.SymbolTable;
import com.sun.org.apache.xerces.internal.xni.NamespaceContext;
import com.sun.org.apache.xerces.internal.xni.grammars.XMLGrammarDescription;
import com.sun.org.apache.xerces.internal.xni.grammars.XSGrammar;
import com.sun.org.apache.xerces.internal.xs.StringList;
import com.sun.org.apache.xerces.internal.xs.XSAnnotation;
import com.sun.org.apache.xerces.internal.xs.XSAttributeDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSAttributeGroupDefinition;
import com.sun.org.apache.xerces.internal.xs.XSConstants;
import com.sun.org.apache.xerces.internal.xs.XSElementDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSIDCDefinition;
import com.sun.org.apache.xerces.internal.xs.XSModel;
import com.sun.org.apache.xerces.internal.xs.XSModelGroupDefinition;
import com.sun.org.apache.xerces.internal.xs.XSNamedMap;
import com.sun.org.apache.xerces.internal.xs.XSNamespaceItem;
import com.sun.org.apache.xerces.internal.xs.XSNotationDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSObjectList;
import com.sun.org.apache.xerces.internal.xs.XSParticle;
import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
import com.sun.org.apache.xerces.internal.xs.XSWildcard;
import com.sun.org.apache.xerces.internal.xs.datatypes.ObjectList;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.xml.sax.SAXException;
/**
* This class is to hold all schema component declaration that are declared
* within one namespace.
*
* The Grammar class this class extends contains what little
* commonality there is between XML Schema and DTD grammars. It's
* useful to distinguish grammar objects from other kinds of object
* when they exist in pools or caches.
*
* @xerces.internal
*
* @author Sandy Gao, IBM
* @author Elena Litani, IBM
*
* @LastModified: Oct 2017
*/
public class SchemaGrammar implements XSGrammar, XSNamespaceItem {
// the target namespace of grammar
String fTargetNamespace;
// global decls: map from decl name to decl object
SymbolHash fGlobalAttrDecls;
SymbolHash fGlobalAttrGrpDecls;
SymbolHash fGlobalElemDecls;
SymbolHash fGlobalGroupDecls;
SymbolHash fGlobalNotationDecls;
SymbolHash fGlobalIDConstraintDecls;
SymbolHash fGlobalTypeDecls;
// extended global decls: map from schema location + decl name to decl object
// key is location,name
SymbolHash fGlobalAttrDeclsExt;
SymbolHash fGlobalAttrGrpDeclsExt;
SymbolHash fGlobalElemDeclsExt;
SymbolHash fGlobalGroupDeclsExt;
SymbolHash fGlobalNotationDeclsExt;
SymbolHash fGlobalIDConstraintDeclsExt;
SymbolHash fGlobalTypeDeclsExt;
// A global map of all global element declarations - used for substitution group computation
// (handy when sharing components by reference, since we might end up with duplicate components
// that are not added to either of the global element declarations above)
SymbolHash fAllGlobalElemDecls;
// the XMLGrammarDescription member
XSDDescription fGrammarDescription = null;
// annotations associated with the "root" schema of this targetNamespace
XSAnnotationImpl [] fAnnotations = null;
// number of annotations declared
int fNumAnnotations;
// symbol table for constructing parsers (annotation support)
private SymbolTable fSymbolTable = null;
// parsers for annotation support
private SoftReference<SAXParser> fSAXParser = null;
private SoftReference<DOMParser> fDOMParser = null;
// is this grammar immutable? (fully constructed and not changeable)
private boolean fIsImmutable = false;
//
// Constructors
//
// needed to make BuiltinSchemaGrammar work.
protected SchemaGrammar() {}
/**
* Default constructor.
*
* @param targetNamespace
* @param grammarDesc the XMLGrammarDescription corresponding to this object
* at the least a systemId should always be known.
* @param symbolTable needed for annotation support
*/
public SchemaGrammar(String targetNamespace, XSDDescription grammarDesc,
SymbolTable symbolTable) {
fTargetNamespace = targetNamespace;
fGrammarDescription = grammarDesc;
fSymbolTable = symbolTable;
// REVISIT: the initial sizes being chosen for each SymbolHash
// may not be ideal and could still be tuned. They were chosen
// somewhat arbitrarily to reduce the initial footprint of
// SymbolHash buckets from 1,515 to 177 (about 12% of the
// default size).
fGlobalAttrDecls = new SymbolHash(12);
fGlobalAttrGrpDecls = new SymbolHash(5);
fGlobalElemDecls = new SymbolHash(25);
fGlobalGroupDecls = new SymbolHash(5);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(3);
// Extended tables
fGlobalAttrDeclsExt = new SymbolHash(12);
fGlobalAttrGrpDeclsExt = new SymbolHash(5);
fGlobalElemDeclsExt = new SymbolHash(25);
fGlobalGroupDeclsExt = new SymbolHash(5);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(3);
fGlobalTypeDeclsExt = new SymbolHash(25);
// All global elements table
fAllGlobalElemDecls = new SymbolHash(25);
// if we are parsing S4S, put built-in types in first
// they might get overwritten by the types from S4S, but that's
// considered what the application wants to do.
if (fTargetNamespace == SchemaSymbols.URI_SCHEMAFORSCHEMA) {
fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls.makeClone();
}
else {
fGlobalTypeDecls = new SymbolHash(25);
}
} // <init>(String, XSDDescription)
// Clone an existing schema grammar
public SchemaGrammar(SchemaGrammar grammar) {
fTargetNamespace = grammar.fTargetNamespace;
fGrammarDescription = grammar.fGrammarDescription.makeClone();
//fGrammarDescription.fContextType |= XSDDescription.CONTEXT_COLLISION; // REVISIT
fSymbolTable = grammar.fSymbolTable; // REVISIT
fGlobalAttrDecls = grammar.fGlobalAttrDecls.makeClone();
fGlobalAttrGrpDecls = grammar.fGlobalAttrGrpDecls.makeClone();
fGlobalElemDecls = grammar.fGlobalElemDecls.makeClone();
fGlobalGroupDecls = grammar.fGlobalGroupDecls.makeClone();
fGlobalNotationDecls = grammar.fGlobalNotationDecls.makeClone();
fGlobalIDConstraintDecls = grammar.fGlobalIDConstraintDecls.makeClone();
fGlobalTypeDecls = grammar.fGlobalTypeDecls.makeClone();
// Extended tables
fGlobalAttrDeclsExt = grammar.fGlobalAttrDeclsExt.makeClone();
fGlobalAttrGrpDeclsExt = grammar.fGlobalAttrGrpDeclsExt.makeClone();
fGlobalElemDeclsExt = grammar.fGlobalElemDeclsExt.makeClone();
fGlobalGroupDeclsExt = grammar.fGlobalGroupDeclsExt.makeClone();
fGlobalNotationDeclsExt = grammar.fGlobalNotationDeclsExt.makeClone();
fGlobalIDConstraintDeclsExt = grammar.fGlobalIDConstraintDeclsExt.makeClone();
fGlobalTypeDeclsExt = grammar.fGlobalTypeDeclsExt.makeClone();
// All global elements table
fAllGlobalElemDecls = grammar.fAllGlobalElemDecls.makeClone();
// Annotations associated with the "root" schema of this targetNamespace
fNumAnnotations = grammar.fNumAnnotations;
if (fNumAnnotations > 0) {
fAnnotations = new XSAnnotationImpl[grammar.fAnnotations.length];
System.arraycopy(grammar.fAnnotations, 0, fAnnotations, 0, fNumAnnotations);
}
// All substitution group information declared in this namespace
fSubGroupCount = grammar.fSubGroupCount;
if (fSubGroupCount > 0) {
fSubGroups = new XSElementDecl[grammar.fSubGroups.length];
System.arraycopy(grammar.fSubGroups, 0, fSubGroups, 0, fSubGroupCount);
}
// Array to store complex type decls for constraint checking
fCTCount = grammar.fCTCount;
if (fCTCount > 0) {
fComplexTypeDecls = new XSComplexTypeDecl[grammar.fComplexTypeDecls.length];
fCTLocators = new SimpleLocator[grammar.fCTLocators.length];
System.arraycopy(grammar.fComplexTypeDecls, 0, fComplexTypeDecls, 0, fCTCount);
System.arraycopy(grammar.fCTLocators, 0, fCTLocators, 0, fCTCount);
}
// Groups being redefined by restriction
fRGCount = grammar.fRGCount;
if (fRGCount > 0) {
fRedefinedGroupDecls = new XSGroupDecl[grammar.fRedefinedGroupDecls.length];
fRGLocators = new SimpleLocator[grammar.fRGLocators.length];
System.arraycopy(grammar.fRedefinedGroupDecls, 0, fRedefinedGroupDecls, 0, fRGCount);
System.arraycopy(grammar.fRGLocators, 0, fRGLocators, 0, fRGCount/2);
}
// List of imported grammars
if (grammar.fImported != null) {
fImported = new ArrayList<>();
for (int i=0; i<grammar.fImported.size(); i++) {
fImported.add(grammar.fImported.get(i));
}
}
// Locations
if (grammar.fLocations != null) {
for (int k=0; k<grammar.fLocations.size(); k++) {
addDocument(null, grammar.fLocations.get(k));
}
}
} // <init>(String, XSDDescription)
// number of built-in XSTypes we need to create for base and full
// datatype set
private static final int BASICSET_COUNT = 29;
private static final int FULLSET_COUNT = 46;
private static final int GRAMMAR_XS = 1;
private static final int GRAMMAR_XSI = 2;
// this class makes sure the static, built-in schema grammars
// are immutable.
public static class BuiltinSchemaGrammar extends SchemaGrammar {
private static final String EXTENDED_SCHEMA_FACTORY_CLASS = "com.sun.org.apache.xerces.internal.impl.dv.xs.ExtendedSchemaDVFactoryImpl";
/**
* Special constructor to create the grammars for the schema namespaces
*
* @param grammar
*/
public BuiltinSchemaGrammar(int grammar, short schemaVersion) {
SchemaDVFactory schemaFactory;
if (schemaVersion == Constants.SCHEMA_VERSION_1_0) {
schemaFactory = SchemaDVFactory.getInstance();
}
else {
schemaFactory = SchemaDVFactory.getInstance(EXTENDED_SCHEMA_FACTORY_CLASS);
}
if (grammar == GRAMMAR_XS) {
// target namespace
fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA);
// no global decls other than types
fGlobalAttrDecls = new SymbolHash(1);
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(1);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(1);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// all global element decls table
fAllGlobalElemDecls = new SymbolHash(1);
// get all built-in types
fGlobalTypeDecls = schemaFactory.getBuiltInTypes();
// assign the built-in schema grammar as the XSNamespaceItem
// for each of the built-in simple type definitions.
int length = fGlobalTypeDecls.getLength();
XSTypeDefinition [] typeDefinitions = new XSTypeDefinition[length];
fGlobalTypeDecls.getValues(typeDefinitions, 0);
for (int i = 0; i < length; ++i) {
XSTypeDefinition xtd = typeDefinitions[i];
if (xtd instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) xtd).setNamespaceItem(this);
}
}
// add anyType
fGlobalTypeDecls.put(fAnyType.getName(), fAnyType);
}
else if (grammar == GRAMMAR_XSI) {
// target namespace
fTargetNamespace = SchemaSymbols.URI_XSI;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_XSI);
// no global decls other than attributes
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(1);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
fGlobalTypeDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(1);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// no all global element decls
fAllGlobalElemDecls = new SymbolHash(1);
// 4 attributes, so initialize the size as 4*2 = 8
fGlobalAttrDecls = new SymbolHash(8);
String name = null;
String tns = null;
XSSimpleType type = null;
short scope = XSConstants.SCOPE_GLOBAL;
// xsi:type
name = SchemaSymbols.XSI_TYPE;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_QNAME);
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
// xsi:nil
name = SchemaSymbols.XSI_NIL;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_BOOLEAN);
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
XSSimpleType anyURI = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_ANYURI);
// xsi:schemaLocation
name = SchemaSymbols.XSI_SCHEMALOCATION;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.createTypeList("#AnonType_schemaLocation", SchemaSymbols.URI_XSI, (short)0, anyURI, null);
if (type instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl)type).setAnonymous(true);
}
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
// xsi:noNamespaceSchemaLocation
name = SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION;
tns = SchemaSymbols.URI_XSI;
type = anyURI;
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
}
} // <init>(int)
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription.makeClone();
} // getGrammarDescription(): XMLGrammarDescription
// override these methods solely so that these
// objects cannot be modified once they're created.
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl, String location) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
// ignore
}
public void addGlobalElementDeclAll(XSElementDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
// ignore
}
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
// ignore
}
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
// ignore
}
public synchronized void addDocument(Object document, String location) {
// ignore
}
// annotation support
synchronized DOMParser getDOMParser() {
return null;
}
synchronized SAXParser getSAXParser() {
return null;
}
}
/**
* <p>A partial schema for schemas for validating annotations.</p>
*
* @xerces.internal
*
* @author Michael Glavassevich, IBM
*/
public static final class Schema4Annotations extends SchemaGrammar {
/**
* Singleton instance.
*/
public static final Schema4Annotations INSTANCE = new Schema4Annotations();
/**
* Special constructor to create a schema
* capable of validating annotations.
*/
private Schema4Annotations() {
// target namespace
fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA);
// no global decls other than types and
// element declarations for <annotation>, <documentation> and <appinfo>.
fGlobalAttrDecls = new SymbolHash(1);
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(6);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(6);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// all global element declarations
fAllGlobalElemDecls = new SymbolHash(6);
// get all built-in types
fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls;
// create element declarations for <annotation>, <documentation> and <appinfo>
XSElementDecl annotationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_ANNOTATION);
XSElementDecl documentationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_DOCUMENTATION);
XSElementDecl appinfoDecl = createAnnotationElementDecl(SchemaSymbols.ELT_APPINFO);
// add global element declarations
fGlobalElemDecls.put(annotationDecl.fName, annotationDecl);
fGlobalElemDecls.put(documentationDecl.fName, documentationDecl);
fGlobalElemDecls.put(appinfoDecl.fName, appinfoDecl);
fGlobalElemDeclsExt.put(","+annotationDecl.fName, annotationDecl);
fGlobalElemDeclsExt.put(","+documentationDecl.fName, documentationDecl);
fGlobalElemDeclsExt.put(","+appinfoDecl.fName, appinfoDecl);
fAllGlobalElemDecls.put(annotationDecl, annotationDecl);
fAllGlobalElemDecls.put(documentationDecl, documentationDecl);
fAllGlobalElemDecls.put(appinfoDecl, appinfoDecl);
// create complex type declarations for <annotation>, <documentation> and <appinfo>
XSComplexTypeDecl annotationType = new XSComplexTypeDecl();
XSComplexTypeDecl documentationType = new XSComplexTypeDecl();
XSComplexTypeDecl appinfoType = new XSComplexTypeDecl();
// set the types on their element declarations
annotationDecl.fType = annotationType;
documentationDecl.fType = documentationType;
appinfoDecl.fType = appinfoType;
// create attribute groups for <annotation>, <documentation> and <appinfo>
XSAttributeGroupDecl annotationAttrs = new XSAttributeGroupDecl();
XSAttributeGroupDecl documentationAttrs = new XSAttributeGroupDecl();
XSAttributeGroupDecl appinfoAttrs = new XSAttributeGroupDecl();
// fill in attribute groups
{
// create and fill attribute uses for <annotation>, <documentation> and <appinfo>
XSAttributeUseImpl annotationIDAttr = new XSAttributeUseImpl();
annotationIDAttr.fAttrDecl = new XSAttributeDecl();
annotationIDAttr.fAttrDecl.setValues(SchemaSymbols.ATT_ID, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ID),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, annotationType, null);
annotationIDAttr.fUse = SchemaSymbols.USE_OPTIONAL;
annotationIDAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl documentationSourceAttr = new XSAttributeUseImpl();
documentationSourceAttr.fAttrDecl = new XSAttributeDecl();
documentationSourceAttr.fAttrDecl.setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ANYURI),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, documentationType, null);
documentationSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL;
documentationSourceAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl documentationLangAttr = new XSAttributeUseImpl();
documentationLangAttr.fAttrDecl = new XSAttributeDecl();
documentationLangAttr.fAttrDecl.setValues("lang".intern(), NamespaceContext.XML_URI, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_LANGUAGE),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, documentationType, null);
documentationLangAttr.fUse = SchemaSymbols.USE_OPTIONAL;
documentationLangAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl appinfoSourceAttr = new XSAttributeUseImpl();
appinfoSourceAttr.fAttrDecl = new XSAttributeDecl();
appinfoSourceAttr.fAttrDecl.setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ANYURI),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, appinfoType, null);
appinfoSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL;
appinfoSourceAttr.fConstraintType = XSConstants.VC_NONE;
// create lax attribute wildcard for <annotation>, <documentation> and <appinfo>
XSWildcardDecl otherAttrs = new XSWildcardDecl();
otherAttrs.fNamespaceList = new String [] {fTargetNamespace, null};
otherAttrs.fType = XSWildcard.NSCONSTRAINT_NOT;
otherAttrs.fProcessContents = XSWildcard.PC_LAX;
// add attribute uses and wildcards to attribute groups for <annotation>, <documentation> and <appinfo>
annotationAttrs.addAttributeUse(annotationIDAttr);
annotationAttrs.fAttributeWC = otherAttrs;
documentationAttrs.addAttributeUse(documentationSourceAttr);
documentationAttrs.addAttributeUse(documentationLangAttr);
documentationAttrs.fAttributeWC = otherAttrs;
appinfoAttrs.addAttributeUse(appinfoSourceAttr);
appinfoAttrs.fAttributeWC = otherAttrs;
}
// create particles for <annotation>
XSParticleDecl annotationParticle = createUnboundedModelGroupParticle();
{
XSModelGroupImpl annotationChoice = new XSModelGroupImpl();
annotationChoice.fCompositor = XSModelGroupImpl.MODELGROUP_CHOICE;
annotationChoice.fParticleCount = 2;
annotationChoice.fParticles = new XSParticleDecl[2];
annotationChoice.fParticles[0] = createChoiceElementParticle(appinfoDecl);
annotationChoice.fParticles[1] = createChoiceElementParticle(documentationDecl);
annotationParticle.fValue = annotationChoice;
}
// create wildcard particle for <documentation> and <appinfo>
XSParticleDecl anyWCSequenceParticle = createUnboundedAnyWildcardSequenceParticle();
// fill complex types
annotationType.setValues("#AnonType_" + SchemaSymbols.ELT_ANNOTATION, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_ELEMENT, false, annotationAttrs, null, annotationParticle, [MASK] .EMPTY_LIST);
annotationType.setName("#AnonType_" + SchemaSymbols.ELT_ANNOTATION);
annotationType.setIsAnonymous();
documentationType.setValues("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_MIXED, false, documentationAttrs, null, anyWCSequenceParticle, [MASK] .EMPTY_LIST);
documentationType.setName("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION);
documentationType.setIsAnonymous();
appinfoType.setValues("#AnonType_" + SchemaSymbols.ELT_APPINFO, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_MIXED, false, appinfoAttrs, null, anyWCSequenceParticle, [MASK] .EMPTY_LIST);
appinfoType.setName("#AnonType_" + SchemaSymbols.ELT_APPINFO);
appinfoType.setIsAnonymous();
} // <init>(int)
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription.makeClone();
} // getGrammarDescription(): XMLGrammarDescription
// override these methods solely so that these
// objects cannot be modified once they're created.
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
// ignore
}
public void addGlobalElementDeclAll(XSElementDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
// ignore
}
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
// ignore
}
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
// ignore
}
public synchronized void addDocument(Object document, String location) {
// ignore
}
// annotation support
synchronized DOMParser getDOMParser() {
return null;
}
synchronized SAXParser getSAXParser() {
return null;
}
//
// private helper methods
//
private XSElementDecl createAnnotationElementDecl(String localName) {
XSElementDecl eDecl = new XSElementDecl();
eDecl.fName = localName;
eDecl.fTargetNamespace = fTargetNamespace;
eDecl.setIsGlobal();
eDecl.fBlock = (XSConstants.DERIVATION_EXTENSION |
XSConstants.DERIVATION_RESTRICTION | XSConstants.DERIVATION_SUBSTITUTION);
eDecl.setConstraintType(XSConstants.VC_NONE);
return eDecl;
}
private XSParticleDecl createUnboundedModelGroupParticle() {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 0;
particle.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED;
particle.fType = XSParticleDecl.PARTICLE_MODELGROUP;
return particle;
}
private XSParticleDecl createChoiceElementParticle(XSElementDecl ref) {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 1;
particle.fMaxOccurs = 1;
particle.fType = XSParticleDecl.PARTICLE_ELEMENT;
particle.fValue = ref;
return particle;
}
private XSParticleDecl createUnboundedAnyWildcardSequenceParticle() {
XSParticleDecl particle = createUnboundedModelGroupParticle();
XSModelGroupImpl sequence = new XSModelGroupImpl();
sequence.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE;
sequence.fParticleCount = 1;
sequence.fParticles = new XSParticleDecl[1];
sequence.fParticles[0] = createAnyLaxWildcardParticle();
particle.fValue = sequence;
return particle;
}
private XSParticleDecl createAnyLaxWildcardParticle() {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 1;
particle.fMaxOccurs = 1;
particle.fType = XSParticleDecl.PARTICLE_WILDCARD;
XSWildcardDecl anyWC = new XSWildcardDecl();
anyWC.fNamespaceList = null;
anyWC.fType = XSWildcard.NSCONSTRAINT_ANY;
anyWC.fProcessContents = XSWildcard.PC_LAX;
particle.fValue = anyWC;
return particle;
}
}
// Grammar methods
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription;
} // getGrammarDescription(): XMLGrammarDescription
// DTDGrammar methods
public boolean isNamespaceAware () {
return true;
} // isNamespaceAware():boolean
List<SchemaGrammar> fImported = null;
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
fImported = importedGrammars;
}
public List<SchemaGrammar> getImportedGrammars() {
return fImported;
}
/**
* Returns this grammar's target namespace.
*/
public final String getTargetNamespace() {
return fTargetNamespace;
} // getTargetNamespace():String
/**
* register one global attribute
*/
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
fGlobalAttrDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalAttributeDecl(XSAttributeDecl decl, String location) {
fGlobalAttrDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global attribute group
*/
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
fGlobalAttrGrpDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
fGlobalAttrGrpDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global element
*/
public void addGlobalElementDeclAll(XSElementDecl decl) {
if (fAllGlobalElemDecls.get(decl) == null) {
fAllGlobalElemDecls.put(decl, decl);
// if there is a substitution group affiliation, store in an array,
// for further constraint checking: UPA, PD, EDC
if (decl.fSubGroup != null) {
if (fSubGroupCount == fSubGroups.length)
fSubGroups = resize(fSubGroups, fSubGroupCount+INC_SIZE);
fSubGroups[fSubGroupCount++] = decl;
}
}
}
public void addGlobalElementDecl(XSElementDecl decl) {
fGlobalElemDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
fGlobalElemDeclsExt.put(((location != null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global group
*/
public void addGlobalGroupDecl(XSGroupDecl decl) {
fGlobalGroupDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
fGlobalGroupDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global notation
*/
public void addGlobalNotationDecl(XSNotationDecl decl) {
fGlobalNotationDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
fGlobalNotationDeclsExt.put(((location!=null) ? location : "") + "," +decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global type
*/
public void addGlobalTypeDecl(XSTypeDefinition decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
if (decl instanceof XSComplexTypeDecl) {
((XSComplexTypeDecl) decl).setNamespaceItem(this);
}
else if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
fGlobalTypeDeclsExt.put(((location!=null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null) {
if (decl instanceof XSComplexTypeDecl) {
((XSComplexTypeDecl) decl).setNamespaceItem(this);
}
else if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
}
/**
* register one global complex type
*/
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
decl.setNamespaceItem(this);
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
fGlobalTypeDeclsExt.put(((location!=null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global simple type
*/
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
fGlobalTypeDeclsExt.put(((location != null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null && decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
/**
* register one identity constraint
*/
public final void addIDConstraintDecl(XSElementDecl elmDecl, IdentityConstraint decl) {
elmDecl.addIDConstraint(decl);
fGlobalIDConstraintDecls.put(decl.getIdentityConstraintName(), decl);
}
public final void addIDConstraintDecl(XSElementDecl elmDecl, IdentityConstraint decl, String location) {
fGlobalIDConstraintDeclsExt.put(((location != null) ? location : "") + "," + decl.getIdentityConstraintName(), decl);
}
/**
* get one global attribute
*/
public final XSAttributeDecl getGlobalAttributeDecl(String declName) {
return(XSAttributeDecl)fGlobalAttrDecls.get(declName);
}
public final XSAttributeDecl getGlobalAttributeDecl(String declName, String location) {
return(XSAttributeDecl)fGlobalAttrDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global attribute group
*/
public final XSAttributeGroupDecl getGlobalAttributeGroupDecl(String declName) {
return(XSAttributeGroupDecl)fGlobalAttrGrpDecls.get(declName);
}
public final XSAttributeGroupDecl getGlobalAttributeGroupDecl(String declName, String location) {
return(XSAttributeGroupDecl)fGlobalAttrGrpDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global element
*/
public final XSElementDecl getGlobalElementDecl(String declName) {
return(XSElementDecl)fGlobalElemDecls.get(declName);
}
public final XSElementDecl getGlobalElementDecl(String declName, String location) {
return(XSElementDecl)fGlobalElemDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global group
*/
public final XSGroupDecl getGlobalGroupDecl(String declName) {
return(XSGroupDecl)fGlobalGroupDecls.get(declName);
}
public final XSGroupDecl getGlobalGroupDecl(String declName, String location) {
return(XSGroupDecl)fGlobalGroupDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global notation
*/
public final XSNotationDecl getGlobalNotationDecl(String declName) {
return(XSNotationDecl)fGlobalNotationDecls.get(declName);
}
public final XSNotationDecl getGlobalNotationDecl(String declName, String location) {
return(XSNotationDecl)fGlobalNotationDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global type
*/
public final XSTypeDefinition getGlobalTypeDecl(String declName) {
return(XSTypeDefinition)fGlobalTypeDecls.get(declName);
}
public final XSTypeDefinition getGlobalTypeDecl(String declName, String location) {
return(XSTypeDefinition)fGlobalTypeDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one identity constraint
*/
public final IdentityConstraint getIDConstraintDecl(String declName) {
return(IdentityConstraint)fGlobalIDConstraintDecls.get(declName);
}
public final IdentityConstraint getIDConstraintDecl(String declName, String location) {
return(IdentityConstraint)fGlobalIDConstraintDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one identity constraint
*/
public final boolean hasIDConstraints() {
return fGlobalIDConstraintDecls.getLength() > 0;
}
// array to store complex type decls
private static final int INITIAL_SIZE = 16;
private static final int INC_SIZE = 16;
private int fCTCount = 0;
private XSComplexTypeDecl[] fComplexTypeDecls = new XSComplexTypeDecl[INITIAL_SIZE];
private SimpleLocator[] fCTLocators = new SimpleLocator[INITIAL_SIZE];
// an array to store groups being redefined by restriction
// even-numbered elements are the derived groups, odd-numbered ones their bases
private static final int REDEFINED_GROUP_INIT_SIZE = 2;
private int fRGCount = 0;
private XSGroupDecl[] fRedefinedGroupDecls = new XSGroupDecl[REDEFINED_GROUP_INIT_SIZE];
private SimpleLocator[] fRGLocators = new SimpleLocator[REDEFINED_GROUP_INIT_SIZE/2];
// a flag to indicate whether we have checked the 3 constraints on this
// grammar.
boolean fFullChecked = false;
/**
* add one complex type decl: for later constraint checking
*/
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
if (fCTCount == fComplexTypeDecls.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount+INC_SIZE);
fCTLocators = resize(fCTLocators, fCTCount+INC_SIZE);
}
fCTLocators[fCTCount] = locator;
fComplexTypeDecls[fCTCount++] = decl;
}
/**
* add a group redefined by restriction: for later constraint checking
*/
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
if (fRGCount == fRedefinedGroupDecls.length) {
// double array size each time.
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount << 1);
fRGLocators = resize(fRGLocators, fRGCount);
}
fRGLocators[fRGCount/2] = locator;
fRedefinedGroupDecls[fRGCount++] = derived;
fRedefinedGroupDecls[fRGCount++] = base;
}
/**
* get all complex type decls: for later constraint checking
*/
final XSComplexTypeDecl[] getUncheckedComplexTypeDecls() {
if (fCTCount < fComplexTypeDecls.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
return fComplexTypeDecls;
}
/**
* get the error locator of all complex type decls
*/
final SimpleLocator[] getUncheckedCTLocators() {
if (fCTCount < fCTLocators.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
return fCTLocators;
}
/**
* get all redefined groups: for later constraint checking
*/
final XSGroupDecl[] getRedefinedGroupDecls() {
if (fRGCount < fRedefinedGroupDecls.length) {
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount);
fRGLocators = resize(fRGLocators, fRGCount/2);
}
return fRedefinedGroupDecls;
}
/**
* get the error locator of all redefined groups
*/
final SimpleLocator[] getRGLocators() {
if (fRGCount < fRedefinedGroupDecls.length) {
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount);
fRGLocators = resize(fRGLocators, fRGCount/2);
}
return fRGLocators;
}
/**
* after the first-round checking, some types don't need to be checked
* against UPA again. here we trim the array to the proper size.
*/
final void setUncheckedTypeNum(int newSize) {
fCTCount = newSize;
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
// used to store all substitution group information declared in
// this namespace
private int fSubGroupCount = 0;
private XSElementDecl[] fSubGroups = new XSElementDecl[INITIAL_SIZE];
/**
* get all substitution group information: for the 3 constraint checking
*/
final XSElementDecl[] getSubstitutionGroups() {
if (fSubGroupCount < fSubGroups.length)
fSubGroups = resize(fSubGroups, fSubGroupCount);
return fSubGroups;
}
// anyType and anySimpleType: because there are so many places where
// we need direct access to these two types
public final static XSComplexTypeDecl fAnyType = new XSAnyType();
private static class XSAnyType extends XSComplexTypeDecl {
public XSAnyType () {
fName = SchemaSymbols.ATTVAL_ANYTYPE;
super.fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
fBaseType = this;
fDerivedBy = XSConstants.DERIVATION_RESTRICTION;
fContentType = XSComplexTypeDecl.CONTENTTYPE_MIXED;
fParticle = createParticle();
fAttrGrp = createAttrGrp();
}
// overridden methods
public void setValues(String name, String targetNamespace,
XSTypeDefinition baseType, short derivedBy, short schemaFinal,
short block, short contentType,
boolean isAbstract, XSAttributeGroupDecl attrGrp,
XSSimpleType simpleType, XSParticleDecl particle) {
// don't allow this.
}
public void setName(String name){
// don't allow this.
}
public void setIsAbstractType() {
// null implementation
}
public void setContainsTypeID() {
// null implementation
}
public void setIsAnonymous() {
// null implementation
}
public void reset() {
// null implementation
}
public XSObjectList getAnnotations() {
return [MASK] .EMPTY_LIST;
}
public XSNamespaceItem getNamespaceItem() {
return SG_SchemaNS;
}
private XSAttributeGroupDecl createAttrGrp() {
XSWildcardDecl wildcard = new XSWildcardDecl();
wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
XSAttributeGroupDecl attrGrp = new XSAttributeGroupDecl();
attrGrp.fAttributeWC = wildcard;
return attrGrp;
}
private XSParticleDecl createParticle() {
// the wildcard used in anyType (content and attribute)
// the spec will change strict to skip for anyType
XSWildcardDecl wildcard = new XSWildcardDecl();
wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
// the particle for the content wildcard
XSParticleDecl particleW = new XSParticleDecl();
particleW.fMinOccurs = 0;
particleW.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED;
particleW.fType = XSParticleDecl.PARTICLE_WILDCARD;
particleW.fValue = wildcard;
// the model group of a sequence of the above particle
XSModelGroupImpl group = new XSModelGroupImpl();
group.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE;
group.fParticleCount = 1;
group.fParticles = new XSParticleDecl[1];
group.fParticles[0] = particleW;
// the content of anyType: particle of the above model group
XSParticleDecl particleG = new XSParticleDecl();
particleG.fType = XSParticleDecl.PARTICLE_MODELGROUP;
particleG.fValue = group;
return particleG;
}
}
private static class BuiltinAttrDecl extends XSAttributeDecl {
public BuiltinAttrDecl(String name, String tns,
XSSimpleType type, short scope) {
fName = name;
super.fTargetNamespace = tns;
fType = type;
fScope = scope;
}
public void setValues(String name, String targetNamespace,
XSSimpleType simpleType, short constraintType, short scope,
ValidatedInfo valInfo, XSComplexTypeDecl enclosingCT) {
// ignore this call.
}
public void reset () {
// also ignore this call.
}
public XSAnnotation getAnnotation() {
return null;
}
public XSNamespaceItem getNamespaceItem() {
return SG_XSI;
}
} // class BuiltinAttrDecl
// the grammars to hold components of the schema namespace
public final static BuiltinSchemaGrammar SG_SchemaNS = new BuiltinSchemaGrammar(GRAMMAR_XS, Constants.SCHEMA_VERSION_1_0);
private final static BuiltinSchemaGrammar SG_SchemaNSExtended = new BuiltinSchemaGrammar(GRAMMAR_XS, Constants.SCHEMA_VERSION_1_0_EXTENDED);
public final static XSSimpleType fAnySimpleType = (XSSimpleType)SG_SchemaNS.getGlobalTypeDecl(SchemaSymbols.ATTVAL_ANYSIMPLETYPE);
// the grammars to hold components of the schema-instance namespace
public final static BuiltinSchemaGrammar SG_XSI = new BuiltinSchemaGrammar(GRAMMAR_XSI, Constants.SCHEMA_VERSION_1_0);
public static SchemaGrammar getS4SGrammar(short schemaVersion) {
if (schemaVersion == Constants.SCHEMA_VERSION_1_0) {
return SG_SchemaNS;
}
else {
return SG_SchemaNSExtended;
}
}
static final XSComplexTypeDecl[] resize(XSComplexTypeDecl[] oldArray, int newSize) {
XSComplexTypeDecl[] newArray = new XSComplexTypeDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final XSGroupDecl[] resize(XSGroupDecl[] oldArray, int newSize) {
XSGroupDecl[] newArray = new XSGroupDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final XSElementDecl[] resize(XSElementDecl[] oldArray, int newSize) {
XSElementDecl[] newArray = new XSElementDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final SimpleLocator[] resize(SimpleLocator[] oldArray, int newSize) {
SimpleLocator[] newArray = new SimpleLocator[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
// XSNamespaceItem methods
// the max index / the max value of XSObject type
private static final short MAX_COMP_IDX = XSTypeDefinition.SIMPLE_TYPE;
private static final boolean[] GLOBAL_COMP = {false, // null
true, // attribute
true, // element
true, // type
false, // attribute use
true, // attribute group
true, // group
false, // model group
false, // particle
false, // wildcard
true, // idc
true, // notation
false, // annotation
false, // facet
false, // multi value facet
true, // complex type
true // simple type
};
// store a certain kind of components from all namespaces
private XSNamedMap[] fComponents = null;
private ObjectList[] fComponentsExt = null;
// store the documents and their locations contributing to this namespace
// REVISIT: use StringList and XSObjectList for there fields.
// fDocuments is never used
private List<Object> fDocuments = null;
private List<String> fLocations = null;
public synchronized void addDocument(Object document, String location) {
if (fDocuments == null) {
// Parsing schema is not thread safe, synchronized may be removed
fDocuments = new CopyOnWriteArrayList<>();
fLocations = new CopyOnWriteArrayList<>();
}
fDocuments.add(document);
fLocations.add(location);
}
public synchronized void removeDocument(int index) {
if (fDocuments != null &&
index >= 0 &&
index < fDocuments.size()) {
fDocuments.remove(index);
fLocations.remove(index);
}
}
/**
* [schema namespace]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#nsi-schema_namespace">[schema namespace]</a>
* @return The target namespace of this item.
*/
public String getSchemaNamespace() {
return fTargetNamespace;
}
// annotation support
synchronized DOMParser getDOMParser() {
if (fDOMParser != null) {
DOMParser parser = fDOMParser.get();
if (parser != null) {
return parser;
}
}
// REVISIT: when schema handles XML 1.1, will need to
// revisit this (and the practice of not prepending an XML decl to the annotation string
XML11Configuration config = new XML11Configuration(fSymbolTable);
// note that this should never produce errors or require
// entity resolution, so just a barebones configuration with
// a couple of feature set will do fine
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true);
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false);
DOMParser parser = new DOMParser(config);
try {
parser.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.DEFER_NODE_EXPANSION_FEATURE, false);
}
catch (SAXException exc) {}
fDOMParser = new SoftReference<DOMParser>(parser);
return parser;
}
synchronized SAXParser getSAXParser() {
if (fSAXParser != null) {
SAXParser parser = fSAXParser.get();
if (parser != null) {
return parser;
}
}
// REVISIT: when schema handles XML 1.1, will need to
// revisit this (and the practice of not prepending an XML decl to the annotation string
XML11Configuration config = new XML11Configuration(fSymbolTable);
// note that this should never produce errors or require
// entity resolution, so just a barebones configuration with
// a couple of feature set will do fine
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true);
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false);
SAXParser parser = new SAXParser(config);
fSAXParser = new SoftReference<SAXParser>(parser);
return parser;
}
/**
* [schema components]: a list of top-level components, i.e. element
* declarations, attribute declarations, etc.
* @param objectType The type of the declaration, i.e.
* <code>ELEMENT_DECLARATION</code>. Note that
* <code>XSTypeDefinition.SIMPLE_TYPE</code> and
* <code>XSTypeDefinition.COMPLEX_TYPE</code> can also be used as the
* <code>objectType</code> to retrieve only complex types or simple
* types, instead of all types.
* @return A list of top-level definition of the specified type in
* <code>objectType</code> or an empty <code>XSNamedMap</code> if no
* such definitions exist.
*/
public synchronized XSNamedMap getComponents(short objectType) {
if (objectType <= 0 || objectType > MAX_COMP_IDX ||
!GLOBAL_COMP[objectType]) {
return XSNamedMapImpl.EMPTY_MAP;
}
if (fComponents == null)
fComponents = new XSNamedMap[MAX_COMP_IDX+1];
// get the hashtable for this type of components
if (fComponents[objectType] == null) {
SymbolHash table = null;
switch (objectType) {
case XSConstants.TYPE_DEFINITION:
case XSTypeDefinition.COMPLEX_TYPE:
case XSTypeDefinition.SIMPLE_TYPE:
table = fGlobalTypeDecls;
break;
case XSConstants.ATTRIBUTE_DECLARATION:
table = fGlobalAttrDecls;
break;
case XSConstants.ELEMENT_DECLARATION:
table = fGlobalElemDecls;
break;
case XSConstants.ATTRIBUTE_GROUP:
table = fGlobalAttrGrpDecls;
break;
case XSConstants.MODEL_GROUP_DEFINITION:
table = fGlobalGroupDecls;
break;
case XSConstants.NOTATION_DECLARATION:
table = fGlobalNotationDecls;
break;
case XSConstants.IDENTITY_CONSTRAINT:
table = this.fGlobalIDConstraintDecls;
break;
}
// for complex/simple types, create a special implementation,
// which take specific types out of the hash table
if (objectType == XSTypeDefinition.COMPLEX_TYPE ||
objectType == XSTypeDefinition.SIMPLE_TYPE) {
fComponents[objectType] = new XSNamedMap4Types(fTargetNamespace, table, objectType);
}
else {
fComponents[objectType] = new XSNamedMapImpl(fTargetNamespace, table);
}
}
return fComponents[objectType];
}
public synchronized ObjectList getComponentsExt(short objectType) {
if (objectType <= 0 || objectType > MAX_COMP_IDX ||
!GLOBAL_COMP[objectType]) {
return ObjectListImpl.EMPTY_LIST;
}
if (fComponentsExt == null)
fComponentsExt = new ObjectList[MAX_COMP_IDX+1];
// get the hashtable for this type of components
if (fComponentsExt[objectType] == null) {
SymbolHash table = null;
switch (objectType) {
case XSConstants.TYPE_DEFINITION:
case XSTypeDefinition.COMPLEX_TYPE:
case XSTypeDefinition.SIMPLE_TYPE:
table = fGlobalTypeDeclsExt;
break;
case XSConstants.ATTRIBUTE_DECLARATION:
table = fGlobalAttrDeclsExt;
break;
case XSConstants.ELEMENT_DECLARATION:
table = fGlobalElemDeclsExt;
break;
case XSConstants.ATTRIBUTE_GROUP:
table = fGlobalAttrGrpDeclsExt;
break;
case XSConstants.MODEL_GROUP_DEFINITION:
table = fGlobalGroupDeclsExt;
break;
case XSConstants.NOTATION_DECLARATION:
table = fGlobalNotationDeclsExt;
break;
case XSConstants.IDENTITY_CONSTRAINT:
table = this.fGlobalIDConstraintDeclsExt;
break;
}
Object[] entries = table.getEntries();
fComponentsExt[objectType] = new ObjectListImpl(entries, entries.length);
}
return fComponentsExt[objectType];
}
public synchronized void resetComponents() {
fComponents = null;
fComponentsExt = null;
}
/**
* Convenience method. Returns a top-level simple or complex type
* definition.
* @param name The name of the definition.
* @return An <code>XSTypeDefinition</code> or null if such definition
* does not exist.
*/
public XSTypeDefinition getTypeDefinition(String name) {
return getGlobalTypeDecl(name);
}
/**
* Convenience method. Returns a top-level attribute declaration.
* @param name The name of the declaration.
* @return A top-level attribute declaration or null if such declaration
* does not exist.
*/
public XSAttributeDeclaration getAttributeDeclaration(String name) {
return getGlobalAttributeDecl(name);
}
/**
* Convenience method. Returns a top-level element declaration.
* @param name The name of the declaration.
* @return A top-level element declaration or null if such declaration
* does not exist.
*/
public XSElementDeclaration getElementDeclaration(String name) {
return getGlobalElementDecl(name);
}
/**
* Convenience method. Returns a top-level attribute group definition.
* @param name The name of the definition.
* @return A top-level attribute group definition or null if such
* definition does not exist.
*/
public XSAttributeGroupDefinition getAttributeGroup(String name) {
return getGlobalAttributeGroupDecl(name);
}
/**
* Convenience method. Returns a top-level model group definition.
*
* @param name The name of the definition.
* @return A top-level model group definition definition or null if such
* definition does not exist.
*/
public XSModelGroupDefinition getModelGroupDefinition(String name) {
return getGlobalGroupDecl(name);
}
/**
* Convenience method. Returns a top-level notation declaration.
*
* @param name The name of the declaration.
* @return A top-level notation declaration or null if such declaration
* does not exist.
*/
public XSNotationDeclaration getNotationDeclaration(String name) {
return getGlobalNotationDecl(name);
}
public XSIDCDefinition getIDCDefinition(String name) {
return getIDConstraintDecl(name);
}
/**
* [document location]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#sd-document_location">[document location]</a>
* @return a list of document information item
*/
public StringList getDocumentLocations() {
return new StringListImpl(fLocations);
}
/**
* Return an <code>XSModel</code> that represents components in this schema
* grammar.
*
* @return an <code>XSModel</code> representing this schema grammar
*/
public XSModel toXSModel() {
return new XSModelImpl(new SchemaGrammar[]{this});
}
public XSModel toXSModel(XSGrammar[] grammars) {
if (grammars == null || grammars.length == 0)
return toXSModel();
int len = grammars.length;
boolean hasSelf = false;
for (int i = 0; i < len; i++) {
if (grammars[i] == this) {
hasSelf = true;
break;
}
}
SchemaGrammar[] gs = new SchemaGrammar[hasSelf ? len : len+1];
for (int i = 0; i < len; i++)
gs[i] = (SchemaGrammar)grammars[i];
if (!hasSelf)
gs[len] = this;
return new XSModelImpl(gs);
}
/**
* @see org.apache.xerces.xs.XSNamespaceItem#getAnnotations()
*/
public XSObjectList getAnnotations() {
if (fNumAnnotations == 0) {
return [MASK] .EMPTY_LIST;
}
return new [MASK] (fAnnotations, fNumAnnotations);
}
public void addAnnotation(XSAnnotationImpl annotation) {
if (annotation == null) {
return;
}
if (fAnnotations == null) {
fAnnotations = new XSAnnotationImpl[2];
}
else if (fNumAnnotations == fAnnotations.length) {
XSAnnotationImpl[] newArray = new XSAnnotationImpl[fNumAnnotations << 1];
System.arraycopy(fAnnotations, 0, newArray, 0, fNumAnnotations);
fAnnotations = newArray;
}
fAnnotations[fNumAnnotations++] = annotation;
}
public void setImmutable(boolean isImmutable) {
fIsImmutable = isImmutable;
}
public boolean isImmutable() {
return fIsImmutable;
}
} // class SchemaGrammar
| XSObjectListImpl |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
[MASK] (output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
[MASK] (zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void [MASK] (OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| closeQuietly |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, [MASK] .fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
[MASK] writer = [MASK] .fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
[MASK] writer = [MASK] .fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, [MASK] entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, [MASK] entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface [MASK] {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link [MASK] } that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link [MASK] } instance
*/
static [MASK] fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link [MASK] } that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link [MASK] } instance
*/
static [MASK] fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| ZipEntryContentWriter |
/*
* 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.kafka.common.config;
import org.apache.kafka.common.config.provider.ConfigProvider;
import java.util.Map;
/**
* Configuration data from a {@link ConfigProvider}.
*/
public class ConfigData {
private final Map< [MASK] , [MASK] > data;
private final Long ttl;
/**
* Creates a new ConfigData with the given data and TTL (in milliseconds).
*
* @param data a Map of key-value pairs
* @param ttl the time-to-live of the data in milliseconds, or null if there is no TTL
*/
public ConfigData(Map< [MASK] , [MASK] > data, Long ttl) {
this.data = data;
this.ttl = ttl;
}
/**
* Creates a new ConfigData with the given data.
*
* @param data a Map of key-value pairs
*/
public ConfigData(Map< [MASK] , [MASK] > data) {
this(data, null);
}
/**
* Returns the data.
*
* @return data a Map of key-value pairs
*/
public Map< [MASK] , [MASK] > data() {
return data;
}
/**
* Returns the TTL (in milliseconds).
*
* @return ttl the time-to-live (in milliseconds) of the data, or null if there is no TTL
*/
public Long ttl() {
return ttl;
}
}
| String |
/*
* Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.hosted;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.stream.Collectors;
import org.graalvm.nativeimage.hosted.RuntimeReflection;
import org.graalvm.nativeimage.hosted.RuntimeResourceAccess;
import com.oracle.svm.core.feature.AutomaticallyRegisteredFeature;
import com.oracle.svm.core.feature.InternalFeature;
import com.oracle.svm.core.jdk.ServiceCatalogSupport;
import com.oracle.svm.core.option.AccumulatingLocatableMultiOptionValue;
import com.oracle.svm.core.option.HostedOptionKey;
import com.oracle.svm.hosted.analysis.Inflation;
import jdk.graal.compiler.options.Option;
import jdk.graal.compiler.options.OptionType;
/**
* Support for {@link ServiceLoader} on Substrate VM.
*
* Services are registered in the folder {@code "META-INF/services/"} using files whose name is the
* fully qualified service interface name. We do not know which services are going to be used by a
* native image: The parameter of {@code ServiceLoader#load} is often but not always a compile-time
* constant that we can track. But we also cannot put all registered services into the native image.
*
* We therefore use the following heuristic: We add all service loader files and service
* implementation classes when the service interfaces that are seen as reachable by the static
* analysis.
*
* Each used service implementation class is added for reflection (using
* {@link org.graalvm.nativeimage.hosted.RuntimeReflection#register(Class[])}) and for reflective
* instantiation (using {@link RuntimeReflection#registerForReflectiveInstantiation(Class[])}).
*
* For each service interface, a single service loader file is added as a resource to the image. The
* single file combines all the individual files that can come from different .jar files.
*/
@AutomaticallyRegisteredFeature
public class ServiceLoaderFeature implements InternalFeature {
public static class Options {
@Option(help = "Automatically register services for run-time lookup using ServiceLoader", type = OptionType.Expert) //
public static final HostedOptionKey<Boolean> UseServiceLoaderFeature = new HostedOptionKey<>(true);
@Option(help = "Comma-separated list of services that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue. [MASK] s> ServiceLoaderFeatureExcludeServices = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue. [MASK] s.buildWithCommaDelimiter());
@Option(help = "Comma-separated list of service providers that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue. [MASK] s> ServiceLoaderFeatureExcludeServiceProviders = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue. [MASK] s.buildWithCommaDelimiter());
}
private static final Set< [MASK] > SKIPPED_SERVICES = Set.of(
// image builder internal ServiceLoader interfaces
"com.oracle.svm.hosted.NativeImageClassLoaderPostProcessing",
"org.graalvm.nativeimage.Platform",
/*
* Loaded in java.util.random.RandomGeneratorFactory.FactoryMapHolder, which is
* initialized at image build time.
*/
"java.util.random.RandomGenerator",
"java.security.Provider", // see SecurityServicesFeature
"sun.util.locale.provider.LocaleDataMetaInfo", // see LocaleSubstitutions
/* Graal hotspot-specific services */
"jdk.vm.ci.hotspot.HotSpotJVMCIBackendFactory",
"jdk.graal.compiler.hotspot.CompilerConfigurationFactory",
"jdk.graal.compiler.hotspot.HotSpotBackendFactory",
"jdk.graal.compiler.hotspot.meta.DefaultHotSpotLoweringProvider$Extensions",
"jdk.graal.compiler.hotspot.meta.HotSpotInvocationPluginProvider",
"jdk.graal.compiler.truffle.hotspot.TruffleCallBoundaryInstrumentationFactory");
// NOTE: Platform class had to be added to this list since our analysis discovers that
// Platform.includedIn is reachable regardless of fact that it is constant folded at
// registerPlatformPlugins method of SubstrateGraphBuilderPlugins. This issue hasn't manifested
// before because implementation classes were instantiated using runtime reflection instead of
// ServiceLoader (and thus weren't reachable in analysis).
/**
* Services that should not be processed here, for example because they are handled by
* specialized features.
*/
private final Set< [MASK] > servicesToSkip = new HashSet<>(SKIPPED_SERVICES);
private static final Set< [MASK] > SKIPPED_PROVIDERS = Set.of(
/* Graal hotspot-specific service-providers */
"jdk.graal.compiler.hotspot.meta.HotSpotDisassemblerProvider",
/* Skip console providers until GR-44085 is fixed */
"jdk.internal.org.jline.JdkConsoleProviderImpl", "jdk.jshell.execution.impl.ConsoleImpl$ConsoleProviderImpl");
private final Set< [MASK] > serviceProvidersToSkip = new HashSet<>(SKIPPED_PROVIDERS);
@Override
public boolean isInConfiguration(IsInConfigurationAccess access) {
return Options.UseServiceLoaderFeature.getValue();
}
@Override
public void afterRegistration(AfterRegistrationAccess access) {
servicesToSkip.addAll(Options.ServiceLoaderFeatureExcludeServices.getValue().values());
serviceProvidersToSkip.addAll(Options.ServiceLoaderFeatureExcludeServiceProviders.getValue().values());
}
@Override
public void beforeAnalysis(BeforeAnalysisAccess access) {
FeatureImpl.BeforeAnalysisAccessImpl accessImpl = (FeatureImpl.BeforeAnalysisAccessImpl) access;
accessImpl.imageClassLoader.classLoaderSupport.serviceProvidersForEach((serviceName, providers) -> {
Class<?> serviceClass = access.findClassByName(serviceName);
boolean skipService = false;
/* If the service should not end up in the image, we remove all the providers with it */
Collection< [MASK] > providersToSkip = providers;
if (servicesToSkip.contains(serviceName)) {
skipService = true;
} else if (serviceClass == null || serviceClass.isArray() || serviceClass.isPrimitive()) {
skipService = true;
} else if (!accessImpl.getHostVM().platformSupported(serviceClass)) {
skipService = true;
} else {
providersToSkip = providers.stream().filter(serviceProvidersToSkip::contains).collect(Collectors.toList());
if (!providersToSkip.isEmpty()) {
skipService = true;
}
}
if (skipService) {
ServiceCatalogSupport.singleton().removeServicesFromServicesCatalog(serviceName, new HashSet<>(providersToSkip));
return;
}
access.registerReachabilityHandler(a -> handleServiceClassIsReachable(a, serviceClass, providers), serviceClass);
});
}
void handleServiceClassIsReachable(DuringAnalysisAccess access, Class<?> serviceProvider, Collection< [MASK] > providers) {
LinkedHashSet< [MASK] > registeredProviders = new LinkedHashSet<>();
for ( [MASK] provider : providers) {
if (serviceProvidersToSkip.contains(provider)) {
continue;
}
/* Make provider reflectively instantiable */
Class<?> providerClass = access.findClassByName(provider);
if (providerClass == null || providerClass.isArray() || providerClass.isPrimitive()) {
continue;
}
FeatureImpl.DuringAnalysisAccessImpl accessImpl = (FeatureImpl.DuringAnalysisAccessImpl) access;
if (!accessImpl.getHostVM().platformSupported(providerClass)) {
continue;
}
if (((Inflation) accessImpl.getBigBang()).getAnnotationSubstitutionProcessor().isDeleted(providerClass)) {
/* Disallow services with implementation classes that are marked as @Deleted */
continue;
}
/*
* Find either a public static provider() method or a nullary constructor (or both).
* Skip providers that do not comply with requirements.
*
* See ServiceLoader#loadProvider and ServiceLoader#findStaticProviderMethod.
*/
Constructor<?> nullaryConstructor = null;
Method nullaryProviderMethod = null;
try {
/* Only look for a provider() method if provider class is in an explicit module. */
if (providerClass.getModule().isNamed() && !providerClass.getModule().getDescriptor().isAutomatic()) {
for (Method method : providerClass.getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers()) &&
method.getParameterCount() == 0 && method.getName().equals("provider")) {
if (nullaryProviderMethod == null) {
nullaryProviderMethod = method;
} else {
/* There must be at most one public static provider() method. */
nullaryProviderMethod = null;
break;
}
}
}
}
Constructor<?> constructor = providerClass.getDeclaredConstructor();
if (Modifier.isPublic(constructor.getModifiers())) {
nullaryConstructor = constructor;
}
} catch (NoSuchMethodException | SecurityException | LinkageError e) {
// ignore
}
if (nullaryConstructor != null || nullaryProviderMethod != null) {
RuntimeReflection.register(providerClass);
if (nullaryConstructor != null) {
/*
* Registering a constructor with
* RuntimeReflection.registerConstructorLookup(providerClass) does not produce
* the same behavior as using RuntimeReflection.register(nullaryConstructor). In
* the first case, the constructor is marked for query purposes only, so this
* if-statement cannot be eliminated.
*
*/
RuntimeReflection.register(nullaryConstructor);
} else {
/*
* If there's no nullary constructor, register it as negative lookup to avoid
* throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerConstructorLookup(providerClass);
}
if (nullaryProviderMethod != null) {
RuntimeReflection.register(nullaryProviderMethod);
} else {
/*
* If there's no declared public provider() method, register it as negative
* lookup to avoid throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerMethodLookup(providerClass, "provider");
}
}
/*
* Register the provider in both cases: when it is JCA-compliant (has a nullary
* constructor or a provider method) or when it lacks both. If neither is present, a
* ServiceConfigurationError will be thrown at runtime, consistent with HotSpot
* behavior.
*/
registeredProviders.add(provider);
}
if (!registeredProviders.isEmpty()) {
[MASK] serviceResourceLocation = "META-INF/services/" + serviceProvider.getName();
byte[] serviceFileData = registeredProviders.stream().collect(Collectors.joining("\n")).getBytes(StandardCharsets.UTF_8);
RuntimeResourceAccess.addResource(access.getApplicationClassLoader().getUnnamedModule(), serviceResourceLocation, serviceFileData);
}
}
}
| String |
/**
* Copyright © 2016-2024 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thingsboard.server.service.sync.ie.importing.impl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.NotificationTargetId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.notification.targets.NotificationTarget;
import org.thingsboard.server.common.data.notification.targets.NotificationTargetType;
import org.thingsboard.server.common.data.notification.targets.platform.CustomerUsersFilter;
import org.thingsboard.server.common.data.notification.targets.platform.PlatformUsersNotificationTargetConfig;
import org.thingsboard.server.common.data.notification.targets.platform.TenantAdministratorsFilter;
import org.thingsboard.server.common.data.notification.targets.platform.UserListFilter;
import org.thingsboard.server.common.data.notification.targets.platform.UsersFilter;
import org.thingsboard.server.common.data.sync.ie. [MASK] ;
import org.thingsboard.server.dao.notification.NotificationTargetService;
import org.thingsboard.server.dao.service.ConstraintValidator;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.sync.vc.data.EntitiesImportCtx;
import java.util.List;
@Service
@TbCoreComponent
@RequiredArgsConstructor
public class NotificationTargetImportService extends BaseEntityImportService<NotificationTargetId, NotificationTarget, [MASK] <NotificationTarget>> {
private final NotificationTargetService notificationTargetService;
@Override
protected void setOwner(TenantId tenantId, NotificationTarget notificationTarget, IdProvider idProvider) {
notificationTarget.setTenantId(tenantId);
}
@Override
protected NotificationTarget prepare(EntitiesImportCtx ctx, NotificationTarget notificationTarget, NotificationTarget oldNotificationTarget, [MASK] <NotificationTarget> exportData, IdProvider idProvider) {
if (notificationTarget.getConfiguration().getType() == NotificationTargetType.PLATFORM_USERS) {
UsersFilter usersFilter = ((PlatformUsersNotificationTargetConfig) notificationTarget.getConfiguration()).getUsersFilter();
switch (usersFilter.getType()) {
case CUSTOMER_USERS:
CustomerUsersFilter customerUsersFilter = (CustomerUsersFilter) usersFilter;
customerUsersFilter.setCustomerId(idProvider.getInternalId(new CustomerId(customerUsersFilter.getCustomerId())).getId());
break;
case USER_LIST:
UserListFilter userListFilter = (UserListFilter) usersFilter;
userListFilter.setUsersIds(List.of(ctx.getUser().getUuidId())); // user entities are not supported by VC; replacing with current user id
break;
case TENANT_ADMINISTRATORS:
if (CollectionUtils.isNotEmpty(((TenantAdministratorsFilter) usersFilter).getTenantsIds()) ||
CollectionUtils.isNotEmpty(((TenantAdministratorsFilter) usersFilter).getTenantProfilesIds())) {
throw new IllegalArgumentException("Permission denied");
}
break;
case SYSTEM_ADMINISTRATORS:
throw new AccessDeniedException("Permission denied");
}
}
return notificationTarget;
}
@Override
protected NotificationTarget saveOrUpdate(EntitiesImportCtx ctx, NotificationTarget notificationTarget, [MASK] <NotificationTarget> exportData, IdProvider idProvider) {
ConstraintValidator.validateFields(notificationTarget);
return notificationTargetService.saveNotificationTarget(ctx.getTenantId(), notificationTarget);
}
@Override
protected void onEntitySaved(User user, NotificationTarget savedEntity, NotificationTarget oldEntity) throws ThingsboardException {
entityActionService.logEntityAction(user, savedEntity.getId(), savedEntity, null,
oldEntity == null ? ActionType.ADDED : ActionType.UPDATED, null);
}
@Override
protected NotificationTarget deepCopy(NotificationTarget notificationTarget) {
return new NotificationTarget(notificationTarget);
}
@Override
public EntityType getEntityType() {
return EntityType.NOTIFICATION_TARGET;
}
}
| EntityExportData |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
[MASK] (name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
[MASK] ("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
[MASK] (classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
[MASK] (NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
[MASK] (name, this.layerIndex::writeTo, false);
}
}
private void [MASK] (String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
[MASK] (name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void [MASK] (String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| writeEntry |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> [MASK] ;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> [MASK] , String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this. [MASK] = [MASK] ;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this. [MASK] .apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| compressionResolver |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file [MASK] } to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails [MASK] ) {
if (skipProcessing( [MASK] )) {
return;
}
try {
writeLoaderEntriesIfNecessary( [MASK] );
if ( [MASK] .isDirectory()) {
processDirectory( [MASK] );
}
else {
processFile( [MASK] );
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + [MASK] + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails [MASK] ) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy( [MASK] )
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory( [MASK] ));
}
private void processDirectory(FileCopyDetails [MASK] ) throws IOException {
String name = [MASK] .getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime( [MASK] ), getFileMode( [MASK] ));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails [MASK] ) throws IOException {
String name = [MASK] .getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime( [MASK] ), getFileMode( [MASK] ));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply( [MASK] );
if (compression == ZipCompression.STORED) {
prepareStoredEntry( [MASK] , entry);
}
this.out.putArchiveEntry(entry);
[MASK] .copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy( [MASK] )) {
this.writtenLibraries.put(name, [MASK] );
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, [MASK] );
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer( [MASK] );
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails [MASK] ) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf( [MASK] )) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails [MASK] ) {
if ( [MASK] == null) {
return false;
}
String[] segments = [MASK] .getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails [MASK] , ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry( [MASK] .open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy( [MASK] )) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash( [MASK] .getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails [MASK] ) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if ( [MASK] != null) {
return [MASK] .getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails [MASK] ) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions( [MASK] );
}
private int getPermissions(FileCopyDetails [MASK] ) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? [MASK] .getPermissions().toUnixNumeric() : getMode( [MASK] );
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails [MASK] ) {
return [MASK] .getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| details |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip. [MASK] ;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
[MASK] entry = new [MASK] (name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
[MASK] entry = new [MASK] (name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
[MASK] entry = new [MASK] (parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
[MASK] entry = new [MASK] (name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry( [MASK] entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, [MASK] archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, [MASK] archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link [MASK] }.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize( [MASK] entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry( [MASK] entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| ZipArchiveEntry |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, [MASK] > compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, [MASK] > compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
[MASK] compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == [MASK] .STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| ZipCompression |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration [MASK] ;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration [MASK] , Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this. [MASK] = [MASK] ;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this. [MASK] == null) {
return;
}
try {
File file = this. [MASK] .getScript();
Map<String, String> properties = this. [MASK] .getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| launchScript |
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.core.utils;
import javax.servlet.http. [MASK] ;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* ReuseHttpRequest.
*
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public interface ReuseHttpRequest extends [MASK] {
/**
* get request body.
*
* @return object
* @throws Exception exception
*/
Object getBody() throws Exception;
/**
* Remove duplicate values from the array.
*
* @param request {@link [MASK] }
* @return {@link Map}
*/
default Map<String, String[]> toDuplication( [MASK] request) {
Map<String, String[]> tmp = request.getParameterMap();
Map<String, String[]> result = new HashMap<>(tmp.size());
Set<String> set = new HashSet<>();
for (Map.Entry<String, String[]> entry : tmp.entrySet()) {
set.addAll(Arrays.asList(entry.getValue()));
result.put(entry.getKey(), set.toArray(new String[0]));
set.clear();
}
return result;
}
}
| HttpServletRequest |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor [MASK] = new Processor(zipOutput);
copyActions.process( [MASK] ::process);
[MASK] .finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| processor |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean [MASK] )
throws IOException {
writeEntry(name, entryWriter, [MASK] , ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean [MASK] ,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if ( [MASK] && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| addToLayerIndex |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, [MASK] (details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, [MASK] (details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries( [MASK] (), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, [MASK] (), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long [MASK] () {
return [MASK] (null);
}
private Long [MASK] (FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| getTime |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io. [MASK] ;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.from [MASK] (library.openStream()), false, (entry) -> {
try ( [MASK] in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try ( [MASK] inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.from [MASK] (inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry( [MASK] input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link [MASK] }.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter from [MASK] ( [MASK] in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize( [MASK] inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load( [MASK] inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| InputStream |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex. [MASK] ;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final [MASK] REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = [MASK]
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| Pattern |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util. [MASK] ;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return ( [MASK] .current().compareTo( [MASK] .version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| GradleVersion |
/*
* 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.kafka.common.config;
import org.apache.kafka.common.config.provider.ConfigProvider;
import java.util.Map;
/**
* Configuration data from a {@link ConfigProvider}.
*/
public class [MASK] {
private final Map<String, String> data;
private final Long ttl;
/**
* Creates a new [MASK] with the given data and TTL (in milliseconds).
*
* @param data a Map of key-value pairs
* @param ttl the time-to-live of the data in milliseconds, or null if there is no TTL
*/
public [MASK] (Map<String, String> data, Long ttl) {
this.data = data;
this.ttl = ttl;
}
/**
* Creates a new [MASK] with the given data.
*
* @param data a Map of key-value pairs
*/
public [MASK] (Map<String, String> data) {
this(data, null);
}
/**
* Returns the data.
*
* @return data a Map of key-value pairs
*/
public Map<String, String> data() {
return data;
}
/**
* Returns the TTL (in milliseconds).
*
* @return ttl the time-to-live (in milliseconds) of the data, or null if there is no TTL
*/
public Long ttl() {
return ttl;
}
}
| ConfigData |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean [MASK] ;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean [MASK] , LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this. [MASK] = [MASK] ;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this. [MASK] && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| supportsSignatureFile |
/*
* Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.hosted;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.stream.Collectors;
import org.graalvm.nativeimage.hosted.RuntimeReflection;
import org.graalvm.nativeimage.hosted.RuntimeResourceAccess;
import com.oracle.svm.core.feature.AutomaticallyRegisteredFeature;
import com.oracle.svm.core.feature.InternalFeature;
import com.oracle.svm.core.jdk.ServiceCatalogSupport;
import com.oracle.svm.core.option.AccumulatingLocatableMultiOptionValue;
import com.oracle.svm.core.option.HostedOptionKey;
import com.oracle.svm.hosted.analysis.Inflation;
import jdk.graal.compiler.options.Option;
import jdk.graal.compiler.options.OptionType;
/**
* Support for {@link ServiceLoader} on Substrate VM.
*
* Services are registered in the folder {@code "META-INF/services/"} using files whose name is the
* fully qualified service interface name. We do not know which services are going to be used by a
* native image: The parameter of {@code ServiceLoader#load} is often but not always a compile-time
* constant that we can track. But we also cannot put all registered services into the native image.
*
* We therefore use the following heuristic: We add all service loader files and service
* implementation classes when the service interfaces that are seen as reachable by the static
* analysis.
*
* Each used service implementation class is added for reflection (using
* {@link org.graalvm.nativeimage.hosted.RuntimeReflection#register(Class[])}) and for reflective
* instantiation (using {@link RuntimeReflection#registerForReflectiveInstantiation(Class[])}).
*
* For each service interface, a single service loader file is added as a resource to the image. The
* single file combines all the individual files that can come from different .jar files.
*/
@AutomaticallyRegisteredFeature
public class ServiceLoaderFeature implements InternalFeature {
public static class Options {
@Option(help = "Automatically register services for run-time lookup using ServiceLoader", type = OptionType.Expert) //
public static final HostedOptionKey<Boolean> UseServiceLoaderFeature = new HostedOptionKey<>(true);
@Option(help = "Comma-separated list of services that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServices = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
@Option(help = "Comma-separated list of service providers that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServiceProviders = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
}
private static final Set<String> SKIPPED_SERVICES = Set.of(
// image builder internal ServiceLoader interfaces
"com.oracle.svm.hosted.NativeImageClassLoaderPostProcessing",
"org.graalvm.nativeimage.Platform",
/*
* Loaded in java.util.random.RandomGeneratorFactory.FactoryMapHolder, which is
* initialized at image build time.
*/
"java.util.random.RandomGenerator",
"java.security.Provider", // see SecurityServicesFeature
"sun.util.locale.provider.LocaleDataMetaInfo", // see LocaleSubstitutions
/* Graal hotspot-specific services */
"jdk.vm.ci.hotspot.HotSpotJVMCIBackendFactory",
"jdk.graal.compiler.hotspot.CompilerConfigurationFactory",
"jdk.graal.compiler.hotspot.HotSpotBackendFactory",
"jdk.graal.compiler.hotspot.meta.DefaultHotSpotLoweringProvider$Extensions",
"jdk.graal.compiler.hotspot.meta.HotSpotInvocationPluginProvider",
"jdk.graal.compiler.truffle.hotspot.TruffleCallBoundaryInstrumentationFactory");
// NOTE: Platform class had to be added to this list since our analysis discovers that
// Platform.includedIn is reachable regardless of fact that it is constant folded at
// registerPlatformPlugins method of SubstrateGraphBuilderPlugins. This issue hasn't manifested
// before because implementation classes were instantiated using runtime reflection instead of
// ServiceLoader (and thus weren't reachable in analysis).
/**
* Services that should not be processed here, for example because they are handled by
* specialized features.
*/
private final Set<String> servicesToSkip = new HashSet<>(SKIPPED_SERVICES);
private static final Set<String> SKIPPED_PROVIDERS = Set.of(
/* Graal hotspot-specific service-providers */
"jdk.graal.compiler.hotspot.meta.HotSpotDisassemblerProvider",
/* Skip console providers until GR-44085 is fixed */
"jdk.internal.org.jline.JdkConsoleProviderImpl", "jdk.jshell.execution.impl.ConsoleImpl$ConsoleProviderImpl");
private final Set<String> serviceProvidersToSkip = new HashSet<>(SKIPPED_PROVIDERS);
@Override
public boolean isInConfiguration(IsInConfigurationAccess access) {
return Options.UseServiceLoaderFeature.getValue();
}
@Override
public void afterRegistration(AfterRegistrationAccess access) {
servicesToSkip.addAll(Options.ServiceLoaderFeatureExcludeServices.getValue().values());
serviceProvidersToSkip.addAll(Options.ServiceLoaderFeatureExcludeServiceProviders.getValue().values());
}
@Override
public void beforeAnalysis(BeforeAnalysisAccess access) {
FeatureImpl.BeforeAnalysisAccessImpl accessImpl = (FeatureImpl.BeforeAnalysisAccessImpl) access;
accessImpl.imageClassLoader.classLoaderSupport.serviceProvidersForEach((serviceName, providers) -> {
Class<?> serviceClass = access.findClassByName(serviceName);
boolean skipService = false;
/* If the service should not end up in the image, we remove all the providers with it */
Collection<String> providersToSkip = providers;
if (servicesToSkip. [MASK] (serviceName)) {
skipService = true;
} else if (serviceClass == null || serviceClass.isArray() || serviceClass.isPrimitive()) {
skipService = true;
} else if (!accessImpl.getHostVM().platformSupported(serviceClass)) {
skipService = true;
} else {
providersToSkip = providers.stream().filter(serviceProvidersToSkip:: [MASK] ).collect(Collectors.toList());
if (!providersToSkip.isEmpty()) {
skipService = true;
}
}
if (skipService) {
ServiceCatalogSupport.singleton().removeServicesFromServicesCatalog(serviceName, new HashSet<>(providersToSkip));
return;
}
access.registerReachabilityHandler(a -> handleServiceClassIsReachable(a, serviceClass, providers), serviceClass);
});
}
void handleServiceClassIsReachable(DuringAnalysisAccess access, Class<?> serviceProvider, Collection<String> providers) {
LinkedHashSet<String> registeredProviders = new LinkedHashSet<>();
for (String provider : providers) {
if (serviceProvidersToSkip. [MASK] (provider)) {
continue;
}
/* Make provider reflectively instantiable */
Class<?> providerClass = access.findClassByName(provider);
if (providerClass == null || providerClass.isArray() || providerClass.isPrimitive()) {
continue;
}
FeatureImpl.DuringAnalysisAccessImpl accessImpl = (FeatureImpl.DuringAnalysisAccessImpl) access;
if (!accessImpl.getHostVM().platformSupported(providerClass)) {
continue;
}
if (((Inflation) accessImpl.getBigBang()).getAnnotationSubstitutionProcessor().isDeleted(providerClass)) {
/* Disallow services with implementation classes that are marked as @Deleted */
continue;
}
/*
* Find either a public static provider() method or a nullary constructor (or both).
* Skip providers that do not comply with requirements.
*
* See ServiceLoader#loadProvider and ServiceLoader#findStaticProviderMethod.
*/
Constructor<?> nullaryConstructor = null;
Method nullaryProviderMethod = null;
try {
/* Only look for a provider() method if provider class is in an explicit module. */
if (providerClass.getModule().isNamed() && !providerClass.getModule().getDescriptor().isAutomatic()) {
for (Method method : providerClass.getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers()) &&
method.getParameterCount() == 0 && method.getName().equals("provider")) {
if (nullaryProviderMethod == null) {
nullaryProviderMethod = method;
} else {
/* There must be at most one public static provider() method. */
nullaryProviderMethod = null;
break;
}
}
}
}
Constructor<?> constructor = providerClass.getDeclaredConstructor();
if (Modifier.isPublic(constructor.getModifiers())) {
nullaryConstructor = constructor;
}
} catch (NoSuchMethodException | SecurityException | LinkageError e) {
// ignore
}
if (nullaryConstructor != null || nullaryProviderMethod != null) {
RuntimeReflection.register(providerClass);
if (nullaryConstructor != null) {
/*
* Registering a constructor with
* RuntimeReflection.registerConstructorLookup(providerClass) does not produce
* the same behavior as using RuntimeReflection.register(nullaryConstructor). In
* the first case, the constructor is marked for query purposes only, so this
* if-statement cannot be eliminated.
*
*/
RuntimeReflection.register(nullaryConstructor);
} else {
/*
* If there's no nullary constructor, register it as negative lookup to avoid
* throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerConstructorLookup(providerClass);
}
if (nullaryProviderMethod != null) {
RuntimeReflection.register(nullaryProviderMethod);
} else {
/*
* If there's no declared public provider() method, register it as negative
* lookup to avoid throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerMethodLookup(providerClass, "provider");
}
}
/*
* Register the provider in both cases: when it is JCA-compliant (has a nullary
* constructor or a provider method) or when it lacks both. If neither is present, a
* ServiceConfigurationError will be thrown at runtime, consistent with HotSpot
* behavior.
*/
registeredProviders.add(provider);
}
if (!registeredProviders.isEmpty()) {
String serviceResourceLocation = "META-INF/services/" + serviceProvider.getName();
byte[] serviceFileData = registeredProviders.stream().collect(Collectors.joining("\n")).getBytes(StandardCharsets.UTF_8);
RuntimeResourceAccess.addResource(access.getApplicationClassLoader().getUnnamedModule(), serviceResourceLocation, serviceFileData);
}
}
}
| contains |
/**
* Copyright © 2016-2024 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thingsboard.server. [MASK] .sync.ie.importing.impl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.NotificationTargetId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.notification.targets.NotificationTarget;
import org.thingsboard.server.common.data.notification.targets.NotificationTargetType;
import org.thingsboard.server.common.data.notification.targets.platform.CustomerUsersFilter;
import org.thingsboard.server.common.data.notification.targets.platform.PlatformUsersNotificationTargetConfig;
import org.thingsboard.server.common.data.notification.targets.platform.TenantAdministratorsFilter;
import org.thingsboard.server.common.data.notification.targets.platform.UserListFilter;
import org.thingsboard.server.common.data.notification.targets.platform.UsersFilter;
import org.thingsboard.server.common.data.sync.ie.EntityExportData;
import org.thingsboard.server.dao.notification.NotificationTargetService;
import org.thingsboard.server.dao. [MASK] .ConstraintValidator;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server. [MASK] .sync.vc.data.EntitiesImportCtx;
import java.util.List;
@Service
@TbCoreComponent
@RequiredArgsConstructor
public class NotificationTargetImportService extends BaseEntityImportService<NotificationTargetId, NotificationTarget, EntityExportData<NotificationTarget>> {
private final NotificationTargetService notificationTargetService;
@Override
protected void setOwner(TenantId tenantId, NotificationTarget notificationTarget, IdProvider idProvider) {
notificationTarget.setTenantId(tenantId);
}
@Override
protected NotificationTarget prepare(EntitiesImportCtx ctx, NotificationTarget notificationTarget, NotificationTarget oldNotificationTarget, EntityExportData<NotificationTarget> exportData, IdProvider idProvider) {
if (notificationTarget.getConfiguration().getType() == NotificationTargetType.PLATFORM_USERS) {
UsersFilter usersFilter = ((PlatformUsersNotificationTargetConfig) notificationTarget.getConfiguration()).getUsersFilter();
switch (usersFilter.getType()) {
case CUSTOMER_USERS:
CustomerUsersFilter customerUsersFilter = (CustomerUsersFilter) usersFilter;
customerUsersFilter.setCustomerId(idProvider.getInternalId(new CustomerId(customerUsersFilter.getCustomerId())).getId());
break;
case USER_LIST:
UserListFilter userListFilter = (UserListFilter) usersFilter;
userListFilter.setUsersIds(List.of(ctx.getUser().getUuidId())); // user entities are not supported by VC; replacing with current user id
break;
case TENANT_ADMINISTRATORS:
if (CollectionUtils.isNotEmpty(((TenantAdministratorsFilter) usersFilter).getTenantsIds()) ||
CollectionUtils.isNotEmpty(((TenantAdministratorsFilter) usersFilter).getTenantProfilesIds())) {
throw new IllegalArgumentException("Permission denied");
}
break;
case SYSTEM_ADMINISTRATORS:
throw new AccessDeniedException("Permission denied");
}
}
return notificationTarget;
}
@Override
protected NotificationTarget saveOrUpdate(EntitiesImportCtx ctx, NotificationTarget notificationTarget, EntityExportData<NotificationTarget> exportData, IdProvider idProvider) {
ConstraintValidator.validateFields(notificationTarget);
return notificationTargetService.saveNotificationTarget(ctx.getTenantId(), notificationTarget);
}
@Override
protected void onEntitySaved(User user, NotificationTarget savedEntity, NotificationTarget oldEntity) throws ThingsboardException {
entityActionService.logEntityAction(user, savedEntity.getId(), savedEntity, null,
oldEntity == null ? ActionType.ADDED : ActionType.UPDATED, null);
}
@Override
protected NotificationTarget deepCopy(NotificationTarget notificationTarget) {
return new NotificationTarget(notificationTarget);
}
@Override
public EntityType getEntityType() {
return EntityType.NOTIFICATION_TARGET;
}
}
| service |
/*
* Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.hosted;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.stream.Collectors;
import org.graalvm.nativeimage.hosted.RuntimeReflection;
import org.graalvm.nativeimage.hosted.RuntimeResourceAccess;
import com.oracle.svm.core.feature.AutomaticallyRegisteredFeature;
import com.oracle.svm.core.feature.InternalFeature;
import com.oracle.svm.core.jdk.ServiceCatalogSupport;
import com.oracle.svm.core.option.AccumulatingLocatableMultiOptionValue;
import com.oracle.svm.core.option.HostedOptionKey;
import com.oracle.svm.hosted.analysis.Inflation;
import jdk.graal.compiler.options.Option;
import jdk.graal.compiler.options.OptionType;
/**
* Support for {@link ServiceLoader} on Substrate VM.
*
* Services are registered in the folder {@code "META-INF/services/"} using files whose name is the
* fully qualified service interface name. We do not know which services are going to be used by a
* native image: The parameter of {@code ServiceLoader#load} is often but not always a compile-time
* constant that we can track. But we also cannot put all registered services into the native image.
*
* We therefore use the following heuristic: We add all service loader files and service
* implementation classes when the service interfaces that are seen as reachable by the static
* analysis.
*
* Each used service implementation class is added for reflection (using
* {@link org.graalvm.nativeimage.hosted.RuntimeReflection#register(Class[])}) and for reflective
* instantiation (using {@link RuntimeReflection#registerForReflectiveInstantiation(Class[])}).
*
* For each service interface, a single service loader file is added as a resource to the image. The
* single file combines all the individual files that can come from different .jar files.
*/
@AutomaticallyRegisteredFeature
public class ServiceLoaderFeature implements InternalFeature {
public static class Options {
@Option(help = "Automatically register services for run-time lookup using ServiceLoader", type = OptionType.Expert) //
public static final HostedOptionKey<Boolean> UseServiceLoaderFeature = new HostedOptionKey<>(true);
@Option(help = "Comma-separated list of services that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServices = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
@Option(help = "Comma-separated list of service providers that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServiceProviders = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
}
private static final Set<String> SKIPPED_SERVICES = Set.of(
// image builder internal ServiceLoader interfaces
"com.oracle.svm.hosted.NativeImageClassLoaderPostProcessing",
"org.graalvm.nativeimage.Platform",
/*
* Loaded in java.util.random.RandomGeneratorFactory.FactoryMapHolder, which is
* initialized at image build time.
*/
"java.util.random.RandomGenerator",
"java.security.Provider", // see SecurityServicesFeature
"sun.util.locale.provider.LocaleDataMetaInfo", // see LocaleSubstitutions
/* Graal hotspot-specific services */
"jdk.vm.ci.hotspot.HotSpotJVMCIBackendFactory",
"jdk.graal.compiler.hotspot.CompilerConfigurationFactory",
"jdk.graal.compiler.hotspot.HotSpotBackendFactory",
"jdk.graal.compiler.hotspot.meta.DefaultHotSpotLoweringProvider$Extensions",
"jdk.graal.compiler.hotspot.meta.HotSpotInvocationPluginProvider",
"jdk.graal.compiler.truffle.hotspot.TruffleCallBoundaryInstrumentationFactory");
// NOTE: Platform class had to be added to this list since our analysis discovers that
// Platform.includedIn is reachable regardless of fact that it is constant folded at
// registerPlatformPlugins method of SubstrateGraphBuilderPlugins. This issue hasn't manifested
// before because implementation classes were instantiated using runtime reflection instead of
// ServiceLoader (and thus weren't reachable in analysis).
/**
* Services that should not be processed here, for example because they are handled by
* specialized features.
*/
private final Set<String> servicesToSkip = new HashSet<>(SKIPPED_SERVICES);
private static final Set<String> SKIPPED_PROVIDERS = Set.of(
/* Graal hotspot-specific service-providers */
"jdk.graal.compiler.hotspot.meta.HotSpotDisassemblerProvider",
/* Skip console providers until GR-44085 is fixed */
"jdk.internal.org.jline.JdkConsoleProviderImpl", "jdk.jshell.execution.impl.ConsoleImpl$ConsoleProviderImpl");
private final Set<String> serviceProvidersToSkip = new HashSet<>(SKIPPED_PROVIDERS);
@Override
public boolean isInConfiguration(IsInConfigurationAccess access) {
return Options.UseServiceLoaderFeature. [MASK] ();
}
@Override
public void afterRegistration(AfterRegistrationAccess access) {
servicesToSkip.addAll(Options.ServiceLoaderFeatureExcludeServices. [MASK] ().values());
serviceProvidersToSkip.addAll(Options.ServiceLoaderFeatureExcludeServiceProviders. [MASK] ().values());
}
@Override
public void beforeAnalysis(BeforeAnalysisAccess access) {
FeatureImpl.BeforeAnalysisAccessImpl accessImpl = (FeatureImpl.BeforeAnalysisAccessImpl) access;
accessImpl.imageClassLoader.classLoaderSupport.serviceProvidersForEach((serviceName, providers) -> {
Class<?> serviceClass = access.findClassByName(serviceName);
boolean skipService = false;
/* If the service should not end up in the image, we remove all the providers with it */
Collection<String> providersToSkip = providers;
if (servicesToSkip.contains(serviceName)) {
skipService = true;
} else if (serviceClass == null || serviceClass.isArray() || serviceClass.isPrimitive()) {
skipService = true;
} else if (!accessImpl.getHostVM().platformSupported(serviceClass)) {
skipService = true;
} else {
providersToSkip = providers.stream().filter(serviceProvidersToSkip::contains).collect(Collectors.toList());
if (!providersToSkip.isEmpty()) {
skipService = true;
}
}
if (skipService) {
ServiceCatalogSupport.singleton().removeServicesFromServicesCatalog(serviceName, new HashSet<>(providersToSkip));
return;
}
access.registerReachabilityHandler(a -> handleServiceClassIsReachable(a, serviceClass, providers), serviceClass);
});
}
void handleServiceClassIsReachable(DuringAnalysisAccess access, Class<?> serviceProvider, Collection<String> providers) {
LinkedHashSet<String> registeredProviders = new LinkedHashSet<>();
for (String provider : providers) {
if (serviceProvidersToSkip.contains(provider)) {
continue;
}
/* Make provider reflectively instantiable */
Class<?> providerClass = access.findClassByName(provider);
if (providerClass == null || providerClass.isArray() || providerClass.isPrimitive()) {
continue;
}
FeatureImpl.DuringAnalysisAccessImpl accessImpl = (FeatureImpl.DuringAnalysisAccessImpl) access;
if (!accessImpl.getHostVM().platformSupported(providerClass)) {
continue;
}
if (((Inflation) accessImpl.getBigBang()).getAnnotationSubstitutionProcessor().isDeleted(providerClass)) {
/* Disallow services with implementation classes that are marked as @Deleted */
continue;
}
/*
* Find either a public static provider() method or a nullary constructor (or both).
* Skip providers that do not comply with requirements.
*
* See ServiceLoader#loadProvider and ServiceLoader#findStaticProviderMethod.
*/
Constructor<?> nullaryConstructor = null;
Method nullaryProviderMethod = null;
try {
/* Only look for a provider() method if provider class is in an explicit module. */
if (providerClass.getModule().isNamed() && !providerClass.getModule().getDescriptor().isAutomatic()) {
for (Method method : providerClass.getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers()) &&
method.getParameterCount() == 0 && method.getName().equals("provider")) {
if (nullaryProviderMethod == null) {
nullaryProviderMethod = method;
} else {
/* There must be at most one public static provider() method. */
nullaryProviderMethod = null;
break;
}
}
}
}
Constructor<?> constructor = providerClass.getDeclaredConstructor();
if (Modifier.isPublic(constructor.getModifiers())) {
nullaryConstructor = constructor;
}
} catch (NoSuchMethodException | SecurityException | LinkageError e) {
// ignore
}
if (nullaryConstructor != null || nullaryProviderMethod != null) {
RuntimeReflection.register(providerClass);
if (nullaryConstructor != null) {
/*
* Registering a constructor with
* RuntimeReflection.registerConstructorLookup(providerClass) does not produce
* the same behavior as using RuntimeReflection.register(nullaryConstructor). In
* the first case, the constructor is marked for query purposes only, so this
* if-statement cannot be eliminated.
*
*/
RuntimeReflection.register(nullaryConstructor);
} else {
/*
* If there's no nullary constructor, register it as negative lookup to avoid
* throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerConstructorLookup(providerClass);
}
if (nullaryProviderMethod != null) {
RuntimeReflection.register(nullaryProviderMethod);
} else {
/*
* If there's no declared public provider() method, register it as negative
* lookup to avoid throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerMethodLookup(providerClass, "provider");
}
}
/*
* Register the provider in both cases: when it is JCA-compliant (has a nullary
* constructor or a provider method) or when it lacks both. If neither is present, a
* ServiceConfigurationError will be thrown at runtime, consistent with HotSpot
* behavior.
*/
registeredProviders.add(provider);
}
if (!registeredProviders.isEmpty()) {
String serviceResourceLocation = "META-INF/services/" + serviceProvider.getName();
byte[] serviceFileData = registeredProviders.stream().collect(Collectors.joining("\n")).getBytes(StandardCharsets.UTF_8);
RuntimeResourceAccess.addResource(access.getApplicationClassLoader().getUnnamedModule(), serviceResourceLocation, serviceFileData);
}
}
}
| getValue |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor [MASK] or = new Processor(zipOutput);
copyActions. [MASK] ( [MASK] or:: [MASK] );
[MASK] or.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal [MASK] used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void [MASK] (FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
[MASK] Directory(details);
}
else {
[MASK] File(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void [MASK] Directory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void [MASK] File(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| process |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry [MASK] = new ZipArchiveEntry(name + '/');
prepareEntry( [MASK] , name, getTime(details), getFileMode(details));
this.out.putArchiveEntry( [MASK] );
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry [MASK] = new ZipArchiveEntry(name);
prepareEntry( [MASK] , name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, [MASK] );
}
this.out.putArchiveEntry( [MASK] );
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry [MASK] = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry( [MASK] , parentDirectory, time, getDirMode());
this.out.putArchiveEntry( [MASK] );
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, ( [MASK] ) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), [MASK] );
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> [MASK] : this.writtenLibraries. [MASK] Set()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find( [MASK] .getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add( [MASK] .getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter [MASK] Writer, boolean addToLayerIndex)
throws IOException {
writeEntry(name, [MASK] Writer, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter [MASK] Writer, boolean addToLayerIndex,
ZipEntryCustomizer [MASK] Customizer) throws IOException {
ZipArchiveEntry [MASK] = new ZipArchiveEntry(name);
prepareEntry( [MASK] , name, getTime(), getFileMode());
[MASK] Customizer.customize( [MASK] );
this.out.putArchiveEntry( [MASK] );
[MASK] Writer.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry [MASK] , String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
[MASK] .setUnixMode(mode);
if (time != null) {
[MASK] .setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = ( [MASK] ) -> {
};
/**
* Customize the [MASK] .
* @param [MASK] the [MASK] to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry [MASK] ) throws IOException;
}
/**
* Callback used to write a zip [MASK] data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the [MASK] data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry [MASK] ) {
[MASK] .setSize(this.size);
[MASK] .setCompressedSize(this.size);
[MASK] .setCrc(this.crc.getValue());
[MASK] .setMethod(ZipEntry.STORED);
}
}
}
| entry |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter [MASK] , boolean addToLayerIndex)
throws IOException {
writeEntry(name, [MASK] , addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter [MASK] , boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
[MASK] .writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| entryWriter |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream [MASK] = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream( [MASK] );
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream [MASK] ) throws IOException {
try ( [MASK] ) {
load( [MASK] );
}
}
private void load(InputStream [MASK] ) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = [MASK] .read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| inputStream |
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
*/
/*
* 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 com.sun.org.apache.xerces.internal.impl.xs;
import com.sun.org.apache.xerces.internal.impl.Constants;
import com.sun.org.apache.xerces.internal.impl.dv.SchemaDVFactory;
import com.sun.org.apache.xerces.internal.impl.dv.ValidatedInfo;
import com.sun.org.apache.xerces.internal.impl.dv.XSSimpleType;
import com.sun.org.apache.xerces.internal.impl.dv.xs.XSSimpleTypeDecl;
import com.sun.org.apache.xerces.internal.impl.xs.identity.IdentityConstraint;
import com.sun.org.apache.xerces.internal.impl.xs.util.ObjectListImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.SimpleLocator;
import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSNamedMap4Types;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSNamedMapImpl;
import com.sun.org.apache.xerces.internal.impl.xs.util.XSObjectListImpl;
import com.sun.org.apache.xerces.internal.parsers.DOMParser;
import com.sun.org.apache.xerces.internal.parsers.SAXParser;
import com.sun.org.apache.xerces.internal.parsers.XML11Configuration;
import com.sun.org.apache.xerces.internal.util.SymbolHash;
import com.sun.org.apache.xerces.internal.util.SymbolTable;
import com.sun.org.apache.xerces.internal.xni.NamespaceContext;
import com.sun.org.apache.xerces.internal.xni.grammars.XMLGrammarDescription;
import com.sun.org.apache.xerces.internal.xni.grammars.XSGrammar;
import com.sun.org.apache.xerces.internal.xs.StringList;
import com.sun.org.apache.xerces.internal.xs.XSAnnotation;
import com.sun.org.apache.xerces.internal.xs.XSAttributeDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSAttributeGroupDefinition;
import com.sun.org.apache.xerces.internal.xs.XSConstants;
import com.sun.org.apache.xerces.internal.xs.XSElementDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSIDCDefinition;
import com.sun.org.apache.xerces.internal.xs.XSModel;
import com.sun.org.apache.xerces.internal.xs.XSModelGroupDefinition;
import com.sun.org.apache.xerces.internal.xs.XSNamedMap;
import com.sun.org.apache.xerces.internal.xs.XSNamespaceItem;
import com.sun.org.apache.xerces.internal.xs.XSNotationDeclaration;
import com.sun.org.apache.xerces.internal.xs.XSObjectList;
import com.sun.org.apache.xerces.internal.xs.XSParticle;
import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
import com.sun.org.apache.xerces.internal.xs.XSWildcard;
import com.sun.org.apache.xerces.internal.xs.datatypes.ObjectList;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.xml.sax.SAXException;
/**
* This class is to hold all schema component declaration that are declared
* within one namespace.
*
* The Grammar class this class extends contains what little
* commonality there is between XML Schema and DTD grammars. It's
* useful to distinguish grammar objects from other kinds of object
* when they exist in pools or caches.
*
* @xerces.internal
*
* @author Sandy Gao, IBM
* @author Elena Litani, IBM
*
* @LastModified: Oct 2017
*/
public class SchemaGrammar implements XSGrammar, XSNamespaceItem {
// the target namespace of grammar
String fTargetNamespace;
// global decls: map from decl name to decl object
SymbolHash fGlobalAttrDecls;
SymbolHash fGlobalAttrGrpDecls;
SymbolHash fGlobalElemDecls;
SymbolHash fGlobalGroupDecls;
SymbolHash fGlobalNotationDecls;
SymbolHash fGlobalIDConstraintDecls;
SymbolHash fGlobalTypeDecls;
// extended global decls: map from schema location + decl name to decl object
// key is location,name
SymbolHash fGlobalAttrDeclsExt;
SymbolHash fGlobalAttrGrpDeclsExt;
SymbolHash fGlobalElemDeclsExt;
SymbolHash fGlobalGroupDeclsExt;
SymbolHash fGlobalNotationDeclsExt;
SymbolHash fGlobalIDConstraintDeclsExt;
SymbolHash fGlobalTypeDeclsExt;
// A global map of all global element declarations - used for substitution group computation
// (handy when sharing components by reference, since we might end up with duplicate components
// that are not added to either of the global element declarations above)
SymbolHash fAllGlobalElemDecls;
// the XMLGrammarDescription member
XSDDescription fGrammarDescription = null;
// annotations associated with the "root" schema of this targetNamespace
XSAnnotationImpl [] fAnnotations = null;
// number of annotations declared
int fNumAnnotations;
// symbol table for constructing parsers (annotation support)
private SymbolTable fSymbolTable = null;
// parsers for annotation support
private SoftReference<SAXParser> fSAXParser = null;
private SoftReference<DOMParser> fDOMParser = null;
// is this grammar immutable? (fully constructed and not changeable)
private boolean fIsImmutable = false;
//
// Constructors
//
// needed to make BuiltinSchemaGrammar work.
protected SchemaGrammar() {}
/**
* Default constructor.
*
* @param targetNamespace
* @param grammarDesc the XMLGrammarDescription corresponding to this object
* at the least a systemId should always be known.
* @param symbolTable needed for annotation support
*/
public SchemaGrammar(String targetNamespace, XSDDescription grammarDesc,
SymbolTable symbolTable) {
fTargetNamespace = targetNamespace;
fGrammarDescription = grammarDesc;
fSymbolTable = symbolTable;
// REVISIT: the initial sizes being chosen for each SymbolHash
// may not be ideal and could still be tuned. They were chosen
// somewhat arbitrarily to reduce the initial footprint of
// SymbolHash buckets from 1,515 to 177 (about 12% of the
// default size).
fGlobalAttrDecls = new SymbolHash(12);
fGlobalAttrGrpDecls = new SymbolHash(5);
fGlobalElemDecls = new SymbolHash(25);
fGlobalGroupDecls = new SymbolHash(5);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(3);
// Extended tables
fGlobalAttrDeclsExt = new SymbolHash(12);
fGlobalAttrGrpDeclsExt = new SymbolHash(5);
fGlobalElemDeclsExt = new SymbolHash(25);
fGlobalGroupDeclsExt = new SymbolHash(5);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(3);
fGlobalTypeDeclsExt = new SymbolHash(25);
// All global elements table
fAllGlobalElemDecls = new SymbolHash(25);
// if we are parsing S4S, put built-in types in first
// they might get overwritten by the types from S4S, but that's
// considered what the application wants to do.
if (fTargetNamespace == SchemaSymbols.URI_SCHEMAFORSCHEMA) {
fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls.makeClone();
}
else {
fGlobalTypeDecls = new SymbolHash(25);
}
} // <init>(String, XSDDescription)
// Clone an existing schema grammar
public SchemaGrammar(SchemaGrammar grammar) {
fTargetNamespace = grammar.fTargetNamespace;
fGrammarDescription = grammar.fGrammarDescription.makeClone();
//fGrammarDescription.fContextType |= XSDDescription.CONTEXT_COLLISION; // REVISIT
fSymbolTable = grammar.fSymbolTable; // REVISIT
fGlobalAttrDecls = grammar.fGlobalAttrDecls.makeClone();
fGlobalAttrGrpDecls = grammar.fGlobalAttrGrpDecls.makeClone();
fGlobalElemDecls = grammar.fGlobalElemDecls.makeClone();
fGlobalGroupDecls = grammar.fGlobalGroupDecls.makeClone();
fGlobalNotationDecls = grammar.fGlobalNotationDecls.makeClone();
fGlobalIDConstraintDecls = grammar.fGlobalIDConstraintDecls.makeClone();
fGlobalTypeDecls = grammar.fGlobalTypeDecls.makeClone();
// Extended tables
fGlobalAttrDeclsExt = grammar.fGlobalAttrDeclsExt.makeClone();
fGlobalAttrGrpDeclsExt = grammar.fGlobalAttrGrpDeclsExt.makeClone();
fGlobalElemDeclsExt = grammar.fGlobalElemDeclsExt.makeClone();
fGlobalGroupDeclsExt = grammar.fGlobalGroupDeclsExt.makeClone();
fGlobalNotationDeclsExt = grammar.fGlobalNotationDeclsExt.makeClone();
fGlobalIDConstraintDeclsExt = grammar.fGlobalIDConstraintDeclsExt.makeClone();
fGlobalTypeDeclsExt = grammar.fGlobalTypeDeclsExt.makeClone();
// All global elements table
fAllGlobalElemDecls = grammar.fAllGlobalElemDecls.makeClone();
// Annotations associated with the "root" schema of this targetNamespace
fNumAnnotations = grammar.fNumAnnotations;
if (fNumAnnotations > 0) {
fAnnotations = new XSAnnotationImpl[grammar.fAnnotations.length];
System.arraycopy(grammar.fAnnotations, 0, fAnnotations, 0, fNumAnnotations);
}
// All substitution group information declared in this namespace
fSubGroupCount = grammar.fSubGroupCount;
if (fSubGroupCount > 0) {
fSubGroups = new XSElementDecl[grammar.fSubGroups.length];
System.arraycopy(grammar.fSubGroups, 0, fSubGroups, 0, fSubGroupCount);
}
// Array to store complex type decls for constraint checking
fCTCount = grammar.fCTCount;
if (fCTCount > 0) {
fComplexTypeDecls = new XSComplexTypeDecl[grammar.fComplexTypeDecls.length];
fCTLocators = new SimpleLocator[grammar.fCTLocators.length];
System.arraycopy(grammar.fComplexTypeDecls, 0, fComplexTypeDecls, 0, fCTCount);
System.arraycopy(grammar.fCTLocators, 0, fCTLocators, 0, fCTCount);
}
// Groups being redefined by restriction
fRGCount = grammar.fRGCount;
if (fRGCount > 0) {
fRedefinedGroupDecls = new XSGroupDecl[grammar.fRedefinedGroupDecls.length];
fRGLocators = new SimpleLocator[grammar.fRGLocators.length];
System.arraycopy(grammar.fRedefinedGroupDecls, 0, fRedefinedGroupDecls, 0, fRGCount);
System.arraycopy(grammar.fRGLocators, 0, fRGLocators, 0, fRGCount/2);
}
// List of imported grammars
if (grammar.fImported != null) {
fImported = new ArrayList<>();
for (int i=0; i<grammar.fImported.size(); i++) {
fImported.add(grammar.fImported.get(i));
}
}
// Locations
if (grammar.fLocations != null) {
for (int k=0; k<grammar.fLocations.size(); k++) {
addDocument(null, grammar.fLocations.get(k));
}
}
} // <init>(String, XSDDescription)
// number of built-in XSTypes we need to create for base and full
// datatype set
private static final int BASICSET_COUNT = 29;
private static final int FULLSET_COUNT = 46;
private static final int GRAMMAR_XS = 1;
private static final int GRAMMAR_XSI = 2;
// this class makes sure the static, built-in schema grammars
// are immutable.
public static class BuiltinSchemaGrammar extends SchemaGrammar {
private static final String EXTENDED_SCHEMA_FACTORY_CLASS = "com.sun.org.apache.xerces.internal.impl.dv.xs.ExtendedSchemaDVFactoryImpl";
/**
* Special constructor to create the grammars for the schema namespaces
*
* @param grammar
*/
public BuiltinSchemaGrammar(int grammar, short schemaVersion) {
SchemaDVFactory schemaFactory;
if (schemaVersion == Constants.SCHEMA_VERSION_1_0) {
schemaFactory = SchemaDVFactory.getInstance();
}
else {
schemaFactory = SchemaDVFactory.getInstance(EXTENDED_SCHEMA_FACTORY_CLASS);
}
if (grammar == GRAMMAR_XS) {
// target namespace
fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA);
// no global decls other than types
fGlobalAttrDecls = new SymbolHash(1);
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(1);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(1);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// all global element decls table
fAllGlobalElemDecls = new SymbolHash(1);
// get all built-in types
fGlobalTypeDecls = schemaFactory.getBuiltInTypes();
// assign the built-in schema grammar as the XSNamespaceItem
// for each of the built-in simple type definitions.
int length = fGlobalTypeDecls.getLength();
XSTypeDefinition [] typeDefinitions = new XSTypeDefinition[length];
fGlobalTypeDecls.getValues(typeDefinitions, 0);
for (int i = 0; i < length; ++i) {
XSTypeDefinition xtd = typeDefinitions[i];
if (xtd instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) xtd).setNamespaceItem(this);
}
}
// add anyType
fGlobalTypeDecls.put(fAnyType.getName(), fAnyType);
}
else if (grammar == GRAMMAR_XSI) {
// target namespace
fTargetNamespace = SchemaSymbols.URI_XSI;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_XSI);
// no global decls other than attributes
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(1);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
fGlobalTypeDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(1);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// no all global element decls
fAllGlobalElemDecls = new SymbolHash(1);
// 4 attributes, so initialize the size as 4*2 = 8
fGlobalAttrDecls = new SymbolHash(8);
String name = null;
String tns = null;
XSSimpleType type = null;
short scope = XSConstants.SCOPE_GLOBAL;
// xsi:type
name = SchemaSymbols.XSI_TYPE;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_QNAME);
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
// xsi:nil
name = SchemaSymbols.XSI_NIL;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_BOOLEAN);
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
XSSimpleType anyURI = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_ANYURI);
// xsi:schemaLocation
name = SchemaSymbols.XSI_SCHEMALOCATION;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.createTypeList("#AnonType_schemaLocation", SchemaSymbols.URI_XSI, (short)0, anyURI, null);
if (type instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl)type).setAnonymous(true);
}
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
// xsi:noNamespaceSchemaLocation
name = SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION;
tns = SchemaSymbols.URI_XSI;
type = anyURI;
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
}
} // <init>(int)
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription.makeClone();
} // getGrammarDescription(): XMLGrammarDescription
// override these methods solely so that these
// objects cannot be modified once they're created.
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl, String location) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
// ignore
}
public void addGlobalElementDeclAll(XSElementDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
// ignore
}
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
// ignore
}
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
// ignore
}
public synchronized void addDocument(Object document, String location) {
// ignore
}
// annotation support
synchronized DOMParser getDOMParser() {
return null;
}
synchronized SAXParser getSAXParser() {
return null;
}
}
/**
* <p>A partial schema for schemas for validating annotations.</p>
*
* @xerces.internal
*
* @author Michael Glavassevich, IBM
*/
public static final class Schema4Annotations extends SchemaGrammar {
/**
* Singleton instance.
*/
public static final Schema4Annotations INSTANCE = new Schema4Annotations();
/**
* Special constructor to create a schema
* capable of validating annotations.
*/
private Schema4Annotations() {
// target namespace
fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA);
// no global decls other than types and
// element declarations for <annotation>, <documentation> and <appinfo>.
fGlobalAttrDecls = new SymbolHash(1);
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(6);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
// no extended global decls
fGlobalAttrDeclsExt = new SymbolHash(1);
fGlobalAttrGrpDeclsExt = new SymbolHash(1);
fGlobalElemDeclsExt = new SymbolHash(6);
fGlobalGroupDeclsExt = new SymbolHash(1);
fGlobalNotationDeclsExt = new SymbolHash(1);
fGlobalIDConstraintDeclsExt = new SymbolHash(1);
fGlobalTypeDeclsExt = new SymbolHash(1);
// all global element declarations
fAllGlobalElemDecls = new SymbolHash(6);
// get all built-in types
fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls;
// create element declarations for <annotation>, <documentation> and <appinfo>
XSElementDecl annotationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_ANNOTATION);
XSElementDecl documentationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_DOCUMENTATION);
XSElementDecl appinfoDecl = createAnnotationElementDecl(SchemaSymbols.ELT_APPINFO);
// add global element declarations
fGlobalElemDecls.put(annotationDecl.fName, annotationDecl);
fGlobalElemDecls.put(documentationDecl.fName, documentationDecl);
fGlobalElemDecls.put(appinfoDecl.fName, appinfoDecl);
fGlobalElemDeclsExt.put(","+annotationDecl.fName, annotationDecl);
fGlobalElemDeclsExt.put(","+documentationDecl.fName, documentationDecl);
fGlobalElemDeclsExt.put(","+appinfoDecl.fName, appinfoDecl);
fAllGlobalElemDecls.put(annotationDecl, annotationDecl);
fAllGlobalElemDecls.put(documentationDecl, documentationDecl);
fAllGlobalElemDecls.put(appinfoDecl, appinfoDecl);
// create complex type declarations for <annotation>, <documentation> and <appinfo>
XSComplexTypeDecl annotationType = new XSComplexTypeDecl();
XSComplexTypeDecl documentationType = new XSComplexTypeDecl();
XSComplexTypeDecl appinfoType = new XSComplexTypeDecl();
// set the types on their element declarations
annotationDecl.fType = annotationType;
documentationDecl.fType = documentationType;
appinfoDecl.fType = appinfoType;
// create attribute groups for <annotation>, <documentation> and <appinfo>
XSAttributeGroupDecl annotationAttrs = new XSAttributeGroupDecl();
XSAttributeGroupDecl documentationAttrs = new XSAttributeGroupDecl();
XSAttributeGroupDecl appinfoAttrs = new XSAttributeGroupDecl();
// fill in attribute groups
{
// create and fill attribute uses for <annotation>, <documentation> and <appinfo>
XSAttributeUseImpl annotationIDAttr = new XSAttributeUseImpl();
annotationIDAttr.fAttrDecl = new XSAttributeDecl();
annotationIDAttr.fAttrDecl.setValues(SchemaSymbols.ATT_ID, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ID),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, annotationType, null);
annotationIDAttr.fUse = SchemaSymbols.USE_OPTIONAL;
annotationIDAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl documentationSourceAttr = new XSAttributeUseImpl();
documentationSourceAttr.fAttrDecl = new XSAttributeDecl();
documentationSourceAttr.fAttrDecl.setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ANYURI),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, documentationType, null);
documentationSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL;
documentationSourceAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl documentationLangAttr = new XSAttributeUseImpl();
documentationLangAttr.fAttrDecl = new XSAttributeDecl();
documentationLangAttr.fAttrDecl.setValues("lang".intern(), NamespaceContext.XML_URI, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_LANGUAGE),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, documentationType, null);
documentationLangAttr.fUse = SchemaSymbols.USE_OPTIONAL;
documentationLangAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl appinfoSourceAttr = new XSAttributeUseImpl();
appinfoSourceAttr.fAttrDecl = new XSAttributeDecl();
appinfoSourceAttr.fAttrDecl.setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ANYURI),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, appinfoType, null);
appinfoSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL;
appinfoSourceAttr.fConstraintType = XSConstants.VC_NONE;
// create lax attribute wildcard for <annotation>, <documentation> and <appinfo>
XSWildcardDecl otherAttrs = new XSWildcardDecl();
otherAttrs.fNamespaceList = new String [] {fTargetNamespace, null};
otherAttrs.fType = XSWildcard.NSCONSTRAINT_NOT;
otherAttrs.fProcessContents = XSWildcard.PC_LAX;
// add attribute uses and wildcards to attribute groups for <annotation>, <documentation> and <appinfo>
annotationAttrs.addAttributeUse(annotationIDAttr);
annotationAttrs.fAttributeWC = otherAttrs;
documentationAttrs.addAttributeUse(documentationSourceAttr);
documentationAttrs.addAttributeUse(documentationLangAttr);
documentationAttrs.fAttributeWC = otherAttrs;
appinfoAttrs.addAttributeUse(appinfoSourceAttr);
appinfoAttrs.fAttributeWC = otherAttrs;
}
// create particles for <annotation>
XSParticleDecl annotationParticle = createUnboundedModelGroupParticle();
{
XSModelGroupImpl annotationChoice = new XSModelGroupImpl();
annotationChoice.fCompositor = XSModelGroupImpl.MODELGROUP_CHOICE;
annotationChoice.fParticleCount = 2;
annotationChoice.fParticles = new XSParticleDecl[2];
annotationChoice.fParticles[0] = createChoiceElementParticle(appinfoDecl);
annotationChoice.fParticles[1] = createChoiceElementParticle(documentationDecl);
annotationParticle.fValue = annotationChoice;
}
// create wildcard particle for <documentation> and <appinfo>
XSParticleDecl anyWCSequenceParticle = createUnboundedAnyWildcardSequenceParticle();
// fill complex types
annotationType.setValues("#AnonType_" + SchemaSymbols.ELT_ANNOTATION, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_ELEMENT, false, annotationAttrs, null, annotationParticle, XSObjectListImpl.EMPTY_LIST);
annotationType.setName("#AnonType_" + SchemaSymbols.ELT_ANNOTATION);
annotationType.setIsAnonymous();
documentationType.setValues("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_MIXED, false, documentationAttrs, null, anyWCSequenceParticle, XSObjectListImpl.EMPTY_LIST);
documentationType.setName("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION);
documentationType.setIsAnonymous();
appinfoType.setValues("#AnonType_" + SchemaSymbols.ELT_APPINFO, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_MIXED, false, appinfoAttrs, null, anyWCSequenceParticle, XSObjectListImpl.EMPTY_LIST);
appinfoType.setName("#AnonType_" + SchemaSymbols.ELT_APPINFO);
appinfoType.setIsAnonymous();
} // <init>(int)
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription.makeClone();
} // getGrammarDescription(): XMLGrammarDescription
// override these methods solely so that these
// objects cannot be modified once they're created.
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
// ignore
}
public void addGlobalElementDeclAll(XSElementDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
// ignore
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
// ignore
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
// ignore
}
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
// ignore
}
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
// ignore
}
public synchronized void addDocument(Object document, String location) {
// ignore
}
// annotation support
synchronized DOMParser getDOMParser() {
return null;
}
synchronized SAXParser getSAXParser() {
return null;
}
//
// private helper methods
//
private XSElementDecl createAnnotationElementDecl(String localName) {
XSElementDecl eDecl = new XSElementDecl();
eDecl.fName = localName;
eDecl.fTargetNamespace = fTargetNamespace;
eDecl.setIsGlobal();
eDecl.fBlock = (XSConstants.DERIVATION_EXTENSION |
XSConstants.DERIVATION_RESTRICTION | XSConstants.DERIVATION_SUBSTITUTION);
eDecl.setConstraintType(XSConstants.VC_NONE);
return eDecl;
}
private XSParticleDecl createUnboundedModelGroupParticle() {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 0;
particle.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED;
particle.fType = XSParticleDecl.PARTICLE_MODELGROUP;
return particle;
}
private XSParticleDecl createChoiceElementParticle(XSElementDecl ref) {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 1;
particle.fMaxOccurs = 1;
particle.fType = XSParticleDecl.PARTICLE_ELEMENT;
particle.fValue = ref;
return particle;
}
private XSParticleDecl createUnboundedAnyWildcardSequenceParticle() {
XSParticleDecl particle = createUnboundedModelGroupParticle();
XSModelGroupImpl sequence = new XSModelGroupImpl();
sequence.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE;
sequence.fParticleCount = 1;
sequence.fParticles = new XSParticleDecl[1];
sequence.fParticles[0] = createAnyLaxWildcardParticle();
particle.fValue = sequence;
return particle;
}
private XSParticleDecl createAnyLaxWildcardParticle() {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 1;
particle.fMaxOccurs = 1;
particle.fType = XSParticleDecl.PARTICLE_WILDCARD;
XSWildcardDecl anyWC = new XSWildcardDecl();
anyWC.fNamespaceList = null;
anyWC.fType = XSWildcard.NSCONSTRAINT_ANY;
anyWC.fProcessContents = XSWildcard.PC_LAX;
particle.fValue = anyWC;
return particle;
}
}
// Grammar methods
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription;
} // getGrammarDescription(): XMLGrammarDescription
// DTDGrammar methods
public boolean isNamespaceAware () {
return true;
} // isNamespaceAware():boolean
List<SchemaGrammar> fImported = null;
public void setImportedGrammars(List<SchemaGrammar> importedGrammars) {
fImported = importedGrammars;
}
public List<SchemaGrammar> getImportedGrammars() {
return fImported;
}
/**
* Returns this grammar's target namespace.
*/
public final String getTargetNamespace() {
return fTargetNamespace;
} // getTargetNamespace():String
/**
* register one global attribute
*/
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
fGlobalAttrDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalAttributeDecl(XSAttributeDecl decl, String location) {
fGlobalAttrDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global attribute group
*/
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
fGlobalAttrGrpDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl, String location) {
fGlobalAttrGrpDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global element
*/
public void addGlobalElementDeclAll(XSElementDecl decl) {
if (fAllGlobalElemDecls.get(decl) == null) {
fAllGlobalElemDecls.put(decl, decl);
// if there is a substitution group affiliation, store in an array,
// for further constraint checking: UPA, PD, EDC
if (decl.fSubGroup != null) {
if (fSubGroupCount == fSubGroups.length)
fSubGroups = resize(fSubGroups, fSubGroupCount+INC_SIZE);
fSubGroups[fSubGroupCount++] = decl;
}
}
}
public void addGlobalElementDecl(XSElementDecl decl) {
fGlobalElemDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalElementDecl(XSElementDecl decl, String location) {
fGlobalElemDeclsExt.put(((location != null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global group
*/
public void addGlobalGroupDecl(XSGroupDecl decl) {
fGlobalGroupDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalGroupDecl(XSGroupDecl decl, String location) {
fGlobalGroupDeclsExt.put(((location!=null) ? location : "") + "," + decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global notation
*/
public void addGlobalNotationDecl(XSNotationDecl decl) {
fGlobalNotationDecls.put(decl.fName, decl);
decl.setNamespaceItem(this);
}
public void addGlobalNotationDecl(XSNotationDecl decl, String location) {
fGlobalNotationDeclsExt.put(((location!=null) ? location : "") + "," +decl.fName, decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global type
*/
public void addGlobalTypeDecl(XSTypeDefinition decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
if (decl instanceof XSComplexTypeDecl) {
((XSComplexTypeDecl) decl).setNamespaceItem(this);
}
else if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
public void addGlobalTypeDecl(XSTypeDefinition decl, String location) {
fGlobalTypeDeclsExt.put(((location!=null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null) {
if (decl instanceof XSComplexTypeDecl) {
((XSComplexTypeDecl) decl).setNamespaceItem(this);
}
else if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
}
/**
* register one global complex type
*/
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
decl.setNamespaceItem(this);
}
public void addGlobalComplexTypeDecl(XSComplexTypeDecl decl, String location) {
fGlobalTypeDeclsExt.put(((location!=null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null) {
decl.setNamespaceItem(this);
}
}
/**
* register one global simple type
*/
public void addGlobalSimpleTypeDecl(XSSimpleType decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
if (decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
public void addGlobalSimpleTypeDecl(XSSimpleType decl, String location) {
fGlobalTypeDeclsExt.put(((location != null) ? location : "") + "," + decl.getName(), decl);
if (decl.getNamespaceItem() == null && decl instanceof XSSimpleTypeDecl) {
((XSSimpleTypeDecl) decl).setNamespaceItem(this);
}
}
/**
* register one identity constraint
*/
public final void addIDConstraintDecl(XSElementDecl elmDecl, IdentityConstraint decl) {
elmDecl.addIDConstraint(decl);
fGlobalIDConstraintDecls.put(decl.getIdentityConstraintName(), decl);
}
public final void addIDConstraintDecl(XSElementDecl elmDecl, IdentityConstraint decl, String location) {
fGlobalIDConstraintDeclsExt.put(((location != null) ? location : "") + "," + decl.getIdentityConstraintName(), decl);
}
/**
* get one global attribute
*/
public final XSAttributeDecl getGlobalAttributeDecl(String declName) {
return(XSAttributeDecl)fGlobalAttrDecls.get(declName);
}
public final XSAttributeDecl getGlobalAttributeDecl(String declName, String location) {
return(XSAttributeDecl)fGlobalAttrDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global attribute group
*/
public final XSAttributeGroupDecl getGlobalAttributeGroupDecl(String declName) {
return(XSAttributeGroupDecl)fGlobalAttrGrpDecls.get(declName);
}
public final XSAttributeGroupDecl getGlobalAttributeGroupDecl(String declName, String location) {
return(XSAttributeGroupDecl)fGlobalAttrGrpDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global element
*/
public final XSElementDecl getGlobalElementDecl(String declName) {
return(XSElementDecl)fGlobalElemDecls.get(declName);
}
public final XSElementDecl getGlobalElementDecl(String declName, String location) {
return(XSElementDecl)fGlobalElemDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global group
*/
public final XSGroupDecl getGlobalGroupDecl(String declName) {
return(XSGroupDecl)fGlobalGroupDecls.get(declName);
}
public final XSGroupDecl getGlobalGroupDecl(String declName, String location) {
return(XSGroupDecl)fGlobalGroupDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global notation
*/
public final XSNotationDecl getGlobalNotationDecl(String declName) {
return(XSNotationDecl)fGlobalNotationDecls.get(declName);
}
public final XSNotationDecl getGlobalNotationDecl(String declName, String location) {
return(XSNotationDecl)fGlobalNotationDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one global type
*/
public final XSTypeDefinition getGlobalTypeDecl(String declName) {
return(XSTypeDefinition)fGlobalTypeDecls.get(declName);
}
public final XSTypeDefinition getGlobalTypeDecl(String declName, String location) {
return(XSTypeDefinition)fGlobalTypeDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one identity constraint
*/
public final IdentityConstraint getIDConstraintDecl(String declName) {
return(IdentityConstraint)fGlobalIDConstraintDecls.get(declName);
}
public final IdentityConstraint getIDConstraintDecl(String declName, String location) {
return(IdentityConstraint)fGlobalIDConstraintDeclsExt.get(((location != null) ? location : "") + "," + declName);
}
/**
* get one identity constraint
*/
public final boolean hasIDConstraints() {
return fGlobalIDConstraintDecls.getLength() > 0;
}
// array to store complex type decls
private static final int INITIAL_SIZE = 16;
private static final int INC_SIZE = 16;
private int fCTCount = 0;
private XSComplexTypeDecl[] fComplexTypeDecls = new XSComplexTypeDecl[INITIAL_SIZE];
private SimpleLocator[] fCTLocators = new SimpleLocator[INITIAL_SIZE];
// an array to store groups being redefined by restriction
// even-numbered elements are the derived groups, odd-numbered ones their bases
private static final int REDEFINED_GROUP_INIT_SIZE = 2;
private int fRGCount = 0;
private XSGroupDecl[] fRedefinedGroupDecls = new XSGroupDecl[REDEFINED_GROUP_INIT_SIZE];
private SimpleLocator[] fRGLocators = new SimpleLocator[REDEFINED_GROUP_INIT_SIZE/2];
// a flag to indicate whether we have checked the 3 constraints on this
// grammar.
boolean fFullChecked = false;
/**
* add one complex type decl: for later constraint checking
*/
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
if (fCTCount == fComplexTypeDecls.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount+INC_SIZE);
fCTLocators = resize(fCTLocators, fCTCount+INC_SIZE);
}
fCTLocators[fCTCount] = locator;
fComplexTypeDecls[fCTCount++] = decl;
}
/**
* add a group redefined by restriction: for later constraint checking
*/
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
if (fRGCount == fRedefinedGroupDecls.length) {
// double array size each time.
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount << 1);
fRGLocators = resize(fRGLocators, fRGCount);
}
fRGLocators[fRGCount/2] = locator;
fRedefinedGroupDecls[fRGCount++] = derived;
fRedefinedGroupDecls[fRGCount++] = base;
}
/**
* get all complex type decls: for later constraint checking
*/
final XSComplexTypeDecl[] getUncheckedComplexTypeDecls() {
if (fCTCount < fComplexTypeDecls.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
return fComplexTypeDecls;
}
/**
* get the error locator of all complex type decls
*/
final SimpleLocator[] getUncheckedCTLocators() {
if (fCTCount < fCTLocators.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
return fCTLocators;
}
/**
* get all redefined groups: for later constraint checking
*/
final XSGroupDecl[] getRedefinedGroupDecls() {
if (fRGCount < fRedefinedGroupDecls.length) {
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount);
fRGLocators = resize(fRGLocators, fRGCount/2);
}
return fRedefinedGroupDecls;
}
/**
* get the error locator of all redefined groups
*/
final SimpleLocator[] getRGLocators() {
if (fRGCount < fRedefinedGroupDecls.length) {
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount);
fRGLocators = resize(fRGLocators, fRGCount/2);
}
return fRGLocators;
}
/**
* after the first-round checking, some types don't need to be checked
* against UPA again. here we trim the array to the proper size.
*/
final void setUncheckedTypeNum(int newSize) {
fCTCount = newSize;
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
// used to store all substitution group information declared in
// this namespace
private int fSubGroupCount = 0;
private XSElementDecl[] fSubGroups = new XSElementDecl[INITIAL_SIZE];
/**
* get all substitution group information: for the 3 constraint checking
*/
final XSElementDecl[] getSubstitutionGroups() {
if (fSubGroupCount < fSubGroups.length)
fSubGroups = resize(fSubGroups, fSubGroupCount);
return fSubGroups;
}
// anyType and anySimpleType: because there are so many places where
// we need direct access to these two types
public final static XSComplexTypeDecl fAnyType = new XSAnyType();
private static class XSAnyType extends XSComplexTypeDecl {
public XSAnyType () {
fName = SchemaSymbols.ATTVAL_ANYTYPE;
super.fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
fBaseType = this;
fDerivedBy = XSConstants.DERIVATION_RESTRICTION;
fContentType = XSComplexTypeDecl.CONTENTTYPE_MIXED;
fParticle = createParticle();
fAttrGrp = createAttrGrp();
}
// overridden methods
public void setValues(String name, String targetNamespace,
XSTypeDefinition baseType, short derivedBy, short schemaFinal,
short block, short contentType,
boolean isAbstract, XSAttributeGroupDecl attrGrp,
XSSimpleType simpleType, XSParticleDecl particle) {
// don't allow this.
}
public void setName(String name){
// don't allow this.
}
public void setIsAbstractType() {
// null implementation
}
public void setContainsTypeID() {
// null implementation
}
public void setIsAnonymous() {
// null implementation
}
public void reset() {
// null implementation
}
public XSObjectList getAnnotations() {
return XSObjectListImpl.EMPTY_LIST;
}
public XSNamespaceItem getNamespaceItem() {
return SG_SchemaNS;
}
private XSAttributeGroupDecl createAttrGrp() {
XSWildcardDecl wildcard = new XSWildcardDecl();
wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
XSAttributeGroupDecl attrGrp = new XSAttributeGroupDecl();
attrGrp.fAttributeWC = wildcard;
return attrGrp;
}
private XSParticleDecl createParticle() {
// the wildcard used in anyType (content and attribute)
// the spec will change strict to skip for anyType
XSWildcardDecl wildcard = new XSWildcardDecl();
wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
// the particle for the content wildcard
XSParticleDecl particleW = new XSParticleDecl();
particleW.fMinOccurs = 0;
particleW.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED;
particleW.fType = XSParticleDecl.PARTICLE_WILDCARD;
particleW.fValue = wildcard;
// the model group of a sequence of the above particle
XSModelGroupImpl group = new XSModelGroupImpl();
group.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE;
group.fParticleCount = 1;
group.fParticles = new XSParticleDecl[1];
group.fParticles[0] = particleW;
// the content of anyType: particle of the above model group
XSParticleDecl particleG = new XSParticleDecl();
particleG.fType = XSParticleDecl.PARTICLE_MODELGROUP;
particleG.fValue = group;
return particleG;
}
}
private static class BuiltinAttrDecl extends XSAttributeDecl {
public BuiltinAttrDecl(String name, String tns,
XSSimpleType type, short scope) {
fName = name;
super.fTargetNamespace = tns;
fType = type;
fScope = scope;
}
public void setValues(String name, String targetNamespace,
XSSimpleType simpleType, short constraintType, short scope,
ValidatedInfo valInfo, XSComplexTypeDecl enclosingCT) {
// ignore this call.
}
public void reset () {
// also ignore this call.
}
public XSAnnotation getAnnotation() {
return null;
}
public XSNamespaceItem getNamespaceItem() {
return SG_XSI;
}
} // class BuiltinAttrDecl
// the grammars to hold components of the schema namespace
public final static BuiltinSchemaGrammar SG_SchemaNS = new BuiltinSchemaGrammar(GRAMMAR_XS, Constants.SCHEMA_VERSION_1_0);
private final static BuiltinSchemaGrammar SG_SchemaNSExtended = new BuiltinSchemaGrammar(GRAMMAR_XS, Constants.SCHEMA_VERSION_1_0_EXTENDED);
public final static XSSimpleType fAnySimpleType = (XSSimpleType)SG_SchemaNS.getGlobalTypeDecl(SchemaSymbols.ATTVAL_ANYSIMPLETYPE);
// the grammars to hold components of the schema-instance namespace
public final static BuiltinSchemaGrammar SG_XSI = new BuiltinSchemaGrammar(GRAMMAR_XSI, Constants.SCHEMA_VERSION_1_0);
public static SchemaGrammar getS4SGrammar(short schemaVersion) {
if (schemaVersion == Constants.SCHEMA_VERSION_1_0) {
return SG_SchemaNS;
}
else {
return SG_SchemaNSExtended;
}
}
static final XSComplexTypeDecl[] resize(XSComplexTypeDecl[] oldArray, int newSize) {
XSComplexTypeDecl[] newArray = new XSComplexTypeDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final XSGroupDecl[] resize(XSGroupDecl[] oldArray, int newSize) {
XSGroupDecl[] newArray = new XSGroupDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final XSElementDecl[] resize(XSElementDecl[] oldArray, int newSize) {
XSElementDecl[] newArray = new XSElementDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final SimpleLocator[] resize(SimpleLocator[] oldArray, int newSize) {
SimpleLocator[] newArray = new SimpleLocator[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
// XSNamespaceItem methods
// the max index / the max value of XSObject type
private static final short MAX_COMP_IDX = XSTypeDefinition.SIMPLE_TYPE;
private static final boolean[] GLOBAL_COMP = {false, // null
true, // attribute
true, // element
true, // type
false, // attribute use
true, // attribute group
true, // group
false, // model group
false, // particle
false, // wildcard
true, // idc
true, // notation
false, // annotation
false, // facet
false, // multi value facet
true, // complex type
true // simple type
};
// store a certain kind of components from all namespaces
private XSNamedMap[] fComponents = null;
private ObjectList[] [MASK] = null;
// store the documents and their locations contributing to this namespace
// REVISIT: use StringList and XSObjectList for there fields.
// fDocuments is never used
private List<Object> fDocuments = null;
private List<String> fLocations = null;
public synchronized void addDocument(Object document, String location) {
if (fDocuments == null) {
// Parsing schema is not thread safe, synchronized may be removed
fDocuments = new CopyOnWriteArrayList<>();
fLocations = new CopyOnWriteArrayList<>();
}
fDocuments.add(document);
fLocations.add(location);
}
public synchronized void removeDocument(int index) {
if (fDocuments != null &&
index >= 0 &&
index < fDocuments.size()) {
fDocuments.remove(index);
fLocations.remove(index);
}
}
/**
* [schema namespace]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#nsi-schema_namespace">[schema namespace]</a>
* @return The target namespace of this item.
*/
public String getSchemaNamespace() {
return fTargetNamespace;
}
// annotation support
synchronized DOMParser getDOMParser() {
if (fDOMParser != null) {
DOMParser parser = fDOMParser.get();
if (parser != null) {
return parser;
}
}
// REVISIT: when schema handles XML 1.1, will need to
// revisit this (and the practice of not prepending an XML decl to the annotation string
XML11Configuration config = new XML11Configuration(fSymbolTable);
// note that this should never produce errors or require
// entity resolution, so just a barebones configuration with
// a couple of feature set will do fine
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true);
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false);
DOMParser parser = new DOMParser(config);
try {
parser.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.DEFER_NODE_EXPANSION_FEATURE, false);
}
catch (SAXException exc) {}
fDOMParser = new SoftReference<DOMParser>(parser);
return parser;
}
synchronized SAXParser getSAXParser() {
if (fSAXParser != null) {
SAXParser parser = fSAXParser.get();
if (parser != null) {
return parser;
}
}
// REVISIT: when schema handles XML 1.1, will need to
// revisit this (and the practice of not prepending an XML decl to the annotation string
XML11Configuration config = new XML11Configuration(fSymbolTable);
// note that this should never produce errors or require
// entity resolution, so just a barebones configuration with
// a couple of feature set will do fine
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true);
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false);
SAXParser parser = new SAXParser(config);
fSAXParser = new SoftReference<SAXParser>(parser);
return parser;
}
/**
* [schema components]: a list of top-level components, i.e. element
* declarations, attribute declarations, etc.
* @param objectType The type of the declaration, i.e.
* <code>ELEMENT_DECLARATION</code>. Note that
* <code>XSTypeDefinition.SIMPLE_TYPE</code> and
* <code>XSTypeDefinition.COMPLEX_TYPE</code> can also be used as the
* <code>objectType</code> to retrieve only complex types or simple
* types, instead of all types.
* @return A list of top-level definition of the specified type in
* <code>objectType</code> or an empty <code>XSNamedMap</code> if no
* such definitions exist.
*/
public synchronized XSNamedMap getComponents(short objectType) {
if (objectType <= 0 || objectType > MAX_COMP_IDX ||
!GLOBAL_COMP[objectType]) {
return XSNamedMapImpl.EMPTY_MAP;
}
if (fComponents == null)
fComponents = new XSNamedMap[MAX_COMP_IDX+1];
// get the hashtable for this type of components
if (fComponents[objectType] == null) {
SymbolHash table = null;
switch (objectType) {
case XSConstants.TYPE_DEFINITION:
case XSTypeDefinition.COMPLEX_TYPE:
case XSTypeDefinition.SIMPLE_TYPE:
table = fGlobalTypeDecls;
break;
case XSConstants.ATTRIBUTE_DECLARATION:
table = fGlobalAttrDecls;
break;
case XSConstants.ELEMENT_DECLARATION:
table = fGlobalElemDecls;
break;
case XSConstants.ATTRIBUTE_GROUP:
table = fGlobalAttrGrpDecls;
break;
case XSConstants.MODEL_GROUP_DEFINITION:
table = fGlobalGroupDecls;
break;
case XSConstants.NOTATION_DECLARATION:
table = fGlobalNotationDecls;
break;
case XSConstants.IDENTITY_CONSTRAINT:
table = this.fGlobalIDConstraintDecls;
break;
}
// for complex/simple types, create a special implementation,
// which take specific types out of the hash table
if (objectType == XSTypeDefinition.COMPLEX_TYPE ||
objectType == XSTypeDefinition.SIMPLE_TYPE) {
fComponents[objectType] = new XSNamedMap4Types(fTargetNamespace, table, objectType);
}
else {
fComponents[objectType] = new XSNamedMapImpl(fTargetNamespace, table);
}
}
return fComponents[objectType];
}
public synchronized ObjectList getComponentsExt(short objectType) {
if (objectType <= 0 || objectType > MAX_COMP_IDX ||
!GLOBAL_COMP[objectType]) {
return ObjectListImpl.EMPTY_LIST;
}
if ( [MASK] == null)
[MASK] = new ObjectList[MAX_COMP_IDX+1];
// get the hashtable for this type of components
if ( [MASK] [objectType] == null) {
SymbolHash table = null;
switch (objectType) {
case XSConstants.TYPE_DEFINITION:
case XSTypeDefinition.COMPLEX_TYPE:
case XSTypeDefinition.SIMPLE_TYPE:
table = fGlobalTypeDeclsExt;
break;
case XSConstants.ATTRIBUTE_DECLARATION:
table = fGlobalAttrDeclsExt;
break;
case XSConstants.ELEMENT_DECLARATION:
table = fGlobalElemDeclsExt;
break;
case XSConstants.ATTRIBUTE_GROUP:
table = fGlobalAttrGrpDeclsExt;
break;
case XSConstants.MODEL_GROUP_DEFINITION:
table = fGlobalGroupDeclsExt;
break;
case XSConstants.NOTATION_DECLARATION:
table = fGlobalNotationDeclsExt;
break;
case XSConstants.IDENTITY_CONSTRAINT:
table = this.fGlobalIDConstraintDeclsExt;
break;
}
Object[] entries = table.getEntries();
[MASK] [objectType] = new ObjectListImpl(entries, entries.length);
}
return [MASK] [objectType];
}
public synchronized void resetComponents() {
fComponents = null;
[MASK] = null;
}
/**
* Convenience method. Returns a top-level simple or complex type
* definition.
* @param name The name of the definition.
* @return An <code>XSTypeDefinition</code> or null if such definition
* does not exist.
*/
public XSTypeDefinition getTypeDefinition(String name) {
return getGlobalTypeDecl(name);
}
/**
* Convenience method. Returns a top-level attribute declaration.
* @param name The name of the declaration.
* @return A top-level attribute declaration or null if such declaration
* does not exist.
*/
public XSAttributeDeclaration getAttributeDeclaration(String name) {
return getGlobalAttributeDecl(name);
}
/**
* Convenience method. Returns a top-level element declaration.
* @param name The name of the declaration.
* @return A top-level element declaration or null if such declaration
* does not exist.
*/
public XSElementDeclaration getElementDeclaration(String name) {
return getGlobalElementDecl(name);
}
/**
* Convenience method. Returns a top-level attribute group definition.
* @param name The name of the definition.
* @return A top-level attribute group definition or null if such
* definition does not exist.
*/
public XSAttributeGroupDefinition getAttributeGroup(String name) {
return getGlobalAttributeGroupDecl(name);
}
/**
* Convenience method. Returns a top-level model group definition.
*
* @param name The name of the definition.
* @return A top-level model group definition definition or null if such
* definition does not exist.
*/
public XSModelGroupDefinition getModelGroupDefinition(String name) {
return getGlobalGroupDecl(name);
}
/**
* Convenience method. Returns a top-level notation declaration.
*
* @param name The name of the declaration.
* @return A top-level notation declaration or null if such declaration
* does not exist.
*/
public XSNotationDeclaration getNotationDeclaration(String name) {
return getGlobalNotationDecl(name);
}
public XSIDCDefinition getIDCDefinition(String name) {
return getIDConstraintDecl(name);
}
/**
* [document location]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#sd-document_location">[document location]</a>
* @return a list of document information item
*/
public StringList getDocumentLocations() {
return new StringListImpl(fLocations);
}
/**
* Return an <code>XSModel</code> that represents components in this schema
* grammar.
*
* @return an <code>XSModel</code> representing this schema grammar
*/
public XSModel toXSModel() {
return new XSModelImpl(new SchemaGrammar[]{this});
}
public XSModel toXSModel(XSGrammar[] grammars) {
if (grammars == null || grammars.length == 0)
return toXSModel();
int len = grammars.length;
boolean hasSelf = false;
for (int i = 0; i < len; i++) {
if (grammars[i] == this) {
hasSelf = true;
break;
}
}
SchemaGrammar[] gs = new SchemaGrammar[hasSelf ? len : len+1];
for (int i = 0; i < len; i++)
gs[i] = (SchemaGrammar)grammars[i];
if (!hasSelf)
gs[len] = this;
return new XSModelImpl(gs);
}
/**
* @see org.apache.xerces.xs.XSNamespaceItem#getAnnotations()
*/
public XSObjectList getAnnotations() {
if (fNumAnnotations == 0) {
return XSObjectListImpl.EMPTY_LIST;
}
return new XSObjectListImpl(fAnnotations, fNumAnnotations);
}
public void addAnnotation(XSAnnotationImpl annotation) {
if (annotation == null) {
return;
}
if (fAnnotations == null) {
fAnnotations = new XSAnnotationImpl[2];
}
else if (fNumAnnotations == fAnnotations.length) {
XSAnnotationImpl[] newArray = new XSAnnotationImpl[fNumAnnotations << 1];
System.arraycopy(fAnnotations, 0, newArray, 0, fNumAnnotations);
fAnnotations = newArray;
}
fAnnotations[fNumAnnotations++] = annotation;
}
public void setImmutable(boolean isImmutable) {
fIsImmutable = isImmutable;
}
public boolean isImmutable() {
return fIsImmutable;
}
} // class SchemaGrammar
| fComponentsExt |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
[MASK] (details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
[MASK] (library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void [MASK] (FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
[MASK] (details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void [MASK] (InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| prepareStoredEntry |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int [MASK] ;
while (( [MASK] = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, [MASK] );
this.size += [MASK] ;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| bytesRead |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools. [MASK] ;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final [MASK] layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new [MASK] (BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
write [MASK] IfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void write [MASK] IfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| LayersIndex |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot. [MASK] .tools.DefaultLaunchScript;
import org.springframework.boot. [MASK] .tools.FileUtils;
import org.springframework.boot. [MASK] .tools.JarModeLibrary;
import org.springframework.boot. [MASK] .tools.Layer;
import org.springframework.boot. [MASK] .tools.LayersIndex;
import org.springframework.boot. [MASK] .tools.LibraryCoordinates;
import org.springframework.boot. [MASK] .tools.LoaderImplementation;
import org.springframework.boot. [MASK] .tools.NativeImageArgFile;
import org.springframework.boot. [MASK] .tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's [MASK] .
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation [MASK] Implementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation [MASK] Implementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this. [MASK] Implementation = [MASK] Implementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write [MASK] entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries [MASK] Entries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this. [MASK] Implementation);
this.writtenLoaderEntries = [MASK] Entries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| loader |
/**
* Copyright © 2016-2024 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thingsboard.server.service.sync.ie.importing.impl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.NotificationTargetId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data. [MASK] .targets.NotificationTarget;
import org.thingsboard.server.common.data. [MASK] .targets.NotificationTargetType;
import org.thingsboard.server.common.data. [MASK] .targets.platform.CustomerUsersFilter;
import org.thingsboard.server.common.data. [MASK] .targets.platform.PlatformUsersNotificationTargetConfig;
import org.thingsboard.server.common.data. [MASK] .targets.platform.TenantAdministratorsFilter;
import org.thingsboard.server.common.data. [MASK] .targets.platform.UserListFilter;
import org.thingsboard.server.common.data. [MASK] .targets.platform.UsersFilter;
import org.thingsboard.server.common.data.sync.ie.EntityExportData;
import org.thingsboard.server.dao. [MASK] .NotificationTargetService;
import org.thingsboard.server.dao.service.ConstraintValidator;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.sync.vc.data.EntitiesImportCtx;
import java.util.List;
@Service
@TbCoreComponent
@RequiredArgsConstructor
public class NotificationTargetImportService extends BaseEntityImportService<NotificationTargetId, NotificationTarget, EntityExportData<NotificationTarget>> {
private final NotificationTargetService [MASK] TargetService;
@Override
protected void setOwner(TenantId tenantId, NotificationTarget [MASK] Target, IdProvider idProvider) {
[MASK] Target.setTenantId(tenantId);
}
@Override
protected NotificationTarget prepare(EntitiesImportCtx ctx, NotificationTarget [MASK] Target, NotificationTarget oldNotificationTarget, EntityExportData<NotificationTarget> exportData, IdProvider idProvider) {
if ( [MASK] Target.getConfiguration().getType() == NotificationTargetType.PLATFORM_USERS) {
UsersFilter usersFilter = ((PlatformUsersNotificationTargetConfig) [MASK] Target.getConfiguration()).getUsersFilter();
switch (usersFilter.getType()) {
case CUSTOMER_USERS:
CustomerUsersFilter customerUsersFilter = (CustomerUsersFilter) usersFilter;
customerUsersFilter.setCustomerId(idProvider.getInternalId(new CustomerId(customerUsersFilter.getCustomerId())).getId());
break;
case USER_LIST:
UserListFilter userListFilter = (UserListFilter) usersFilter;
userListFilter.setUsersIds(List.of(ctx.getUser().getUuidId())); // user entities are not supported by VC; replacing with current user id
break;
case TENANT_ADMINISTRATORS:
if (CollectionUtils.isNotEmpty(((TenantAdministratorsFilter) usersFilter).getTenantsIds()) ||
CollectionUtils.isNotEmpty(((TenantAdministratorsFilter) usersFilter).getTenantProfilesIds())) {
throw new IllegalArgumentException("Permission denied");
}
break;
case SYSTEM_ADMINISTRATORS:
throw new AccessDeniedException("Permission denied");
}
}
return [MASK] Target;
}
@Override
protected NotificationTarget saveOrUpdate(EntitiesImportCtx ctx, NotificationTarget [MASK] Target, EntityExportData<NotificationTarget> exportData, IdProvider idProvider) {
ConstraintValidator.validateFields( [MASK] Target);
return [MASK] TargetService.saveNotificationTarget(ctx.getTenantId(), [MASK] Target);
}
@Override
protected void onEntitySaved(User user, NotificationTarget savedEntity, NotificationTarget oldEntity) throws ThingsboardException {
entityActionService.logEntityAction(user, savedEntity.getId(), savedEntity, null,
oldEntity == null ? ActionType.ADDED : ActionType.UPDATED, null);
}
@Override
protected NotificationTarget deepCopy(NotificationTarget [MASK] Target) {
return new NotificationTarget( [MASK] Target);
}
@Override
public EntityType getEntityType() {
return EntityType.NOTIFICATION_TARGET;
}
}
| notification |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class [MASK] implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
[MASK] (File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = ( [MASK] .this.layerResolver != null)
? new LayersIndex( [MASK] .this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + [MASK] .this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return [MASK] .this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = [MASK] .this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if ( [MASK] .this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if ( [MASK] .this.layerResolver != null) {
Layer layer = [MASK] .this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (! [MASK] .this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
[MASK] .this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if ( [MASK] .this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = [MASK] .this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if ( [MASK] .this.jarmodeToolsLocation != null) {
writeJarModeLibrary( [MASK] .this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if ( [MASK] .this.layerResolver != null) {
Layer layer = [MASK] .this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if ( [MASK] .this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = [MASK] .this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines( [MASK] .this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = [MASK] .this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines( [MASK] .this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if ( [MASK] .this.layerResolver != null) {
Attributes manifestAttributes = [MASK] .this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = [MASK] .this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && [MASK] .this.layerResolver != null) {
Layer layer = [MASK] .this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if ( [MASK] .this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (! [MASK] .this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return ( [MASK] .this.dirMode != null) ? [MASK] .this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return ( [MASK] .this.fileMode != null) ? [MASK] .this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return ( [MASK] .this.fileMode != null) ? [MASK] .this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| BootZipCopyAction |
/**
* Copyright © 2016-2024 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org. [MASK] .server.service.sync.ie.importing.impl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import org. [MASK] .server.common.data.EntityType;
import org. [MASK] .server.common.data.User;
import org. [MASK] .server.common.data.audit.ActionType;
import org. [MASK] .server.common.data.exception.ThingsboardException;
import org. [MASK] .server.common.data.id.CustomerId;
import org. [MASK] .server.common.data.id.NotificationTargetId;
import org. [MASK] .server.common.data.id.TenantId;
import org. [MASK] .server.common.data.notification.targets.NotificationTarget;
import org. [MASK] .server.common.data.notification.targets.NotificationTargetType;
import org. [MASK] .server.common.data.notification.targets.platform.CustomerUsersFilter;
import org. [MASK] .server.common.data.notification.targets.platform.PlatformUsersNotificationTargetConfig;
import org. [MASK] .server.common.data.notification.targets.platform.TenantAdministratorsFilter;
import org. [MASK] .server.common.data.notification.targets.platform.UserListFilter;
import org. [MASK] .server.common.data.notification.targets.platform.UsersFilter;
import org. [MASK] .server.common.data.sync.ie.EntityExportData;
import org. [MASK] .server.dao.notification.NotificationTargetService;
import org. [MASK] .server.dao.service.ConstraintValidator;
import org. [MASK] .server.queue.util.TbCoreComponent;
import org. [MASK] .server.service.sync.vc.data.EntitiesImportCtx;
import java.util.List;
@Service
@TbCoreComponent
@RequiredArgsConstructor
public class NotificationTargetImportService extends BaseEntityImportService<NotificationTargetId, NotificationTarget, EntityExportData<NotificationTarget>> {
private final NotificationTargetService notificationTargetService;
@Override
protected void setOwner(TenantId tenantId, NotificationTarget notificationTarget, IdProvider idProvider) {
notificationTarget.setTenantId(tenantId);
}
@Override
protected NotificationTarget prepare(EntitiesImportCtx ctx, NotificationTarget notificationTarget, NotificationTarget oldNotificationTarget, EntityExportData<NotificationTarget> exportData, IdProvider idProvider) {
if (notificationTarget.getConfiguration().getType() == NotificationTargetType.PLATFORM_USERS) {
UsersFilter usersFilter = ((PlatformUsersNotificationTargetConfig) notificationTarget.getConfiguration()).getUsersFilter();
switch (usersFilter.getType()) {
case CUSTOMER_USERS:
CustomerUsersFilter customerUsersFilter = (CustomerUsersFilter) usersFilter;
customerUsersFilter.setCustomerId(idProvider.getInternalId(new CustomerId(customerUsersFilter.getCustomerId())).getId());
break;
case USER_LIST:
UserListFilter userListFilter = (UserListFilter) usersFilter;
userListFilter.setUsersIds(List.of(ctx.getUser().getUuidId())); // user entities are not supported by VC; replacing with current user id
break;
case TENANT_ADMINISTRATORS:
if (CollectionUtils.isNotEmpty(((TenantAdministratorsFilter) usersFilter).getTenantsIds()) ||
CollectionUtils.isNotEmpty(((TenantAdministratorsFilter) usersFilter).getTenantProfilesIds())) {
throw new IllegalArgumentException("Permission denied");
}
break;
case SYSTEM_ADMINISTRATORS:
throw new AccessDeniedException("Permission denied");
}
}
return notificationTarget;
}
@Override
protected NotificationTarget saveOrUpdate(EntitiesImportCtx ctx, NotificationTarget notificationTarget, EntityExportData<NotificationTarget> exportData, IdProvider idProvider) {
ConstraintValidator.validateFields(notificationTarget);
return notificationTargetService.saveNotificationTarget(ctx.getTenantId(), notificationTarget);
}
@Override
protected void onEntitySaved(User user, NotificationTarget savedEntity, NotificationTarget oldEntity) throws ThingsboardException {
entityActionService.logEntityAction(user, savedEntity.getId(), savedEntity, null,
oldEntity == null ? ActionType.ADDED : ActionType.UPDATED, null);
}
@Override
protected NotificationTarget deepCopy(NotificationTarget notificationTarget) {
return new NotificationTarget(notificationTarget);
}
@Override
public EntityType getEntityType() {
return EntityType.NOTIFICATION_TARGET;
}
}
| thingsboard |
/*
* Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.hosted;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashSet;
import java.util. [MASK] ;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.stream.Collectors;
import org.graalvm.nativeimage.hosted.RuntimeReflection;
import org.graalvm.nativeimage.hosted.RuntimeResourceAccess;
import com.oracle.svm.core.feature.AutomaticallyRegisteredFeature;
import com.oracle.svm.core.feature.InternalFeature;
import com.oracle.svm.core.jdk.ServiceCatalogSupport;
import com.oracle.svm.core.option.AccumulatingLocatableMultiOptionValue;
import com.oracle.svm.core.option.HostedOptionKey;
import com.oracle.svm.hosted.analysis.Inflation;
import jdk.graal.compiler.options.Option;
import jdk.graal.compiler.options.OptionType;
/**
* Support for {@link ServiceLoader} on Substrate VM.
*
* Services are registered in the folder {@code "META-INF/services/"} using files whose name is the
* fully qualified service interface name. We do not know which services are going to be used by a
* native image: The parameter of {@code ServiceLoader#load} is often but not always a compile-time
* constant that we can track. But we also cannot put all registered services into the native image.
*
* We therefore use the following heuristic: We add all service loader files and service
* implementation classes when the service interfaces that are seen as reachable by the static
* analysis.
*
* Each used service implementation class is added for reflection (using
* {@link org.graalvm.nativeimage.hosted.RuntimeReflection#register(Class[])}) and for reflective
* instantiation (using {@link RuntimeReflection#registerForReflectiveInstantiation(Class[])}).
*
* For each service interface, a single service loader file is added as a resource to the image. The
* single file combines all the individual files that can come from different .jar files.
*/
@AutomaticallyRegisteredFeature
public class ServiceLoaderFeature implements InternalFeature {
public static class Options {
@Option(help = "Automatically register services for run-time lookup using ServiceLoader", type = OptionType.Expert) //
public static final HostedOptionKey<Boolean> UseServiceLoaderFeature = new HostedOptionKey<>(true);
@Option(help = "Comma-separated list of services that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServices = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
@Option(help = "Comma-separated list of service providers that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServiceProviders = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
}
private static final Set<String> SKIPPED_SERVICES = Set.of(
// image builder internal ServiceLoader interfaces
"com.oracle.svm.hosted.NativeImageClassLoaderPostProcessing",
"org.graalvm.nativeimage.Platform",
/*
* Loaded in java.util.random.RandomGeneratorFactory.FactoryMapHolder, which is
* initialized at image build time.
*/
"java.util.random.RandomGenerator",
"java.security.Provider", // see SecurityServicesFeature
"sun.util.locale.provider.LocaleDataMetaInfo", // see LocaleSubstitutions
/* Graal hotspot-specific services */
"jdk.vm.ci.hotspot.HotSpotJVMCIBackendFactory",
"jdk.graal.compiler.hotspot.CompilerConfigurationFactory",
"jdk.graal.compiler.hotspot.HotSpotBackendFactory",
"jdk.graal.compiler.hotspot.meta.DefaultHotSpotLoweringProvider$Extensions",
"jdk.graal.compiler.hotspot.meta.HotSpotInvocationPluginProvider",
"jdk.graal.compiler.truffle.hotspot.TruffleCallBoundaryInstrumentationFactory");
// NOTE: Platform class had to be added to this list since our analysis discovers that
// Platform.includedIn is reachable regardless of fact that it is constant folded at
// registerPlatformPlugins method of SubstrateGraphBuilderPlugins. This issue hasn't manifested
// before because implementation classes were instantiated using runtime reflection instead of
// ServiceLoader (and thus weren't reachable in analysis).
/**
* Services that should not be processed here, for example because they are handled by
* specialized features.
*/
private final Set<String> servicesToSkip = new HashSet<>(SKIPPED_SERVICES);
private static final Set<String> SKIPPED_PROVIDERS = Set.of(
/* Graal hotspot-specific service-providers */
"jdk.graal.compiler.hotspot.meta.HotSpotDisassemblerProvider",
/* Skip console providers until GR-44085 is fixed */
"jdk.internal.org.jline.JdkConsoleProviderImpl", "jdk.jshell.execution.impl.ConsoleImpl$ConsoleProviderImpl");
private final Set<String> serviceProvidersToSkip = new HashSet<>(SKIPPED_PROVIDERS);
@Override
public boolean isInConfiguration(IsInConfigurationAccess access) {
return Options.UseServiceLoaderFeature.getValue();
}
@Override
public void afterRegistration(AfterRegistrationAccess access) {
servicesToSkip.addAll(Options.ServiceLoaderFeatureExcludeServices.getValue().values());
serviceProvidersToSkip.addAll(Options.ServiceLoaderFeatureExcludeServiceProviders.getValue().values());
}
@Override
public void beforeAnalysis(BeforeAnalysisAccess access) {
FeatureImpl.BeforeAnalysisAccessImpl accessImpl = (FeatureImpl.BeforeAnalysisAccessImpl) access;
accessImpl.imageClassLoader.classLoaderSupport.serviceProvidersForEach((serviceName, providers) -> {
Class<?> serviceClass = access.findClassByName(serviceName);
boolean skipService = false;
/* If the service should not end up in the image, we remove all the providers with it */
Collection<String> providersToSkip = providers;
if (servicesToSkip.contains(serviceName)) {
skipService = true;
} else if (serviceClass == null || serviceClass.isArray() || serviceClass.isPrimitive()) {
skipService = true;
} else if (!accessImpl.getHostVM().platformSupported(serviceClass)) {
skipService = true;
} else {
providersToSkip = providers.stream().filter(serviceProvidersToSkip::contains).collect(Collectors.toList());
if (!providersToSkip.isEmpty()) {
skipService = true;
}
}
if (skipService) {
ServiceCatalogSupport.singleton().removeServicesFromServicesCatalog(serviceName, new HashSet<>(providersToSkip));
return;
}
access.registerReachabilityHandler(a -> handleServiceClassIsReachable(a, serviceClass, providers), serviceClass);
});
}
void handleServiceClassIsReachable(DuringAnalysisAccess access, Class<?> serviceProvider, Collection<String> providers) {
[MASK] <String> registeredProviders = new [MASK] <>();
for (String provider : providers) {
if (serviceProvidersToSkip.contains(provider)) {
continue;
}
/* Make provider reflectively instantiable */
Class<?> providerClass = access.findClassByName(provider);
if (providerClass == null || providerClass.isArray() || providerClass.isPrimitive()) {
continue;
}
FeatureImpl.DuringAnalysisAccessImpl accessImpl = (FeatureImpl.DuringAnalysisAccessImpl) access;
if (!accessImpl.getHostVM().platformSupported(providerClass)) {
continue;
}
if (((Inflation) accessImpl.getBigBang()).getAnnotationSubstitutionProcessor().isDeleted(providerClass)) {
/* Disallow services with implementation classes that are marked as @Deleted */
continue;
}
/*
* Find either a public static provider() method or a nullary constructor (or both).
* Skip providers that do not comply with requirements.
*
* See ServiceLoader#loadProvider and ServiceLoader#findStaticProviderMethod.
*/
Constructor<?> nullaryConstructor = null;
Method nullaryProviderMethod = null;
try {
/* Only look for a provider() method if provider class is in an explicit module. */
if (providerClass.getModule().isNamed() && !providerClass.getModule().getDescriptor().isAutomatic()) {
for (Method method : providerClass.getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers()) &&
method.getParameterCount() == 0 && method.getName().equals("provider")) {
if (nullaryProviderMethod == null) {
nullaryProviderMethod = method;
} else {
/* There must be at most one public static provider() method. */
nullaryProviderMethod = null;
break;
}
}
}
}
Constructor<?> constructor = providerClass.getDeclaredConstructor();
if (Modifier.isPublic(constructor.getModifiers())) {
nullaryConstructor = constructor;
}
} catch (NoSuchMethodException | SecurityException | LinkageError e) {
// ignore
}
if (nullaryConstructor != null || nullaryProviderMethod != null) {
RuntimeReflection.register(providerClass);
if (nullaryConstructor != null) {
/*
* Registering a constructor with
* RuntimeReflection.registerConstructorLookup(providerClass) does not produce
* the same behavior as using RuntimeReflection.register(nullaryConstructor). In
* the first case, the constructor is marked for query purposes only, so this
* if-statement cannot be eliminated.
*
*/
RuntimeReflection.register(nullaryConstructor);
} else {
/*
* If there's no nullary constructor, register it as negative lookup to avoid
* throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerConstructorLookup(providerClass);
}
if (nullaryProviderMethod != null) {
RuntimeReflection.register(nullaryProviderMethod);
} else {
/*
* If there's no declared public provider() method, register it as negative
* lookup to avoid throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerMethodLookup(providerClass, "provider");
}
}
/*
* Register the provider in both cases: when it is JCA-compliant (has a nullary
* constructor or a provider method) or when it lacks both. If neither is present, a
* ServiceConfigurationError will be thrown at runtime, consistent with HotSpot
* behavior.
*/
registeredProviders.add(provider);
}
if (!registeredProviders.isEmpty()) {
String serviceResourceLocation = "META-INF/services/" + serviceProvider.getName();
byte[] serviceFileData = registeredProviders.stream().collect(Collectors.joining("\n")).getBytes(StandardCharsets.UTF_8);
RuntimeResourceAccess.addResource(access.getApplicationClassLoader().getUnnamedModule(), serviceResourceLocation, serviceFileData);
}
}
}
| LinkedHashSet |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver [MASK] Resolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver [MASK] Resolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this. [MASK] Resolver = [MASK] Resolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex [MASK] Index;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this. [MASK] Index = (BootZipCopyAction.this. [MASK] Resolver != null)
? new LayersIndex(BootZipCopyAction.this. [MASK] Resolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this. [MASK] Resolver != null) {
Layer [MASK] = BootZipCopyAction.this. [MASK] Resolver.getLayer(details);
this. [MASK] Index.add( [MASK] , name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the [MASK] index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this. [MASK] Resolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer [MASK] = BootZipCopyAction.this. [MASK] Resolver.getLayer(name);
this. [MASK] Index.add( [MASK] , name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this. [MASK] Resolver != null) {
Layer [MASK] = BootZipCopyAction.this. [MASK] Resolver.getLayer(library);
this. [MASK] Index.add( [MASK] , name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this. [MASK] Resolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing [MASK] index manifest attribute");
Layer [MASK] = BootZipCopyAction.this. [MASK] Resolver.getLayer(name);
this. [MASK] Index.add( [MASK] , name);
writeEntry(name, this. [MASK] Index::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this. [MASK] Resolver != null) {
Layer [MASK] = BootZipCopyAction.this. [MASK] Resolver.getLayer(name);
this. [MASK] Index.add( [MASK] , name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| layer |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter. [MASK] (library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
. [MASK] (inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter [MASK] (InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| fromInputStream |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation [MASK] ;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation [MASK] ) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this. [MASK] = [MASK] ;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this. [MASK] );
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| loaderImplementation |
/*
* Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.hosted;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.stream.Collectors;
import org.graalvm.nativeimage.hosted.RuntimeReflection;
import org.graalvm.nativeimage.hosted.RuntimeResourceAccess;
import com.oracle.svm.core.feature.AutomaticallyRegisteredFeature;
import com.oracle.svm.core.feature.InternalFeature;
import com.oracle.svm.core.jdk.ServiceCatalogSupport;
import com.oracle.svm.core.option.AccumulatingLocatableMultiOptionValue;
import com.oracle.svm.core.option.HostedOptionKey;
import com.oracle.svm.hosted.analysis.Inflation;
import jdk.graal.compiler.options.Option;
import jdk.graal.compiler.options.OptionType;
/**
* Support for {@link ServiceLoader} on Substrate VM.
*
* Services are registered in the folder {@code "META-INF/services/"} using files whose name is the
* fully qualified service interface name. We do not know which services are going to be used by a
* native image: The parameter of {@code ServiceLoader#load} is often but not always a compile-time
* constant that we can track. But we also cannot put all registered services into the native image.
*
* We therefore use the following heuristic: We add all service loader files and service
* implementation classes when the service interfaces that are seen as reachable by the static
* analysis.
*
* Each used service implementation class is added for reflection (using
* {@link org.graalvm.nativeimage.hosted.RuntimeReflection#register(Class[])}) and for reflective
* instantiation (using {@link RuntimeReflection#registerForReflectiveInstantiation(Class[])}).
*
* For each service interface, a single service loader file is added as a resource to the image. The
* single file combines all the individual files that can come from different .jar files.
*/
@AutomaticallyRegisteredFeature
public class ServiceLoaderFeature implements InternalFeature {
public static class Options {
@Option(help = "Automatically register services for run-time lookup using ServiceLoader", type = OptionType.Expert) //
public static final HostedOptionKey<Boolean> UseServiceLoaderFeature = new HostedOptionKey<>(true);
@Option(help = "Comma-separated list of services that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServices = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
@Option(help = "Comma-separated list of service [MASK] s that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServiceProviders = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
}
private static final Set<String> SKIPPED_SERVICES = Set.of(
// image builder internal ServiceLoader interfaces
"com.oracle.svm.hosted.NativeImageClassLoaderPostProcessing",
"org.graalvm.nativeimage.Platform",
/*
* Loaded in java.util.random.RandomGeneratorFactory.FactoryMapHolder, which is
* initialized at image build time.
*/
"java.util.random.RandomGenerator",
"java.security.Provider", // see SecurityServicesFeature
"sun.util.locale. [MASK] .LocaleDataMetaInfo", // see LocaleSubstitutions
/* Graal hotspot-specific services */
"jdk.vm.ci.hotspot.HotSpotJVMCIBackendFactory",
"jdk.graal.compiler.hotspot.CompilerConfigurationFactory",
"jdk.graal.compiler.hotspot.HotSpotBackendFactory",
"jdk.graal.compiler.hotspot.meta.DefaultHotSpotLoweringProvider$Extensions",
"jdk.graal.compiler.hotspot.meta.HotSpotInvocationPluginProvider",
"jdk.graal.compiler.truffle.hotspot.TruffleCallBoundaryInstrumentationFactory");
// NOTE: Platform class had to be added to this list since our analysis discovers that
// Platform.includedIn is reachable regardless of fact that it is constant folded at
// registerPlatformPlugins method of SubstrateGraphBuilderPlugins. This issue hasn't manifested
// before because implementation classes were instantiated using runtime reflection instead of
// ServiceLoader (and thus weren't reachable in analysis).
/**
* Services that should not be processed here, for example because they are handled by
* specialized features.
*/
private final Set<String> servicesToSkip = new HashSet<>(SKIPPED_SERVICES);
private static final Set<String> SKIPPED_PROVIDERS = Set.of(
/* Graal hotspot-specific service- [MASK] s */
"jdk.graal.compiler.hotspot.meta.HotSpotDisassemblerProvider",
/* Skip console [MASK] s until GR-44085 is fixed */
"jdk.internal.org.jline.JdkConsoleProviderImpl", "jdk.jshell.execution.impl.ConsoleImpl$ConsoleProviderImpl");
private final Set<String> serviceProvidersToSkip = new HashSet<>(SKIPPED_PROVIDERS);
@Override
public boolean isInConfiguration(IsInConfigurationAccess access) {
return Options.UseServiceLoaderFeature.getValue();
}
@Override
public void afterRegistration(AfterRegistrationAccess access) {
servicesToSkip.addAll(Options.ServiceLoaderFeatureExcludeServices.getValue().values());
serviceProvidersToSkip.addAll(Options.ServiceLoaderFeatureExcludeServiceProviders.getValue().values());
}
@Override
public void beforeAnalysis(BeforeAnalysisAccess access) {
FeatureImpl.BeforeAnalysisAccessImpl accessImpl = (FeatureImpl.BeforeAnalysisAccessImpl) access;
accessImpl.imageClassLoader.classLoaderSupport.serviceProvidersForEach((serviceName, [MASK] s) -> {
Class<?> serviceClass = access.findClassByName(serviceName);
boolean skipService = false;
/* If the service should not end up in the image, we remove all the [MASK] s with it */
Collection<String> [MASK] sToSkip = [MASK] s;
if (servicesToSkip.contains(serviceName)) {
skipService = true;
} else if (serviceClass == null || serviceClass.isArray() || serviceClass.isPrimitive()) {
skipService = true;
} else if (!accessImpl.getHostVM().platformSupported(serviceClass)) {
skipService = true;
} else {
[MASK] sToSkip = [MASK] s.stream().filter(serviceProvidersToSkip::contains).collect(Collectors.toList());
if (! [MASK] sToSkip.isEmpty()) {
skipService = true;
}
}
if (skipService) {
ServiceCatalogSupport.singleton().removeServicesFromServicesCatalog(serviceName, new HashSet<>( [MASK] sToSkip));
return;
}
access.registerReachabilityHandler(a -> handleServiceClassIsReachable(a, serviceClass, [MASK] s), serviceClass);
});
}
void handleServiceClassIsReachable(DuringAnalysisAccess access, Class<?> serviceProvider, Collection<String> [MASK] s) {
LinkedHashSet<String> registeredProviders = new LinkedHashSet<>();
for (String [MASK] : [MASK] s) {
if (serviceProvidersToSkip.contains( [MASK] )) {
continue;
}
/* Make [MASK] reflectively instantiable */
Class<?> [MASK] Class = access.findClassByName( [MASK] );
if ( [MASK] Class == null || [MASK] Class.isArray() || [MASK] Class.isPrimitive()) {
continue;
}
FeatureImpl.DuringAnalysisAccessImpl accessImpl = (FeatureImpl.DuringAnalysisAccessImpl) access;
if (!accessImpl.getHostVM().platformSupported( [MASK] Class)) {
continue;
}
if (((Inflation) accessImpl.getBigBang()).getAnnotationSubstitutionProcessor().isDeleted( [MASK] Class)) {
/* Disallow services with implementation classes that are marked as @Deleted */
continue;
}
/*
* Find either a public static [MASK] () method or a nullary constructor (or both).
* Skip [MASK] s that do not comply with requirements.
*
* See ServiceLoader#loadProvider and ServiceLoader#findStaticProviderMethod.
*/
Constructor<?> nullaryConstructor = null;
Method nullaryProviderMethod = null;
try {
/* Only look for a [MASK] () method if [MASK] class is in an explicit module. */
if ( [MASK] Class.getModule().isNamed() && ! [MASK] Class.getModule().getDescriptor().isAutomatic()) {
for (Method method : [MASK] Class.getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers()) &&
method.getParameterCount() == 0 && method.getName().equals(" [MASK] ")) {
if (nullaryProviderMethod == null) {
nullaryProviderMethod = method;
} else {
/* There must be at most one public static [MASK] () method. */
nullaryProviderMethod = null;
break;
}
}
}
}
Constructor<?> constructor = [MASK] Class.getDeclaredConstructor();
if (Modifier.isPublic(constructor.getModifiers())) {
nullaryConstructor = constructor;
}
} catch (NoSuchMethodException | SecurityException | LinkageError e) {
// ignore
}
if (nullaryConstructor != null || nullaryProviderMethod != null) {
RuntimeReflection.register( [MASK] Class);
if (nullaryConstructor != null) {
/*
* Registering a constructor with
* RuntimeReflection.registerConstructorLookup( [MASK] Class) does not produce
* the same behavior as using RuntimeReflection.register(nullaryConstructor). In
* the first case, the constructor is marked for query purposes only, so this
* if-statement cannot be eliminated.
*
*/
RuntimeReflection.register(nullaryConstructor);
} else {
/*
* If there's no nullary constructor, register it as negative lookup to avoid
* throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerConstructorLookup( [MASK] Class);
}
if (nullaryProviderMethod != null) {
RuntimeReflection.register(nullaryProviderMethod);
} else {
/*
* If there's no declared public [MASK] () method, register it as negative
* lookup to avoid throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerMethodLookup( [MASK] Class, " [MASK] ");
}
}
/*
* Register the [MASK] in both cases: when it is JCA-compliant (has a nullary
* constructor or a [MASK] method) or when it lacks both. If neither is present, a
* ServiceConfigurationError will be thrown at runtime, consistent with HotSpot
* behavior.
*/
registeredProviders.add( [MASK] );
}
if (!registeredProviders.isEmpty()) {
String serviceResourceLocation = "META-INF/services/" + serviceProvider.getName();
byte[] serviceFileData = registeredProviders.stream().collect(Collectors.joining("\n")).getBytes(StandardCharsets.UTF_8);
RuntimeResourceAccess.addResource(access.getApplicationClassLoader().getUnnamedModule(), serviceResourceLocation, serviceFileData);
}
}
}
| provider |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor [MASK] = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = ( [MASK] != null) ? [MASK] .getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| descriptor |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean [MASK] ;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean [MASK] , String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this. [MASK] = [MASK] ;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this. [MASK] || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| includeDefaultLoader |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> [MASK] = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, [MASK] ).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails [MASK] File = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if ( [MASK] File != null) {
try (InputStream inputStream = [MASK] File.open()) {
ReachabilityMetadataProperties [MASK] = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if ( [MASK] .isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| properties |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file. [MASK] ;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec< [MASK] > librarySpec;
private final Function< [MASK] , ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec< [MASK] > librarySpec,
Function< [MASK] , ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link [MASK] file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, [MASK] > writtenLibraries = new LinkedHashMap<>();
private final Map<String, [MASK] > reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process( [MASK] details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing( [MASK] details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory( [MASK] details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile( [MASK] details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary( [MASK] details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf( [MASK] details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for ( [MASK] writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, [MASK] > entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
[MASK] propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry( [MASK] details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime( [MASK] details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode( [MASK] details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions( [MASK] details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode( [MASK] details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| FileCopyDetails |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
[MASK] (entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
[MASK] (entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
[MASK] (entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
[MASK] (entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void [MASK] (ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| prepareEntry |
/**
* Copyright © 2016-2024 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thingsboard.server.service.sync.ie.importing.impl;
import lombok.RequiredArgsConstructor;
import org.apache. [MASK] s.collections4.CollectionUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import org.thingsboard.server. [MASK] .data.EntityType;
import org.thingsboard.server. [MASK] .data.User;
import org.thingsboard.server. [MASK] .data.audit.ActionType;
import org.thingsboard.server. [MASK] .data.exception.ThingsboardException;
import org.thingsboard.server. [MASK] .data.id.CustomerId;
import org.thingsboard.server. [MASK] .data.id.NotificationTargetId;
import org.thingsboard.server. [MASK] .data.id.TenantId;
import org.thingsboard.server. [MASK] .data.notification.targets.NotificationTarget;
import org.thingsboard.server. [MASK] .data.notification.targets.NotificationTargetType;
import org.thingsboard.server. [MASK] .data.notification.targets.platform.CustomerUsersFilter;
import org.thingsboard.server. [MASK] .data.notification.targets.platform.PlatformUsersNotificationTargetConfig;
import org.thingsboard.server. [MASK] .data.notification.targets.platform.TenantAdministratorsFilter;
import org.thingsboard.server. [MASK] .data.notification.targets.platform.UserListFilter;
import org.thingsboard.server. [MASK] .data.notification.targets.platform.UsersFilter;
import org.thingsboard.server. [MASK] .data.sync.ie.EntityExportData;
import org.thingsboard.server.dao.notification.NotificationTargetService;
import org.thingsboard.server.dao.service.ConstraintValidator;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.sync.vc.data.EntitiesImportCtx;
import java.util.List;
@Service
@TbCoreComponent
@RequiredArgsConstructor
public class NotificationTargetImportService extends BaseEntityImportService<NotificationTargetId, NotificationTarget, EntityExportData<NotificationTarget>> {
private final NotificationTargetService notificationTargetService;
@Override
protected void setOwner(TenantId tenantId, NotificationTarget notificationTarget, IdProvider idProvider) {
notificationTarget.setTenantId(tenantId);
}
@Override
protected NotificationTarget prepare(EntitiesImportCtx ctx, NotificationTarget notificationTarget, NotificationTarget oldNotificationTarget, EntityExportData<NotificationTarget> exportData, IdProvider idProvider) {
if (notificationTarget.getConfiguration().getType() == NotificationTargetType.PLATFORM_USERS) {
UsersFilter usersFilter = ((PlatformUsersNotificationTargetConfig) notificationTarget.getConfiguration()).getUsersFilter();
switch (usersFilter.getType()) {
case CUSTOMER_USERS:
CustomerUsersFilter customerUsersFilter = (CustomerUsersFilter) usersFilter;
customerUsersFilter.setCustomerId(idProvider.getInternalId(new CustomerId(customerUsersFilter.getCustomerId())).getId());
break;
case USER_LIST:
UserListFilter userListFilter = (UserListFilter) usersFilter;
userListFilter.setUsersIds(List.of(ctx.getUser().getUuidId())); // user entities are not supported by VC; replacing with current user id
break;
case TENANT_ADMINISTRATORS:
if (CollectionUtils.isNotEmpty(((TenantAdministratorsFilter) usersFilter).getTenantsIds()) ||
CollectionUtils.isNotEmpty(((TenantAdministratorsFilter) usersFilter).getTenantProfilesIds())) {
throw new IllegalArgumentException("Permission denied");
}
break;
case SYSTEM_ADMINISTRATORS:
throw new AccessDeniedException("Permission denied");
}
}
return notificationTarget;
}
@Override
protected NotificationTarget saveOrUpdate(EntitiesImportCtx ctx, NotificationTarget notificationTarget, EntityExportData<NotificationTarget> exportData, IdProvider idProvider) {
ConstraintValidator.validateFields(notificationTarget);
return notificationTargetService.saveNotificationTarget(ctx.getTenantId(), notificationTarget);
}
@Override
protected void onEntitySaved(User user, NotificationTarget savedEntity, NotificationTarget oldEntity) throws ThingsboardException {
entityActionService.logEntityAction(user, savedEntity.getId(), savedEntity, null,
oldEntity == null ? ActionType.ADDED : ActionType.UPDATED, null);
}
@Override
protected NotificationTarget deepCopy(NotificationTarget notificationTarget) {
return new NotificationTarget(notificationTarget);
}
@Override
public EntityType getEntityType() {
return EntityType.NOTIFICATION_TARGET;
}
}
| common |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip. [MASK] ;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: [MASK] .DIR_FLAG | [MASK] .DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: [MASK] .FILE_FLAG | [MASK] .DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: [MASK] .FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| UnixStat |
/**
* Copyright © 2016-2024 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thingsboard.server.service.sync.ie.importing.impl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.NotificationTargetId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.notification.targets.NotificationTarget;
import org.thingsboard.server.common.data.notification.targets.NotificationTargetType;
import org.thingsboard.server.common.data.notification.targets.platform.CustomerUsersFilter;
import org.thingsboard.server.common.data.notification.targets.platform.PlatformUsersNotificationTargetConfig;
import org.thingsboard.server.common.data.notification.targets.platform.TenantAdministratorsFilter;
import org.thingsboard.server.common.data.notification.targets.platform.UserListFilter;
import org.thingsboard.server.common.data.notification.targets.platform.UsersFilter;
import org.thingsboard.server.common.data.sync.ie.EntityExportData;
import org.thingsboard.server.dao.notification.NotificationTargetService;
import org.thingsboard.server.dao.service.ConstraintValidator;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.sync.vc.data.EntitiesImportCtx;
import java.util.List;
@Service
@TbCoreComponent
@RequiredArgsConstructor
public class NotificationTargetImportService extends BaseEntityImportService<NotificationTargetId, NotificationTarget, EntityExportData<NotificationTarget>> {
private final NotificationTargetService notificationTargetService;
@Override
protected void setOwner(TenantId tenantId, NotificationTarget notificationTarget, IdProvider idProvider) {
notificationTarget.setTenantId(tenantId);
}
@Override
protected NotificationTarget prepare(EntitiesImportCtx ctx, NotificationTarget notificationTarget, NotificationTarget oldNotificationTarget, EntityExportData<NotificationTarget> exportData, IdProvider idProvider) {
if (notificationTarget.getConfiguration().getType() == NotificationTargetType.PLATFORM_USERS) {
UsersFilter usersFilter = ((PlatformUsersNotificationTargetConfig) notificationTarget.getConfiguration()).getUsersFilter();
switch (usersFilter.getType()) {
case CUSTOMER_USERS:
CustomerUsersFilter [MASK] = (CustomerUsersFilter) usersFilter;
[MASK] .setCustomerId(idProvider.getInternalId(new CustomerId( [MASK] .getCustomerId())).getId());
break;
case USER_LIST:
UserListFilter userListFilter = (UserListFilter) usersFilter;
userListFilter.setUsersIds(List.of(ctx.getUser().getUuidId())); // user entities are not supported by VC; replacing with current user id
break;
case TENANT_ADMINISTRATORS:
if (CollectionUtils.isNotEmpty(((TenantAdministratorsFilter) usersFilter).getTenantsIds()) ||
CollectionUtils.isNotEmpty(((TenantAdministratorsFilter) usersFilter).getTenantProfilesIds())) {
throw new IllegalArgumentException("Permission denied");
}
break;
case SYSTEM_ADMINISTRATORS:
throw new AccessDeniedException("Permission denied");
}
}
return notificationTarget;
}
@Override
protected NotificationTarget saveOrUpdate(EntitiesImportCtx ctx, NotificationTarget notificationTarget, EntityExportData<NotificationTarget> exportData, IdProvider idProvider) {
ConstraintValidator.validateFields(notificationTarget);
return notificationTargetService.saveNotificationTarget(ctx.getTenantId(), notificationTarget);
}
@Override
protected void onEntitySaved(User user, NotificationTarget savedEntity, NotificationTarget oldEntity) throws ThingsboardException {
entityActionService.logEntityAction(user, savedEntity.getId(), savedEntity, null,
oldEntity == null ? ActionType.ADDED : ActionType.UPDATED, null);
}
@Override
protected NotificationTarget deepCopy(NotificationTarget notificationTarget) {
return new NotificationTarget(notificationTarget);
}
@Override
public EntityType getEntityType() {
return EntityType.NOTIFICATION_TARGET;
}
}
| customerUsersFilter |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools. [MASK] ;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
Processor processor = new Processor(zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class Processor {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
Processor(ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
write [MASK] IfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void write [MASK] IfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
[MASK] argFile = new [MASK] (excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry( [MASK] .LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| NativeImageArgFile |
/*
* Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.hosted;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.stream.Collectors;
import org.graalvm.nativeimage.hosted.RuntimeReflection;
import org.graalvm.nativeimage.hosted.RuntimeResourceAccess;
import com.oracle.svm.core.feature.AutomaticallyRegisteredFeature;
import com.oracle.svm.core.feature.InternalFeature;
import com.oracle.svm.core.jdk.ServiceCatalogSupport;
import com.oracle.svm.core.option.AccumulatingLocatableMultiOptionValue;
import com.oracle.svm.core.option.HostedOptionKey;
import com.oracle.svm.hosted.analysis.Inflation;
import jdk.graal.compiler.options.Option;
import jdk.graal.compiler.options.OptionType;
/**
* Support for {@link ServiceLoader} on Substrate VM.
*
* Services are [MASK] ed in the folder {@code "META-INF/services/"} using files whose name is the
* fully qualified service interface name. We do not know which services are going to be used by a
* native image: The parameter of {@code ServiceLoader#load} is often but not always a compile-time
* constant that we can track. But we also cannot put all [MASK] ed services into the native image.
*
* We therefore use the following heuristic: We add all service loader files and service
* implementation classes when the service interfaces that are seen as reachable by the static
* analysis.
*
* Each used service implementation class is added for reflection (using
* {@link org.graalvm.nativeimage.hosted.RuntimeReflection# [MASK] (Class[])}) and for reflective
* instantiation (using {@link RuntimeReflection# [MASK] ForReflectiveInstantiation(Class[])}).
*
* For each service interface, a single service loader file is added as a resource to the image. The
* single file combines all the individual files that can come from different .jar files.
*/
@AutomaticallyRegisteredFeature
public class ServiceLoaderFeature implements InternalFeature {
public static class Options {
@Option(help = "Automatically [MASK] services for run-time lookup using ServiceLoader", type = OptionType.Expert) //
public static final HostedOptionKey<Boolean> UseServiceLoaderFeature = new HostedOptionKey<>(true);
@Option(help = "Comma-separated list of services that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServices = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
@Option(help = "Comma-separated list of service providers that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServiceProviders = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
}
private static final Set<String> SKIPPED_SERVICES = Set.of(
// image builder internal ServiceLoader interfaces
"com.oracle.svm.hosted.NativeImageClassLoaderPostProcessing",
"org.graalvm.nativeimage.Platform",
/*
* Loaded in java.util.random.RandomGeneratorFactory.FactoryMapHolder, which is
* initialized at image build time.
*/
"java.util.random.RandomGenerator",
"java.security.Provider", // see SecurityServicesFeature
"sun.util.locale.provider.LocaleDataMetaInfo", // see LocaleSubstitutions
/* Graal hotspot-specific services */
"jdk.vm.ci.hotspot.HotSpotJVMCIBackendFactory",
"jdk.graal.compiler.hotspot.CompilerConfigurationFactory",
"jdk.graal.compiler.hotspot.HotSpotBackendFactory",
"jdk.graal.compiler.hotspot.meta.DefaultHotSpotLoweringProvider$Extensions",
"jdk.graal.compiler.hotspot.meta.HotSpotInvocationPluginProvider",
"jdk.graal.compiler.truffle.hotspot.TruffleCallBoundaryInstrumentationFactory");
// NOTE: Platform class had to be added to this list since our analysis discovers that
// Platform.includedIn is reachable regardless of fact that it is constant folded at
// [MASK] PlatformPlugins method of SubstrateGraphBuilderPlugins. This issue hasn't manifested
// before because implementation classes were instantiated using runtime reflection instead of
// ServiceLoader (and thus weren't reachable in analysis).
/**
* Services that should not be processed here, for example because they are handled by
* specialized features.
*/
private final Set<String> servicesToSkip = new HashSet<>(SKIPPED_SERVICES);
private static final Set<String> SKIPPED_PROVIDERS = Set.of(
/* Graal hotspot-specific service-providers */
"jdk.graal.compiler.hotspot.meta.HotSpotDisassemblerProvider",
/* Skip console providers until GR-44085 is fixed */
"jdk.internal.org.jline.JdkConsoleProviderImpl", "jdk.jshell.execution.impl.ConsoleImpl$ConsoleProviderImpl");
private final Set<String> serviceProvidersToSkip = new HashSet<>(SKIPPED_PROVIDERS);
@Override
public boolean isInConfiguration(IsInConfigurationAccess access) {
return Options.UseServiceLoaderFeature.getValue();
}
@Override
public void afterRegistration(AfterRegistrationAccess access) {
servicesToSkip.addAll(Options.ServiceLoaderFeatureExcludeServices.getValue().values());
serviceProvidersToSkip.addAll(Options.ServiceLoaderFeatureExcludeServiceProviders.getValue().values());
}
@Override
public void beforeAnalysis(BeforeAnalysisAccess access) {
FeatureImpl.BeforeAnalysisAccessImpl accessImpl = (FeatureImpl.BeforeAnalysisAccessImpl) access;
accessImpl.imageClassLoader.classLoaderSupport.serviceProvidersForEach((serviceName, providers) -> {
Class<?> serviceClass = access.findClassByName(serviceName);
boolean skipService = false;
/* If the service should not end up in the image, we remove all the providers with it */
Collection<String> providersToSkip = providers;
if (servicesToSkip.contains(serviceName)) {
skipService = true;
} else if (serviceClass == null || serviceClass.isArray() || serviceClass.isPrimitive()) {
skipService = true;
} else if (!accessImpl.getHostVM().platformSupported(serviceClass)) {
skipService = true;
} else {
providersToSkip = providers.stream().filter(serviceProvidersToSkip::contains).collect(Collectors.toList());
if (!providersToSkip.isEmpty()) {
skipService = true;
}
}
if (skipService) {
ServiceCatalogSupport.singleton().removeServicesFromServicesCatalog(serviceName, new HashSet<>(providersToSkip));
return;
}
access. [MASK] ReachabilityHandler(a -> handleServiceClassIsReachable(a, serviceClass, providers), serviceClass);
});
}
void handleServiceClassIsReachable(DuringAnalysisAccess access, Class<?> serviceProvider, Collection<String> providers) {
LinkedHashSet<String> [MASK] edProviders = new LinkedHashSet<>();
for (String provider : providers) {
if (serviceProvidersToSkip.contains(provider)) {
continue;
}
/* Make provider reflectively instantiable */
Class<?> providerClass = access.findClassByName(provider);
if (providerClass == null || providerClass.isArray() || providerClass.isPrimitive()) {
continue;
}
FeatureImpl.DuringAnalysisAccessImpl accessImpl = (FeatureImpl.DuringAnalysisAccessImpl) access;
if (!accessImpl.getHostVM().platformSupported(providerClass)) {
continue;
}
if (((Inflation) accessImpl.getBigBang()).getAnnotationSubstitutionProcessor().isDeleted(providerClass)) {
/* Disallow services with implementation classes that are marked as @Deleted */
continue;
}
/*
* Find either a public static provider() method or a nullary constructor (or both).
* Skip providers that do not comply with requirements.
*
* See ServiceLoader#loadProvider and ServiceLoader#findStaticProviderMethod.
*/
Constructor<?> nullaryConstructor = null;
Method nullaryProviderMethod = null;
try {
/* Only look for a provider() method if provider class is in an explicit module. */
if (providerClass.getModule().isNamed() && !providerClass.getModule().getDescriptor().isAutomatic()) {
for (Method method : providerClass.getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers()) &&
method.getParameterCount() == 0 && method.getName().equals("provider")) {
if (nullaryProviderMethod == null) {
nullaryProviderMethod = method;
} else {
/* There must be at most one public static provider() method. */
nullaryProviderMethod = null;
break;
}
}
}
}
Constructor<?> constructor = providerClass.getDeclaredConstructor();
if (Modifier.isPublic(constructor.getModifiers())) {
nullaryConstructor = constructor;
}
} catch (NoSuchMethodException | SecurityException | LinkageError e) {
// ignore
}
if (nullaryConstructor != null || nullaryProviderMethod != null) {
RuntimeReflection. [MASK] (providerClass);
if (nullaryConstructor != null) {
/*
* Registering a constructor with
* RuntimeReflection. [MASK] ConstructorLookup(providerClass) does not produce
* the same behavior as using RuntimeReflection. [MASK] (nullaryConstructor). In
* the first case, the constructor is marked for query purposes only, so this
* if-statement cannot be eliminated.
*
*/
RuntimeReflection. [MASK] (nullaryConstructor);
} else {
/*
* If there's no nullary constructor, [MASK] it as negative lookup to avoid
* throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection. [MASK] ConstructorLookup(providerClass);
}
if (nullaryProviderMethod != null) {
RuntimeReflection. [MASK] (nullaryProviderMethod);
} else {
/*
* If there's no declared public provider() method, [MASK] it as negative
* lookup to avoid throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection. [MASK] MethodLookup(providerClass, "provider");
}
}
/*
* Register the provider in both cases: when it is JCA-compliant (has a nullary
* constructor or a provider method) or when it lacks both. If neither is present, a
* ServiceConfigurationError will be thrown at runtime, consistent with HotSpot
* behavior.
*/
[MASK] edProviders.add(provider);
}
if (! [MASK] edProviders.isEmpty()) {
String serviceResourceLocation = "META-INF/services/" + serviceProvider.getName();
byte[] serviceFileData = [MASK] edProviders.stream().collect(Collectors.joining("\n")).getBytes(StandardCharsets.UTF_8);
RuntimeResourceAccess.addResource(access.getApplicationClassLoader().getUnnamedModule(), serviceResourceLocation, serviceFileData);
}
}
}
| register |
/*
* Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.hosted;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.stream.Collectors;
import org.graalvm.nativeimage.hosted.RuntimeReflection;
import org.graalvm.nativeimage.hosted.RuntimeResourceAccess;
import com.oracle.svm.core.feature.AutomaticallyRegisteredFeature;
import com.oracle.svm.core.feature.InternalFeature;
import com.oracle.svm.core.jdk.ServiceCatalogSupport;
import com.oracle.svm.core.option.AccumulatingLocatableMultiOptionValue;
import com.oracle.svm.core.option.HostedOptionKey;
import com.oracle.svm.hosted.analysis.Inflation;
import jdk.graal.compiler.options.Option;
import jdk.graal.compiler.options.OptionType;
/**
* Support for {@link ServiceLoader} on Substrate VM.
*
* Services are registered in the folder {@code "META-INF/services/"} using files whose name is the
* fully qualified service interface name. We do not know which services are going to be used by a
* native image: The parameter of {@code ServiceLoader#load} is often but not always a compile-time
* constant that we can track. But we also cannot put all registered services into the native image.
*
* We therefore use the following heuristic: We add all service loader files and service
* implementation classes when the service interfaces that are seen as reachable by the static
* analysis.
*
* Each used service implementation class is added for reflection (using
* {@link org.graalvm.nativeimage.hosted.RuntimeReflection#register(Class[])}) and for reflective
* instantiation (using {@link RuntimeReflection#registerForReflectiveInstantiation(Class[])}).
*
* For each service interface, a single service loader file is added as a resource to the image. The
* single file combines all the individual files that can come from different .jar files.
*/
@AutomaticallyRegisteredFeature
public class ServiceLoaderFeature implements InternalFeature {
public static class Options {
@Option(help = "Automatically register services for run-time lookup using ServiceLoader", type = OptionType.Expert) //
public static final HostedOptionKey<Boolean> UseServiceLoaderFeature = new HostedOptionKey<>(true);
@Option(help = "Comma-separated list of services that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServices = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
@Option(help = "Comma-separated list of service providers that should be excluded", type = OptionType.Expert) //
public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> ServiceLoaderFeatureExcludeServiceProviders = new HostedOptionKey<>(
AccumulatingLocatableMultiOptionValue.Strings.buildWithCommaDelimiter());
}
private static final Set<String> SKIPPED_SERVICES = Set.of(
// image builder internal ServiceLoader interfaces
"com.oracle.svm.hosted.NativeImageClassLoaderPostProcessing",
"org.graalvm.nativeimage.Platform",
/*
* Loaded in java.util.random.RandomGeneratorFactory.FactoryMapHolder, which is
* initialized at image build time.
*/
"java.util.random.RandomGenerator",
"java.security.Provider", // see SecurityServicesFeature
"sun.util.locale.provider.LocaleDataMetaInfo", // see LocaleSubstitutions
/* Graal hotspot-specific services */
"jdk.vm.ci.hotspot.HotSpotJVMCIBackendFactory",
"jdk.graal.compiler.hotspot.CompilerConfigurationFactory",
"jdk.graal.compiler.hotspot.HotSpotBackendFactory",
"jdk.graal.compiler.hotspot.meta.DefaultHotSpotLoweringProvider$Extensions",
"jdk.graal.compiler.hotspot.meta.HotSpotInvocationPluginProvider",
"jdk.graal.compiler.truffle.hotspot.TruffleCallBoundaryInstrumentationFactory");
// NOTE: Platform class had to be added to this list since our analysis discovers that
// Platform.includedIn is reachable regardless of fact that it is constant folded at
// registerPlatformPlugins method of SubstrateGraphBuilderPlugins. This issue hasn't manifested
// before because implementation classes were instantiated using runtime reflection instead of
// ServiceLoader (and thus weren't reachable in analysis).
/**
* Services that should not be processed here, for example because they are handled by
* specialized features.
*/
private final Set<String> servicesToSkip = new HashSet<>(SKIPPED_SERVICES);
private static final Set<String> SKIPPED_PROVIDERS = Set.of(
/* Graal hotspot-specific service-providers */
"jdk.graal.compiler.hotspot.meta.HotSpotDisassemblerProvider",
/* Skip console providers until GR-44085 is fixed */
"jdk.internal.org.jline.JdkConsoleProviderImpl", "jdk.jshell.execution.impl.ConsoleImpl$ConsoleProviderImpl");
private final Set<String> serviceProvidersToSkip = new HashSet<>(SKIPPED_PROVIDERS);
@Override
public boolean isInConfiguration(IsInConfigurationAccess access) {
return Options.UseServiceLoaderFeature.getValue();
}
@Override
public void afterRegistration(AfterRegistrationAccess access) {
servicesToSkip.addAll(Options.ServiceLoaderFeatureExcludeServices.getValue().values());
serviceProvidersToSkip.addAll(Options.ServiceLoaderFeatureExcludeServiceProviders.getValue().values());
}
@Override
public void beforeAnalysis(BeforeAnalysisAccess access) {
FeatureImpl.BeforeAnalysisAccessImpl [MASK] = (FeatureImpl.BeforeAnalysisAccessImpl) access;
[MASK] .imageClassLoader.classLoaderSupport.serviceProvidersForEach((serviceName, providers) -> {
Class<?> serviceClass = access.findClassByName(serviceName);
boolean skipService = false;
/* If the service should not end up in the image, we remove all the providers with it */
Collection<String> providersToSkip = providers;
if (servicesToSkip.contains(serviceName)) {
skipService = true;
} else if (serviceClass == null || serviceClass.isArray() || serviceClass.isPrimitive()) {
skipService = true;
} else if (! [MASK] .getHostVM().platformSupported(serviceClass)) {
skipService = true;
} else {
providersToSkip = providers.stream().filter(serviceProvidersToSkip::contains).collect(Collectors.toList());
if (!providersToSkip.isEmpty()) {
skipService = true;
}
}
if (skipService) {
ServiceCatalogSupport.singleton().removeServicesFromServicesCatalog(serviceName, new HashSet<>(providersToSkip));
return;
}
access.registerReachabilityHandler(a -> handleServiceClassIsReachable(a, serviceClass, providers), serviceClass);
});
}
void handleServiceClassIsReachable(DuringAnalysisAccess access, Class<?> serviceProvider, Collection<String> providers) {
LinkedHashSet<String> registeredProviders = new LinkedHashSet<>();
for (String provider : providers) {
if (serviceProvidersToSkip.contains(provider)) {
continue;
}
/* Make provider reflectively instantiable */
Class<?> providerClass = access.findClassByName(provider);
if (providerClass == null || providerClass.isArray() || providerClass.isPrimitive()) {
continue;
}
FeatureImpl.DuringAnalysisAccessImpl [MASK] = (FeatureImpl.DuringAnalysisAccessImpl) access;
if (! [MASK] .getHostVM().platformSupported(providerClass)) {
continue;
}
if (((Inflation) [MASK] .getBigBang()).getAnnotationSubstitutionProcessor().isDeleted(providerClass)) {
/* Disallow services with implementation classes that are marked as @Deleted */
continue;
}
/*
* Find either a public static provider() method or a nullary constructor (or both).
* Skip providers that do not comply with requirements.
*
* See ServiceLoader#loadProvider and ServiceLoader#findStaticProviderMethod.
*/
Constructor<?> nullaryConstructor = null;
Method nullaryProviderMethod = null;
try {
/* Only look for a provider() method if provider class is in an explicit module. */
if (providerClass.getModule().isNamed() && !providerClass.getModule().getDescriptor().isAutomatic()) {
for (Method method : providerClass.getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers()) &&
method.getParameterCount() == 0 && method.getName().equals("provider")) {
if (nullaryProviderMethod == null) {
nullaryProviderMethod = method;
} else {
/* There must be at most one public static provider() method. */
nullaryProviderMethod = null;
break;
}
}
}
}
Constructor<?> constructor = providerClass.getDeclaredConstructor();
if (Modifier.isPublic(constructor.getModifiers())) {
nullaryConstructor = constructor;
}
} catch (NoSuchMethodException | SecurityException | LinkageError e) {
// ignore
}
if (nullaryConstructor != null || nullaryProviderMethod != null) {
RuntimeReflection.register(providerClass);
if (nullaryConstructor != null) {
/*
* Registering a constructor with
* RuntimeReflection.registerConstructorLookup(providerClass) does not produce
* the same behavior as using RuntimeReflection.register(nullaryConstructor). In
* the first case, the constructor is marked for query purposes only, so this
* if-statement cannot be eliminated.
*
*/
RuntimeReflection.register(nullaryConstructor);
} else {
/*
* If there's no nullary constructor, register it as negative lookup to avoid
* throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerConstructorLookup(providerClass);
}
if (nullaryProviderMethod != null) {
RuntimeReflection.register(nullaryProviderMethod);
} else {
/*
* If there's no declared public provider() method, register it as negative
* lookup to avoid throwing a MissingReflectionRegistrationError at run time.
*/
RuntimeReflection.registerMethodLookup(providerClass, "provider");
}
}
/*
* Register the provider in both cases: when it is JCA-compliant (has a nullary
* constructor or a provider method) or when it lacks both. If neither is present, a
* ServiceConfigurationError will be thrown at runtime, consistent with HotSpot
* behavior.
*/
registeredProviders.add(provider);
}
if (!registeredProviders.isEmpty()) {
String serviceResourceLocation = "META-INF/services/" + serviceProvider.getName();
byte[] serviceFileData = registeredProviders.stream().collect(Collectors.joining("\n")).getBytes(StandardCharsets.UTF_8);
RuntimeResourceAccess.addResource(access.getApplicationClassLoader().getUnnamedModule(), serviceResourceLocation, serviceFileData);
}
}
}
| accessImpl |
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;
import org.gradle.util.GradleVersion;
import org.springframework.boot.gradle.tasks.bundling.ResolvedDependencies.DependencyDescriptor;
import org.springframework.boot.loader.tools.DefaultLaunchScript;
import org.springframework.boot.loader.tools.FileUtils;
import org.springframework.boot.loader.tools.JarModeLibrary;
import org.springframework.boot.loader.tools.Layer;
import org.springframework.boot.loader.tools.LayersIndex;
import org.springframework.boot.loader.tools.LibraryCoordinates;
import org.springframework.boot.loader.tools.LoaderImplementation;
import org.springframework.boot.loader.tools.NativeImageArgFile;
import org.springframework.boot.loader.tools.ReachabilityMetadataProperties;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* A {@link CopyAction} for creating a Spring Boot zip archive (typically a jar or war).
* Stores jar files without compression as required by Spring Boot's loader.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Scott Frederick
*/
class BootZipCopyAction implements CopyAction {
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = OffsetDateTime.of(1980, 2, 1, 0, 0, 0, 0, ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern
.compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*",
".*"));
private final File output;
private final Manifest manifest;
private final boolean preserveFileTimestamps;
private final Integer dirMode;
private final Integer fileMode;
private final boolean includeDefaultLoader;
private final String jarmodeToolsLocation;
private final Spec<FileTreeElement> requiresUnpack;
private final Spec<FileTreeElement> exclusions;
private final LaunchScriptConfiguration launchScript;
private final Spec<FileCopyDetails> librarySpec;
private final Function<FileCopyDetails, ZipCompression> compressionResolver;
private final String encoding;
private final ResolvedDependencies resolvedDependencies;
private final boolean supportsSignatureFile;
private final LayerResolver layerResolver;
private final LoaderImplementation loaderImplementation;
BootZipCopyAction(File output, Manifest manifest, boolean preserveFileTimestamps, Integer dirMode, Integer fileMode,
boolean includeDefaultLoader, String jarmodeToolsLocation, Spec<FileTreeElement> requiresUnpack,
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript, Spec<FileCopyDetails> librarySpec,
Function<FileCopyDetails, ZipCompression> compressionResolver, String encoding,
ResolvedDependencies resolvedDependencies, boolean supportsSignatureFile, LayerResolver layerResolver,
LoaderImplementation loaderImplementation) {
this.output = output;
this.manifest = manifest;
this.preserveFileTimestamps = preserveFileTimestamps;
this.dirMode = dirMode;
this.fileMode = fileMode;
this.includeDefaultLoader = includeDefaultLoader;
this.jarmodeToolsLocation = jarmodeToolsLocation;
this.requiresUnpack = requiresUnpack;
this.exclusions = exclusions;
this.launchScript = launchScript;
this.librarySpec = librarySpec;
this.compressionResolver = compressionResolver;
this.encoding = encoding;
this.resolvedDependencies = resolvedDependencies;
this.supportsSignatureFile = supportsSignatureFile;
this.layerResolver = layerResolver;
this.loaderImplementation = loaderImplementation;
}
@Override
public WorkResult execute(CopyActionProcessingStream copyActions) {
try {
writeArchive(copyActions);
return WorkResults.didWork(true);
}
catch (IOException ex) {
throw new GradleException("Failed to create " + this.output, ex);
}
}
private void writeArchive(CopyActionProcessingStream copyActions) throws IOException {
OutputStream output = new FileOutputStream(this.output);
try {
writeArchive(copyActions, output);
}
finally {
closeQuietly(output);
}
}
private void writeArchive(CopyActionProcessingStream copyActions, OutputStream output) throws IOException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(output);
writeLaunchScriptIfNecessary(zipOutput);
try {
setEncodingIfNecessary(zipOutput);
[MASK] processor = new [MASK] (zipOutput);
copyActions.process(processor::process);
processor.finish();
}
finally {
closeQuietly(zipOutput);
}
}
private void writeLaunchScriptIfNecessary(ZipArchiveOutputStream outputStream) {
if (this.launchScript == null) {
return;
}
try {
File file = this.launchScript.getScript();
Map<String, String> properties = this.launchScript.getProperties();
outputStream.writePreamble(new DefaultLaunchScript(file, properties).toByteArray());
this.output.setExecutable(true);
}
catch (IOException ex) {
throw new GradleException("Failed to write launch script to " + this.output, ex);
}
}
private void setEncodingIfNecessary(ZipArchiveOutputStream zipOutputStream) {
if (this.encoding != null) {
zipOutputStream.setEncoding(this.encoding);
}
}
private void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
}
catch (IOException ex) {
// Ignore
}
}
/**
* Internal process used to copy {@link FileCopyDetails file details} to the zip file.
*/
private class [MASK] {
private final ZipArchiveOutputStream out;
private final LayersIndex layerIndex;
private LoaderZipEntries.WrittenEntries writtenLoaderEntries;
private final Set<String> writtenDirectories = new LinkedHashSet<>();
private final Map<String, FileCopyDetails> writtenLibraries = new LinkedHashMap<>();
private final Map<String, FileCopyDetails> reachabilityMetadataProperties = new HashMap<>();
[MASK] (ZipArchiveOutputStream out) {
this.out = out;
this.layerIndex = (BootZipCopyAction.this.layerResolver != null)
? new LayersIndex(BootZipCopyAction.this.layerResolver.getLayers()) : null;
}
void process(FileCopyDetails details) {
if (skipProcessing(details)) {
return;
}
try {
writeLoaderEntriesIfNecessary(details);
if (details.isDirectory()) {
processDirectory(details);
}
else {
processFile(details);
}
}
catch (IOException ex) {
throw new GradleException("Failed to add " + details + " to " + BootZipCopyAction.this.output, ex);
}
}
private boolean skipProcessing(FileCopyDetails details) {
return BootZipCopyAction.this.exclusions.isSatisfiedBy(details)
|| (this.writtenLoaderEntries != null && this.writtenLoaderEntries.isWrittenDirectory(details));
}
private void processDirectory(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name + '/');
prepareEntry(entry, name, getTime(details), getFileMode(details));
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
this.writtenDirectories.add(name);
}
private void processFile(FileCopyDetails details) throws IOException {
String name = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(details), getFileMode(details));
ZipCompression compression = BootZipCopyAction.this.compressionResolver.apply(details);
if (compression == ZipCompression.STORED) {
prepareStoredEntry(details, entry);
}
this.out.putArchiveEntry(entry);
details.copyTo(this.out);
this.out.closeArchiveEntry();
if (BootZipCopyAction.this.librarySpec.isSatisfiedBy(details)) {
this.writtenLibraries.put(name, details);
}
if (REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN.matcher(name).matches()) {
this.reachabilityMetadataProperties.put(name, details);
}
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(details);
this.layerIndex.add(layer, name);
}
}
private void writeParentDirectoriesIfNecessary(String name, Long time) throws IOException {
String parentDirectory = getParentDirectory(name);
if (parentDirectory != null && this.writtenDirectories.add(parentDirectory)) {
ZipArchiveEntry entry = new ZipArchiveEntry(parentDirectory + '/');
prepareEntry(entry, parentDirectory, time, getDirMode());
this.out.putArchiveEntry(entry);
this.out.closeArchiveEntry();
}
}
private String getParentDirectory(String name) {
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1) {
return null;
}
return name.substring(0, lastSlash);
}
void finish() throws IOException {
writeLoaderEntriesIfNecessary(null);
writeJarToolsIfNecessary();
writeSignatureFileIfNecessary();
writeClassPathIndexIfNecessary();
writeNativeImageArgFileIfNecessary();
// We must write the layer index last
writeLayersIndexIfNecessary();
}
private void writeLoaderEntriesIfNecessary(FileCopyDetails details) throws IOException {
if (!BootZipCopyAction.this.includeDefaultLoader || this.writtenLoaderEntries != null) {
return;
}
if (isInMetaInf(details)) {
// Always write loader entries after META-INF directory (see gh-16698)
return;
}
LoaderZipEntries loaderEntries = new LoaderZipEntries(getTime(), getDirMode(), getFileMode(),
BootZipCopyAction.this.loaderImplementation);
this.writtenLoaderEntries = loaderEntries.writeTo(this.out);
if (BootZipCopyAction.this.layerResolver != null) {
for (String name : this.writtenLoaderEntries.getFiles()) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
}
private boolean isInMetaInf(FileCopyDetails details) {
if (details == null) {
return false;
}
String[] segments = details.getRelativePath().getSegments();
return segments.length > 0 && "META-INF".equals(segments[0]);
}
private void writeJarToolsIfNecessary() throws IOException {
if (BootZipCopyAction.this.jarmodeToolsLocation != null) {
writeJarModeLibrary(BootZipCopyAction.this.jarmodeToolsLocation, JarModeLibrary.TOOLS);
}
}
private void writeJarModeLibrary(String location, JarModeLibrary library) throws IOException {
String name = location + library.getName();
writeEntry(name, ZipEntryContentWriter.fromInputStream(library.openStream()), false, (entry) -> {
try (InputStream in = library.openStream()) {
prepareStoredEntry(library.openStream(), entry);
}
});
if (BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(library);
this.layerIndex.add(layer, name);
}
}
private void writeSignatureFileIfNecessary() throws IOException {
if (BootZipCopyAction.this.supportsSignatureFile && hasSignedLibrary()) {
writeEntry("META-INF/BOOT.SF", (out) -> {
}, false);
}
}
private boolean hasSignedLibrary() throws IOException {
for (FileCopyDetails writtenLibrary : this.writtenLibraries.values()) {
if (FileUtils.isSignedJarFile(writtenLibrary.getFile())) {
return true;
}
}
return false;
}
private void writeClassPathIndexIfNecessary() throws IOException {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index");
if (classPathIndex != null) {
Set<String> libraryNames = this.writtenLibraries.keySet();
List<String> lines = libraryNames.stream().map((line) -> "- \"" + line + "\"").toList();
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(classPathIndex, writer, true);
}
}
private void writeNativeImageArgFileIfNecessary() throws IOException {
Set<String> excludes = new LinkedHashSet<>();
for (Map.Entry<String, FileCopyDetails> entry : this.writtenLibraries.entrySet()) {
DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies
.find(entry.getValue().getFile());
LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null;
FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties
.get(ReachabilityMetadataProperties.getLocation(coordinates)) : null;
if (propertiesFile != null) {
try (InputStream inputStream = propertiesFile.open()) {
ReachabilityMetadataProperties properties = ReachabilityMetadataProperties
.fromInputStream(inputStream);
if (properties.isOverridden()) {
excludes.add(entry.getKey());
}
}
}
}
NativeImageArgFile argFile = new NativeImageArgFile(excludes);
argFile.writeIfNecessary((lines) -> {
ZipEntryContentWriter writer = ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines);
writeEntry(NativeImageArgFile.LOCATION, writer, true);
});
}
private void writeLayersIndexIfNecessary() throws IOException {
if (BootZipCopyAction.this.layerResolver != null) {
Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes();
String name = (String) manifestAttributes.get("Spring-Boot-Layers-Index");
Assert.state(StringUtils.hasText(name), "Missing layer index manifest attribute");
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
writeEntry(name, this.layerIndex::writeTo, false);
}
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex)
throws IOException {
writeEntry(name, entryWriter, addToLayerIndex, ZipEntryCustomizer.NONE);
}
private void writeEntry(String name, ZipEntryContentWriter entryWriter, boolean addToLayerIndex,
ZipEntryCustomizer entryCustomizer) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
prepareEntry(entry, name, getTime(), getFileMode());
entryCustomizer.customize(entry);
this.out.putArchiveEntry(entry);
entryWriter.writeTo(this.out);
this.out.closeArchiveEntry();
if (addToLayerIndex && BootZipCopyAction.this.layerResolver != null) {
Layer layer = BootZipCopyAction.this.layerResolver.getLayer(name);
this.layerIndex.add(layer, name);
}
}
private void prepareEntry(ZipArchiveEntry entry, String name, Long time, int mode) throws IOException {
writeParentDirectoriesIfNecessary(name, time);
entry.setUnixMode(mode);
if (time != null) {
entry.setTime(DefaultTimeZoneOffset.INSTANCE.removeFrom(time));
}
}
private void prepareStoredEntry(FileCopyDetails details, ZipArchiveEntry archiveEntry) throws IOException {
prepareStoredEntry(details.open(), archiveEntry);
if (BootZipCopyAction.this.requiresUnpack.isSatisfiedBy(details)) {
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
}
}
private void prepareStoredEntry(InputStream input, ZipArchiveEntry archiveEntry) throws IOException {
new CrcAndSize(input).setUpStoredEntry(archiveEntry);
}
private Long getTime() {
return getTime(null);
}
private Long getTime(FileCopyDetails details) {
if (!BootZipCopyAction.this.preserveFileTimestamps) {
return CONSTANT_TIME_FOR_ZIP_ENTRIES;
}
if (details != null) {
return details.getLastModified();
}
return null;
}
private int getDirMode() {
return (BootZipCopyAction.this.dirMode != null) ? BootZipCopyAction.this.dirMode
: UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM;
}
private int getFileMode() {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM;
}
private int getFileMode(FileCopyDetails details) {
return (BootZipCopyAction.this.fileMode != null) ? BootZipCopyAction.this.fileMode
: UnixStat.FILE_FLAG | getPermissions(details);
}
private int getPermissions(FileCopyDetails details) {
return (GradleVersion.current().compareTo(GradleVersion.version("8.3")) >= 0)
? details.getPermissions().toUnixNumeric() : getMode(details);
}
@SuppressWarnings("deprecation")
private int getMode(FileCopyDetails details) {
return details.getMode();
}
}
/**
* Callback interface used to customize a {@link ZipArchiveEntry}.
*/
@FunctionalInterface
private interface ZipEntryCustomizer {
ZipEntryCustomizer NONE = (entry) -> {
};
/**
* Customize the entry.
* @param entry the entry to customize
* @throws IOException on IO error
*/
void customize(ZipArchiveEntry entry) throws IOException;
}
/**
* Callback used to write a zip entry data.
*/
@FunctionalInterface
private interface ZipEntryContentWriter {
/**
* Write the entry data.
* @param out the output stream used to write the data
* @throws IOException on IO error
*/
void writeTo(ZipArchiveOutputStream out) throws IOException;
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given {@link InputStream}.
* @param in the source input stream
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromInputStream(InputStream in) {
return (out) -> {
StreamUtils.copy(in, out);
in.close();
};
}
/**
* Create a new {@link ZipEntryContentWriter} that will copy content from the
* given lines.
* @param encoding the required character encoding
* @param lines the lines to write
* @return a new {@link ZipEntryContentWriter} instance
*/
static ZipEntryContentWriter fromLines(String encoding, Collection<String> lines) {
return (out) -> {
OutputStreamWriter writer = new OutputStreamWriter(out, encoding);
for (String line : lines) {
writer.append(line).append("\n");
}
writer.flush();
};
}
}
/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {
private static final int BUFFER_SIZE = 32 * 1024;
private final CRC32 crc = new CRC32();
private long size;
CrcAndSize(InputStream inputStream) throws IOException {
try (inputStream) {
load(inputStream);
}
}
private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}
void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}
}
| Processor |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.