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(); + // }); + } @@ -59,6 +65,9 @@ limitations under the License. Get related resources + + Put dataspace + + + + + + + + Dataspace name + + + + + Send + + + + " + this.type + " :: " + (this.type.toLowerCase().includes('calendar'))) - -// console.log(this.name + " --> " + this.type + " :: " + (this.type.toLowerCase().includes('calendar'))) - var divCollapseInput_TMP = null; - if(this.parentElt.properties!=null && this.type.toLowerCase().includes("string") && (this.parentElt.properties.length==1 || (this.value != null && this.value.length > 100)) ){ +export class ResqmlElement { + + + + /*constructor(){ + this.htmlAttributeElt = null; // balise html de l'element courant dans l'arbre de visualisation + this.htmlTitleElt = null; // balise html du titre de l'objet + this.htmlSubAttribCreatorList = null; // balise html qui liste les sous élement qu'il est possible de créer + this.htmlSubAttribElt = null; // balise html contenant tous les sous-attributs + this.htmlPropertyElt = null; // balise html des proprietes de l'element courant + + this.name = ""; // chemin de l'element courant depuis l'element root (e.g. 'Citation.Title', 'TrianglePatch.0.Count' etc.) + this.type = ""; // type de l'element courant + this.value = null; // valeur (String) de l'element courant + this.typeValues = null; // liste des valeurs possibles prises par le type de l'element courant (pour les enumerations) + this.attributes = []; // liste des sous-elements qui ont eux même des sous-elements + this.properties = []; // liste des elements proprietes (qui n'ont pas de sous-elements) + this.parentElt = null; // element parent + + this.visible = true; // boolean de visibilite de l'element html + this.rootUUID = null; // UUID de l'element Resqml racine + this.htmlElt_propertyRoot = null; // Element html devant contenir toutes les propriétés des objets de l'arbre + }*/ + + constructor(resqmlJSONContent, resqmlRootUUID, htmlElt_propertyRoot, parentElt, isAttribute) { + this.htmlAttributeElt = null; + this.htmlTitleElt = null; + this.htmlSubAttribCreatorList = null; + this.htmlSubAttribElt = null; + this.htmlPropertyElt = null; + this.htmlElt_propertyRoot = htmlElt_propertyRoot; + this.htmlCurrentProperty = null; + this.subAttribCollapserElt = null; // Fleche qui permet de toggle l'affichage des sous-attributs + this.parentElt = parentElt; + this.rootUUID = resqmlRootUUID; + if (isAttribute != null) { + this.isAttribute = isAttribute; + } else { + this.isAttribute = true; + } + + this.updateElementFromJSON(resqmlJSONContent); + this.visible = true; + } + + updateElementFromJSON(resqmlJSONContent) { + this.name = resqmlJSONContent.name; + + this.mandatory = resqmlJSONContent.mandatory; + //console.log("mladat : " + resqmlJSONContent.mandatory); + + //console.log(resqmlJSONContent); + + if (this.name == null || this.name.length <= 0 || !isNaN(this.name)) { + this.name = ""; + } + this.type = resqmlJSONContent.type; + if (this.type == null || this.type.length <= 0 || !isNaN(this.type)) { + this.type = ""; + } + this.value = resqmlJSONContent.value; + + this.templatedClass = resqmlJSONContent.templatedClass; + + if (this.attributes == null) { // Si les attributs n'ont jamais existés + if (resqmlJSONContent.attributes != null) { + this.attributes = []; + for (var attrib_Idx = 0; attrib_Idx < resqmlJSONContent.attributes.length; attrib_Idx++) { + this.attributes.push(new ResqmlElement(resqmlJSONContent.attributes[attrib_Idx], + this.rootUUID, + this.htmlElt_propertyRoot, + this, + true)) + } + } + } else if (this.isResqmlListType()) { // Si c'est une liste, il faut remettre à jour tous les fils + // car leur numérotation à peut être changée + // cela empeche de garder les fils de liste ouverts... + //console.log("updating list"); + var visibleIdx = [] + if (this.attributes != null) { + for (var curAtt_Idx = 0; curAtt_Idx < this.attributes.length; curAtt_Idx++) { + try { + if (this.attributes[curAtt_Idx].visible) { + visibleIdx.push(curAtt_Idx) + } + this.attributes[curAtt_Idx].remove(false); + } catch (exceptRemove) { + console.log(exceptRemove); + } + } + } + + this.attributes = []; + + if (resqmlJSONContent.attributes != null) { + for (var attrib_Idx = 0; attrib_Idx < resqmlJSONContent.attributes.length; attrib_Idx++) { + this.attributes.push(new ResqmlElement(resqmlJSONContent.attributes[attrib_Idx], + this.rootUUID, + this.htmlElt_propertyRoot, + this, + true)); + } + } + for (var curAtt_Idx = 0; curAtt_Idx < visibleIdx.length; curAtt_Idx++) { + var cur_idx = visibleIdx[curAtt_Idx]; + if (this.attributes.length >= cur_idx) { + try { + this.attributes[cur_idx].visible = true; + this.attributes[cur_idx].subAttribCollapserElt.click(); + } catch (exceptionVisible) { + console.log(exceptionVisible); + console.log(this.attributes); + console.log(cur_idx); + console.log(visibleIdx); + } + } + } + } else { // Si on met à jour un arbre existant + // Si il y a des attributs + + var tabAttIdxToRemove = []; // Ceux qui sont null doivent être enlevés de la vue mais pas de la liste + var tabNullAttIdx = []; // Ceux qui doivent être aussi enlevés de la liste des attributs + + if (resqmlJSONContent.attributes != null) { + for (var attrib_Idx = 0; attrib_Idx < resqmlJSONContent.attributes.length; attrib_Idx++) { + var found = false; + var attrib = resqmlJSONContent.attributes[attrib_Idx]; + for (var curAtt_Idx = 0; curAtt_Idx < this.attributes.length; curAtt_Idx++) { + if (attrib.name.localeCompare(this.attributes[curAtt_Idx].name) == 0) { + // Si les deux attributs matchent, on update le sous-attribut + found = true; + this.attributes[curAtt_Idx].updateElementFromJSON(attrib); + } + } + if (!found) { // Si on ne l'a pas trouvé on l'ajoute + this.attributes.push(new ResqmlElement(resqmlJSONContent.attributes[attrib_Idx], + this.rootUUID, + this.htmlElt_propertyRoot, + this, + true)); + } + } + // Test de ceux qu'il faut enlever + for (var curAtt_Idx = 0; curAtt_Idx < this.attributes.length; curAtt_Idx++) { + var found = false; + for (var attrib_Idx = 0; attrib_Idx < resqmlJSONContent.attributes.length; attrib_Idx++) { + if (resqmlJSONContent.attributes[attrib_Idx].name.localeCompare(this.attributes[curAtt_Idx].name) == 0) { + found = true; + if (ResqmlElement_isNullAttribute(resqmlJSONContent.attributes[attrib_Idx])) { + // Si toujours la mais que valeur est nulle + tabNullAttIdx.push(curAtt_Idx); + } + break; + } + } + if (!found) { + // Si ce n'est pas un attribut null + tabAttIdxToRemove.push(curAtt_Idx); + } + } + + } else { + // si aucun attribut, on supprime ceux qui etaient la avant + for (var curAtt_Idx = 0; curAtt_Idx < this.attributes.length; curAtt_Idx++) { + tabAttIdxToRemove.push(curAtt_Idx); + } + } + + // On supprime de la vue ceux qui n'étaient pas null et donc présent dans l'arbre mais qui sont null a présent + for (var attRemoveIdx = tabNullAttIdx.length - 1; attRemoveIdx >= 0; attRemoveIdx--) { + var removedElt = this.attributes[tabNullAttIdx[attRemoveIdx]]; // Le retour est un tableau + try { + /*console.log("REM 1)"); + console.log(removedElt);*/ + removedElt.remove(false); + } catch (exceptionNullAtt) { + console.log("ERRROR removing for : " + removedElt.name); + console.log(exceptionNullAtt); + } + } + // On parcours à partir de la fin pour commencer par les indices les plus elevés sinon on aurait un decalage au fur et a mesure + for (var attRemoveIdx = tabAttIdxToRemove.length - 1; attRemoveIdx >= 0; attRemoveIdx--) { + var removedElt = this.attributes.splice(tabAttIdxToRemove[attRemoveIdx], 1); // Le retour est un tableau + removedElt[0].remove(false); + } + + } + + if (this.properties == null) { + if (resqmlJSONContent.properties != null) { + this.properties = []; + for (var prop_Idx = 0; prop_Idx < resqmlJSONContent.properties.length; prop_Idx++) { + this.properties.push(new ResqmlElement(resqmlJSONContent.properties[prop_Idx], + this.rootUUID, + this.htmlElt_propertyRoot, + this, + false)) + } + } + } else { // Si on met à jour un arbre existant + + var tabPropIdxToRemove = []; + + // Si il y a des proprietes + if (resqmlJSONContent.properties != null) { + for (var prop_Idx = 0; prop_Idx < resqmlJSONContent.properties.length; prop_Idx++) { + var found = false; + var prop = resqmlJSONContent.properties[prop_Idx]; + for (var curProp_Idx = 0; curProp_Idx < this.properties.length; curProp_Idx++) { + if (prop.name.localeCompare(this.properties[curProp_Idx].name) == 0) { + //console.log("compare FOUND P : " + prop.name + " " + this.properties[curProp_Idx].name); + // Si les deux proprietes matchent, on update + found = true; + this.properties[curProp_Idx].updateElementFromJSON(prop); + break; + } + } + if (!found) { // Si on ne l'a pas trouvé on l'ajoute + this.properties.push(new ResqmlElement(resqmlJSONContent.properties[prop_Idx], + this.rootUUID, + this.htmlElt_propertyRoot, + this, + false)) + } + } + // Test de ceux qu'il faut enlever + for (var curProp_Idx = 0; curProp_Idx < this.properties.length; curProp_Idx++) { + var found = false; + for (var prop_Idx = 0; prop_Idx < resqmlJSONContent.properties.length; prop_Idx++) { + if (resqmlJSONContent.properties[prop_Idx].name.localeCompare(this.properties[curProp_Idx].name) == 0) { + found = true; + break; + } else { + /*console.log("compare FOUND P : " + resqmlJSONContent.properties[prop_Idx].name + + " " + this.properties[curProp_Idx].name);*/ + } + } + if (!found) { + tabPropIdxToRemove.push(curProp_Idx); + } + } + + } else { + // si aucune propriete, on supprime ceux qui etaient la avant + for (var curProp_Idx = 0; curProp_Idx < this.properties.length; curProp_Idx++) { + tabPropIdxToRemove.push(curProp_Idx); + } + } + + // On parcours à partir de la fin pour commencer par les indices les plus elevés sinon on aurait un decalage au fur et a mesure + for (var propRemoveIdx = tabPropIdxToRemove.length - 1; propRemoveIdx >= 0; propRemoveIdx--) { + var removedElt = this.properties.splice(tabPropIdxToRemove[propRemoveIdx], 1); + removedElt[0].remove(false); + } + } + + const eltValueNameAsProp = "_"; + if (this.properties != null) { + for (var propRemoveIdx = 0; propRemoveIdx < this.properties.length; propRemoveIdx++) { + if (this.properties[propRemoveIdx].name.endsWith(eltValueNameAsProp)) { + var removedElt = this.properties.splice(propRemoveIdx, 1); + removedElt[0].remove(false); + } + } + } + + if (this.isAttribute && + !this.isResqmlListType() && + this.value != null && + (this.properties == null || this.properties.length == 0) + ) { + this.properties = [new ResqmlElement(resqmlJSONContent, + this.rootUUID, + this.htmlElt_propertyRoot, + this, + false)]; + } + + + if (this.isResqmlListType() && (this.attributes == null || this.attributes.length <= 0)) { + this.remove(false); + } else { + this.createView(); + } + } + + + createView() { + const constThis = this; + var isUpdating = false; + + + // Nom a afficher : la derniere partie du path + var shortName = this.name; + if (shortName.includes(".")) + shortName = shortName.substring(shortName.lastIndexOf('.') + 1); + + var shortType = this.type; + if (shortType.includes(".")) + shortType = shortType.substring(shortType.lastIndexOf('.') + 1); + + /* + _____ _ _ __ _ __ + / ___/(_) ____( )___ _____/ /_ __ ______ ___ ____ _________ ____ _____(_)__ / /____ + \__ \/ / / ___/// _ \/ ___/ __/ / / / / __ \/ _ \ / __ \/ ___/ __ \/ __ \/ ___/ / _ \/ __/ _ \ + ___/ / / / /__ / __(__ ) /_ / /_/ / / / / __/ / /_/ / / / /_/ / /_/ / / / / __/ /_/ __/ + /____/_/ \___/ \___/____/\__/ \__,_/_/ /_/\___/ / .___/_/ \____/ .___/_/ /_/\___/\__/\___/ + /_/ /_/ + */ + if (!this.isAttribute) { + + // Creation d'une case de tableau + if (this.htmlAttributeElt == null) { // On crée l'element si il n'existe pas deja + this.htmlAttributeElt = document.createElement("tr"); + } else { + // Si existe deja on fait un e mise à jour + isUpdating = true; + // On enlève le contenu de l'ancien titre + while (this.htmlAttributeElt.firstChild) { + this.htmlAttributeElt.removeChild(this.htmlAttributeElt.firstChild); + } + } + this.htmlAttributeElt.name = ResqmlElement_NAMESUBATTPREFIX + "_" + shortName; + + const col0 = document.createElement("td"); + const divCollapseLabel = document.createElement("label"); + if (this.mandatory == "true") { + divCollapseLabel.className += "mandatoryElt"; + } + divCollapseLabel.appendChild(document.createTextNode(shortName)); + + + var isExtEnum = false; + var enumValues = mapResqmlEnumToValues[this.type.toLowerCase()] + + if (enumValues == null && this.parentElt != null) { + isExtEnum = true; + var parentElt = this.parentElt; + + var parentResqmlType = this.parentElt.type.toLowerCase(); + + while ("java.lang.string" == parentResqmlType || parentElt.isResqmlListType()) { + parentElt = parentElt.parentElt; + parentResqmlType = parentElt.type.toLowerCase(); + } + + var thisName = this.name.replace(/\.\d+/g, '').toLowerCase(); // On supprime les idx des listes (e.g. Tr.0.Throw.3 ==> Tr.Throw) + if (thisName.includes(".")) { + thisName = thisName.substring(thisName.lastIndexOf(".") + 1); + } + + + if (extTypeAttributes[parentResqmlType + "." + thisName] != null) { + + var realType = extTypeAttributes[parentResqmlType + "." + thisName]; + enumValues = mapResqmlEnumToValues[realType.toLowerCase()]; + if (enumValues == undefined && realType.toLowerCase().endsWith("ext")) { + // on essaie sans le "ext" a la fin + enumValues = mapResqmlEnumToValues[realType.toLowerCase().substring(0, realType.length - 3)]; + } + if (realType.includes(".")) { + realType = realType.substring(realType.lastIndexOf(".") + 1); + } + + divCollapseLabel.title = extTypeAttributes[realType]; + } else if (parentResqmlType.endsWith("ext") && extTypeAttributes[parentResqmlType.substring(0, parentResqmlType.length - 3) + "." + thisName] != null) { + var realType = extTypeAttributes[parentResqmlType.substring(0, parentResqmlType.length - 3) + "." + thisName]; + // Si le ext n'existe pas, on cherche le type de base qui sera etendu + enumValues = mapResqmlEnumToValues[realType.toLowerCase()]; + if (realType.includes(".")) { + realType = realType.substring(realType.lastIndexOf(".") + 1); + } + divCollapseLabel.title = realType; + } else if (!parentResqmlType.endsWith("ext") && extTypeAttributes[parentResqmlType + "ext." + thisName] != null) { + var realType = extTypeAttributes[parentResqmlType + "ext." + thisName]; + // Si le ext n'existe pas, on cherche le type avec "ext" a la fin + enumValues = mapResqmlEnumToValues[realType.toLowerCase()]; + if (realType.includes(".")) { + realType = realType.substring(realType.lastIndexOf(".") + 1); + } + divCollapseLabel.title = realType; + } + } + + divCollapseLabel.title = shortType; + col0.appendChild(divCollapseLabel); + + const col1 = document.createElement("td"); + + if (enumValues != null) { // si c'est un type enum + const divCollapseSelect = geosiris_createEditableSelector(enumValues, this.value, isExtEnum); + divCollapseSelect.className = "form-control"; + divCollapseSelect.id = this.name; // Le chemin + divCollapseSelect.name = this.name; // Le chemin + + col1.appendChild(divCollapseSelect); + + } else { // ce n'est pas un type enum + //console.log(this.name + " --> " + this.type + " :: " + (this.type.toLowerCase().includes('calendar'))) + + // console.log(this.name + " --> " + this.type + " :: " + (this.type.toLowerCase().includes('calendar'))) + var divCollapseInput_TMP = null; + if (this.parentElt.properties != null && this.type.toLowerCase().includes("string") && (this.parentElt.properties.length == 1 || (this.value != null && this.value.length > 100))) { // On met un champs text plus gros si c'est une chaine de caratere et que c'est la seule propriete. divCollapseInput_TMP = document.createElement("textarea"); divCollapseInput_TMP.rows = 10; //divCollapseInput.min - }else{ + } else { divCollapseInput_TMP = document.createElement("input"); } const divCollapseInput = divCollapseInput_TMP; -// console.log("\tdivCollapseInput " + divCollapseInput) - - divCollapseInput.className = "form-control"; // Le chemin - divCollapseInput.name = this.name; // Le chemin - divCollapseInput.typeName = "text"; - if(this.value!=null){ - divCollapseInput.value = this.value; - } - //console.log("\tset value to " + this.value + " -- " + divCollapseInput.value) - - col1.appendChild(divCollapseInput); - if(this.name.toLowerCase().endsWith('uuid') && this.value != this.rootUUID){ - divCollapseInput.style.display = 'inline-block'; - - {// Bouton d'oeil pour ouvrir l'objet represente par l'uuid - const but_open_from_uuid = document.createElement("span"); - but_open_from_uuid.className = "openElementBut fas fa-eye"; - but_open_from_uuid.title = "Open"; - but_open_from_uuid.addEventListener("mouseover", function() { - but_open_from_uuid.className = "openElementBut far fa-eye"; - }); - - but_open_from_uuid.addEventListener("mouseout", function() { - but_open_from_uuid.className = "openElementBut fas fa-eye"; - }) - but_open_from_uuid.onclick = function(){ - openResqmlObjectContentByUUID(constThis.value); - } - col1.appendChild(but_open_from_uuid); - /*// On catch le clic droit - divCollapseInput.oncontextmenu = function (event) { - if(constThis.value!=null){ - console.log("test open") - var popOverOpenUUID = getPopoverOpenUUID(constThis.value); - popOverOpenUUID.className = "geosirisPopOver"; - document.body.append(popOverOpenUUID); - } - console.log("NO open") - return false; //on annule l'affichage du menu contextuel - }*/ - } - { // uuid generator - const but_generate_uuid = document.createElement("span"); - but_generate_uuid.className = "genElementBut far fa-edit"; - but_generate_uuid.title = "Generate uuid (field MUST be empty!)"; - - but_generate_uuid.addEventListener("mouseover", function() { - but_generate_uuid.className = "genElementBut fas fa-edit"; - }); - - but_generate_uuid.addEventListener("mouseout", function() { - but_generate_uuid.className = "genElementBut fas fa-edit"; - }) - but_generate_uuid.onclick = function(){ - if(isUUID(divCollapseInput.value)){ - // On ne remplace pas si deja qqch d'ecrit - createSnackBar("UUID field must be empty before generation", 1000); - }else{ - constThis.value = generateUUID(); - divCollapseInput.value = constThis.value; - } - } - col1.appendChild(but_generate_uuid); - } - divCollapseInput.pattern = UUID_REGEX_str; - }else if (this.type.toLowerCase().includes('calendar')){ - divCollapseInput.style.display = 'inline-block'; - var but = document.createElement("span"); - but.className = "openElementBut fas fa-clock"; - but.title = "Now"; - but.addEventListener("mouseover", function() { - but.className = "openElementBut far fa-clock"; - }); - - but.addEventListener("mouseout", function() { - but.className = "openElementBut fas fa-clock"; - }) - but.onclick = function(){ - // On veut une date en format : 2020-07-29T10:08:38.952+02:00 - const dateNow = new Date(Date.now()); - /*var timeNow = dateNow.toTimeString().replaceAll(' ', ''); - //timeNow = timeNow.substring(0, timeNow.indexOf('(')); - var month = dateNow.getUTCMonth()+1 - if((""+month).length<=1) - month = "0"+month; - var day = dateNow.getUTCDate(); - if((""+day).length<=1) - day = "0"+day; - var milisec = dateNow.getUTCMilliseconds(); - var strDate = dateNow.getUTCFullYear()+"-"+month+"-"+day+"T"+timeNow;*/ - var strDate = dateNow.toISOString(); - constThis.value= strDate; - divCollapseInput.value = strDate; - } - col1.appendChild(but); - } - } - this.htmlAttributeElt.appendChild(col0); - this.htmlAttributeElt.appendChild(col1); - }else{ - /* - _____ _ _ __ ____ _ ____ __ ___ __ __ __ __ _ __ __ _ - / ___/(_) ____( )___ _____/ /_ __ ______ ___ / __/__ __ __(_) / /__ ____/ /__ / ( )____ ______/ /_ ________ _/_/___ _/ /_/ /______(_) /_ __ __/ /_| | - \__ \/ / / ___/// _ \/ ___/ __/ / / / / __ \/ _ \ / /_/ _ \/ / / / / / / _ \ / __ / _ \ / /|// __ `/ ___/ __ \/ ___/ _ \ / // __ `/ __/ __/ ___/ / __ \/ / / / __// / - ___/ / / / /__ / __(__ ) /_ / /_/ / / / / __/ / __/ __/ /_/ / / / / __/ / /_/ / __/ / / / /_/ / / / /_/ / / / __/ / // /_/ / /_/ /_/ / / / /_/ / /_/ / /_ / / - /____/_/ \___/ \___/____/\__/ \__,_/_/ /_/\___/ /_/ \___/\__,_/_/_/_/\___/ \__,_/\___/ /_/ \__,_/_/ /_.___/_/ \___/ / / \__,_/\__/\__/_/ /_/_.___/\__,_/\__//_/ - |_| /_/ - */ - // Creation d'une div pour l'element courant et ses attributs - if(this.htmlAttributeElt == null){ // On crée l'element si il n'existe pas deja - this.htmlAttributeElt = document.createElement("div"); - }else{ - // Si existe deja on fait une mise à jour - isUpdating = true; - if(this.isResqmlListType() && (this.attributes == null || this.attributes.length <= 0) ){ - // Si c'est une liste et qu'elle est vide, on supprime l'element - // this.remove(); - return null; - } - } - this.htmlAttributeElt.name = ResqmlElement_NAMESUBATTPREFIX + "_" + shortName; - - if(this.type.includes("CustomData")){ - // On enlève le contenu de l'ancien titre - if(isUpdating){ - while (this.htmlAttributeElt.firstChild) { - this.htmlAttributeElt.removeChild(this.htmlAttributeElt.firstChild); - } - } - var italicDiv = document.createElement("i"); - italicDiv.className = "fa fa-exclamation-triangle"; - italicDiv.title = "Check object's xml translation to see the custom data"; - italicDiv.appendChild(document.createTextNode("CustomData not supported")); - this.htmlAttributeElt.appendChild(italicDiv); - }else{ - - /** Attributs **/ - - // Creation des sous-elements : - var tabCreateSubAttrib = []; - var tabListsAttribs = []; - - if(!isUpdating){ - this.htmlSubAttribElt = document.createElement("div"); - if(this.isResqmlListType()){ - this.htmlSubAttribElt.className = "dropper"; - } - } - - if(this.attributes != null && this.attributes.length>0){ - for(var attIdx=0; attIdx < this.attributes.length; attIdx++){ - const subA = this.attributes[attIdx]; - if(ResqmlElement_isNullAttribute(subA)){ - // Les elements que l'on pourra créer - tabCreateSubAttrib.push(subA.getCurrentListContentElt()); - //console.log("# Null attribt : " + subA.type); - }else{ - const subAElt = subA.createView(); - if(subAElt != null){ - if(subA.isResqmlListType()){ - //console.log("IS LIST : " ); - if(subA.attributes!=null && subA.attributes.length>0){ - this.htmlSubAttribElt.appendChild(subAElt); - //console.log(" ----------- " ); - } - //console.log(subA); - tabListsAttribs.push(subA.getCurrentListContentElt()); - }else{ - this.htmlSubAttribElt.appendChild(subAElt); - if(this.isResqmlListType()){ - const currentDraggableElt = subA; - const currentDraggableElt_html = subAElt; - subAElt.className = "draggableElt"; - if(!subAElt.lastChild.previousSibling.className.includes("draggableButton") && this.attributes.length > 1){ - var butDrag = document.createElement("span"); - butDrag.className = "draggableButton"; - butDrag.name = this.name; - const constButDrag = butDrag; - geosiris_DndHandler.applyDragEvents(constButDrag, function(){updateListEltIdx(currentDraggableElt_html, currentDraggableElt);}); - subAElt.insertBefore(butDrag, subAElt.lastChild); - } - } - } - }else{ - tabCreateSubAttrib.push(subA.getCurrentListContentElt()); - } - } - } - - - // Pour les draggables - if(this.isResqmlListType()){ - geosiris_DndHandler.applyDropEvents(this.htmlSubAttribElt); - } - } - - - - - //console.log("List for : " + this.name + " is ");console.log(tabListsAttribs); - //console.log("ResqmlElement_isNullAttribute: " + this.name + " is ");console.log(tabCreateSubAttrib); - // Creation du titre - if(!isUpdating){ - this.htmlTitleElt = document.createElement("span"); - if(this.mandatory=="true"){ - this.htmlTitleElt.className += " mandatoryElt"; - } - }else{ - if(this.htmlTitleElt!=null){ - // On enlève le contenu de l'ancien titre - while (this.htmlTitleElt.firstChild) { - this.htmlTitleElt.removeChild(this.htmlTitleElt.firstChild); - } - }else{ - console.log("null title"); - console.log(this); - } - } - - var showTypeAsTooltip = false; - - var typeInTitle = "[" + shortType + "] " - - if(this.parentElt != null){ - if(shortType.endsWith("List")){ - typeInTitle = ""; - }else if(shortType.length + shortName.length > 25){ - typeInTitle = typeInTitle.replace( /[a-z]/g, '' ) - showTypeAsTooltip = true; - } - }else{ // the Top title - var title = getResqmlEltCitationTitle(this); - if (title != null && title.length > 0){ - typeInTitle += " '" + title + "'"; - } - typeInTitle += " " + this.rootUUID; - } - - - var booleanInTitle = "" - if(this.properties != null){ - // Search boolean properties to print in title - for(var propIdx=0;propIdx 2){ - propName = propName.substring(2); - } - booleanInTitle += " {" + propName + "} "; - } - } - } - - var titleValue = booleanInTitle + shortName ; - /*console.log('This title : ' + titleValue + " -- ") - console.log(this.properties)*/ - - { // === TITLE SUFFIX - var subColor = null; - var subTitle = null; - var subValue = null; - if(!isNaN(parseInt(shortName)) || this.type.toLowerCase().includes("dataobjectreference")){ - // On cherche si pour les elements des listes on peut avoir un meilleur nom - // Pour tous les fils, on regarde si il existe un element Title - if(this.properties != null){ - - for(var propIdx=0; propIdx < this.properties.length; propIdx++){ - const subProp = this.properties[propIdx]; - var subPropName = subProp.name; - if(subPropName.includes(".")){ - subPropName = subPropName.substring(subPropName.lastIndexOf('.') + 1); + // console.log("\tdivCollapseInput " + divCollapseInput) + + divCollapseInput.className = "form-control"; // Le chemin + divCollapseInput.name = this.name; // Le chemin + divCollapseInput.typeName = "text"; + if (this.value != null) { + divCollapseInput.value = this.value; + } + //console.log("\tset value to " + this.value + " -- " + divCollapseInput.value) + + col1.appendChild(divCollapseInput); + if (this.name.toLowerCase().endsWith('uuid') && this.value != this.rootUUID) { + divCollapseInput.style.display = 'inline-block'; + + { // Bouton d'oeil pour ouvrir l'objet represente par l'uuid + const but_open_from_uuid = document.createElement("span"); + but_open_from_uuid.className = "openElementBut fas fa-eye"; + but_open_from_uuid.title = "Open"; + but_open_from_uuid.addEventListener("mouseover", function() { + but_open_from_uuid.className = "openElementBut far fa-eye"; + }); + + but_open_from_uuid.addEventListener("mouseout", function() { + but_open_from_uuid.className = "openElementBut fas fa-eye"; + }) + but_open_from_uuid.onclick = function() { + openResqmlObjectContentByUUID(constThis.value); + } + col1.appendChild(but_open_from_uuid); + /*// On catch le clic droit + divCollapseInput.oncontextmenu = function (event) { + if(constThis.value!=null){ + console.log("test open") + var popOverOpenUUID = getPopoverOpenUUID(constThis.value); + popOverOpenUUID.className = "geosirisPopOver"; + document.body.append(popOverOpenUUID); + } + console.log("NO open") + return false; //on annule l'affichage du menu contextuel + }*/ + } { // uuid generator + const but_generate_uuid = document.createElement("span"); + but_generate_uuid.className = "genElementBut far fa-edit"; + but_generate_uuid.title = "Generate uuid (field MUST be empty!)"; + + but_generate_uuid.addEventListener("mouseover", function() { + but_generate_uuid.className = "genElementBut fas fa-edit"; + }); + + but_generate_uuid.addEventListener("mouseout", function() { + but_generate_uuid.className = "genElementBut fas fa-edit"; + }) + but_generate_uuid.onclick = function() { + if (isUUID(divCollapseInput.value)) { + // On ne remplace pas si deja qqch d'ecrit + createSnackBar("UUID field must be empty before generation", 1000); + } else { + constThis.value = generateUUID(); + divCollapseInput.value = constThis.value; + } + } + col1.appendChild(but_generate_uuid); + } + divCollapseInput.pattern = UUID_REGEX_str; + } else if (this.type.toLowerCase().includes('calendar')) { + divCollapseInput.style.display = 'inline-block'; + var but = document.createElement("span"); + but.className = "openElementBut fas fa-clock"; + but.title = "Now"; + but.addEventListener("mouseover", function() { + but.className = "openElementBut far fa-clock"; + }); + + but.addEventListener("mouseout", function() { + but.className = "openElementBut fas fa-clock"; + }) + but.onclick = function() { + // On veut une date en format : 2020-07-29T10:08:38.952+02:00 + const dateNow = new Date(Date.now()); + /*var timeNow = dateNow.toTimeString().replaceAll(' ', ''); + //timeNow = timeNow.substring(0, timeNow.indexOf('(')); + var month = dateNow.getUTCMonth()+1 + if((""+month).length<=1) + month = "0"+month; + var day = dateNow.getUTCDate(); + if((""+day).length<=1) + day = "0"+day; + var milisec = dateNow.getUTCMilliseconds(); + var strDate = dateNow.getUTCFullYear()+"-"+month+"-"+day+"T"+timeNow;*/ + var strDate = dateNow.toISOString(); + constThis.value = strDate; + divCollapseInput.value = strDate; + } + col1.appendChild(but); } - if(subColor == null && subPropName.toLowerCase() == "hue"){ - var hue = subProp.value; - var value = null; - var saturation = null; - - for(var propIdxBIS=0; propIdxBIS < this.properties.length; propIdxBIS++){ - const subPropBIS = this.properties[propIdx]; - if(subPropBIS.name .toLowerCase() == "value"){ - value = subPropBIS.value; + } + this.htmlAttributeElt.appendChild(col0); + this.htmlAttributeElt.appendChild(col1); + } else { + /* + _____ _ _ __ ____ _ ____ __ ___ __ __ __ __ _ __ __ _ + / ___/(_) ____( )___ _____/ /_ __ ______ ___ / __/__ __ __(_) / /__ ____/ /__ / ( )____ ______/ /_ ________ _/_/___ _/ /_/ /______(_) /_ __ __/ /_| | + \__ \/ / / ___/// _ \/ ___/ __/ / / / / __ \/ _ \ / /_/ _ \/ / / / / / / _ \ / __ / _ \ / /|// __ `/ ___/ __ \/ ___/ _ \ / // __ `/ __/ __/ ___/ / __ \/ / / / __// / + ___/ / / / /__ / __(__ ) /_ / /_/ / / / / __/ / __/ __/ /_/ / / / / __/ / /_/ / __/ / / / /_/ / / / /_/ / / / __/ / // /_/ / /_/ /_/ / / / /_/ / /_/ / /_ / / + /____/_/ \___/ \___/____/\__/ \__,_/_/ /_/\___/ /_/ \___/\__,_/_/_/_/\___/ \__,_/\___/ /_/ \__,_/_/ /_.___/_/ \___/ / / \__,_/\__/\__/_/ /_/_.___/\__,_/\__//_/ + |_| /_/ + */ + // Creation d'une div pour l'element courant et ses attributs + if (this.htmlAttributeElt == null) { // On crée l'element si il n'existe pas deja + this.htmlAttributeElt = document.createElement("div"); + } else { + // Si existe deja on fait une mise à jour + isUpdating = true; + if (this.isResqmlListType() && (this.attributes == null || this.attributes.length <= 0)) { + // Si c'est une liste et qu'elle est vide, on supprime l'element + // this.remove(); + return null; + } + } + this.htmlAttributeElt.name = ResqmlElement_NAMESUBATTPREFIX + "_" + shortName; + + if (this.type.includes("CustomData")) { + // On enlève le contenu de l'ancien titre + if (isUpdating) { + while (this.htmlAttributeElt.firstChild) { + this.htmlAttributeElt.removeChild(this.htmlAttributeElt.firstChild); } - if(subPropBIS.name .toLowerCase() == "saturation"){ - saturation = subPropBIS.value; + } + var italicDiv = document.createElement("i"); + italicDiv.className = "fa fa-exclamation-triangle"; + italicDiv.title = "Check object's xml translation to see the custom data"; + italicDiv.appendChild(document.createTextNode("CustomData not supported")); + this.htmlAttributeElt.appendChild(italicDiv); + } else { + + /** Attributs **/ + + // Creation des sous-elements : + var tabCreateSubAttrib = []; + var tabListsAttribs = []; + + if (!isUpdating) { + this.htmlSubAttribElt = document.createElement("div"); + if (this.isResqmlListType()) { + this.htmlSubAttribElt.className = "dropper"; } - } - if(hue != null && value != null && saturation != null){ - subColor = hsvToRgb(hue, saturation, value); - } } - if(subTitle == null && subPropName.toLowerCase() == "title"){ - titleValue += " '" + subProp.value + "'"; - subTitle = subProp.value; - if(REGEX_HEX_COLOR.test(subTitle)){ - subColor = subTitle; - } + + if (this.attributes != null && this.attributes.length > 0) { + for (var attIdx = 0; attIdx < this.attributes.length; attIdx++) { + const subA = this.attributes[attIdx]; + if (ResqmlElement_isNullAttribute(subA)) { + // Les elements que l'on pourra créer + tabCreateSubAttrib.push(subA.getCurrentListContentElt()); + //console.log("# Null attribt : " + subA.type); + } else { + const subAElt = subA.createView(); + if (subAElt != null) { + if (subA.isResqmlListType()) { + //console.log("IS LIST : " ); + if (subA.attributes != null && subA.attributes.length > 0) { + this.htmlSubAttribElt.appendChild(subAElt); + //console.log(" ----------- " ); + } + //console.log(subA); + tabListsAttribs.push(subA.getCurrentListContentElt()); + } else { + this.htmlSubAttribElt.appendChild(subAElt); + if (this.isResqmlListType()) { + const currentDraggableElt = subA; + const currentDraggableElt_html = subAElt; + subAElt.className = "draggableElt"; + if (!subAElt.lastChild.previousSibling.className.includes("draggableButton") && this.attributes.length > 1) { + var butDrag = document.createElement("span"); + butDrag.className = "draggableButton"; + butDrag.name = this.name; + const constButDrag = butDrag; + geosiris_DndHandler.applyDragEvents(constButDrag, function() { + updateListEltIdx(currentDraggableElt_html, currentDraggableElt); + }); + subAElt.insertBefore(butDrag, subAElt.lastChild); + } + } + } + } else { + tabCreateSubAttrib.push(subA.getCurrentListContentElt()); + } + } + } + + + // Pour les draggables + if (this.isResqmlListType()) { + geosiris_DndHandler.applyDropEvents(this.htmlSubAttribElt); + } } - if(subTitle == null && subPropName.toLowerCase() == "value"){ - titleValue += " '" + subProp.value + "'"; - subValue = subProp.value; + + + + + //console.log("List for : " + this.name + " is ");console.log(tabListsAttribs); + //console.log("ResqmlElement_isNullAttribute: " + this.name + " is ");console.log(tabCreateSubAttrib); + // Creation du titre + if (!isUpdating) { + this.htmlTitleElt = document.createElement("span"); + if (this.mandatory == "true") { + this.htmlTitleElt.className += " mandatoryElt"; + } + } else { + if (this.htmlTitleElt != null) { + // On enlève le contenu de l'ancien titre + while (this.htmlTitleElt.firstChild) { + this.htmlTitleElt.removeChild(this.htmlTitleElt.firstChild); + } + } else { + console.log("null title"); + console.log(this); + } } - } - } - if(this.attributes!=null){ - for(var attIdx=0; attIdx < this.attributes.length; attIdx++){ - const subA = this.attributes[attIdx]; - if(subA.properties != null && subA.properties.length > 0){ - var subA_shortName = subA.name; - if(subA_shortName.includes(".")){ - subA_shortName = subA_shortName.substring(subA_shortName.lastIndexOf('.')+1); - } - for(var propIdx=0; propIdx < subA.properties.length; propIdx++){ - const subProp = subA.properties[propIdx]; - var subPropName = subProp.name; - if(subPropName.includes(".")){ - subPropName = subPropName.substring(subPropName.lastIndexOf('.') + 1); + + var showTypeAsTooltip = false; + + var typeInTitle = shortType + + if (this.parentElt != null) { + if (shortType.endsWith("List")) { + typeInTitle = ""; + } else if (shortType.length + shortName.length > 25) { + typeInTitle = typeInTitle.replace(/[a-z]/g, '') + showTypeAsTooltip = true; + } + } else { // the Top title + var title = getResqmlEltCitationTitle(this); + if (title != null && title.length > 0) { + typeInTitle += " '" + title + "'"; + } + typeInTitle += " " + this.rootUUID; + } + + + var booleanInTitle = "" + if (this.properties != null) { + // Search boolean properties to print in title + for (var propIdx = 0; propIdx < this.properties.length; propIdx++) { + var prop = this.properties[propIdx]; + if (prop.type.toLowerCase().endsWith("boolean") && + (prop.value.toLowerCase() == "true" || + prop.value.toLowerCase() == "yes" || + prop.value.toLowerCase() == "1") + ) { + var propName = prop.name; + propName = propName.substring(propName.lastIndexOf('.') + 1); + if (propName.startsWith("Is") && propName.length > 2) { + propName = propName.substring(2); + } + booleanInTitle += " {" + propName + "} "; + } } - if(subColor == null && subPropName.toLowerCase() == "hue"){ - var hue = subProp.value; - var value = null; - var saturation = null; - - for(var propIdxBIS=0; propIdxBIS < subA.properties.length; propIdxBIS++){ - const subPropBIS = subA.properties[propIdx]; - if(subPropBIS.name .toLowerCase() == "value"){ - value = subPropBIS.value; + } + + var titleValue = booleanInTitle + shortName; + /*console.log('This title : ' + titleValue + " -- ") + console.log(this.properties)*/ + + { // === TITLE SUFFIX + var subColor = null; + var subTitle = null; + var subValue = null; + if (!isNaN(parseInt(shortName)) || this.type.toLowerCase().includes("dataobjectreference")) { + // On cherche si pour les elements des listes on peut avoir un meilleur nom + // Pour tous les fils, on regarde si il existe un element Title + if (this.properties != null) { + + for (var propIdx = 0; propIdx < this.properties.length; propIdx++) { + const subProp = this.properties[propIdx]; + var subPropName = subProp.name; + if (subPropName.includes(".")) { + subPropName = subPropName.substring(subPropName.lastIndexOf('.') + 1); + } + if (subColor == null && subPropName.toLowerCase() == "hue") { + var hue = subProp.value; + var value = null; + var saturation = null; + + for (var propIdxBIS = 0; propIdxBIS < this.properties.length; propIdxBIS++) { + const subPropBIS = this.properties[propIdx]; + if (subPropBIS.name.toLowerCase() == "value") { + value = subPropBIS.value; + } + if (subPropBIS.name.toLowerCase() == "saturation") { + saturation = subPropBIS.value; + } + } + if (hue != null && value != null && saturation != null) { + subColor = hsvToRgb(hue, saturation, value); + } + } + if (subTitle == null && subPropName.toLowerCase() == "title") { + titleValue += " '" + subProp.value + "'"; + subTitle = subProp.value; + if (REGEX_HEX_COLOR.test(subTitle)) { + subColor = subTitle; + } + } + if (subTitle == null && subPropName.toLowerCase() == "value") { + titleValue += " '" + subProp.value + "'"; + subValue = subProp.value; + } + } } - if(subPropBIS.name .toLowerCase() == "saturation"){ - saturation = subPropBIS.value; + if (this.attributes != null) { + for (var attIdx = 0; attIdx < this.attributes.length; attIdx++) { + const subA = this.attributes[attIdx]; + if (subA.properties != null && subA.properties.length > 0) { + var subA_shortName = subA.name; + if (subA_shortName.includes(".")) { + subA_shortName = subA_shortName.substring(subA_shortName.lastIndexOf('.') + 1); + } + for (var propIdx = 0; propIdx < subA.properties.length; propIdx++) { + const subProp = subA.properties[propIdx]; + var subPropName = subProp.name; + if (subPropName.includes(".")) { + subPropName = subPropName.substring(subPropName.lastIndexOf('.') + 1); + } + if (subColor == null && subPropName.toLowerCase() == "hue") { + var hue = subProp.value; + var value = null; + var saturation = null; + + for (var propIdxBIS = 0; propIdxBIS < subA.properties.length; propIdxBIS++) { + const subPropBIS = subA.properties[propIdx]; + if (subPropBIS.name.toLowerCase() == "value") { + value = subPropBIS.value; + } + if (subPropBIS.name.toLowerCase() == "saturation") { + saturation = subPropBIS.value; + } + } + if (hue != null && value != null && saturation != null) { + subColor = hsvToRgb(hue, saturation, value); + } + } + if (subTitle == null && subPropName.toLowerCase() == "title") { + titleValue += " '" + subProp.value + "'"; + subTitle = subProp.value; + if (REGEX_HEX_COLOR.test(subTitle)) { + subColor = subTitle; + } + } + if (subTitle == null && subPropName.toLowerCase() == "value") { + titleValue += " '" + subProp.value + "'"; + subValue = subProp.value; + } + } + /*for(var propIdx=0; propIdx < subA.properties.length; propIdx++){ + const subProp = subA.properties[propIdx]; + var subPropName = subProp.name; + if(subPropName.includes(".")){ + subPropName = subPropName.substring(subPropName.lastIndexOf('.')+1); + } + if(subPropName.toLowerCase() == "title"){ + titleValue += " " + subA_shortName.replace( /[a-z]/g, '' ) + "(" + subProp.value + ")"; + break; + } + }*/ + } + } } - } - if(hue != null && value != null && saturation != null){ - subColor = hsvToRgb(hue, saturation, value); - } } - if(subTitle == null && subPropName.toLowerCase() == "title"){ - titleValue += " '" + subProp.value + "'"; - subTitle = subProp.value; - if(REGEX_HEX_COLOR.test(subTitle)){ - subColor = subTitle; - } + + if (subColor != null) { + var spanTitleColor = document.createElement("span"); + spanTitleColor.className = "fas fa-circle colorCircle"; + spanTitleColor.style.color = subColor; + this.htmlTitleElt.appendChild(spanTitleColor); + } + } + if (typeInTitle.length > 0){ + // Title type + var htmlTitleElt_type = document.createElement("span"); + htmlTitleElt_type.appendChild(document.createTextNode("[" + typeInTitle)); + this.htmlTitleElt.appendChild(htmlTitleElt_type); + + if (mapResqmlTypesComment[this.type.toLowerCase()] != null) { + var commentType = document.createElement("span"); + commentType.className = "typeCommentIcon fas fa-question-circle"; + htmlTitleElt_type.appendChild(commentType); + var divCommentTitle = createHoverableHtmlContent(commentType, '' + this.type + " : " + mapResqmlTypesComment[this.type.toLowerCase()], false); + + this.htmlTitleElt.appendChild(divCommentTitle); + } else { + //console.log("no comment for " + this.type); + } + htmlTitleElt_type.appendChild(document.createTextNode("]")); + } + + var htmlTitleElt_values = document.createElement("span"); + htmlTitleElt_values.appendChild(document.createTextNode(titleValue)); + this.htmlTitleElt.appendChild(htmlTitleElt_values); + if (showTypeAsTooltip) { + this.htmlTitleElt.title = shortType; + } + + + if (!isUpdating) { + // Creation du bouton de collapser d'arbre + this.subAttribCollapserElt = document.createElement("span"); + //this.subAttribCollapserElt.id = this.rootUUID + this.name; + this.subAttribCollapserElt.style.cursor = "pointer"; + this.subAttribCollapserElt.className = "resqmlCollapse fas fa-chevron-right"; + + this.subAttribCollapserElt.onclick = + function() { + if (constThis.htmlSubAttribElt != null) { + if (constThis.subAttribCollapserElt.className.includes("fa-chevron-right")) { + constThis.subAttribCollapserElt.className = constThis.subAttribCollapserElt.className.replace("fa-chevron-right", "fa-chevron-down"); + constThis.htmlSubAttribElt.style.display = ""; + } else { + constThis.subAttribCollapserElt.className = constThis.subAttribCollapserElt.className.replace("fa-chevron-down", "fa-chevron-right"); + constThis.htmlSubAttribElt.style.display = "none"; + } + } + }; + + this.htmlAttributeElt.appendChild(this.subAttribCollapserElt); + + this.htmlAttributeElt.appendChild(this.htmlTitleElt); + + // HDF Button doesn't work anymore + // if (constThis.type.toLowerCase().includes("datasetpart") || + // constThis.type.toLowerCase().includes("hdf5dataset")) { + // var butOpenHDFView = document.createElement("img"); + // butOpenHDFView.src = "ressources/img/HDF_logo.png"; + // butOpenHDFView.alt = "[ HDFView ]"; + // butOpenHDFView.className = "hdfViewIcon" + // butOpenHDFView.title = "Open in HDFView" + // //var butOpenHDFView = document.createElement("span"); + // //butOpenHDFView.appendChild(document.createTextNode("[[HDFView]]")); + // //butOpenHDFView.appendChild(document.createTextNode("")); + // butOpenHDFView.onclick = function() { + // //console.log(constThis); + // var pathInHDF = ""; + // for (var propIdx = 0; propIdx < constThis.properties.length; propIdx++) { + // if (constThis.properties[propIdx].name.toLowerCase().endsWith("pathinhdffile") || + // constThis.properties[propIdx].name.toLowerCase().endsWith("pathinexternalfile")) { + // //console.log(constThis.properties[propIdx]); + // pathInHDF = constThis.properties[propIdx].value; + // break; + // } + // } + + // for (var attIdx = 0; attIdx < constThis.attributes.length; attIdx++) { + // var cur_attrib = constThis.attributes[attIdx]; + // if (cur_attrib.name.toLowerCase().endsWith("epcexternalpartreference")) { + // var extUuid = "" + // for (var propIdx = 0; propIdx < cur_attrib.properties.length; propIdx++) { + // if (cur_attrib.properties[propIdx].name.toLowerCase().endsWith(".uuid")) { + // //console.log("uuid found") + // extUuid = cur_attrib.properties[propIdx].value; + // break; + // } + // } + // try { + // cur_attrib.getResqmlObjectJson(extUuid, "Filename").then( + // res => { + // openHDFViewAskH5Location(res.value, pathInHDF); + // }); + // } catch (e) { + // console.log(e); + // } + // } + // } + // /*openHDFViewAskH5Location(pathInHDF); + // console.log("===> HDF5 open") + // console.log(constThis.attributes)*/ + // }; + // this.htmlAttributeElt.appendChild(butOpenHDFView); + // } + + + // Si il y a des sous-element a creer + if (tabCreateSubAttrib.length > 0 || tabListsAttribs.length > 0) { + this.htmlSubAttribCreatorList = this.createSubAttribAddingListCollapser(tabCreateSubAttrib.concat(tabListsAttribs)); + if (this.htmlSubAttribCreatorList != null) { + this.htmlAttributeElt.appendChild(this.htmlSubAttribCreatorList); + } + } + + if (!this.isResqmlListType() && this.name.length > 0) { + // Bouton de suppression + var deleteBut = createDeleteButton("deleteButton deleteButtonTree", "Delete Element"); + deleteBut.onclick = function() { + constThis.remove(true); + }; + this.htmlAttributeElt.appendChild(deleteBut); + } + + if (this.htmlSubAttribElt != null) { + this.htmlAttributeElt.appendChild(this.htmlSubAttribElt); + this.htmlSubAttribElt.style.display = "none"; + this.htmlSubAttribElt.className += " treeSubAttribute"; + } + + } else { // updating + // Si il y a des sous-element a creer + if (tabCreateSubAttrib.length > 0 || tabListsAttribs.length > 0) { + var newCreatorList = this.createSubAttribAddingListCollapser(tabCreateSubAttrib.concat(tabListsAttribs), this); + if (this.htmlSubAttribCreatorList != null) { // Si il y en avait un avant on le remplace + if (newCreatorList != null) { + this.htmlAttributeElt.replaceChild(newCreatorList, this.htmlSubAttribCreatorList); + try { + this.htmlSubAttribCreatorList.remove(); + } catch (Ee) { + console.log(Ee); + } + } else { + this.htmlAttributeElt.remove(); + } + } else { // Si il y en avait pas avant on l'ajoute apres le title + if (newCreatorList != null) { + this.htmlTitleElt.after(newCreatorList); + } + } + this.htmlSubAttribCreatorList = newCreatorList; + } else { + if (this.htmlSubAttribCreatorList != null) { + this.htmlSubAttribCreatorList.remove(); + this.htmlSubAttribCreatorList = null; + } } - if(subTitle == null && subPropName.toLowerCase() == "value"){ - titleValue += " '" + subProp.value + "'"; - subValue = subProp.value; + } + + // Si il y a des sous-attributs on affiche la fleche, sinon on ne l'affiche pas + if (this.htmlSubAttribElt.children.length <= 0) { + this.subAttribCollapserElt.style.display = "none"; + this.subAttribCollapserElt.className = this.subAttribCollapserElt.className.replace("fa-chevron-down", "fa-chevron-right"); + this.htmlSubAttribElt.style.display = "none"; + } else { + this.subAttribCollapserElt.style.display = ""; + } + + + /** Property **/ + if ((this.properties != null && this.properties.length > 0) || this.value != null) { + const propRootElt = this.htmlElt_propertyRoot; + if (propRootElt != null) { + var lastStyleDisplay = "none"; + if (this.htmlCurrentProperty != null) { + lastStyleDisplay = this.htmlCurrentProperty.style.display; + this.htmlCurrentProperty.remove(); + } + + this.htmlCurrentProperty = this.createPropertyTable(); + this.htmlCurrentProperty.style.display = lastStyleDisplay; + propRootElt.appendChild(this.htmlCurrentProperty); + + const constCurrentProp = this.htmlCurrentProperty; + + this.htmlTitleElt.style.cursor = "pointer"; + if (!this.htmlTitleElt.className.includes("treeLeafWithProperty")) + this.htmlTitleElt.className += " treeLeafWithProperty"; + //this.htmlTitleElt.style.fontStyle = "italic"; + + this.htmlTitleElt.onclick = function() { + for (var propChildIdx = 0; propChildIdx < propRootElt.childNodes.length; propChildIdx++) { + try { + // on invisibilise toutes les propriétés + propRootElt.childNodes[propChildIdx].style.display = "none"; + // console.log("child disable : " + propRootElt.childNodes[propChildIdx] + " " + propChildIdx); + } catch (e) { + console.error("/!\\ child not disable : " + propChildIdx); + } + } + //console.log(constCurrentProp); + constCurrentProp.style.display = ""; + }; + } else { + // console.log("no property ROOT " + this.name); } - } - /*for(var propIdx=0; propIdx < subA.properties.length; propIdx++){ - const subProp = subA.properties[propIdx]; - var subPropName = subProp.name; - if(subPropName.includes(".")){ - subPropName = subPropName.substring(subPropName.lastIndexOf('.')+1); + } else { + // console.log("no property for " + this.name); + // Si on a pas de propriete on active le click pour ouvrir les sous element a la place. + const constThis = this; + this.htmlTitleElt.onclick = function() { + constThis.subAttribCollapserElt.click(); + }; + } + + if (!isUpdating && this.parentElt == null) { + this.subAttribCollapserElt.click(); + } + } + } + + /** **/ + return this.htmlAttributeElt; + } + + + createPropertyTable() { + var shortName = this.name; + if (shortName.includes(".")) + shortName = shortName.substring(shortName.lastIndexOf('.') + 1); + if (shortName.length <= 0) { + shortName = this.rootUUID; + } + + // En-tete + var titleElt = document.createElement("h4"); + titleElt.appendChild(document.createTextNode("Properties of " + shortName)); + titleElt.title = this.name; + + // Tableau + var propTable = document.createElement("table"); + propTable.className += "propertyTable"; + + if (this.properties != null) { + for (var prop = 0; prop < this.properties.length; prop++) { + const propValue = this.properties[prop]; + //console.log("Prop creation : " + propValue.name); + + propTable.appendChild(propValue.createView()); + } + } else if (this.data != null && !this.isResqmlListType()) { + // Pour les element propriete qui apparaissent quand meme dans l'arbre : + // ex : ObjActivityTemplate.Parameter.0.KeyConstraint.0 : ce sont des String qui doivent etre dans l'arbre + + propTable.appendChild(this.createView()); + //console.log(' adding elt : ' + this); + } + + var divId = "prop_" + this.rootUUID + this.name; + const propertyDiv = document.createElement("div"); + propertyDiv.id = divId; + propertyDiv.className = "propertyContainer"; + + + if (this.type.toLowerCase().includes("dataobjectreference")) { + try { + propTable.appendChild(document.createElement("hr")); + + const line = document.createElement("tr"); + + const col0_uri = document.createElement("td"); + const col0_uri_label = document.createElement("label"); + col0_uri_label.appendChild(document.createTextNode("URI (generated)")); + col0_uri.appendChild(col0_uri_label); + line.appendChild(col0_uri); + + var contentType = null; + var qualifiedtype = null; + var contentUUID = "###"; + if (this.properties != null) { + for (var prop = 0; prop < this.properties.length; prop++) { + const propValue = this.properties[prop]; + if (propValue.name.toLowerCase().endsWith("contenttype")) { + contentType = propValue.value + } else if (propValue.name.toLowerCase().endsWith("qualifiedtype")) { + qualifiedtype = propValue.value + } + if (propValue.name.toLowerCase().endsWith("uuid")) { + contentUUID = propValue.value + } } - if(subPropName.toLowerCase() == "title"){ - titleValue += " " + subA_shortName.replace( /[a-z]/g, '' ) + "(" + subProp.value + ")"; - break; + } + try { + var match = null; + if (contentType != null) { + match = contentType.match(/application\/x-(?\w+)\+xml;version=(?[\w\.]+);type=(?\w+)/mi); + } else if (qualifiedtype != null) { + match = qualifiedtype.match(/(?\w+)(?[\w\.]+)\.(?\w+)/mi); } - }*/ + var obj_version_num = match.groups["version"]; + var obj_pkg = match.groups["pkgName"]; + var obj_type = match.groups["objecType"]; + const generated_uri = "eml:///" + obj_pkg + (obj_version_num != null ? obj_version_num.replace(".", "") : "") + "." + obj_type + "(" + contentUUID + ")"; + + const col1_uri = document.createElement("td"); + const col1_uri_text = document.createElement("input"); + col1_uri_text.readOnly = "readonly"; + col1_uri_text.className = "form-control"; // Le chemin + col1_uri_text.typeName = "text"; + col1_uri_text.value = generated_uri; + col1_uri.appendChild(col1_uri_text); + line.appendChild(col1_uri); + propTable.appendChild(line); + } catch (Except) { + console.log("unable to generate URI"); + //console.log(Except); } - } + + } catch (Except) { + console.log(Except); } - } - - if(subColor != null){ - var spanTitleColor = document.createElement("span"); - spanTitleColor.className = "fas fa-circle colorCircle"; - spanTitleColor.style.color = subColor; - this.htmlTitleElt.appendChild(spanTitleColor); - } - - - // Title type - var htmlTitleElt_type = document.createElement("span"); - htmlTitleElt_type.appendChild(document.createTextNode(typeInTitle)); - this.htmlTitleElt.appendChild(htmlTitleElt_type); } - if(mapResqmlTypesComment[this.type.toLowerCase()] != null){ - var commentType = document.createElement("span"); - commentType.className = "typeCommentIcon fas fa-question-circle"; - this.htmlTitleElt.appendChild(commentType); - var divCommentTitle = createHoverableHtmlContent(commentType, mapResqmlTypesComment[this.type.toLowerCase()]); - - this.htmlTitleElt.appendChild(divCommentTitle); - }else{ - //console.log("no comment for " + this.type); - } - - var htmlTitleElt_values = document.createElement("span"); - htmlTitleElt_values.appendChild(document.createTextNode(titleValue)); - this.htmlTitleElt.appendChild(htmlTitleElt_values); - if(showTypeAsTooltip){ - this.htmlTitleElt.title = shortType; - } - - - if(!isUpdating){ - // Creation du bouton de collapser d'arbre - this.subAttribCollapserElt = document.createElement("span"); - //this.subAttribCollapserElt.id = this.rootUUID + this.name; - this.subAttribCollapserElt.style.cursor = "pointer"; - this.subAttribCollapserElt.className = "resqmlCollapse fas fa-chevron-right"; - - this.subAttribCollapserElt.onclick = - function(){ - if(constThis.htmlSubAttribElt != null){ - if(constThis.subAttribCollapserElt.className.includes("fa-chevron-right")){ - constThis.subAttribCollapserElt.className = constThis.subAttribCollapserElt.className.replace("fa-chevron-right", "fa-chevron-down"); - constThis.htmlSubAttribElt.style.display = ""; - }else{ - constThis.subAttribCollapserElt.className = constThis.subAttribCollapserElt.className.replace("fa-chevron-down", "fa-chevron-right"); - constThis.htmlSubAttribElt.style.display = "none"; - } - } - }; - - this.htmlAttributeElt.appendChild(this.subAttribCollapserElt); - - this.htmlAttributeElt.appendChild(this.htmlTitleElt); - - if(constThis.type.toLowerCase().includes("datasetpart") - || constThis.type.toLowerCase().includes("hdf5dataset")){ - var butOpenHDFView = document.createElement("img"); - butOpenHDFView.src = "ressources/img/HDF_logo.png"; - butOpenHDFView.alt = "[ HDFView ]"; - butOpenHDFView.className = "hdfViewIcon" - butOpenHDFView.title = "Open in HDFView" - //var butOpenHDFView = document.createElement("span"); - //butOpenHDFView.appendChild(document.createTextNode("[[HDFView]]")); - //butOpenHDFView.appendChild(document.createTextNode("")); - butOpenHDFView.onclick = function(){ - //console.log(constThis); - var pathInHDF = ""; - for(var propIdx=0; propIdx { - openHDFViewAskH5Location(res.value, pathInHDF); - }); - }catch(e){ - console.log(e); - } - } - } - /*openHDFViewAskH5Location(pathInHDF); - console.log("===> HDF5 open") - console.log(constThis.attributes)*/ - }; - this.htmlAttributeElt.appendChild(butOpenHDFView); - } - - - // Si il y a des sous-element a creer - if(tabCreateSubAttrib.length>0 || tabListsAttribs.length>0){ - this.htmlSubAttribCreatorList = this.createSubAttribAddingListCollapser(tabCreateSubAttrib.concat(tabListsAttribs)); - if(this.htmlSubAttribCreatorList != null){ - this.htmlAttributeElt.appendChild(this.htmlSubAttribCreatorList); - } - } - - if(!this.isResqmlListType() && this.name.length>0){ - // Bouton de suppression - var deleteBut = createDeleteButton("deleteButton deleteButtonTree", "Delete Element"); - deleteBut.onclick = function(){constThis.remove(true);}; - this.htmlAttributeElt.appendChild(deleteBut); - } - - if(this.htmlSubAttribElt != null){ - this.htmlAttributeElt.appendChild(this.htmlSubAttribElt); - this.htmlSubAttribElt.style.display = "none"; - this.htmlSubAttribElt.className += " treeSubAttribute"; - } - - }else{ // updating - // Si il y a des sous-element a creer - if(tabCreateSubAttrib.length>0 || tabListsAttribs.length>0){ - var newCreatorList = this.createSubAttribAddingListCollapser(tabCreateSubAttrib.concat(tabListsAttribs), this); - if(this.htmlSubAttribCreatorList != null){ // Si il y en avait un avant on le remplace - if(newCreatorList != null){ - this.htmlAttributeElt.replaceChild(newCreatorList, this.htmlSubAttribCreatorList); - try{ - this.htmlSubAttribCreatorList.remove(); - }catch(Ee){console.log(Ee);} - }else{ - this.htmlAttributeElt.remove(); - } - }else{ // Si il y en avait pas avant on l'ajoute apres le title - if(newCreatorList != null){ - this.htmlTitleElt.after(newCreatorList); - } - } - this.htmlSubAttribCreatorList = newCreatorList; - }else{ - if(this.htmlSubAttribCreatorList != null){ - this.htmlSubAttribCreatorList.remove(); - this.htmlSubAttribCreatorList = null; - } - } - } - - // Si il y a des sous-attributs on affiche la fleche, sinon on ne l'affiche pas - if(this.htmlSubAttribElt.children.length <= 0){ - this.subAttribCollapserElt.style.display = "none"; - this.subAttribCollapserElt.className = this.subAttribCollapserElt.className.replace("fa-chevron-down", "fa-chevron-right"); - this.htmlSubAttribElt.style.display = "none"; - }else{ - this.subAttribCollapserElt.style.display = ""; - } - - - /** Property **/ - if((this.properties!= null && this.properties.length > 0) || this.value != null){ - const propRootElt = this.htmlElt_propertyRoot; - if(propRootElt != null){ - var lastStyleDisplay = "none"; - if(this.htmlCurrentProperty!=null){ - lastStyleDisplay = this.htmlCurrentProperty.style.display; - this.htmlCurrentProperty.remove(); - } - - this.htmlCurrentProperty = this.createPropertyTable(); - this.htmlCurrentProperty.style.display = lastStyleDisplay; - propRootElt.appendChild(this.htmlCurrentProperty); - - const constCurrentProp = this.htmlCurrentProperty; - - this.htmlTitleElt.style.cursor = "pointer"; - if(!this.htmlTitleElt.className.includes("treeLeafWithProperty")) - this.htmlTitleElt.className += " treeLeafWithProperty"; - //this.htmlTitleElt.style.fontStyle = "italic"; - - this.htmlTitleElt.onclick = function(){ - for(var propChildIdx=0; propChildIdx < propRootElt.childNodes.length; propChildIdx++){ - try{ - // on invisibilise toutes les propriétés - propRootElt.childNodes[propChildIdx].style.display = "none"; - // console.log("child disable : " + propRootElt.childNodes[propChildIdx] + " " + propChildIdx); - }catch(e){console.error("/!\\ child not disable : " + propChildIdx);} - } - //console.log(constCurrentProp); - constCurrentProp.style.display = ""; - }; - }else{ - // console.log("no property ROOT " + this.name); - } - }else{ - // console.log("no property for " + this.name); - // Si on a pas de propriete on active le click pour ouvrir les sous element a la place. - const constThis = this; - this.htmlTitleElt.onclick = function(){ - constThis.subAttribCollapserElt.click(); - }; - } - - if(!isUpdating && this.parentElt == null){ - this.subAttribCollapserElt.click(); - } - } - } - - /** **/ - return this.htmlAttributeElt; - } - - - createPropertyTable(){ - var shortName = this.name; - if(shortName.includes(".")) - shortName = shortName.substring(shortName.lastIndexOf('.')+1); - if(shortName.length<=0){ - shortName = this.rootUUID; - } - - // En-tete - var titleElt = document.createElement("h4"); - titleElt.appendChild(document.createTextNode("Properties of " + shortName)); - titleElt.title = this.name; - - // Tableau - var propTable = document.createElement("table"); - propTable.className += "propertyTable"; - - if(this.properties != null){ - for(var prop=0; prop\w+)\+xml;version=(?[\w\.]+);type=(?\w+)/mi); - }else if(qualifiedtype != null){ - match = qualifiedtype.match(/(?\w+)(?[\w\.]+)\.(?\w+)/mi); - } - var obj_version_num = match.groups["version"]; - var obj_pkg = match.groups["pkgName"]; - var obj_type = match.groups["objecType"]; - const generated_uri = "eml:///" + obj_pkg + (obj_version_num != null ? obj_version_num.replace(".", "") : "") + "." + obj_type + "(" + contentUUID + ")"; - - const col1_uri = document.createElement("td"); - const col1_uri_text = document.createElement("input"); - col1_uri_text.readOnly = "readonly"; - col1_uri_text.className = "form-control"; // Le chemin - col1_uri_text.typeName = "text"; - col1_uri_text.value = generated_uri; - col1_uri.appendChild(col1_uri_text); - line.appendChild(col1_uri); - propTable.appendChild(line); - }catch(Except){ - console.log("unable to generate URI"); - //console.log(Except); - } - - }catch(Except){ - console.log(Except); - } - } - - propertyDiv.appendChild(titleElt); - propertyDiv.appendChild(propTable); - - return propertyDiv; - } - - - getCurrentListContentElt(){ - try{ - if(this.isResqmlListType()){ - var contentJSON = "{\"name\":\"" + this.name + "\", " + " \"type\":\"" + this.templatedClass[0] + "\"}"; - - var res = new ResqmlElement(JSON.parse(contentJSON), - this.rootUUID, - this.htmlElt_propertyRoot, - this, - true); - return res; - }else{ - //console.log("not a list type " + this.name +" - " + this.type); - } - }catch(except){ - console.log(except) + propertyDiv.appendChild(titleElt); + propertyDiv.appendChild(propTable); + + return propertyDiv; } - return this; - } - - refresh(){ - //console.log("refreshing " + this.name); - const constThis = this; - - var url = "ResqmlObjectTree?uuid="+this.rootUUID; - if(this.name.length > 0){ - url += "&path=" + this.name; - } - //console.log("UPDATING sending url " + url); - return sendGetURL_Promise(url).then( - responseText => new Promise((resolve, reject) =>{ - if(responseText != null){ - //console.log(responseText); - try{ - var jsonContent = JSON.parse(responseText); - constThis.updateElementFromJSON(jsonContent); - resolve(); - }catch(ExceptionJSON){reject();} - }else{ - reject(); - } - })); - } - - getResqmlObjectJson(uuid, subPath){ - //console.log("refreshing " + this.name); - - var url = "ResqmlObjectTree?uuid="+uuid; - if(subPath && subPath.length > 0){ - url += "&path=" + subPath; - } - //console.log("getResqmlObjectJson sending url " + url); - return sendGetURL_Promise(url).then( - responseText => new Promise((resolve, reject) =>{ - if(responseText != null){ - //console.log("RESPONSE : " + responseText); - try{ - var jsonContent = JSON.parse(responseText); - resolve(jsonContent); - }catch(ExceptionJSON){reject();} - }else{ - reject(); - } - })); - } - - isLeafProperty(){ - return (this.properties == null || this.properties.length <= 0) - && (this.attributes == null || this.attributes.length <= 0) - && !this.isResqmlListType(); - } - - isResqmlListType(){ - return this.type.endsWith("List");// || this.type.endsWith("Array"); // ou Collection - } - - remove(updateServer){ - const constThis = this; - /*console.log("> REMOVING "); - console.log(this);*/ - - if(updateServer!=null && updateServer){ - var url = "ObjectEdit?Root_UUID=" + this.rootUUID - + "&command=delete" - + "&path=" + this.name; - //console.log("remove and request server : " + this.name + " URL : " + url); - fetch(url).then(function(){ - if(constThis.parentElt != null){ - /*console.log("fini delete"); - console.log("refresh parent : "); - console.log(constThis.parentElt);*/ - constThis.parentElt.refresh(); - }else{ - console.log("null parent for refresh"); - console.log(constThis); - } - }).catch((error) => console.error(error)); - }else{ - if(this.htmlAttributeElt != null && this.htmlAttributeElt.parentNode != null){ - //console.log("removing elt : " + this.name); - //this.htmlAttributeElt.remove(); - this.htmlAttributeElt.parentNode.removeChild(this.htmlAttributeElt); - this.htmlAttributeElt = null; - //this.htmlElt_propertyRoot.remove(); - //this.htmlElt_propertyRoot = null; - }else{ - /*console.log("null html for "); - console.log(this);*/ - } - if(this.htmlCurrentProperty!=null){ - //console.log("removing all element with id starting with : " + this.htmlCurrentProperty); - document.querySelectorAll('[id^="' + this.htmlCurrentProperty.id + '"]').forEach( - function(element, index) { - element.remove(); - }); - } - } - } - - // Ici on se sert d'une liste globale qui contient tous les types existants - createSubAttribAddingListCollapser(subAttList, currentElt){ - var tabSubAttElt = []; - - // On tris les element à creer - subAttList.sort(function (a, b) { - return a.name.localeCompare(b.name); - }); - - - for(var subA_Idx=0; subA_Idx>>>" + mapResqmlTypeToSubtypes[subA.type.toLowerCase()][nbInstanciableType] + " + " + subA.name + " + " + subA.type); - console.log(mapResqmlTypeToSubtypes);*/ - } - }else if("java.lang.Object" != subA.type){ - if(!subA.type.toLowerCase().includes("contactelement") || this.type.toLowerCase().includes("contact")){ - tabSubAttElt.push(this.createSubAttribAddingElt(subA.type, subA.name, currentElt)); - if(subA.mandatory=="true"){ - tabSubAttElt[tabSubAttElt.length-1].className += " mandatoryElt"; - } - }else{ - console.log('On a oublié contactelement[reference] pour le type ' + this.type); - } - /*console.log(mapResqmlTypeToSubtypes) - console.log(">-->" +subA.type + " + " + subA.name);*/ - }else{ - console.log("Error for subElement '" + subA.name + "'' creation. Editor doesn't support " + subA.type + " creation"); - } - } - if(tabSubAttElt.length>0){ - var dropDown = createDropDownButton(tabSubAttElt, "subAttributeCreatorList_"+this.name, "dropdown-menu-energyml-elt"); - dropDown.title = "Create sub element"; - dropDown.className += " dropDownCreateSubAttribute"; - return dropDown; - }else{ - return null; - } - } - - createSubAttribAddingElt(subEltType, subEltName, currentElt){ - const constThis = this; - const constSubEltName = subEltName; - - var link = document.createElement("span"); - //link.id = id; - var typeName = subEltType; - if(typeName.includes(".")){ - typeName = typeName.substr(typeName.lastIndexOf(".")+1); - } - var parentName = this.name; - if(parentName.includes(".")){ - parentName = parentName.substr(0, parentName.lastIndexOf(".")); - } - - var currentName = subEltName; - if(currentName.includes(".")){ - currentName = currentName.substr(currentName.lastIndexOf(".")+1); - } - - link.appendChild(document.createTextNode("> " + currentName + " ["+ typeName + "]")); - - const htmlEltParent = this.htmlAttributeElt; - - var enableFilter = true; - - - // Fin du formulaire - - if(enableFilter && (subEltType.includes("DataObjectReference") || subEltType.includes("ContactElement")) ){ - link.onclick = function(){ + getCurrentListContentElt() { + try { + if (this.isResqmlListType()) { + var contentJSON = "{\"name\":\"" + this.name + "\", " + " \"type\":\"" + this.templatedClass[0] + "\"}"; + + var res = new ResqmlElement(JSON.parse(contentJSON), + this.rootUUID, + this.htmlElt_propertyRoot, + this, + true); + return res; + } else { + //console.log("not a list type " + this.name +" - " + this.type); + } + } catch (except) { + console.log(except) + } + return this; + } + + refresh() { + //console.log("refreshing " + this.name); + const constThis = this; + + var url = "ResqmlObjectTree?uuid=" + this.rootUUID; + if (this.name.length > 0) { + url += "&path=" + this.name; + } + //console.log("UPDATING sending url " + url); + return sendGetURL_Promise(url).then( + responseText => new Promise((resolve, reject) => { + if (responseText != null) { + //console.log(responseText); + try { + var jsonContent = JSON.parse(responseText); + constThis.updateElementFromJSON(jsonContent); + resolve(); + } catch (ExceptionJSON) { + reject(); + } + } else { + reject(); + } + })); + } + + getResqmlObjectJson(uuid, subPath) { + //console.log("refreshing " + this.name); + + var url = "ResqmlObjectTree?uuid=" + uuid; + if (subPath && subPath.length > 0) { + url += "&path=" + subPath; + } + //console.log("getResqmlObjectJson sending url " + url); + return sendGetURL_Promise(url).then( + responseText => new Promise((resolve, reject) => { + if (responseText != null) { + //console.log("RESPONSE : " + responseText); + try { + var jsonContent = JSON.parse(responseText); + resolve(jsonContent); + } catch (ExceptionJSON) { + reject(); + } + } else { + reject(); + } + })); + } + + isLeafProperty() { + return (this.properties == null || this.properties.length <= 0) && + (this.attributes == null || this.attributes.length <= 0) && + !this.isResqmlListType(); + } + + isResqmlListType() { + return this.type.endsWith("List"); // || this.type.endsWith("Array"); // ou Collection + } + + remove(updateServer) { + const constThis = this; + /*console.log("> REMOVING "); + console.log(this);*/ + + if (updateServer != null && updateServer) { + var url = "ObjectEdit?Root_UUID=" + this.rootUUID + + "&command=delete" + + "&path=" + this.name; + //console.log("remove and request server : " + this.name + " URL : " + url); + fetch(url).then(function() { + if (constThis.parentElt != null) { + /*console.log("fini delete"); + console.log("refresh parent : "); + console.log(constThis.parentElt);*/ + constThis.parentElt.refresh(); + } else { + console.log("null parent for refresh"); + console.log(constThis); + } + }).catch((error) => console.error(error)); + } else { + if (this.htmlAttributeElt != null && this.htmlAttributeElt.parentNode != null) { + //console.log("removing elt : " + this.name); + //this.htmlAttributeElt.remove(); + this.htmlAttributeElt.parentNode.removeChild(this.htmlAttributeElt); + this.htmlAttributeElt = null; + //this.htmlElt_propertyRoot.remove(); + //this.htmlElt_propertyRoot = null; + } else { + /*console.log("null html for "); + console.log(this);*/ + } + if (this.htmlCurrentProperty != null) { + //console.log("removing all element with id starting with : " + this.htmlCurrentProperty); + document.querySelectorAll('[id^="' + this.htmlCurrentProperty.id + '"]').forEach( + function(element, index) { + element.remove(); + }); + } + } + } + + // Ici on se sert d'une liste globale qui contient tous les types existants + createSubAttribAddingListCollapser(subAttList, currentElt) { + var tabSubAttElt = []; + + // On tris les element à creer + subAttList.sort(function(a, b) { + return a.name.localeCompare(b.name); + }); + + + for (var subA_Idx = 0; subA_Idx < subAttList.length; subA_Idx++) { + var subA = subAttList[subA_Idx]; + if (mapResqmlTypeToSubtypes[subA.type.toLowerCase()] != null) { + for (var nbInstanciableType = 0; nbInstanciableType < mapResqmlTypeToSubtypes[subA.type.toLowerCase()].length; nbInstanciableType++) { + var subEltType = mapResqmlTypeToSubtypes[subA.type.toLowerCase()][nbInstanciableType]; + + /* + ___ ___________________ ________________ _ __ + / |/_ __/_ __/ ____/ | / /_ __/ _/ __ \/ | / / + / /| | / / / / / __/ / |/ / / / / // / / / |/ / + / ___ |/ / / / / /___/ /| / / / _/ // /_/ / /| / + /_/ |_/_/ /_/ /_____/_/ |_/ /_/ /___/\____/_/ |_/ + */ + + // On filtre les ContactElement[Reference] car ils etendent DOR et sont proposés partout alors qu'il ne sont + // utiles QUE dans les BinaryContactInterpretationPart (dans les StructuralOrgInterp et StratigraphiqOrgInterp) + + // Ici on a choisi de bypasser le CER si le type de l'element courant ne contient pas le mot "Contact" + if (!subEltType.toLowerCase().includes("contactelement") || + this.type.toLowerCase().includes("contact")) { + tabSubAttElt.push(this.createSubAttribAddingElt(subEltType, subA.name, currentElt)); + if (subA.mandatory == "true") { + tabSubAttElt[tabSubAttElt.length - 1].className += " mandatoryElt"; + } + } + + /*console.log(">>>>" + mapResqmlTypeToSubtypes[subA.type.toLowerCase()][nbInstanciableType] + " + " + subA.name + " + " + subA.type); + console.log(mapResqmlTypeToSubtypes);*/ + } + } else if ("java.lang.Object" != subA.type) { + if (!subA.type.toLowerCase().includes("contactelement") || this.type.toLowerCase().includes("contact")) { + tabSubAttElt.push(this.createSubAttribAddingElt(subA.type, subA.name, currentElt)); + if (subA.mandatory == "true") { + tabSubAttElt[tabSubAttElt.length - 1].className += " mandatoryElt"; + } + } else { + console.log('On a oublié contactelement[reference] pour le type ' + this.type); + } + /*console.log(mapResqmlTypeToSubtypes) + console.log(">-->" +subA.type + " + " + subA.name);*/ + } else { + console.log("Error for subElement '" + subA.name + "'' creation. Editor doesn't support " + subA.type + " creation"); + } + } + if (tabSubAttElt.length > 0) { + var dropDown = createDropDownButton(tabSubAttElt, "subAttributeCreatorList_" + this.name, "dropdown-menu-energyml-elt"); + dropDown.title = "Create sub element"; + dropDown.className += " dropDownCreateSubAttribute"; + return dropDown; + } else { + return null; + } + } + + createSubAttribAddingElt(subEltType, subEltName, currentElt) { + const constThis = this; + const constSubEltName = subEltName; + + var link = document.createElement("span"); + //link.id = id; + var typeName = subEltType; + if (typeName.includes(".")) { + typeName = typeName.substr(typeName.lastIndexOf(".") + 1); + } + var parentName = this.name; + if (parentName.includes(".")) { + parentName = parentName.substr(0, parentName.lastIndexOf(".")); + } + + var currentName = subEltName; + if (currentName.includes(".")) { + currentName = currentName.substr(currentName.lastIndexOf(".") + 1); + } + + link.appendChild(document.createTextNode("> " + currentName + " [" + typeName + "]")); + + const htmlEltParent = this.htmlAttributeElt; + + var enableFilter = true; + + + // Fin du formulaire + + if (enableFilter && (subEltType.includes("DataObjectReference") || subEltType.includes("ContactElement"))) { + link.onclick = function() { var etp_dataspace = null; - try{ + try { etp_dataspace = document.getElementsByClassName("etp_select_dataspace")[0].value; - }catch(e){console.log(e);} - getJsonObjectFromServer("ResqmlAccessibleDOR?uuid=" + constThis.rootUUID - + "&subParamPath=" + constThis.name - + "&subParamName=" + currentName - + ( (etp_dataspace != null && etp_dataspace.length > 0 ) ? "&dataspace=" + etp_dataspace : "" ) - ).then( - function(jsonContent){ + } catch (e) { + console.log(e); + } + getJsonObjectFromServer("ResqmlAccessibleDOR?uuid=" + constThis.rootUUID + + "&subParamPath=" + constThis.name + + "&subParamName=" + currentName + + ((etp_dataspace != null && etp_dataspace.length > 0) ? "&dataspace=" + etp_dataspace : "") + ).then( + function(jsonContent) { const workspace_content = jsonContent["workspace"]; const etp_content = jsonContent["etp"]; @@ -1448,21 +1509,21 @@ export class ResqmlElement{ formCreate_Empty.method = "post"; var inputCommand_Empty = document.createElement("input"); - inputCommand_Empty.type ="text"; + inputCommand_Empty.type = "text"; inputCommand_Empty.name = "command"; inputCommand_Empty.value = "update"; inputCommand_Empty.hidden = "hidden"; formCreate_Empty.appendChild(inputCommand_Empty); var inputRootUUID = document.createElement("input"); - inputRootUUID.type ="text"; + inputRootUUID.type = "text"; inputRootUUID.name = "Root_UUID"; inputRootUUID.value = constThis.rootUUID; inputRootUUID.hidden = "hidden"; formCreate_Empty.appendChild(inputRootUUID); var inputUUID_Empty = document.createElement("input"); - inputUUID_Empty.type ="text"; + inputUUID_Empty.type = "text"; inputUUID_Empty.name = constSubEltName; inputUUID_Empty.className = "form-control"; inputUUID_Empty.placeholder = "External UUID (e.g. 00000000-0000-0000-0000-000000000000)"; @@ -1473,10 +1534,10 @@ export class ResqmlElement{ var inputSubmit_Empty = document.createElement("button"); inputSubmit_Empty.className = "btn btn-success"; inputSubmit_Empty.appendChild(document.createTextNode("OK")); - inputSubmit_Empty.onclick = function(){ - sendPostForm_Func(formCreate_Empty, "ObjectEdit", function(){ - constThis.refresh(); - }); + inputSubmit_Empty.onclick = function() { + sendPostForm_Func(formCreate_Empty, "ObjectEdit", function() { + constThis.refresh(); + }); closeModal(modalID); }; @@ -1485,7 +1546,7 @@ export class ResqmlElement{ formDiv_Empty.appendChild(formCreate_Empty); formDiv_Empty.appendChild(inputSubmit_Empty);*/ - var formDiv_Empty = createInputGroup([formCreate_Empty,inputSubmit_Empty], [false, true]); + var formDiv_Empty = createInputGroup([formCreate_Empty, inputSubmit_Empty], [false, true]); /** Formulaire de creation par un uuid interne e l'epc **/ @@ -1494,39 +1555,41 @@ export class ResqmlElement{ formCreate.method = "post"; var inputCommand = document.createElement("input"); - inputCommand.type ="text"; + inputCommand.type = "text"; inputCommand.name = "command"; inputCommand.value = "update"; inputCommand.hidden = "hidden"; formCreate.appendChild(inputCommand); var inputRootUUID = document.createElement("input"); - inputRootUUID.type ="text"; + inputRootUUID.type = "text"; inputRootUUID.name = "Root_UUID"; inputRootUUID.value = constThis.rootUUID; inputRootUUID.hidden = "hidden"; formCreate.appendChild(inputRootUUID); var tableDOR = createTableFromData( - workspace_content, - ["num", "type", "title", "uuid", "schemaVersion"], - ["Num", "Type", "Title", "UUID", "SchemaVersion"], - workspace_content.map(contentElt => [ function(){openResqmlObjectContentByUUID(contentElt['uuid'])} ]), - null ); + workspace_content, + ["num", "type", "title", "uuid", "schemaVersion"], + ["Num", "Type", "Title", "UUID", "SchemaVersion"], + workspace_content.map(contentElt => [function() { + openResqmlObjectContentByUUID(contentElt['uuid']) + }]), + null); var tableDOR_etp = createTableFromData( - etp_content, - ["num", "type", "title", "uuid", "schemaVersion", "uri"], - ["Num", "Type", "Title", "UUID", "SchemaVersion", "Uri"], - null, - null ); + etp_content, + ["num", "type", "title", "uuid", "schemaVersion", "uri"], + ["Num", "Type", "Title", "UUID", "SchemaVersion", "Uri"], + null, + null); var shouldBeCheckable = currentElt.type.includes("proposal2_2.Collection"); - for(var attIdx in currentElt.attributes){ + for (var attIdx in currentElt.attributes) { var attrib = currentElt.attributes[attIdx]; - if(attrib.name == subEltName){ - if(attrib.type.endsWith("List")){ + if (attrib.name == subEltName) { + if (attrib.type.endsWith("List")) { shouldBeCheckable = true; } break; @@ -1535,17 +1598,17 @@ export class ResqmlElement{ /*console.log('sub elt name' + subEltName + " -- ") console.log(currentElt)*/ - if(shouldBeCheckable){ + if (shouldBeCheckable) { transformTabToFormCheckable(tableDOR, workspace_content.map(contentElt => contentElt.uuid), constSubEltName); transformTabToFormCheckable(tableDOR_etp, etp_content.map(contentElt => contentElt.uri), constSubEltName); - }else{ + } else { transformTabToFormRadio(tableDOR, workspace_content.map(contentElt => contentElt.uuid), constSubEltName); transformTabToFormRadio(tableDOR_etp, etp_content.map(contentElt => contentElt.uri), constSubEltName); } formCreate.appendChild(tableDOR); - if(etp_content.length > 0){ + if (etp_content.length > 0) { var etpTableTitle = document.createElement("h3"); etpTableTitle.appendChild(document.createTextNode(`From ETP server (dataspace ${etp_dataspace})`)); formCreate.appendChild(etpTableTitle); @@ -1555,10 +1618,10 @@ export class ResqmlElement{ var inputSubmit = document.createElement("button"); inputSubmit.className = "btn btn-success"; inputSubmit.appendChild(document.createTextNode("OK")); - inputSubmit.onclick = function(){ - sendPostForm_Func(formCreate, "ObjectEdit", function(){ - constThis.refresh(); - }); + inputSubmit.onclick = function() { + sendPostForm_Func(formCreate, "ObjectEdit", function() { + constThis.refresh(); + }); closeModal(modalID); }; @@ -1581,135 +1644,135 @@ export class ResqmlElement{ modalContentDiv.appendChild(inputSubmit); openModal(modalID, "Creating DOR for " + constThis.rootUUID, modalContentDiv); - } - ); - }; - }else{ - // Debut du formulaire - - const formCreate = document.createElement("form"); - formCreate.action = "ObjectEdit"; - formCreate.method = "post"; - formCreate.acceptCharset = "UTF-8"; - - var inputCommand = document.createElement("input"); - inputCommand.name = "command"; - inputCommand.value = "update"; - inputCommand.hidden = "hidden"; - formCreate.appendChild(inputCommand); - - var inputUUID = document.createElement("input"); - inputUUID.name = "Root_UUID"; - inputUUID.value = this.rootUUID; - inputUUID.hidden = "hidden"; - formCreate.appendChild(inputUUID); - - var inputPath = document.createElement("input"); - inputPath.name = "path"; - inputPath.value = constSubEltName; - formCreate.appendChild(inputPath); - - inputCommand.value = "create"; - - var inputTypeToCreate = document.createElement("input"); - inputTypeToCreate.name = "type"; - inputTypeToCreate.value = subEltType; - formCreate.appendChild(inputTypeToCreate); - - // ATTENTION ! on ne supporte pas les CustomData - if(!enableFilter || !subEltType.includes("CustomData")){ - link.onclick = async function(){ - - // We should save before creating the sub element, else, it will reset all modifications - try{ - saveResqmlObjectByUUID(constThis.rootUUID)[0].then( - function(){ - sendPostForm_Func(formCreate, "ObjectEdit", function(){ - constThis.refresh(); - }) - } - ); - }catch(Except){ - console.log(Except); - console.log("Exception while trying to save data before adding sub element"); - sendPostForm_Func(formCreate, "ObjectEdit", function(){ - constThis.refresh(); - }); - } - }; - }else{ - link.className = "disabledLink"; - } - } - return link; - } - - updateListAttributesNames(){ - if(this.isResqmlListType()){ - this.attributes.forEach(function(x){ - var newIdx = getHtmlEltIdxInParent(x.htmlAttributeElt); - x.name = x.name.substring(0, x.name.lastIndexOf(".")+1) + newIdx; - // console.log("new name : " + x.name); - }); - } - } - - - create_activityView(){ - const constThis = this; - var isUpdating = false; - - - // Nom a afficher : la derniere partie du path - var shortName = this.name; - if(shortName.includes(".")) - shortName = shortName.substring(shortName.lastIndexOf('.')+1); - - var shortType = this.type; - if(shortType.includes(".")) - shortType = shortType.substring(shortType.lastIndexOf('.')+1); - - /* - _____ _ _ __ _ __ - / ___/(_) ____( )___ _____/ /_ __ ______ ___ ____ _________ ____ _____(_)__ / /____ - \__ \/ / / ___/// _ \/ ___/ __/ / / / / __ \/ _ \ / __ \/ ___/ __ \/ __ \/ ___/ / _ \/ __/ _ \ - ___/ / / / /__ / __(__ ) /_ / /_/ / / / / __/ / /_/ / / / /_/ / /_/ / / / / __/ /_/ __/ - /____/_/ \___/ \___/____/\__/ \__,_/_/ /_/\___/ / .___/_/ \____/ .___/_/ /_/\___/\__/\___/ - /_/ /_/ - */ - if(!this.isAttribute){ - - this.htmlAttributeElt.appendChild(col0); - }else{ - /* - _____ _ _ __ ____ _ ____ __ ___ __ __ __ __ _ __ __ _ - / ___/(_) ____( )___ _____/ /_ __ ______ ___ / __/__ __ __(_) / /__ ____/ /__ / ( )____ ______/ /_ ________ _/_/___ _/ /_/ /______(_) /_ __ __/ /_| | - \__ \/ / / ___/// _ \/ ___/ __/ / / / / __ \/ _ \ / /_/ _ \/ / / / / / / _ \ / __ / _ \ / /|// __ `/ ___/ __ \/ ___/ _ \ / // __ `/ __/ __/ ___/ / __ \/ / / / __// / - ___/ / / / /__ / __(__ ) /_ / /_/ / / / / __/ / __/ __/ /_/ / / / / __/ / /_/ / __/ / / / /_/ / / / /_/ / / / __/ / // /_/ / /_/ /_/ / / / /_/ / /_/ / /_ / / - /____/_/ \___/ \___/____/\__/ \__,_/_/ /_/\___/ /_/ \___/\__,_/_/_/_/\___/ \__,_/\___/ /_/ \__,_/_/ /_.___/_/ \___/ / / \__,_/\__/\__/_/ /_/_.___/\__,_/\__//_/ - |_| /_/ - */ - // Creation d'une div pour l'element courant et ses attributs - if(this.htmlAttributeElt == null){ // On crée l'element si il n'existe pas deja - this.htmlAttributeElt = document.createElement("div"); - }else{ - // Si existe deja on fait une mise à jour - isUpdating = true; - if(this.isResqmlListType() && (this.attributes == null || this.attributes.length <= 0) ){ - // Si c'est une liste et qu'elle est vide, on supprime l'element - // this.remove(); - return null; - } - } - this.htmlAttributeElt.name = ResqmlElement_NAMESUBATTPREFIX + "_" + shortName; - - - - if(!isUpdating && this.parentElt == null){ - this.subAttribCollapserElt.click(); - } - } - - return this.htmlAttributeElt; - } + } + ); + }; + } else { + // Debut du formulaire + + const formCreate = document.createElement("form"); + formCreate.action = "ObjectEdit"; + formCreate.method = "post"; + formCreate.acceptCharset = "UTF-8"; + + var inputCommand = document.createElement("input"); + inputCommand.name = "command"; + inputCommand.value = "update"; + inputCommand.hidden = "hidden"; + formCreate.appendChild(inputCommand); + + var inputUUID = document.createElement("input"); + inputUUID.name = "Root_UUID"; + inputUUID.value = this.rootUUID; + inputUUID.hidden = "hidden"; + formCreate.appendChild(inputUUID); + + var inputPath = document.createElement("input"); + inputPath.name = "path"; + inputPath.value = constSubEltName; + formCreate.appendChild(inputPath); + + inputCommand.value = "create"; + + var inputTypeToCreate = document.createElement("input"); + inputTypeToCreate.name = "type"; + inputTypeToCreate.value = subEltType; + formCreate.appendChild(inputTypeToCreate); + + // ATTENTION ! on ne supporte pas les CustomData + if (!enableFilter || !subEltType.includes("CustomData")) { + link.onclick = async function() { + + // We should save before creating the sub element, else, it will reset all modifications + try { + saveResqmlObjectByUUID(constThis.rootUUID)[0].then( + function() { + sendPostForm_Func(formCreate, "ObjectEdit", function() { + constThis.refresh(); + }) + } + ); + } catch (Except) { + console.log(Except); + console.log("Exception while trying to save data before adding sub element"); + sendPostForm_Func(formCreate, "ObjectEdit", function() { + constThis.refresh(); + }); + } + }; + } else { + link.className = "disabledLink"; + } + } + return link; + } + + updateListAttributesNames() { + if (this.isResqmlListType()) { + this.attributes.forEach(function(x) { + var newIdx = getHtmlEltIdxInParent(x.htmlAttributeElt); + x.name = x.name.substring(0, x.name.lastIndexOf(".") + 1) + newIdx; + // console.log("new name : " + x.name); + }); + } + } + + + create_activityView() { + const constThis = this; + var isUpdating = false; + + + // Nom a afficher : la derniere partie du path + var shortName = this.name; + if (shortName.includes(".")) + shortName = shortName.substring(shortName.lastIndexOf('.') + 1); + + var shortType = this.type; + if (shortType.includes(".")) + shortType = shortType.substring(shortType.lastIndexOf('.') + 1); + + /* + _____ _ _ __ _ __ + / ___/(_) ____( )___ _____/ /_ __ ______ ___ ____ _________ ____ _____(_)__ / /____ + \__ \/ / / ___/// _ \/ ___/ __/ / / / / __ \/ _ \ / __ \/ ___/ __ \/ __ \/ ___/ / _ \/ __/ _ \ + ___/ / / / /__ / __(__ ) /_ / /_/ / / / / __/ / /_/ / / / /_/ / /_/ / / / / __/ /_/ __/ + /____/_/ \___/ \___/____/\__/ \__,_/_/ /_/\___/ / .___/_/ \____/ .___/_/ /_/\___/\__/\___/ + /_/ /_/ + */ + if (!this.isAttribute) { + + this.htmlAttributeElt.appendChild(col0); + } else { + /* + _____ _ _ __ ____ _ ____ __ ___ __ __ __ __ _ __ __ _ + / ___/(_) ____( )___ _____/ /_ __ ______ ___ / __/__ __ __(_) / /__ ____/ /__ / ( )____ ______/ /_ ________ _/_/___ _/ /_/ /______(_) /_ __ __/ /_| | + \__ \/ / / ___/// _ \/ ___/ __/ / / / / __ \/ _ \ / /_/ _ \/ / / / / / / _ \ / __ / _ \ / /|// __ `/ ___/ __ \/ ___/ _ \ / // __ `/ __/ __/ ___/ / __ \/ / / / __// / + ___/ / / / /__ / __(__ ) /_ / /_/ / / / / __/ / __/ __/ /_/ / / / / __/ / /_/ / __/ / / / /_/ / / / /_/ / / / __/ / // /_/ / /_/ /_/ / / / /_/ / /_/ / /_ / / + /____/_/ \___/ \___/____/\__/ \__,_/_/ /_/\___/ /_/ \___/\__,_/_/_/_/\___/ \__,_/\___/ /_/ \__,_/_/ /_.___/_/ \___/ / / \__,_/\__/\__/_/ /_/_.___/\__,_/\__//_/ + |_| /_/ + */ + // Creation d'une div pour l'element courant et ses attributs + if (this.htmlAttributeElt == null) { // On crée l'element si il n'existe pas deja + this.htmlAttributeElt = document.createElement("div"); + } else { + // Si existe deja on fait une mise à jour + isUpdating = true; + if (this.isResqmlListType() && (this.attributes == null || this.attributes.length <= 0)) { + // Si c'est une liste et qu'elle est vide, on supprime l'element + // this.remove(); + return null; + } + } + this.htmlAttributeElt.name = ResqmlElement_NAMESUBATTPREFIX + "_" + shortName; + + + + if (!isUpdating && this.parentElt == null) { + this.subAttribCollapserElt.click(); + } + } + + return this.htmlAttributeElt; + } } \ No newline at end of file diff --git a/src/main/webapp/ressources/script/modules/etp/etp_connection.js b/src/main/webapp/ressources/script/modules/etp/etp_connection.js index 3aeb1d0..603993f 100644 --- a/src/main/webapp/ressources/script/modules/etp/etp_connection.js +++ b/src/main/webapp/ressources/script/modules/etp/etp_connection.js @@ -70,6 +70,14 @@ export function geosiris_createETP_connector_form(fun_isConnected, fun_isDisconn form.appendChild(inputGroup); + const headers = document.createElement("textarea"); + headers.classList.add('form-control'); + headers.setAttribute('name', 'etp-server-headers'); + headers.setAttribute('row', '6'); + headers.value = '{\n\t"data-partition-id": "osdu"\n}'; + form.appendChild(headers); + + const connectButton = document.createElement('input'); connectButton.setAttribute('type', 'button'); connectButton.setAttribute('name', 'request-type'); @@ -116,6 +124,8 @@ export function geosiris_createETP_connector_form(fun_isConnected, fun_isDisconn }catch(jsonFailed){ console.log(jsonFailed); } + + update_dataspaces_inputs(cst_callback_func); } ); @@ -125,6 +135,7 @@ export function geosiris_createETP_connector_form(fun_isConnected, fun_isDisconn btnConn.className = "btn btn-danger"; input_req.value = "disconnect"; inputGroup.style.display = 'none'; + headers.style.display = 'none'; if(cst_fun_isConnected != null){ cst_fun_isConnected(); } @@ -138,11 +149,12 @@ export function geosiris_createETP_connector_form(fun_isConnected, fun_isDisconn btnConn.className = "btn btn-primary mt-2"; input_req.value = "connect"; inputGroup.style.display = ''; + headers.style.display = ''; if(HAS_BEEN_CONNECTED_ONCE && cst_fun_isDisconnected != null){ cst_fun_isDisconnected(); } + update_dataspaces_inputs(cst_callback_func); } - update_dataspaces_inputs(cst_callback_func); } form.updateView = function(isConnected){ func_update_btn_view(connectButton, inreq, isConnected); @@ -199,6 +211,13 @@ export function create_dataspace_input(callback_func, inputs_classes_to_update){ const const_inputs_classes_to_update = inputs_classes_to_update; + var but_refresh_dataspaces = document.createElement('i'); + but_refresh_dataspaces.className = "btn btn-info fas fa-sync-alt"; + but_refresh_dataspaces.title = "Refresh dataspace list"; + but_refresh_dataspaces.addEventListener("click", function(event){ + update_dataspaces_inputs(null, true); + }); + selectDataspace.addEventListener("change", function(event){ if(const_inputs_classes_to_update != null){ @@ -210,7 +229,6 @@ export function create_dataspace_input(callback_func, inputs_classes_to_update){ } }); - selectDataspace.update = function (dataspacesNamesArray){ var selectedValue = null; // keep previous selected value during updates @@ -221,6 +239,7 @@ export function create_dataspace_input(callback_func, inputs_classes_to_update){ while(selectDataspace.firstChild){ selectDataspace.firstChild.remove(); } + if(dataspacesNamesArray.length > 0){ var option = document.createElement("option"); option.value = ""; @@ -228,6 +247,7 @@ export function create_dataspace_input(callback_func, inputs_classes_to_update){ selectDataspace.appendChild(option); } + dataspacesNamesArray = dataspacesNamesArray.filter((ds) => ds.length > 0 && ds != "eml:///"); [].forEach.call(dataspacesNamesArray, (elt, idx) =>{ var option = document.createElement("option"); option.value = elt; @@ -248,6 +268,7 @@ export function create_dataspace_input(callback_func, inputs_classes_to_update){ }; selectDataspace.update([]); div.appendChild(selectDataspace); + div.appendChild(but_refresh_dataspaces); return div; } diff --git a/src/main/webapp/ressources/script/modules/logs/console.js b/src/main/webapp/ressources/script/modules/logs/console.js index 1705f62..4efaf67 100644 --- a/src/main/webapp/ressources/script/modules/logs/console.js +++ b/src/main/webapp/ressources/script/modules/logs/console.js @@ -102,6 +102,8 @@ export function appendConsoleMessage(console_id, msg){ if(msg.severity != null){ severityClass = getSeverityClass(__CL_CONSOLE_LI__, msg.severity) } + + // console.log("severityClass " + severityClass + " __ " + msg.severity); var content = msg; if(msg.message != null){ @@ -208,8 +210,6 @@ export function rws_addConsoleMessageFilter(console_id){ } } } - - }; // Ajout des checkbox @@ -228,19 +228,23 @@ export function rws_addConsoleMessageFilter(console_id){ for (var mutation of mutationsList) { if(mutation.type == "childList"){ var target = mutation.target; + var addedNodes = mutation.addedNodes; const check_msg_type = console_elt.getElementsByClassName(check_classes); for (let checkboxDiv of check_msg_type) { var checkbox = checkboxDiv; if(checkbox.type==null || checkbox.type.toLowerCase()!="checkbox"){ checkbox = checkbox.getElementsByTagName("input")[0]; } - if(target.className.includes(getSeverityClass(__CL_CONSOLE_LI__, checkbox.value)) ){ - if(checkbox.checked){ - target.style.display = ""; - }else{ - target.style.display = "none"; + for(var addedN of addedNodes){ + if(addedN.className.includes(getSeverityClass(__CL_CONSOLE_LI__, checkbox.value)) ){ + if(checkbox.checked){ + addedN.style.display = ""; + }else{ + addedN.style.display = "none"; + } } } + } } } @@ -251,8 +255,8 @@ export function rws_addConsoleMessageFilter(console_id){ var observer = new MutationObserver(callback); // Event lors de l'ajout d'un message - for(let lu_msg of console_elt.getElementsByClassName(__CL_CONSOLE_UL__)){ - observer.observe(lu_msg, config); + for(let ul_msg of console_elt.getElementsByClassName(__CL_CONSOLE_UL__)){ + observer.observe(ul_msg, config); } // Creation du clear button diff --git a/src/main/webapp/ressources/script/modules/requests/requests.js b/src/main/webapp/ressources/script/modules/requests/requests.js index d0213a0..e1d2fe0 100644 --- a/src/main/webapp/ressources/script/modules/requests/requests.js +++ b/src/main/webapp/ressources/script/modules/requests/requests.js @@ -136,7 +136,9 @@ export function sendPostForm(form, url, showRequestResult) { XHR.send(FD); return XHR; -}export function sendPostForm_Func(form, url, onloadFunc) { +} + +export function sendPostForm_Func(form, url, onloadFunc) { var XHR = new XMLHttpRequest(); // Liez l'objet FormData et l'élément form diff --git a/src/main/webapp/ressources/script/modules/requests/uiRequest.js b/src/main/webapp/ressources/script/modules/requests/uiRequest.js index dc2f615..e51ff4a 100644 --- a/src/main/webapp/ressources/script/modules/requests/uiRequest.js +++ b/src/main/webapp/ressources/script/modules/requests/uiRequest.js @@ -57,37 +57,41 @@ export function exportAndClose(fileName){ } //Ouvre un onglet dans le panneau de contenur d'objet (le crée si non déjà existant) -export function openResqmlObjectContent( uuid, +export function openResqmlObjectContent( uuid, idTabHeader, idTabContainer, idConsoleElt, - classObjectContent, classObjectProperty){ + classObjectContent, classObjectProperty, endpoint="ResqmlObjectTree"){ + /*ObjectRelsTree*/ + //console.log('openTab ' + uuid); if(beginTask(true)){ - if(!openTabulation(uuid, idTabHeader)){ // Si la tabulation existe on n'en re-crée pas une + if(endpoint=="ObjectRelsTree" || !openTabulation(uuid, idTabHeader)){ // Si la tabulation existe on n'en re-crée pas une var xmlHttp = new XMLHttpRequest(); - getJsonObjectFromServer("ResqmlObjectTree?uuid=" + uuid).then(function(parsedJSON){ + getJsonObjectFromServer(endpoint + "?uuid=" + uuid).then(function(parsedJSON){ + var id_suffix = endpoint == "ObjectRelsTree" ? "-rels" : ""; + + //console.log(parsedJSON); if(parsedJSON != null){ var objectProperty = document.createElement("div"); - objectProperty.id = genObjectPropertyElementId(uuid); + objectProperty.id = genObjectPropertyElementId(uuid) + id_suffix; objectProperty.className = classObjectProperty; // ---------- var resqmlElt = new ResqmlElement(parsedJSON, uuid, objectProperty); var content = resqmlElt.createView(); // ---------- - - content.id = genObjectContentElementId(uuid); + content.id = genObjectContentElementId(uuid) + id_suffix; content.className += " " + classObjectContent; var divObjectContent = document.createElement("div"); divObjectContent.style.height = "100%"; divObjectContent.style.width = "100%"; divObjectContent.style.padding= "0px"; - divObjectContent.id= genObjectContentDivElementId(); + divObjectContent.id= genObjectContentDivElementId() + id_suffix; var butExpandObject = document.createElement("span"); butExpandObject.title = "Expand tree"; butExpandObject.className += " treeExpander fas fa-angle-double-down"; - butExpandObject.id = "but_Expand_" + uuid; + butExpandObject.id = "but_Expand_" + uuid + id_suffix; divObjectContent.appendChild(butExpandObject); butExpandObject.onclick = function(){ @@ -102,7 +106,7 @@ export function openResqmlObjectContent( uuid, var butCollapseObject = document.createElement("span"); butCollapseObject.title = "Collapse tree"; butCollapseObject.className += " treeExpander fas fa-angle-double-up"; - butCollapseObject.id = "but_Collapse_" + uuid; + butCollapseObject.id = "but_Collapse_" + uuid + id_suffix; divObjectContent.appendChild(butCollapseObject); butCollapseObject.onclick = function(){ @@ -121,7 +125,7 @@ export function openResqmlObjectContent( uuid, var butValidateObject = document.createElement("button"); butValidateObject.appendChild(document.createTextNode("Validate")); butValidateObject.className += " btn btn-outline-dark objButtonAction"; - butValidateObject.id = "but_Validate_" + uuid; + butValidateObject.id = "but_Validate_" + uuid + id_suffix; divBtnGrp.appendChild(butValidateObject); butValidateObject.onclick = function(){ @@ -131,7 +135,7 @@ export function openResqmlObjectContent( uuid, var butRefresh = document.createElement("button"); butRefresh.appendChild(document.createTextNode("Refresh")); butRefresh.className += " btn btn-outline-dark objButtonAction"; - butRefresh.id = "but_AutoCorrect_" + uuid; + butRefresh.id = "but_AutoCorrect_" + uuid + id_suffix; divBtnGrp.appendChild(butRefresh); butRefresh.onclick = function(){ @@ -154,7 +158,7 @@ export function openResqmlObjectContent( uuid, butPrint_Json.appendChild(document.createTextNode("Json")); butPrint_Json.title = "Google Gson translation"; butPrint_Json.className += " btn btn-outline-success objButtonAction"; - butPrint_Json.id = "but_Print_Json_" + uuid; + butPrint_Json.id = "but_Print_Json_" + uuid + id_suffix; divBtnGrp.appendChild(butPrint_Json); butPrint_Json.onclick = function(){ @@ -164,7 +168,7 @@ export function openResqmlObjectContent( uuid, var butPrintDownloadJSON = document.createElement("button"); butPrintDownloadJSON.appendChild(document.createTextNode("Download JSON")); butPrintDownloadJSON.className += " btn btn-outline-success objButtonAction"; - butPrintDownloadJSON.id = "but_Download_json_" + uuid; + butPrintDownloadJSON.id = "but_Download_json_" + uuid + id_suffix; divBtnGrp.appendChild(butPrintDownloadJSON); butPrintDownloadJSON.onclick = function(){ @@ -174,7 +178,7 @@ export function openResqmlObjectContent( uuid, /*var butPrintXml = document.createElement("button"); butPrintXml.appendChild(document.createTextNode("Xml")); butPrintXml.className += " btn btn-outline-success objButtonAction"; - butPrintXml.id = "but_Print_xml_" + uuid; + butPrintXml.id = "but_Print_xml_" + uuid + id_suffix; divBtnGrp.appendChild(butPrintXml); butPrintXml.onclick = function(){ @@ -184,7 +188,7 @@ export function openResqmlObjectContent( uuid, var butRawEditXml = document.createElement("button"); butRawEditXml.appendChild(document.createTextNode("Edit raw XML")); butRawEditXml.className += " btn btn-outline-info objButtonAction"; - butRawEditXml.id = "butRawEditXml_" + uuid; + butRawEditXml.id = "butRawEditXml_" + uuid + id_suffix; divBtnGrp.appendChild(butRawEditXml); butRawEditXml.onclick = function(){ @@ -194,7 +198,7 @@ export function openResqmlObjectContent( uuid, var butPrintDownloadXML = document.createElement("button"); butPrintDownloadXML.appendChild(document.createTextNode("Download XML")); butPrintDownloadXML.className += " btn btn-outline-success objButtonAction"; - butPrintDownloadXML.id = "but_Download_xml_" + uuid; + butPrintDownloadXML.id = "but_Download_xml_" + uuid + id_suffix; divBtnGrp.appendChild(butPrintDownloadXML); butPrintDownloadXML.onclick = function(){ @@ -204,7 +208,7 @@ export function openResqmlObjectContent( uuid, var butAutoCorrect = document.createElement("button"); butAutoCorrect.appendChild(document.createTextNode("Auto-correct")); butAutoCorrect.className += " btn btn-outline-info objButtonAction"; - butAutoCorrect.id = "but_AutoCorrect_" + uuid; + butAutoCorrect.id = "but_AutoCorrect_" + uuid + id_suffix; divBtnGrp.appendChild(butAutoCorrect); butAutoCorrect.onclick = function(){ @@ -214,7 +218,7 @@ export function openResqmlObjectContent( uuid, var butClone = document.createElement("button"); butClone.appendChild(document.createTextNode("Clone")); butClone.className += " btn btn-outline-success objButtonAction"; - butClone.id = "but_Clone_" + uuid; + butClone.id = "but_Clone_" + uuid + id_suffix; butClone.title = "Clone this object to create a copy with an other uuid. The copy's title contains the original object uuid."; divBtnGrp.appendChild(butClone); @@ -230,6 +234,21 @@ export function openResqmlObjectContent( uuid, // formObjectModification.appendChild(formValidator); // on le met avant le form pour bypass la valdiation de form divBtnGrp.appendChild(formValidator); + /*if(endpoint=="ResqmlObjectTree"){ + // Root additional rels + var formOpenRels = document.createElement("input"); + formOpenRels.type = "submit"; + formOpenRels.value = "Rels"; + formOpenRels.className += "tabulationSave btn btn-outline-info objButtonAction"; + divBtnGrp.appendChild(formOpenRels); + + formOpenRels.onclick = function(){ + openResqmlObjectContent(uuid, + idTabHeader, idTabContainer, idConsoleElt, + classObjectContent, classObjectProperty, endpoint="ObjectRelsTree") + }; + }*/ + /// AJOUTER * madatory element var mandatoryLabel = document.createElement("span");