diff --git a/.github/workflows/docker-no-ssl.yml b/.github/workflows/docker-no-ssl.yml index 55ffec8..b2ca6e4 100644 --- a/.github/workflows/docker-no-ssl.yml +++ b/.github/workflows/docker-no-ssl.yml @@ -4,80 +4,77 @@ on: release: types: [published] - # pull_request: - # branches: main + pull_request: + branches: [main] jobs: + version-checker: + uses: ./.github/workflows/version-setup.yml + build: runs-on: ubuntu-latest + needs: version-checker permissions: contents: read packages: write - outputs: - jar_version: ${{ steps.bump.outputs.jar_version }} - steps: - - uses: actions/checkout@v3 - - - name: Set up JDK 11 - uses: actions/setup-java@v3 - with: - java-version: '11' - distribution: 'temurin' - - - name: change Web.xml to avoid use of ssl - id: webxml - run: | - rm ${{ github.workspace }}/src/main/webapp/WEB-INF/web.xml - mv ${{ github.workspace }}/docker/tomcat/web-no-ssl.xml ${{ github.workspace }}/src/main/webapp/WEB-INF/web.xml - - - name: Build a package - run: | - mvn versions:set -DnewVersion="${{ github.event.release.tag_name }}" - mvn -B -U --file pom.xml clean package -P release - - - name: Bump jar version - id: bump - run: | - PROJECT_VERSION=$(mvn help:evaluate -Dexpression=project.version -q -DforceStdout) - echo "jar_version=${PROJECT_VERSION}" >> $GITHUB_OUTPUT - - - name: Temporarily save jar artifact - uses: actions/upload-artifact@v3 - with: - name: jar-artifact - path: ${{ github.workspace }}/target/*.war - retention-days: 1 + - uses: actions/checkout@v4 + + - name: Set up JDK 11 + uses: actions/setup-java@v4 + with: + java-version: "11" + distribution: "temurin" + + - name: change Web.xml to avoid use of ssl + id: webxml + run: | + rm ${{ github.workspace }}/src/main/webapp/WEB-INF/web.xml + mv ${{ github.workspace }}/docker/tomcat/web-no-ssl.xml ${{ github.workspace }}/src/main/webapp/WEB-INF/web.xml + + - name: Build a package + run: | + mvn -B -U --file pom.xml clean package -P release \ + "-Drevision=${{ needs.version-checker.outputs.revision }}" \ + "-Dsha1=${{ needs.version-checker.outputs.sha1 }}" \ + "-Dchangelist=${{ needs.version-checker.outputs.changelist }}" + + - name: Temporarily save jar artifact + uses: actions/upload-artifact@v4 + with: + name: jar-artifact + path: ${{ github.workspace }}/target/*.war + retention-days: 1 deploy: runs-on: ubuntu-latest - needs: build + needs: [build, version-checker] steps: - - uses: actions/checkout@v3 - - uses: actions/download-artifact@v3 - with: + - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + with: name: jar-artifact path: target/ - - name: Docker build - run: | - docker build . --file docker/webstudio.dockerfile --target image-no-ssl \ - -t ${{ secrets.DOCKER_HUB_REPO }}/${{ secrets.DOCKER_HUB_REPO }}-webstudio-no-ssl:${{needs.build.outputs.jar_version}} \ - -t ${{ secrets.DOCKER_HUB_REPO }}/${{ secrets.DOCKER_HUB_REPO }}-webstudio-no-ssl:latest \ - --build-arg WEBSTUDIO_WAR_PATH=target/webstudio-${{needs.build.outputs.jar_version}}.war + - name: Docker build + run: | + docker build . --file docker/webstudio.dockerfile --target image-no-ssl \ + -t ${{ secrets.DOCKER_HUB_REPO }}/${{ secrets.DOCKER_HUB_REPO }}-webstudio-no-ssl:${{ needs.version-checker.outputs.flattened_version }} \ + -t ${{ secrets.DOCKER_HUB_REPO }}/${{ secrets.DOCKER_HUB_REPO }}-webstudio-no-ssl:latest \ + --build-arg WEBSTUDIO_WAR_PATH=target/webstudio-${{ needs.version-checker.outputs.flattened_version }}.war - - name: Login to DockerHub - uses: docker/login-action@v2 - with: - username: ${{ secrets.DOCKER_USERNAME }} - password: ${{ secrets.DOCKER_PASSWORD }} + - name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_PASSWORD }} - - name: Docker push - run: | - docker push ${{ secrets.DOCKER_HUB_REPO }}/${{ secrets.DOCKER_HUB_REPO }}-webstudio-no-ssl:${{needs.build.outputs.jar_version}} + - name: Docker push + run: | + docker push ${{ secrets.DOCKER_HUB_REPO }}/${{ secrets.DOCKER_HUB_REPO }}-webstudio-no-ssl:${{ needs.version-checker.outputs.flattened_version }} # run: # runs-on: ubuntu-18.04 @@ -86,4 +83,4 @@ jobs: # steps: # - name: Run container # run: | - # docker run ${{ secrets.DOCKER_HUB_REPO }}/${{ secrets.DOCKER_HUB_REPO }}-webstudio-no-ssl:${{needs.build.outputs.jar_version}} \ No newline at end of file + # docker run ${{ secrets.DOCKER_HUB_REPO }}/${{ secrets.DOCKER_HUB_REPO }}-webstudio-no-ssl:${{ needs.version-checker.outputs.flattened_version }} diff --git a/.github/workflows/docker-release.yml b/.github/workflows/docker-release.yml index 6d339a5..640b332 100644 --- a/.github/workflows/docker-release.yml +++ b/.github/workflows/docker-release.yml @@ -8,70 +8,67 @@ on: # branches: main jobs: + version-checker: + uses: ./.github/workflows/version-setup.yml + build: runs-on: ubuntu-latest + needs: version-checker permissions: contents: read packages: write - outputs: - jar_version: ${{ steps.bump.outputs.jar_version }} - steps: - - uses: actions/checkout@v3 - - - name: Set up JDK 11 - uses: actions/setup-java@v3 - with: - java-version: '11' - distribution: 'temurin' - - - name: Build a package - run: | - mvn versions:set -DnewVersion="${{ github.event.release.tag_name }}" - mvn -B -U --file pom.xml clean package -P release - - - name: Bump jar version - id: bump - run: | - PROJECT_VERSION=$(mvn help:evaluate -Dexpression=project.version -q -DforceStdout) - echo "jar_version=${PROJECT_VERSION}" >> $GITHUB_OUTPUT - - - name: Temporarily save jar artifact - uses: actions/upload-artifact@v3 - with: - name: jar-artifact - path: ${{ github.workspace }}/target/*.war - retention-days: 1 + - uses: actions/checkout@v4 + + - name: Set up JDK 11 + uses: actions/setup-java@v4 + with: + java-version: "11" + distribution: "temurin" + + - name: Build a package + run: | + mvn -B -U --file pom.xml clean package -P release \ + "-Drevision=${{ needs.version-checker.outputs.revision }}" \ + "-Dsha1=${{ needs.version-checker.outputs.sha1 }}" \ + "-Dchangelist=${{ needs.version-checker.outputs.changelist }}" + + - name: Temporarily save jar artifact + uses: actions/upload-artifact@v4 + with: + name: jar-artifact + path: ${{ github.workspace }}/target/*.war + retention-days: 1 deploy: runs-on: ubuntu-latest - needs: build + needs: [build, version-checker] steps: - - uses: actions/checkout@v3 - - uses: actions/download-artifact@v3 - with: + - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + with: name: jar-artifact path: target/ - - name: Docker build - run: | - docker build . --file docker/webstudio.dockerfile --target image-with-ssl \ - -t ${{ secrets.DOCKER_HUB_REPO }}/${{ secrets.DOCKER_HUB_REPO }}-webstudio:${{needs.build.outputs.jar_version}} \ - -t ${{ secrets.DOCKER_HUB_REPO }}/${{ secrets.DOCKER_HUB_REPO }}-webstudio:latest \ - --build-arg WEBSTUDIO_WAR_PATH=target/webstudio-${{needs.build.outputs.jar_version}}.war - - - name: Login to DockerHub - uses: docker/login-action@v2 - with: - username: ${{ secrets.DOCKER_USERNAME }} - password: ${{ secrets.DOCKER_PASSWORD }} - - - name: Docker push - run: | - docker push ${{ secrets.DOCKER_HUB_REPO }}/${{ secrets.DOCKER_HUB_REPO }}-webstudio:${{needs.build.outputs.jar_version}} + - name: Docker build + run: | + docker build . --file docker/webstudio.dockerfile --target image-with-ssl \ + -t ${{ secrets.DOCKER_HUB_REPO }}/${{ secrets.DOCKER_HUB_REPO }}-webstudio:${{needs.version-checker.outputs.flattened_version}} \ + -t ${{ secrets.DOCKER_HUB_REPO }}/${{ secrets.DOCKER_HUB_REPO }}-webstudio:latest \ + --build-arg WEBSTUDIO_WAR_PATH=target/webstudio-${{needs.version-checker.outputs.flattened_version}}.war + + - name: Login to DockerHub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_PASSWORD }} + + - name: Docker push + run: | + docker push ${{ secrets.DOCKER_HUB_REPO }}/${{ secrets.DOCKER_HUB_REPO }}-webstudio:${{needs.version-checker.outputs.flattened_version}} # run: # runs-on: ubuntu-18.04 # needs: [build, deploy] @@ -79,4 +76,4 @@ jobs: # steps: # - name: Run container # run: | - # docker run ${{ secrets.DOCKER_HUB_REPO }}/${{ secrets.DOCKER_HUB_REPO }}-webstudio:${{needs.build.outputs.jar_version}} \ No newline at end of file + # docker run ${{ secrets.DOCKER_HUB_REPO }}/${{ secrets.DOCKER_HUB_REPO }}-webstudio:${{needs.version-checker.outputs.flattened_version}} diff --git a/.github/workflows/sonarcloud-build.yml b/.github/workflows/sonarcloud-build.yml index cbe5dba..cef4ebc 100644 --- a/.github/workflows/sonarcloud-build.yml +++ b/.github/workflows/sonarcloud-build.yml @@ -7,52 +7,52 @@ on: types: [opened, synchronize, reopened] jobs: coverage: - runs-on: 'ubuntu-latest' + runs-on: "ubuntu-latest" steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 with: - fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis + fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis - name: Set up JDK 11 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: - distribution: 'temurin' - java-version: '11' + distribution: "temurin" + java-version: "11" - name: Cache SonarCloud packages - uses: actions/cache@v1 + uses: actions/cache@v4 with: path: ~/.sonar/cache key: ${{ runner.os }}-sonar restore-keys: ${{ runner.os }}-sonar - name: Build and analyze env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} run: mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.projectKey=geosiris-technologies_webstudio - - build: + + build: runs-on: ${{ matrix.os }} strategy: matrix: - distribution: [ 'zulu', 'temurin', 'microsoft', 'corretto', 'liberica' ] - java: [ '11' ] - os: [ 'ubuntu-latest', 'macos-latest', 'windows-latest' ] + distribution: ["zulu", "temurin", "microsoft", "corretto", "liberica"] + java: ["11"] + os: ["ubuntu-latest", "macos-latest", "windows-latest"] name: Java ${{ matrix.Java }} (${{ matrix.distribution }}) steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 with: - fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis + fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis - name: Set up JDK ${{ matrix.java }} - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: ${{ matrix.distribution }} java-version: ${{ matrix.java }} - name: Cache Maven packages - uses: actions/cache@v1 + uses: actions/cache@v4 with: path: ~/.m2 key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} restore-keys: ${{ runner.os }}-m2 - - name: Build + - name: Build env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any run: mvn -B compile --file pom.xml diff --git a/.github/workflows/version-setup.yml b/.github/workflows/version-setup.yml new file mode 100644 index 0000000..58baf8b --- /dev/null +++ b/.github/workflows/version-setup.yml @@ -0,0 +1,65 @@ +# .github/workflows/version-setup.yml +name: Maven Version Setup + +on: + workflow_call: + outputs: + revision: + description: "Revision" + value: ${{ jobs.version.outputs.revision }} + sha1: + description: "SHA1" + value: ${{ jobs.version.outputs.sha1 }} + changelist: + description: "Changelist" + value: ${{ jobs.version.outputs.changelist }} + flattened_version: + description: "Flattened Version" + value: ${{ jobs.version.outputs.flattened_version }} + +jobs: + version: + runs-on: ubuntu-latest + outputs: + revision: ${{ steps.setver.outputs.revision }} + sha1: ${{ steps.setver.outputs.sha1 }} + changelist: ${{ steps.setver.outputs.changelist }} + flattened_version: ${{ steps.setver.outputs.flattened_version }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - id: setver + run: | + COMMIT_SHA_LONG="${{ github.sha }}" + COMMIT_SHA_SHORT="${COMMIT_SHA_LONG:0:7}" + + REVISION_VAR="" + SHA1_VAR="" + CHANGELIST_VAR="" + + if [[ "${{ github.ref_type }}" == "tag" ]]; then + TAG_NAME="${{ github.ref_name }}" + TAG_CLEAN=$(echo "$TAG_NAME" | sed 's/^v//') + + REVISION_VAR="$TAG_CLEAN" + SHA1_VAR="" + CHANGELIST_VAR="" + echo "🏗️ Version de Release (Tag) détectée : $TAG_CLEAN" + else + LAST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "v0.0.0") + VERSION_BASE=$(echo "$LAST_TAG" | sed 's/^v//') + IFS='.' read -r MAJOR MINOR PATCH <<< "$VERSION_BASE" + NEXT_PATCH=$((PATCH + 1)) + + REVISION_VAR="$MAJOR.$MINOR.$NEXT_PATCH" + SHA1_VAR="-$COMMIT_SHA_SHORT" + CHANGELIST_VAR="-SNAPSHOT" + echo "🧪 Version Snapshot détectée (basée sur $LAST_TAG) : ${REVISION_VAR}${SHA1_VAR}${CHANGELIST_VAR}" + fi + + echo "revision=$REVISION_VAR" >> "$GITHUB_OUTPUT" + echo "sha1=$SHA1_VAR" >> "$GITHUB_OUTPUT" + echo "changelist=$CHANGELIST_VAR" >> "$GITHUB_OUTPUT" + echo "flattened_version=${REVISION_VAR}${SHA1_VAR}${CHANGELIST_VAR}" >> "$GITHUB_OUTPUT" + echo "➡️ Variables de sortie définies : revision='$REVISION_VAR', sha1='$SHA1_VAR', changelist='$CHANGELIST_VAR'" diff --git a/.gitignore b/.gitignore index 758b51a..aac2c8e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,24 +1,72 @@ -/build -*.class -/bin/ -.settings -settings.xml +# === Java build === target/ -target/* -*.venv -*/venv -.vscode/ -.vscode/* -*__pycache__* +*.class +*.jar +*.war +*.ear +build/ +bin/ + +# === Maven/Gradle === +.settings/ .classpath .project -.idea .factorypath +settings.xml +mvnw +mvnw.cmd +.mvn/ +gradle/ +build.gradle +build.gradle.kts +gradlew +gradlew.bat + +# === Python === +__pycache__/ +*.py[cod] +*.venv/ +venv/ +*/venv/ +.env +.env.* + +# === Node.js === +node_modules/ +package-lock.json +yarn.lock +pnpm-lock.yaml +package.json + +# === IDEs and Editors === +.idea/ +.vscode/ +.vscode/* +.DS_Store +Thumbs.db + +# === OS files === +.DS_Store +Thumbs.db +ehthumbs.db +Desktop.ini + +# === Docker === docker/tomcat_old/ -/todo.txt +docker/compose/ docker/compose/docker-compose-local-test.yml -docker/compose -*package-lock.json -*package.json -manip.txt \ No newline at end of file +# === Logs and temp === +*.log +*.tmp +*.swp +*.swo + +# === Project-specific === +todo.txt +manip.txt +manip.md +xsd_mapping.json + +# === Misc === +!README.md \ No newline at end of file diff --git a/docker/data/resqmlAccessibleDORMapping.json b/docker/data/resqmlAccessibleDORMapping.json index 0b64406..2d7d21f 100644 --- a/docker/data/resqmlAccessibleDORMapping.json +++ b/docker/data/resqmlAccessibleDORMapping.json @@ -19,7 +19,7 @@ "Seismic2dPostStackRepresentation" : ["PolylineRepresentation", "AbstractLocal3Dcrs"], "Seismic3dPostStackRepresentation" : ["Grid2DRepresentation", "AbstractLocal3Dcrs"], "StratigraphicColumn" : ["StratigraphicColumnRankInterpretation"], - "StratigraphicColumnRankInterpretation" : ["StratigraphicUnitInterpretation" , "AbstractContactInterpretationPart" , "AbstractGeologicFeature"], + "StratigraphicColumnRankInterpretation" : ["StratigraphicUnitInterpretation" , "AbstractContactInterpretationPart" , "AbstractGeologicFeature", "Model"], "StratigraphicOccurenceInterpretation" : ["GeologicUnitInterpretation" , "AbstractContactInterpretationPart" , "AbstractGeologicFeature"], "StreamlinesRepresentation" : ["WellboreTrajectoryRepresentation"], "StructuralOrganizationInterpretation" : ["AbstractFeatureInterpretation" , "AbstractGeologicFeature" , "Model" , "InterpretationSet" , "AbstractContactInterpretationPart"], diff --git a/docker/tomcat/web-no-ssl.xml b/docker/tomcat/web-no-ssl.xml index 2c63765..f21e1f1 100644 --- a/docker/tomcat/web-no-ssl.xml +++ b/docker/tomcat/web-no-ssl.xml @@ -52,7 +52,7 @@ SameSiteFilter - com.geosiris.webstudio.filters.SameSiteFilter + com.geosiris.webstudio.servlet.filters.SameSiteFilter SameSiteFilter diff --git a/docker/webstudio.dockerfile b/docker/webstudio.dockerfile index ea8c005..c572bce 100644 --- a/docker/webstudio.dockerfile +++ b/docker/webstudio.dockerfile @@ -1,4 +1,4 @@ -FROM tomcat:10.1-jdk11-openjdk-slim as base +from tomcat:10.1-jdk11-openjdk-slim as base # FROM tomcat:10.1-jdk21-openjdk-slim as base LABEL maintainer="valentin.gauthier@geosiris.com" @@ -86,7 +86,7 @@ RUN echo "{ \ \"energyml.prodml2_2\" : \"/config/data/xsd/energyml/prodml/v2.2/xsd_schemas/ProdmlAllObjects.xsd\" \ }" > /config/data/xsd/xsd_mapping.json -ENV webstudio_fpathToXSDMapping /config/data/xsd/xsd_mapping.json +ENV webstudio_fpathToXSDMapping=/config/data/xsd/xsd_mapping.json # Cleaning zips RUN rm -rf tmp_ZIP @@ -95,7 +95,7 @@ RUN rm -rf tmp_ZIP RUN mkdir -p /config/data/rc/ RUN wget http://geosiris.com/wp-content/uploads/2022/09/PropertyKindDictionary_v2.3.xml -P /config/data/rc/ -ENV webstudio_pathToAdditionalObjectsDir /config/data/rc/ +ENV webstudio_pathToAdditionalObjectsDir=/config/data/rc/ # ______ _____ __ _ @@ -105,16 +105,16 @@ ENV webstudio_pathToAdditionalObjectsDir /config/data/rc/ # \____/\____/_/ /_/_/ /_/\__, /\__,_/_/ \__,_/\__/_/\____/_/ /_/ # /____/ -ENV WS_CONFIG_INI_FILE_PATH /config/sample-ws-config.ini +ENV WS_CONFIG_INI_FILE_PATH=/config/sample-ws-config.ini COPY ./docker/config/sample-ws-config.ini /config/sample-ws-config.ini ADD docker/data/ /config/data -ENV webstudio_fpathToEPCPkgGroup /config/data/epcPackagesGroups.json -ENV webstudio_fpathToAccessibleDORMapping /config/data/resqmlAccessibleDORMapping.json -ENV webstudio_dirPathToComments /config/data/comments/ -ENV webstudio_dirPathToExtTypes /config/data/extTypesAttributes/ +ENV webstudio_fpathToEPCPkgGroup=/config/data/epcPackagesGroups.json +ENV webstudio_fpathToAccessibleDORMapping=/config/data/resqmlAccessibleDORMapping.json +ENV webstudio_dirPathToComments=/config/data/comments/ +ENV webstudio_dirPathToExtTypes=/config/data/extTypesAttributes/ # ______ __ diff --git a/pom.xml b/pom.xml index 0b958d1..0fb947e 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ com.geosiris webstudio ${project.groupId}:${project.artifactId} - 1.0.16 + ${revision}${sha1}${changelist} Geosiris http://www.geosiris.com @@ -43,6 +43,10 @@ + 0.0.0 + + + [1.0.20,) ${project.basedir}/src/main/webapp 10.1.0-M15 true @@ -66,12 +70,12 @@ com.geosiris energyml-utils - 1.0.12 + ${energyml.utils.version} com.geosiris etpproto-java - 1.0.5 + 1.0.6 diff --git a/src/main/java/com/geosiris/webstudio/etp/DataspaceHandler_WebStudio.java b/src/main/java/com/geosiris/webstudio/etp/DataspaceHandler_WebStudio.java index 2b50374..afda358 100644 --- a/src/main/java/com/geosiris/webstudio/etp/DataspaceHandler_WebStudio.java +++ b/src/main/java/com/geosiris/webstudio/etp/DataspaceHandler_WebStudio.java @@ -20,6 +20,8 @@ import com.geosiris.etp.communication.ClientInfo; import com.geosiris.etp.communication.Message; import com.geosiris.etp.protocols.handlers.DataspaceHandler; +import com.geosiris.webstudio.utils.SessionUtility; +import jakarta.servlet.http.HttpSession; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -31,6 +33,12 @@ public class DataspaceHandler_WebStudio extends DataspaceHandler{ public static Logger logger = LogManager.getLogger(DataspaceHandler_WebStudio.class); + private HttpSession session; + + public DataspaceHandler_WebStudio(HttpSession session){ + this.session = session; + } + @Override public Collection on_DeleteDataspaces(DeleteDataspaces msg, MessageHeader msgHeader, ClientInfo clientInfo) { logger.info("[DataspaceHandler_WebStudio] received message" + msg); @@ -64,6 +72,9 @@ public Collection on_PutDataspaces(PutDataspaces msg, MessageHeader msg @Override public Collection on_PutDataspacesResponse(PutDataspacesResponse msg, MessageHeader msgHeader, ClientInfo clientInfo) { logger.info("[DataspaceHandler_WebStudio] received message" + msg); + + SessionUtility.logToast(session, "Dataspace created"); + SessionUtility.logAction(session, "updatedataspace"); return new ArrayList<>(); } diff --git a/src/main/java/com/geosiris/webstudio/etp/ETPWorkspace.java b/src/main/java/com/geosiris/webstudio/etp/ETPWorkspace.java index daac8b4..ca7bf86 100644 --- a/src/main/java/com/geosiris/webstudio/etp/ETPWorkspace.java +++ b/src/main/java/com/geosiris/webstudio/etp/ETPWorkspace.java @@ -16,25 +16,44 @@ package com.geosiris.webstudio.etp; import Energistics.Etp.v12.Datatypes.DataArrayTypes.DataArray; +import Energistics.Etp.v12.Datatypes.DataArrayTypes.DataArrayIdentifier; import Energistics.Etp.v12.Datatypes.Object.ContextScopeKind; -import Energistics.Etp.v12.Protocol.DataArray.GetDataArraysResponse; +import Energistics.Etp.v12.Protocol.DataArray.GetDataArrays; import com.geosiris.energyml.exception.ObjectNotFoundNotError; import com.geosiris.energyml.pkg.EPCFile; import com.geosiris.energyml.pkg.EPCPackage; import com.geosiris.energyml.utils.EnergymlWorkspace; import com.geosiris.energyml.utils.ObjectController; import com.geosiris.etp.utils.ETPHelper; -import com.geosiris.etp.utils.ETPHelperREST; import com.geosiris.etp.utils.ETPUri; import com.geosiris.etp.websocket.ETPClient; import com.geosiris.webstudio.servlet.Editor; +import com.google.gson.Gson; import jakarta.xml.bind.JAXBElement; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.HttpClientBuilder; +import org.eclipse.jetty.util.ssl.SslContextFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509ExtendedTrustManager; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; import java.util.*; import java.util.stream.Collectors; +import static com.geosiris.energyml.utils.EPCGenericManager.getObjectTypeForFilePath_fromClassName; import static com.geosiris.energyml.utils.EnergymlWorkspaceHelper.getHdfReference; public class ETPWorkspace implements EnergymlWorkspace { @@ -67,6 +86,7 @@ public ETPWorkspace(String dataspace, ETPClient client) { this.dataspace = dataspace; this.client = client; this.uuidUri_cache = new HashMap<>(); + updateUuidCache(); } public String getDataspace() { @@ -97,16 +117,64 @@ public Object getObjectByUUID(String uuid) { public List readExternalArray(Object energymlArray, Object rootObj, String pathInRoot) throws ObjectNotFoundNotError { String pathInExternal = getHdfReference(energymlArray).get(0); String uri = getUriFromObject(rootObj, dataspace).toString(); - try { + /*try { GetDataArraysResponse resp = ETPHelperREST.getMultipleDataArrays(client, uri, List.of(pathInExternal)); List res = dataArraysToNumbers(resp.getDataArrays().entrySet().stream() - .sorted(Comparator.comparing(a -> a.getKey().toString())) + .sorted(Comparator.comparing(a -> a.getKey().toString())) // .sorted(Comparator.comparingInt(e -> Integer.getInteger(e.getKey().toString()))) .map(Map.Entry::getValue) .collect(Collectors.toList())); // logger.info("@readExternalArray values {} ", res.subList(0,9)); return res; - } catch (Exception _ignore) {_ignore.printStackTrace();} + } catch (Exception _ignore) {_ignore.printStackTrace();}*/ + logger.info("uri " + uri + " pathInExternal " + pathInExternal); + String serverHost = client.getServerUri().getHost(); + if(serverHost.contains("geosiris.com")) { + // Using our own table raw download with http + try { + Map map = new HashMap<>(); + map.put("0", DataArrayIdentifier.newBuilder().setUri(uri).setPathInResource(pathInExternal).build()); + + List res = new ArrayList<>(); + logger.info(client.getServerUri().toString().replace("ws", "http")); + HttpPost send_req = new HttpPost(client.getServerUri().toString().replace("ws", "http") + "/data-array/raw/get"); + send_req.addHeader("content-type", "application/json"); + StringEntity params = new StringEntity(GetDataArrays.newBuilder().setDataArrays(map).build().toString()); + send_req.setEntity(params); + + SSLContext sslContext = SSLContext.getInstance("SSL"); // OR TLS + sslContext.init(null, new TrustManager[]{MOCK_TRUST_MANAGER }, new SecureRandom()); + HttpClient httpClient = HttpClientBuilder.create().setSSLContext(sslContext).build(); + HttpResponse answer = httpClient.execute(send_req); + Gson gson = new Gson(); + String content = new BufferedReader( + new InputStreamReader(answer.getEntity().getContent(), StandardCharsets.UTF_8)) + .lines() + .collect(Collectors.joining("\n")); + logger.info(content); + res = gson.fromJson(content, ArrayList.class); + + // Following line to remove "NAN" values + res = res.stream().map(x -> x instanceof String ? Double.NaN: x).collect(Collectors.toList()); +// if(!res.isEmpty() && res.get(0) instanceof String) { +// try { +// Float.parseFloat((String) res.get(0)); +// res = res.stream().map(x -> Float.parseFloat((String) x)).collect(Collectors.toList()); +// }catch (Exception ignore){} +// } + logger.info(String.valueOf(res)); + logger.info("==> " + res.get(0) + " " + res.get(0).getClass()); + return res; + } catch (Exception _ignore) { + _ignore.printStackTrace(); + } + }else{ + try { +// List res = ETPHelper.sendGetDataArray_prettier(client, uri, pathInExternal, 50000, true); + List res = ETPHelper.getMultipleDataArrays(client, uri, Collections.singletonList(pathInExternal), 500000).values().iterator().next(); + return res; + } catch (Exception _ignore) {_ignore.printStackTrace();} + } return null; } @@ -140,8 +208,8 @@ public String getObjectUriFromUuid(String uuid){ if(uuidUri_cache.containsKey(uuid)) { return uuidUri_cache.get(uuid).data; }else{ - logger.info("@getObjectUriFromUuid {} {}", uuid); - List uris = ETPHelper.sendGetRessources_pretty(client, new ETPUri(dataspace).toString(), 1, ContextScopeKind.self, 5000); + logger.info("@getObjectUriFromUuid {} dataspace : {}", uuid, dataspace); + List uris = ETPHelper.sendGetRessources_pretty(client, new ETPUri(dataspace).toString(), 1, ContextScopeKind.self, 5000000); for (String uri : uris) { if (uri.contains(uuid)) { uuidUri_cache.put(uuid, new CacheData<>(uri)); @@ -152,6 +220,17 @@ public String getObjectUriFromUuid(String uuid){ return null; } + public void updateUuidCache(){ + logger.info("@updateUuidCache"); + try { + List uris = ETPHelper.sendGetRessources_pretty(client, new ETPUri(dataspace).toString(), 1, ContextScopeKind.self, 5000000); + for (String uri : uris) { + ETPUri etpuri = ETPUri.parse(uri); + uuidUri_cache.put(etpuri.getUuid(), new CacheData<>(uri)); + } + }catch (Exception e){logger.error("{}", e);} + } + public static ETPUri getUriFromObject(Object obj, String dataspace){ EPCPackage epc_pkg = Editor.pkgManager.getMatchingPackage(obj.getClass()); ETPUri uri = new ETPUri(); @@ -159,46 +238,69 @@ public static ETPUri getUriFromObject(Object obj, String dataspace){ uri.setUuid((String) ObjectController.getObjectAttributeValue(obj, "uuid")); uri.setDomain(epc_pkg.getDomain()); uri.setDomainVersion(epc_pkg.getVersionNum().replace(".", "").substring(0,2)); - uri.setObjectType(obj.getClass().getSimpleName()); - uri.setVersion((String) ObjectController.getObjectAttributeValue(obj, "version")); + uri.setObjectType(getObjectTypeForFilePath_fromClassName(obj.getClass().getName())); + try { + uri.setVersion((String) ObjectController.getObjectAttributeValue(obj, "version")); + }catch (Exception ignore){} return uri; } public static List dataArraysToNumbers(List das){ return das.stream() - .map(da -> { - try { - List values = ((List) ObjectController.getObjectAttributeValue(da.getData().getItem(), "values")); - if(values == null){ - // cas of object filled by json from http and deserialized by Gson : - // [Energistics.Etp.v12.Datatypes.ArrayOfInt, {values=[48.0, ...] } ] - // this is translated by Gson as : [String = "Energistics.Etp.v12.Datatypes.ArrayOfInt", com.google.gson.internal.LinkedTreeMap = {'values': [[48.0, ...]]}] - values = (List) ((com.google.gson.internal.LinkedTreeMap) ((List)da.getData().getItem()).get(1)).get("values"); - } -// logger.info("@dataArraysToNumbers values {} ", values.subList(0,9)); - return values; - } catch (Exception ex) { - throw new RuntimeException(ex); + .map(da -> { + try { + List values = ((List) ObjectController.getObjectAttributeValue(da.getData().getItem(), "values")); + if(values == null){ + // cas of object filled by json from http and deserialized by Gson : + // [Energistics.Etp.v12.Datatypes.ArrayOfInt, {values=[48.0, ...] } ] + // this is translated by Gson as : [String = "Energistics.Etp.v12.Datatypes.ArrayOfInt", com.google.gson.internal.LinkedTreeMap = {'values': [[48.0, ...]]}] + values = (List) ((com.google.gson.internal.LinkedTreeMap) ((List)da.getData().getItem()).get(1)).get("values"); } - }) - .flatMap(List::stream).collect(Collectors.toList()); - /* - return das.stream() - .map(da -> { - try { - List values = ((List) ObjectController.getObjectAttributeValue(da.getData().getItem(), "values")); - if(values == null){ - // cas of object filled by json from http and deserialized by Gson : - // [Energistics.Etp.v12.Datatypes.ArrayOfInt, {values=[48.0, ...] } ] - // this is translated by Gson as : [String = "Energistics.Etp.v12.Datatypes.ArrayOfInt", com.google.gson.internal.LinkedTreeMap = {'values': [[48.0, ...]]}] - values = (List) ((com.google.gson.internal.LinkedTreeMap) ((List)da.getData().getItem()).get(1)).get("values"); - } - return values.stream().map(v-> v instanceof String ? Double.parseDouble((String) v) : ((Number)v).doubleValue()).collect(Collectors.toList()); - } catch (Exception ex) { - throw new RuntimeException(ex); - } - }) - .flatMap(List::stream).collect(Collectors.toList());*/ +// logger.info("@dataArraysToNumbers values {} ", values.subList(0,9)); + return values; + } catch (Exception ex) { + throw new RuntimeException(ex); + } + }) + .flatMap(List::stream).collect(Collectors.toList()); } + + private static final TrustManager MOCK_TRUST_MANAGER = new X509ExtendedTrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException { + + } + + @Override + public void checkServerTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException { + + } + + @Override + public void checkClientTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) throws CertificateException { + + } + + @Override + public void checkServerTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) throws CertificateException { + + } + + @Override + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return new java.security.cert.X509Certificate[0]; + } + + @Override + public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { + + } + + @Override + public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { + // empty method + } + // ... Other void methods + }; } diff --git a/src/main/java/com/geosiris/webstudio/model/WorkspaceContent.java b/src/main/java/com/geosiris/webstudio/model/WorkspaceContent.java index a61e506..d5f41a3 100644 --- a/src/main/java/com/geosiris/webstudio/model/WorkspaceContent.java +++ b/src/main/java/com/geosiris/webstudio/model/WorkspaceContent.java @@ -32,12 +32,14 @@ public class WorkspaceContent { private Map readObjects; private Map additionalInformation; private Map parsedRels; + private List loadedEpcNames; public WorkspaceContent() { this.notReadObjects = new ArrayList<>(); this.readObjects = new HashMap<>(); this.additionalInformation = new HashMap<>(); this.parsedRels = new HashMap<>(); + this.loadedEpcNames = new ArrayList<>(); } public List> getNotReadObjects() { @@ -64,6 +66,10 @@ public void setAdditionalInformation(Map additionalInformation) this.additionalInformation = additionalInformation; } + public List getLoadedEpcNames() { + return loadedEpcNames; + } + public void putAll(WorkspaceContent rf) { if(rf != null){ if(rf.notReadObjects != null) @@ -74,6 +80,8 @@ public void putAll(WorkspaceContent rf) { this.additionalInformation.putAll(rf.additionalInformation); if(rf.parsedRels != null) this.parsedRels.putAll(rf.parsedRels); + if(rf.loadedEpcNames != null) + this.loadedEpcNames.addAll(rf.loadedEpcNames); } } @@ -112,6 +120,7 @@ public String toJson(){ .collect(Collectors.toList())); vue.put("Other objects", notReadObjects.stream().map(Pair::l).collect(Collectors.toList())); + vue.put("Imported Epc files", loadedEpcNames); /*res.append("\"Other information\": ["); for(String name: additionalInformation.keySet()){ diff --git a/src/main/java/com/geosiris/webstudio/servlet/editing/FileReciever.java b/src/main/java/com/geosiris/webstudio/servlet/editing/FileReciever.java index 92b8423..8fb5208 100644 --- a/src/main/java/com/geosiris/webstudio/servlet/editing/FileReciever.java +++ b/src/main/java/com/geosiris/webstudio/servlet/editing/FileReciever.java @@ -183,6 +183,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) FileItemIterator iterator = upload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); + String inputFileName = item.getName(); InputStream stream = item.openStream(); if (item.isFormField() && item.getFieldName().compareTo("epcInputURL") == 0) { @@ -236,6 +237,9 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) } } else { WorkspaceContent currentFile = HttpSender.readFile(session, stream, item.getName()); + if(inputFileName.toLowerCase().endsWith(".epc")) { + currentFile.getLoadedEpcNames().add(inputFileName); + } loadedEPC.putAll(currentFile); } } @@ -260,6 +264,9 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) URL epcURL = new URL(SessionUtility.wsProperties.getDefaultDataEPCUrl()); InputStream epcFile = new BufferedInputStream(epcURL.openStream()); WorkspaceContent currentFile = HttpSender.readFile(session, epcFile, ""); + if(inputFileName.toLowerCase().endsWith(".epc")) { + currentFile.getLoadedEpcNames().add(inputFileName); + } loadedEPC.putAll(currentFile); } catch (Exception e) { logger.error(e.getMessage(), e); diff --git a/src/main/java/com/geosiris/webstudio/servlet/editing/ObjectEdit.java b/src/main/java/com/geosiris/webstudio/servlet/editing/ObjectEdit.java index 295a53d..f08ae36 100644 --- a/src/main/java/com/geosiris/webstudio/servlet/editing/ObjectEdit.java +++ b/src/main/java/com/geosiris/webstudio/servlet/editing/ObjectEdit.java @@ -248,6 +248,8 @@ public String editObject(HttpSession session, String rootUUID, String command, S Object newObj = Editor.pkgManager.createInstance(type, map, null, userName, false); String objUuid = ObjectController.getObjectAttributeValue(newObj, "Uuid") + ""; map.put(objUuid, newObj); + // Applying default values + ResqmlObjectControler.applyDefaultValues(newObj); SessionUtility.getWorkspaceContent(session).setReadObjects(map); response = "Object created with uuid " + objUuid; LoadWorkspace.updateWorkspace(session, objUuid); diff --git a/src/main/java/com/geosiris/webstudio/servlet/energyml/ObjectRelsTree.java b/src/main/java/com/geosiris/webstudio/servlet/energyml/ObjectRelsTree.java new file mode 100644 index 0000000..e8574b9 --- /dev/null +++ b/src/main/java/com/geosiris/webstudio/servlet/energyml/ObjectRelsTree.java @@ -0,0 +1,98 @@ +/* +Copyright 2019 GEOSIRIS + +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.geosiris.webstudio.servlet.energyml; + +import com.geosiris.energyml.utils.ObjectController; +import com.geosiris.webstudio.model.WorkspaceContent; +import com.geosiris.webstudio.utils.ObjectTree; +import com.geosiris.webstudio.utils.SessionUtility; +import com.geosiris.webstudio.utils.Utility; +import energyml.relationships.Relationships; +import jakarta.servlet.ServletException; +import jakarta.servlet.annotation.WebServlet; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * Servlet implementation class ResqmlObjectTree + */ +@WebServlet("/ObjectRelsTree") +public class ObjectRelsTree extends HttpServlet { + private static final long serialVersionUID = 1L; + public static Logger logger = LogManager.getLogger(ObjectRelsTree.class); + + /** + * @see HttpServlet#HttpServlet() + */ + public ObjectRelsTree() { + super(); + } + + /** + * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) + */ + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + if (!SessionUtility.tryConnectServlet(request, response)) { + return; + } + + HttpSession session = request.getSession(false); + + WorkspaceContent wc = SessionUtility.getWorkspaceContent(session); + String objectJSONTree = ""; + + String uuid = request.getParameter("uuid"); + if (uuid != null) { + if (!wc.getParsedRels().containsKey(uuid)) { + wc.getParsedRels().put(uuid, new Relationships()); + } + ObjectTree objTree = ObjectTree.createTree(wc.getParsedRels().get(uuid)); + if (objTree != null) + objectJSONTree = objTree.toJSON(); + else { + logger.error("Null json " + ObjectTree.createTree(wc.getParsedRels().get(uuid)).toJSON()); + } + } + if(objectJSONTree.length() == 0){ + objectJSONTree = "null"; + } + + PrintWriter out = response.getWriter(); + response.setContentType("application/json"); + response.setCharacterEncoding("UTF-8"); + out.write(objectJSONTree); + out.flush(); + } + + /** + * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) + */ + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doGet(request, response); + } + + +} diff --git a/src/main/java/com/geosiris/webstudio/servlet/etp/ETPConnexion.java b/src/main/java/com/geosiris/webstudio/servlet/etp/ETPConnexion.java index f2e00bb..1b33aaf 100644 --- a/src/main/java/com/geosiris/webstudio/servlet/etp/ETPConnexion.java +++ b/src/main/java/com/geosiris/webstudio/servlet/etp/ETPConnexion.java @@ -15,9 +15,13 @@ */ package com.geosiris.webstudio.servlet.etp; +import Energistics.Etp.v12.Datatypes.Object.ContextScopeKind; +import com.geosiris.etp.utils.ETPHelper; import com.geosiris.etp.websocket.ETPClient; +import com.geosiris.webstudio.utils.ETPRequestUtils; import com.geosiris.webstudio.utils.ETPUtils; import com.geosiris.webstudio.utils.SessionUtility; +import com.google.gson.Gson; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; @@ -37,6 +41,7 @@ import java.io.PrintWriter; import java.util.HashMap; import java.util.Locale; +import java.util.Map; /** * Servlet implementation class ETPConnexion @@ -44,7 +49,7 @@ @WebServlet("/ETPConnexion") public class ETPConnexion extends HttpServlet { private static final long serialVersionUID = 1L; - public static Logger logger = LogManager.getLogger(ETPConnexion.class); + public static Logger logger = LogManager.getLogger(ETPConnexion.class); /** * @see HttpServlet#HttpServlet() @@ -73,10 +78,10 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) answer = "unkown request"; } PrintWriter out = response.getWriter(); - response.setContentType("application/text"); - response.setCharacterEncoding("UTF-8"); - out.write(answer); - out.flush(); + response.setContentType("application/text"); + response.setCharacterEncoding("UTF-8"); + out.write(answer); + out.flush(); } /** @@ -91,6 +96,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) String userName = null; String password = null; + Map headers = new HashMap<>(); boolean askConnection = true; HttpURI host_uri = null; @@ -123,6 +129,9 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) if (value.compareToIgnoreCase("disconnect") == 0) { askConnection = false; } + }else if ("etp-server-headers".compareToIgnoreCase(item.getFieldName()) == 0) { + Gson gson = new Gson(); + headers.putAll(gson.fromJson(value, HashMap.class)); } } } @@ -146,20 +155,22 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) if (value.compareToIgnoreCase("disconnect") == 0) { askConnection = false; } + }else if ("etp-server-headers".compareToIgnoreCase(k) == 0) { + Gson gson = new Gson(); + headers.putAll(gson.fromJson(value, HashMap.class)); } } } logger.info("#ETP : host " + host_uri); logger.info(request.getSession(false)); - ETPClient client = ETPUtils.establishConnexion(request.getSession(false), host_uri, userName, password, null, new HashMap<>(), askConnection); + ETPClient client = ETPUtils.establishConnexion(request.getSession(false), host_uri, userName, password, null, headers, askConnection); PrintWriter out = response.getWriter(); - response.setContentType("application/text"); - response.setCharacterEncoding("UTF-8"); - out.write(String.valueOf(client != null)); - out.flush(); + response.setContentType("application/text"); + response.setCharacterEncoding("UTF-8"); + out.write(String.valueOf(client != null)); + out.flush(); } - } diff --git a/src/main/java/com/geosiris/webstudio/servlet/etp/ETPListDataspaces.java b/src/main/java/com/geosiris/webstudio/servlet/etp/ETPListDataspaces.java index 1de6691..59753de 100644 --- a/src/main/java/com/geosiris/webstudio/servlet/etp/ETPListDataspaces.java +++ b/src/main/java/com/geosiris/webstudio/servlet/etp/ETPListDataspaces.java @@ -27,6 +27,8 @@ import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.io.IOException; import java.io.PrintWriter; @@ -39,6 +41,7 @@ @WebServlet("/ETPListDataspaces") public class ETPListDataspaces extends HttpServlet { private static final long serialVersionUID = 1L; + public static Logger logger = LogManager.getLogger(ETPListDataspaces.class); /** * @see HttpServlet#HttpServlet() @@ -63,10 +66,15 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) if(isConnected){ GetDataspaces getRess = GetDataspaces.newBuilder().setStoreLastWriteFilter(0L).build(); long id = etpClient.send(getRess); - List ressResp_l = etpClient.getEtpClientSession().waitForResponse(id, 100000); - for(Dataspace ds : ((GetDataspacesResponse)ressResp_l.get(0).getBody()).getDataspaces()){ - dataspacesNames.add(searchDataspaceNameFromUri(ds.getUri()+"")); - } + try { + List ressResp_l = etpClient.getEtpClientSession().waitForResponse(id, 5000); + for (Dataspace ds : ((GetDataspacesResponse) ressResp_l.get(0).getBody()).getDataspaces()) { + dataspacesNames.add(searchDataspaceNameFromUri(ds.getUri() + "")); + } + }catch (Exception e){logger.error(e);} + } + if(dataspacesNames.isEmpty()){ + dataspacesNames.add("eml:///"); } PrintWriter out = response.getWriter(); diff --git a/src/main/java/com/geosiris/webstudio/servlet/etp/ETPLoadSurfaceInVue.java b/src/main/java/com/geosiris/webstudio/servlet/etp/ETPLoadSurfaceInVue.java index 6ec7a8d..f0f79c0 100644 --- a/src/main/java/com/geosiris/webstudio/servlet/etp/ETPLoadSurfaceInVue.java +++ b/src/main/java/com/geosiris/webstudio/servlet/etp/ETPLoadSurfaceInVue.java @@ -108,7 +108,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) List surfaces = new ArrayList<>(); for(ETPUri etpUri: mapUri.values()) { try { - surfaces.add(ETPUtils.get3DFileFromETP((ETPClient) session.getAttribute(SessionUtility.SESSION_ETP_CLIENT_ID), session, etpUri.toString(), File3DType.OFF)); + surfaces.add(ETPUtils.get3DFileFromETP((ETPClient) session.getAttribute(SessionUtility.SESSION_ETP_CLIENT_ID), session, etpUri.toString(), File3DType.OBJ)); } catch (Exception e) { logger.error(e.getMessage(), e); } diff --git a/src/main/java/com/geosiris/webstudio/servlet/etp/ETPRequest.java b/src/main/java/com/geosiris/webstudio/servlet/etp/ETPRequest.java index f926557..3f32bf8 100644 --- a/src/main/java/com/geosiris/webstudio/servlet/etp/ETPRequest.java +++ b/src/main/java/com/geosiris/webstudio/servlet/etp/ETPRequest.java @@ -15,10 +15,9 @@ */ package com.geosiris.webstudio.servlet.etp; -import Energistics.Etp.v12.Datatypes.Object.ActiveStatusKind; -import Energistics.Etp.v12.Datatypes.Object.ContextScopeKind; -import Energistics.Etp.v12.Datatypes.Object.DataObject; -import Energistics.Etp.v12.Datatypes.Object.Resource; +import Energistics.Etp.v12.Datatypes.Object.*; +import Energistics.Etp.v12.Protocol.Dataspace.PutDataspaces; +import Energistics.Etp.v12.Protocol.Dataspace.PutDataspacesResponse; import Energistics.Etp.v12.Protocol.Discovery.GetResources; import Energistics.Etp.v12.Protocol.Discovery.GetResourcesResponse; import Energistics.Etp.v12.Protocol.Store.*; @@ -47,6 +46,7 @@ import jakarta.servlet.http.HttpSession; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.eclipse.jetty.http.HttpURI; import javax.xml.datatype.XMLGregorianCalendar; import java.io.IOException; @@ -81,7 +81,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) return; } - PrintWriter out = response.getWriter(); + PrintWriter out = response.getWriter(); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); out.write(ETPRequestUtils.getAllBuildableMessages()); @@ -120,6 +120,9 @@ private String manageETPRequest(Map> parameterMap, HttpSess if(parameterMap.containsKey("dataspace")){ dataspace = parameterMap.get("dataspace").get(0); } + if(dataspace!=null && (dataspace.isEmpty() || dataspace.compareToIgnoreCase("eml:///") == 0)){ + dataspace = null; + } boolean ask_aknowledge = parameterMap.containsKey("ask_aknowledge"); @@ -134,7 +137,7 @@ private String manageETPRequest(Map> parameterMap, HttpSess try { StringBuilder req_result = new StringBuilder(); if (request.toLowerCase().startsWith("getresource")) { - + logger.info("Getting resources : " + new ETPUri(dataspace)); GetResources getRess = ETPDefaultProtocolBuilder.buildGetResources(new ETPUri(dataspace).toString(), ContextScopeKind.self, new ArrayList<>()); @@ -169,6 +172,18 @@ private String manageETPRequest(Map> parameterMap, HttpSess logger.info("null GetResourcesResponse "); } } + } else if (request.toLowerCase().startsWith("putdataspace")) { + String newDataspace = parameterMap.get("newDataspace").get(0); + PutDataspaces pds = PutDataspaces.newBuilder() + .setDataspaces(Map.of("0", Dataspace.newBuilder() + .setUri(new ETPUri(newDataspace).toString()) + .setStoreLastWrite(0) + .setStoreCreated(0) + .setPath(dataspace) + .setCustomData(new HashMap<>()) + .build()) + ).build(); + ETPUtils.sendETPRequest(session, etpClient, pds, ask_aknowledge, ETPUtils.waitingForResponseTime); } else if (request.toLowerCase().startsWith("deletedataobject")) { Map mapUri = new HashMap<>(); for (String uri : parameterMap.get("etp_uri")) { @@ -209,8 +224,8 @@ private String manageETPRequest(Map> parameterMap, HttpSess etpuri.setDataspace(dataspace); } SessionUtility.log(session, new ServerLogMessage(MessageType.LOG, - "ETP request import on " + etpuri + " == " + etpuri.hasDataspace() + " --- " + etpuri.getDataspace(), - SessionUtility.EDITOR_NAME)); + "ETP request import on " + etpuri + " == " + etpuri.hasDataspace() + " --- " + etpuri.getDataspace(), + SessionUtility.EDITOR_NAME)); mapUri.put(mapUri.size()+"", etpuri.toString()); } @@ -369,7 +384,7 @@ private Pair, String> getDataObjectMaptoURI(List, String> getDataObjectMaptoURI(List(mapResult, logs.toString()); } + } diff --git a/src/main/java/com/geosiris/webstudio/filters/SameSiteFilter.java b/src/main/java/com/geosiris/webstudio/servlet/filters/SameSiteFilter.java similarity index 97% rename from src/main/java/com/geosiris/webstudio/filters/SameSiteFilter.java rename to src/main/java/com/geosiris/webstudio/servlet/filters/SameSiteFilter.java index 83509c4..4af17d6 100644 --- a/src/main/java/com/geosiris/webstudio/filters/SameSiteFilter.java +++ b/src/main/java/com/geosiris/webstudio/servlet/filters/SameSiteFilter.java @@ -13,7 +13,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package com.geosiris.webstudio.filters; +package com.geosiris.webstudio.servlet.filters; import jakarta.servlet.*; import jakarta.servlet.http.HttpServletResponse; diff --git a/src/main/java/com/geosiris/webstudio/servlet/rest/ETPSurfaceToFile.java b/src/main/java/com/geosiris/webstudio/servlet/rest/ETPSurfaceToFile.java index d674455..299cb01 100644 --- a/src/main/java/com/geosiris/webstudio/servlet/rest/ETPSurfaceToFile.java +++ b/src/main/java/com/geosiris/webstudio/servlet/rest/ETPSurfaceToFile.java @@ -15,8 +15,13 @@ */ package com.geosiris.webstudio.servlet.rest; +import com.geosiris.energyml.data.Mesh; +import com.geosiris.energyml.utils.ObjectController; +import com.geosiris.energyml.utils.Utils; import com.geosiris.etp.utils.ETPUri; import com.geosiris.etp.websocket.ETPClient; +import com.geosiris.webstudio.etp.ETPWorkspace; +import com.geosiris.webstudio.logs.ServerLogMessage; import com.geosiris.webstudio.model.ETP3DObject; import com.geosiris.webstudio.utils.ETPUtils; import com.geosiris.webstudio.utils.File3DType; @@ -31,11 +36,12 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.PrintWriter; +import java.io.*; +import java.lang.reflect.InvocationTargetException; import java.util.*; +import static com.geosiris.energyml.data.SurfaceMesh.exportObj; + /** * Servlet implementation class ETPSurfaceToOff */ @@ -114,10 +120,17 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) List surfaces = new ArrayList<>(); for(ETPUri etpUri: mapUri.values()) { + String err_msg = "Failed to load 3D surface : " + etpUri; try { - surfaces.add(ETPUtils.get3DFileFromETP(etpClient, null, etpUri.toString(), fileFormat)); + ETP3DObject o = ETPUtils.get3DFileFromETP(etpClient, null, etpUri.toString(), fileFormat); + if(o == null){ + SessionUtility.log(request.getSession(), new ServerLogMessage(ServerLogMessage.MessageType.TOAST, err_msg, "Surface loader")); + }else { + surfaces.add(o); + } } catch (Exception e) { logger.error(e.getMessage(), e); + SessionUtility.log(request.getSession(), new ServerLogMessage(ServerLogMessage.MessageType.TOAST, err_msg, "Surface loader")); } } PrintWriter out = response.getWriter(); @@ -127,4 +140,31 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) out.flush(); } + public static void main(String[] argv) throws IOException, InvocationTargetException, IllegalAccessException { + String serverUrl = "https://rdms.geosiris.com:443/etp"; + String username = "FAKE"; + String password = "FAKE"; + ETPClient etpClient = ETPUtils.establishConnexion(null, ETPUtils.getHttpUriETP(serverUrl), username, password, null, new HashMap<>(), true); + + ETPUri etpuri = ETPUri.parse("eml:///dataspace('brgm')/resqml22.TriangulatedSetRepresentation(ffbf9912-c2d2-489f-a924-7d14e2627134)"); +// ETPUri etpuri = ETPUri.parse("eml:///dataspace('brgm')/resqml22.PointSetRepresentation(c26dfedf-c354-4263-9219-97797638beef)"); +// ETPUri etpuri = ETPUri.parse("eml:///dataspace('brgm')/resqml22.TriangulatedSetRepresentation(e648b1d0-70a3-46c6-9be8-b12625661c2b)"); +// ETPUri etpuri = ETPUri.parse("eml:///dataspace('brgm')/resqml22.TriangulatedSetRepresentation(16ca92d0-912b-4c3d-a8d5-86378c9e8be5)"); +// ETPUri etpuri = ETPUri.parse("eml:///dataspace('brgm')/resqml22.PolylineSetRepresentation(2ab8076e-a9cd-4e4b-b9af-a32f8f434f43)"); +// ETPUri etpuri = ETPUri.parse("eml:///dataspace('brgm')/resqml22.PolylineSetRepresentation(8ba85389-0ab9-4a79-a6ac-a4de0d7b1cb2)"); +// ETPUri etpuri = ETPUri.parse("eml:///dataspace('brgm')/resqml22.PolylineSetRepresentation(8236dd72-0944-4df1-abfc-28e86b2e446e)"); +// ETPUri etpuri = ETPUri.parse("eml:///dataspace('brgm')/resqml22.PolylineSetRepresentation(950e490a-f12c-4920-bc66-70ef4a5aaba0)"); + + + ETPWorkspace workspace = new ETPWorkspace(etpuri.getDataspace(), etpClient); + Object obj = workspace.getEnergisticsObject(etpuri.toString()); + System.out.println(obj); + exportObj(Mesh.readMeshObject(obj, workspace), + new FileOutputStream("D:/Geosiris/Cloud/Geo-Workflow/BRGM/BRGM_RESQML_PROJECT/AVRE/results/" + etpuri.getObjectType() + "_" + etpuri.getUuid() + + ObjectController.getObjectAttributeValue(obj, "citation.Title") + ".obj"), "test", false); + + etpClient.closeClient(); + + } + } diff --git a/src/main/java/com/geosiris/webstudio/utils/ETPUtils.java b/src/main/java/com/geosiris/webstudio/utils/ETPUtils.java index 722ca51..5ce3598 100644 --- a/src/main/java/com/geosiris/webstudio/utils/ETPUtils.java +++ b/src/main/java/com/geosiris/webstudio/utils/ETPUtils.java @@ -15,9 +15,8 @@ */ package com.geosiris.webstudio.utils; -import Energistics.Etp.v12.Datatypes.DataValue; +import Energistics.Etp.v12.Datatypes.*; import Energistics.Etp.v12.Datatypes.Object.*; -import Energistics.Etp.v12.Datatypes.ServerCapabilities; import Energistics.Etp.v12.Protocol.Discovery.GetResources; import Energistics.Etp.v12.Protocol.Discovery.GetResourcesResponse; import Energistics.Etp.v12.Protocol.Store.PutDataObjects; @@ -48,6 +47,8 @@ import com.geosiris.webstudio.model.ETP3DObject; import com.geosiris.webstudio.servlet.Editor; import com.google.gson.Gson; +import energyml.resqml2_0_1.ObjPointSetRepresentation; +import energyml.resqml2_2.PointSetRepresentation; import jakarta.servlet.http.HttpSession; import jakarta.xml.bind.JAXBException; import org.apache.avro.specific.SpecificRecordBase; @@ -68,6 +69,7 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; +import static com.geosiris.energyml.utils.EPCGenericManager.getObjectTypeForFilePath_fromClassName; import static com.geosiris.energyml.utils.EnergymlWorkspaceHelper.getCrsObj; import static com.geosiris.energyml.utils.EnergymlWorkspaceHelper.readArray; import static com.geosiris.energyml.utils.ObjectController.searchAttributeMatchingNameWithPath; @@ -78,12 +80,18 @@ public class ETPUtils { public static HttpURI getHttpUriETP(String serverUrl){ + HttpURI uri = null; if(serverUrl.toLowerCase(Locale.ROOT).startsWith("http:")) { - serverUrl = "ws" + serverUrl.substring(4); + uri = new HttpURI("ws" + serverUrl.substring(4)); + }else if(serverUrl.toLowerCase(Locale.ROOT).startsWith("https:")) { + uri = new HttpURI("wss" + serverUrl.substring(5)); }else if(!serverUrl.toLowerCase(Locale.ROOT).startsWith("ws") && !serverUrl.toLowerCase(Locale.ROOT).startsWith("wss") ){ - serverUrl = "ws://" + serverUrl; + uri = new HttpURI("ws://" + serverUrl); + }else{ + uri = new HttpURI(serverUrl); } - return new HttpURI(serverUrl); + logger.info(uri); + return uri; } public static List sendETPRequest(HttpSession session, ETPClient etpClient, SpecificRecordBase msg, @@ -135,16 +143,16 @@ public static ETPClient establishConnexion( Boolean askConnection ) { Map parsedHeaders = new HashMap<>(); - try{ - Gson gson = new Gson(); - parsedHeaders = gson.fromJson(headers, HashMap.class); - }catch (Exception ignore){} + try{ + Gson gson = new Gson(); + parsedHeaders = gson.fromJson(headers, HashMap.class); + }catch (Exception ignore){} if(parsedHeaders == null){ parsedHeaders = new HashMap<>(); } - for(Map.Entry he: parsedHeaders.entrySet()){ - logger.info("Headers " + he.getKey() + " " + he.getValue()); - } + for(Map.Entry he: parsedHeaders.entrySet()){ + logger.info("Headers " + he.getKey() + " " + he.getValue()); + } return establishConnexion(session, host, userName, password, token, parsedHeaders, askConnection); } @@ -299,6 +307,19 @@ public static String getDataObjectFromUuid(HttpSession session, String dataspace return result; } + public static List computeSupportedProtocols(Map protocolHandlers){ + List supported = new ArrayList<>(); + for(Map.Entry ph: protocolHandlers.entrySet()){ + supported.add(new SupportedProtocol( + ph.getKey().id, + Version.newBuilder().setMajor(1).setMinor(2).build(), // TODO: change version when etp changes + "store", + new HashMap<>() + )); + } + + return supported; + } private static ETPClient establishConnexionForClient( HttpSession session, @@ -315,27 +336,41 @@ private static ETPClient establishConnexionForClient( // mapCaps.put("MaxWebSocketMessagePayloadSize", DataValue.newBuilder().setItem(40000).build()); ServerCapabilities caps = new ServerCapabilities(); caps.setEndpointCapabilities(mapCaps); + +// List sdo = new ArrayList<>(); +// Map doc_eml = new HashMap<>(); +// doc_eml.put("SupportsDelete", DataValue.newBuilder().setItem(true).build()); +// doc_eml.put("SupportsPut", DataValue.newBuilder().setItem(true).build()); +// doc_eml.put("SupportsGet", DataValue.newBuilder().setItem(true).build()); +// sdo.add(SupportedDataObject.newBuilder().setQualifiedType("eml20.*").setDataObjectCapabilities(doc_eml).build()); +// caps.setSupportedDataObjects(sdo); + Map protocolHandlers = new HashMap<>(); if(useDefaultHandler){ protocolHandlers.put(CoreHandler_WebStudio.protocol, new CoreHandler_WebStudio()); - protocolHandlers.put(StoreHandler.protocol, new StoreHandler()); - protocolHandlers.put(DataspaceHandler.protocol, new DataspaceHandler()); protocolHandlers.put(DiscoveryHandler.protocol, new DiscoveryHandler()); + protocolHandlers.put(StoreHandler.protocol, new StoreHandler()); + if(host.getHost().contains("geosiris")) + protocolHandlers.put(DataspaceHandler.protocol, new DataspaceHandler()); protocolHandlers.put(DataArrayHandler.protocol, new DataArrayHandler_WebStudio()); }else{ protocolHandlers.put(CoreHandler_WebStudio.protocol, new CoreHandler_WebStudio()); - protocolHandlers.put(StoreHandler_WebStudio.protocol, new StoreHandler_WebStudio(session)); - protocolHandlers.put(DataspaceHandler_WebStudio.protocol, new DataspaceHandler_WebStudio()); protocolHandlers.put(DiscoveryHandler_WebStudio.protocol, new DiscoveryHandler_WebStudio()); + protocolHandlers.put(StoreHandler_WebStudio.protocol, new StoreHandler_WebStudio(session)); + if(host.getHost().contains("geosiris")) + protocolHandlers.put(DataspaceHandler_WebStudio.protocol, new DataspaceHandler_WebStudio(session)); protocolHandlers.put(DataArrayHandler.protocol, new DataArrayHandler_WebStudio()); } + + caps.setSupportedProtocols(computeSupportedProtocols(protocolHandlers)); // TODO : remove when etpproto-java is updated + ETPConnection etpConnection = new ETPConnection(ConnectionType.CLIENT, caps, clientInfo, protocolHandlers); if(token != null && !token.trim().isEmpty()){ - return ETPClient.getInstanceWithAuth_Token(host, etpConnection, 5000, token, headers); + return ETPClient.getInstanceWithAuth_Token(host, etpConnection, 5000, token, 1 << 22, headers); }else { - return ETPClient.getInstanceWithAuth_Basic(host, etpConnection, 5000, userName, password, headers); + return ETPClient.getInstanceWithAuth_Basic(host, etpConnection, 5000, userName, password, 1 << 22, headers); } } @@ -494,7 +529,7 @@ public static ETP3DObject get3DFileFromETP(ETPClient etpClient, HttpSession sess String epsgCode = null; logger.info("URI to load " + uri + " ==> " + obj); - String objClassNameLC = obj.getClass().getSimpleName().toLowerCase(); + String objClassNameLC = obj.getClass().getName(); List meshes = null; try { @@ -815,5 +850,7 @@ public static List readPointRepresentation(Object energymlObject, public static void main(String[] argv){ System.out.println(hsvToRgb(180.0f, 33.0f, 100.0f)); + System.out.println(getObjectTypeForFilePath_fromClassName(ObjPointSetRepresentation.class.getName())); + System.out.println(getObjectTypeForFilePath_fromClassName(PointSetRepresentation.class.getSimpleName())); } } diff --git a/src/main/java/com/geosiris/webstudio/utils/ObjectTree.java b/src/main/java/com/geosiris/webstudio/utils/ObjectTree.java index c45c54a..e6a429a 100644 --- a/src/main/java/com/geosiris/webstudio/utils/ObjectTree.java +++ b/src/main/java/com/geosiris/webstudio/utils/ObjectTree.java @@ -20,6 +20,7 @@ import com.geosiris.webstudio.property.ConfigurationType; import com.geosiris.webstudio.servlet.Editor; import com.google.gson.Gson; +import energyml.relationships.Relationships; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -351,7 +352,8 @@ public String toJSON() { StringBuilder jsonValue = new StringBuilder(); jsonValue.append(" { \"name\" : \"").append(name).append("\",\n"); - jsonValue.append(" \"type\" : \"").append(dataClass.getCanonicalName()).append("\",\n"); + if(dataClass != null) + jsonValue.append(" \"type\" : \"").append(dataClass.getCanonicalName()).append("\",\n"); jsonValue.append(" \"mandatory\" : \"").append(isMandatory).append("\",\n"); if (dataClassTemplatedList != null && dataClassTemplatedList.size() > 0) { @@ -402,7 +404,7 @@ public String toJSON() { // }else { // On met une valeur si ce n'est pas un array et si c'est un type modifiable // directement (comme les proprietes) - if (data != null && !dataClass.getName().toLowerCase().endsWith("array") + if (data != null && dataClass != null && !dataClass.getName().toLowerCase().endsWith("array") && ObjectController.isPropertyClass(data.getClass())) { String dataAsString = data + ""; if (data.getClass().isEnum()) { @@ -416,7 +418,7 @@ public String toJSON() { } dataAsString = Utility.transformStringForJsonCompatibility(dataAsString); jsonValue.append(" \"value\" : ").append(dataAsString).append("\n"); - } else if (data == null && ObjectController.isPrimitiveClass(dataClass)) { + } else if (data == null && dataClass != null && ObjectController.isPrimitiveClass(dataClass)) { jsonValue.append(" \"value\" : \"\"\n"); } else { jsonValue = new StringBuilder(jsonValue.substring(0, jsonValue.lastIndexOf(",")) + " "); @@ -465,4 +467,8 @@ public String toString() { public ObjectTree getParent() { return parent; } + + public static void main(String[] argv){ + System.out.println(createTree(new Relationships()).toJSON()); + } } diff --git a/src/main/java/com/geosiris/webstudio/utils/ResqmlObjectControler.java b/src/main/java/com/geosiris/webstudio/utils/ResqmlObjectControler.java index 8936e25..d0d926b 100644 --- a/src/main/java/com/geosiris/webstudio/utils/ResqmlObjectControler.java +++ b/src/main/java/com/geosiris/webstudio/utils/ResqmlObjectControler.java @@ -56,10 +56,10 @@ public static void modifyResqmlObjectFromParameter(HttpSession session, Object r } private static void modifyResqmlObjectFromParameter(HttpSession session, Object resqmlObj, String paramPath, - ModficationType modifType, Object value, - Map epcObjects, - String completePath, - Object rootObject + ModficationType modifType, Object value, + Map epcObjects, + String completePath, + Object rootObject ) throws Exception { if (resqmlObj != null) { @@ -432,26 +432,27 @@ public static Object randomizecontent(Class objClass, WorkspaceContent wc){ private static Map extTypes = Editor.pkgManager.getExtTypesAsJson(SessionUtility.wsProperties.getDirPathToExtTypes()); public static Object createInstance(Class objClass, WorkspaceContent wc, Object parent, String thisAttributeName){ + Object objInstance = null; + if(objClass.getName().compareToIgnoreCase("java.lang.Object") == 0) return null; if(objClass.isEnum()){ - return objClass.getEnumConstants()[RANDOMIZER.nextInt(objClass.getEnumConstants().length)]; + objInstance = objClass.getEnumConstants()[RANDOMIZER.nextInt(objClass.getEnumConstants().length)]; }else{ if(Number.class.isAssignableFrom(objClass)){ Integer rand = RANDOMIZER.nextInt(100); try { - return objClass.getMethod("valueOf", String.class).invoke(null, String.valueOf(rand)); - } catch (Exception e) {e.printStackTrace();} + objInstance = objClass.getMethod("valueOf", String.class).invoke(null, String.valueOf(rand)); + } catch (Exception e) {logger.error(e);} }else if(Boolean.class.isAssignableFrom(objClass)){ int rand = RANDOMIZER.nextInt(2); - return rand != 0; + objInstance = rand != 0; }else if(objClass.isPrimitive()){ - Integer rand = RANDOMIZER.nextInt(100); try { - return createInstance( + objInstance = createInstance( Class.forName("java.lang." + objClass.getSimpleName().substring(0,1).toUpperCase() + objClass.getSimpleName().substring(1)), wc, parent, thisAttributeName ); - } catch (ClassNotFoundException e) {e.printStackTrace();} + } catch (ClassNotFoundException e) {logger.error(e);} }else if(String.class.isAssignableFrom(objClass)){ if(thisAttributeName != null){ String refClass = (parent!=null?parent.getClass().getName():objClass.getName()).toLowerCase(); @@ -461,12 +462,12 @@ public static Object createInstance(Class objClass, WorkspaceContent wc, Obje if(thisAttributeName.compareToIgnoreCase("uuid") == 0 || thisAttributeName.compareToIgnoreCase("uid") == 0 ){ - return UUID.randomUUID().toString(); + objInstance = UUID.randomUUID().toString(); }else if(extTypes.containsKey(attribPath)){ try { String enumClassName = extTypes.get(attribPath); if(enumClassName.toLowerCase().endsWith("ext")) enumClassName = enumClassName.substring(0,enumClassName.length()-3); - return String.valueOf( + objInstance = String.valueOf( createInstance( Class.forName(enumClassName), wc, parent, thisAttributeName @@ -474,39 +475,38 @@ public static Object createInstance(Class objClass, WorkspaceContent wc, Obje ); } catch (ClassNotFoundException e) { - e.printStackTrace(); - return "Randomization of " + thisAttributeName + "(" + RANDOMIZER.nextInt() + ") ExtEnum value failed to generate"; + logger.error(e); + objInstance = "Randomization of " + thisAttributeName + "(" + RANDOMIZER.nextInt() + ") ExtEnum value failed to generate"; } }else{ - return "Randomization of " + thisAttributeName + "(" + RANDOMIZER.nextInt() + ") ";// + attribPath; + objInstance = "Randomization of " + thisAttributeName + "(" + RANDOMIZER.nextInt() + ") ";// + attribPath; } }else{ - return "A random value (" + RANDOMIZER.nextInt() + ")"; + objInstance = "A random value (" + RANDOMIZER.nextInt() + ")"; } }else if(objClass.getSimpleName().compareToIgnoreCase("DataObjectReference") == 0){ // TODO }else if(XMLGregorianCalendar.class.isAssignableFrom(objClass)){ - return Utils.getCalendarForNow(); + objInstance = Utils.getCalendarForNow(); }else if(Collection.class.isAssignableFrom(objClass)){ try { - Collection objInstance = (Collection) (!Modifier.isAbstract(objClass.getModifiers()) ? objClass.getDeclaredConstructor().newInstance(): new ArrayList<>()); + objInstance = (!Modifier.isAbstract(objClass.getModifiers()) ? objClass.getDeclaredConstructor().newInstance(): new ArrayList<>()); for(int i=0; i> possibleClasses = ObjectController.getResqmlInheritorClasses(objClass.getName(), energymlPkg.getPkgClasses()); - return createInstance( + objInstance = createInstance( possibleClasses.get(RANDOMIZER.nextInt(possibleClasses.size())), wc, parent, thisAttributeName ); }else { try { - Object objInstance = objClass.getDeclaredConstructor().newInstance(); + objInstance = objClass.getDeclaredConstructor().newInstance(); for (Pair, String> param : ObjectController.getClassAttributes(objClass)) { Object paramInstance = createInstance(param.l(), wc, objInstance, param.r()); if(Collection.class.isAssignableFrom(param.l())) { @@ -515,15 +515,26 @@ public static Object createInstance(Class objClass, WorkspaceContent wc, Obje ObjectController.editObjectAttribute(objInstance, param.r(), paramInstance); } } - return objInstance; } catch (Exception e) { System.err.println("Failed to instanciate class " + objClass + " for attribute " + thisAttributeName); - e.printStackTrace(); + logger.error(e); } } } } - return null; + return objInstance; + } + + public static Object applyDefaultValues(Object obj){ + try { + modifyResqmlObjectFromParameter(null, + obj, + ".AscendingOrderingCriteria", + ModficationType.EDITION, "AGE", + new HashMap<>() + ); + }catch (Exception _ignore){} + return obj; } public static void main(String[] argv){ diff --git a/src/main/java/com/geosiris/webstudio/utils/ResqmlVerification.java b/src/main/java/com/geosiris/webstudio/utils/ResqmlVerification.java index 140fd2c..225c93a 100644 --- a/src/main/java/com/geosiris/webstudio/utils/ResqmlVerification.java +++ b/src/main/java/com/geosiris/webstudio/utils/ResqmlVerification.java @@ -17,10 +17,16 @@ import com.geosiris.energyml.utils.EPCGenericManager; import com.geosiris.energyml.utils.ObjectController; +import com.geosiris.energyml.utils.Utils; import com.geosiris.webstudio.logs.LogResqmlVerification; import com.geosiris.webstudio.logs.ServerLogMessage; import com.geosiris.webstudio.servlet.Editor; import com.geosiris.webstudio.servlet.global.GetAdditionalObjects; + +import energyml.common2_3.Citation; +import energyml.common2_3.DataObjectReference; +import energyml.resqml2_2.TriangulatedSetRepresentation; + import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -353,6 +359,9 @@ private static List verifyReferencedDOR( } else { Object referencedObj = resqmlObjects.get(refUuid); String refObjVersion = (String) ObjectController.getObjectAttributeValue(referencedObj, "ObjectVersion"); + if(refObjVersion == null){ + refObjVersion = (String) ObjectController.getObjectAttributeValue(referencedObj, "Citation.VersionString"); + } String refObjTitle = (String) ObjectController.getObjectAttributeValue(referencedObj, "Citation.Title"); String refObjContentType = EPCGenericManager.getObjectContentType(referencedObj); String refObjQualifiedType = EPCGenericManager.getObjectQualifiedType(referencedObj); @@ -405,7 +414,7 @@ private static List verifyReferencedDOR( || (refObjVersion != null && refObjVersion.compareTo(objVersion) != 0) ) { messages.add(new LogResqmlVerification("DOR reference has wrong information", - "Referenced object Version is '" + refObjTitle + "' and not '" + objVersion + "Referenced object Version is '" + refObjVersion + "' and not '" + objVersion + "' at path : " + dor.getName(), rootUUID, rootTitle, @@ -491,7 +500,7 @@ private static List verifyWithXSDSchema(Object resqmlObje Editor.pkgManager.validate(resqmlObject); }catch (Exception e){ messages.add(new LogResqmlVerification("XSD validation fail", - "[" + objUuid + "] xsd validation failed : '" + e.getCause() + "'\n" + e.getMessage(), + "[" + objUuid + "] xsd validation failed : '" + e.getCause() + "'" + e.getMessage(), objUuid, objTitle, objType, ServerLogMessage.MessageType.INFO)); } @@ -530,6 +539,9 @@ private static List correctDORInformation(final Object re // DOR infos String dorTitle = (String) ObjectController.getObjectAttributeValue(dor, "Title"); String dorVersion = (String) ObjectController.getObjectAttributeValue(dor, "ObjectVersion"); + if(dorVersion == null){ + dorVersion = (String) ObjectController.getObjectAttributeValue(dor, "VersionString"); + } // Target object infos Object dorTarget; @@ -542,6 +554,9 @@ private static List correctDORInformation(final Object re String targetTitle = (String) ObjectController.getObjectAttributeValue(dorTarget, "Citation.Title"); String targetVersion = (String) ObjectController.getObjectAttributeValue(dorTarget, "ObjectVersion"); + if(targetVersion == null){ + targetVersion = (String) ObjectController.getObjectAttributeValue(dorTarget, "Citation.VersionString"); + } if(ObjectController.hasAttribute(dor, "ContentType")){ String dorType = (String) ObjectController.getObjectAttributeValue(dor, "ContentType"); @@ -574,6 +589,10 @@ private static List correctDORInformation(final Object re ObjectController.editObjectAttribute(dor, "ObjectVersion", targetVersion); modificationOccured = true; } catch (Exception ignore){} + try { + ObjectController.editObjectAttribute(dor, "Citation.VersionString", targetVersion); + modificationOccured = true; + } catch (Exception ignore){} } if(modificationOccured){ @@ -774,4 +793,30 @@ public static List doCorrectSchemaVersion(Map SameSiteFilter - com.geosiris.webstudio.filters.SameSiteFilter + com.geosiris.webstudio.servlet.filters.SameSiteFilter SameSiteFilter diff --git a/src/main/webapp/jsp/htmlParts/modal_ETP.jsp b/src/main/webapp/jsp/htmlParts/modal_ETP.jsp index 405c961..a8afee2 100644 --- a/src/main/webapp/jsp/htmlParts/modal_ETP.jsp +++ b/src/main/webapp/jsp/htmlParts/modal_ETP.jsp @@ -33,6 +33,12 @@ limitations under the License. document.getElementById("submit_getDataArray").onclick = function(){ sendForm('ETPRequest_getDataArray_Form', 'modal_ETP', 'rolling_ETP', false, false, false); } + document.getElementById("submit_putDataspace").onclick = function(){ + sendForm('ETPRequest_putDataspace_Form', 'modal_ETP', 'rolling_ETP', false, false, false); + // $('form#ETPRequest_putDataspace_Form').submit(function(e){ + // e.preventDefault(); + // }); + }