This is an automated email from the ASF dual-hosted git repository. asf-gitbox-commits pushed a commit to branch geoapi-4.0 in repository https://gitbox.apache.org/repos/asf/sis.git
commit 88870cafb9d2a5af46d3e9d3c7e142c3aabc045d Author: jsorel <[email protected]> AuthorDate: Thu Nov 12 16:34:45 2026 +0100 feat(Process): add processing API --- .../org.apache.sis.process/main/module-info.java | 5 +- .../sis/process/DismissProcessException.java | 48 ++++ .../main/org/apache/sis/process/Process.java | 132 +++++++++ .../org/apache/sis/process/ProcessCategories.java | 312 +++++++++++++++++++++ .../org/apache/sis/process/ProcessDescriptor.java | 142 ++++++++++ .../main/org/apache/sis/process/ProcessEvent.java | 211 ++++++++++++++ .../org/apache/sis/process/ProcessException.java | 78 ++++++ .../main/org/apache/sis/process/ProcessFinder.java | 126 +++++++++ .../org/apache/sis/process/ProcessListener.java | 107 +++++++ .../apache/sis/process/RollbackableProcess.java} | 24 +- .../apache/sis/process/ProcessCategoriesTest.java | 94 +++++++ 11 files changed, 1270 insertions(+), 9 deletions(-) diff --git a/incubator/src/org.apache.sis.process/main/module-info.java b/incubator/src/org.apache.sis.process/main/module-info.java index 4d2fb131c0..06189b1b99 100644 --- a/incubator/src/org.apache.sis.process/main/module-info.java +++ b/incubator/src/org.apache.sis.process/main/module-info.java @@ -24,6 +24,7 @@ module org.apache.sis.process { // Dependencies used in public API. requires transitive org.apache.sis.referencing; - // Uncomment when the package contains at least one class. - // exports org.apache.sis.process; + exports org.apache.sis.process; + + uses org.apache.sis.process.ProcessDescriptor; } diff --git a/incubator/src/org.apache.sis.process/main/org/apache/sis/process/DismissProcessException.java b/incubator/src/org.apache.sis.process/main/org/apache/sis/process/DismissProcessException.java new file mode 100644 index 0000000000..e81af2802d --- /dev/null +++ b/incubator/src/org.apache.sis.process/main/org/apache/sis/process/DismissProcessException.java @@ -0,0 +1,48 @@ +/* + * 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.sis.process; + +/** + * Thrown when a {@linkplain Process process} is dismissed. + * + * @author Mehdi Sidhoum (Geomatys). + */ +public class DismissProcessException extends ProcessException { + + /** + * Creates a new exception with the specified detail message. + * + * @param message The details message, or {@code null}. + * @param process The process that failed, or {@code null}. + */ + public DismissProcessException(String message, Process process) { + super(message, process); + } + + /** + * Creates a new exception with the specified detail message and cause. + * + * @param message The details message, or {@code null}. + * @param process The process that failed, or {@code null}. + * @param cause The cause, or {@code null}. + */ + public DismissProcessException(String message, Process process, Throwable cause) { + super(message, process, cause); + } + + +} diff --git a/incubator/src/org.apache.sis.process/main/org/apache/sis/process/Process.java b/incubator/src/org.apache.sis.process/main/org/apache/sis/process/Process.java new file mode 100644 index 0000000000..7fca9e7635 --- /dev/null +++ b/incubator/src/org.apache.sis.process/main/org/apache/sis/process/Process.java @@ -0,0 +1,132 @@ +/* + * 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.sis.process; + +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import org.opengis.metadata.lineage.ProcessStep; +import org.opengis.parameter.ParameterValueGroup; + + +/** + * An operation applied to some given data to achieve whatever analyze or model transformation. + * {@code Process} instances are created by {@link ProcessDescriptor} and can be executed in an + * {@link ExecutorService}. + * + * <h2>Event notifications</h2> + * All {@code Process} implementations <strong>must</strong> notify all their {@link ProcessListener}s + * when the {@link #call()} method is starting and when it is terminating, either successfully or on + * failure. + * + * @author Johann Sorel (Geomatys) + */ +public interface Process extends Callable<ParameterValueGroup> { + /** + * Description of the process algorithm and its input/output parameters. + * The returned value is the descriptor that created this {@code Process} instance. + * + * @return The process descriptor. + */ + ProcessDescriptor getDescriptor(); + + /** + * Returns the input values given to the {@link ProcessDescriptor#createProcess(ParameterValueGroup)} method. + * The {@linkplain ParameterValueGroup#getDescriptor() descriptor} of those parameters is the instance returned by + * <code>{@linkplain #getDescriptor()}.{@linkplain ProcessDescriptor#getInputDescriptor() getInputDescriptor()}</code>. + * + * @return The input parameter values (never {@code null}). + * + * @see ProcessDescriptor#getInputDescriptor() + * @see ProcessStep#getSources() + */ + ParameterValueGroup getInput(); + + /** + * Executes the process and returns the output in a new {@link ParameterValueGroup}. + * + * <div class="note"><b>Note:</b> + * returning a parameter object may sound strange, since parameters are usually for + * input values rather than output values. Note however that ISO 19115 does the same, + * since the {@code ProcessStep} outputs is a collection of {@code Source} objects. + * In both cases, the outputs may be used as inputs in the next step of a process chain.</div> + * + * <p>The following relations shall hold:</p> + * <ul> + * <li>The {@linkplain ParameterValueGroup#getDescriptor() descriptor} of the returned parameters is the same instance than + * <code>{@linkplain #getDescriptor()}.{@linkplain ProcessDescriptor#getOutputDescriptor() getOutputDescriptor()}</code>.</li> + * <li>When the process is {@linkplain ProcessListener#completed completed}, the {@link ProcessEvent#getOutput()} value shall + * be the same than the return value of this {@code call()} method.</li> + * </ul> + * + * <h4>Event notifications</h4> + * For any {@linkplain #addListener registered listeners}, this method shall invoke the + * following methods. Note that all notification events except {@code progressing} are + * mandatory for all {@code Process} implementations. + * <ul> + * <li>{@link ProcessListener#started(ProcessEvent) started} (<em>mandatory</em>) at the beginning of this {@code call()} method;</li> + * <li>{@link ProcessListener#progressing(ProcessEvent) progressing} (<em>optional</em>) during the process execution;</li> + * <li>When this {@code call()} method is about to exit, exactly <strong>one</strong> of the following:<ul> + * <li>{@link ProcessListener#completed(ProcessEvent) completed} on success, or</li> + * <li>{@link ProcessListener#failed(ProcessEvent) failed} if an error occurred.</li></ul> + * </li> + * </ul> + * + * @return The computation results as an parameter value groups. + * @throws ProcessException if the process failed. + * + * @see ProcessDescriptor#getOutputDescriptor() + * @see ProcessStep#getOutputs() + */ + @Override + ParameterValueGroup call() throws ProcessException; + + /** + * Returns a description of the process, the geographic inputs and outputs and other metadata. + * Those metadata are suitable to processes on geographic data and may not be applicable to every kind of processes. + * If this parameter is provided, then: + * <ul> + * <li>{@link ProcessStep#getDate()} is the execution date and time of the process.</li> + * <li>{@link ProcessStep#getSources()} are the geographic {@linkplain Process#getInput() process inputs}.</li> + * <li>{@link ProcessStep#getOutputs()} are the geographic {@linkplain Process#call() process outputs}.</li> + * <li>{@link ProcessStep#getProcessingInformation()} is the {@linkplain Process#getDescriptor() process descriptor}.</li> + * </ul> + * + * @return A description of the process, the geographic inputs and outputs and other metadata. + */ + ProcessStep getMetadata(); + + /** + * Adds a listener to the list of objects to inform about the process progress. + * + * @param listener The listener to add. + */ + void addListener(ProcessListener listener); + + /** + * Removes a listener from the list of objects to inform about the process progress. + * + * @param listener The listener to remove. + */ + void removeListener(ProcessListener listener); + + /** + * Returns all registered listeners, or an empty array if none. + * + * @return The registered listeners. + */ + ProcessListener[] getListeners(); +} diff --git a/incubator/src/org.apache.sis.process/main/org/apache/sis/process/ProcessCategories.java b/incubator/src/org.apache.sis.process/main/org/apache/sis/process/ProcessCategories.java new file mode 100644 index 0000000000..d14282bdf7 --- /dev/null +++ b/incubator/src/org.apache.sis.process/main/org/apache/sis/process/ProcessCategories.java @@ -0,0 +1,312 @@ +/* + * 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.sis.process; + +import java.io.Serializable; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import org.opengis.util.GenericName; +import org.opengis.util.InternationalString; +import org.apache.sis.util.AbstractInternationalString; +import org.apache.sis.util.DefaultInternationalString; +import org.apache.sis.util.iso.Names; +import org.apache.sis.util.iso.Types; + + +/** + * Common categories for organizing processes in a tree, such as a toolbox. + * A category is a {@link GenericName} where each {@linkplain GenericName#getParsedNames() component} + * is a folder of the tree, from the root ({@linkplain GenericName#head() head}) to the folder containing + * the process ({@linkplain GenericName#tip() tip}). For each component: + * + * <ul> + * <li>{@code toString()} returns a locale-independent code identifying the folder. + * Folders declared by different processes are merged when their codes are equal.</li> + * <li>{@code toInternationalString()} returns the label to show to users.</li> + * </ul> + * + * The {@code toString()} value of a whole category is the path of codes separated by {@code '/'}, + * for example {@code "raster/terrain"} for {@link #RASTER_TERRAIN}. + * Processes which do not fit in the categories defined here can use their own categories, + * created by {@link #create(GenericName, String, CharSequence)} either as roots or as + * sub-categories of the constants defined in this class. + * + * @author Johann Sorel (Geomatys) + * + * @see ProcessDescriptor#getCategory() + */ +public final class ProcessCategories { + /** + * The separator between the components of a category path. + */ + private static final String SEPARATOR = "/"; + + /** + * Processes working on vector data, for example features. + */ + public static final GenericName VECTOR = root("vector", "Vector", "Vecteur"); + + /** + * Processes creating or modifying geometries one by one, + * for example buffer, centroid, simplification or convex hull. + */ + public static final GenericName VECTOR_GEOMETRY = child(VECTOR, "geometry", "Geometry", "Géométrie"); + + /** + * Processes combining the geometries of two or more layers, + * for example clip, intersection, union or difference. + */ + public static final GenericName VECTOR_OVERLAY = child(VECTOR, "overlay", "Overlay", "Superposition"); + + /** + * Processes selecting or extracting a subset of features, + * for example by attribute values or by spatial relationship. + */ + public static final GenericName VECTOR_SELECTION = child(VECTOR, "selection", "Selection", "Sélection"); + + /** + * Processes working on feature attributes, + * for example computing, renaming or joining attributes. + */ + public static final GenericName VECTOR_TABLE = child(VECTOR, "table", "Attribute table", "Table attributaire"); + + /** + * Processes computing statistics or relationships on features, + * for example counting points in polygons or finding nearest neighbors. + */ + public static final GenericName VECTOR_ANALYSIS = child(VECTOR, "analysis", "Analysis", "Analyse"); + + /** + * Processes creating new vector data, + * for example regular grids or random points. + */ + public static final GenericName VECTOR_CREATION = child(VECTOR, "creation", "Creation", "Création"); + + /** + * Processes working on raster data, for example grid coverages. + */ + public static final GenericName RASTER = root("raster", "Raster", "Raster"); + + /** + * Processes computing cell values from expressions on one or more rasters, + * for example band arithmetic or conditional expressions. + */ + public static final GenericName RASTER_ALGEBRA = child(RASTER, "algebra", "Map algebra", "Algèbre de cartes"); + + /** + * Processes computing statistics or classifications on rasters, + * for example zonal statistics or reclassification. + */ + public static final GenericName RASTER_ANALYSIS = child(RASTER, "analysis", "Analysis", "Analyse"); + + /** + * Processes working on elevation models, + * for example slope, aspect, hillshade or viewshed. + */ + public static final GenericName RASTER_TERRAIN = child(RASTER, "terrain", "Terrain analysis", "Analyse de terrain"); + + /** + * Processes extracting a part of a raster, + * for example clip by extent, by mask or band selection. + */ + public static final GenericName RASTER_EXTRACTION = child(RASTER, "extraction", "Extraction", "Extraction"); + + /** + * Processes creating a raster from sparse values, + * for example inverse distance weighting or kriging. + */ + public static final GenericName RASTER_INTERPOLATION = child(RASTER, "interpolation", "Interpolation", "Interpolation"); + + /** + * Processes working on remote sensing images, + * for example radiometric correction, pansharpening or image classification. + */ + public static final GenericName IMAGERY = root("imagery", "Imagery", "Imagerie"); + + /** + * Processes working on point clouds, + * for example LiDAR filtering, classification or thinning. + */ + public static final GenericName POINT_CLOUD = root("pointCloud", "Point cloud", "Nuage de points"); + + /** + * Processes working on meshes and other three-dimensional geometries, + * for example triangulation or mesh simplification. + */ + public static final GenericName MESH = root("mesh", "Mesh", "Maillage"); + + /** + * Processes working on time series, + * for example temporal aggregation or gap filling. + */ + public static final GenericName TEMPORAL = root("temporal", "Temporal", "Temporel"); + + /** + * Processes working on coordinate reference systems, + * for example reprojection or datum shift. + */ + public static final GenericName REFERENCING = root("referencing", + "Projections and transformations", "Projections et transformations"); + + /** + * Processes converting data from one format or model to another, + * for example raster to vector or file format conversion. + */ + public static final GenericName CONVERSION = root("conversion", "Conversion", "Conversion"); + + /** + * Processes managing datasets and their metadata, + * for example copying, merging, indexing or editing metadata. + */ + public static final GenericName DATA_MANAGEMENT = root("dataManagement", "Data management", "Gestion des données"); + + /** + * Processes preparing data for map production, + * for example generalization, labelling or symbology. + */ + public static final GenericName CARTOGRAPHY = root("cartography", "Cartography", "Cartographie"); + + /** + * Do not allow instantiation of this class. + */ + private ProcessCategories() { + } + + /** + * Creates a root category with English and French labels. + * + * @param code locale-independent identifier of the category. + * @param english label in English, also used as the fallback for languages other than French. + * @param french label in French. + * @return the root category. + */ + private static GenericName root(final String code, final String english, final String french) { + return create(null, code, i18n(english, french)); + } + + /** + * Creates a sub-category with English and French labels. + * + * @param parent the parent category. + * @param code locale-independent identifier of the category. + * @param english label in English, also used as the fallback for languages other than French. + * @param french label in French. + * @return the sub-category. + */ + private static GenericName child(final GenericName parent, final String code, final String english, final String french) { + return create(parent, code, i18n(english, french)); + } + + /** + * Returns a label with an English text used as the fallback for all languages except French. + * + * @param english label in English. + * @param french label in French. + * @return the localized label. + */ + private static InternationalString i18n(final String english, final String french) { + return new DefaultInternationalString(Map.of(Locale.ROOT, english, Locale.FRENCH, french)); + } + + /** + * Creates a category with the given code and label. + * The {@code code} is a locale-independent identifier used for merging folders declared by different processes. + * It is the value returned by {@code toString()} on the {@linkplain GenericName#tip() tip} of the returned name. + * The {@code label} is the text to show to users, and can be an {@link InternationalString} for localization. + * + * @param parent the parent category, or {@code null} for creating a root category. + * @param code locale-independent identifier of the category. Shall not contain the {@code '/'} character. + * @param label text to show to users, or {@code null} for using the code as the label. + * @return the category. + * @throws IllegalArgumentException if the code is empty or contains the {@code '/'} character. + */ + public static GenericName create(final GenericName parent, final String code, final CharSequence label) { + Objects.requireNonNull(code, "code"); + if (code.isBlank() || code.contains(SEPARATOR)) { + throw new IllegalArgumentException("Illegal category code: \"" + code + "\"."); + } + final var name = new Label(code, (label != null) ? Types.toInternationalString(label) : null); + return (parent != null) ? Names.createScopedName(parent, SEPARATOR, name) + : Names.createLocalName(null, SEPARATOR, name); + } + + /** + * A category name component which is a code in the unlocalized (root) locale, + * and a label in all other locales. + */ + private static final class Label extends AbstractInternationalString implements Serializable { + /** + * For cross-version compatibility. + */ + private static final long serialVersionUID = 6153028412436591471L; + + /** + * Locale-independent identifier of the category. + */ + private final String code; + + /** + * Text to show to users, or {@code null} for using the code. + */ + @SuppressWarnings("serial") // Most SIS implementations are serializable. + private final InternationalString label; + + /** + * Creates a new component. + * + * @param code locale-independent identifier of the category. + * @param label text to show to users, or {@code null} for using the code. + */ + Label(final String code, final InternationalString label) { + this.code = code; + this.label = label; + } + + /** + * Returns the code if the given locale is {@code null} or {@link Locale#ROOT}, + * or the label in the given locale otherwise. + */ + @Override + public String toString(final Locale locale) { + if (label == null || locale == null || locale.equals(Locale.ROOT)) { + return code; + } + return label.toString(locale); + } + + /** + * Compares this component with the given object for equality. + */ + @Override + public boolean equals(final Object other) { + if (other instanceof Label) { + final var that = (Label) other; + return code.equals(that.code) && Objects.equals(label, that.label); + } + return false; + } + + /** + * Returns a hash code value for this component. + */ + @Override + public int hashCode() { + return code.hashCode() + 31 * Objects.hashCode(label); + } + } +} diff --git a/incubator/src/org.apache.sis.process/main/org/apache/sis/process/ProcessDescriptor.java b/incubator/src/org.apache.sis.process/main/org/apache/sis/process/ProcessDescriptor.java new file mode 100644 index 0000000000..df4faaa4da --- /dev/null +++ b/incubator/src/org.apache.sis.process/main/org/apache/sis/process/ProcessDescriptor.java @@ -0,0 +1,142 @@ +/* + * 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.sis.process; + + +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; + +import org.opengis.metadata.Identifier; +import org.opengis.metadata.lineage.Processing; +import org.opengis.metadata.lineage.ProcessStep; +import org.opengis.parameter.ParameterValueGroup; +import org.opengis.parameter.ParameterDescriptorGroup; +import org.opengis.util.GenericName; +import org.opengis.util.InternationalString; + + +/** + * Description of a {@linkplain Process process} algorithm and its input/output parameters. + * This interface extends the ISO 19115 {@link Processing} interface, which provide human-readable + * information about the process. In addition to the ISO/OGC interface, {@code ProcessDescriptor} + * provides: + * <ul> + * <li>A more machine-usable description of the input and output parameters + * (including source data and output data).</li> + * <li>A method for creating new {@link Process} instances which can be run in + * an {@link ExecutorService}.</li> + * </ul> + * <p> + * {@code ProcessDescriptor} implementations are declared as services for {@link java.util.ServiceLoader} + * and can be found by name with {@link ProcessFinder}. + * + * @author Johann Sorel (Geomatys) + * @author Quentin Boileau (Geomatys) + */ +public interface ProcessDescriptor extends Processing { + /** + * Information to identify the processing package that run the process. + * The identifier {@linkplain Identifier#getCode() code} is the name used by + * {@link ProcessFinder} for finding this descriptor, and the identifier + * {@linkplain Identifier#getCodeSpace() code space} or {@linkplain Identifier#getAuthority() authority} + * identifies the processing package. + * + * @return Identifier of the processing package that run the process. + */ + @Override + Identifier getIdentifier(); + + /** + * Process name to display in user interfaces. + * This name is not intended to identify the process; + * identification shall use the process {@linkplain #getIdentifier() identifier} instead. + * + * @return The processing name to display in user interfaces, or {@code null} if none. + */ + InternationalString getDisplayName(); + + /** + * Category where to show this process in a tree of processes, such as a toolbox. + * Each {@linkplain GenericName#getParsedNames() component} of the returned name is a folder of the tree, + * from the root ({@linkplain GenericName#head() head}) to the folder containing this process + * ({@linkplain GenericName#tip() tip}). The {@code toString()} value of each component is a + * locale-independent code identifying the folder, and {@code toInternationalString()} is the label + * to show to users. Common categories are defined in {@link ProcessCategories}. + * + * <p>The default implementation returns {@code null}.</p> + * + * @return category of this process, or {@code null} if uncategorized. + * + * @see ProcessCategories + */ + default GenericName getCategory() { + return null; + } + + /** + * Additional details about the processing procedures. + * + * @return The processing procedures, or {@code null} if none. + */ + @Override + InternationalString getProcedureDescription(); + + /** + * Returns a description of the input parameters. The {@linkplain ParameterValueGroup parameter + * values} include both the source data (for example the source images) and the parameters that + * configure the operation applied on those data. + * <p> + * This is the descriptor of the parameter values returned by {@link Process#getInput()}. + * + * @return Description of the input parameters. + * + * @see Process#getInput() + * @see ProcessStep#getSources() + */ + ParameterDescriptorGroup getInputDescriptor(); + + /** + * Returns a description of the output parameters. + * This is the descriptor of the parameter values returned by {@link Process#call()}. + * Those {@linkplain ParameterValueGroup parameter values} include output data + * (for example the output images) and optionally some metadata related to those outputs + * (for example statistics). + * + * @return Description of the output parameters. + * + * @see Process#call() + * @see ProcessStep#getOutputs() + */ + ParameterDescriptorGroup getOutputDescriptor(); + + /** + * Creates a new process initialized with the given input parameter values. The returned + * process is not yet started. To start the process, callers must give the process to an + * {@link ExecutorService} or invoke {@link Process#call()} explicitely. + * <p> + * The input parameters are typically created by calls to + * <code>{@linkplain #getInputDescriptor()}.{@linkplain ParameterDescriptorGroup#createValue() + * createValue()}</code>. Then the parameter values shall be set before to be given to this + * {@code createProcess} method. + * + * @param input The input parameters. + * @return A new un-started process which will use the given input parameter values. + * + * @see ExecutorService#submit(Callable) + */ + Process createProcess(ParameterValueGroup input); +} diff --git a/incubator/src/org.apache.sis.process/main/org/apache/sis/process/ProcessEvent.java b/incubator/src/org.apache.sis.process/main/org/apache/sis/process/ProcessEvent.java new file mode 100644 index 0000000000..a31d1c4a08 --- /dev/null +++ b/incubator/src/org.apache.sis.process/main/org/apache/sis/process/ProcessEvent.java @@ -0,0 +1,211 @@ +/* + * 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.sis.process; + +import java.util.EventObject; +import org.opengis.util.InternationalString; +import org.opengis.parameter.ParameterValueGroup; +import org.apache.sis.util.iso.Types; + + +/** + * Event sent by a running {@linkplain Process process} to its {@linkplain ProcessListener listeners}. + * This event contains an optional user-friendly {@linkplain #getTask() task description} together + * with the {@linkplain #getProgress() task progression} as a percentage. In addition the event can + * contains one of the following: + * <ul> + * <li>A {@link ParameterValueGroup} which contain either the final calculation result when + * the process {@linkplain ProcessListener#completed completed}, or intermediate values + * while the process is still {@linkplain ProcessListener#progressing progressing}.</li> + * <li>An {@link Exception} which describe either the fatal error why the process + * {@linkplain ProcessListener#failed failed}, or non-fatal warnings while the process + * is still {@linkplain ProcessListener#progressing progressing}.</li> + * </ul> + * + * @author Johann Sorel (Geomatys) + */ +public class ProcessEvent extends EventObject { + /** + * For cross-version compatibility. + */ + private static final long serialVersionUID = 622026012845207483L; + + /** + * A message that describe the task under execution, or {@code null} if none. + * + * @see #getTask() + */ + private final InternationalString task; + + /** + * The current progress as a percent completed, from 0 to 100 inclusive. + * The {@link Float#NaN NaN} value means that the process is in an undetermined state. + */ + private final float progress; + + /** + * An intermediate calculation or the final result to be returned by {@link #getOutput()}, + * or {@code null} if none. + */ + private final ParameterValueGroup output; + + /** + * An error or warning that occurred while executing the task, or {@code null} if none. + * The exception is considered fatal if this {@code ProcessEvent} was given to the + * {@link ProcessListener#failed(ProcessEvent)} method. Otherwise the exception is + * considered as a warning only. + */ + private final Exception exception; + + /** + * Creates a new event with the given source but no message, no exception and an + * undetermined progress state. + * + * @param source The source of this event. + */ + public ProcessEvent(final Process source) { + super(source); + this.progress = Float.NaN; + this.task = null; + this.exception = null; + this.output = null; + } + + /** + * Creates a new event with the given source, task and progress. + * + * @param source The source of this event. + * @param task A message that describe the task under execution, or {@code null} if none. + * @param progress The progress as a number between 0 and 100, or {@link Float#NaN} if undetermined. + */ + public ProcessEvent(final Process source, final CharSequence task, final float progress) { + super(source); + this.progress = progress; + this.task = Types.toInternationalString(task); + this.exception = null; + this.output = null; + } + + /** + * Creates a new event with the given source, task, progress and output. + * The output may be an intermediate calculation, or the final result. + * + * @param source The source of this event. + * @param task A message that describe the task under execution, or {@code null} if none. + * @param progress The progress as a number between 0 and 100, or {@link Float#NaN} if undetermined. + * @param output The output (intermediate calculation of final result), or {@code null} if none. + */ + public ProcessEvent(final Process source, final CharSequence task, final float progress, final ParameterValueGroup output) { + super(source); + this.progress = progress; + this.task = Types.toInternationalString(task); + this.exception = null; + this.output = output; + } + + /** + * Creates a new event with the given source, task, progress and exception. + * + * @param source The source of this event. + * @param task A message that describe the task under execution, or {@code null} if none. + * @param progress The progress as a number between 0 and 100, or {@link Float#NaN} if undetermined. + * @param exception An error or warning that occurred while executing the task, or {@code null} if none. + */ + public ProcessEvent(final Process source, final CharSequence task, final float progress, final Exception exception) { + super(source); + this.progress = progress; + this.task = Types.toInternationalString(task); + this.exception = exception; + this.output = null; + } + + /** + * Returns the source of this event. + */ + @Override + public Process getSource() { + return (Process) super.getSource(); + } + + /** + * Returns a message that describes the task under execution, or {@code null} if none. + * The message may contain user friendly information provided by the process. This message + * may be show in a dialog box or elsewhere, at listener choice. + * + * @return A message that describe the tasks under execution, or {@code null} if none. + */ + public InternationalString getTask() { + return task; + } + + /** + * Returns the current progress as a percent completed, from 0 to 100 inclusive. + * The {@link Float#NaN NaN} value means that the process is in an undetermined state. + * + * @return The current progress from 0 to 100 inclusive, or {@link Float#NaN} if undetermined. + */ + public float getProgress() { + return progress; + } + + /** + * Returns the output, which may be an intermediate calculation or the final result. + * More specifically: + * <ul> + * <li>If the event has been given to {@link ProcessListener#progressing(ProcessEvent)} + * then the output (if non-null) is an intermediate calculation.</li> + * <li>If the event has been given to {@link ProcessListener#completed(ProcessEvent)} + * then the output is the same final result than the one returned by + * {@link Process#call()}.</li> + * </ul> + * + * @return The intermediate calculation (when {@linkplain ProcessListener#progressing progressing}) + * or the final result (when {@linkplain ProcessListener#completed completed}), + * or {@code null} if none. + */ + public ParameterValueGroup getOutput() { + return output; + } + + /** + * Returns an error or warning that occurred while executing the task, or {@code null} if none. + * The exception is considered fatal if this {@code ProcessEvent} was given to the + * {@link ProcessListener#failed(ProcessEvent)} method. Otherwise the exception is + * considered as a warning only. + * + * @return Error or warning that occurred while executing the task, or {@code null} if none. + */ + public Exception getException() { + return exception; + } + + /** + * Returns a string representation of this event. + */ + @Override + public String toString() { + final StringBuilder buffer = new StringBuilder(getClass().getSimpleName()); + buffer.append("[source=").append(source); + if (task != null) { + buffer.append(", task=\"").append(task).append('"'); + } + if (!Float.isNaN(progress)) { + buffer.append(", progress=").append(progress).append('%'); + } + return buffer.append(']').toString(); + } +} diff --git a/incubator/src/org.apache.sis.process/main/org/apache/sis/process/ProcessException.java b/incubator/src/org.apache.sis.process/main/org/apache/sis/process/ProcessException.java new file mode 100644 index 0000000000..96320a81eb --- /dev/null +++ b/incubator/src/org.apache.sis.process/main/org/apache/sis/process/ProcessException.java @@ -0,0 +1,78 @@ +/* + * 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.sis.process; + +import org.opengis.metadata.Identifier; + + +/** + * Thrown when a {@linkplain Process process} failed. + * + * @author Martin Desruisseaux (Geomatys) + */ +public class ProcessException extends Exception { + /** + * For cross-version compatibility. + */ + private static final long serialVersionUID = -9009593453460083634L; + + /** + * The process identifier, or {@code null}. We retain only the identifier rather than + * a full {@link Process} object because the process may not be serializable, or may + * be associated with large amount of data that we don't want to serialize. + */ + private final Identifier processId; + + /** + * Creates a new exception with the specified detail message. + * + * @param message The details message, or {@code null}. + * @param process The process that failed, or {@code null}. + */ + public ProcessException(final String message, final Process process) { + this(message, process, null); + } + + /** + * Creates a new exception with the specified detail message and cause. + * + * @param message The details message, or {@code null}. + * @param process The process that failed, or {@code null}. + * @param cause The cause, or {@code null}. + */ + public ProcessException(final String message, final Process process, final Throwable cause) { + super(message, cause); + if (process != null) { + final ProcessDescriptor descriptor = process.getDescriptor(); + if (descriptor != null) { + processId = descriptor.getIdentifier(); + return; + } + } + processId = null; + } + + /** + * Returns the identifier of the process that failed, or {@code null} if this information + * is not available. + * + * @return The identifier of the process that failed, or {@code null}. + */ + public Identifier getProcessIdentifier() { + return processId; + } +} diff --git a/incubator/src/org.apache.sis.process/main/org/apache/sis/process/ProcessFinder.java b/incubator/src/org.apache.sis.process/main/org/apache/sis/process/ProcessFinder.java new file mode 100644 index 0000000000..018fe8a436 --- /dev/null +++ b/incubator/src/org.apache.sis.process/main/org/apache/sis/process/ProcessFinder.java @@ -0,0 +1,126 @@ +/* + * 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.sis.process; + +import java.util.List; +import java.util.ServiceLoader; +import org.opengis.metadata.Identifier; +import org.opengis.util.NoSuchIdentifierException; +import org.apache.sis.metadata.iso.citation.Citations; + + +/** + * Utility class for finding process descriptors. + * Descriptors are discovered with {@link ServiceLoader}. Implementations of {@link ProcessDescriptor} + * shall be declared as services, either in the {@code module-info.java} file of the module providing them: + * + * {@snippet lang="java" : + * provides org.apache.sis.process.ProcessDescriptor with com.myorg.MyProcessDescriptor; + * } + * + * or, for libraries on the class-path, in a {@code META-INF/services/org.apache.sis.process.ProcessDescriptor} file. + * Descriptors are loaded at the first call of a {@code ProcessFinder} method, then cached. + * Invoke {@link #scanForPlugins()} for discarding the cache. + * + * <h2>Usage example</h2> + * {@snippet lang="java" : + * // Get all descriptors. + * List<ProcessDescriptor> descriptors = ProcessFinder.getProcessDescriptors(); + * + * // Get a descriptor by its name, regardless of the authority. + * ProcessDescriptor descriptor = ProcessFinder.getProcessDescriptor("myProcessName"); + * + * // Get a descriptor by its name in the namespace of a specific authority. + * ProcessDescriptor descriptor = ProcessFinder.getProcessDescriptor("myAuthority", "myProcessName"); + * } + * + * @author Johann Sorel (Geomatys) + * @author Quentin Boileau (Geomatys) + */ +public final class ProcessFinder { + /** + * All process descriptors found by the service loader, + * or {@code null} if not yet loaded or if a rescan has been requested. + */ + private static List<ProcessDescriptor> descriptors; + + /** + * Do not allow instantiation of this class. + */ + private ProcessFinder() { + } + + /** + * Returns all process descriptors declared as services. + * + * @return all available process descriptors (unmodifiable). + */ + public static synchronized List<ProcessDescriptor> getProcessDescriptors() { + if (descriptors == null) { + descriptors = ServiceLoader.load(ProcessDescriptor.class).stream().map(ServiceLoader.Provider::get).toList(); + } + return descriptors; + } + + /** + * Returns the process descriptor of the given name, regardless of its authority. + * If many authorities provide a process of the given name, the first one found is returned. + * + * @param name {@linkplain Identifier#getCode() code} of the process descriptor identifier. + * @return the process descriptor (never null). + * @throws NoSuchIdentifierException if no descriptor exists for the given name. + */ + public static ProcessDescriptor getProcessDescriptor(final String name) throws NoSuchIdentifierException { + return getProcessDescriptor(null, name); + } + + /** + * Returns the process descriptor of the given name in the namespace of the given authority. + * The authority is compared to the {@linkplain Identifier#getCodeSpace() code space} and to the + * {@linkplain Identifier#getAuthority() authority} identifiers of the process descriptor identifier. + * + * @param authority authority of the process, or {@code null} or blank for searching in all authorities. + * @param name {@linkplain Identifier#getCode() code} of the process descriptor identifier. + * @return the process descriptor (never null). + * @throws NoSuchIdentifierException if no descriptor exists for the given authority and name. + */ + public static ProcessDescriptor getProcessDescriptor(String authority, final String name) throws NoSuchIdentifierException { + if (authority != null && authority.isBlank()) { + authority = null; + } + for (final ProcessDescriptor candidate : getProcessDescriptors()) { + final Identifier id = candidate.getIdentifier(); + if (id != null && id.getCode().equals(name)) { + if (authority == null || authority.equalsIgnoreCase(id.getCodeSpace()) + || Citations.identifierMatches(id.getAuthority(), authority)) + { + return candidate; + } + } + } + final String code = (authority != null) ? authority + ':' + name : name; + throw new NoSuchIdentifierException("No process for the given identifier.", code); + } + + /** + * Discards the cached list of process descriptors. + * Services will be searched again at the next call of a {@code ProcessFinder} method. + */ + public static synchronized void scanForPlugins() { + descriptors = null; + } +} diff --git a/incubator/src/org.apache.sis.process/main/org/apache/sis/process/ProcessListener.java b/incubator/src/org.apache.sis.process/main/org/apache/sis/process/ProcessListener.java new file mode 100644 index 0000000000..ea42c9575b --- /dev/null +++ b/incubator/src/org.apache.sis.process/main/org/apache/sis/process/ProcessListener.java @@ -0,0 +1,107 @@ +/* + * 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.sis.process; + +import java.util.EventListener; + + +/** + * Receives general indications of {@linkplain Process process} progress and events indicating + * start, completion or failure. For any {@linkplain Process#addListener registered listeners}, + * the {@link Process#call()} method shall invoke at least the {@link #started started} and + * {@link #completed completed} or {@link #failed failed} methods (mandatory). Calls to the + * {@link #progressing progressing} method are optional but recommended. + * + * @author Johann Sorel (Geomatys) + * @author Guilhem Legal (Geomatys) + */ +public interface ProcessListener extends EventListener { + /** + * Reports that a process is beginning. {@link Process} implementations + * are required to call this method exactly once. + * + * @param event The progress event. + */ + void started(ProcessEvent event); + + /** + * Invoked at any time during process progression. {@link Process} implementations + * may invoke this method an arbitrary number of time. In addition to the source, + * task name and progress indicator, the event argument may contain the following + * optional information: + * <ul> + * <li>{@link ProcessEvent#getOutput()}, if non-null, indicates an intermediate calculation value.</li> + * <li>{@link ProcessEvent#getException()}, if non-null, indicates a non-fatal warning.</li> + * </ul> + * + * @param event The progress event. + */ + void progressing(ProcessEvent event); + + /** + * Reports that a process has been dismissed. + * + * @param event The progress event. + */ + void dismissed(ProcessEvent event); + + /** + * Reports that a process has been paused. In addition to the + * source and task name, the event argument may contain the following optional information: + * <ul> + * <li>{@link ProcessEvent#getOutput()}, if non-null, indicates the calculation state before + * the pause.</li> + * </ul> + * + * @param event The progress event. + */ + void paused(ProcessEvent event); + + /** + * Reports that a process has been resumed after a pause. + * + * @param event The progress event. + */ + void resumed(ProcessEvent event); + + /** + * Reports that a process has completed successfully. {@link Process} implementations + * are required to call either this method or {@link #failed(ProcessEvent)} exactly once. + * In addition to the source and task name, the event argument shall contain the following + * information: + * <ul> + * <li>{@link ProcessEvent#getOutput()} is the final result returned by {@link Process#call()}.</li> + * </ul> + * + * @param event The progress event. + */ + void completed(ProcessEvent event); + + /** + * Reports that a process has failed. {@link Process} implementations are required to call + * either this method or {@link #completed(ProcessEvent)} exactly once. In addition to the + * source and task name, the event argument may contain the following optional information: + * <ul> + * <li>{@link ProcessEvent#getException()}, if non-null, indicates the failure cause.</li> + * <li>{@link ProcessEvent#getOutput()}, if non-null, indicates the calculation state before + * the failure.</li> + * </ul> + * + * @param event The progress event. + */ + void failed(ProcessEvent event); +} diff --git a/incubator/src/org.apache.sis.process/main/module-info.java b/incubator/src/org.apache.sis.process/main/org/apache/sis/process/RollbackableProcess.java similarity index 52% copy from incubator/src/org.apache.sis.process/main/module-info.java copy to incubator/src/org.apache.sis.process/main/org/apache/sis/process/RollbackableProcess.java index 4d2fb131c0..4773b555a7 100644 --- a/incubator/src/org.apache.sis.process/main/module-info.java +++ b/incubator/src/org.apache.sis.process/main/org/apache/sis/process/RollbackableProcess.java @@ -14,16 +14,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package org.apache.sis.process; + /** - * Description and execution of processes. + * Extend {@link Process} interface to add a rollback method used + * to revert process {@link Process#call()} actions. * - * @author Johann Sorel (Geomatys) + * @author Quentin Boileau (Geomatys) */ -module org.apache.sis.process { - // Dependencies used in public API. - requires transitive org.apache.sis.referencing; +public interface RollbackableProcess extends Process { - // Uncomment when the package contains at least one class. - // exports org.apache.sis.process; + /** + * Rollback {@link Process#call()}. + * Implementers must also handle partial rollback + * if something went wrong in the middle of {@link Process#call()}. + * + * For example a process that create two files must not fail on rollback because + * the last file was not created because of an exception in {@link Process#call()}. + * + * @throws ProcessException if something went wrong during rollback. + */ + void rollback() throws ProcessException; } diff --git a/incubator/src/org.apache.sis.process/test/org/apache/sis/process/ProcessCategoriesTest.java b/incubator/src/org.apache.sis.process/test/org/apache/sis/process/ProcessCategoriesTest.java new file mode 100644 index 0000000000..1eb84c341f --- /dev/null +++ b/incubator/src/org.apache.sis.process/test/org/apache/sis/process/ProcessCategoriesTest.java @@ -0,0 +1,94 @@ +/* + * 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.sis.process; + +import java.util.Locale; +import org.opengis.util.GenericName; +import org.opengis.util.ScopedName; + +// Test dependencies +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + + +/** + * Tests the {@link ProcessCategories} class. + * + * @author Johann Sorel (Geomatys) + */ +public final class ProcessCategoriesTest { + /** + * Creates a new test case. + */ + public ProcessCategoriesTest() { + } + + /** + * Tests the locale-independent codes of root and child categories. + */ + @Test + public void testCodes() { + assertEquals("vector", ProcessCategories.VECTOR.toString()); + assertEquals("pointCloud", ProcessCategories.POINT_CLOUD.toString()); + assertEquals("raster/terrain", ProcessCategories.RASTER_TERRAIN.toString()); + assertEquals("terrain", ProcessCategories.RASTER_TERRAIN.tip().toString()); + } + + /** + * Tests the localized labels, including the fallback on English for unsupported languages. + */ + @Test + public void testLabels() { + final var label = ProcessCategories.RASTER_TERRAIN.tip().toInternationalString(); + assertEquals("Terrain analysis", label.toString(Locale.ENGLISH)); + assertEquals("Analyse de terrain", label.toString(Locale.FRENCH)); + assertEquals("Terrain analysis", label.toString(Locale.GERMAN)); + assertEquals("terrain", label.toString(Locale.ROOT)); + assertEquals("Raster/Analyse de terrain", + ProcessCategories.RASTER_TERRAIN.toInternationalString().toString(Locale.FRENCH)); + } + + /** + * Tests the parent-child relationship between categories. + */ + @Test + public void testHierarchy() { + final GenericName category = ProcessCategories.RASTER_TERRAIN; + assertEquals(2, category.depth()); + assertEquals(ProcessCategories.RASTER, category.head()); + assertEquals(ProcessCategories.RASTER, ((ScopedName) category).path()); + assertEquals(1, ProcessCategories.RASTER.depth()); + } + + /** + * Tests the creation of custom categories, as roots or below existing categories. + */ + @Test + public void testCreate() { + final GenericName hydrology = ProcessCategories.create(ProcessCategories.RASTER_TERRAIN, "hydrology", "Hydrology"); + assertEquals("raster/terrain/hydrology", hydrology.toString()); + assertEquals(ProcessCategories.RASTER, hydrology.head()); + assertEquals("Hydrology", hydrology.tip().toInternationalString().toString(Locale.FRENCH)); + + final GenericName custom = ProcessCategories.create(null, "custom", null); + assertEquals("custom", custom.toString()); + assertEquals("custom", custom.toInternationalString().toString(Locale.ENGLISH)); + + assertThrows(IllegalArgumentException.class, () -> ProcessCategories.create(null, "a/b", null)); + assertThrows(IllegalArgumentException.class, () -> ProcessCategories.create(null, " ", null)); + } +}
