Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 58 additions & 2 deletions plugins/datahub-integration/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,19 @@
<npmVersion>10.7.0</npmVersion>
</configuration>
</execution>
<!-- Install Angular DevKit dependency explicitly -->
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note for me : delete and put back : ci --loglevel error

<execution>
<id>npm-install-angular-devkit</id>
<phase>initialize</phase>
<goals>
<goal>npm</goal>
</goals>
<configuration>
<arguments>install @angular-devkit/architect @angular-devkit/build-angular @angular-devkit/core @angular-devkit/schematics --legacy-peer-deps</arguments>
<workingDirectory>geonetwork-ui</workingDirectory>
<installDirectory>${basedir}</installDirectory>
</configuration>
</execution>
<!-- Install geonetwork-ui dependencies -->
<execution>
<id>npm-install</id>
Expand All @@ -118,7 +131,7 @@
<goal>npm</goal>
</goals>
<configuration>
<arguments>ci --loglevel error</arguments>
<arguments>install --no-audit --legacy-peer-deps</arguments>
<workingDirectory>geonetwork-ui</workingDirectory>
<installDirectory>${basedir}</installDirectory>
</configuration>
Expand All @@ -135,7 +148,25 @@
<NX_DAEMON>false</NX_DAEMON>
</environmentVariables>
<arguments>
run nx -- build datahub --base-href=./
run nx -- build datahub --base-href=/geonetwork/datahub/
</arguments>
<workingDirectory>geonetwork-ui</workingDirectory>
<installDirectory>${basedir}</installDirectory>
</configuration>
</execution>
<!-- Build metadata-editor app -->
<execution>
<id>npm-build-metadata-editor</id>
<phase>generate-resources</phase>
<goals>
<goal>npm</goal>
</goals>
<configuration>
<environmentVariables>
<NX_DAEMON>false</NX_DAEMON>
</environmentVariables>
<arguments>
run nx -- build metadata-editor --base-href=/geonetwork/metadata-editor/
</arguments>
<workingDirectory>geonetwork-ui</workingDirectory>
<installDirectory>${basedir}</installDirectory>
Expand Down Expand Up @@ -173,6 +204,31 @@
</resources>
</configuration>
</execution>
<execution>
<id>copy-metadata-editor-resources</id>
<phase>generate-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<overwrite>true</overwrite>
<encoding>UTF-8</encoding>
<outputDirectory>target/resources/metadata-editor</outputDirectory>
<resources>
<resource>
<directory>geonetwork-ui/dist/apps/metadata-editor</directory>
<filtering>false</filtering>
</resource>
<resource>
<directory>geonetwork-ui</directory>
<includes>
<include>package.json</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,18 @@
import java.nio.file.Files;
import java.nio.file.Path;

// Generated by ChatGPT
// Generated by ChatGPT & Claude3.7
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this comment necessary?

public class FileUtils {
private static final Path TEMP_DIR;
private static final Path DATAHUB_TEMP_DIR;
private static final Path METADATA_EDITOR_TEMP_DIR;

static {
try {
TEMP_DIR = Files.createTempDirectory("plugin_cache");
TEMP_DIR.toFile().deleteOnExit(); // Ensure temp directory is cleaned up
DATAHUB_TEMP_DIR = Files.createTempDirectory("datahub_cache");
METADATA_EDITOR_TEMP_DIR = Files.createTempDirectory("metadata_editor_cache");

DATAHUB_TEMP_DIR.toFile().deleteOnExit();
METADATA_EDITOR_TEMP_DIR.toFile().deleteOnExit();
} catch (IOException e) {
throw new RuntimeException(e);
}
Expand All @@ -25,7 +29,17 @@ public static boolean fileExistsInJar(String relativePath) {
}

public static File getFileFromJar(String relativePath) throws IOException {
File tempFile = new File(TEMP_DIR.toFile(), new File(relativePath).getName());
Path tempDir;

if (relativePath.startsWith("/datahub/") || relativePath.startsWith("datahub/")) {
tempDir = DATAHUB_TEMP_DIR;
} else if (relativePath.startsWith("/metadata-editor/") || relativePath.startsWith("metadata-editor/")) {
tempDir = METADATA_EDITOR_TEMP_DIR;
} else {
tempDir = DATAHUB_TEMP_DIR;
}

File tempFile = new File(tempDir.toFile(), new File(relativePath).getName());
if (tempFile.exists()) {
return tempFile;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
package org.fao.geonet.metadataeditor;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpHeaders;
import org.fao.geonet.NodeInfo;
import org.fao.geonet.datahub.FileUtils;
import org.fao.geonet.domain.Source;
import org.fao.geonet.domain.SourceType;
import org.fao.geonet.repository.SourceRepository;
import org.fao.geonet.utils.Log;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.GZIPOutputStream;

import static org.fao.geonet.kernel.schema.SchemaPlugin.LOGGER_NAME;

// FIXME: unit tests missing for this class!

@RequestMapping(value = {"/{geonetworkPath:[a-zA-Z0-9_\\-]+}"})
@Controller("metadata-editor")
public class MetadataEditorController {
public static final String INDEX_PATH = "/metadata-editor/index.html";
public static final String METADATA_EDITOR_FILES_PATH = "/metadata-editor/";
public static final String DEFAULT_CONFIGURATION_FILE_PATH = METADATA_EDITOR_FILES_PATH + "assets/configuration/default.toml";

@Autowired
SourceRepository sourceRepository;

/*@GetMapping("/metadata-editor/status")
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note for me : delete

public ResponseEntity<String> getDatahubStatus() throws IOException {
File configFile = FileUtils.getFileFromJar(DEFAULT_CONFIGURATION_FILE_PATH);
String defaultConfig = FileUtils.readFromInputStream(new FileInputStream(configFile));
JSONObject body = new JSONObject();
body.put("defaultConfig", defaultConfig);
File packageJsonFile = FileUtils.getFileFromJar( DATAHUB_FILES_PATH + "package.json");
String packageJsonContent = FileUtils.readFromInputStream(new FileInputStream(packageJsonFile));
JSONObject packageJson = new JSONObject(packageJsonContent);
return ResponseEntity
.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(body.toString());
}*/

@GetMapping("/metadata-editor")
public RedirectView redirectMetadataEditor(HttpServletRequest request, HttpServletResponse response) {
String uri = request.getRequestURI();
if (!uri.endsWith("/")) {
uri += "/";
}
return new RedirectView(uri + "index.html");
}

@GetMapping("/{locale:[a-z]{2,3}}/metadata-editor")
public RedirectView redirectLocalizedMetadataEditor(HttpServletRequest request, HttpServletResponse response) {
String uri = request.getRequestURI();
if (!uri.endsWith("/")) {
uri += "/";
}
return new RedirectView(uri + "index.html");
}

@RequestMapping("/metadata-editor/**")
public void handleMetadataEditorWithFilepath(HttpServletRequest request, HttpServletResponse response) throws IOException {
handleMetadataEditorRequest(request, response);
}

@RequestMapping("/{locale:[a-z]{2,3}}/metadata-editor/**")
public void handleLocalizedMetadataEditorWithFilepath(HttpServletRequest request, HttpServletResponse response,
@PathVariable String locale) throws IOException {
handleMetadataEditorRequest(request, response);
}

void handleMetadataEditorRequest(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String portalName = getPortalName(request);
if (!isPortalDatahubEnabled(portalName)) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}

File actualFile = getRequestedFile(request);
if (!actualFile.exists()) {
actualFile = getFallbackFile();
disableCacheForIndex(response);
}

setResponseHeaders(response, actualFile);
writeResponseContent(request, response, actualFile, portalName);
}

private String getPortalName(HttpServletRequest request) {
String reqPath = request.getPathInfo();
String[] parts = reqPath.split("/");
return FilenameUtils.getName(parts[1]);
}

private boolean isPortalDatahubEnabled(String portalName) {
if (NodeInfo.DEFAULT_NODE.equals(portalName)) {
return true;
} else if (sourceRepository.existsByUuidAndType(portalName, SourceType.subportal)) {
return Objects.requireNonNull(sourceRepository.findOneByUuid(portalName)).getDatahubEnabled();
}
return false;
}

private File getRequestedFile(HttpServletRequest request) {
String reqPath = request.getPathInfo();
String filePath = Stream.of(reqPath.split("/metadata-editor/")).skip(1).collect(Collectors.joining("/"));
filePath = FilenameUtils.normalize(filePath);
try {
return FileUtils.getFileFromJar(METADATA_EDITOR_FILES_PATH + filePath);
} catch (IOException e) {
return new File(INDEX_PATH);// return file doesn't exist in jar => go back to main menu
}
}

private File getFallbackFile() {
try {
return FileUtils.getFileFromJar(INDEX_PATH);
} catch (IOException e) {
Log.error(LOGGER_NAME, e.getMessage());
return new File(INDEX_PATH);
}
}

private void disableCacheForIndex(HttpServletResponse response) {
response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache");
response.setHeader(HttpHeaders.PRAGMA, "no-cache");
response.setHeader(HttpHeaders.EXPIRES, "0");
}

private void setResponseHeaders(HttpServletResponse response, File actualFile) throws IOException {
response.setStatus(HttpServletResponse.SC_OK);
String extension = actualFile.getName().toLowerCase();
String contentType = extension.equals("js") ? "text/javascript; charset=UTF-8"
: Files.probeContentType(actualFile.toPath());
response.setContentType(contentType);
}

void writeResponseContent(HttpServletRequest request, HttpServletResponse response, File actualFile,
String portalName) throws IOException {
InputStream inStream = actualFile.getName().equals("default.toml") ? readConfiguration(portalName)
: new FileInputStream(actualFile);
OutputStream outStream = response.getOutputStream();

if (request.getHeader(HttpHeaders.ACCEPT_ENCODING).contains("gzip")) {
response.setHeader(HttpHeaders.CONTENT_ENCODING, "gzip");
outStream = new GZIPOutputStream(outStream);
}

if (actualFile.getName().equals("index.html")) {
// rewrite the base-href attribute to make app routing work
String baseHref = "/geonetwork/" + portalName + "/metadata-editor/";
String content = IOUtils
.toString(inStream, StandardCharsets.UTF_8)
.replaceAll("<base href=\".*\">", "<base href=\"" + baseHref + "\">");
outStream.write(content.getBytes());
} else {
IOUtils.copy(inStream, outStream);
}

outStream.close();
}

InputStream readConfiguration(String portalName) throws IOException {
String configuration = getPortalConfiguration(portalName);
configuration = configuration.replaceAll("\ngeonetwork4_api_url\\s?=.+", "\n")
.replace("[global]", "[global]\ngeonetwork4_api_url = \"/geonetwork/" + portalName + "/api\"");
return new ByteArrayInputStream(configuration.getBytes());
}

private String getPortalConfiguration(String portalName) throws IOException {
Source portal = Objects.requireNonNull(sourceRepository.findByType(SourceType.portal, null)).get(0);
if (isNotDefaultPortal(portalName)) {
portal = sourceRepository.findOneByUuid(portalName);
}

// 1. read for subportal
if (datahubConfigurationExist(portal)) {
return portal.getDatahubConfiguration();
}
// 2. fallback: read from main portal
else if (isNotDefaultPortal(portalName)) {
return this.getPortalConfiguration(NodeInfo.DEFAULT_NODE);
}
// 3. fallback: read from default.toml file in resource
else {
File defaultConfig = FileUtils.getFileFromJar(DEFAULT_CONFIGURATION_FILE_PATH);
return FileUtils.readFromInputStream(new FileInputStream(defaultConfig));
}
}

private boolean isNotDefaultPortal(String portalName) {
return !portalName.equals(NodeInfo.DEFAULT_NODE);
}

private boolean datahubConfigurationExist(Source portal) {
return portal != null
&& portal.getDatahubConfiguration() != null
&& !portal.getDatahubConfiguration().isEmpty();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -254,11 +254,17 @@
access="permitAll"/>
<sec:intercept-url pattern="/[a-zA-Z0-9_\-]+/[a-z]{2,3}/getSLD/.*" access="permitAll"/>

<!-- Datahub endpoint -->
<!-- Datahub & Metadata-editor endpoint -->
<sec:intercept-url
pattern="/[a-zA-Z0-9_\-]+/[a-z]{2,3}/datahub.*"
access="permitAll"/>

<sec:intercept-url pattern="/[a-zA-Z0-9_\-]+/datahub.*" access="permitAll"/>
<sec:intercept-url
pattern="/[a-zA-Z0-9_\-]+/[a-z]{2,3}/metadata-editor.*"
access="permitAll"/>
<sec:intercept-url pattern="/[a-zA-Z0-9_\-]+/metadata-editor.*" access="permitAll"/>
<sec:intercept-url pattern="/metadata-editor.*" access="permitAll"/>

<sec:intercept-url pattern="/.*" access="denyAll"/>
</sec:filter-security-metadata-source>
Expand Down
Loading