diff --git a/.classpath b/.classpath
index 08850775..12a87fb0 100644
--- a/.classpath
+++ b/.classpath
@@ -4,7 +4,8 @@
-
+
+
@@ -20,7 +21,6 @@
-
@@ -71,10 +71,9 @@
-
+
-
diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml
new file mode 100644
index 00000000..8c0539ae
--- /dev/null
+++ b/.github/workflows/gradle.yml
@@ -0,0 +1,31 @@
+# This workflow will build a Java project with Gradle
+
+name: Java CI with Gradle
+
+# Triggers the workflow on push events (on every branch)
+on:
+ push:
+ branches:
+ - '*'
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout Code
+ uses: actions/checkout@v2
+
+ - name: Set up JDK 17
+ uses: actions/setup-java@v1
+ with:
+ java-version: 17
+
+ - name: Set up Arangodb
+ uses: xinova/arangodb-action@v1
+ with:
+ arangodb version: 'latest' # See https://hub.docker.com/_/arangodb for available versions
+
+ - name: Grant execute permission for gradlew
+ run: chmod +x gradlew
+
+ - name: Build WebOCD Service
+ run: ./gradlew build
\ No newline at end of file
diff --git a/.project b/.project
index eff6925b..7f273d7a 100644
--- a/.project
+++ b/.project
@@ -20,4 +20,15 @@
org.eclipse.jdt.core.javanature
org.eclipse.buildship.core.gradleprojectnature
+
+
+ 1643825602746
+
+ 30
+
+ org.eclipse.core.resources.regexFilterMatcher
+ node_modules|.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__
+
+
+
diff --git a/Dockerfile b/Dockerfile
index 24e966c7..1d46f6f2 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,4 +1,4 @@
-FROM openjdk:14-alpine
+FROM openjdk:17-alpine
COPY . /usr/src/webocd
WORKDIR /usr/src/webocd
RUN apk update && apk add bash \
@@ -8,8 +8,22 @@ RUN apk update && apk add bash \
ghostscript-fonts \
build-base
# Fetch fitting gradle version manually because so far no os container has both jdk14 and a high enough gradle package version
-RUN mkdir ../gradleFolder && wget https://services.gradle.org/distributions/gradle-6.8.3-bin.zip -P ../gradleFolder \
- && unzip -d ../gradleFolder ../gradleFolder/gradle-6.8.3-bin.zip && rm -R ../gradleFolder/gradle-6.8.3-bin.zip
-RUN ../gradleFolder/gradle-6.8.3/bin/gradle build
+RUN mkdir ../gradleFolder && wget https://services.gradle.org/distributions/gradle-7.3.2-bin.zip -P ../gradleFolder \
+ && unzip -d ../gradleFolder ../gradleFolder/gradle-7.3.2-bin.zip && rm -R ../gradleFolder/gradle-7.3.2-bin.zip
+
+# Replace HOST for database configuration (standard & for testing) with the db container name
+RUN sed -i "s/^HOST.*/HOST=arangodb/" ocd/arangoDB/config_test.properties
+RUN sed -i "s/^HOST.*/HOST=arangodb/" ocd/arangoDB/standard_config.properties
+
+
+# This is to clean the previously generated agents and avoid error in case WebOCD was built before image creation
+RUN ../gradleFolder/gradle-7.3.2/bin/gradle clean
+
+# Execute gradle build and tests excluding db tests
+RUN ../gradleFolder/gradle-7.3.2/bin/gradle build -x test
+RUN ../gradleFolder/gradle-7.3.2/bin/gradle testWithoutDB
+
+# Add a loop that waits for arangodb to run, before webocd service starts when start_network.sh is used
+RUN sed -i '2 i while ! nc -z arangodb 8529; do sleep 10; done' bin/start_network.sh
RUN chmod +x bin/start_network.sh
-CMD ["bin/start_network.sh"]
+CMD ["bin/start_network.sh"]
\ No newline at end of file
diff --git a/README.md b/README.md
index 98ee89c8..5ba9bea3 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
# OCD Service - WebOCD
-This is a RESTful web service offering various overlapping community detection algorithms(OCDA) and centrality measures/simulations. The service is developed with the Eclipse IDE and IntelliJ, so we recommend you to use one of these tools to work on the project.
+This is a RESTful web service offering various overlapping community detection algorithms(OCDA) and centrality measures/simulations. The service is developed with the IntelliJ IDE, so we recommend you to use this tool to work on the project.
**WebOCD works best with its corresponding [web client](https://github.com/rwth-acis/OCD-Web-Client)**.
A running instance of WebOCD can be found at http://webocd.dbis.rwth-aachen.de/OCDWebClient/.
@@ -9,3 +9,20 @@ For any information on the service itself please refer to the [project wiki](htt
### Additional Notes
This service is based on the LAS2peer Template Project and its underlying LAS2peer framework. For any information on these please refer to https://github.com/rwth-acis/LAS2peer-Template-Project and https://github.com/rwth-acis/LAS2peer
+
+# Building & Running WebOCD Service
+
+WebOCD Service requires a running arangodb instance, which has to be [installed separately](https://www.arangodb.com/docs/stable/installation.html). In order for WebOCD to access the database, the configuration files, located under [ocd/arangoDB](/ocd/arangoDB) should be adjusted accordingly.
+
+The service can be built using the gradle build task. Afterwards, it can be run using start_network.sh/start_network.bat scripts located in the [bin](/bin) directory (Consider changing the java heap size in the file with the ```-Xmx``` parameter to avoid storage allocation issues).
+
+Alternatively, Docker can be used, as explained below, to run the WebOCD service and database in one line.
+
+# Quickstart Docker
+To build and run WebOCD Service using Docker, you can navigate to the REST-OCD-Service directory and execute
+```
+docker compose up
+```
+This will build and run containers for WebOCD service and arangodb, which is required for the service to run properly.
+
+You can adjust the database container default password by modifying docker-compose.yml. Keep in mind to also change the config file [config.properties](ocd/arangoDB/config.properties), so that WebOCD tests as well as the service can use the database.
\ No newline at end of file
diff --git a/docker-compose.yml b/docker-compose.yml
new file mode 100644
index 00000000..72a7a501
--- /dev/null
+++ b/docker-compose.yml
@@ -0,0 +1,23 @@
+version: '3'
+services:
+ arangodb:
+ image: arangodb
+ container_name: webocd-arangodb
+ ports:
+ - "127.0.0.1:8529:8529"
+ environment:
+ - ARANGO_ROOT_PASSWORD=password
+ webocd-service:
+ container_name: webocd-service
+ stdin_open: true # docker run -i
+ tty: true # docker run -t
+ restart: on-failure
+ depends_on:
+ - arangodb
+ build:
+ context: .
+ dockerfile: ./Dockerfile
+ links:
+ - arangodb
+ ports:
+ - "127.0.0.1:8080:8080"
\ No newline at end of file
diff --git a/docs/pages/index.md b/docs/pages/index.md
index 555a8103..ce6c1e12 100644
--- a/docs/pages/index.md
+++ b/docs/pages/index.md
@@ -28,10 +28,10 @@ The OCD Service is publicly accessible via this [link](http://webocd.dbis.rwth-a
Along with the service we provide a web client which also has its own [project](https://github.com/rwth-acis/OCD-Web-Client). The client can only be used with a valid Learning Layers account. We recommend to use the service along with the web client.
-We additionally provide a brief [Integration Tutorial](/integration/) that shows you the usage of the most important requests so that you can get started with the OCD Service more quickly.
+We additionally provide a brief [Integration Tutorial](/REST-OCD-Services/pages/wiki/integration/) that shows you the usage of the most important requests so that you can get started with the OCD Service more quickly. A more detailed usage examples of WebOCD Service, using the WebOCD webclient can be found here [link](/REST-OCD-Services/pages/tutorials/login).
## The OCD Service
-The service is developed using the Eclipse IDE, so we recommend you to stick to that tool for any work on this project.
+The service is developed using the IntelliJ IDEA, so we recommend you to stick to that tool for any work on this project.
Please refer to the following pages in order to obtain more information about the OCD Service.
@@ -41,9 +41,10 @@ Please refer to the following pages in order to obtain more information about th
+ [User Management and Authentication](/REST-OCD-Services/pages/wiki/user-management-and-authentication)
+ [Deploying the OCD Service](/REST-OCD-Services/pages/wiki/service-deployment)
+ [Database Configuration](/REST-OCD-Services/pages/wiki/database-configuration)
++ [Tutorials using WebOCD Service and Webclient](/REST-OCD-Services/pages/tutorials/login)
### Important
-The OCD Service is largely based on the commercial **yFiles** library. You will only be able to run it yourself if you have access to the archive _y.jar_. The Chair i5 of RWTH Aachen University has a license for that library. If you are affiliated with that institute, please contact somebody to obtain the library. Also, keep in mind that the archive mentioned above must under no circumstances be publicly deployed or otherwise made publicly available. Please refer to [Deploying the OCD Service](/REST-OCD-Services/pages/wiki/service-deployment) for more information.
+The WebOCD Service uses **ArangoDB** database, which has to be separately installed on the machine where the service runs. Alternatively, docker can be used to build the WebOCD Service together with the database. To build and run WebOCD Service with Docker, refer to [link](/REST-OCD-Services/pages/wiki/running#docker).
-The service also currently requires **Java JDK 14** to be built and most likely also to run it. However, there also exists an older version for JDK 8 (tag [1.0.0](https://github.com/rwth-acis/REST-OCD-Services/tree/1.0.0)) which is still functional in case you need it.
+The service also currently requires **Java JDK 17** to be built and most likely also to run it. However, there also exists an older version for JDK 8 (tag [1.0.0](https://github.com/rwth-acis/REST-OCD-Services/tree/1.0.0)) which is still functional in case you need it.
diff --git a/docs/pages/wiki/build-process.md b/docs/pages/wiki/build-process.md
index 5b031fc3..38733e95 100644
--- a/docs/pages/wiki/build-process.md
+++ b/docs/pages/wiki/build-process.md
@@ -4,59 +4,27 @@ title: Build Process
---
# Introduction
-The OCD Service is built via Gradle. We recommend a version similar to 6.8, yet others may also work. The project has mostly been developed with the Eclipse IDE using the gradle buildship plugin (most eclipse IDEs already include this), yet IDEs like IntelliJ are actively used as well. Finally note that you will likely need Java version 14 for the build to work without problems.
-
-There also exists an older version using Apache Ant which is described at the bottom. Here, there are two build files, _build.xml_, and _ocd_build.xml_. Please do only use the _ocd_build.xml_. Note that Eclipse might illustrate errors for the build file because apparently it is not able to resolve the external target dependencies to the second build file correctly. This should not cause an issue. It is highly recommended that you build the project with Eclipse (To use Java 8 for the older version you may have to go with the Eclipse IDE for Java EE Developers variant) as this is the environment used during development and therefore the best tested one.
+The OCD Service is built via Gradle. We recommend a version similar to 7.3, yet newer versions may also work. The project has mostly been developed with the IntelliJ IDEA. You can import the project into IntelliJ as a Gradle project. Finally note that you will likely need Java version 17 for the build to work without problems.
# Executing the Build Process
## First Build
-When you are going to run the build process the very first time, you will need two manually obtain two libraries:
-+ _y.jar_ forms part of the commercial yFiles library by yWorks which is not publicly available. Therefore you will have to add it manually to the project. The Chair i5 of RWTH Aachen University has a license for the library, so please contact somebody to obtain access. This will obviously only be possible if you are somehow affiliated with the Chair.
-+ _ysvg.jar_ is an SVG writer for yFiles Graph2D objects that makes it possible to add useful features to generated SVG diagrams. The library is used for the visualization of graphs and covers.
-Both libraries then have to be placed into the _yFiles_ folder.
-
-Now, you just have to import the project as a gradle project via eclipse or simply open in via IntelliJ. After the first build, eclipse might still give you errors saying the yFiles jars are missing. To fix this, simply refresh the gradle project via the option you get from right clicking the folder.
+When you are going to run the build process the very first time, you just have to import the project as a gradle project IntelliJ and execute the gradle *build* task. Make sure to adapt the database configuration _ocd/arangoDB/config.properties_ to fit your running ArangoDB instance.
After the build, you can then either start the _start_network.bat_ or _start_network.sh_ files in the bin folder to get the service running, see [Running the OCD Service](/REST-OCD-Services/pages/wiki/running) for more information.
## General Build
-There are numerous targets which can be run. This summarizes the most important ones:
+There are numerous gradle tasks which can be executed. This summarizes the most important ones:
+ _jar_: Generates the service jar in the _service_ and a copy in the _rest\_ocd\_services/export/jars_ directory. This archive is required for running the service.
+ _test_: Runs all jUnit tests . The test reports are stored in _rest\_ocd\_services/export/test_reports_.
-+ _yguard_: Generates an obfuscated service jar in the _rest\_ocd\_services/export/obfuscated_ directory. This is required for public service deployment. Please refer to [Deploying the OCD Service](/REST-OCD-Services/pages/wiki/service-deployment) for more information. A log file of the obfuscation process is stored under _ocd/yGuard/log.xml_.
+ _build_: The target you'll likely be running most of the time. This executes the build process and generates a jar as well as the executables.
++ _startscripts:_ Generates startscripts into the bin folder that are used to start the service.
++ _generateAgents_: Generates the user and service agents as specified in _build.gradle_. The users will be loaded when the service (or more precisely the underlying LAS2peer node) is launched.
++ _clean_: Clean up files generated from the build. This should be executed before rebuilding.
-# Potential Issues
-
-Currently, the build might fail if a version of Java not equal to 14 (or 8 for the older version of the service) is used, even with eclipse in compliance mode for that version, and running the service with a version other than this one is also likely to cause errors.
-
-## Linux Users
-The system was mainly tested on Windows so far. For Linux, there is still a small issue with the old Ant Build. In case you receive an exception that the database (_db_) could not be created, please do manually remove the directory _db_ from the _ocd_ directory before the build.
-
-
-# Executing the Old Ant Build Process
-
-## First Build
-When you are going to run the build process the very first time, please make sure to run the target _get_deps_ in order to obtain all dependencies.
-
-Due to the yFiles library being commercial, there are three dependencies which will be missing and must be added manually to the _lib_ folder:
-+ _y.jar_ forms part of the commercial yFiles library by yWorks which is not publicly available. Therefore you will have to add it manually to the project. The Chair i5 of RWTH Aachen University has a license for the library, so please contact somebody to obtain access. This will obviously only be possible if you are somehow affiliated with the Chair.
-+ _yguard.jar_ is a free obfuscation tool by yWorks which is only required for public deployment of the service. Anybody can download it from this [link](https://www.yworks.com/downloads#yGuard). Refer to [Deploying the OCD Service](/REST-OCD-Services/pages/wiki/service-deployment) for more information. You can probably do without it.
-+ _ysvg.jar_ is an SVG writer for yFiles Graph2D objects that makes it possible to add useful features to generated SVG diagrams. The library is used for the visualization of graphs and covers.
-## Linux Users
-Please make sure that the program _ocd/lfr/LfrBenchmarkLinux_ is executable (via `chmod +x `).
+# Potential Issues
+Currently, the build might fail if a version of Java not equal to 17 is used.
-## General Build
-There are numerous targets which can be run. This summarizes the most important ones:
-+ _jar_: Generates the service jar in the _service_ and a copy in the _export/jars_ directory. This archive is required for running the service.
-+ _generate_configs_: Generates the user and service agents as specified in _etc/ant_configuration_. The users will be loaded when the service (or more precisely the underlying LAS2peer node) is launched.
-+ _junit_: Runs all jUnit tests (except _src/test/i5/las2peer/services/ocd/DatabaseInitializer.java_, take look at the target _setup_database_ for more information). The test reports are stored in _export/test_reports_.
-+ _startscripts:_ Generates startscripts into the bin folder that are used to start the service.
-+ _obfuscate_: Generates an obfuscated service jar in the _export/obfuscated_ directory. This is required for public service deployment. Please refer to [Deploying the OCD Service](/REST-OCD-Services/pages/wiki/service-deployment) for more information. A log file of the obfuscation process is stored under _ocd/yGuard/log.xml_.
-+ _setup_database_: This is intended for automatically populating the database for presentation or debugging purposes. It is not required in any way to actually make the database work. The database is set up by running _src/test/i5/las2peer/services/ocd/DatabaseInitializer.java_ as a jUnit test. You can adapt the code in any way that suits your needs.
-+ _all_: Runs all of the above except _setup_database_.
+Running WebOCD Service might cause *AgentAccessDeniedException* if the *build* task was performed multiple times without having performed the *clean* task inbetween. If this occurs, simply do the *clean* task followed by the *build* task and the issue should be solved.
-## Building with IntelliJ
-For IntelliJ, you can follow the above guide as well. For correct indexing in the IDE you however need to add the lib folder as a library via right click. You might also want to double check that build.xml isn't selected as an ant build file instead of ocd_build.xml
diff --git a/docs/pages/wiki/database-configuration.md b/docs/pages/wiki/database-configuration.md
index 8607f2c5..8e16a67c 100644
--- a/docs/pages/wiki/database-configuration.md
+++ b/docs/pages/wiki/database-configuration.md
@@ -3,11 +3,8 @@ layout: page
title: Database Configurations
---
-# JPA and persistence.xml
-The service makes use of the Java Persistence API (JPA) specification to simplify database access. The JPA implementation that is being used is EclipseLink. If you want to use the service with another database or change some aspects of the database configuration you must adapt the following files accordingly.
-+ _rest\_ocd\_services/src/main/java/META-INF/persistence.xml_: This database configuration is used for the actual execution of the service through the service jar (e.g. when running _bin/start_network.bat_)
-+ _rest\_ocd\_services/src/main/java/META-INF/testing/persistence.xml_: This database configuration is used during jUnit testing.
+# ArangoDB
+The service makes use of ArangoDB database. A database instance should be running before executing the build process. Otherwise, the database related tests will fail.
+Database instance details that WebOCD Service uses can be configured by changing the _ocd/arangoDB/config.properties_ file.
-The file locations are different in the old ant build:
-+ _ocd/eclipselink/persistence.xml_ for the execution
-+ _src/META-INF/persistence.xml_ for testing
\ No newline at end of file
+If the database is not available on the machine where WebOCD Service should run, it is possible to use Docker, without installing/running the database first. For this refer to [Running the OCD Service](/REST-OCD-Services/pages/wiki/running#docker).
diff --git a/docs/pages/wiki/integration.md b/docs/pages/wiki/integration.md
index f52dade5..8fd3f4e6 100644
--- a/docs/pages/wiki/integration.md
+++ b/docs/pages/wiki/integration.md
@@ -4,13 +4,15 @@ title: Integration
---
# Introduction
-This tutorial will give you a brief explanation about how to handle the OCD Service. It explains a few basic requests for e.g. uploading a graph, retrieving the saved graphs, creating a cover from a graph, ...
+This tutorial will give you a brief explanation about how to handle the OCD Service. It explains a few basic requests for e.g. uploading a graph, retrieving the saved graphs, creating a cover from a graph etc.
-However this is only a fraction of what the service actually allows. Other functionalities include for instance the execution of metrics to determine the quality of the calculated covers or the computation of benchmark graphs and covers for the generation of standardized testing data.
+However, this is only a fraction of what the service actually allows. Other functionalities include for instance the execution of metrics to determine the quality of the calculated covers or the computation of benchmark graphs and covers for the generation of standardized testing data.
At the bottom, an overview of all possible requests is given. For a more detailed description of the requests you should refer to the OCD Service's source code.
All responses other than actual graph and cover data (which has the specified output format), as well as JSON visualization data are sent in XML format.
+For more detailed information about using WebOCD Service, refer to the [tutorials](/REST-OCD-Services/pages/tutorials/login), which explains usage of WebOCD Service with the [WebClient](https://github.com/rwth-acis/OCD-Web-Client)
+
# Graphs
## List Available Graphs
@@ -115,7 +117,7 @@ After that, make a post request to run the algorithm with the following paramete
+ _name_: Email_Cover
+ _algorithm_: _SPEAKER_LISTENER_LABEL_PROPAGATION_ALGORITHM_
+ _body_: ``
-`memorySize100probabilityThreshold0.15`
+ `memorySize100probabilityThreshold0.15`
+ _contentWeighting_: false
+ _componentNodeCountFilter_: 0
diff --git a/docs/pages/wiki/project-structure.md b/docs/pages/wiki/project-structure.md
index 020df142..cc7096e9 100644
--- a/docs/pages/wiki/project-structure.md
+++ b/docs/pages/wiki/project-structure.md
@@ -7,19 +7,18 @@ title: Project Structure
This page gives you an overview over the file structure of the OCD Service Project. The focus will be set on the _ocd_ directory where most service specific files are located (aside from the source code). Some other files will be discussed as well. For more information on the remaining files you may refer to the LAS2peer Template Project or LAS2peer documentation.
# Source Code
-The actual source code of the service is located under _rest\_ocd\_services/src/main/java_. The most important class here is probably the _i5/las2peer/services/ocd/ServiceClass.java_ which contains the entire Service API. You will also find the _META-INF_ directory with the persistence.xml files. For more information on this aspect take a look at [Database Configuration](/REST-OCD-Services/pages/wiki/database-configuration).
+The actual source code of the service is located under _rest\_ocd\_services/src/main/java_. The most important class here is probably the _i5/las2peer/services/ocd/ServiceClass.java_ which contains the entire Service API.
-The source code for the jUnit tests is in _rest\_ocd\_services/src/test_. This directory includes also the _src/test/i5/las2peer/services/ocd/DatabaseInitializer.java_ which can be used for database initialisation. For more information please refer to [Build Process](/REST-OCD-Services/pages/wiki/build-process).
+The source code for the jUnit tests is in _rest\_ocd\_services/src/test_.
+
+ArangoDB database configuration file *config.properties* is located in *ocd/arangoDB* directory. This file can be modified to adjust database used for WebOCD Service as well as tests. For more information please refer to [Build Process](/REST-OCD-Services/pages/wiki/database-configuration).
# OCD Directory
The _ocd_ directory contains most files apart from the source code which are specific to the OCD Service. You will find the following subdirectories.
-+ _db_: Contains the database of the JPA provider.
++ _arangoDB_: Contains the database configuration file.
+ _eclipselink_: Any log files for database creation or dropping created by the EclipseLink JPA persitence provider will be stored here.
-+ _lfr_: Provides an application from Lancichinetti for calculating the LFR benchmarks he introduced (for directed and weighted graphs). It is compiled once for each Linux and Windows.
+ _test_: Contains a folder with data files for jUnit test input. An additional folder for test output files may be created during the build.
-+ _yGuard_: Any log files of the obfuscation process will be stored here. Please refer to [Deploying the OCD Service](Deploying the OCD Service) for more information.
-+ (_ivy_ if using the old ant build: Contains an _ocd_ivy.xml_ file to load the service's dependencies via Ivy. Note that there is an additional _ivy.xml_ and _ivy.settings_ file for dependencies required by LAS2peer under _etc/ivy_ from the root directory.)
# Other Important Resources
+ _bin_: Comprises scripts for launching the service and generating Agents.
@@ -27,6 +26,3 @@ The _ocd_ directory contains most files apart from the source code which are spe
+ _service_: This directory contains the service jar. Please refer to [Build Process](/REST-OCD-Services/pages/wiki/build-process) for more information.
+ _bin/start_network.bat_ and _bin/start_network.sh_: Skripts for launching the OCD Service. Please refer to [Running the OCD Service](/REST-OCD-Services/pages/wiki/running) for more information.
+ _etc/startup/passphrases.txt_: Password storage for preinstalled users. Please refer to [User Management and Authentication](/REST-OCD-Services/pages/wiki/user-management-and-authentication) for more information.
-+ (_ocd_build.xml_ if using the old ant build: The build file for the OCD Service. Please do only make use of this build file. Please refer to [Build Process](/REST-OCD-Services/pages/wiki/build-process) for more information.)
-+ (_ocd.conf_ if using the old ant build: Upstart script for the OCD Service. Please refer to [Deploying the OCD Service](/REST-OCD-Services/pages/wiki/service-deployment) for more information.)
-+ (_etc/ant_configuration/user.properties_ if using the old ant build: Ant property file for user agent generation. Please refer to [User Management and Authentication](/REST-OCD-Services/pages/wiki/user-management-and-authentication) for more information.)
\ No newline at end of file
diff --git a/docs/pages/wiki/running.md b/docs/pages/wiki/running.md
index b105fe31..6408fd35 100644
--- a/docs/pages/wiki/running.md
+++ b/docs/pages/wiki/running.md
@@ -11,12 +11,20 @@ Before you start the service you might want to configure the _start_network.bat_
Use `chmod +x ` to allow the execution of the scripts.
# Running the Service
-Once the database is accessible, you can launch the service on a single node LAS2peer network with the scripts _start_network.bat_ or _start_network.sh_ which are located in the _bin_ directory. The service should be running within a few seconds and be available as a REST service under the basepath _`http://127.0.0.1:8080/ocd/`_ (Note that your browser will display a 404 if you type in this adress, to see if the service is running check the address without the _`/ocd`_ part instead). You can terminate the process by either typing _exit_ in the interactive console or of course also by any other common means.
+Once the arangoDB instance is accessible, you can launch the service on a single node LAS2peer network with the scripts _start_network.bat_ or _start_network.sh_ which are located in the _bin_ directory. The service should be running within a few seconds and be available as a REST service under the basepath _`http://127.0.0.1:8080/ocd/`_ (Note that your browser will display a 404 if you type in this address, to see if the service is running check the address without the _`/ocd`_ part instead). You can terminate the process by either typing _exit_ in the interactive console or of course also by any other common means.
It is recommended that you use the OCD Service in combination with the web client at https://github.com/rwth-acis/OCD-Web-Client, which will take care of formulating the right requests and especially the login process for you as well as provide JSON visualization.
+# Docker
+To build and run WebOCD Service using Docker, you can navigate to the REST-OCD-Service directory and execute
+```
+docker compose up
+```
+This will build and run containers for WebOCD service and ArangoDB database, which is required for the service to run properly.
+
+You can adjust the database container default password by modifying *docker-compose.yml*. Keep in mind to also change the config file *ocd/arangoDB/config.properties*, so that WebOCD tests as well as the service can use the database.
# Potential Issues
-Your service might run into the _java.lang.outOfMemoryError_, this indicates that the heap size of the program is most likely to small. You can increase the maximum size by adding the -Xmx parameter in the _start_network_ files. For information on how to use it, please refer to the official Documentation [here](https://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/jrdocs/refman/optionX.html).
+Your service might run into the _java.lang.outOfMemoryError_, this indicates that the heap size of the program is most likely to small. You can increase the maximum size by adding the -Xmx parameter in the _start_network_ files. For information on how to use it, please refer to the official Documentation (https://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/jrdocs/refman/optionX.html)
If you are getting a warning about encryption problems then you most likely have to change the Security Policy Files of your JRE. This can also happen after a JRE update. Please refer to the Las2Peer Template Project for more information.
\ No newline at end of file
diff --git a/docs/pages/wiki/service-deployment.md b/docs/pages/wiki/service-deployment.md
index 435cd0fb..6050e9bb 100644
--- a/docs/pages/wiki/service-deployment.md
+++ b/docs/pages/wiki/service-deployment.md
@@ -4,10 +4,7 @@ title: Service Deployment
---
# Building
-If you want to deploy the OCD Service to a server, the service must first be build. There are two basic alternatives. Either you directly build the project on the machine where it should be deployed, or you build it on some other machine and then move the files to their designated location. You will have to execute the _jar_ target in order to create the service jar. Please refer to [Build Process](Build Process) for more information. Make sure you also generate the user agents for any required user accounts through the target by altering the gradle build file accordingly and running the _jar_ target, if needed.
-
-# Public Deployment: Obfuscation
-The OCD Service makes heavy use of the archive _y.jar_ which is part of the commercial yFiles framework by yWorks. The Chair i5 of RWTH Aachen University has a license allowing the usage of this software. However, it is not allowed to make this library publicly accessible to others. Therefore, if you intend to deploy the OCD Service on a public machine (accessible to people which are not affiliated with the chair) you must obfuscate that library. For this purpose you will require the archive _yguard.jar_ which is offered for free by yWorks. The _yguard_ target will help you with the obfuscation. Please refer to [Build Process](Build Process) for more information. For the obfuscation requirements concerning yFiles and more information on yGuard please refer to the corresponding documentation by yWorks. Also make sure that the yGuard log file under _ocd/yGuard/log.xml_ is not being deployed.
+If you want to deploy the OCD Service to a server, the service must first be build. There are two basic alternatives. Either you directly build the project on the machine where it should be deployed, or you build it on some other machine and then move the files to their designated location. You will have to execute the _jar_ target in order to create the service jar. Please refer to [Build Process](/REST-OCD-Services/pages/wiki/build-process) for more information. Make sure you also generate the user agents for any required user accounts through the target by altering the gradle build file accordingly and running the _jar_ target, if needed.
# Additional Aspects
There are a few additional aspects that should be taken under consideration. First of all, there are several project folders which do not need to be deployed. After completing the build, only the following resources are relevant for the service execution, any others may be removed.
@@ -23,8 +20,7 @@ There are a few additional aspects that should be taken under consideration. Fir
+ README.md
+ (ocd.conf in the old and build)
-Please keep in mind again that in the case of a public deployment the yGuard log file must not be deployed.
-Also, when deploying on a Linux system, make sure with `chmod +x ` that the execution of all relevant scripts and programs is allowed. Besides the scripts to launch the service and the database this includes also the LFR Benchmark Application. Please refer to [Project Structure](Project Structure) for more information.
+Also, when deploying on a Linux system, make sure with `chmod +x ` that the execution of all relevant scripts and programs is allowed. Please refer to [Project Structure](/REST-OCD-Services/pages/wiki/project-structure/) for more information.
Remember also that the Security Policy Files of the JRE being used on the server will in some cases have to be changed, please refer to the LAS2peer Template Project for more information.
\ No newline at end of file
diff --git a/docs/pages/wiki/user-management-and-authentication.md b/docs/pages/wiki/user-management-and-authentication.md
index 69d497e9..1655b3a4 100644
--- a/docs/pages/wiki/user-management-and-authentication.md
+++ b/docs/pages/wiki/user-management-and-authentication.md
@@ -9,7 +9,7 @@ This part deals with manually adding users which should not be necessary if you
# User Management
-You can preinstall up to three users via the Ant build target _generate_configs_. For that purpose the users must be defined in the Ant property file _etc/ant_configuration/user.properties_ and the corresponding password in _etc/startup/passphrases.txt_. For preinstalling more users you will have to adapt the _build.xml_ in the root directory accordingly.
+You can preinstall up to three users via the gradle task _generateAgents_. For that purpose the users must be defined in the *gradle.properties* file.
It is also possible to manually add LAS2peer user agents to an existing network. Please refer to the LAS2peer Template Project and LAS2peer for more information.
diff --git a/etc/userLimitInformation.json b/etc/userLimitInformation.json
new file mode 100644
index 00000000..88fc0edc
--- /dev/null
+++ b/etc/userLimitInformation.json
@@ -0,0 +1,16 @@
+[
+ {
+ "username": "default",
+ "allowedInactiveDays": "30",
+ "graphSize": "1000",
+ "graphCount": "10",
+ "coverCount": "15"
+ },
+ {
+ "username": "user1",
+ "allowedInactiveDays": "5",
+ "graphSize": "1000",
+ "graphCount": "5",
+ "coverCount": "10"
+ }
+]
\ No newline at end of file
diff --git a/gradle.properties b/gradle.properties
index 3c07660e..a78c7581 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -1,8 +1,8 @@
-core.version=1.1.1
+core.version=1.2.2
service.name=i5.las2peer.services.ocd
service.class=ServiceClass
service.version=1.0.0
-java.version=14
+java.version=17
las2peer_user1.name=alice
las2peer_user1.password=pwalice
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index 442d9132..d2880ba8 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.3-bin.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
diff --git a/gradlew b/gradlew
old mode 100644
new mode 100755
diff --git a/ocd/arangoDB/config.properties b/ocd/arangoDB/config.properties
new file mode 100644
index 00000000..f7ecc4ae
--- /dev/null
+++ b/ocd/arangoDB/config.properties
@@ -0,0 +1,6 @@
+PORT=8529
+PASSWORD=password
+DATABASENAME=ocdDB
+TESTDATABASENAME=testDB
+HOST=127.0.0.1
+USER=root
diff --git a/ocd/eclipselink/serviceCreateDDL.jdbc b/ocd/eclipselink/serviceCreateDDL.jdbc
index 3ae4a39b..adce6aa5 100644
--- a/ocd/eclipselink/serviceCreateDDL.jdbc
+++ b/ocd/eclipselink/serviceCreateDDL.jdbc
@@ -1,4 +1,4 @@
-CREATE TABLE SIMULATIONSERIESGROUP (ID BIGINT NOT NULL, COOPERATIVIATY REAL, NAME VARCHAR(255), USERID BIGINT, WEALTH REAL, AVERAGE REAL, DEVIATION REAL, MAXIMUM REAL, MINIMUM REAL, VARIANCE REAL, payoffAverage REAL, payoffdeviation REAL, payoffmaximum REAL, payoffminimum REAL, payoffvariance REAL, graphId BIGINT, username VARCHAR(255), PRIMARY KEY (ID))
+CREATE TABLE SIMULATIONSERIESGROUP (ID BIGINT NOT NULL, COOPERATIVIATY REAL, NAME VARCHAR(255), USERID VARCHAR(255), WEALTH REAL, AVERAGE REAL, DEVIATION REAL, MAXIMUM REAL, MINIMUM REAL, VARIANCE REAL, payoffAverage REAL, payoffdeviation REAL, payoffmaximum REAL, payoffminimum REAL, payoffvariance REAL, graphId BIGINT, username VARCHAR(255), PRIMARY KEY (ID))
CREATE TABLE COVER (ID BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 1 INCREMENT BY 1) NOT NULL, NAME VARCHAR(255), SIMILARITYCOSTS REAL, CREATION_METHOD BIGINT, GRAPH_ID BIGINT NOT NULL, USER_NAME VARCHAR(255) NOT NULL, PRIMARY KEY (ID, GRAPH_ID, USER_NAME))
CREATE TABLE AGENTDATA (ID BIGINT NOT NULL, COOPERATIVITY REAL, FINALPAYOFF REAL, FINALSTRATEGY BOOLEAN, WEALTH REAL, DATASET_ID BIGINT, AGENTDATA_ID BIGINT, PRIMARY KEY (ID))
CREATE TABLE CENTRALITYMAP (ID BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 1 INCREMENT BY 1) NOT NULL, MAP LONGVARBINARY, NAME VARCHAR(255), CREATION_METHOD BIGINT, GRAPH_ID BIGINT NOT NULL, USER_NAME VARCHAR(255) NOT NULL, PRIMARY KEY (ID, GRAPH_ID, USER_NAME))
@@ -6,13 +6,13 @@ CREATE TABLE CUSTOMNODE (INDEX INTEGER GENERATED BY DEFAULT AS IDENTITY (START W
CREATE TABLE CUSTOMGRAPH (ID BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 1 INCREMENT BY 1) NOT NULL, USER_NAME VARCHAR(255) NOT NULL, NAME VARCHAR(255), INDEX_PATH VARCHAR(255), CREATION_METHOD BIGINT, PRIMARY KEY (ID, USER_NAME))
CREATE TABLE COVERCREATIONLOG (ID BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 1 INCREMENT BY 1) NOT NULL, STATUS INTEGER, TYPE INTEGER, PRIMARY KEY (ID))
CREATE TABLE GRAPHCREATIONLOG (ID BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 1 INCREMENT BY 1) NOT NULL, STATUS INTEGER, TYPE INTEGER, PRIMARY KEY (ID))
-CREATE TABLE SIMULATIONSERIES (ID BIGINT NOT NULL, COOPERATIVIATY REAL, GENERATIONS INTEGER, NAME VARCHAR(255), USERID BIGINT, WEALTH REAL, AVERAGE REAL, DEVIATION REAL, MAXIMUM REAL, MINIMUM REAL, VARIANCE REAL, CONDITION VARCHAR(255), DYNAMIC VARCHAR(255), DYNAMICVALUE REAL, GAME VARCHAR(255), graphId BIGINT, GRAPHNAME VARCHAR(255), ITERATIONS INTEGER, MAXITERATIONS INTEGER, MINITERATIONS INTEGER, PAYOFFCC REAL, PAYOFFCD REAL, PAYOFFDC REAL, PAYOFFDD REAL, SIMULATIONNAME VARCHAR(255), THRESHOLD INTEGER, TIMEWINDOW INTEGER, payoffAverage REAL, payoffdeviation REAL, payoffmaximum REAL, payoffminimum REAL, payoffvariance REAL, username VARCHAR(255), PRIMARY KEY (ID))
+CREATE TABLE SIMULATIONSERIES (ID BIGINT NOT NULL, COOPERATIVIATY REAL, GENERATIONS INTEGER, NAME VARCHAR(255), USERID VARCHAR(255), WEALTH REAL, AVERAGE REAL, DEVIATION REAL, MAXIMUM REAL, MINIMUM REAL, VARIANCE REAL, CONDITION VARCHAR(255), DYNAMIC VARCHAR(255), DYNAMICVALUE REAL, GAME VARCHAR(255), graphId BIGINT, GRAPHNAME VARCHAR(255), ITERATIONS INTEGER, MAXITERATIONS INTEGER, MINITERATIONS INTEGER, PAYOFFCC REAL, PAYOFFCD REAL, PAYOFFDC REAL, PAYOFFDD REAL, SIMULATIONNAME VARCHAR(255), THRESHOLD INTEGER, TIMEWINDOW INTEGER, payoffAverage REAL, payoffdeviation REAL, payoffmaximum REAL, payoffminimum REAL, payoffvariance REAL, username VARCHAR(255), PRIMARY KEY (ID))
CREATE TABLE CENTRALITYCREATIONLOG (ID BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 1 INCREMENT BY 1) NOT NULL, CENTRALITY_TYPE INTEGER, CREATION_TYPE INTEGER, EXECUTION_TIME BIGINT, STATUS INTEGER, PRIMARY KEY (ID))
CREATE TABLE COMMUNITY (ID BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 1 INCREMENT BY 1) NOT NULL, COLOR INTEGER, NAME VARCHAR(255), GRAPH_ID BIGINT NOT NULL, USER_NAME VARCHAR(255) NOT NULL, COVER_ID BIGINT NOT NULL, PRIMARY KEY (ID, GRAPH_ID, USER_NAME, COVER_ID))
CREATE TABLE GROUPPARAMETERS (DYNAMIC VARCHAR(255), GAME VARCHAR(255), GRAPHID BIGINT, SCALING INTEGER, SIMULATIONS_ID BIGINT NOT NULL, PRIMARY KEY (SIMULATIONS_ID))
CREATE TABLE CUSTOMEDGE (ID INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 1 INCREMENT BY 1) NOT NULL, WEIGHT REAL, GRAPH_ID BIGINT NOT NULL, USER_NAME VARCHAR(255) NOT NULL, SOURCE_INDEX INTEGER, TARGET_INDEX INTEGER, RUNTIME_ID INTEGER, PRIMARY KEY (ID, GRAPH_ID, USER_NAME))
CREATE TABLE OCDMETRICLOG (ID BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 1 INCREMENT BY 1) NOT NULL, STATUS INTEGER, TYPE INTEGER, VALUE REAL, GRAPH_ID BIGINT NOT NULL, USER_NAME VARCHAR(255) NOT NULL, COVER_ID BIGINT NOT NULL, PRIMARY KEY (ID, GRAPH_ID, USER_NAME, COVER_ID))
-CREATE TABLE SIMULATIONDATASET (ID BIGINT NOT NULL, COOPERATIVIATY REAL, FINALCOOPERATIONVALUE REAL, FINALPAYOFFVALUE REAL, ITERATIONS REAL, NAME VARCHAR(255), USERID BIGINT, WEALTH REAL, AVERAGE REAL, DEVIATION REAL, MAXIMUM REAL, MINIMUM REAL, VARIANCE REAL, payoffAverage REAL, payoffdeviation REAL, payoffmaximum REAL, payoffminimum REAL, payoffvariance REAL, graphId BIGINT, username VARCHAR(255), simulationSeries BIGINT, SIMULATIONDATASETS_ID BIGINT, PRIMARY KEY (ID))
+CREATE TABLE SIMULATIONDATASET (ID BIGINT NOT NULL, COOPERATIVIATY REAL, FINALCOOPERATIONVALUE REAL, FINALPAYOFFVALUE REAL, ITERATIONS REAL, NAME VARCHAR(255), USERID VARCHAR(255), WEALTH REAL, AVERAGE REAL, DEVIATION REAL, MAXIMUM REAL, MINIMUM REAL, VARIANCE REAL, payoffAverage REAL, payoffdeviation REAL, payoffmaximum REAL, payoffminimum REAL, payoffvariance REAL, graphId BIGINT, username VARCHAR(255), simulationSeries BIGINT, SIMULATIONDATASETS_ID BIGINT, PRIMARY KEY (ID))
CREATE TABLE SIMULATIONSERIESGROUP_SIMULATIONSERIES (SimulationSeriesGroup_ID BIGINT NOT NULL, seriesList_ID BIGINT NOT NULL, PRIMARY KEY (SimulationSeriesGroup_ID, seriesList_ID))
CREATE TABLE CustomGraph_PROPERTIES (ID BIGINT, USER_NAME VARCHAR(255), PROPERTIES REAL)
CREATE TABLE CustomGraph_TYPES (ID BIGINT, USER_NAME VARCHAR(255), TYPES INTEGER)
@@ -66,3 +66,5 @@ ALTER TABLE SimulationDataset_COOPERATIONVALUES ADD CONSTRAINT SmlationDatasetCO
ALTER TABLE SimulationDataset_PAYOFFVALUES ADD CONSTRAINT SimulationDataset_PAYOFFVALUESSimulationDataset_ID FOREIGN KEY (SimulationDataset_ID) REFERENCES SIMULATIONDATASET (ID)
CREATE TABLE SEQUENCE (SEQ_NAME VARCHAR(50) NOT NULL, SEQ_COUNT NUMERIC(38), PRIMARY KEY (SEQ_NAME))
INSERT INTO SEQUENCE(SEQ_NAME, SEQ_COUNT) values ('SEQ_GEN', 0)
+CREATE TABLE SEQUENCE (SEQ_NAME VARCHAR(50) NOT NULL, SEQ_COUNT NUMERIC(38), PRIMARY KEY (SEQ_NAME))
+INSERT INTO SEQUENCE(SEQ_NAME, SEQ_COUNT) values ('SEQ_GEN', 0)
diff --git a/ocd/test/input/SawmillGraphMl.xml b/ocd/test/input/SawmillGraphMl.xml
index 8f35352b..40c30da1 100644
--- a/ocd/test/input/SawmillGraphMl.xml
+++ b/ocd/test/input/SawmillGraphMl.xml
@@ -1,1815 +1,652 @@
-
-
-
-
-
-
+
+
0.0
-
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
2.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
1.0
-
-
-
-
-
-
-
-
+
-
-
-
diff --git a/rest_ocd_services/.project b/rest_ocd_services/.project
index 314c2344..b47460c9 100644
--- a/rest_ocd_services/.project
+++ b/rest_ocd_services/.project
@@ -20,4 +20,15 @@
org.eclipse.jdt.core.javanature
org.eclipse.buildship.core.gradleprojectnature
+
+
+ 1643825602774
+
+ 30
+
+ org.eclipse.core.resources.regexFilterMatcher
+ node_modules|.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__
+
+
+
diff --git a/rest_ocd_services/build.gradle b/rest_ocd_services/build.gradle
index f625a58b..4a6bff11 100644
--- a/rest_ocd_services/build.gradle
+++ b/rest_ocd_services/build.gradle
@@ -8,9 +8,10 @@ plugins {
// Apply the application plugin to add support for building a CLI application in Java.
id 'application'
id 'eclipse' // only required when using Eclipse
+ id 'java-library'
}
-def yFiles = "$rootDir/yFiles"
+
def export = "$projectDir/export"
def ocd = "$rootDir/ocd"
@@ -25,21 +26,20 @@ repositories {
}
dependencies {
- //yGuard
- compileOnly 'com.yworks:yguard:3.0.0'
+
// Use JUnit test framework.
testImplementation 'junit:junit:4.13'
// las2peer bundle which is not necessary in the runtime path
// compileOnly will be moved into the lib dir afterwards
- compileOnly "i5:las2peer-bundle:${project.property('core.version')}"
+ api "i5:las2peer-bundle:${project.property('core.version')}"
//ocd service deps
- compileOnly "org.apache.commons:commons-exec:1.3"
+ implementation "org.apache.commons:commons-exec:1.3"
compileOnly "com.google.guava:guava:31.0.1-jre"
- compileOnly "org.la4j:la4j:0.4.9"
- compileOnly "org.eclipse.persistence:eclipselink:2.7.9"
+ implementation "org.la4j:la4j:0.4.9"
+ implementation "org.eclipse.persistence:eclipselink:2.7.9"
compileOnly "org.apache.geronimo.specs:geronimo-jpa_2.0_spec:1.1"
compileOnly("commons-jxpath:commons-jxpath:1.3") {
exclude group: 'xml-apis', module: 'xml-apis'
@@ -51,34 +51,41 @@ dependencies {
compileOnly "net.minidev:json-smart:2.4.7"
compileOnly "com.googlecode.json-simple:json-simple:1.1.1"
compileOnly "org.apache.commons:commons-pool2:2.11.1"
- compileOnly "org.apache.commons:commons-dbcp2:2.9.0"
+ implementation "org.apache.commons:commons-dbcp2:2.9.0"
+ implementation 'org.apache.commons:commons-lang3:3.12.0'
compileOnly "org.apache.commons:commons-math3:3.6.1"
compileOnly "org.apache.geronimo.specs:geronimo-jpa_2.0_spec:1.1"
- compileOnly "org.apache.lucene:lucene-core:8.9.1"
- compileOnly "org.apache.lucene:lucene-analyzers-common:8.11.1"
+ implementation "org.apache.lucene:lucene-core:8.9.1"
+ implementation "org.apache.lucene:lucene-analyzers-common:8.11.1"
compileOnly "org.apache.poi:poi:5.1.0"
- compileOnly "org.apache.poi:poi-ooxml:5.1.0"
+ implementation "org.apache.poi:poi-ooxml:5.1.0"
compileOnly "org.apache.jena:jena-core:4.3.2"
//Exclude jackson modules as they are already included by las2peer and newer versions may break things like swagger
- compileOnly ("org.apache.jena:jena-arq:4.3.2") {
+ implementation ("org.apache.jena:jena-arq:4.3.2") {
exclude group: "com.fasterxml.jackson.core", module: "jackson-core"
exclude group: "com.fasterxml.jackson.core", module: "jackson-databind"
}
compileOnly "org.ejml:ejml-core:0.41"
- compileOnly "org.hsqldb:hsqldb:2.6.1"
+ implementation "org.hsqldb:hsqldb:2.6.1"
compileOnly "org.apache.xmlgraphics:batik-svggen:1.14"
compileOnly("org.apache.xmlgraphics:batik-bridge:1.14") {
exclude group: 'xml-apis', module: 'xml-apis'
}
- compileOnly "org.mockito:mockito-all:1.9.5"
- compileOnly "fr.irit.smac.thirdparty.edu.gmu.cs:mason:19"
- compileOnly "org.ojalgo:ojalgo:50.0.0"
+ implementation "org.mockito:mockito-all:1.9.5"
+ implementation "fr.irit.smac.thirdparty.edu.gmu.cs:mason:19"
+ implementation "org.ojalgo:ojalgo:50.0.0"
compileOnly "net.sbbi:sbbi-upnplib:1.0.4"
+ implementation "org.graphstream:gs-core:2.0"
- //yFiles
- compileOnly fileTree(dir: "${yFiles}", include: '*.jar')
+ //gs-algo version that includes HopcroftTarjanBiconnectedComponents
+ implementation "org.graphstream:gs-algo:2.0.ACIS"
+ implementation 'com.googlecode.json-simple:json-simple:1.1.1'
+
+ //arangoDB Java driver
+ implementation "com.arangodb:arangodb-java-driver:6.18.0"
+ implementation "com.arangodb:jackson-dataformat-velocypack:3.0.1"
}
configurations {
@@ -93,10 +100,14 @@ jar {
attributes "Library-SymbolicName": "${project.property('service.name')}"
}
- from { (configurations.runtimeClasspath).collect { it.isDirectory() ? it : zipTree(it) } } {
+ from { configurations.runtimeClasspath.findAll { it.name.endsWith('jar') }.collect { zipTree(it) }} {
// Exclude signatures to be able to natively bundle signed jars
exclude 'META-INF/*.RSA', 'META-INF/*.SF', 'META-INF/*.DSA'
}
+ duplicatesStrategy = 'include' // this is needed due to duplicate error in gradle 7.0 which seems to be a bug
+
+
+
}
application {
@@ -106,11 +117,11 @@ application {
// put all .jar files into export/jars folder
tasks.withType(Jar) {
- destinationDir = file("$projectDir/export/jars")
+ getDestinationDirectory().set(file("$projectDir/export/jars"))
}
javadoc {
- destinationDir = file("$projectDir/export/doc")
+ setDestinationDir(file("$projectDir/export/doc"))
}
build.dependsOn "javadoc"
@@ -157,7 +168,7 @@ task startscripts {
# this script is autogenerated by 'gradle startscripts'
# it starts a las2peer node providing the service '${project.property('service.name')}.${project.property('service.class')}' of this project
# pls execute it from the root folder of your deployment, e. g. ./bin/start_network.sh
-java -cp "lib/*:service/*" i5.las2peer.tools.L2pNodeLauncher --port 9011 --service-directory service uploadStartupDirectory startService\\(\\'${project.property('service.name')}.${project.property('service.class')}@${project.property('service.version')}\\'\\) startWebConnector interactive
+java -cp "lib/*:service/*" --add-opens java.base/java.lang=ALL-UNNAMED i5.las2peer.tools.L2pNodeLauncher --port 9011 --service-directory service uploadStartupDirectory startService\\(\\'${project.property('service.name')}.${project.property('service.class')}@${project.property('service.version')}\\'\\) startWebConnector interactive
"""
new File("$rootDir/bin", "start_network.bat").text = """:: this script is autogenerated by 'gradle startscripts'
:: it starts a las2peer node providing the service '${project.property('service.name')}.${project.property('service.class')}' of this project
@@ -167,7 +178,7 @@ cd %~p0
cd ..
set BASE=%CD%
set CLASSPATH="%BASE%/lib/*;%BASE%/service/*;"
-java -cp %CLASSPATH% i5.las2peer.tools.L2pNodeLauncher --port 9011 --service-directory service uploadStartupDirectory startService('${project.property('service.name')}.${project.property('service.class')}@${project.property('service.version')}') startWebConnector interactive
+java -cp %CLASSPATH% --add-opens java.base/java.lang=ALL-UNNAMED i5.las2peer.tools.L2pNodeLauncher --port 9011 --service-directory service uploadStartupDirectory startService('${project.property('service.name')}.${project.property('service.class')}@${project.property('service.version')}') startWebConnector interactive
pause
"""
}
@@ -254,7 +265,7 @@ build.dependsOn "generateAgents"
clean.doLast {
file("$ocd/db").deleteDir()
file("$ocd/indexes").deleteDir()
- file("$ocd/yGuard").deleteDir()
+
file("$rootDir/tmp").deleteDir()
file("$rootDir/lib").deleteDir()
@@ -278,55 +289,17 @@ test {
workingDir = file("$rootDir")
}
-task yguard {
- group 'yGuard'
- description 'Obfuscates and shrinks the java archive.'
-
- mkdir "${export}/obfuscated"
- mkdir "$ocd/yGuard"
-
- doLast {
- ant.taskdef(
- name: 'yguard',
- classname: 'com.yworks.yguard.YGuardTask',
- classpath: '../lib/yGuard-3.0.0.jar'
- )
-
- ant.yguard {
- // see the yGuard task documentation for information about the yGuard element
- // Obfuscate the yFiles Jar.
- inoutpair(in: "${yFiles}/y.jar", out: "./export/obfuscated/y.jar")
- inoutpair(in: "${yFiles}/ysvg.jar", out: "./export/obfuscated/ysvg.jar")
- // While obfuscating, adjust the names of yFiles features in the
- // application's Jar file.
- inoutpair(in: "${export}/jars/rest_ocd_services.jar", out: "${export}/obfuscated/rest_ocd_services.jar")
-
- externalclasses {
- //pathelement(location: configurations.compileOnly.asPath)
- fileset(dir: "${rootDir}/lib") {
- include(name: '**/*.jar')
- }
- }
- // ...using the yGuard 'rename' task.
- rename(logfile: "${rootDir}/ocd/yGuard/log.xml", replaceClassNameStrings: "true") {
- property(name: "obfuscation-prefix", value: "yguard")
- keep {
- 'class'(classes: "private", methods: "private", fields: "private") {
- patternset {
- //< !--define classes / methods / fields not to be renamed-- >
- include(name: "i5.**")
- //< !--exlude custom classes extending / implementing yFiles classes-->
- exclude(name: "i5.las2peer.services.ocd.graphs.CustomGraph")
- exclude(name: "i5.las2peer.services.ocd.graphs.CustomGraphListener")
- }
- }
- //< keep custom field names required for persistence
- field('class': "i5.las2peer.services.ocd.graphs.CustomGraph", name: "id")
- field('class': "i5.las2peer.services.ocd.graphs.CustomGraph", name: "userName")
- field('class': "i5.las2peer.services.ocd.graphs.CustomGraph", name: "creationMethod")
- }
- }
- }
+// Executes WebOCD tests without database tests. This task is used for github actions.
+task testWithoutDB(type: Test) {
+ workingDir = file("$rootDir")
+ filter {
+ excludeTestsMatching '**.ServiceDatabaseTest'
+ excludeTestsMatching '**.ServiceTest'
+ excludeTestsMatching '**.SimulationPersistenceTest'
+ excludeTestsMatching '**.CoverDatabaseTest'
+ excludeTestsMatching '**.CustomGraphDatabaseTest'
+ excludeTestsMatching '**.DatabaseMethodTest'
+ excludeTestsMatching '**.DatabaseTest'
}
}
@@ -349,4 +322,4 @@ eclipse {
}
}
}
-}
\ No newline at end of file
+}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/ServiceClass.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/ServiceClass.java
index 79731a59..bb022935 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/ServiceClass.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/ServiceClass.java
@@ -3,8 +3,7 @@
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URLDecoder;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
+import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
@@ -17,7 +16,7 @@
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
-import javax.persistence.TypedQuery;
+import javax.persistence.Query;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
@@ -32,10 +31,14 @@
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
+import i5.las2peer.services.ocd.centrality.data.*;
+import i5.las2peer.services.ocd.graphs.*;
import i5.las2peer.services.ocd.utils.*;
import i5.las2peer.services.ocd.utils.Error;
import org.apache.commons.lang3.NotImplementedException;
import org.apache.commons.math3.linear.RealMatrix;
+import org.graphstream.algorithm.ConnectedComponents;
+import org.json.simple.JSONObject;
import org.la4j.matrix.sparse.CCSMatrix;
import i5.las2peer.api.Context;
@@ -73,7 +76,6 @@
import i5.las2peer.services.ocd.centrality.utils.CentralitySimulation;
import i5.las2peer.services.ocd.centrality.utils.CentralitySimulationFactory;
import i5.las2peer.services.ocd.centrality.utils.MatrixOperations;
-import i5.las2peer.services.ocd.cooperation.data.SimulationEntityHandler;
import i5.las2peer.services.ocd.cooperation.data.mapping.MappingFactory;
import i5.las2peer.services.ocd.cooperation.data.mapping.SimulationGroupSetMapping;
import i5.las2peer.services.ocd.cooperation.data.mapping.SimulationSeriesSetMapping;
@@ -124,8 +126,7 @@
import io.swagger.annotations.Info;
import io.swagger.annotations.License;
import io.swagger.annotations.SwaggerDefinition;
-import y.algo.GraphChecker;
-import y.base.Graph;
+
/**
*
@@ -154,12 +155,16 @@ protected void initResources() {
public ServiceClass() {
+ database = new Database(false);
setFieldValues();
+ // instantiate inactivityHandler to regularly remove content of inactive users.
+ inactivityHandler = new InactivityHandler(database, threadHandler, this); //TODO inactivity handler muss sich auf db beziehens
+ // instantiate UserLimitHandler to limit content for various users.
+ userLimitsHandler = new UserLimitsHandler(database);
- // instantiate inactivityHandler to regularly remove content of inactive users.
- inactivityHandler = new InactivityHandler(entityHandler, threadHandler, this);
}
+
///////////////////////////////////////////////////////////
///// ATTRIBUTES
///////////////////////////////////////////////////////////
@@ -167,7 +172,8 @@ public ServiceClass() {
/**
* l2p logger
*/
- private final static L2pLogger logger = L2pLogger.getInstance(ServiceClass.class.getName());
+ private final static GeneralLogger generalLogger = new GeneralLogger();
+
/**
* The thread handler used for algorithm, benchmark and metric execution.
*/
@@ -181,7 +187,7 @@ public ServiceClass() {
/**
* The entity handler used for access stored entities.
*/
- private final static SimulationEntityHandler entityHandler = new SimulationEntityHandler();
+ private static Database database;
/**
* The factory used for creating benchmarks.
@@ -220,14 +226,11 @@ public ServiceClass() {
/**
- * Number of days of inactivity allowed, before user content gets removed.
+ * User limit handler for inactive days allowed and size of user content allowed.
*/
- private int maxInactiveDays;
+ private static UserLimitsHandler userLimitsHandler;
+
- /**
- * Password to be used to adjust number of days before inactive user content is removed.
- */
- private String inactivityHandlerPassword;
//////////////////////////////////////////////////////////////////
///////// Utility Methods
@@ -241,17 +244,7 @@ public static String getUserId() {
return Context.getCurrent().getMainAgent().getIdentifier();
}
- public int getMaxInactiveDays() { return this.maxInactiveDays; }
- public String getInactivityHandlerPassword(){return this.inactivityHandlerPassword;}
-
- /**
- * This method is used to set fresh field values, in case modifications were made in
- * i5.las2peer.services.ocd.ServiceClass.properties file
- */
- public void setFreshFieldValues() {
- setFieldValues();
- }
//////////////////////////////////////////////////////////////////
@@ -291,7 +284,8 @@ public static class RootResource {
public Response validateLogin() {
try {
// update user inactivity info when user logs in.
- inactivityHandler.refreshUserInactivityData(getUserName());
+ inactivityHandler.getAndUpdateUserInactivityData(getUserName(), true);
+ generalLogger.getLogger().log(Level.INFO, "user " + getUserName() + " logged in.");
return Response.ok(requestHandler.writeConfirmationXml()).build();
} catch (Exception e) {
requestHandler.log(Level.SEVERE, "", e);
@@ -300,61 +294,26 @@ public Response validateLogin() {
}
/**
- * This method can be used to adjust number of days before content of inactive users is removed. This is an
- * alternative to directly modifying the value in i5.las2peer.services.ocd.ServiceClass.properties file.
- *
- * @param contentStr XML with new inactivity days to set and the access code that allows modifications to take place.
- * @return Newly set value of inactive days allowed before content deletion, or Error XML.
+ * Returns xml that stores user's content deletion date and the number of days before content deletion
+ * @param usernameStr
+ * @return
*/
- @POST
- @Path("allowedInactivity")
+ @GET
@Produces(MediaType.TEXT_PLAIN)
- public Response adjustAllowedInactivity(String contentStr) {
-
- Map parameters;
- String inactivityPassword;
- int allowedInactivityDays;
-
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Success"),
+ @ApiResponse(code = 401, message = "Unauthorized") })
+ @Path("inactivity/{username}")
+ @ApiOperation(tags = {"show"}, value = "Content deletion date", notes = "Returns content deletion date of a user")
+ public Response getContentDeletionDate(@PathParam("username") String usernameStr) {
try {
- parameters = requestHandler.parseParameters(contentStr);
- if (parameters.get("AccessCode") == null) {
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Access code is required to modify allowed inactivity.");
- }
- String accessCode = parameters.get("AccessCode");
-
- // read most recent password for inactivityHandler
- service.setFreshFieldValues();
- inactivityPassword = service.getInactivityHandlerPassword();
- if(!accessCode.equals(inactivityPassword)){
- return requestHandler.writeError(Error.INTERNAL, "Access code is invalid.");
- }
-
-
- String allowedInactivityDaysString = parameters.get("AllowedInactivityDays");
- if ((allowedInactivityDaysString == null) || (Integer.parseInt(allowedInactivityDaysString) < 0)) {
- return requestHandler.writeError(Error.PARAMETER_INVALID, "AllowedInactivityDays parameter needs to be provided and be a positive integer.");
- }
- allowedInactivityDays = Integer.parseInt(allowedInactivityDaysString);
-
+ LocalDate deletionDate = inactivityHandler.getAndUpdateUserInactivityData(usernameStr, false);
+ //generalLogger.getLogger().log(Level.INFO, "user " + getUserName() + ": content deletion date is " + deletionDate.toString());
+ return Response.ok(requestHandler.writeDeletionDate(usernameStr, deletionDate)).build();
} catch (Exception e) {
- requestHandler.log(Level.WARNING, "", e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Invalid parameters provided.");
-
- }
-
- // write new allowed inactivity value to ServiceClass properties file
- try {
- BufferedWriter writer = new BufferedWriter(new FileWriter("etc/i5.las2peer.services.ocd.ServiceClass.properties"));
- writer.write("maxInactiveDays=" + allowedInactivityDays);
- writer.newLine();
- writer.write("inactivityHandlerPassword=" + inactivityPassword );
- writer.close();
- } catch (IOException e) {
- e.printStackTrace();
+ requestHandler.log(Level.SEVERE, "", e);
+ return requestHandler.writeError(Error.INTERNAL, "Internal system error.");
}
- return Response.ok(allowedInactivityDays).build();
-
}
//////////////////////////////////////////////////////////////////////////
@@ -392,7 +351,7 @@ public Response adjustAllowedInactivity(String contentStr) {
* The graph input.
* @return A graph id xml. Or an error xml.
*/
- @POST
+ @POST
@Path("graphs")
@Produces(MediaType.TEXT_XML)
@Consumes(MediaType.TEXT_PLAIN)
@@ -412,6 +371,15 @@ public Response createGraph(@DefaultValue("unnamed") @QueryParam("name") String
String contentStr) {
try {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
+ /*
+ Check if user has a limit regarding number of graph throw an error if the limit is violated.
+ */
+
+ if (userLimitsHandler.reachedGraphCountLimit(username)){
+ requestHandler.log(Level.WARNING, "user: " + username + " reached graph count limit.");
+ return requestHandler.writeError(Error.INTERNAL, "Graph count limit reached. Delete a graph before generating a new one, or contact administrator to adjust limits.");
+ }
+
GraphInputFormat format;
CustomGraph graph;
try {
@@ -487,6 +455,7 @@ public Response createGraph(@DefaultValue("unnamed") @QueryParam("name") String
graph.setCreationMethod(log);
GraphProcessor processor = new GraphProcessor();
processor.determineGraphTypes(graph);
+ graph.setNodeEdgeCountColumnFields(); // before persisting the graph, update node/edge count information
if (doMakeUndirected) {
Set graphTypes = graph.getTypes();
if (graphTypes.remove(GraphType.DIRECTED)) {
@@ -494,7 +463,8 @@ public Response createGraph(@DefaultValue("unnamed") @QueryParam("name") String
}
}
try {
- entityHandler.storeGraph(graph);
+ database.storeGraph(graph);
+ generalLogger.getLogger().log(Level.INFO, "user " + username + ": import graph " + graph.getKey() + " in format " + graphInputFormatStr);
} catch (Exception e) {
return requestHandler.writeError(Error.INTERNAL, "Could not store graph");
}
@@ -523,6 +493,15 @@ public Response createGraph(@DefaultValue("unnamed") @QueryParam("name") String
@ApiOperation(tags = {"special"}, value = "Big Graph Import", notes = "Stores a graph step by step.")
public Response storeGraph(@DefaultValue("unnamed") @QueryParam("name") String nameStr, String contentStr) {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
+ /*
+ Check if user has a limit regarding number of graph or covers and throw an error if the limit is violated.
+ */
+
+ if (userLimitsHandler.reachedGraphCountLimit(username)){
+ requestHandler.log(Level.WARNING, "user: " + username + " reached graph count limit.");
+ return requestHandler.writeError(Error.INTERNAL, "Graph count limit reached. Delete a graph before generating a new one, or contact administrator to adjust limits.");
+ }
+
File graphDir = new File("tmp" + File.separator + username);
if (!graphDir.exists()) {
graphDir.mkdirs();
@@ -640,12 +619,12 @@ public Response processStoredGraph(@DefaultValue("unnamed") @QueryParam("name")
@ApiResponse(code = 401, message = "Unauthorized") })
@ApiOperation(tags = {"show"}, value = "Get Graphs Info", notes = "Returns the ids or meta information of multiple graphs.")
public Response getGraphs(@DefaultValue("0") @QueryParam("firstIndex") String firstIndexStr,
- @DefaultValue("0") @QueryParam("length") String lengthStr,
+ @DefaultValue("") @QueryParam("length") String lengthStr,
@DefaultValue("FALSE") @QueryParam("includeMeta") String includeMetaStr,
@DefaultValue("") @QueryParam("executionStatuses") String executionStatusesStr) {
try {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
- List queryResults;
+ List queryResults;
List executionStatusIds = new ArrayList();
if (!executionStatusesStr.equals("")) {
try {
@@ -687,17 +666,20 @@ public Response getGraphs(@DefaultValue("0") @QueryParam("firstIndex") String fi
if (!lengthStr.equals("")) {
length = Integer.parseInt(lengthStr);
}
+ else {
+ length = Integer.MAX_VALUE;
+ }
} catch (Exception e) {
requestHandler.log(Level.WARNING, "user: " + username, e);
return requestHandler.writeError(Error.PARAMETER_INVALID, "Length is not valid.");
}
- queryResults = entityHandler.getGraphs(username, firstIndex, length, executionStatusIds);
+ queryResults = database.getGraphMetaDataEfficiently(username, firstIndex, length, executionStatusIds);
String responseStr;
if (includeMeta) {
- responseStr = requestHandler.writeGraphMetas(queryResults);
+ responseStr = requestHandler.writeGraphMetasEfficiently(queryResults);
} else {
- responseStr = requestHandler.writeGraphIds(queryResults);
+ responseStr = requestHandler.writeGraphIdsEfficiently(queryResults);
}
return Response.ok(responseStr).build();
} catch (Exception e) {
@@ -724,28 +706,25 @@ public Response getGraphs(@DefaultValue("0") @QueryParam("firstIndex") String fi
public Response getGraph(@DefaultValue("GRAPH_ML") @QueryParam("outputFormat") String graphOutputFormatStr,
@PathParam("graphId") String graphIdStr) {
try {
- long graphId;
+
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
GraphOutputFormat format;
try {
- graphId = Long.parseLong(graphIdStr);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph id is not valid.");
- }
- try {
+
format = GraphOutputFormat.valueOf(graphOutputFormatStr);
} catch (Exception e) {
requestHandler.log(Level.WARNING, "user: " + username, e);
return requestHandler.writeError(Error.PARAMETER_INVALID,
"Specified graph output format does not exist.");
}
-
- CustomGraph graph = entityHandler.getGraph(username, graphId);
+
+ CustomGraph graph = database.getGraph(username, graphIdStr); //done
+
if (graph == null)
return requestHandler.writeError(Error.PARAMETER_INVALID,
- "Graph does not exist: graph id " + graphId);
+ "Graph does not exist: graph key " + graphIdStr); //done
+ generalLogger.getLogger().log(Level.INFO, "user " + username + ": get cover " + graphIdStr + " in format " + graphOutputFormatStr );
return Response.ok(requestHandler.writeGraph(graph, format)).build();
} catch (Exception e) {
requestHandler.log(Level.SEVERE, "", e);
@@ -759,10 +738,10 @@ public Response getGraph(@DefaultValue("GRAPH_ML") @QueryParam("outputFormat") S
* If a benchmark is currently calculating the graph the execution is
* terminated. If an algorithm is currently calculating a cover based on
* the graph it is terminated. If a metric is currently running on a
- * cover based on the grap it is terminated.
+ * cover based on the graph it is terminated.
*
* @param graphIdStr
- * The graph id.
+ * The graph key.
* @return A confirmation xml. Or an error xml.
*/
@DELETE
@@ -773,17 +752,10 @@ public Response getGraph(@DefaultValue("GRAPH_ML") @QueryParam("outputFormat") S
@ApiOperation(tags = {"delete"}, value = "Delete Graph", notes = "Deletes a graph.")
public Response deleteGraph(@PathParam("graphId") String graphIdStr) {
try {
- long graphId;
- String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
- try {
- graphId = Long.parseLong(graphIdStr);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph id is not valid.");
- }
+ String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
try {
- entityHandler.deleteGraph(username, graphId, threadHandler);
+ database.deleteGraph(username, graphIdStr, threadHandler); //done
} catch (Exception e) {
if(e.getMessage() != null) {
@@ -791,7 +763,7 @@ public Response deleteGraph(@PathParam("graphId") String graphIdStr) {
}
requestHandler.writeError(Error.INTERNAL, "Graph not found");
}
-
+ generalLogger.getLogger().log(Level.INFO, "user " + username + ": delete graph " + graphIdStr);
return Response.ok(requestHandler.writeConfirmationXml()).build();
} catch (Exception e) {
requestHandler.log(Level.SEVERE, "", e);
@@ -832,13 +804,15 @@ public Response createCover(@PathParam("graphId") String graphIdStr,
String contentStr) {
try {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
- long graphId;
- try {
- graphId = Long.parseLong(graphIdStr);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph id is not valid.");
+
+ /*
+ Check if user has a limit regarding covers and throw an error if the limit is violated.
+ */
+ if (userLimitsHandler.reachedCoverCountLimit(username)){
+ requestHandler.log(Level.WARNING, "user: " + username + " reached cover count limit.");
+ return requestHandler.writeError(Error.INTERNAL, "Cover count limit reached. Delete a cover before generating a new one, or contact administrator to adjust limits.");
}
+
CoverInputFormat format;
try {
format = CoverInputFormat.valueOf(coverInputFormatStr);
@@ -864,38 +838,28 @@ public Response createCover(@PathParam("graphId") String graphIdStr,
}
CoverCreationLog log = new CoverCreationLog(algorithmType, new HashMap(), graphTypes);
log.setStatus(ExecutionStatus.COMPLETED);
- EntityManager em = entityHandler.getEntityManager();
- EntityTransaction tx = em.getTransaction();
+
Cover cover;
+ CustomGraph graph;
try {
- CustomGraph graph;
- try {
- graph = entityHandler.getGraph(username, graphId);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING,
- "user: " + username + ", " + "Graph does not exist: graph id " + graphId);
- return requestHandler.writeError(Error.PARAMETER_INVALID,
- "Graph does not exist: graph id " + graphId);
- }
- try {
- cover = requestHandler.parseCover(contentStr, graph, format);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID,
- "Input cover does not correspond to the specified format.");
- }
- cover.setCreationMethod(log);
- cover.setName(URLDecoder.decode(nameStr, "UTF-8"));
- tx.begin();
- em.persist(cover);
- tx.commit();
- } catch (RuntimeException e) {
- if (tx != null && tx.isActive()) {
- tx.rollback();
- }
- throw e;
+ graph = database.getGraph(username, graphIdStr);
+ } catch (Exception e) {
+ requestHandler.log(Level.WARNING,
+ "user: " + username + ", " + "Graph does not exist: graph id " + graphIdStr);
+ return requestHandler.writeError(Error.PARAMETER_INVALID,
+ "Graph does not exist: graph id " + graphIdStr);
}
- em.close();
+ try {
+ cover = requestHandler.parseCover(contentStr, graph, format);
+ } catch (Exception e) {
+ requestHandler.log(Level.WARNING, "user: " + username, e);
+ return requestHandler.writeError(Error.PARAMETER_INVALID,
+ "Input cover does not correspond to the specified format.");
+ }
+ cover.setCreationMethod(log);
+ cover.setName(URLDecoder.decode(nameStr, "UTF-8"));
+ database.storeCover(cover); //done
+ generalLogger.getLogger().log(Level.INFO, "user " + username + ": import cover " + cover.getKey() + " in format " + coverInputFormatStr);
return Response.ok(requestHandler.writeId(cover)).build();
} catch (Exception e) {
requestHandler.log(Level.SEVERE, "", e);
@@ -950,15 +914,8 @@ public Response getCovers(
{
try {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
- long graphId = 0;
- if (!graphIdStr.equals("")) {
- try {
- graphId = Long.parseLong(graphIdStr);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph id is not valid.");
- }
- }
+ int length;
+ int firstIndex;
List executionStatusIds = new ArrayList();
if (!executionStatusesStr.equals("")) {
try {
@@ -993,40 +950,20 @@ public Response getCovers(
"Specified metric execution status does not exist.");
}
}
- List queryResults;
- EntityManager em = entityHandler.getEntityManager();
- /*
- * Query
- */
- String queryStr = "SELECT c from Cover c" + " JOIN c." + Cover.GRAPH_FIELD_NAME + " g" + " JOIN c."
- + Cover.CREATION_METHOD_FIELD_NAME + " a";
- if (!metricExecutionStatusesStr.equals("")) {
- queryStr += " JOIN c." + Cover.METRICS_FIELD_NAME + " m";
- }
- queryStr += " WHERE g." + CustomGraph.USER_NAME_FIELD_NAME + " = :username" + " AND a."
- + CoverCreationLog.STATUS_ID_FIELD_NAME + " IN :execStatusIds";
- if (!metricExecutionStatusesStr.equals("")) {
- queryStr += " AND m." + OcdMetricLog.STATUS_ID_FIELD_NAME + " IN :metricExecStatusIds";
- }
- if (!graphIdStr.equals("")) {
- queryStr += " AND g." + CustomGraph.ID_FIELD_NAME + " = " + graphId;
- }
- /*
- * Gets each cover only once.
- */
- queryStr += " GROUP BY c";
- TypedQuery query = em.createQuery(queryStr, Cover.class);
+
+ List queryResults;
try {
- int firstIndex = Integer.parseInt(firstIndexStr);
- query.setFirstResult(firstIndex);
+ firstIndex = Integer.parseInt(firstIndexStr);
} catch (Exception e) {
requestHandler.log(Level.WARNING, "user: " + username, e);
return requestHandler.writeError(Error.PARAMETER_INVALID, "First index is not valid.");
}
try {
if (!lengthStr.equals("")) {
- int length = Integer.parseInt(lengthStr);
- query.setMaxResults(length);
+ length = Integer.parseInt(lengthStr);
+ }
+ else {
+ length = Integer.MAX_VALUE;
}
} catch (Exception e) {
requestHandler.log(Level.WARNING, "user: " + username, e);
@@ -1039,18 +976,13 @@ public Response getCovers(
requestHandler.log(Level.WARNING, "", e);
return requestHandler.writeError(Error.PARAMETER_INVALID, "Include meta is not a boolean value.");
}
- query.setParameter("username", username);
- query.setParameter("execStatusIds", executionStatusIds);
- if (!metricExecutionStatusesStr.equals("")) {
- query.setParameter("metricExecStatusIds", metricExecutionStatusIds);
- }
- queryResults = query.getResultList();
- em.close();
+
+ queryResults = database.getCoverMetaDataEfficiently(username, graphIdStr, executionStatusIds, metricExecutionStatusIds, firstIndex, length);
String responseStr;
if (includeMeta) {
- responseStr = requestHandler.writeCoverMetas(queryResults);
+ responseStr = requestHandler.writeCoverMetasEfficiently(queryResults);
} else {
- responseStr = requestHandler.writeCoverIds(queryResults);
+ responseStr = requestHandler.writeCoverIdsEfficiently(queryResults);
}
return Response.ok(responseStr).build();
} catch (Exception e) {
@@ -1080,20 +1012,7 @@ public Response getCover(@PathParam("graphId") String graphIdStr, @PathParam("co
@DefaultValue("LABELED_MEMBERSHIP_MATRIX") @QueryParam("outputFormat") String coverOutputFormatStr) {
try {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
- long graphId;
- try {
- graphId = Long.parseLong(graphIdStr);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph id is not valid.");
- }
- long coverId;
- try {
- coverId = Long.parseLong(coverIdStr);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Cover id is not valid.");
- }
+
CoverOutputFormat format;
try {
format = CoverOutputFormat.valueOf(coverOutputFormatStr);
@@ -1105,7 +1024,7 @@ public Response getCover(@PathParam("graphId") String graphIdStr, @PathParam("co
Cover cover = null;
try {
- cover = entityHandler.getCover(username, graphId, coverId);
+ cover = database.getCover(username, graphIdStr, coverIdStr); //done
// Paint cover if not yet done when requested type is default XML
if(format == CoverOutputFormat.DEFAULT_XML && !cover.isPainted()) {
@@ -1116,10 +1035,11 @@ public Response getCover(@PathParam("graphId") String graphIdStr, @PathParam("co
} catch (Exception e) {
requestHandler.log(Level.WARNING, "user: " + username + ", " + "Cover does not exist: cover id "
- + coverId + ", graph id " + graphId);
+ + coverIdStr + ", graph id " + graphIdStr);
return requestHandler.writeError(Error.PARAMETER_INVALID,
- "Cover does not exist: cover id " + coverId + ", graph id " + graphId);
+ "Cover does not exist: cover id " + coverIdStr + ", graph id " + graphIdStr);
}
+ generalLogger.getLogger().log(Level.INFO, "user " + username + ": get cover " + coverIdStr + " in format " + coverOutputFormatStr );
return Response.ok(requestHandler.writeCover(cover, format)).build();
} catch (Exception e) {
requestHandler.log(Level.SEVERE, "", e);
@@ -1149,23 +1069,10 @@ public Response getCover(@PathParam("graphId") String graphIdStr, @PathParam("co
public Response deleteCover(@PathParam("coverId") String coverIdStr, @PathParam("graphId") String graphIdStr) {
try {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
- long graphId;
- try {
- graphId = Long.parseLong(graphIdStr);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph id is not valid.");
- }
- long coverId;
- try {
- coverId = Long.parseLong(coverIdStr);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Cover id is not valid.");
- }
try {
- entityHandler.deleteCover(username, graphId, coverId, threadHandler);
+ database.deleteCover(username, graphIdStr, coverIdStr, threadHandler); //TODO
+ generalLogger.getLogger().log(Level.INFO, "user " + username + ": delete cover " + coverIdStr);
return Response.ok(requestHandler.writeConfirmationXml()).build();
} catch (IllegalArgumentException e) {
return requestHandler.writeError(Error.PARAMETER_INVALID, e.getMessage());
@@ -1222,16 +1129,20 @@ public Response runAlgorithm(@PathParam("graphId") String graphIdStr,
@DefaultValue("0") @QueryParam("componentNodeCountFilter") String componentNodeCountFilterStr) {
try {
int componentNodeCountFilter;
- long graphId;
+
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
CoverCreationType algorithmType;
- try {
- graphId = Long.parseLong(graphIdStr);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph id is not valid.");
+
+ /*
+ Check if user has a limit regarding number of graph or covers and throw an error if the limit is violated.
+ */
+ if (userLimitsHandler.reachedCoverCountLimit(username)){
+ requestHandler.log(Level.WARNING, "user: " + username + " reached cover count limit.");
+ return requestHandler.writeError(Error.INTERNAL, "Cover count limit reached. Delete a cover before generating a new one, or contact administrator to adjust limits.");
}
+
try {
+
componentNodeCountFilter = Integer.parseInt(componentNodeCountFilterStr);
} catch (Exception e) {
requestHandler.log(Level.WARNING, "user: " + username, e);
@@ -1255,78 +1166,69 @@ public Response runAlgorithm(@PathParam("graphId") String graphIdStr,
Map parameters;
try {
parameters = requestHandler.parseParameters(content);
- algorithm = algorithmFactory.getInstance(algorithmType, parameters);
+ algorithm = algorithmFactory.getInstance(algorithmType, new HashMap(parameters));
} catch (Exception e) {
requestHandler.log(Level.WARNING, "user: " + username, e);
return requestHandler.writeError(Error.PARAMETER_INVALID, "Parameters are not valid.");
}
Cover cover;
- EntityManager em = entityHandler.getEntityManager();
- CustomGraphId id = new CustomGraphId(graphId, username);
+
CoverCreationLog log;
synchronized (threadHandler) {
- EntityTransaction tx = em.getTransaction();
+
CustomGraph graph;
- try {
- tx.begin();
- graph = em.find(CustomGraph.class, id);
- if (graph == null) {
- requestHandler.log(Level.WARNING,
- "user: " + username + ", " + "Graph does not exist: graph id " + graphId);
- return requestHandler.writeError(Error.PARAMETER_INVALID,
- "Graph does not exist: graph id " + graphId);
- }
- if (graph.getCreationMethod().getStatus() != ExecutionStatus.COMPLETED) {
- requestHandler.log(Level.WARNING,
- "user: " + username + ", "
- + "Invalid graph creation method status for metric execution: "
- + graph.getCreationMethod().getStatus().name());
- return requestHandler.writeError(Error.PARAMETER_INVALID,
- "Invalid graph creation method status for metric execution: "
- + graph.getCreationMethod().getStatus().name());
- }
- boolean weight = Boolean.parseBoolean(contentWeighting);
- if(!graph.isOfType(GraphType.CONTENT_LINKED) && !graph.isOfType(GraphType.CONTENT_UNLINKED) && (weight || (algorithm
- .getAlgorithmType() == CoverCreationType.COST_FUNC_OPT_CLUSTERING_ALGORITHM
- || algorithm.getAlgorithmType() == CoverCreationType.WORD_CLUSTERING_REF_ALGORITHM))) {
- requestHandler.log(Level.WARNING,
- "user: " + username + ", "
- + "Content weighted algorithm chosen for non-content graph: "
- + algorithm.getAlgorithmType().toString() + " " + graph.getTypes() + " " + graph.getPath());
- return requestHandler.writeError(Error.PARAMETER_INVALID,
- "Content weighted algorithm chosen for non-content graph");
- }
- if (weight && (algorithm
- .getAlgorithmType() == CoverCreationType.COST_FUNC_OPT_CLUSTERING_ALGORITHM
- || algorithm.getAlgorithmType() == CoverCreationType.WORD_CLUSTERING_REF_ALGORITHM)) {
- requestHandler.log(Level.WARNING,
- "user: " + username + ", "
- + "Invalid algorithm in combination of weighting requested: "
- + algorithm.getAlgorithmType().toString());
- return requestHandler.writeError(Error.PARAMETER_INVALID,
- "Invalid algorithm in combination of weighting requested");
- }
- if (weight) {
- ContentBasedWeightingAlgorithm weightAlgo = new ContentBasedWeightingAlgorithm();
- graph = weightAlgo.detectOverlappingCommunities(graph, new ExecutionTime());
- }
- cover = new Cover(graph, new CCSMatrix(graph.nodeCount(), 0));
- log = new CoverCreationLog(algorithmType, parameters, algorithm.compatibleGraphTypes());
- cover.setCreationMethod(log);
- cover.setName(URLDecoder.decode(nameStr, "UTF-8"));
- em.persist(cover);
- tx.commit();
- } catch (RuntimeException e) {
- if (tx != null && tx.isActive()) {
- tx.rollback();
- }
- throw e;
+ graph = database.getGraph(username, graphIdStr);
+ if (graph == null) {
+ requestHandler.log(Level.WARNING,
+ "user: " + username + ", " + "Graph does not exist: graph id " + graphIdStr);
+ return requestHandler.writeError(Error.PARAMETER_INVALID,
+ "Graph does not exist: graph id " + graphIdStr);
}
- em.close();
+ if (graph.getCreationMethod().getStatus() != ExecutionStatus.COMPLETED) {
+ requestHandler.log(Level.WARNING,
+ "user: " + username + ", "
+ + "Invalid graph creation method status for metric execution: "
+ + graph.getCreationMethod().getStatus().name());
+ return requestHandler.writeError(Error.PARAMETER_INVALID,
+ "Invalid graph creation method status for metric execution: "
+ + graph.getCreationMethod().getStatus().name());
+ }
+ boolean weight = Boolean.parseBoolean(contentWeighting);
+ if(!graph.isOfType(GraphType.CONTENT_LINKED) && !graph.isOfType(GraphType.CONTENT_UNLINKED) && (weight || (algorithm
+ .getAlgorithmType() == CoverCreationType.COST_FUNC_OPT_CLUSTERING_ALGORITHM
+ || algorithm.getAlgorithmType() == CoverCreationType.WORD_CLUSTERING_REF_ALGORITHM))) {
+ requestHandler.log(Level.WARNING,
+ "user: " + username + ", "
+ + "Content weighted algorithm chosen for non-content graph: "
+ + algorithm.getAlgorithmType().toString() + " " + graph.getTypes() + " " + graph.getPath());
+ return requestHandler.writeError(Error.PARAMETER_INVALID,
+ "Content weighted algorithm chosen for non-content graph");
+ }
+ if (weight && (algorithm
+ .getAlgorithmType() == CoverCreationType.COST_FUNC_OPT_CLUSTERING_ALGORITHM
+ || algorithm.getAlgorithmType() == CoverCreationType.WORD_CLUSTERING_REF_ALGORITHM)) {
+ requestHandler.log(Level.WARNING,
+ "user: " + username + ", "
+ + "Invalid algorithm in combination of weighting requested: "
+ + algorithm.getAlgorithmType().toString());
+ return requestHandler.writeError(Error.PARAMETER_INVALID,
+ "Invalid algorithm in combination of weighting requested");
+ }
+ if (weight) {
+ ContentBasedWeightingAlgorithm weightAlgo = new ContentBasedWeightingAlgorithm();
+ graph = weightAlgo.detectOverlappingCommunities(graph, new ExecutionTime());
+ database.updateGraph(graph); //done
+ }
+ cover = new Cover(graph, new CCSMatrix(graph.getNodeCount(), 0));
+ log = new CoverCreationLog(algorithmType, parameters, algorithm.compatibleGraphTypes());
+ cover.setCreationMethod(log);
+ cover.setName(URLDecoder.decode(nameStr, "UTF-8"));
+ database.storeCover(cover); //done
/*
* Registers and starts algorithm
*/
threadHandler.runAlgorithm(cover, algorithm, componentNodeCountFilter);
+ generalLogger.getLogger().log(Level.INFO, "user " + username + ": run " + algorithm.getClass().getSimpleName() + " on graph " + graph.getKey() + ". Created cover " + cover.getKey());
}
return Response.ok(requestHandler.writeId(cover)).build();
} catch (Exception e) {
@@ -1368,13 +1270,7 @@ public Response importCentralityMap(@PathParam("graphId") String graphIdStr,
String contentStr) {
try {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
- long graphId;
- try {
- graphId = Long.parseLong(graphIdStr);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph id is not valid.");
- }
+
CentralityInputFormat format;
try {
format = CentralityInputFormat.valueOf(centralityInputFormatStr);
@@ -1392,39 +1288,31 @@ public Response importCentralityMap(@PathParam("graphId") String graphIdStr,
}
CentralityCreationLog log = new CentralityCreationLog(null, creationType, null, null);
log.setStatus(ExecutionStatus.COMPLETED);
- EntityManager em = entityHandler.getEntityManager();
- EntityTransaction tx = em.getTransaction();
+
CentralityMap map;
+ CustomGraph graph;
try {
- CustomGraph graph;
- try {
- graph = entityHandler.getGraph(username, graphId);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING,
- "user: " + username + ", " + "Graph does not exist: graph id " + graphId);
- return requestHandler.writeError(Error.PARAMETER_INVALID,
- "Graph does not exist: graph id " + graphId);
- }
- try {
- map = requestHandler.parseCentralityMap(contentStr, graph, format);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID,
- "Input centrality data does not correspond to the specified format.");
- }
- map.setCreationMethod(log);
- map.setName(nameStr);
- tx.begin();
- em.persist(map);
- tx.commit();
- } catch (RuntimeException e) {
- if (tx != null && tx.isActive()) {
- tx.rollback();
- }
- throw e;
+ graph = database.getGraph(username, graphIdStr); //done
+ } catch (Exception e) {
+ requestHandler.log(Level.WARNING,
+ "user: " + username + ", " + "Graph does not exist: graph id " + graphIdStr);
+ return requestHandler.writeError(Error.PARAMETER_INVALID,
+ "Graph does not exist: graph id " + graphIdStr);
}
- em.close();
+ try {
+ map = requestHandler.parseCentralityMap(contentStr, graph, format);
+ } catch (Exception e) {
+ requestHandler.log(Level.WARNING, "user: " + username, e);
+ return requestHandler.writeError(Error.PARAMETER_INVALID,
+ "Input centrality data does not correspond to the specified format.");
+ }
+ map.setCreationMethod(log);
+ map.setName(nameStr);
+
+ database.storeCentralityMap(map); //done
+ generalLogger.getLogger().log(Level.INFO, "user " + username + ": import centrality " + nameStr + " in format " + centralityInputFormatStr);
return Response.ok(requestHandler.writeId(map)).build();
+
} catch (Exception e) {
requestHandler.log(Level.SEVERE, "", e);
return requestHandler.writeError(Error.INTERNAL, "Internal system error.");
@@ -1471,16 +1359,7 @@ public Response getCentralityMaps(
{
try {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
- long graphId = 0;
- if(!graphIdStr.equals("")) {
- try {
- graphId = Long.parseLong(graphIdStr);
- }
- catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph id is not valid.");
- }
- }
+
List executionStatusIds = new ArrayList();
if(!executionStatusesStr.equals("")) {
try {
@@ -1500,36 +1379,21 @@ public Response getCentralityMaps(
executionStatusIds.add(executionStatus.getId());
}
}
- List queryResults;
- EntityManager em = entityHandler.getEntityManager();
- /*
- * Query
- */
- String queryStr = "SELECT c from CentralityMap c"
- + " JOIN c." + CentralityMap.GRAPH_FIELD_NAME + " g"
- + " JOIN c." + CentralityMap.CREATION_METHOD_FIELD_NAME + " a";
- queryStr += " WHERE g." + CustomGraph.USER_NAME_FIELD_NAME + " = :username"
- + " AND a." + CentralityCreationLog.STATUS_ID_FIELD_NAME + " IN :execStatusIds";
- if(!graphIdStr.equals("")) {
- queryStr += " AND g." + CustomGraph.ID_FIELD_NAME + " = " + graphId;
- }
- /*
- * Gets each CentralityMap only once.
- */
- queryStr += " GROUP BY c";
- TypedQuery query = em.createQuery(queryStr, CentralityMap.class);
+ int firstIndex;
try {
- int firstIndex = Integer.parseInt(firstIndexStr);
- query.setFirstResult(firstIndex);
+ firstIndex = Integer.parseInt(firstIndexStr);
}
catch (Exception e) {
requestHandler.log(Level.WARNING, "user: " + username, e);
return requestHandler.writeError(Error.PARAMETER_INVALID, "First index is not valid.");
}
+ int length;
try {
if(!lengthStr.equals("")) {
- int length = Integer.parseInt(lengthStr);
- query.setMaxResults(length);
+ length = Integer.parseInt(lengthStr);
+ }
+ else {
+ length = Integer.MAX_VALUE;
}
}
catch (Exception e) {
@@ -1544,16 +1408,13 @@ public Response getCentralityMaps(
requestHandler.log(Level.WARNING, "", e);
return requestHandler.writeError(Error.PARAMETER_INVALID, "Include meta is not a boolean value.");
}
- query.setParameter("username", username);
- query.setParameter("execStatusIds", executionStatusIds);
- queryResults = query.getResultList();
- em.close();
+ List queryResults = database.getCentralityMapsEfficiently(username, graphIdStr, executionStatusIds, firstIndex, length);
String responseStr;
if(includeMeta) {
- responseStr = requestHandler.writeCentralityMapMetas(queryResults);
+ responseStr = requestHandler.writeCentralityMapMetasEfficiently(queryResults);
}
else {
- responseStr = requestHandler.writeCentralityMapIds(queryResults);
+ responseStr = requestHandler.writeCentralityMapIdsEfficiently(queryResults);
}
return Response.ok(responseStr).build();
}
@@ -1596,17 +1457,11 @@ public Response calculateCentrality(
@DefaultValue("Degree Centrality") @QueryParam("algorithm") String centralityMeasureTypeStr, String content)
{
try {
- long graphId;
+
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
CentralityMeasureType centralityMeasureType;
try {
- graphId = Long.parseLong(graphIdStr);
- }
- catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph id is not valid.");
- }
- try {
+
centralityMeasureType = CentralityMeasureType.valueOf(centralityMeasureTypeStr);
if(centralityMeasureType == CentralityMeasureType.UNDEFINED) {
requestHandler.log(Level.WARNING, "user: " + username + ", " + "Specified centrality measure type is not valid for this request: " + centralityMeasureType.getDisplayName());
@@ -1632,45 +1487,37 @@ public Response calculateCentrality(
return requestHandler.writeError(Error.PARAMETER_INVALID, "Parameters are not valid.");
}
CentralityMap map;
- EntityManager em = entityHandler.getEntityManager();
- CustomGraphId id = new CustomGraphId(graphId, username);
+
synchronized(threadHandler) {
- EntityTransaction tx = em.getTransaction();
+
CustomGraph graph;
CentralityCreationLog log;
- try {
- tx.begin();
- graph = em.find(CustomGraph.class, id);
- if(graph == null) {
- requestHandler.log(Level.WARNING, "user: " + username + ", " + "Graph does not exist: graph id " + graphId);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph does not exist: graph id " + graphId);
- }
- if(graph.getCreationMethod().getStatus() != ExecutionStatus.COMPLETED) {
- requestHandler.log(Level.WARNING, "user: " + username + ", " + "Invalid graph creation method status for centrality algorithm execution: " + graph.getCreationMethod().getStatus().name());
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Invalid graph creation method status for centrality algorithm execution: " + graph.getCreationMethod().getStatus().name());
- }
- // Some centrality measures cannot be computed or do not give meaningful results on unconnected graphs
- if(algorithm.getCentralityMeasureType() == CentralityMeasureType.CURRENT_FLOW_BETWEENNESS || algorithm.getCentralityMeasureType() == CentralityMeasureType.CURRENT_FLOW_CLOSENESS || algorithm.getCentralityMeasureType() == CentralityMeasureType.ECCENTRICITY || algorithm.getCentralityMeasureType() == CentralityMeasureType.CLOSENESS_CENTRALITY) {
- if(!GraphChecker.isConnected((Graph)graph)) {
- return Response.serverError().entity("Show Error: This centrality measure can only be used on a connected network.").build();
- }
- }
- map = new CentralityMap(graph);
- map.setName(centralityMeasureType.getDisplayName());
- log = new CentralityCreationLog(centralityMeasureType, CentralityCreationType.CENTRALITY_MEASURE, parametersCopy, algorithm.compatibleGraphTypes());
- map.setCreationMethod(log);
- em.persist(map);
- tx.commit();
+ graph = database.getGraph(username, graphIdStr);
+ if(graph == null) {
+ requestHandler.log(Level.WARNING, "user: " + username + ", " + "Graph does not exist: graph id " + graphIdStr);
+ return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph does not exist: graph id " + graphIdStr);
}
- catch( RuntimeException e ) {
- if( tx != null && tx.isActive() ) {
- tx.rollback();
+ if(graph.getCreationMethod().getStatus() != ExecutionStatus.COMPLETED) {
+ requestHandler.log(Level.WARNING, "user: " + username + ", " + "Invalid graph creation method status for centrality algorithm execution: " + graph.getCreationMethod().getStatus().name());
+ return requestHandler.writeError(Error.PARAMETER_INVALID, "Invalid graph creation method status for centrality algorithm execution: " + graph.getCreationMethod().getStatus().name());
+ }
+ // Some centrality measures cannot be computed or do not give meaningful results on unconnected graphs
+ if(algorithm.getCentralityMeasureType() == CentralityMeasureType.CURRENT_FLOW_BETWEENNESS || algorithm.getCentralityMeasureType() == CentralityMeasureType.CURRENT_FLOW_CLOSENESS || algorithm.getCentralityMeasureType() == CentralityMeasureType.ECCENTRICITY || algorithm.getCentralityMeasureType() == CentralityMeasureType.CLOSENESS_CENTRALITY) {
+ ConnectedComponents ccAlgo = new ConnectedComponents(graph);
+ if(graph.getEdgeCount() < graph.getNodeCount() || ccAlgo.getGiantComponent().getNodeCount() != graph.getNodeCount()) { //I.e. the graph is not connected
+ return Response.serverError().entity("Show Error: This centrality measure can only be used on a connected network.").build();
}
- throw e;
- }
- em.close();
- /*
+ }
+ //System.out.println(centralityMeasureType.getId() + "Centrality Typ Name : " + centralityMeasureType.getDisplayName());
+ map = new CentralityMap(graph);
+ map.setName(centralityMeasureType.getDisplayName());
+ log = new CentralityCreationLog(centralityMeasureType, CentralityCreationType.CENTRALITY_MEASURE, parametersCopy, algorithm.compatibleGraphTypes());
+ //System.out.println(log.String());
+ map.setCreationMethod(log);
+ database.storeCentralityMap(map);
+ generalLogger.getLogger().log(Level.INFO, "user " + username + ": run centrality " + algorithm.getClass().getSimpleName() + " on graph " + graph.getId() +". Created centrality " + map.getKey());
+ /*
* Registers and starts algorithm
*/
threadHandler.runCentralityAlgorithm(map, algorithm);
@@ -1716,22 +1563,7 @@ public Response getCentralityMap(
{
try {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
- long graphId;
- try {
- graphId = Long.parseLong(graphIdStr);
- }
- catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph id is not valid.");
- }
- long mapId;
- try {
- mapId = Long.parseLong(mapIdStr);
- }
- catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Centrality map id is not valid.");
- }
+
CentralityOutputFormat format;
try {
format = CentralityOutputFormat.valueOf(centralityOutputFormatStr);
@@ -1755,10 +1587,11 @@ public Response getCentralityMap(
requestHandler.log(Level.WARNING, "user: " + username, e);
return requestHandler.writeError(Error.PARAMETER_INVALID, "Top nodes number is not valid.");
}
- CentralityMap map = entityHandler.getCentralityMap(username, graphId, mapId);
+ CentralityMap map = database.getCentralityMap(username, graphIdStr, mapIdStr); //done
if(onlyTopNodes && topNodesNumber != 0) {
return Response.ok(requestHandler.writeCentralityMapTopNodes(map, topNodesNumber)).build();
}
+ generalLogger.getLogger().log(Level.INFO, "user " + username + ": get centrality " + mapIdStr );
return Response.ok(requestHandler.writeCentralityMap(map, format)).build();
}
catch (Exception e) {
@@ -1792,25 +1625,9 @@ public Response deleteCentralityMap(
{
try {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
- long graphId;
- try {
- graphId = Long.parseLong(graphIdStr);
- }
- catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph id is not valid.");
- }
- long mapId;
- try {
- mapId = Long.parseLong(mapIdStr);
- }
- catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Centrality map id is not valid.");
- }
-
- entityHandler.deleteCentralityMap(username, graphId, mapId, threadHandler);
- return Response.ok(requestHandler.writeConfirmationXml()).build();
+ database.deleteCentralityMap(username, graphIdStr, mapIdStr, threadHandler);
+ generalLogger.getLogger().log(Level.INFO, "user " + username + ": delete centrality " + mapIdStr);
+ return Response.ok(requestHandler.writeConfirmationXml()).build();
}
catch (Exception e) {
requestHandler.log(Level.SEVERE, "", e);
@@ -1840,40 +1657,19 @@ public Response getAdjacencyMatrixEigenvalue(
double eigenvalue;
try {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
- long graphId;
- try {
- graphId = Long.parseLong(graphIdStr);
- }
- catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph id is not valid.");
- }
- EntityManager em = entityHandler.getEntityManager();
- CustomGraphId id = new CustomGraphId(graphId, username);
synchronized(threadHandler) {
- EntityTransaction tx = em.getTransaction();
+
CustomGraph graph;
- try {
- tx.begin();
- graph = em.find(CustomGraph.class, id);
- if(graph == null) {
- requestHandler.log(Level.WARNING, "user: " + username + ", " + "Graph does not exist: graph id " + graphId);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph does not exist: graph id " + graphId);
- }
- if(graph.getCreationMethod().getStatus() != ExecutionStatus.COMPLETED) {
- requestHandler.log(Level.WARNING, "user: " + username + ", " + "Invalid graph creation method status for eigenvalue calculation: " + graph.getCreationMethod().getStatus().name());
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Invalid graph creation method status for eigenvalue calculation: " + graph.getCreationMethod().getStatus().name());
- }
- tx.commit();
+ graph = database.getGraph(username, graphIdStr);
+ if(graph == null) {
+ requestHandler.log(Level.WARNING, "user: " + username + ", " + "Graph does not exist: graph id " + graphIdStr);
+ return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph does not exist: graph id " + graphIdStr);
+ }
+ if(graph.getCreationMethod().getStatus() != ExecutionStatus.COMPLETED) {
+ requestHandler.log(Level.WARNING, "user: " + username + ", " + "Invalid graph creation method status for eigenvalue calculation: " + graph.getCreationMethod().getStatus().name());
+ return requestHandler.writeError(Error.PARAMETER_INVALID, "Invalid graph creation method status for eigenvalue calculation: " + graph.getCreationMethod().getStatus().name());
}
- catch( RuntimeException e ) {
- if( tx != null && tx.isActive() ) {
- tx.rollback();
- }
- throw e;
- }
- em.close();
eigenvalue = MatrixOperations.calculateAbsolutePrincipalEigenvalue(graph.getNeighbourhoodMatrix());
}
return Response.ok(requestHandler.writeValueXml(eigenvalue)).build();
@@ -1917,18 +1713,12 @@ public Response runCentralitySimulation(
@DefaultValue("SIR Simulation") @QueryParam("simulation") String simulationTypeStr, String content)
{
try {
- long graphId;
+
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
CentralitySimulationType simulationType;
CentralitySimulation simulation;
try {
- graphId = Long.parseLong(graphIdStr);
- }
- catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph id is not valid.");
- }
- try {
+
simulationType = CentralitySimulationType.valueOf(simulationTypeStr);
}
catch (Exception e) {
@@ -1949,25 +1739,24 @@ public Response runCentralitySimulation(
return requestHandler.writeError(Error.PARAMETER_INVALID, "Parameters are not valid.");
}
CentralityMap map;
- EntityManager em = entityHandler.getEntityManager();
- CustomGraphId id = new CustomGraphId(graphId, username);
+
synchronized(threadHandler) {
- EntityTransaction tx = em.getTransaction();
+
CustomGraph graph;
CentralityCreationLog log;
try {
- tx.begin();
- graph = em.find(CustomGraph.class, id);
+ graph = database.getGraph(username, graphIdStr); //done
if(graph == null) {
- requestHandler.log(Level.WARNING, "user: " + username + ", " + "Graph does not exist: graph id " + graphId);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph does not exist: graph id " + graphId);
+ requestHandler.log(Level.WARNING, "user: " + username + ", " + "Graph does not exist: graph id " + graphIdStr);
+ return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph does not exist: graph id " + graphIdStr);
}
if(graph.getCreationMethod().getStatus() != ExecutionStatus.COMPLETED) {
requestHandler.log(Level.WARNING, "user: " + username + ", " + "Invalid graph creation method status for simulation execution: " + graph.getCreationMethod().getStatus().name());
return requestHandler.writeError(Error.PARAMETER_INVALID, "Invalid graph creation method status for simulation execution: " + graph.getCreationMethod().getStatus().name());
}
- if(simulation.getSimulationType() == CentralitySimulationType.RANDOM_PACKAGE_TRANSMISSION_UNWEIGHTED) {
- if(!GraphChecker.isConnected((Graph)graph)) {
+ if(simulation.getSimulationType() == CentralitySimulationType.RANDOM_PACKAGE_TRANSMISSION_UNWEIGHTED) {
+ ConnectedComponents ccAlgo = new ConnectedComponents(graph);
+ if(graph.getEdgeCount() < graph.getNodeCount() || ccAlgo.getGiantComponent().getNodeCount() != graph.getNodeCount()) { //I.e. the graph is not connected
return Response.serverError().entity("Show Error: This simulation can only be used on a connected network.").build();
}
}
@@ -1975,21 +1764,19 @@ public Response runCentralitySimulation(
map.setName(simulationType.getDisplayName());
log = new CentralityCreationLog(simulationType, CentralityCreationType.SIMULATION, parametersCopy, simulation.compatibleGraphTypes());
map.setCreationMethod(log);
- em.persist(map);
- tx.commit();
+ database.storeCentralityMap(map); //done
}
catch( RuntimeException e ) {
- if( tx != null && tx.isActive() ) {
- tx.rollback();
- }
+
throw e;
}
- em.close();
+
/*
* Registers and starts algorithm
*/
threadHandler.runCentralitySimulation(map, simulation);
- }
+ generalLogger.getLogger().log(Level.INFO, "user " + username + ": run simulation " + simulationTypeStr + " on graph " + graphIdStr + " with paramneters: " + parameters );
+ }
return Response.ok(requestHandler.writeId(map)).build();
}
catch (Exception e) {
@@ -2030,63 +1817,37 @@ public Response getAverageCentralityMap(
@QueryParam("mapName") String averageMapName) {
try {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
- long graphId;
- try {
- graphId = Long.parseLong(graphIdStr);
- }
- catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph id is not valid.");
- }
+
CustomGraph graph;
- EntityManager em = entityHandler.getEntityManager();
- CustomGraphId gId = new CustomGraphId(graphId, username);
+
+ CustomGraphId gId = new CustomGraphId(graphIdStr, username);
synchronized(threadHandler) {
- EntityTransaction tx = em.getTransaction();
try {
- tx.begin();
- graph = em.find(CustomGraph.class, gId);
+ graph = database.getGraph(username, graphIdStr);
if(graph == null) {
- requestHandler.log(Level.WARNING, "user: " + username + ", " + "Graph does not exist: graph id " + graphId);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph does not exist: graph id " + graphId);
+ requestHandler.log(Level.WARNING, "user: " + username + ", " + "Graph does not exist: graph id " + graphIdStr);
+ return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph does not exist: graph id " + graphIdStr);
}
if(graph.getCreationMethod().getStatus() != ExecutionStatus.COMPLETED) {
requestHandler.log(Level.WARNING, "user: " + username + ", " + "Invalid graph creation method status for centrality calculation: " + graph.getCreationMethod().getStatus().name());
return requestHandler.writeError(Error.PARAMETER_INVALID, "Invalid graph creation method status for centrality calculation: " + graph.getCreationMethod().getStatus().name());
}
- tx.commit();
+
}
catch( RuntimeException e ) {
- if( tx != null && tx.isActive() ) {
- tx.rollback();
- }
+
throw e;
}
- em.close();
+
}
-
- List maps = new LinkedList();
- for(int id : ids) {
- long mapId = (long) id;
- em = entityHandler.getEntityManager();
- CentralityMapId cId = new CentralityMapId(mapId, gId);
-
- EntityTransaction tx = em.getTransaction();
- CentralityMap map;
- try {
- tx.begin();
- map = em.find(CentralityMap.class, cId);
- tx.commit();
- }
- catch( RuntimeException e ) {
- if( tx != null && tx.isActive() ) {
- tx.rollback();
- }
- throw e;
- }
+
+ List maps = new LinkedList();
+ for(int id : ids) {
+ String mapIdStr = Integer.toString(id);
+ CentralityMap map = database.getCentralityMap(username, graphIdStr, mapIdStr);
if(map == null) {
- requestHandler.log(Level.WARNING, "user: " + username + ", " + "Centrality map does not exist: Centrality map id " + mapId + ", graph id " + graphId);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Centrality map does not exist: Centrality map id " + mapId + ", graph id " + graphId);
+ requestHandler.log(Level.WARNING, "user: " + username + ", " + "Centrality map does not exist: Centrality map id " + mapIdStr + ", graph id " + graphIdStr);
+ return requestHandler.writeError(Error.PARAMETER_INVALID, "Centrality map does not exist: Centrality map id " + mapIdStr + ", graph id " + graphIdStr);
}
maps.add(map);
}
@@ -2095,24 +1856,15 @@ public Response getAverageCentralityMap(
Map parameters = new HashMap();
parameters.put("Number of measures", Integer.toString(ids.size()));
synchronized(threadHandler) {
- EntityTransaction tx = em.getTransaction();
- try {
- tx.begin();
- log = new CentralityCreationLog(CentralityMeasureType.UNDEFINED, CentralityCreationType.AVERAGE, parameters, new HashSet(Arrays.asList(GraphType.values())));
- averageMap.setCreationMethod(log);
- averageMap.setName(averageMapName);
- em.persist(averageMap);
- tx.commit();
- }
- catch( RuntimeException e ) {
- if( tx != null && tx.isActive() ) {
- tx.rollback();
- }
- throw e;
- }
- em.close();
- threadHandler.createCentralityMap(averageMap, new CentralityMapId(averageMap.getId(), new CustomGraphId(graphId, username)), false);
- }
+ log = new CentralityCreationLog(CentralityMeasureType.UNDEFINED, CentralityCreationType.AVERAGE, parameters, new HashSet(Arrays.asList(GraphType.values())));
+ averageMap.setCreationMethod(log);
+ averageMap.setName(averageMapName);
+ database.storeCentralityMap(averageMap);
+ //System.out.println(log.String());
+ threadHandler.createCentralityMap(averageMap, new CentralityMapId(averageMap.getKey(), gId), false); // 444 should be " new CustomGraphId(graphId, username)" instead of gid
+ generalLogger.getLogger().log(Level.INFO, "user " + username + ": calculate average " + averageMap +" for centrality maps: " + ids );
+
+ }
return Response.ok(requestHandler.writeId(averageMap)).build();
}
@@ -2158,67 +1910,36 @@ public Response getCorrelation(
requestHandler.log(Level.WARNING, "user: " + username, e);
return requestHandler.writeError(Error.PARAMETER_INVALID, "Specified correlation coefficient does not exist.");
}
- long graphId;
- try {
- graphId = Long.parseLong(graphIdStr);
- }
- catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph id is not valid.");
- }
+
CustomGraph graph;
- EntityManager em = entityHandler.getEntityManager();
- CustomGraphId gId = new CustomGraphId(graphId, username);
+
synchronized(threadHandler) {
- EntityTransaction tx = em.getTransaction();
- try {
- tx.begin();
- graph = em.find(CustomGraph.class, gId);
- if(graph == null) {
- requestHandler.log(Level.WARNING, "user: " + username + ", " + "Graph does not exist: graph id " + graphId);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph does not exist: graph id " + graphId);
- }
- if(graph.getCreationMethod().getStatus() != ExecutionStatus.COMPLETED) {
- requestHandler.log(Level.WARNING, "user: " + username + ", " + "Invalid graph creation method status for correlation calculation: " + graph.getCreationMethod().getStatus().name());
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Invalid graph creation method status for correlation calculation: " + graph.getCreationMethod().getStatus().name());
- }
- tx.commit();
- }
- catch( RuntimeException e ) {
- if( tx != null && tx.isActive() ) {
- tx.rollback();
- }
- throw e;
- }
- em.close();
+ graph = database.getGraph(username, graphIdStr);
+ if(graph == null) {
+ requestHandler.log(Level.WARNING, "user: " + username + ", " + "Graph does not exist: graph id " + graphIdStr);
+ return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph does not exist: graph id " + graphIdStr);
+ }
+ if(graph.getCreationMethod().getStatus() != ExecutionStatus.COMPLETED) {
+ requestHandler.log(Level.WARNING, "user: " + username + ", " + "Invalid graph creation method status for correlation calculation: " + graph.getCreationMethod().getStatus().name());
+ return requestHandler.writeError(Error.PARAMETER_INVALID, "Invalid graph creation method status for correlation calculation: " + graph.getCreationMethod().getStatus().name());
+ }
+
}
List maps = new ArrayList();
for(int id : mapIds) {
- long mapId = (long) id;
- em = entityHandler.getEntityManager();
- CentralityMapId cId = new CentralityMapId(mapId, gId);
-
- EntityTransaction tx = em.getTransaction();
+ String mapIdStr = Integer.toString(id); //TODO unschoener typecast von begin an Strings in request verwenden
CentralityMap map;
- try {
- tx.begin();
- map = em.find(CentralityMap.class, cId);
- tx.commit();
- }
- catch( RuntimeException e ) {
- if( tx != null && tx.isActive() ) {
- tx.rollback();
- }
- throw e;
- }
+
+ map = database.getCentralityMap(username, graphIdStr, mapIdStr);
if(map == null) {
- requestHandler.log(Level.WARNING, "user: " + username + ", " + "Centrality map does not exist: Centrality map id " + mapId + ", graph id " + graphId);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Centrality map does not exist: Centrality map id " + mapId + ", graph id " + graphId);
+ requestHandler.log(Level.WARNING, "user: " + username + ", " + "Centrality map does not exist: Centrality map id " + mapIdStr + ", graph id " + graphIdStr);
+ return requestHandler.writeError(Error.PARAMETER_INVALID, "Centrality map does not exist: Centrality map id " + mapIdStr + ", graph id " + graphIdStr);
}
maps.add(map);
}
- RealMatrix correlationMatrix = StatisticalProcessor.getCorrelation(graph, maps, correlationCoefficient);
- return Response.ok(requestHandler.writeCorrelationMatrix(mapIds, correlationMatrix)).build();
+ RealMatrix correlationMatrix = StatisticalProcessor.getCorrelation(graph, maps, correlationCoefficient);
+ //generalLogger.getLogger().log(Level.INFO, "user " + username + " calculate" + correlationCoefficientStr + " correlation on centrality maps:" + mapIds );
+ return Response.ok(requestHandler.writeCorrelationMatrix(mapIds, correlationMatrix)).build();
}
catch (Exception e) {
requestHandler.log(Level.SEVERE, "", e);
@@ -2261,68 +1982,33 @@ public Response getPrecision(
requestHandler.log(Level.WARNING, "user: " + username, e);
return requestHandler.writeError(Error.PARAMETER_INVALID, "Parameter k is not valid.");
}
- long graphId;
- try {
- graphId = Long.parseLong(graphIdStr);
- }
- catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph id is not valid.");
- }
+
CustomGraph graph;
- EntityManager em = entityHandler.getEntityManager();
- CustomGraphId gId = new CustomGraphId(graphId, username);
synchronized(threadHandler) {
- EntityTransaction tx = em.getTransaction();
- try {
- tx.begin();
- graph = em.find(CustomGraph.class, gId);
- if(graph == null) {
- requestHandler.log(Level.WARNING, "user: " + username + ", " + "Graph does not exist: graph id " + graphId);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph does not exist: graph id " + graphId);
- }
- if(graph.getCreationMethod().getStatus() != ExecutionStatus.COMPLETED) {
- requestHandler.log(Level.WARNING, "user: " + username + ", " + "Invalid graph creation method status for correlation calculation: " + graph.getCreationMethod().getStatus().name());
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Invalid graph creation method status for correlation calculation: " + graph.getCreationMethod().getStatus().name());
- }
- tx.commit();
- }
- catch( RuntimeException e ) {
- if( tx != null && tx.isActive() ) {
- tx.rollback();
- }
- throw e;
- }
- em.close();
+ graph = database.getGraph(username, graphIdStr);
+ if(graph == null) {
+ requestHandler.log(Level.WARNING, "user: " + username + ", " + "Graph does not exist: graph id " + graphIdStr);
+ return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph does not exist: graph id " + graphIdStr);
+ }
+ if(graph.getCreationMethod().getStatus() != ExecutionStatus.COMPLETED) {
+ requestHandler.log(Level.WARNING, "user: " + username + ", " + "Invalid graph creation method status for correlation calculation: " + graph.getCreationMethod().getStatus().name());
+ return requestHandler.writeError(Error.PARAMETER_INVALID, "Invalid graph creation method status for correlation calculation: " + graph.getCreationMethod().getStatus().name());
+ }
}
List maps = new ArrayList();
for(int id : mapIds) {
- long mapId = (long) id;
- em = entityHandler.getEntityManager();
- CentralityMapId cId = new CentralityMapId(mapId, gId);
-
- EntityTransaction tx = em.getTransaction();
- CentralityMap map;
- try {
- tx.begin();
- map = em.find(CentralityMap.class, cId);
- tx.commit();
- }
- catch( RuntimeException e ) {
- if( tx != null && tx.isActive() ) {
- tx.rollback();
- }
- throw e;
- }
+ String mapIdStr = Integer.toString(id);
+ CentralityMap map = database.getCentralityMap(username, graphIdStr, mapIdStr);
if(map == null) {
- requestHandler.log(Level.WARNING, "user: " + username + ", " + "Centrality map does not exist: Centrality map id " + mapId + ", graph id " + graphId);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Centrality map does not exist: Centrality map id " + mapId + ", graph id " + graphId);
+ requestHandler.log(Level.WARNING, "user: " + username + ", " + "Centrality map does not exist: Centrality map id " + mapIdStr + ", graph id " + graphIdStr);
+ return requestHandler.writeError(Error.PARAMETER_INVALID, "Centrality map does not exist: Centrality map id " + mapIdStr + ", graph id " + graphIdStr);
}
maps.add(map);
}
CentralityMap groundTruthMap = maps.get(0);
maps = maps.subList(1, maps.size());
- double[] precisionVector = StatisticalProcessor.getPrecision(graph, groundTruthMap, maps, k);
+ //generalLogger.getLogger().log(Level.INFO, "user " + username + ": calculate top" + k + " precision using centralities" + mapIds + " based on " + graphIdStr);
+ double[] precisionVector = StatisticalProcessor.getPrecision(graph, groundTruthMap, maps, k);
return Response.ok(requestHandler.writePrecisionResult(maps, precisionVector)).build();
}
catch (Exception e) {
@@ -2367,6 +2053,20 @@ public Response runGroundTruthBenchmark(@DefaultValue("unnamed") @QueryParam("co
@DefaultValue("LFR") @QueryParam("benchmark") String creationTypeStr, String contentStr) {
try {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
+
+ /*
+ Check if user has a limit regarding number of graph or covers and throw an error if the limit is violated.
+ */
+ if (userLimitsHandler.reachedGraphCountLimit(username)){
+ requestHandler.log(Level.WARNING, "user: " + username + " reached graph count limit.");
+ return requestHandler.writeError(Error.INTERNAL, "Graph count limit reached. Delete a graph before generating a new one, or contact administrator to adjust limits.");
+ }
+ if (userLimitsHandler.reachedCoverCountLimit(username)){
+ requestHandler.log(Level.WARNING, "user: " + username + " reached cover count limit.");
+ return requestHandler.writeError(Error.INTERNAL, "Cover count limit reached. Delete a cover before generating a new one, or contact administrator to adjust limits.");
+ }
+
+
GraphCreationType benchmarkType;
CoverCreationType coverCreationType;
try {
@@ -2391,45 +2091,48 @@ public Response runGroundTruthBenchmark(@DefaultValue("unnamed") @QueryParam("co
} else {
try {
parameters = requestHandler.parseParameters(contentStr);
+
+ /*
+ Check if there is a limit on the graph size for the user and if this limit is violated
+ */
+ if (parameters.get("n") != null){
+ // limits set for user in userLimitInformation.json file
+ JSONObject userLimits = userLimitsHandler.getUserLimits(username);
+ if ( userLimits != null && userLimits.get("graphSize") != null &&
+ Integer.parseInt((String) userLimits.get("graphSize")) < Integer.parseInt(parameters.get("n"))){
+ requestHandler.log(Level.WARNING, "user: " + username + " is not allowed to generate graph of size " + parameters.get("n"));
+ return requestHandler.writeError(Error.INTERNAL, "Graph size is above the user's limit, contact administrator to adjust limits");
+ }
+ }
+
benchmark = (GroundTruthBenchmark) benchmarkFactory.getInstance(benchmarkType, parameters);
} catch (Exception e) {
requestHandler.log(Level.WARNING, "user: " + username, e);
return requestHandler.writeError(Error.PARAMETER_INVALID, "Parameters are not valid.");
}
}
- EntityManager em = entityHandler.getEntityManager();
+
CustomGraph graph = new CustomGraph();
graph.setName(URLDecoder.decode(graphNameStr, "UTF-8"));
graph.setUserName(username);
GraphCreationLog log = new GraphCreationLog(benchmarkType, parameters);
log.setStatus(ExecutionStatus.WAITING);
graph.setCreationMethod(log);
- Cover cover = new Cover(graph, new CCSMatrix(graph.nodeCount(), 0));
+ Cover cover = new Cover(graph, new CCSMatrix(graph.getNodeCount(), 0));
cover.setName(URLDecoder.decode(coverNameStr, "UTF-8"));
CoverCreationLog coverLog = new CoverCreationLog(coverCreationType, parameters,
new HashSet());
coverLog.setStatus(ExecutionStatus.WAITING);
cover.setCreationMethod(coverLog);
synchronized (threadHandler) {
-
- EntityTransaction tx = em.getTransaction();
- try {
- tx.begin();
- em.persist(graph);
- em.persist(cover);
- tx.commit();
- } catch (RuntimeException e) {
- if (tx != null && tx.isActive()) {
- tx.rollback();
- }
- throw e;
- }
- em.close();
+ System.out.println("GraphKey : " + database.storeGraph(graph)); //TODO beides in einer transaktion
+ System.out.println("CoverKey : " + database.storeCover(cover));
/*
* Registers and starts benchmark creation.
*/
threadHandler.runGroundTruthBenchmark(cover, benchmark);
- }
+ generalLogger.getLogger().log(Level.INFO, "user " + username + ": run " + creationTypeStr + " benchmark. Created graph " + graph.getKey() + ", cover " + cover.getKey());
+ }
return Response.ok(requestHandler.writeId(cover)).build();
} catch (Exception e) {
requestHandler.log(Level.SEVERE, "", e);
@@ -2474,20 +2177,7 @@ public Response runStatisticalMeasure(@PathParam("coverId") String coverIdStr,
String contentStr) {
try {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
- long graphId;
- try {
- graphId = Long.parseLong(graphIdStr);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph id is not valid.");
- }
- long coverId;
- try {
- coverId = Long.parseLong(coverIdStr);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Cover id is not valid.");
- }
+
OcdMetricType metricType;
try {
metricType = OcdMetricType.valueOf(metricTypeStr);
@@ -2516,80 +2206,70 @@ public Response runStatisticalMeasure(@PathParam("coverId") String coverIdStr,
return requestHandler.writeError(Error.PARAMETER_INVALID, "Parameters are not valid.");
}
}
-
- EntityManager em = entityHandler.getEntityManager();
- CustomGraphId gId = new CustomGraphId(graphId, username);
- CoverId cId = new CoverId(coverId, gId);
+
/*
* Finds cover
*/
OcdMetricLog log;
synchronized (threadHandler) {
- EntityTransaction tx = em.getTransaction();
+
Cover cover;
- try {
- tx.begin();
- cover = em.find(Cover.class, cId);
- if (cover == null) {
- requestHandler.log(Level.WARNING, "user: " + username + ", "
- + "Cover does not exist: cover id " + coverId + ", graph id " + graphId);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Cover does not exist.");
- }
- if (cover.getCreationMethod().getStatus() != ExecutionStatus.COMPLETED) {
- requestHandler.log(Level.WARNING,
- "user: " + username + ", "
- + "Invalid cover creation method status for metric execution: "
- + cover.getCreationMethod().getStatus().name());
- return requestHandler.writeError(Error.PARAMETER_INVALID,
- "Invalid cover creation method status for metric execution: "
- + cover.getCreationMethod().getStatus().name());
- }
-
- boolean compatibleType = false;
- if(cover.getGraph().getTypes().isEmpty())
- {
- compatibleType = true;
- }
- else {
- for(GraphType type : cover.getGraph().getTypes()) {
- if(metric.compatibleGraphTypes().contains(type))
- {
- compatibleType = true;
- break;
- }
- }
+ cover = database.getCover(username, graphIdStr, coverIdStr); //done
+ if (cover == null) {
+ requestHandler.log(Level.WARNING, "user: " + username + ", "
+ + "Cover does not exist: cover id " + coverIdStr + ", graph id " + graphIdStr);
+ return requestHandler.writeError(Error.PARAMETER_INVALID, "Cover does not exist.");
+ }
+ if (cover.getCreationMethod().getStatus() != ExecutionStatus.COMPLETED) {
+ requestHandler.log(Level.WARNING,
+ "user: " + username + ", "
+ + "Invalid cover creation method status for metric execution: "
+ + cover.getCreationMethod().getStatus().name());
+ return requestHandler.writeError(Error.PARAMETER_INVALID,
+ "Invalid cover creation method status for metric execution: "
+ + cover.getCreationMethod().getStatus().name());
+ }
+
+ boolean compatibleType = false;
+ if(cover.getGraph().getTypes().isEmpty())
+ {
+ compatibleType = true;
+ }
+ else {
+ for(GraphType type : cover.getGraph().getTypes()) {
+ if(metric.compatibleGraphTypes().contains(type))
+ {
+ compatibleType = true;
+ break;
+ }
}
- if(!compatibleType) {
- requestHandler.log(Level.WARNING,
- "user: " + username + ", "
- + "Metric not applicable with graph, needs one of these types: "
- + metric.compatibleGraphTypes().toString());
- return requestHandler.writeError(Error.PARAMETER_INVALID,
- "Metric not applicable with graph, needs one of these types: " + metric.compatibleGraphTypes().toString());
- }
- else if (metric instanceof NewmanModularityCombined && !cover.getGraph().isOfType(GraphType.CONTENT_LINKED) && !cover.getGraph().isOfType(GraphType.CONTENT_UNLINKED))
- {
- requestHandler.log(Level.WARNING,
- "user: " + username + ", "
- + "Metric not applicable with graph, needs to be a graph with node content "
- + metric.compatibleGraphTypes().toString());
- return requestHandler.writeError(Error.PARAMETER_INVALID,
- "Metric not applicable with graph, needs to be a graph with node content");
- }
-
- log = new OcdMetricLog(metricType, 0, parameters, cover);
- log.setStatus(ExecutionStatus.WAITING);
- cover.addMetric(log);
- tx.commit();
- } catch (RuntimeException e) {
- if (tx != null && tx.isActive()) {
- tx.rollback();
- }
- throw e;
- }
+ }
+ if(!compatibleType) {
+ requestHandler.log(Level.WARNING,
+ "user: " + username + ", "
+ + "Metric not applicable with graph, needs one of these types: "
+ + metric.compatibleGraphTypes().toString());
+ return requestHandler.writeError(Error.PARAMETER_INVALID,
+ "Metric not applicable with graph, needs one of these types: " + metric.compatibleGraphTypes().toString());
+ }
+ else if (metric instanceof NewmanModularityCombined && !cover.getGraph().isOfType(GraphType.CONTENT_LINKED) && !cover.getGraph().isOfType(GraphType.CONTENT_UNLINKED))
+ {
+ requestHandler.log(Level.WARNING,
+ "user: " + username + ", "
+ + "Metric not applicable with graph, needs to be a graph with node content "
+ + metric.compatibleGraphTypes().toString());
+ return requestHandler.writeError(Error.PARAMETER_INVALID,
+ "Metric not applicable with graph, needs to be a graph with node content");
+ }
+ log = new OcdMetricLog(metricType, 0, parameters, cover);
+ log.setStatus(ExecutionStatus.WAITING);
+ cover.addMetric(log);
+ database.updateCover(cover); //TODO hier muss eine funktion hin, die ein bestehendes cover aendert
threadHandler.runStatisticalMeasure(log, metric, cover);
- }
-
+ generalLogger.getLogger().log(Level.INFO, "user " + username + ": run statistical measure " + metricTypeStr + " on cover " + coverIdStr + " with parameters " + parameters);
+
+ }
+
return Response.ok(requestHandler.writeId(log)).build();
} catch (Exception e) {
requestHandler.log(Level.SEVERE, "", e);
@@ -2635,27 +2315,7 @@ public Response runKnowledgeDrivenMeasure(@PathParam("coverId") String coverIdSt
@PathParam("groundTruthCoverId") String groundTruthCoverIdStr, String contentStr) {
try {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
- long graphId;
- try {
- graphId = Long.parseLong(graphIdStr);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph id is not valid.");
- }
- long coverId;
- try {
- coverId = Long.parseLong(coverIdStr);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Cover id is not valid.");
- }
- long groundTruthCoverId;
- try {
- groundTruthCoverId = Long.parseLong(groundTruthCoverIdStr);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Ground truth cover id is not valid.");
- }
+
OcdMetricType metricType;
try {
metricType = OcdMetricType.valueOf(metricTypeStr);
@@ -2684,70 +2344,64 @@ public Response runKnowledgeDrivenMeasure(@PathParam("coverId") String coverIdSt
return requestHandler.writeError(Error.PARAMETER_INVALID, "Parameters are not valid.");
}
}
- EntityManager em = entityHandler.getEntityManager();
- CustomGraphId gId = new CustomGraphId(graphId, username);
- CoverId cId = new CoverId(coverId, gId);
- CoverId gtId = new CoverId(groundTruthCoverId, gId);
+
/*
* Finds cover
*/
OcdMetricLog log;
synchronized (threadHandler) {
- EntityTransaction tx = em.getTransaction();
Cover cover;
Cover groundTruth;
- try {
- tx.begin();
- cover = em.find(Cover.class, cId);
- if (cover == null) {
- requestHandler.log(Level.WARNING, "user: " + username + ", "
- + "Cover does not exist: cover id " + coverId + ", graph id " + graphId);
- return requestHandler.writeError(Error.PARAMETER_INVALID,
- "Cover does not exist: cover id " + coverId + ", graph id " + graphId);
- }
- if (cover.getCreationMethod().getStatus() != ExecutionStatus.COMPLETED) {
- requestHandler.log(Level.WARNING,
- "user: " + username + ", "
- + "Invalid cover creation method status for metric execution: "
- + cover.getCreationMethod().getStatus().name());
- return requestHandler.writeError(Error.PARAMETER_INVALID,
- "Invalid cover creation method status for metric execution: "
- + cover.getCreationMethod().getStatus().name());
- }
- if (groundTruthCoverId != coverId) {
- groundTruth = em.find(Cover.class, gtId);
- if (groundTruth == null) {
- requestHandler.log(Level.WARNING,
- "user: " + username + ", " + "Ground truth cover does not exist: cover id "
- + groundTruthCoverId + ", graph id " + graphId);
- return requestHandler.writeError(Error.PARAMETER_INVALID,
- "Ground truth cover does not exist: cover id " + groundTruthCoverId
- + ", graph id " + graphId);
- }
- } else {
- groundTruth = cover;
- }
- if (groundTruth.getCreationMethod().getStatus() != ExecutionStatus.COMPLETED) {
- requestHandler.log(Level.WARNING,
- "user: " + username + ", "
- + "Invalid ground truth cover creation method status for metric execution: "
- + groundTruth.getCreationMethod().getStatus().name());
- return requestHandler.writeError(Error.PARAMETER_INVALID,
- "Invalid ground truth cover creation method status for metric execution: "
- + groundTruth.getCreationMethod().getStatus().name());
- }
- log = new OcdMetricLog(metricType, 0, parameters, cover);
- log.setStatus(ExecutionStatus.WAITING);
- cover.addMetric(log);
- tx.commit();
- } catch (RuntimeException e) {
- if (tx != null && tx.isActive()) {
- tx.rollback();
- }
- throw e;
- }
+
+ cover = database.getCover(username, graphIdStr, coverIdStr);
+ if (cover == null) {
+ requestHandler.log(Level.WARNING, "user: " + username + ", "
+ + "Cover does not exist: cover id " + coverIdStr + ", graph id " + graphIdStr);
+ return requestHandler.writeError(Error.PARAMETER_INVALID,
+ "Cover does not exist: cover id " + coverIdStr + ", graph id " + graphIdStr);
+ }
+ if (cover.getCreationMethod().getStatus() != ExecutionStatus.COMPLETED) {
+ requestHandler.log(Level.WARNING,
+ "user: " + username + ", "
+ + "Invalid cover creation method status for metric execution: "
+ + cover.getCreationMethod().getStatus().name());
+ return requestHandler.writeError(Error.PARAMETER_INVALID,
+ "Invalid cover creation method status for metric execution: "
+ + cover.getCreationMethod().getStatus().name());
+ }
+ if (!groundTruthCoverIdStr.equals(coverIdStr)) {
+
+ //System.out.println("Cover und GT are not equal");
+ groundTruth = database.getCover(username, graphIdStr, groundTruthCoverIdStr);
+ if (groundTruth == null) {
+ requestHandler.log(Level.WARNING,
+ "user: " + username + ", " + "Ground truth cover does not exist: cover id "
+ + groundTruthCoverIdStr + ", graph id " + graphIdStr);
+ return requestHandler.writeError(Error.PARAMETER_INVALID,
+ "Ground truth cover does not exist: cover id " + groundTruthCoverIdStr
+ + ", graph id " + graphIdStr);
+ }
+ } else {
+ //System.out.println("Cover und GT are equal : Cover :" + coverIdStr + " GroundTruth :" + groundTruthCoverIdStr);
+ groundTruth = cover;
+ }
+ if (groundTruth.getCreationMethod().getStatus() != ExecutionStatus.COMPLETED) {
+ requestHandler.log(Level.WARNING,
+ "user: " + username + ", "
+ + "Invalid ground truth cover creation method status for metric execution: "
+ + groundTruth.getCreationMethod().getStatus().name());
+ return requestHandler.writeError(Error.PARAMETER_INVALID,
+ "Invalid ground truth cover creation method status for metric execution: "
+ + groundTruth.getCreationMethod().getStatus().name());
+ }
+ log = new OcdMetricLog(metricType, 0, parameters, cover);
+ log.setStatus(ExecutionStatus.WAITING);
+ cover.addMetric(log);
+
+ database.updateCover(cover); //done ?
threadHandler.runKnowledgeDrivenMeasure(log, metric, cover, groundTruth);
- }
+ generalLogger.getLogger().log(Level.INFO, "user " + username + ": run knowledge driven measure " + metricTypeStr + " on cover " + coverIdStr + " with parameters " + parameters);
+ }
return Response.ok(requestHandler.writeId(log)).build();
} catch (Exception e) {
requestHandler.log(Level.SEVERE, "", e);
@@ -2777,54 +2431,23 @@ public Response deleteMetric(@PathParam("coverId") String coverIdStr, @PathParam
@PathParam("metricId") String metricIdStr) {
try {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
- long graphId;
- try {
- graphId = Long.parseLong(graphIdStr);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph id is not valid.");
- }
- long coverId;
- try {
- coverId = Long.parseLong(coverIdStr);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Cover id is not valid.");
- }
- long metricId;
- try {
- metricId = Long.parseLong(metricIdStr);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Metric id is not valid.");
- }
- EntityManager em = entityHandler.getEntityManager();
- CustomGraphId gId = new CustomGraphId(graphId, username);
- CoverId cId = new CoverId(coverId, gId);
- OcdMetricLogId mId = new OcdMetricLogId(metricId, cId);
- EntityTransaction tx = em.getTransaction();
+
+ CustomGraphId gId = new CustomGraphId(graphIdStr, username);
+ CoverId cId = new CoverId(coverIdStr, gId);
+ OcdMetricLogId mId = new OcdMetricLogId(metricIdStr, cId);
OcdMetricLog log;
/*
* Deletes the metric.
*/
synchronized (threadHandler) {
- tx = em.getTransaction();
- try {
- tx.begin();
- log = em.find(OcdMetricLog.class, mId);
- tx.commit();
- } catch (RuntimeException e) {
- if (tx != null && tx.isActive()) {
- tx.rollback();
- }
- throw e;
- }
+
+ log = database.getOcdMetricLog(username, graphIdStr, coverIdStr, metricIdStr);
if (log == null) {
requestHandler.log(Level.WARNING,
- "user: " + username + ", " + "Metric does not exist: cover id " + coverId
- + ", graph id " + graphId + ", metric id " + metricId);
+ "user: " + username + ", " + "Metric does not exist: cover id " + coverIdStr
+ + ", graph id " + graphIdStr + ", metric id " + metricIdStr);
return requestHandler.writeError(Error.PARAMETER_INVALID, "Metric does not exist: cover id "
- + coverId + ", graph id " + graphId + ", metric id " + metricId);
+ + coverIdStr + ", graph id " + graphIdStr + ", metric id " + metricIdStr);
}
/*
* Interrupts metric.
@@ -2833,20 +2456,11 @@ public Response deleteMetric(@PathParam("coverId") String coverIdStr, @PathParam
/*
* Removes metric
*/
- tx = em.getTransaction();
- try {
- tx.begin();
- log.getCover().removeMetric(log);
- em.remove(log);
- tx.commit();
- } catch (RuntimeException e) {
- if (tx != null && tx.isActive()) {
- tx.rollback();
- }
- throw e;
- }
- em.close();
- return Response.ok(requestHandler.writeConfirmationXml()).build();
+ Cover cover = log.getCover();
+ cover.removeMetric(log);
+ database.updateCover(cover);
+ generalLogger.getLogger().log(Level.INFO, "user " + username + ": delete metric " + coverIdStr);
+ return Response.ok(requestHandler.writeConfirmationXml()).build();
}
} catch (Exception e) {
requestHandler.log(Level.SEVERE, "", e);
@@ -2900,21 +2514,9 @@ public Response getCoverVisualization(@PathParam("graphId") String graphIdStr,
@DefaultValue("20") @QueryParam("minNodeSize") String minNodeSizeStr,
@DefaultValue("45") @QueryParam("maxNodeSize") String maxNodeSizeStr) {
try {
- long graphId;
+
String username = getUserName();
- try {
- graphId = Long.parseLong(graphIdStr);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph id is not valid.");
- }
- long coverId;
- try {
- coverId = Long.parseLong(coverIdStr);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Cover id is not valid.");
- }
+
double minNodeSize;
try {
minNodeSize = Double.parseDouble(minNodeSizeStr);
@@ -2972,31 +2574,18 @@ public Response getCoverVisualization(@PathParam("graphId") String graphIdStr,
return requestHandler.writeError(Error.PARAMETER_INVALID, "Label edges is not a boolean value.");
}
- Cover cover = entityHandler.getCover(username, graphId, coverId);
+ Cover cover = database.getCover(username, graphIdStr, coverIdStr); //done
if (cover == null) {
requestHandler.log(Level.WARNING, "user: " + username + ", " + "Cover does not exist: cover id "
- + coverId + ", graph id " + graphId);
+ + coverIdStr + ", graph id " + graphIdStr);
return requestHandler.writeError(Error.PARAMETER_INVALID,
- "Cover does not exist: cover id " + coverId + ", graph id " + graphId);
+ "Cover does not exist: cover id " + coverIdStr + ", graph id " + graphIdStr);
}
layoutHandler.doLayout(cover, layout, doLabelNodes, doLabelEdges, minNodeSize, maxNodeSize, painting);
-
- EntityManager em = entityHandler.getEntityManager();
- EntityTransaction tx = em.getTransaction();
- try {
- tx.begin();
- em.merge(cover);
- tx.commit();
- } catch (RuntimeException e) {
- if (tx != null && tx.isActive()) {
- tx.rollback();
- }
- throw e;
- }
- em.close();
-
- return requestHandler.writeCover(cover, format);
+ database.updateCover(cover);
+ generalLogger.getLogger().log(Level.INFO, "user " + username + ": get visualization of cover " + coverIdStr + " in " +visualOutputFormatStr + " format." );
+ return requestHandler.writeCover(cover, format);
} catch (Exception e) {
requestHandler.log(Level.SEVERE, "", e);
return requestHandler.writeError(Error.INTERNAL, "Internal system error.");
@@ -3039,14 +2628,9 @@ public Response getGraphVisualization(@PathParam("graphId") String graphIdStr,
@DefaultValue("20") @QueryParam("minNodeSize") String minNodeSizeStr,
@DefaultValue("45") @QueryParam("maxNodeSize") String maxNodeSizeStr) {
try {
- long graphId;
+
String username = getUserName();
- try {
- graphId = Long.parseLong(graphIdStr);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph id is not valid.");
- }
+
double minNodeSize;
try {
minNodeSize = Double.parseDouble(minNodeSizeStr);
@@ -3097,16 +2681,16 @@ public Response getGraphVisualization(@PathParam("graphId") String graphIdStr,
return requestHandler.writeError(Error.PARAMETER_INVALID, "Label edges is not a boolean value.");
}
- CustomGraph graph = entityHandler.getGraph(username, graphId);
+ CustomGraph graph = database.getGraph(username, graphIdStr); //done
if (graph == null) {
requestHandler.log(Level.WARNING,
- "user: " + username + ", " + "Graph does not exist: graph id " + graphId);
+ "user: " + username + ", " + "Graph does not exist: graph id " + graphIdStr);
return requestHandler.writeError(Error.PARAMETER_INVALID,
- "Graph does not exist: graph id " + graphId);
+ "Graph does not exist: graph id " + graphIdStr);
}
-
layoutHandler.doLayout(graph, layout, doLabelNodes, doLabelEdges, minNodeSize, maxNodeSize);
- return requestHandler.writeGraph(graph, format);
+ generalLogger.getLogger().log(Level.INFO, "user " + username + ": get visualization of graph " + graphIdStr + " in " +visualOutputFormatStr + " format." );
+ return requestHandler.writeGraph(graph, format);
} catch (Exception e) {
requestHandler.log(Level.SEVERE, "", e);
return requestHandler.writeError(Error.INTERNAL, "Internal system error.");
@@ -3144,21 +2728,9 @@ public Response getCentralityMapVisualization(
@DefaultValue("TRUE") @QueryParam("doLabelNodes") String doLabelNodesStr,
@DefaultValue("TRUE") @QueryParam("showEdgeWeights") String showEdgeWeightsStr) {
try {
- long graphId;
+
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
- try {
- graphId = Long.parseLong(graphIdStr);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph id is not valid.");
- }
- long centralityMapId;
- try {
- centralityMapId = Long.parseLong(centralityMapIdStr);
- } catch (Exception e) {
- requestHandler.log(Level.WARNING, "user: " + username, e);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "CentralityMap id is not valid.");
- }
+
VisualOutputFormat format;
GraphLayoutType layout;
boolean doLabelNodes;
@@ -3193,32 +2765,20 @@ public Response getCentralityMapVisualization(
} catch (Exception e) {
requestHandler.log(Level.WARNING, "", e);
return requestHandler.writeError(Error.PARAMETER_INVALID, "Label edges is not a boolean value.");
- }
- EntityManager em = entityHandler.getEntityManager();
- CustomGraphId gId = new CustomGraphId(graphId, username);
- CentralityMapId cId = new CentralityMapId(centralityMapId, gId);
- EntityTransaction tx = em.getTransaction();
- CentralityMap map;
- try {
- tx.begin();
- map = em.find(CentralityMap.class, cId);
- if(map == null) {
- requestHandler.log(Level.WARNING, "user: " + username + ", " + "CentralityMap does not exist: CentralityMap id " + centralityMapId + ", graph id " + graphId);
- return requestHandler.writeError(Error.PARAMETER_INVALID, "CentralityMap does not exist: CentralityMap id " + centralityMapId + ", graph id " + graphId);
- }
- tx.commit();
- } catch( RuntimeException e ) {
- if( tx != null && tx.isActive() ) {
- tx.rollback();
- }
- throw e;
- }
- em.close();
+ }
+
+
+ CentralityMap map = database.getCentralityMap(username, graphIdStr, centralityMapIdStr); //444 should take gId
+ if(map == null) {
+ requestHandler.log(Level.WARNING, "user: " + username + ", " + "CentralityMap does not exist: CentralityMap id " + centralityMapIdStr + ", graph id " + graphIdStr);
+ return requestHandler.writeError(Error.PARAMETER_INVALID, "CentralityMap does not exist: CentralityMap id " + centralityMapIdStr + ", graph id " + graphIdStr);
+ }
if(doLabelEdges) {
doLabelEdges = map.getGraph().getTypes().contains(GraphType.WEIGHTED) ? true : false;
}
layoutHandler.doLayout(map, layout, doLabelNodes, doLabelEdges, centralityVisualizationType);
- return requestHandler.writeCentralityMap(map, format);
+ generalLogger.getLogger().log(Level.INFO, "user " + username + ": get visualization of centrality " + centralityMapIdStr + " in " +visualOutputFormatStr + " format." );
+ return requestHandler.writeCentralityMap(map, format);
} catch (Exception e) {
requestHandler.log(Level.SEVERE, "", e);
return requestHandler.writeError(Error.INTERNAL, "Internal system error.");
@@ -3261,6 +2821,7 @@ public Response getAlgorithmDefaultParams(@PathParam("CoverCreationType") String
} else {
OcdAlgorithm defaultInstance = algorithmFactory.getInstance(creationType,
new HashMap());
+ //generalLogger.getLogger().log(Level.INFO, "user " + username + ": get default parameters of " + coverCreationTypeStr );
return Response.ok(requestHandler.writeParameters(defaultInstance.getParameters())).build();
}
} catch (Exception e) {
@@ -3304,6 +2865,7 @@ public Response getCentralityAlgorithmDefaultParams(
}
else {
CentralityAlgorithm defaultInstance = centralityAlgorithmFactory.getInstance(centralityMeasureType, new HashMap());
+ //generalLogger.getLogger().log(Level.INFO, "user " + username + ": get default parameters of centrality measure " + centralityMeasureTypeStr );
return Response.ok(requestHandler.writeParameters(defaultInstance.getParameters())).build();
}
}
@@ -3347,6 +2909,7 @@ public Response getSimulationDefaultParams(
}
else {
CentralitySimulation defaultInstance = centralitySimulationFactory.getInstance(simulationType, new HashMap());
+ //generalLogger.getLogger().log(Level.INFO, "user " + username + ": get default parameters of centrality simulation " + simulationTypeStr );
return Response.ok(requestHandler.writeParameters(defaultInstance.getParameters())).build();
}
}
@@ -3389,6 +2952,7 @@ public Response getBenchmarkDefaultParams(@PathParam("GraphCreationType") String
if (creationType.correspondsGroundTruthBenchmark()) {
GroundTruthBenchmark defaultInstance = (GroundTruthBenchmark) benchmarkFactory
.getInstance(creationType, new HashMap());
+ //generalLogger.getLogger().log(Level.INFO, "user " + username + ": get default parameters of benchmark " + graphCreationTypeStr );
return Response.ok(requestHandler.writeParameters(defaultInstance.getParameters())).build();
} else {
throw new NotImplementedException("Specified graph creation type is not a benchmark.");
@@ -3436,6 +3000,7 @@ public Response getMetricDefaultParameters(@PathParam("OcdMetricType") String oc
if (metricType.correspondsStatisticalMeasure()) {
StatisticalMeasure defaultInstance = (StatisticalMeasure) metricFactory.getInstance(metricType,
new HashMap());
+ //generalLogger.getLogger().log(Level.INFO, "user " + username + ": get default parameters of metric " + metricType);
return Response.ok(requestHandler.writeParameters(defaultInstance.getParameters())).build();
} else {
throw new NotImplementedException("Metric type is not properly registered.");
@@ -3502,6 +3067,7 @@ public Response getAlgorithmCompatibleGraphTypes(@PathParam("CoverCreationType")
} else {
OcdAlgorithm defaultInstance = algorithmFactory.getInstance(creationType,
new HashMap());
+ //generalLogger.getLogger().log(Level.INFO, "user " + username + ": get compatible graph types for OCDA " + coverCreationTypeStr);
return Response.ok(requestHandler.writeSpecificEnumNames(defaultInstance.compatibleGraphTypes())).build();
}
} catch (Exception e) {
@@ -3648,6 +3214,7 @@ public Response getCentralitySimulationCompatibleGraphTypes(@PathParam("Centrali
return requestHandler.writeError(Error.PARAMETER_INVALID,
"Specified cover creation type is not instantiatable: " + simulationType.name());
} else {
+ //generalLogger.getLogger().log(Level.INFO, "user " + username + ": get compatible graph types for centrality simulation " + centralitySimulationTypeStr);
CentralitySimulation defaultInstance = centralitySimulationFactory.getInstance(simulationType,
new HashMap());
return Response.ok(requestHandler.writeSpecificEnumNames(defaultInstance.compatibleGraphTypes())).build();
@@ -4016,10 +3583,10 @@ public Response getCentralityVisualizationTypeNames() {
public Response getSimulations(SimulationSeriesParameters parameters) {
List series = new ArrayList<>();
- String userId = getUserId();
+ String userId = getUserName();
try {
- series = entityHandler.getSimulationSeriesByUser(userId);
+ series = database.getSimulationSeriesByUser(userId);
} catch (Exception e) {
Context.getCurrent().monitorEvent(this, MonitoringEvent.SERVICE_ERROR, "fail to get simulation series. " + e.toString());
@@ -4041,23 +3608,24 @@ public Response getSimulations(SimulationSeriesParameters parameters) {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "OK"),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
public Response getSimulationMeta(@DefaultValue("0") @QueryParam("firstIndex") int firstIndex,
- @DefaultValue("0") @QueryParam("length") int length,
- @DefaultValue("0") @QueryParam("graphId") long graphId,
- SimulationSeriesParameters parameters) {
+ @DefaultValue("0") @QueryParam("length") int length,
+ @DefaultValue("0") @QueryParam("graphId") String graphKey,
+ SimulationSeriesParameters parameters) {
if (parameters == null) {
parameters = new SimulationSeriesParameters();
}
-
+
List simulations = new ArrayList<>();
try {
if (firstIndex < 0 || length <= 0) {
- simulations = entityHandler.getSimulationSeriesByUser(getUserId());
+
+ simulations = database.getSimulationSeriesByUser(getUserName());
} else {
- if (graphId <= 0) {
- simulations = entityHandler.getSimulationSeriesByUser(getUserId(), firstIndex, length);
+ if (graphKey.equals("0")) {
+ simulations = database.getSimulationSeriesByUser(getUserName(), firstIndex, length);
} else {
- simulations = entityHandler.getSimulationSeriesByUser(getUserId(), graphId, firstIndex, length);
+ simulations = database.getSimulationSeriesByUser(getUserName(), graphKey, firstIndex,length);
}
}
} catch (Exception e) {
@@ -4075,7 +3643,7 @@ public Response getSimulationMeta(@DefaultValue("0") @QueryParam("firstIndex") i
for (SimulationSeries simulation : simulations) {
try {
SimulationSeriesMetaData metaData = simulation.getMetaData();
- metaData.setGraphName(entityHandler.getGraph(getUserName(), simulation.getParameters().getGraphId()).getName());
+ metaData.setGraphName(database.getGraph(getUserName(), simulation.getSimulationSeriesParameters().getGraphKey()).getName());
metaList.add(metaData);
} catch (Exception e) {
@@ -4091,7 +3659,7 @@ public Response getSimulationMeta(@DefaultValue("0") @QueryParam("firstIndex") i
/**
* Gets the results of a performed simulation series on a network
*
- * @param seriesId the id of the series
+ * @param seriesKey the key of the series
* @return HttpResponse with the returnString
*/
@GET
@@ -4101,16 +3669,15 @@ public Response getSimulationMeta(@DefaultValue("0") @QueryParam("firstIndex") i
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "OK"),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
- public Response getSimulation(@PathParam("seriesId") long seriesId) {
-
+ public Response getSimulation(@PathParam("seriesId") String seriesKey) {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
SimulationSeries series = null;
try {
- series = entityHandler.getSimulationSeries(seriesId);
+ series = database.getSimulationSeries(seriesKey);
if (series == null)
- return Response.status(Status.BAD_REQUEST).entity("no simulation with id " + seriesId + " found")
+ return Response.status(Status.BAD_REQUEST).entity("no simulation with id " + seriesKey + " found")
.build();
if (!series.isEvaluated()) {
@@ -4118,18 +3685,18 @@ public Response getSimulation(@PathParam("seriesId") long seriesId) {
}
} catch (Exception e) {
- logger.log(Level.WARNING, "user: " + username, e);
+ generalLogger.getLogger().log(Level.WARNING, "user: " + username, e);
e.printStackTrace();
return Response.status(Status.INTERNAL_SERVER_ERROR).entity("internal error").build();
}
-
+ //generalLogger.getLogger().log(Level.INFO, "user " + username + ": get results of simulation series with id " + seriesId );
return Response.ok().entity(series).build();
}
/**
* Gets the results of a performed simulation series on a network
*
- * @param seriesId the id of the series
+ * @param seriesKey the key of the series
* @return HttpResponse with the returnString
*/
@GET
@@ -4139,22 +3706,21 @@ public Response getSimulation(@PathParam("seriesId") long seriesId) {
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "OK"),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
- public Response getSimulationTable(@PathParam("seriesId") long seriesId) {
-
+ public Response getSimulationTable(@PathParam("seriesId") String seriesKey) {
String username = getUserName();
SimulationSeries series = null;
try {
- series = entityHandler.getSimulationSeries(seriesId);
+ series = database.getSimulationSeries(seriesKey);
if (series == null)
- return Response.status(Status.BAD_REQUEST).entity("no simulation with id " + seriesId + " found")
+ return Response.status(Status.BAD_REQUEST).entity("no simulation with key " + seriesKey + " found")
.build();
series.evaluate();
} catch (Exception e) {
- logger.log(Level.WARNING, "user: " + username, e);
+ generalLogger.getLogger().log(Level.WARNING, "user: " + username, e);
e.printStackTrace();
return Response.status(Status.INTERNAL_SERVER_ERROR).entity("internal error").build();
}
@@ -4165,14 +3731,14 @@ public Response getSimulationTable(@PathParam("seriesId") long seriesId) {
} catch (Exception e) {
e.printStackTrace();
}
-
+ //generalLogger.getLogger().log(Level.INFO, "user " + username + ": get results of simulation series with id " + seriesId );
return Response.ok().entity(responseString).build();
}
/**
* Gets the parameters of a simulation
*
- * @param seriesId the id of the series
+ * @param seriesKey the key of the series to which the parameters belong
* @return HttpResponse with the returnString
*/
@GET
@@ -4182,13 +3748,13 @@ public Response getSimulationTable(@PathParam("seriesId") long seriesId) {
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "OK"),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
- public Response getSimulationParameters(@PathParam("seriesId") long seriesId) {
-
+ public Response getSimulationParameters(@PathParam("seriesId") String seriesKey) {
+
SimulationSeriesParameters parameters = null;
try {
- parameters = entityHandler.getSimulationParameters(seriesId);
+ parameters = database.getSimulationSeries(seriesKey).getSimulationSeriesParameters();
} catch (Exception e) {
- logger.log(Level.WARNING, "fail to get simulation series parameters");
+ generalLogger.getLogger().log(Level.WARNING, "fail to get simulation series parameters");
return Response.status(Status.INTERNAL_SERVER_ERROR).entity("fail to get simulation series parameters")
.build();
}
@@ -4199,7 +3765,7 @@ public Response getSimulationParameters(@PathParam("seriesId") long seriesId) {
/**
* Deletes a performed simulation series on a network
*
- * @param seriesId the id of the series
+ * @param seriesKey the key of the series
* @return HttpResponse with the returnString
*/
@DELETE
@@ -4209,10 +3775,9 @@ public Response getSimulationParameters(@PathParam("seriesId") long seriesId) {
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "OK"),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
- public Response deleteSimulation(@PathParam("seriesId") long seriesId) {
-
+ public Response deleteSimulation(@PathParam("seriesId") String seriesKey) {
try {
- entityHandler.deleteSeries(seriesId);
+ database.deleteSimulationSeries(seriesKey);
} catch (Exception e) {
return Response.serverError().entity(e.getMessage()).build();
}
@@ -4223,9 +3788,9 @@ public Response deleteSimulation(@PathParam("seriesId") long seriesId) {
/**
* Starts the simulation of a cooperation and defection game simulation
- *
+ *
* @param parameters the parameters
- *
+ *
* @return HttpResponse with the returnString
*/
@POST
@@ -4238,9 +3803,7 @@ public Response deleteSimulation(@PathParam("seriesId") long seriesId) {
public Response postSimulation(SimulationSeriesParameters parameters) {
String username = getUserName();
-
- long graphId = parameters.getGraphId();
- CustomGraph network = entityHandler.getGraph(username, graphId);
+ CustomGraph network = database.getGraph(getUserName(), parameters.getGraphKey());
if (network == null)
return Response.status(Status.BAD_REQUEST).entity("graph not found").build();
@@ -4270,18 +3833,19 @@ public Response postSimulation(SimulationSeriesParameters parameters) {
series = simulationBuilder.simulate();
} catch (Exception e) {
- logger.log(Level.WARNING, "user: " + username, e);
+ generalLogger.getLogger().log(Level.WARNING, "user: " + username, e);
e.printStackTrace();
return Response.serverError().entity("simulation could not be carried out\n" + e.getMessage()).build();
}
-
- if(series.getSimulationDatasets() == null || !(series.getSimulationDatasets().size() == parameters.getIterations()))
+
+ if(series.getSimulationDatasets() == null || !(series.getSimulationDatasets().size() == parameters.getIterations()))
return Response.serverError().entity("something went wrong").build();
-
- long result;
+
+ String result;
try {
- result = entityHandler.store(series, getUserId());
-
+ //generalLogger.getLogger().log(Level.INFO, "user " + username + ": start simulation with parameters " + parameters );
+ result = database.storeSimulationSeries(series, getUserName());
+
} catch (Exception e) {
e.printStackTrace();
return Response.serverError().entity("simulation not stored").build();
@@ -4300,15 +3864,15 @@ public Response postSimulation(SimulationSeriesParameters parameters) {
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(tags = {"execution"}, value = "Run simulation group", notes = " Starts a simulation group of evolutionary cooperation or defection games ")
public Response putSimulationGroup(@DefaultValue("") @QueryParam("name") String name,
- List seriesIds) {
-
- List series = new ArrayList<>(seriesIds.size());
+ List seriesKeys) {
+
+ List series = new ArrayList<>(seriesKeys.size());
try {
- for(Integer id: seriesIds) {
- series.add(entityHandler.getSimulationSeries(id));
+ for(String seriesKey: seriesKeys) {
+ series.add(database.getSimulationSeries(seriesKey));
}
} catch (Exception e) {
- logger.log(Level.WARNING, "user: " + getUserName(), e);
+ generalLogger.getLogger().log(Level.WARNING, "user: " + getUserName(), e);
e.printStackTrace();
return Response.serverError().entity("Invalid simulation series \n" + e.getMessage()).build();
}
@@ -4318,9 +3882,9 @@ public Response putSimulationGroup(@DefaultValue("") @QueryParam("name") String
group = new SimulationSeriesGroup(series);
group.setName(name);
- entityHandler.store(group, getUserId());
-
-
+ group.calculateMetaData(); // calculate and store metadata that will be used for WebClient
+ database.storeSimulationSeriesGroup(group, getUserName());
+
} catch (Exception e) {
e.printStackTrace();
return Response.serverError().entity("fail store series group").build();
@@ -4337,13 +3901,13 @@ public Response putSimulationGroup(@DefaultValue("") @QueryParam("name") String
@ApiOperation(tags = {"show"}, value = "Get Simulation Group Meta", notes = "Returns the meta information for a performed group of simulations")
public Response getSimulationGroups(@DefaultValue("0") @QueryParam("firstIndex") int firstIndex,
@DefaultValue("0") @QueryParam("length") int length) {
-
+
List simulations = new ArrayList<>();
try {
if (firstIndex < 0 || length <= 0) {
- simulations = entityHandler.getSimulationSeriesGroups(getUserId());
+ simulations = database.getSimulationSeriesGroups(getUserName());
} else {
- simulations = entityHandler.getSimulationSeriesGroups(getUserId(), firstIndex, length);
+ simulations = database.getSimulationSeriesGroups(getUserName(), firstIndex, length);
}
} catch (Exception e) {
Context.getCurrent().monitorEvent(this, MonitoringEvent.SERVICE_ERROR, "fail to get simulation series. " + e.toString());
@@ -4351,14 +3915,16 @@ public Response getSimulationGroups(@DefaultValue("0") @QueryParam("firstIndex")
e.printStackTrace();
return Response.status(Status.INTERNAL_SERVER_ERROR).entity("fail to get simulation series").build();
}
-
- if (simulations == null || simulations.size() < 1)
+
+ if (simulations == null || simulations.size() < 1) {
return Response.status(Status.BAD_REQUEST).entity("No simulation series found").build();
-
+ }
+
List metaList = new ArrayList<>(simulations.size());
try {
for (SimulationSeriesGroup simulation : simulations) {
- SimulationSeriesGroupMetaData metaData = simulation.getMetaData();
+ SimulationSeriesGroupMetaData metaData = simulation.getGroupMetaData();
+ metaData.setKey(simulation.getKey()); // set group key, which became available when group was created
metaList.add(metaData);
}
} catch (Exception e) {
@@ -4371,7 +3937,7 @@ public Response getSimulationGroups(@DefaultValue("0") @QueryParam("firstIndex")
/**
* Gets the results of a performed simulation series group on a network
*
- * @param groupId the id of the group
+ * @param groupKey the id of the group
* @return HttpResponse with the returnString
*/
@GET
@@ -4381,33 +3947,38 @@ public Response getSimulationGroups(@DefaultValue("0") @QueryParam("firstIndex")
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "OK"),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
- public Response getSimulationGroupTable(@PathParam("groupId") long groupId) {
-
+ public Response getSimulationGroupTable(@PathParam("groupId") String groupKey) {
String username = getUserName();
- SimulationSeriesGroup series = null;
+ SimulationSeriesGroup simulationSeriesGroup = null;
try {
- series = entityHandler.getSimulationSeriesGroup(groupId);
+ simulationSeriesGroup = database.getSimulationSeriesGroup(groupKey);
+
+ List simulationSeriesInGroup = new ArrayList<>();
+ for (String simulationSeriesKey : simulationSeriesGroup.getSimulationSeriesKeys()){
+ simulationSeriesInGroup.add(database.getSimulationSeries(simulationSeriesKey));
+ }
+ simulationSeriesGroup.setSimulationSeries(simulationSeriesInGroup);
- if (series == null)
- return Response.status(Status.BAD_REQUEST).entity("no simulation with id " + groupId + " found")
+ if (simulationSeriesGroup == null)
+ return Response.status(Status.BAD_REQUEST).entity("no simulation with id " + groupKey + " found")
.build();
- series.evaluate();
+ simulationSeriesGroup.evaluate();
} catch (Exception e) {
- logger.log(Level.WARNING, "user: " + username, e);
+ generalLogger.getLogger().log(Level.WARNING, "user: " + username, e);
e.printStackTrace();
return Response.status(Status.INTERNAL_SERVER_ERROR).entity("internal error").build();
}
String responseString = "";
try {
- responseString = series.toTable().print();
+ responseString = simulationSeriesGroup.toTable().print();
} catch (Exception e) {
e.printStackTrace();
}
-
+ //generalLogger.getLogger().log(Level.INFO, "user " + username + ": get results of simulation series with id " + groupId );
return Response.ok().entity(responseString).build();
}
@@ -4418,11 +3989,17 @@ public Response getSimulationGroupTable(@PathParam("groupId") long groupId) {
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "OK"),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(tags = {"show"}, value = "Get a Simulation Group", notes = "Returns a performed simulation group")
- public Response getSimulationGroup(@PathParam("groupId") long groupId) {
-
+ public Response getSimulationGroup(@PathParam("groupId") String groupKey) {
SimulationSeriesGroup simulation = null;
- try {
- simulation = entityHandler.getSimulationSeriesGroup(groupId);
+ try {
+ simulation = database.getSimulationSeriesGroup(groupKey);
+
+ List simulationSeriesInGroup = new ArrayList<>();
+ for (String simulationSeriesKey : simulation.getSimulationSeriesKeys()){
+ simulationSeriesInGroup.add(database.getSimulationSeries(simulationSeriesKey));
+ }
+ simulation.setSimulationSeries(simulationSeriesInGroup);
+
if(!simulation.isEvaluated())
simulation.evaluate();
@@ -4442,7 +4019,7 @@ public Response getSimulationGroup(@PathParam("groupId") long groupId) {
/**
* Deletes a simulation series group
*
- * @param groupId the id of the group
+ * @param groupKey the id of the group
* @return HttpResponse with the returnString
*/
@DELETE
@@ -4452,14 +4029,14 @@ public Response getSimulationGroup(@PathParam("groupId") long groupId) {
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "OK"),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
- public Response deleteSimulationSeriesGroup(@PathParam("groupId") long groupId) {
-
+ public Response deleteSimulationSeriesGroup(@PathParam("groupId") String groupKey) {
try {
- entityHandler.deleteGroup(groupId);
+ database.deleteSimulationSeriesGroup(groupKey);
} catch (Exception e) {
e.printStackTrace();
return Response.serverError().entity(e.getMessage()).build();
- }
+ }
+ generalLogger.getLogger().log(Level.INFO, "user " + getUserName() + ": delete simulation series with id " + groupKey );
return Response.ok("done").build();
}
@@ -4473,34 +4050,44 @@ public Response deleteSimulationSeriesGroup(@PathParam("groupId") long groupId)
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "OK"),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
- public Response getSimulationGroupMapping(@PathParam("groupId") long groupId) {
-
+ public Response getSimulationGroupMapping(@PathParam("groupId") String groupKey) {
+
String username = getUserName();
SimulationSeriesGroup simulationGroup = null;
SimulationSeriesSetMapping mapping;
try {
- simulationGroup = entityHandler.getSimulationSeriesGroup(groupId);
+ simulationGroup = database.getSimulationSeriesGroup(groupKey);
+
+ List simulationSeriesInGroup = new ArrayList<>();
+ for (String simulationSeriesKey : simulationGroup.getSimulationSeriesKeys()){
+ simulationSeriesInGroup.add(database.getSimulationSeries(simulationSeriesKey));
+ }
+ simulationGroup.setSimulationSeries(simulationSeriesInGroup);
- if (simulationGroup == null)
- return Response.status(Status.BAD_REQUEST).entity("no simulation with id " + groupId + " found")
+
+ if (simulationGroup == null) {
+ return Response.status(Status.BAD_REQUEST).entity("no simulation with id " + groupKey + " found")
.build();
+ }
- if (!simulationGroup.isEvaluated())
+ if (!simulationGroup.isEvaluated()) {
simulationGroup.evaluate();
-
+ }
+
MappingFactory factory = new MappingFactory();
- mapping = factory.build(simulationGroup.getSimulationSeries(), simulationGroup.getName());
+ mapping = factory.build(simulationGroup.getSeriesList(), simulationGroup.getName());
for(SimulationSeries sim: mapping.getSimulation()) {
- sim.setNetwork(entityHandler.getGraph(getUserName(), sim.getParameters().getGraphId()));
+ sim.setNetwork(database.getGraph(getUserName(), sim.getSimulationSeriesParameters().getGraphKey()));
}
-
- if (!mapping.isEvaluated())
+
+ if (!mapping.isEvaluated()) {
mapping.correlate();
+ }
} catch (Exception e) {
- logger.log(Level.WARNING, "user: " + username, e);
+ generalLogger.getLogger().log(Level.WARNING, "user: " + username, e);
e.printStackTrace();
return Response.status(Status.INTERNAL_SERVER_ERROR).entity("internal error").build();
}
@@ -4519,16 +4106,23 @@ public Response getSimulationGroupMapping(@PathParam("groupId") long groupId) {
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "OK"),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
- public Response getSimulationGroupsMapping(List groupIds) {
+ public Response getSimulationGroupsMapping(List groupKeys) {
String username = getUserName();
- List groups = new ArrayList<>(groupIds.size());
+ List groups = new ArrayList<>(groupKeys.size());
SimulationGroupSetMapping mapping = null;
try {
- for (Long groupId : groupIds) {
+ for (String groupKey : groupKeys) {
try {
- SimulationSeriesGroup group = entityHandler.getSimulationSeriesGroup(groupId);
+ SimulationSeriesGroup group = database.getSimulationSeriesGroup(groupKey);
+ // load simulation series belonging to the group
+ // based on the simulation series keys stored in the group
+ List simulationSeriesInGroup = new ArrayList<>();
+ for (String simulationSeriesKey : group.getSimulationSeriesKeys()){
+ simulationSeriesInGroup.add(database.getSimulationSeries(simulationSeriesKey));
+ }
+ group.setSimulationSeries(simulationSeriesInGroup);
groups.add(group);
} catch (Exception e) {
@@ -4540,10 +4134,10 @@ public Response getSimulationGroupsMapping(List groupIds) {
try {
for (int i = 0; i < groups.size(); i++) {
- for (int j = 0; j < groups.get(i).getSimulationSeries().size(); j++) {
- groups.get(i).getSimulationSeries().get(j).setNetwork(entityHandler.getGraph(getUserName(),
- groups.get(i).getSimulationSeries().get(j).getParameters().getGraphId()));
- groups.get(i).getSimulationSeries().get(j).evaluate();
+ for (int j = 0; j < groups.get(i).getSeriesList().size(); j++) {
+ groups.get(i).getSeriesList().get(j).setNetwork(database.getGraph(getUserName(),
+ groups.get(i).getSeriesList().get(j).getSimulationSeriesParameters().getGraphKey()));
+ groups.get(i).getSeriesList().get(j).evaluate();
}
groups.get(i).evaluate();
}
@@ -4555,7 +4149,7 @@ public Response getSimulationGroupsMapping(List groupIds) {
}
} catch (Exception e) {
- logger.log(Level.WARNING, "user: " + username, e);
+ generalLogger.getLogger().log(Level.WARNING, "user: " + username, e);
e.printStackTrace();
return Response.status(Status.INTERNAL_SERVER_ERROR).entity("internal error").build();
}
@@ -4631,24 +4225,23 @@ public Response getBreakConditions() {
* method invocation. It returns only default types and classes.
*
*
- * @param graphId
+ * @param graphIdStr
* Id of the requested stored graph
* @return HashMap
*
*/
- public Map getGraphById(long graphId) {
-
+ public Map getGraphById(String graphIdStr) {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
CustomGraph graph;
try {
- graph = entityHandler.getGraph(username, graphId);
+ graph = database.getGraph(username, graphIdStr);
} catch (Exception e) {
e.printStackTrace();
return null;
}
- Integer nodeCount = graph.nodeCount();
- Integer edgeCount = graph.edgeCount();
+ Integer nodeCount = graph.getNodeCount();
+ Integer edgeCount = graph.getEdgeCount();
Boolean directed = graph.isDirected();
Boolean weighted = graph.isWeighted();
String name = graph.getName();
@@ -4664,7 +4257,7 @@ public Map getGraphById(long graphId) {
graphData.put("name", name);
graphData.put("graph", adjList);
- logger.log(Level.INFO, "RMI requested a graph: " + graphId);
+ generalLogger.getLogger().log(Level.INFO, "RMI requested a graph: " + graphIdStr);
return graphData;
}
@@ -4674,17 +4267,16 @@ public Map getGraphById(long graphId) {
* @return List
* @throws AgentNotRegisteredException if the agent was not registered
*/
- public List getGraphIds() throws AgentNotRegisteredException {
-
+ public List getGraphIds() throws AgentNotRegisteredException {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
- List graphIdList = new ArrayList();
+ List graphIdList = new ArrayList();
- List graphList = entityHandler.getGraphs(username);
+ List graphList = database.getGraphs(username);
for (int i = 0, si = graphList.size(); i < si; i++) {
- graphIdList.add(graphList.get(i).getId());
+ graphIdList.add(graphList.get(i).getKey());
}
- logger.log(Level.INFO, "RMI requested graph Ids");
+ generalLogger.getLogger().log(Level.INFO, "RMI requested graph Ids");
return graphIdList;
}
@@ -4696,9 +4288,9 @@ public List getGraphIds() throws AgentNotRegisteredException {
* This method is intended to be used by other las2peer services for remote
* method invocation. It returns only default types and classes.
*
- * @param graphId
+ * @param graphIdStr
* Index of the requested graph
- * @param coverId
+ * @param coverIdStr
* Index of the requested community cover
*
* @return HashMap including the community members lists. The outer list has
@@ -4706,12 +4298,11 @@ public List getGraphIds() throws AgentNotRegisteredException {
* contains the indices of the member nodes.
*
*/
- public Map getCoverById(long graphId, long coverId) {
-
+ public Map getCoverById(String graphIdStr, String coverIdStr) {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
Cover cover;
try {
- cover = entityHandler.getCover(username, graphId, coverId);
+ cover = database.getCover(username, graphIdStr, coverIdStr);
} catch (Exception e) {
e.printStackTrace();
return null;
@@ -4726,8 +4317,8 @@ public Map getCoverById(long graphId, long coverId) {
Map coverData = new HashMap();
coverData.put("size", communityCount);
coverData.put("algorithm", algorithm);
- coverData.put("graphId", graphId);
- coverData.put("coverId", coverId);
+ coverData.put("graphId", graphIdStr);
+ coverData.put("coverId", coverIdStr);
coverData.put("cover", communityMemberList);
return coverData;
@@ -4739,25 +4330,24 @@ public Map getCoverById(long graphId, long coverId) {
* This method is intended to be used by other las2peer services for remote
* method invocation. It returns only default types and classes.
*
- * @param graphId
+ * @param graphIdStr
* Index of the requested graph
*
* @return list containing cover indices.
*
*/
- public List getCoverIdsByGraphId(long graphId) {
-
+ public List getCoverIdsByGraphId(String graphIdStr) {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
- List covers = entityHandler.getCovers(username, graphId);
+ List covers = database.getCovers(username, graphIdStr);
int size = covers.size();
- List coverIds = new ArrayList<>(size);
+ List coverIds = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
- coverIds.add(covers.get(i).getId());
+ coverIds.add(covers.get(i).getKey());
}
return coverIds;
}
-}
\ No newline at end of file
+}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/centralityInput/NodeValueListInputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/centralityInput/NodeValueListInputAdapter.java
index 703e1de0..acf9b673 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/centralityInput/NodeValueListInputAdapter.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/centralityInput/NodeValueListInputAdapter.java
@@ -1,13 +1,14 @@
package i5.las2peer.services.ocd.adapters.centralityInput;
import java.util.ArrayList;
+import java.util.Iterator;
import java.util.List;
import i5.las2peer.services.ocd.adapters.AdapterException;
import i5.las2peer.services.ocd.adapters.Adapters;
import i5.las2peer.services.ocd.centrality.data.CentralityMap;
import i5.las2peer.services.ocd.graphs.CustomGraph;
-import y.base.NodeCursor;
+import org.graphstream.graph.Node;
public class NodeValueListInputAdapter extends AbstractCentralityInputAdapter {
@@ -19,10 +20,9 @@ public CentralityMap readCentrality(CustomGraph graph) throws AdapterException {
// Get all node names from the graph
List nodeNames = new ArrayList();
- NodeCursor nc = graph.nodes();
- while(nc.ok()) {
- nodeNames.add(graph.getNodeName(nc.node()));
- nc.next();
+ Iterator nc = graph.iterator();
+ while(nc.hasNext()) {
+ nodeNames.add(graph.getNodeName(nc.next()));
}
try {
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/centralityOutput/DefaultXmlCentralityOutputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/centralityOutput/DefaultXmlCentralityOutputAdapter.java
index d9b98343..1ca94e1b 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/centralityOutput/DefaultXmlCentralityOutputAdapter.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/centralityOutput/DefaultXmlCentralityOutputAdapter.java
@@ -1,5 +1,6 @@
package i5.las2peer.services.ocd.adapters.centralityOutput;
+import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -18,8 +19,7 @@
import i5.las2peer.services.ocd.adapters.AdapterException;
import i5.las2peer.services.ocd.centrality.data.CentralityMap;
import i5.las2peer.services.ocd.utils.ExecutionStatus;
-import y.base.Node;
-import y.base.NodeCursor;
+import org.graphstream.graph.Node;
public class DefaultXmlCentralityOutputAdapter extends AbstractCentralityOutputAdapter {
@@ -37,10 +37,10 @@ public void writeCentralityMap(CentralityMap map) throws AdapterException {
*/
Element centralityValuesElt = doc.createElement("CentralityValues");
if(map.getCreationMethod().getStatus() == ExecutionStatus.COMPLETED) {
- NodeCursor nodes = map.getGraph().nodes();
+ Iterator nodes = map.getGraph().iterator();
Node node;
- while(nodes.ok()) {
- node = nodes.node();
+ while(nodes.hasNext()) {
+ node = nodes.next();
Element nodeElt = doc.createElement("Node");
Element nodeIdElt = doc.createElement("Name");
nodeIdElt.appendChild(doc.createTextNode(map.getGraph().getNodeName(node)) );
@@ -49,7 +49,6 @@ public void writeCentralityMap(CentralityMap map) throws AdapterException {
nodeValueElt.appendChild(doc.createTextNode( ((Double)map.getNodeValue(node)).toString()) );
nodeElt.appendChild(nodeValueElt);
centralityValuesElt.appendChild(nodeElt);
- nodes.next();
}
}
mapElt.appendChild(centralityValuesElt);
@@ -105,7 +104,7 @@ private void writeMetaInfo(CentralityMap map, Document doc, Element mapElt) {
mapIdElt.appendChild(doc.createTextNode(Long.toString(map.getId())));
idElt.appendChild(mapIdElt);
Element graphIdElt = doc.createElement("GraphId");
- graphIdElt.appendChild(doc.createTextNode(Long.toString(map.getGraph().getId())));
+ graphIdElt.appendChild(doc.createTextNode(map.getGraph().getKey()));
idElt.appendChild(graphIdElt);
mapElt.appendChild(idElt);
Element graphElt = doc.createElement("Graph");
@@ -113,7 +112,7 @@ private void writeMetaInfo(CentralityMap map, Document doc, Element mapElt) {
graphNameElt.appendChild(doc.createTextNode(map.getGraph().getName()));
graphElt.appendChild(graphNameElt);
Element graphSizeElt = doc.createElement("GraphSize");
- graphSizeElt.appendChild(doc.createTextNode(Integer.toString(map.getGraph().nodeCount())));
+ graphSizeElt.appendChild(doc.createTextNode(Integer.toString(map.getGraph().getNodeCount())));
graphElt.appendChild(graphSizeElt);
mapElt.appendChild(graphElt);
/*
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/centralityOutput/MetaXmlCentralityOutputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/centralityOutput/MetaXmlCentralityOutputAdapter.java
index e66ca00d..3651279a 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/centralityOutput/MetaXmlCentralityOutputAdapter.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/centralityOutput/MetaXmlCentralityOutputAdapter.java
@@ -35,10 +35,10 @@ public void writeCentralityMap(CentralityMap map) throws AdapterException {
mapElt.appendChild(nameElt);
Element idElt = doc.createElement("Id");
Element mapIdElt = doc.createElement("CentralityMapId");
- mapIdElt.appendChild(doc.createTextNode(Long.toString(map.getId())));
+ mapIdElt.appendChild(doc.createTextNode(map.getKey())); //done
idElt.appendChild(mapIdElt);
Element graphIdElt = doc.createElement("GraphId");
- graphIdElt.appendChild(doc.createTextNode(Long.toString(map.getGraph().getId())));
+ graphIdElt.appendChild(doc.createTextNode(map.getGraph().getKey())); //done
idElt.appendChild(graphIdElt);
mapElt.appendChild(idElt);
Element graphElt = doc.createElement("Graph");
@@ -46,7 +46,7 @@ public void writeCentralityMap(CentralityMap map) throws AdapterException {
graphNameElt.appendChild(doc.createTextNode(map.getGraph().getName()));
graphElt.appendChild(graphNameElt);
Element graphSizeElt = doc.createElement("GraphSize");
- graphSizeElt.appendChild(doc.createTextNode(Integer.toString(map.getGraph().nodeCount())));
+ graphSizeElt.appendChild(doc.createTextNode(Integer.toString(map.getGraph().getNodeCount())));
graphElt.appendChild(graphSizeElt);
mapElt.appendChild(graphElt);
/*
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/coverInput/CommunityMemberListsCoverInputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/coverInput/CommunityMemberListsCoverInputAdapter.java
index 0f6dce5c..d8085f1a 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/coverInput/CommunityMemberListsCoverInputAdapter.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/coverInput/CommunityMemberListsCoverInputAdapter.java
@@ -6,16 +6,12 @@
import i5.las2peer.services.ocd.graphs.CustomGraph;
import java.io.Reader;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
import org.la4j.matrix.Matrix;
import org.la4j.matrix.sparse.CCSMatrix;
-import y.base.Node;
-import y.base.NodeCursor;
+import org.graphstream.graph.Node;
/**
* A cover input adapter for the community member list format.
@@ -98,19 +94,18 @@ public Cover readCover(CustomGraph graph) throws AdapterException {
e.printStackTrace();
}
}
- Matrix memberships = new CCSMatrix(graph.nodeCount(), communityCount);
- NodeCursor nodes = graph.nodes();
+ Matrix memberships = new CCSMatrix(graph.getNodeCount(), communityCount);
+ Iterator nodes = graph.iterator();
Node node;
- while(nodes.ok()) {
- node = nodes.node();
+ while(nodes.hasNext()) {
+ node = nodes.next();
nodeName = graph.getNodeName(node);
communityIndices = nodeCommunities.get(nodeName);
if(communityIndices != null) {
for(int communityIndex : communityIndices) {
- memberships.set(node.index(), communityIndex, 1d/communityIndices.size());
+ memberships.set(node.getIndex(), communityIndex, 1d/communityIndices.size());
}
}
- nodes.next();
}
Cover cover = new Cover(graph, memberships);
if(communityNamesDefined) {
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/coverInput/LabeledMembershipMatrixCoverInputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/coverInput/LabeledMembershipMatrixCoverInputAdapter.java
index d64f6698..173c4f84 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/coverInput/LabeledMembershipMatrixCoverInputAdapter.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/coverInput/LabeledMembershipMatrixCoverInputAdapter.java
@@ -7,14 +7,14 @@
import java.io.Reader;
import java.util.HashMap;
+import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.la4j.matrix.Matrix;
import org.la4j.matrix.sparse.CCSMatrix;
-import y.base.Node;
-import y.base.NodeCursor;
+import org.graphstream.graph.Node;
/**
* A cover input adapter for the labeled membership matrix format.
@@ -42,21 +42,20 @@ public LabeledMembershipMatrixCoverInputAdapter() {
@Override
public Cover readCover(CustomGraph graph) throws AdapterException {
- NodeCursor nodes = graph.nodes();
+ Iterator nodes = graph.iterator();
Node node;
Map reverseNodeNames = new HashMap();
- while(nodes.ok()) {
- node = nodes.node();
+ while(nodes.hasNext()) {
+ node = nodes.next();
reverseNodeNames.put(graph.getNodeName(node), node);
- nodes.next();
}
try {
List line = Adapters.readLine(reader);
- Matrix memberships = new CCSMatrix(graph.nodeCount(), line.size() - 1);
+ Matrix memberships = new CCSMatrix(graph.getNodeCount(), line.size() - 1);
int nodeIndex;
double belongingFactor;
while(line.size() > 0) {
- nodeIndex = reverseNodeNames.get(line.get(0)).index();
+ nodeIndex = reverseNodeNames.get(line.get(0)).getIndex();
for(int i=1; i nodes = graph.iterator();
Node node;
- while(nodes.ok()) {
- node = nodes.node();
+ while(nodes.hasNext()) {
+ node = nodes.next();
nodeName = graph.getNodeName(node);
communityIndices = nodeCommunities.get(nodeName);
for(int communityIndex : communityIndices) {
- memberships.set(node.index(), communityIndex, 1d/communityIndices.size());
+ memberships.set(node.getIndex(), communityIndex, 1d/communityIndices.size());
}
- nodes.next();
}
return new Cover(graph, memberships);
}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/coverOutput/DefaultXmlCoverOutputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/coverOutput/DefaultXmlCoverOutputAdapter.java
index daaa6683..2b9e10e8 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/coverOutput/DefaultXmlCoverOutputAdapter.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/coverOutput/DefaultXmlCoverOutputAdapter.java
@@ -5,6 +5,7 @@
import i5.las2peer.services.ocd.graphs.CustomGraph;
import i5.las2peer.services.ocd.metrics.OcdMetricLog;
+import java.util.Iterator;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
@@ -18,8 +19,7 @@
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-import y.base.Node;
-import y.base.NodeCursor;
+import org.graphstream.graph.Node;
/**
* A cover output adapter for the default XML format.
@@ -92,7 +92,7 @@ public void writeCover(Cover cover) throws AdapterException {
OcdMetricLog metric = cover.getMetrics().get(i);
Element metricElt = doc.createElement("Metric");
Element metricIdElt = doc.createElement("Id");
- metricIdElt.appendChild(doc.createTextNode(Long.toString(metric.getId())));
+ metricIdElt.appendChild(doc.createTextNode(metric.getKey())); //done
metricElt.appendChild(metricIdElt);
Element metricTypeElt = doc.createElement("Type");
metricTypeElt.appendChild(doc.createTextNode(metric.getType().name()));
@@ -154,10 +154,10 @@ public void writeCover(Cover cover) throws AdapterException {
* Community Memberships
*/
Element membershipsElt = doc.createElement("Memberships");
- NodeCursor nodes = cover.getGraph().nodes();
+ Iterator nodes = cover.getGraph().iterator();
Node node;
- while(nodes.ok()) {
- node = nodes.node();
+ while(nodes.hasNext()) {
+ node = nodes.next();
Element membershipElt = doc.createElement("Membership");
Element memberIdElt = doc.createElement("Name");
memberIdElt.appendChild(doc.createTextNode(graph.getNodeName(node)));
@@ -166,7 +166,6 @@ public void writeCover(Cover cover) throws AdapterException {
belongingFactorElt.appendChild(doc.createTextNode(String.format("%.5f\n", cover.getBelongingFactor(node, i))));
membershipElt.appendChild(belongingFactorElt);
membershipsElt.appendChild(membershipElt);
- nodes.next();
}
communityElt.appendChild(membershipsElt);
communitiesElt.appendChild(communityElt);
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/coverOutput/LabeledMembershipMatrixCoverOutputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/coverOutput/LabeledMembershipMatrixCoverOutputAdapter.java
index f9f3bdd8..4886bfb1 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/coverOutput/LabeledMembershipMatrixCoverOutputAdapter.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/coverOutput/LabeledMembershipMatrixCoverOutputAdapter.java
@@ -5,9 +5,9 @@
import i5.las2peer.services.ocd.graphs.CustomGraph;
import java.io.Writer;
+import java.util.Iterator;
-import y.base.Node;
-import y.base.NodeCursor;
+import org.graphstream.graph.Node;
/**
* A cover output adapter for the labeled membership matrix format.
@@ -33,19 +33,18 @@ public LabeledMembershipMatrixCoverOutputAdapter() {
public void writeCover(Cover cover) throws AdapterException {
try {
CustomGraph graph = cover.getGraph();
- NodeCursor nodes = graph.nodes();
- while(nodes.ok()) {
- Node node = nodes.node();
+ Iterator nodes = graph.iterator();
+ while(nodes.hasNext()) {
+ Node node = nodes.next();
String nodeName = graph.getNodeName(node);
if(nodeName.isEmpty()) {
- nodeName = Integer.toString(node.index());
+ nodeName = Integer.toString(node.getIndex());
}
writer.write(nodeName + " ");
for(int i=0; i nodes = new ArrayList<>();
for (int i = 0; i < nodeCount; i++) {
- nodes.add(i, graph.createNode());
+ nodes.add(i, graph.addNode(String.valueOf(i)));
graph.setNodeName(nodes.get(i), String.valueOf(i+1));
}
@@ -49,7 +50,7 @@ public CustomGraph readGraph() throws AdapterException {
Node targetNode = nodes.get(column);
double edgeWeight = Double.parseDouble(line.get(column));
if (edgeWeight > 0) {
- Edge edge = graph.createEdge(sourceNode, targetNode);
+ Edge edge = graph.addEdge(UUID.randomUUID().toString(), sourceNode, targetNode);
graph.setEdgeWeight(edge, edgeWeight);
}
}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/GmlGraphInputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/GmlGraphInputAdapter.java
index c052dfa6..21ff0797 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/GmlGraphInputAdapter.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/GmlGraphInputAdapter.java
@@ -1,5 +1,7 @@
package i5.las2peer.services.ocd.adapters.graphInput;
+import com.google.common.base.Charsets;
+import com.google.common.io.CharStreams;
import i5.las2peer.services.ocd.adapters.AdapterException;
import i5.las2peer.services.ocd.graphs.CustomGraph;
@@ -8,121 +10,114 @@
import java.io.InputStream;
import java.text.ParseException;
import java.util.HashMap;
+import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
-import y.base.Edge;
-import y.base.EdgeCursor;
-import y.base.Node;
-import y.base.NodeCursor;
-import y.io.GMLIOHandler;
+import org.apache.lucene.util.ThreadInterruptedException;
+import org.graphstream.graph.Node;
+import org.graphstream.graph.Edge;
+import org.graphstream.stream.file.FileSourceGML;
+import org.graphstream.stream.file.gml.GMLParser;
/**
* A graph input adapter for GML format, based on the GMLIOHandler of the yFiles library.
* In case each node has a label with a unique value node names will be derived from there. Otherwise node names will be set as indices.
* In case each edge has a label with a numeric value edge weights will be derived from there.
- * @author Sebastian
*
+ * @author Sebastian
*/
+//TODO: Test for graphstream
public class GmlGraphInputAdapter extends AbstractGraphInputAdapter {
-
- @Override
- public void setParameter(Map param) throws IllegalArgumentException, ParseException{
-
- }
-
- @Override
- public CustomGraph readGraph() throws AdapterException {
- GMLIOHandler ioh = new GMLIOHandler();
- Scanner scanner = new Scanner(reader);
- String inString = scanner.useDelimiter("\\A").next();
- scanner.close();
- InputStream is = new ByteArrayInputStream(inString.getBytes());
- CustomGraph graph = new CustomGraph();
- try {
- ioh.read(graph, is);
- } catch (IOException e) {
- throw new AdapterException(e);
- } finally {
- try {
- is.close();
- } catch (IOException e) {
- }
- }
- /*
- * Check whether node labels are unique names.
- */
- NodeCursor nodes = graph.nodes();
- Node node;
- HashMap nodenames = new HashMap();
- try {
- while(nodes.ok()) {
- node = nodes.node();
- String name = graph.getRealizer(node).getLabel().getText();
- if(name.isEmpty()) {
- break;
- }
- nodenames.put(node, name);
- nodes.next();
- }
- } catch (RuntimeException e) {
- // label not set
- }
- nodes.toFirst();
- /*
- * Node labels are unique.
- */
- if(nodenames.size() == graph.nodeCount()) {
- while(nodes.ok()) {
- node = nodes.node();
- graph.setNodeName(node, nodenames.get(node));
- nodes.next();
- }
- }
- /*
- * Node labels are not unique.
- */
- else {
- while(nodes.ok()) {
- node = nodes.node();
- graph.setNodeName(node, Integer.toString(node.index()));
- nodes.next();
- }
- }
- /*
- * Check whether node labels are numeric.
- */
- EdgeCursor edges = graph.edges();
- Edge edge;
- HashMap edgeweights = new HashMap();
- try {
- while(edges.ok()) {
- edge = edges.edge();
- String weightStr = graph.getRealizer(edge).getLabel().getText();
- Double weight = Double.parseDouble(weightStr);
- if(weight != null) {
- edgeweights.put(edge, weight);
- }
- else {
- break;
- }
- edges.next();
- }
- } catch (RuntimeException e) {
- // label not set
- }
- edges.toFirst();
- /*
- * all labels correspond numeric
- */
- if(edgeweights.size() == graph.edgeCount()) {
- while(edges.ok()) {
- edge = edges.edge();
- graph.setEdgeWeight(edge, edgeweights.get(edge));
- edges.next();
- }
- }
- return graph;
- }
+
+ @Override
+ public void setParameter(Map param) throws IllegalArgumentException, ParseException {
+
+ }
+
+ @Override
+ public CustomGraph readGraph() throws AdapterException {
+ CustomGraph graph = new CustomGraph();
+ FileSourceGML fileSource = new FileSourceGML();
+ fileSource.addSink(graph);
+
+ try {
+ InputStream inStream = new ByteArrayInputStream(CharStreams.toString(reader)
+ .getBytes(Charsets.UTF_8));
+
+ reader.close();
+
+ fileSource.begin(inStream);
+ while (fileSource.nextEvents()) { //TODO: Check if that is necessary here or if we shouldnt just do readAll
+ if (Thread.interrupted()) {
+ throw new InterruptedException();
+ }
+ }
+ inStream.close();
+ } catch (Exception e) {
+ throw new AdapterException("ERROR Could not read file: " + e.getMessage());
+ }
+
+ /*
+ * Check whether node labels are unique names.
+ */
+ Iterator nodesIt = graph.iterator();
+ Node node;
+ HashMap nodenames = new HashMap();
+ while (nodesIt.hasNext()) {
+ node = nodesIt.next();
+ CharSequence name = node.getLabel("ui.label");
+ if (name == null) {
+ break;
+ }
+ nodenames.put(node, name.toString());
+ }
+ nodesIt = graph.iterator();
+ /*
+ * Node labels are unique.
+ */
+ if (nodenames.size() == graph.getNodeCount()) {
+ while (nodesIt.hasNext()) {
+ node = nodesIt.next();
+ graph.setNodeName(node, nodenames.get(node));
+ }
+ }
+ /*
+ * Node labels are not unique.
+ */
+ else {
+ while (nodesIt.hasNext()) {
+ node = nodesIt.next();
+ graph.setNodeName(node, node.getId()); //TODO: Changed from Index to Id here, check if that makes sense with how graphstream reads it
+ }
+ }
+ /*
+ * Check whether edge labels/weights are numeric.
+ */
+ Iterator edges = graph.edges().iterator();
+ Edge edge;
+ HashMap edgeweights = new HashMap();
+ while (edges.hasNext()) {
+ edge = edges.next();
+ Double weight = edge.getNumber("weight");
+ if (!weight.isNaN()) {
+ edgeweights.put(edge, weight);
+ } else {
+ break;
+ }
+ }
+ edges = graph.edges().iterator();
+ /*
+ * all labels correspond numeric
+ */
+ if (edgeweights.size() == graph.getEdgeCount()) {
+ while (edges.hasNext()) {
+ edge = edges.next();
+ graph.setEdgeWeight(edge, edgeweights.get(edge));
+ }
+ }
+
+ return graph;
+ }
}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/GraphMlGraphInputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/GraphMlGraphInputAdapter.java
index 228da156..52594b4c 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/GraphMlGraphInputAdapter.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/GraphMlGraphInputAdapter.java
@@ -1,27 +1,18 @@
package i5.las2peer.services.ocd.adapters.graphInput;
+import com.google.common.base.Charsets;
+import com.google.common.io.CharStreams;
import i5.las2peer.services.ocd.adapters.AdapterException;
import i5.las2peer.services.ocd.graphs.CustomGraph;
import java.io.ByteArrayInputStream;
-import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Scanner;
-import java.util.Set;
+import java.util.*;
-import y.base.Edge;
-import y.base.EdgeCursor;
-import y.base.EdgeMap;
-import y.base.Node;
-import y.base.NodeCursor;
-import y.base.NodeMap;
-import y.io.GraphMLIOHandler;
-import y.io.graphml.GraphMLHandler;
-import y.io.graphml.KeyScope;
-import y.io.graphml.KeyType;
+import org.graphstream.stream.file.FileSourceGraphML;
+import org.graphstream.graph.Node;
+import org.graphstream.graph.Edge;
/**
* A graph input adapter for GraphML format, based on the GraphMLIOHandler of the yFiles library..
@@ -30,6 +21,7 @@
* @author Sebastian
*
*/
+//TODO: Test for graphstream
public class GraphMlGraphInputAdapter extends AbstractGraphInputAdapter {
@Override
@@ -39,78 +31,71 @@ public void setParameter(Map param) throws IllegalArgumentExcepti
@Override
public CustomGraph readGraph() throws AdapterException {
- Scanner scanner = new Scanner(reader);
- String inString = scanner.useDelimiter("\\A").next();
- scanner.close();
- InputStream is = new ByteArrayInputStream(inString.getBytes());
- GraphMLIOHandler ioh = new GraphMLIOHandler();
CustomGraph graph = new CustomGraph();
- NodeMap nodeNames = graph.createNodeMap();
- EdgeMap edgeWeights = graph.createEdgeMap();
- GraphMLHandler core = ioh.getGraphMLHandler();
- core.addInputDataAcceptor("name", nodeNames, KeyScope.NODE, KeyType.STRING);
- core.addInputDataAcceptor("weight", edgeWeights, KeyScope.EDGE, KeyType.DOUBLE);
+ FileSourceGraphML fileSource = new FileSourceGraphML();
+ fileSource.addSink(graph);
+
try {
- ioh.read(graph, is);
+ InputStream inStream = new ByteArrayInputStream(CharStreams.toString(reader)
+ .getBytes(Charsets.UTF_8));
+
+ reader.close();
+
+ fileSource.begin(inStream);
+ while (fileSource.nextEvents()) { //TODO: Check if that is necessary here or if we shouldnt just do readAll
+ if (Thread.interrupted()) {
+ throw new InterruptedException();
+ }
+ }
+ inStream.close();
+ } catch (Exception e) {
+ throw new AdapterException("ERROR Could not read file: " + e.getMessage());
+ }
/*
* Checks whether node names are unique.
*/
- NodeCursor nodes = graph.nodes();
- Node node;
- String name;
- Set names = new HashSet();
- while(nodes.ok()) {
- name = (String)nodeNames.get(nodes.node());
- if(name == null || name.isEmpty()) {
+ Iterator nodes = graph.iterator();
+ CharSequence name;
+ HashMap names = new HashMap();
+ while(nodes.hasNext()) {
+ Node node = nodes.next();
+ name = node.getLabel("ui.label");
+ if(name == null || name.toString().isEmpty()) {
break;
}
- names.add(name);
- nodes.next();
+ names.put(node.getIndex(), name.toString());
}
- nodes.toFirst();
+ nodes = graph.iterator();
/*
* Sets unique node names.
*/
- if(names.size() == graph.nodeCount()) {
- while(nodes.ok()) {
- node = nodes.node();
- graph.setNodeName(node, (String)nodeNames.get(node));
- nodes.next();
+ if(names.size() == graph.getNodeCount()) {
+ while(nodes.hasNext()) {
+ Node node = nodes.next();
+ graph.setNodeName(node, names.get(node.getIndex()));
}
}
/*
* If names not unique sets indices instead.
*/
else {
- while(nodes.ok()) {
- node = nodes.node();
- graph.setNodeName(node, Integer.toString(node.index()));
- nodes.next();
+ while(nodes.hasNext()) {
+ Node node = nodes.next();
+ graph.setNodeName(node, node.getId()); //TODO: Changed from Index to Id here, check if that makes sense with how graphstream reads it
}
}
- EdgeCursor edges = graph.edges();
+ Iterator edges = graph.edges().iterator();
Edge edge;
- while(edges.ok()) {
- edge = edges.edge();
- Double weight = (Double)edgeWeights.get(edge);
- if(weight != null) {
+ while(edges.hasNext()) {
+ edge = edges.next();
+ Double weight = edge.getNumber("weight");
+ if(!weight.isNaN()) {
graph.setEdgeWeight(edge, weight);
}
else {
break;
}
- edges.next();
}
- } catch (Exception e) {
- throw new AdapterException(e);
- } finally {
- graph.disposeNodeMap(nodeNames);
- graph.disposeEdgeMap(edgeWeights);
- try {
- is.close();
- } catch (IOException e) {
- }
- }
return graph;
}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/LmsTripleStoreGraphInputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/LmsTripleStoreGraphInputAdapter.java
index d16b232b..a24a9769 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/LmsTripleStoreGraphInputAdapter.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/LmsTripleStoreGraphInputAdapter.java
@@ -6,11 +6,11 @@
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
+import java.util.UUID;
import i5.las2peer.services.ocd.adapters.AdapterException;
import i5.las2peer.services.ocd.graphs.CustomGraph;
-import y.base.Edge;
-import y.base.Node;
+import org.graphstream.graph.Node;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryExecution;
@@ -95,9 +95,10 @@ public CustomGraph readGraph() throws AdapterException {
try {
if(!involvedUsers.isEmpty()) {
//System.out.println("Users: " + involvedUsers + " " + involvedUsers.size() + " <" + involvedUserURIs + ">");
+ int i = 0;
for(String userUri : involvedUsers) {
if(users.containsKey(userUri)) {
- Node userNode = graph.createNode();
+ Node userNode = graph.addNode(Integer.toString(i++));
if(showUserNames) {
graph.setNodeName(userNode, users.get(userUri));
}
@@ -111,8 +112,9 @@ public CustomGraph readGraph() throws AdapterException {
}
else {
//create nodes for all users
+ int i = 0;
for(Map.Entry user : users.entrySet()) {
- Node userNode = graph.createNode();
+ Node userNode = graph.addNode(Integer.toString(i++));
if(showUserNames) {
graph.setNodeName(userNode, user.getValue());
}
@@ -137,7 +139,7 @@ public CustomGraph readGraph() throws AdapterException {
for(String interactingUser : interactingUsers) {
//System.out.println("USERS: " + user.getKey() + " " + interactingUser);
if(nodeIds.containsKey(interactingUser)) {
- graph.createEdge(nodeIds.get(interactingUser), user.getValue());
+ graph.addEdge(UUID.randomUUID().toString(), nodeIds.get(interactingUser), user.getValue());
}
}
}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/NodeContentEdgeListGraphInputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/NodeContentEdgeListGraphInputAdapter.java
index 63517051..26dba839 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/NodeContentEdgeListGraphInputAdapter.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/NodeContentEdgeListGraphInputAdapter.java
@@ -4,12 +4,7 @@
import java.io.Reader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
import java.util.Map.Entry;
import i5.las2peer.services.ocd.adapters.AdapterException;
@@ -17,8 +12,8 @@
import i5.las2peer.services.ocd.graphs.CustomGraph;
import i5.las2peer.services.ocd.preprocessing.TextProcessor;
import i5.las2peer.services.ocd.utils.DocIndexer;
-import y.base.Edge;
-import y.base.Node;
+import org.graphstream.graph.Edge;
+import org.graphstream.graph.Node;
/**
* A graph input adapter for a node list which includes a content attribute for each node and edges in form of a
@@ -179,7 +174,7 @@ private CustomGraph readSenderReceiverGraph(int senderIndex, int receiverIndex,
String customNodeReceiver = line.get(receiverIndex);
// node does not yet exist
if(!nodeNames.containsKey(customNodeName)){
- node = graph.createNode(); //create new node and add attributes
+ node = graph.addNode(UUID.randomUUID().toString()); //create new node and add attributes
graph.setNodeName(node , customNodeName);
nodeContents.put(customNodeName, customNodeContent);
//graph.setNodeContent(node, customNodeContent);
@@ -222,7 +217,7 @@ private CustomGraph readSenderReceiverGraph(int senderIndex, int receiverIndex,
HashMap list = entry.getValue();
for(Entry e : list.entrySet()){
if(nodeNames.containsKey(e.getKey())){
- Edge edge = graph.createEdge(curr, nodeNames.get(e.getKey()));
+ Edge edge = graph.addEdge(UUID.randomUUID().toString(), curr, nodeNames.get(e.getKey()));
graph.setEdgeWeight(edge, e.getValue());
}
}
@@ -266,7 +261,7 @@ private CustomGraph readThreadGraph(int nameIndex, int contentIndex, int dateInd
String customNodeContent = textProc.preprocText(line.get(contentIndex));
String customNodeThread = line.get(threadIndex);
if(!nodeNames.containsKey(customNodeName)){
- node = graph.createNode();
+ node = graph.addNode(UUID.randomUUID().toString());
graph.setNodeName(node , customNodeName);
nodeContents.put(customNodeName, customNodeContent);
//graph.setNodeContent(node, customNodeContent);
@@ -302,7 +297,7 @@ private CustomGraph readThreadGraph(int nameIndex, int contentIndex, int dateInd
for(String str:list){
for(Entry> reciever : nodeThreads.entrySet()){
if(curr != reciever.getKey() && reciever.getValue().contains(str)){
- graph.createEdge(curr, reciever.getKey());
+ graph.addEdge(UUID.randomUUID().toString(), curr, reciever.getKey());
//graph.setEdgeWeight(edge, reciever.getValue());
}
}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/NodeIdDeserializationHandler.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/NodeIdDeserializationHandler.java
deleted file mode 100644
index 9cb79bd1..00000000
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/NodeIdDeserializationHandler.java
+++ /dev/null
@@ -1,36 +0,0 @@
-package i5.las2peer.services.ocd.adapters.graphInput;
-
-import java.util.HashMap;
-
-import org.w3c.dom.Element;
-
-import y.io.graphml.input.DeserializationEvent;
-import y.io.graphml.input.DeserializationHandler;
-import y.io.graphml.input.GraphMLParseException;
-
-public class NodeIdDeserializationHandler implements DeserializationHandler {
-
- private HashMap nodeIds = new HashMap();
- int i=0;
-
- @Override
- public void onHandleDeserialization(DeserializationEvent event)
- throws GraphMLParseException {
- // get the element to parse
- org.w3c.dom.Node xmlNode = event.getXmlNode();
-
- // if the element can be parsed
- // create a new instance
- if (xmlNode.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE
- && "node".equals(xmlNode.getLocalName())) {
- // create a new instance with the value of the "value" attribute
- String id = new String(((Element) xmlNode).getAttribute("id"));
- // pass the new instance as result
- // Note: setting the result already marks the event as handled
- nodeIds.put(i, id);
- i++;
- }
-
- }
-
-}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/NodeWeightedEdgeListGraphInputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/NodeWeightedEdgeListGraphInputAdapter.java
index 8a52ddae..b2bd4a28 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/NodeWeightedEdgeListGraphInputAdapter.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/NodeWeightedEdgeListGraphInputAdapter.java
@@ -9,9 +9,10 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.UUID;
-import y.base.Edge;
-import y.base.Node;
+import org.graphstream.graph.Edge;
+import org.graphstream.graph.Node;
/**
* A graph input adapter for node weighted edge list format.
@@ -53,8 +54,9 @@ public CustomGraph readGraph() throws AdapterException {
* Reads nodes
*/
while(line.size() == 1) {
- Node node = graph.createNode();
String nodeName = line.get(0);
+ Node node = graph.addNode(nodeName);
+
if(!reverseNodeNames.containsKey(nodeName)) {
graph.setNodeName(node, nodeName);
reverseNodeNames.put(nodeName, node);
@@ -79,7 +81,7 @@ public CustomGraph readGraph() throws AdapterException {
if(targetNode == null) {
throw new AdapterException("Node not specified: " + targetNodeName);
}
- Edge edge = graph.createEdge(sourceNode, targetNode);
+ Edge edge = graph.addEdge(UUID.randomUUID().toString(), sourceNode, targetNode);
graph.setEdgeWeight(edge, edgeWeight);
line = Adapters.readLine(reader);
}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/UnweightedEdgeListGraphInputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/UnweightedEdgeListGraphInputAdapter.java
index 1fd88586..12993ae2 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/UnweightedEdgeListGraphInputAdapter.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/UnweightedEdgeListGraphInputAdapter.java
@@ -9,9 +9,10 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.UUID;
-import y.base.Edge;
-import y.base.Node;
+import org.graphstream.graph.Edge;
+import org.graphstream.graph.Node;
/**
* A graph input adapter for unweighted edge list format.
@@ -55,7 +56,7 @@ public CustomGraph readGraph() throws AdapterException {
String sourceNodeName = line.get(0);
Node sourceNode;
if (!reverseNodeNames.containsKey(sourceNodeName)) {
- sourceNode = graph.createNode();
+ sourceNode = graph.addNode(sourceNodeName);
reverseNodeNames.put(sourceNodeName, sourceNode);
graph.setNodeName(sourceNode, sourceNodeName);
} else {
@@ -64,13 +65,13 @@ public CustomGraph readGraph() throws AdapterException {
String targetNodeName = line.get(1);
Node targetNode;
if (!reverseNodeNames.containsKey(targetNodeName)) {
- targetNode = graph.createNode();
+ targetNode = graph.addNode(targetNodeName);
reverseNodeNames.put(targetNodeName, targetNode);
graph.setNodeName(targetNode, targetNodeName);
} else {
targetNode = reverseNodeNames.get(targetNodeName);
}
- Edge edge = graph.createEdge(sourceNode, targetNode);
+ Edge edge = graph.addEdge(UUID.randomUUID().toString(), sourceNode, targetNode);
graph.setEdgeWeight(edge, 1);
line = Adapters.readLine(reader);
}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/WeightedEdgeListGraphInputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/WeightedEdgeListGraphInputAdapter.java
index fb949709..911624e0 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/WeightedEdgeListGraphInputAdapter.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/WeightedEdgeListGraphInputAdapter.java
@@ -9,9 +9,10 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.UUID;
-import y.base.Edge;
-import y.base.Node;
+import org.graphstream.graph.Edge;
+import org.graphstream.graph.Node;
/**
* A graph input adapter for weighted edge list format.
@@ -54,7 +55,7 @@ public CustomGraph readGraph() throws AdapterException {
String sourceNodeName = line.get(0);
Node sourceNode;
if (!reverseNodeNames.containsKey(sourceNodeName)) {
- sourceNode = graph.createNode();
+ sourceNode = graph.addNode(sourceNodeName);
reverseNodeNames.put(sourceNodeName, sourceNode);
graph.setNodeName(sourceNode, sourceNodeName);
}
@@ -64,7 +65,7 @@ public CustomGraph readGraph() throws AdapterException {
String targetNodeName = line.get(1);
Node targetNode;
if (!reverseNodeNames.containsKey(targetNodeName)) {
- targetNode = graph.createNode();
+ targetNode = graph.addNode(targetNodeName);
reverseNodeNames.put(targetNodeName, targetNode);
graph.setNodeName(targetNode, targetNodeName);
}
@@ -73,7 +74,7 @@ public CustomGraph readGraph() throws AdapterException {
}
String edgeWeightString = line.get(2);
double edgeWeight = Double.parseDouble(edgeWeightString);
- Edge edge = graph.createEdge(sourceNode, targetNode);
+ Edge edge = graph.addEdge(UUID.randomUUID().toString(), sourceNode, targetNode);
graph.setEdgeWeight(edge, edgeWeight);
line = Adapters.readLine(reader);
}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/XGMMLGraphInputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/XGMMLGraphInputAdapter.java
index 9aa33a2f..1d2990c2 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/XGMMLGraphInputAdapter.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/XGMMLGraphInputAdapter.java
@@ -27,14 +27,13 @@
import i5.las2peer.services.ocd.adapters.AdapterException;
import i5.las2peer.services.ocd.graphs.CustomGraph;
//import i5.las2peer.services.ocd.utils.DocIndexer;
-import y.base.Edge;
-import y.base.Node;
-import y.view.EdgeLabel;
-import y.view.EdgeRealizer;
-import y.view.LineType;
+import org.graphstream.graph.Edge;
+import org.graphstream.graph.Node;
+
import java.io.Reader;
import java.io.FileReader;
+import java.util.UUID;
//TODO: Currently only for the youtube graph, make more general
//TODO: Be able to have more Attributes for nodes(at least string id's) and maybe edges(at least type) in general
@@ -82,8 +81,6 @@ public void setParameter(Map param) throws IllegalArgumentExcept
// Ignore for now as LineTypes are not stored in persistence for some reason
public void setLineType(Element edgeElement, Edge edge, CustomGraph graph) {
if (type1 != "" || type2 != "" || type3 != "") {
- EdgeRealizer eRealizer = graph.getRealizer(edge);
-
NodeList atts = edgeElement.getChildNodes();
if (atts.getLength() != 0) {
if (key.contentEquals("")) {
@@ -93,14 +90,17 @@ public void setLineType(Element edgeElement, Edge edge, CustomGraph graph) {
System.out.println(e.getAttribute(type2));
System.out.println(e.getAttribute("name"));
if (type1 != "" && e.hasAttribute(type1)) {
- eRealizer.setLineType(LineType.LINE_1);
+ edge.setAttribute("ui.fill-mode", "plain");
break;
} else if (type2 != "" && e.hasAttribute(type2)) {
- eRealizer.setLineType(LineType.DASHED_1);
- System.out.println(eRealizer.getLineType().equals(LineType.DASHED_1));
+ edge.setAttribute("ui.fill-mode", "none");
+ edge.setAttribute("ui.size", "0px");
+ edge.setAttribute("ui.stroke-mode", "dashes");
break;
} else if (type3 != "" && e.hasAttribute(type3)) {
- eRealizer.setLineType(LineType.DOTTED_1);
+ edge.setAttribute("ui.fill-mode", "none");
+ edge.setAttribute("ui.size", "0px");
+ edge.setAttribute("ui.stroke-mode", "dots");
break;
}
}
@@ -111,13 +111,17 @@ public void setLineType(Element edgeElement, Edge edge, CustomGraph graph) {
Element e = (Element) atts.item(u);
if (type1 != "" && e.getAttribute(key).contentEquals(type1)) {
- eRealizer.setLineType(LineType.LINE_1);
+ edge.setAttribute("ui.fill-mode", "plain");
break;
} else if (type2 != "" && e.getAttribute(key).contentEquals(type2)) {
- eRealizer.setLineType(LineType.DASHED_1);
+ edge.setAttribute("ui.fill-mode", "none");
+ edge.setAttribute("ui.size", "0px");
+ edge.setAttribute("ui.stroke-mode", "dashes");
break;
} else if (type3 != "" && e.getAttribute(key).contentEquals(type3)) {
- eRealizer.setLineType(LineType.DOTTED_1);
+ edge.setAttribute("ui.fill-mode", "none");
+ edge.setAttribute("ui.size", "0px");
+ edge.setAttribute("ui.stroke-mode", "dots");
break;
}
}
@@ -187,7 +191,7 @@ public CustomGraph readGraph() throws AdapterException {
}
// node does not yet exist
if (!nodeIds.containsKey(customNodeId)) {
- node = graph.createNode(); // create new node and add attributes
+ node = graph.addNode(customNodeId); // create new node and add attributes
graph.setNodeName(node, customNodeId);
nodeIds.put(customNodeId, node);
// nodeContents.put(customNodeName, customNodeContent);
@@ -206,11 +210,11 @@ public CustomGraph readGraph() throws AdapterException {
if (nodeIds.containsKey(e.getAttribute("source")) && nodeIds.containsKey(e.getAttribute("target"))) {
if (!edgeMap.containsKey(e.getAttribute("label"))) {
- Edge edge = graph.createEdge(nodeIds.get(e.getAttribute("source")), nodeIds.get(e.getAttribute("target")));
+ Edge edge = graph.addEdge(UUID.randomUUID().toString(), nodeIds.get(e.getAttribute("source")), nodeIds.get(e.getAttribute("target")));
//setLineType(e, edge, graph);
if (undirected) {
- Edge reverseEdge = graph.createEdge(nodeIds.get(e.getAttribute("target")), nodeIds.get(e.getAttribute("source")));
+ Edge reverseEdge = graph.addEdge(UUID.randomUUID().toString(), nodeIds.get(e.getAttribute("target")), nodeIds.get(e.getAttribute("source")));
//graph.getRealizer(reverseEdge).setLineType(graph.getRealizer(edge).getLineType());
}
edgeMap.put(e.getAttribute("source") + e.getAttribute("target"), edge);
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/XMLGraphInputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/XMLGraphInputAdapter.java
index 6fb76fe4..065a0d72 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/XMLGraphInputAdapter.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphInput/XMLGraphInputAdapter.java
@@ -10,6 +10,7 @@
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.UUID;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
@@ -27,8 +28,8 @@
import i5.las2peer.services.ocd.preprocessing.TextProcessor;
import i5.las2peer.services.ocd.utils.DocIndexer;
//import i5.las2peer.services.ocd.utils.DocIndexer;
-import y.base.Edge;
-import y.base.Node;
+import org.graphstream.graph.Node;
+import org.graphstream.graph.Edge;
public class XMLGraphInputAdapter extends AbstractGraphInputAdapter{
@@ -119,7 +120,7 @@ public CustomGraph readGraph() throws AdapterException{
String customNodeParent = e.getAttribute("ParentId");
// node does not yet exist
if(!nodeNames.containsKey(customNodeName)){
- node = graph.createNode(); //create new node and add attributes
+ node = graph.addNode(customNodeName); //create new node and add attributes
graph.setNodeName(node , customNodeName);
nodeIds.put(customNodeId, node);
nodeContents.put(customNodeName, customNodeContent);
@@ -171,7 +172,7 @@ public CustomGraph readGraph() throws AdapterException{
HashMap list = entry.getValue();
for(Entry e : list.entrySet()){
if(nodeIds.containsKey(e.getKey())){
- Edge edge = graph.createEdge(curr, nodeIds.get(e.getKey()));
+ Edge edge = graph.addEdge(UUID.randomUUID().toString(), curr, nodeIds.get(e.getKey()));
graph.setEdgeWeight(edge, e.getValue());
}
}
@@ -185,10 +186,8 @@ public CustomGraph readGraph() throws AdapterException{
} catch (IOException e) {
e.printStackTrace();
} catch (DOMException e) {
- // TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
- // TODO Auto-generated catch block
e.printStackTrace();
}
return graph;
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphOutput/GraphMlGraphOutputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphOutput/GraphMlGraphOutputAdapter.java
index 49d2160c..15a26673 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphOutput/GraphMlGraphOutputAdapter.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphOutput/GraphMlGraphOutputAdapter.java
@@ -5,52 +5,39 @@
import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import java.util.Iterator;
-import y.base.Edge;
-import y.base.EdgeCursor;
-import y.base.EdgeMap;
-import y.base.Node;
-import y.base.NodeCursor;
-import y.base.NodeMap;
-import y.io.GraphMLIOHandler;
-import y.io.graphml.GraphMLHandler;
-import y.io.graphml.KeyScope;
-import y.io.graphml.KeyType;
+import org.graphstream.graph.Edge;
+import org.graphstream.graph.Node;
+import org.graphstream.stream.file.FileSinkGraphML;
/**
- * A graph output adapter for GraphML format, based on the GraphMLIOHandler of the yFiles library..
- * Node names will be written into a CDATA Section in a "name" element.
- * Edge weights will be written into a "weight" element.
+ * A graph output adapter for GraphML format, based on the GraphMLIOHandler of the graphstream library.
+ * Node names will be written into a CDATA Section in a "name" element. //TODO
+ * Edge weights will be written into a "weight" element. //TODO
* @author Sebastian
*
*/
+//TODO: Check how output of customgraph attributes looks
public class GraphMlGraphOutputAdapter extends AbstractGraphOutputAdapter {
@Override
public void writeGraph(CustomGraph graph) throws AdapterException {
+ FileSinkGraphML fileSink = new FileSinkGraphML();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
- NodeMap nodeNames = graph.createNodeMap();
- NodeCursor nodes = graph.nodes();
- Node node;
- while(nodes.ok()) {
- node = nodes.node();
- nodeNames.set(node, graph.getNodeName(node));
- nodes.next();
+
+ //write node names and edge weights into attributes
+ for (Node node : graph) {
+ node.setAttribute("name", graph.getNodeName(node));
}
- EdgeMap edgeWeights = graph.createEdgeMap();
- EdgeCursor edges = graph.edges();
- Edge edge;
- while(edges.ok()) {
- edge = edges.edge();
- edgeWeights.set(edge, graph.getEdgeWeight(edge));
- edges.next();
+ Iterator edgesIt = graph.edges().iterator();
+ while(edgesIt.hasNext()) {
+ Edge edge = edgesIt.next();
+ edge.setAttribute("weight", graph.getEdgeWeight(edge));
}
- GraphMLIOHandler ioh = new GraphMLIOHandler();
- GraphMLHandler core = ioh.getGraphMLHandler();
- core.addOutputDataProvider("name", nodeNames, KeyScope.NODE, KeyType.STRING);
- core.addOutputDataProvider("weight", edgeWeights, KeyScope.EDGE, KeyType.DOUBLE);
+
try {
- ioh.write(graph, outStream);
+ fileSink.writeAll(graph, outStream);
String outString = outStream.toString();
writer.write(outString);
}
@@ -67,8 +54,6 @@ public void writeGraph(CustomGraph graph) throws AdapterException {
}
catch(IOException e) {
}
- graph.disposeNodeMap(nodeNames);
- graph.disposeEdgeMap(edgeWeights);
}
}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphOutput/MetaXmlGraphOutputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphOutput/MetaXmlGraphOutputAdapter.java
index 521e3401..9fea9633 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphOutput/MetaXmlGraphOutputAdapter.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphOutput/MetaXmlGraphOutputAdapter.java
@@ -35,7 +35,7 @@ public void writeGraph(CustomGraph graph) throws AdapterException {
* Basic Attributes
*/
Element graphIdElt = doc.createElement("Id");
- graphIdElt.appendChild(doc.createTextNode(Long.toString(graph.getId())));
+ graphIdElt.appendChild(doc.createTextNode(graph.getKey()));
graphElt.appendChild(graphIdElt);
Element graphNameElt = doc.createElement("Name");
graphNameElt.appendChild(doc.createTextNode(graph.getName()));
@@ -44,10 +44,10 @@ public void writeGraph(CustomGraph graph) throws AdapterException {
// graphDescrElt.appendChild(doc.createTextNode(graph.getDescription()));
// graphElt.appendChild(graphDescrElt);
Element graphNodeCountElt = doc.createElement("NodeCount");
- graphNodeCountElt.appendChild(doc.createTextNode(Integer.toString(graph.nodeCount())));
+ graphNodeCountElt.appendChild(doc.createTextNode(Integer.toString(graph.getNodeCount())));
graphElt.appendChild(graphNodeCountElt);
Element graphEdgeCountElt = doc.createElement("EdgeCount");
- graphEdgeCountElt.appendChild(doc.createTextNode(Integer.toString(graph.edgeCount())));
+ graphEdgeCountElt.appendChild(doc.createTextNode(Integer.toString(graph.getEdgeCount())));
graphElt.appendChild(graphEdgeCountElt);
// Element lastUpdateElt = doc.createElement("LastUpdate");
// if(graph.getLastUpdate() != null) {
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphOutput/PropertiesXmlGraphOutputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphOutput/PropertiesXmlGraphOutputAdapter.java
index f9218071..7e73eedb 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphOutput/PropertiesXmlGraphOutputAdapter.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphOutput/PropertiesXmlGraphOutputAdapter.java
@@ -28,7 +28,7 @@ public void writeGraph(CustomGraph graph) throws AdapterException {
doc.appendChild(graphElt);
Element graphIdElt = doc.createElement("Id");
- graphIdElt.appendChild(doc.createTextNode(Long.toString(graph.getId())));
+ graphIdElt.appendChild(doc.createTextNode(graph.getKey())); //done
graphElt.appendChild(graphIdElt);
Element graphNameElt = doc.createElement("Name");
@@ -36,14 +36,14 @@ public void writeGraph(CustomGraph graph) throws AdapterException {
graphElt.appendChild(graphNameElt);
Element graphNodeCountElt = doc.createElement("Size");
- graphNodeCountElt.appendChild(doc.createTextNode(Integer.toString(graph.nodeCount())));
+ graphNodeCountElt.appendChild(doc.createTextNode(Integer.toString(graph.getNodeCount())));
graphElt.appendChild(graphNodeCountElt);
Element graphEdgeCountElt = doc.createElement("Links");
if (graph.isDirected()) {
- graphEdgeCountElt.appendChild(doc.createTextNode(Integer.toString(graph.edgeCount())));
+ graphEdgeCountElt.appendChild(doc.createTextNode(Integer.toString(graph.getEdgeCount())));
} else {
- graphEdgeCountElt.appendChild(doc.createTextNode(Integer.toString(graph.edgeCount() / 2)));
+ graphEdgeCountElt.appendChild(doc.createTextNode(Integer.toString(graph.getEdgeCount() / 2)));
}
graphElt.appendChild(graphEdgeCountElt);
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphOutput/WeightedEdgeListGraphOutputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphOutput/WeightedEdgeListGraphOutputAdapter.java
index 3638a548..b41099f3 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphOutput/WeightedEdgeListGraphOutputAdapter.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/graphOutput/WeightedEdgeListGraphOutputAdapter.java
@@ -4,9 +4,9 @@
import i5.las2peer.services.ocd.graphs.CustomGraph;
import java.io.Writer;
+import java.util.Iterator;
-import y.base.Edge;
-import y.base.EdgeCursor;
+import org.graphstream.graph.Edge;
/**
* A graph output adapter for weighted edge list format.
@@ -44,17 +44,16 @@ public void setWeighted(boolean weighted) {
@Override
public void writeGraph(CustomGraph graph) throws AdapterException {
try {
- EdgeCursor edges = graph.edges();
+ Iterator edges = graph.edges().iterator();
Edge edge;
- while(edges.ok()) {
- edge = edges.edge();
- writer.write(graph.getNodeName(edge.source()) + " ");
- writer.write(graph.getNodeName(edge.target()));
+ while(edges.hasNext()) {
+ edge = edges.next();
+ writer.write(graph.getNodeName(edge.getSourceNode()) + " ");
+ writer.write(graph.getNodeName(edge.getTargetNode()));
if(weighted) {
writer.write(" " + String.format("%.2f", graph.getEdgeWeight(edge)));
}
- edges.next();
- if(edges.ok()) {
+ if(edges.hasNext()) {
writer.write("\n");
}
}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/AbstractCentralityMetaOutputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/AbstractCentralityMetaOutputAdapter.java
new file mode 100644
index 00000000..06220ac0
--- /dev/null
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/AbstractCentralityMetaOutputAdapter.java
@@ -0,0 +1,10 @@
+package i5.las2peer.services.ocd.adapters.metaOutput;
+
+import i5.las2peer.services.ocd.adapters.AbstractOutputAdapter;
+
+/**
+ * An abstract class for centrality meta information output adapters.
+ *
+ */
+public abstract class AbstractCentralityMetaOutputAdapter extends AbstractOutputAdapter implements CentralityMetaOutputAdapter {
+}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/AbstractCoverMetaOutputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/AbstractCoverMetaOutputAdapter.java
new file mode 100644
index 00000000..d994f03b
--- /dev/null
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/AbstractCoverMetaOutputAdapter.java
@@ -0,0 +1,11 @@
+package i5.las2peer.services.ocd.adapters.metaOutput;
+
+import i5.las2peer.services.ocd.adapters.AbstractOutputAdapter;
+
+/**
+ * An abstract class for cover meta information output adapters.
+ *
+ */
+public abstract class AbstractCoverMetaOutputAdapter extends AbstractOutputAdapter implements CoverMetaOutputAdapter {
+
+}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/AbstractGraphMetaOutputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/AbstractGraphMetaOutputAdapter.java
new file mode 100644
index 00000000..a67b575a
--- /dev/null
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/AbstractGraphMetaOutputAdapter.java
@@ -0,0 +1,11 @@
+package i5.las2peer.services.ocd.adapters.metaOutput;
+
+import i5.las2peer.services.ocd.adapters.AbstractOutputAdapter;
+
+
+/**
+ * An abstract class for graph meta information output adapters.
+ *
+ */
+public abstract class AbstractGraphMetaOutputAdapter extends AbstractOutputAdapter implements GraphMetaOutputAdapter {
+}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/CentralityMetaOutputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/CentralityMetaOutputAdapter.java
new file mode 100644
index 00000000..10b42ecc
--- /dev/null
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/CentralityMetaOutputAdapter.java
@@ -0,0 +1,19 @@
+package i5.las2peer.services.ocd.adapters.metaOutput;
+
+import i5.las2peer.services.ocd.adapters.AdapterException;
+import i5.las2peer.services.ocd.adapters.OutputAdapter;
+import i5.las2peer.services.ocd.centrality.data.CentralityMeta;
+
+/**
+ * The common interface of centrality output adapters.
+ *
+ */
+public interface CentralityMetaOutputAdapter extends OutputAdapter {
+
+ /**
+ * Writes a CentralityMap and closes the writer.
+ * @param centralityMeta The CentralityMeta instance holding meta information about centrality.
+ * @throws AdapterException if the adapter failed
+ */
+ public void writeCentralityMap(CentralityMeta centralityMeta) throws AdapterException;
+}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/CoverMetaOutputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/CoverMetaOutputAdapter.java
new file mode 100644
index 00000000..2b6af808
--- /dev/null
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/CoverMetaOutputAdapter.java
@@ -0,0 +1,18 @@
+package i5.las2peer.services.ocd.adapters.metaOutput;
+
+import i5.las2peer.services.ocd.adapters.AdapterException;
+import i5.las2peer.services.ocd.adapters.OutputAdapter;
+import i5.las2peer.services.ocd.graphs.CoverMeta;
+
+/**
+ * The common interface of graph output adapters.
+ *
+ */
+public interface CoverMetaOutputAdapter extends OutputAdapter {
+ /**
+ * Writes a cover and closes the writer.
+ * @param coverMeta TThe cover meta information to write.
+ * @throws AdapterException if the adapter failed
+ */
+ public void writeCover(CoverMeta coverMeta) throws AdapterException;
+}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/GraphMetaOutputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/GraphMetaOutputAdapter.java
new file mode 100644
index 00000000..22dc94af
--- /dev/null
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/GraphMetaOutputAdapter.java
@@ -0,0 +1,21 @@
+package i5.las2peer.services.ocd.adapters.metaOutput;
+
+import i5.las2peer.services.ocd.adapters.AdapterException;
+import i5.las2peer.services.ocd.adapters.OutputAdapter;
+import i5.las2peer.services.ocd.graphs.CustomGraphMeta;
+
+
+/**
+ * The common interface of graph output adapters.
+ *
+ */
+public interface GraphMetaOutputAdapter extends OutputAdapter {
+
+ /**
+ * Writes a graph meta and closes the writer.
+ * @param graphMeta The graph meta information to write.
+ * @throws AdapterException if the adapter failed
+ */
+ public void writeGraph(CustomGraphMeta graphMeta) throws AdapterException;
+
+}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/MetaXmlCentralityMetaOutputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/MetaXmlCentralityMetaOutputAdapter.java
new file mode 100644
index 00000000..c0b8d4d3
--- /dev/null
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/MetaXmlCentralityMetaOutputAdapter.java
@@ -0,0 +1,105 @@
+package i5.las2peer.services.ocd.adapters.metaOutput;
+
+import i5.las2peer.services.ocd.adapters.AdapterException;
+import i5.las2peer.services.ocd.centrality.data.CentralityMeta;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import java.util.Map;
+
+/**
+ * A centrality meta information output adapter for the meta XML format. More efficient than
+ * MetaXmlCentralityOutputAdapter due to not loading full centrality details, but only
+ * necessary metadata. The output contains meta information about the centrality and corresponding
+ * graph in XML format.
+ *
+ */
+public class MetaXmlCentralityMetaOutputAdapter extends AbstractCentralityMetaOutputAdapter {
+
+ @Override
+ public void writeCentralityMap(CentralityMeta centralityMeta) throws AdapterException {
+ DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
+ try {
+ DocumentBuilder builder = builderFactory.newDocumentBuilder();
+ Document doc = builder.newDocument();
+ Element mapElt = doc.createElement("CentralityMap");
+ doc.appendChild(mapElt);
+ /*
+ * Basic Attributes
+ */
+ Element nameElt = doc.createElement("Name");
+ nameElt.appendChild(doc.createTextNode(centralityMeta.getCentralityName()));
+ mapElt.appendChild(nameElt);
+ Element idElt = doc.createElement("Id");
+ Element mapIdElt = doc.createElement("CentralityMapId");
+ mapIdElt.appendChild(doc.createTextNode((centralityMeta.getCentralityKey())));
+ idElt.appendChild(mapIdElt);
+ Element graphIdElt = doc.createElement("GraphId");
+ graphIdElt.appendChild(doc.createTextNode(centralityMeta.getGraphKey()));
+ idElt.appendChild(graphIdElt);
+ mapElt.appendChild(idElt);
+ Element graphElt = doc.createElement("Graph");
+ Element graphNameElt = doc.createElement("GraphName");
+ graphNameElt.appendChild(doc.createTextNode(centralityMeta.getGraphName()));
+ graphElt.appendChild(graphNameElt);
+ mapElt.appendChild(graphElt);
+ /*
+ * Creation Method
+ */
+ Element creationMethodElt = doc.createElement("CreationMethod");
+ Element creationMethodTypeElt = doc.createElement("Type");
+ creationMethodTypeElt.appendChild(doc.createTextNode(centralityMeta.getCreationTypeName()));
+ creationMethodTypeElt.setAttribute("displayName", centralityMeta.getCreationTypeDisplayName());
+ creationMethodElt.appendChild(creationMethodTypeElt);
+// /*
+// * Parameters
+// */
+// Element creationMethodParameters = doc.createElement("Parameters");
+// Map parameters = centralityMeta.getCentralityCreationLog().getParameters();
+// for(String parameter : parameters.keySet()) {
+// Element creationMethodParameter = doc.createElement("Parameter");
+// Element creationMethodParameterName = doc.createElement("ParameterName");
+// creationMethodParameterName.appendChild(doc.createTextNode(parameter));
+// Element creationMethodParameterValue = doc.createElement("ParameterValue");
+// creationMethodParameterValue.appendChild(doc.createTextNode(parameters.get(parameter)));
+// creationMethodParameter.appendChild(creationMethodParameterName);
+// creationMethodParameter.appendChild(creationMethodParameterValue);
+// creationMethodParameters.appendChild(creationMethodParameter);
+// }
+// creationMethodElt.appendChild(creationMethodParameters);
+ /*
+ * Status
+ */
+ Element creationMethodStatusElt = doc.createElement("Status");
+ creationMethodStatusElt.appendChild(doc.createTextNode(centralityMeta.getCreationStatusName()));
+ creationMethodElt.appendChild(creationMethodStatusElt);
+ /*
+ * Execution Time
+ */
+ Element creationMethodExecutionTimeElt = doc.createElement("ExecutionTime");
+ creationMethodExecutionTimeElt.appendChild(doc.createTextNode(Long.toString(centralityMeta.getExecutionTime())));
+ creationMethodElt.appendChild(creationMethodExecutionTimeElt);
+
+ mapElt.appendChild(creationMethodElt);
+ /*
+ * XML output
+ */
+ TransformerFactory transformerFactory = TransformerFactory.newInstance();
+ Transformer transformer = transformerFactory.newTransformer();
+ transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+ DOMSource domSource = new DOMSource(doc);
+ StreamResult streamResult = new StreamResult(this.writer);
+ transformer.transform(domSource, streamResult);
+ }
+ catch(Exception e) {
+ throw new AdapterException(e);
+ }
+ }
+}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/MetaXmlCoverMetaOutputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/MetaXmlCoverMetaOutputAdapter.java
new file mode 100644
index 00000000..15c3df5a
--- /dev/null
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/MetaXmlCoverMetaOutputAdapter.java
@@ -0,0 +1,93 @@
+package i5.las2peer.services.ocd.adapters.metaOutput;
+
+import i5.las2peer.services.ocd.adapters.AdapterException;
+import i5.las2peer.services.ocd.graphs.CoverMeta;
+import i5.las2peer.services.ocd.metrics.OcdMetricLog;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import java.util.Map;
+
+/**
+ * A cover meta information output adapter for the meta XML format. More efficient than MetaXmlCoverOutputAdapter
+ * due to not loading full covers/graphs. The output contains meta information about the cover and corresponding
+ * graph in XML format, but not the actual cover/graph instances or other node or edge related meta data.
+ *
+ */
+public class MetaXmlCoverMetaOutputAdapter extends AbstractCoverMetaOutputAdapter{
+ @Override
+ public void writeCover(CoverMeta coverMeta) throws AdapterException {
+ DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
+ try {
+ DocumentBuilder builder = builderFactory.newDocumentBuilder();
+ Document doc = builder.newDocument();
+ Element coverElt = doc.createElement("Cover");
+ doc.appendChild(coverElt);
+ /*
+ * Basic Attributes
+ */
+ Element idElt = doc.createElement("Id");
+ Element coverIdElt = doc.createElement("CoverId");
+ coverIdElt.appendChild(doc.createTextNode(coverMeta.getKey()));
+ idElt.appendChild(coverIdElt);
+ Element graphIdElt = doc.createElement("GraphId");
+ graphIdElt.appendChild(doc.createTextNode(coverMeta.getGraphKey()));
+ idElt.appendChild(graphIdElt);
+ coverElt.appendChild(idElt);
+ Element coverNameElt = doc.createElement("Name");
+ coverNameElt.appendChild(doc.createTextNode(coverMeta.getName()));
+ coverElt.appendChild(coverNameElt);
+// Element coverDescrElt = doc.createElement("Description");
+// coverDescrElt.appendChild(doc.createTextNode(cover.getDescription()));
+// coverElt.appendChild(coverDescrElt);
+ Element graphElt = doc.createElement("Graph");
+ Element graphNameElt = doc.createElement("Name");
+ graphNameElt.appendChild(doc.createTextNode(coverMeta.getGraphName()));
+ graphElt.appendChild(graphNameElt);
+ coverElt.appendChild(graphElt);
+// Element lastUpdateElt = doc.createElement("LastUpdate");
+// if(cover.getLastUpdate() != null) {
+// SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss");
+// lastUpdateElt.appendChild(doc.createTextNode(dateFormat.format(cover.getLastUpdate())));
+// coverElt.appendChild(lastUpdateElt);
+// }
+ /*
+ * Creation Method
+ */
+ Element creationMethodElt = doc.createElement("CreationMethod");
+ Element creationMethodTypeElt = doc.createElement("Type");
+ creationMethodTypeElt.appendChild(doc.createTextNode(coverMeta.getCreationTypeName()));
+ creationMethodElt.appendChild(creationMethodTypeElt);
+ creationMethodElt.setAttribute("displayName", coverMeta.getCreationTypeDisplayName());
+ Element creationMethodStatusElt = doc.createElement("Status");
+ creationMethodStatusElt.appendChild(doc.createTextNode(coverMeta.getCreationStatusName()));
+ creationMethodElt.appendChild(creationMethodStatusElt);
+ coverElt.appendChild(creationMethodElt);
+ /*
+ * Communities
+ */
+ Element communityCountElement = doc.createElement("CommunityCount");
+ communityCountElement.appendChild(doc.createTextNode(Long.toString(coverMeta.getNumberOfCommunities())));
+ coverElt.appendChild(communityCountElement);
+ /*
+ * XML output
+ */
+ TransformerFactory transformerFactory = TransformerFactory.newInstance();
+ Transformer transformer = transformerFactory.newTransformer();
+ transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+ DOMSource domSource = new DOMSource(doc);
+ StreamResult streamResult = new StreamResult(this.writer);
+ transformer.transform(domSource, streamResult);
+ }
+ catch(Exception e) {
+ throw new AdapterException(e);
+ }
+ }
+}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/MetaXmlGraphMetaOutputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/MetaXmlGraphMetaOutputAdapter.java
new file mode 100644
index 00000000..12e1925f
--- /dev/null
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/metaOutput/MetaXmlGraphMetaOutputAdapter.java
@@ -0,0 +1,101 @@
+package i5.las2peer.services.ocd.adapters.metaOutput;
+
+import i5.las2peer.services.ocd.adapters.AdapterException;
+import i5.las2peer.services.ocd.graphs.CustomGraphMeta;
+import i5.las2peer.services.ocd.graphs.GraphType;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+
+
+/**
+ * A graph meta information output adapter for the meta XML format. More efficient than MetaXmlGraphOutputAdapter
+ * due to not loading full graphs. The output contains meta information about the graph in XML format, but
+ * not the actual graph instance or other node or edge related meta data.
+ *
+ */
+public class MetaXmlGraphMetaOutputAdapter extends AbstractGraphMetaOutputAdapter {
+
+ @Override
+ public void writeGraph(CustomGraphMeta graphMeta) throws AdapterException {
+ DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
+ try {
+ DocumentBuilder builder = builderFactory.newDocumentBuilder();
+ Document doc = builder.newDocument();
+ Element graphElt = doc.createElement("Graph");
+ doc.appendChild(graphElt);
+ /*
+ * Basic Attributes
+ */
+ Element graphIdElt = doc.createElement("Id");
+ graphIdElt.appendChild(doc.createTextNode(graphMeta.getKey()));
+ graphElt.appendChild(graphIdElt);
+ Element graphNameElt = doc.createElement("Name");
+ graphNameElt.appendChild(doc.createTextNode(graphMeta.getName()));
+ graphElt.appendChild(graphNameElt);
+// Element graphDescrElt = doc.createElement("Description");
+// graphDescrElt.appendChild(doc.createTextNode(graph.getDescription()));
+// graphElt.appendChild(graphDescrElt);
+ Element graphNodeCountElt = doc.createElement("NodeCount");
+ graphNodeCountElt.appendChild(doc.createTextNode(Long.toString(graphMeta.getNodeCount())));
+ graphElt.appendChild(graphNodeCountElt);
+ Element graphEdgeCountElt = doc.createElement("EdgeCount");
+ graphEdgeCountElt.appendChild(doc.createTextNode(Long.toString(graphMeta.getEdgeCount())));
+ graphElt.appendChild(graphEdgeCountElt);
+// Element lastUpdateElt = doc.createElement("LastUpdate");
+// if(graph.getLastUpdate() != null) {
+// SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss");
+// lastUpdateElt.appendChild(doc.createTextNode(dateFormat.format(graph.getLastUpdate())));
+// graphElt.appendChild(lastUpdateElt);
+// }
+ /*
+ * Graph Types
+ */
+
+ Element typesElt = doc.createElement("Types");
+ for(Integer type_id : graphMeta.getTypes()) {
+
+ if(type_id != null) { // case where graph has no types
+ GraphType type = GraphType.lookupType(type_id);
+ Element typeElt = doc.createElement("Type");
+ typeElt.appendChild(doc.createTextNode(type.name()));
+ typeElt.setAttribute("displayName", type.getDisplayName());
+ typesElt.appendChild(typeElt);
+ }
+ }
+ graphElt.appendChild(typesElt);
+ /*
+ * Creation Method
+ */
+ Element creationMethodElt = doc.createElement("CreationMethod");
+ Element creationMethodTypeElt = doc.createElement("Type");
+ creationMethodTypeElt.appendChild(doc.createTextNode(graphMeta.getCreationTypeName()));
+ creationMethodTypeElt.setAttribute("displayName", graphMeta.getCreationTypeDisplayName());
+ creationMethodElt.appendChild(creationMethodTypeElt);
+ Element creationMethodStatus = doc.createElement("Status");
+ creationMethodStatus.appendChild(doc.createTextNode(graphMeta.getCreationStatusName()));
+ creationMethodElt.appendChild(creationMethodStatus);
+ graphElt.appendChild(creationMethodElt);
+ /*
+ * XML output
+ */
+ TransformerFactory transformerFactory = TransformerFactory.newInstance();
+ Transformer transformer = transformerFactory.newTransformer();
+ transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+ DOMSource domSource = new DOMSource(doc);
+ StreamResult streamResult = new StreamResult(this.writer);
+ transformer.transform(domSource, streamResult);
+ }
+ catch(Exception e) {
+ throw new AdapterException(e);
+ }
+ //System.out.println("end: writing Graph in MetaXmlGraphMetaOutputAdapter");
+ }
+}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/simulationOutput/MetaXmlSimulationOutputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/simulationOutput/MetaXmlSimulationOutputAdapter.java
index 4f821212..7564b84d 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/simulationOutput/MetaXmlSimulationOutputAdapter.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/simulationOutput/MetaXmlSimulationOutputAdapter.java
@@ -58,7 +58,7 @@ public void write(SimulationSeries simulation) throws AdapterException {
private void writeElementsAbstract(SimulationAbstract simulation, Document doc, Element root) {
Element eltId = doc.createElement("Id");
- eltId.appendChild(doc.createTextNode(Long.toString(simulation.getId())));
+ eltId.appendChild(doc.createTextNode(simulation.getKey()));
root.appendChild(eltId);
Element eltName = doc.createElement("Name");
@@ -75,7 +75,7 @@ private void writeElementsAbstract(SimulationAbstract simulation, Document doc,
Element eltGraph = doc.createElement("Graph");
Element eltGraphId = doc.createElement("Id");
- eltGraphId.appendChild(doc.createTextNode(String.valueOf(simulation.getNetwork().getId())));
+ eltGraphId.appendChild(doc.createTextNode(String.valueOf(simulation.getNetwork().getKey())));
eltGraph.appendChild(eltGraphId);
Element eltGraphName = doc.createElement("Name");
eltGraphName.appendChild(doc.createTextNode(String.valueOf(simulation.getNetwork().getName())));
@@ -86,7 +86,7 @@ private void writeElementsAbstract(SimulationAbstract simulation, Document doc,
private void writeElementsSeries(SimulationSeries simulation, Document doc, Element root) {
Element eltGraph = doc.createElement("Parameters");
- SimulationSeriesParameters parameters = simulation.getParameters();
+ SimulationSeriesParameters parameters = simulation.getSimulationSeriesParameters();
Element eltGraphId = doc.createElement("Game");
eltGraphId.appendChild(doc.createTextNode(String.valueOf(parameters.getGame().humanRead())));
eltGraph.appendChild(eltGraphId);
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/visualOutput/JsonVisualOutputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/visualOutput/JsonVisualOutputAdapter.java
index c7bdd5af..d47cece3 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/visualOutput/JsonVisualOutputAdapter.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/visualOutput/JsonVisualOutputAdapter.java
@@ -8,26 +8,19 @@
import net.minidev.json.JSONObject;
import net.minidev.json.JSONArray;
-import y.base.Node;
-import y.base.Edge;
-import y.view.Graph2D;
+import org.graphstream.graph.Node;
+import org.graphstream.graph.Edge;
-import y.view.NodeLabel;
-import java.awt.Color;
-import y.view.NodeRealizer;
-import y.view.ShapeNodeRealizer;
-import y.view.EdgeLabel;
-import y.view.EdgeRealizer;
-import y.view.LineType;
+import java.awt.*;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
+import java.util.Iterator;
-//TODO: Add labels
-public class JsonVisualOutputAdapter extends AbstractVisualOutputAdapter {
+public class JsonVisualOutputAdapter extends AbstractVisualOutputAdapter {
/**
* Creates a new instance setting the writer attribute.
* @param writer The writer used for output.
@@ -43,37 +36,44 @@ public JsonVisualOutputAdapter() {
}
@Override
- public void writeGraph(Graph2D graph) throws AdapterException {
+ //TODO: Check if color values still need to be multiplied with 255
+ public void writeGraph(CustomGraph graph) throws AdapterException {
JSONObject obj = new JSONObject();
// Document doc = builder.newDocument();
ArrayList nodes = new ArrayList();
- for (Node n : graph.getNodeArray()) {
+ Iterator nodesIt = graph.iterator();
+ while (nodesIt.hasNext()) {
+ Node n = nodesIt.next();
HashMap tmp = new HashMap();
- tmp.put("id", n.index());
+ tmp.put("id", n.getIndex());
if(graph instanceof CustomGraph)
{
- tmp.put("name", ((CustomGraph)graph).getNodeName(n));
+ tmp.put("name", graph.getNodeName(n));
}
- NodeRealizer nRealizer = graph.getRealizer(n);
- //TODO: Check what the color is when not set
- //Color
+ //TODO: Check whether default coloring makes sense here
+ //Color
//rgba(r,g,b,a)
- float[] nodeColor = new float[4];
- nodeColor = nRealizer.getFillColor().getRGBComponents(nodeColor);
- tmp.put("color", "rgba(" + nodeColor[0]*255 + "," + nodeColor[1]*255 + "," + nodeColor[2]*255 + "," + nodeColor[3] + ")");
-
- //TODO: Check what the size is when not set
+
+ float[] fillColor = (float[]) n.getAttribute("ui.fill-color");
+ if(fillColor == null) {
+ fillColor = new float[]{0.f,0.f,1.f, 0.6f}; // default coloring
+ }
+ tmp.put("color", "rgba(" + fillColor[0] + "," + fillColor[1] + "," + fillColor[2] + "," + fillColor[3] + ")");
+
+ //TODO: Check whether default size makes sense here
//Size
//As the force graph representation uses circles and height and width are the same in our layoutHandler, this suffices
- double nodeSize = 0.0f;
- nodeSize = nRealizer.getHeight();
- tmp.put("size", nodeSize);
+ double nodeSize = .3f;
+ if(n.getAttribute("ui.size") != null) {
+ tmp.put("size", n.getAttribute("ui.size").toString());
+ }
+ else {
+ tmp.put("size", nodeSize);
+ }
//Label
- String nodeLabel = "";
- nodeLabel = nRealizer.getLabelText();
- tmp.put("label", nodeLabel);
+ tmp.put("label", n.getLabel("label").toString());
JSONObject jsonNode = (JSONObject) JSONValue.parse(JSONValue.toJSONString(tmp));
@@ -82,23 +82,21 @@ public void writeGraph(Graph2D graph) throws AdapterException {
ArrayList edges = new ArrayList();
- for (Edge e : graph.getEdgeArray()) {
+ Iterator edgesIt = graph.edges().iterator();
+ while (edgesIt.hasNext()) {
+ Edge e = edgesIt.next();
HashMap tmp = new HashMap();
- tmp.put("source", e.source().index());
- tmp.put("target", e.target().index());
+ tmp.put("source", e.getSourceNode().getIndex());
+ tmp.put("target", e.getTargetNode().getIndex());
// LINE_STYLE = 0; DASHED_STYLE = 1; DOTTED_STYLE = 2; DASHED_DOTTED_STYLE = 3;
- EdgeRealizer eRealizer = graph.getRealizer(e);
- LineType lineType = LineType.LINE_1;
- lineType = eRealizer.getLineType();
- if(lineType.equals(LineType.DASHED_1))
- {
- System.out.println("WORKED");
- tmp.put("style", 1);
- }
- else if(lineType.equals(LineType.DOTTED_1))
- {
- tmp.put("style", 2);
+ if(e.getAttribute("ui.stroke-mode") != null) {
+ String lineType = e.getAttribute("ui.stroke-mode").toString();
+ if (lineType.equals("dashes")) {
+ tmp.put("style", 1);
+ } else if (lineType.equals("dots")) {
+ tmp.put("style", 2);
+ }
}
else
{
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/visualOutput/SvgVisualOutputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/visualOutput/SvgVisualOutputAdapter.java
index c10efb64..8c87509a 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/visualOutput/SvgVisualOutputAdapter.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/visualOutput/SvgVisualOutputAdapter.java
@@ -5,20 +5,20 @@
import java.io.ByteArrayOutputStream;
import java.io.IOException;
-import y.io.IOHandler;
-import y.view.Graph2D;
-import yext.svg.io.SVGIOHandler;
+import i5.las2peer.services.ocd.graphs.CustomGraph;
+import org.graphstream.stream.file.FileSinkSVG;
public class SvgVisualOutputAdapter extends AbstractVisualOutputAdapter {
@Override
- public void writeGraph(Graph2D graph) throws AdapterException {
+ public void writeGraph(CustomGraph graph) throws AdapterException {
+ FileSinkSVG fileSink = new FileSinkSVG();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
+
// Writes out the graph using the IOHandler
- IOHandler ioh = new SVGIOHandler();
try {
- ioh.write(graph, outStream);
+ fileSink.writeAll(graph, outStream);
String outString = outStream.toString();
writer.write(outString);
}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/visualOutput/VisualOutputAdapter.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/visualOutput/VisualOutputAdapter.java
index 5f3ffb40..884e5de6 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/visualOutput/VisualOutputAdapter.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/adapters/visualOutput/VisualOutputAdapter.java
@@ -2,7 +2,7 @@
import i5.las2peer.services.ocd.adapters.AdapterException;
import i5.las2peer.services.ocd.adapters.OutputAdapter;
-import y.view.Graph2D;
+import i5.las2peer.services.ocd.graphs.CustomGraph;
/**
* The common interface of all visual output adapters.
@@ -16,6 +16,6 @@ public interface VisualOutputAdapter extends OutputAdapter {
* @param graph The graph to write.
* @throws AdapterException if the adapter failed
*/
- public void writeGraph(Graph2D graph) throws AdapterException;
+ public void writeGraph(CustomGraph graph) throws AdapterException;
}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/AntColonyOptimizationAlgorithm.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/AntColonyOptimizationAlgorithm.java
index 7f22b82c..1975b504 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/AntColonyOptimizationAlgorithm.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/AntColonyOptimizationAlgorithm.java
@@ -21,6 +21,7 @@
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
+import java.util.UUID;
import java.lang.Double;
import java.lang.Math;
@@ -29,9 +30,9 @@
import org.la4j.matrix.dense.Basic2DMatrix;
import org.la4j.vector.Vector;
import org.la4j.vector.dense.BasicVector;
-import y.base.Edge;
-import y.base.Node;
-import y.base.NodeCursor;
+import org.graphstream.graph.Graph;
+import org.graphstream.graph.Node;
+import org.graphstream.graph.Edge;
/**
* The original version of the overlapping community detection algorithm introduced in 2020 by Ping Ji, Shanxin Zhang, Zhiping Zhou:
@@ -49,7 +50,7 @@ public class AntColonyOptimizationAlgorithm implements OcdAlgorithm {
* maximal clique encoding. the integer represents the number of the clique and the Hashset stores the
* clique members
*/
- private HashMap> maxClq;
+ private HashMap> maxClq;
/**
* number of ants/subproblems to solve. Must be at least 2 (Otherwise it will result in a division by 0).
@@ -226,7 +227,7 @@ public CoverCreationType getAlgorithmType(){
public Cover detectOverlappingCommunities(CustomGraph graph) throws OcdAlgorithmException, InterruptedException, OcdMetricException {
// construct the maximal clique graph and initialize the parameters
CustomGraph MCR = representationScheme(graph);
- int nodeNr = MCR.nodeCount();
+ int nodeNr = MCR.getNodeCount();
List ants = initialization(MCR, nodeNr);
for(int i = 0; i < maxIterations; i++) {// constructions of the Pareto Front (Pareto optimal solutions)
@@ -251,8 +252,9 @@ public Cover detectOverlappingCommunities(CustomGraph graph) throws OcdAlgorithm
* connected.
* @param graph to make an Maximal Clique Graph from
* @return encoded input graph
+ * @throws InterruptedException If the executing thread was interrupted.
*/
- protected CustomGraph representationScheme(CustomGraph graph) {
+ protected CustomGraph representationScheme(CustomGraph graph) throws InterruptedException {
// maximal clique search
MaximalCliqueSearch MCR = new MaximalCliqueSearch();
maxClq = MCR.cliques(graph);
@@ -265,16 +267,16 @@ protected CustomGraph representationScheme(CustomGraph graph) {
int nodes = maxClq.size();
CustomGraph encoding = new CustomGraph();
for(int i = 0; i < nodes; i++) {//creating clique nodes
- encoding.createNode();
+ encoding.addNode(Integer.toString(i));
}
- for(Node n1: encoding.getNodeArray()) { // creating clique edges
- int i1 = n1.index();
- for(Node n2: encoding.getNodeArray()) {
- int i2 = n2.index();
+ for(Node n1: encoding.nodes().toArray(Node[]::new)) { // creating clique edges
+ int i1 = n1.getIndex();
+ for(Node n2: encoding.nodes().toArray(Node[]::new)) {
+ int i2 = n2.getIndex();
double ls = lkstrgth.get(i1, i2);
if(ls>=wtr) { // filter out weak edges
- Edge e1 = encoding.createEdge(n1, n2);
- Edge e2 = encoding.createEdge(n2, n1);
+ Edge e1 = encoding.addEdge(UUID.randomUUID().toString(),n1, n2);
+ Edge e2 = encoding.addEdge(UUID.randomUUID().toString(),n2, n1);
encoding.setEdgeWeight(e1, ls);
encoding.setEdgeWeight(e2, ls);
}
@@ -288,8 +290,9 @@ protected CustomGraph representationScheme(CustomGraph graph) {
* @param graph Original undirected graph
* @param maxClq output of the MaximalCliqueGraphRepresentation
* @return Matrix of link strength of the clique edges
+ * @throws InterruptedException If the executing thread was interrupted.
*/
- protected Matrix linkStrength(CustomGraph graph, HashMap> maxClq) {
+ protected Matrix linkStrength(CustomGraph graph, HashMap> maxClq) throws InterruptedException {
int clqNr = maxClq.size();
Matrix lkstrgth = new Basic2DMatrix(clqNr,clqNr);
@@ -336,35 +339,35 @@ protected Matrix linkStrength(CustomGraph graph, HashMap>
* @param v1 node which is in a clique
* @param v2 node which is not in the same clique as v1
* @return Czechkanowski Dice distance
+ * @throws InterruptedException If the executing thread was interrupted.
*/
- protected double CzechkanowskiDice(CustomGraph graph, Node v1, Node v2) {
- NodeCursor nbors1 = v1.neighbors();
- NodeCursor nbors2 = v2.neighbors();
+ protected double CzechkanowskiDice(CustomGraph graph, Node v1, Node v2) throws InterruptedException {
+ Node[] nbors1 = graph.getNeighbours(v1).toArray(Node[]::new);
+ Node[] nbors2 = graph.getNeighbours(v2).toArray(Node[]::new);
- int nbor1size = nbors1.size()/2;
- int nbor2size = nbors2.size()/2;
+ int nbor1size = nbors1.length/2;
+ int nbor2size = nbors2.length/2;
// compute the shared neighbors
- double olapsize = 0;
- for(int i = 0 ; i = nbors2.length) {
+ j1=0;
+ }
+ Node n2 = nbors2[j1];
if(n2 == n1) {
olapsize++;
break;
}
-
- nbors2.cyclicNext();
}
-
- nbors1.cyclicNext();
}
// compute the distance
- double edgeNr = graph.edgeCount()/2;
- double nodeNr = graph.nodeCount();
+ double edgeNr = graph.getEdgeCount()/2;
+ double nodeNr = graph.getNodeCount();
double avgDegr = 2*edgeNr/nodeNr;
double tmp1 = avgDegr - nbor1size;
double tmp2 = avgDegr - nbor2size;
@@ -448,7 +451,7 @@ protected List initialization(CustomGraph graph, int nodeNr) throws Interru
heuristic = new Basic2DMatrix(nodeNr,nodeNr); // heuristic information matrix
Matrix neighbors = graph.getNeighbourhoodMatrix();
- Node[] nodes = graph.getNodeArray();
+ Node[] nodes = graph.nodes().toArray(Node[]::new);
pheromones = new ArrayList();
double[][] p = new double[nodeNr][nodeNr];
for(int i = 0; i < nodeNr-1; i++) {
@@ -467,7 +470,7 @@ protected List initialization(CustomGraph graph, int nodeNr) throws Interru
for(int j = i+1; j < nodeNr; j++) {
Node n2 = nodes[j];
double h; // heuristic for edge ij
- if(!graph.containsEdge(n1, n2)) {
+ if(!n1.hasEdgeToward(n2)) {
h = 0;
} else {
Vector nbor2 = neighbors.getRow(j);
@@ -491,8 +494,8 @@ protected List initialization(CustomGraph graph, int nodeNr) throws Interru
h = 1/(1+Math.pow(Math.E, pearson)); // heuristic information value for nodes i, j
// set initial pheromone matrix
- p[n1.index()][n2.index()] = initialPheromones;
- p[n2.index()][n1.index()] = initialPheromones;
+ p[n1.getIndex()][n2.getIndex()] = initialPheromones;
+ p[n2.getIndex()][n1.getIndex()] = initialPheromones;
}
// set heuristic information matrix
@@ -691,7 +694,7 @@ protected void update(CustomGraph graph, List ants, int nodeNr) throws Inte
*/
protected void constructSolution(CustomGraph graph, Ant ant, int nodeNr) throws InterruptedException {
Random rand = new Random();
- Node[] nodes = graph.getNodeArray();
+ Node[] nodes = graph.nodes().toArray(Node[]::new);
ant.setFalseNew_sol();
Matrix phi = new Basic2DMatrix(nodeNr,nodeNr);
@@ -799,7 +802,7 @@ protected double tchebycheffDecomposition(Vector fitness, Vector lambda) {
* @return whether edge (k,l) is contained in solution sol
*/
protected double isEdgeinSol(CustomGraph graph, Vector sol, int k, int l) {
- if(graph.containsEdge(graph.getNodeArray()[l], graph.getNodeArray()[k])&& sol.get(k) == sol.get(l)) {
+ if(graph.getNode(l).hasEdgeToward(graph.getNode(k)) && sol.get(k) == sol.get(l)) { //TODO: Check if this behaves the same as previous
return 1;
}
return 0;
@@ -865,7 +868,7 @@ protected Vector fitnessCalculations(CustomGraph graph, Vector sol, int nodeNr)
*/
protected double cliqueInterconectivity(CustomGraph graph, Vector com1, Vector com2, int nodeNr) {
double L = 0; // counter of edges in between the communities
- Node[] nodes = graph.getNodeArray();
+ Node[] nodes = graph.nodes().toArray(Node[]::new);
for(int i = 0; i < nodeNr; i++) {
if(com1.get(i) == 0) { // filters out all nodes within a community from the community vector
continue;
@@ -876,8 +879,8 @@ protected double cliqueInterconectivity(CustomGraph graph, Vector com1, Vector c
continue;
}
Node n2 = nodes[j];
- if (graph.containsEdge(n1, n2)) { // if two nodes from these two communities are connected by an edge
- L += graph.getEdgeWeight(n1.getEdgeTo(n2));
+ if (n1.hasEdgeToward(n2)) { // if two nodes from these two communities are connected by an edge
+ L += graph.getEdgeWeight(n1.getEdgeToward(n2)); //TODO: Check if this behaves the same as before
}
}
}
@@ -909,13 +912,13 @@ protected Cover decodeMaximalCliques(CustomGraph graph, int nodeNr) throws OcdAl
ModularityMetric MM = new ModularityMetric();
HashSet inCommunity = new HashSet();
- Node[] nodes = graph.getNodeArray();
+ Node[] nodes = graph.nodes().toArray(Node[]::new);
for(Vector sol: EP.values()) {
// find out how many communities are there
List membershipMatrixVectors = new ArrayList(nodeNr);
List com = new ArrayList();
- for(int i = 0; i < graph.nodeCount(); i++) {
+ for(int i = 0; i < graph.getNodeCount(); i++) {
inCommunity.add(nodes[i]);
}
for(int i = 0; i < nodeNr; i++) {
@@ -926,7 +929,7 @@ protected Cover decodeMaximalCliques(CustomGraph graph, int nodeNr) throws OcdAl
}
for(int i = 0; i < nodeNr; i++) { // create empty membership vectors
- Vector v = new BasicVector(graph.nodeCount());
+ Vector v = new BasicVector(graph.getNodeCount());
membershipMatrixVectors.add(i,v);
}
@@ -936,7 +939,7 @@ protected Cover decodeMaximalCliques(CustomGraph graph, int nodeNr) throws OcdAl
for(Node n: entry.getValue()){
inCommunity.remove(n);
Vector v = membershipMatrixVectors.get(member);
- v.set(n.index(), 1);
+ v.set(n.getIndex(), 1);
membershipMatrixVectors.set(member, v); // set node in community
}
}
@@ -945,11 +948,11 @@ protected Cover decodeMaximalCliques(CustomGraph graph, int nodeNr) throws OcdAl
for(Node n: inCommunity) {
Set neighbors = graph.getNeighbours(n);
for(Node neighbor: neighbors) {
- int id = neighbor.index();
+ int id = neighbor.getIndex();
for(int i = 0; i < membershipMatrixVectors.size(); i++) {
Vector v = membershipMatrixVectors.get(i);
if(v.get(id) == 1) {
- v.set(n.index(), 1);
+ v.set(n.getIndex(), 1);
break;
}
}
@@ -958,7 +961,7 @@ protected Cover decodeMaximalCliques(CustomGraph graph, int nodeNr) throws OcdAl
}
// set membership matrix
- Matrix membershipMatrix = new Basic2DMatrix(graph.nodeCount(),com.size());
+ Matrix membershipMatrix = new Basic2DMatrix(graph.getNodeCount(),com.size());
for(int i = 0; i < com.size(); i++) {
membershipMatrix.setColumn(i, membershipMatrixVectors.get(com.get(i)));
}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/BinarySearchRandomWalkLabelPropagationAlgorithm.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/BinarySearchRandomWalkLabelPropagationAlgorithm.java
index 35fbe00c..f510afb5 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/BinarySearchRandomWalkLabelPropagationAlgorithm.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/BinarySearchRandomWalkLabelPropagationAlgorithm.java
@@ -14,6 +14,7 @@
import java.util.Map;
import java.util.Set;
+import org.graphstream.graph.implementations.MultiNode;
import org.la4j.matrix.Matrix;
import org.la4j.matrix.dense.Basic2DMatrix;
import org.la4j.matrix.sparse.CCSMatrix;
@@ -21,10 +22,9 @@
import org.la4j.vector.Vectors;
import org.la4j.vector.dense.BasicVector;
-import y.base.Edge;
-import y.base.EdgeCursor;
-import y.base.Node;
-import y.base.NodeCursor;
+import org.graphstream.graph.Graph;
+import org.graphstream.graph.Node;
+import org.graphstream.graph.Edge;
/**
* Implements a custom extended version of the Random Walk Label Propagation Algorithm, also called DMID, by M. Shahriari, S. Krott and R. Klamma:
@@ -148,22 +148,18 @@ protected Matrix getTransposedDisassortativityMatrix(CustomGraph graph) throws I
* Calculates transposed disassortativity matrix in a special sparse
* matrix format.
*/
- Matrix disassortativities = new CCSMatrix(graph.nodeCount(),
- graph.nodeCount());
- EdgeCursor edges = graph.edges();
+ Matrix disassortativities = new CCSMatrix(graph.getNodeCount(),
+ graph.getNodeCount());
double disassortativity;
- Edge edge;
- while (edges.ok()) {
+ for (Edge edge : graph.edges().toArray(Edge[]::new)) {
if(Thread.interrupted()) {
throw new InterruptedException();
}
- edge = edges.edge();
disassortativity = Math
- .abs(graph.getWeightedInDegree(edge.target())
- - graph.getWeightedInDegree(edge.source()));
- disassortativities.set(edge.target().index(),
- edge.source().index(), disassortativity);
- edges.next();
+ .abs(graph.getWeightedInDegree(edge.getTargetNode())
+ - graph.getWeightedInDegree(edge.getSourceNode()));
+ disassortativities.set(edge.getTargetNode().getIndex(),
+ edge.getSourceNode().getIndex(), disassortativity);
}
/*
@@ -234,23 +230,20 @@ protected Vector executeRandomWalk(Matrix disassortativityMatrix)
*/
protected Vector getLeadershipValues(CustomGraph graph,
Vector disassortativityVector) throws InterruptedException {
- Vector leadershipVector = new BasicVector(graph.nodeCount());
- NodeCursor nodes = graph.nodes();
- Node node;
+ Vector leadershipVector = new BasicVector(graph.getNodeCount());
+
double leadershipValue;
- while (nodes.ok()) {
+ for (Node node : graph.nodes().toArray(Node[]::new)) {
if(Thread.interrupted()) {
throw new InterruptedException();
}
- node = nodes.node();
/*
* Note: degree normalization is left out since it
* does not influence the outcome.
*/
leadershipValue = graph.getWeightedInDegree(node)
- * disassortativityVector.get(node.index());
- leadershipVector.set(node.index(), leadershipValue);
- nodes.next();
+ * disassortativityVector.get(node.getIndex());
+ leadershipVector.set(node.getIndex(), leadershipValue);
}
return leadershipVector;
}
@@ -269,12 +262,12 @@ protected Vector getLeadershipValues(CustomGraph graph,
protected Map getFollowerDegrees(CustomGraph graph,
Vector leadershipVector) throws InterruptedException {
Map followerMap = new HashMap();
- NodeCursor nodes = graph.nodes();
+ Iterator nodes = graph.iterator();
/*
* Iterates over all nodes to detect their local leader
*/
Node node;
- NodeCursor successors;
+ Iterator successorsIt;
double maxInfluence;
List leaders = new ArrayList();
Node successor;
@@ -282,21 +275,21 @@ protected Map getFollowerDegrees(CustomGraph graph,
double successorInfluence;
Edge nodeEdge;
double followerDegree;
- while (nodes.ok()) {
+ while (nodes.hasNext()) {
if(Thread.interrupted()) {
throw new InterruptedException();
}
- node = nodes.node();
- successors = node.successors();
+ node = nodes.next();
+ successorsIt = graph.getSuccessorNeighbours(node).iterator();
maxInfluence = Double.NEGATIVE_INFINITY;
leaders.clear();
/*
* Checks all successors for possible leader
*/
- while (successors.ok()) {
- successor = successors.node();
- successorEdge = node.getEdgeTo(successor);
- successorInfluence = leadershipVector.get(successor.index())
+ while (successorsIt.hasNext()) {
+ successor = successorsIt.next();
+ successorEdge = node.getEdgeToward(successor);
+ successorInfluence = leadershipVector.get(successor.getIndex())
* graph.getEdgeWeight(successorEdge);
if (successorInfluence >= maxInfluence) {
nodeEdge = node.getEdgeFrom(successor);
@@ -305,7 +298,7 @@ protected Map getFollowerDegrees(CustomGraph graph,
*/
if (nodeEdge == null
|| successorInfluence > leadershipVector.get(node
- .index()) * graph.getEdgeWeight(nodeEdge)) {
+ .getIndex()) * graph.getEdgeWeight(nodeEdge)) {
if (successorInfluence > maxInfluence) {
/*
* Other nodes have lower influence
@@ -316,7 +309,6 @@ protected Map getFollowerDegrees(CustomGraph graph,
maxInfluence = successorInfluence;
}
}
- successors.next();
}
if (!leaders.isEmpty()) {
for (Node leader : leaders) {
@@ -328,7 +320,6 @@ protected Map getFollowerDegrees(CustomGraph graph,
followerDegree += 1d / leaders.size());
}
}
- nodes.next();
}
return followerMap;
}
@@ -439,7 +430,8 @@ protected Map executeLabelPropagation(CustomGraph graph,
Iterator nodeIt;
Node node;
double profitability;
- NodeCursor nodeSuccessors;
+ Set nodesuccessors;
+ Iterator nodesuccessorsIt;
Node nodeSuccessor;
do {
if(Thread.interrupted()) {
@@ -456,17 +448,17 @@ protected Map executeLabelPropagation(CustomGraph graph,
while (nodeIt.hasNext()) {
node = nodeIt.next();
profitability = 0;
- nodeSuccessors = node.successors();
- while (nodeSuccessors.ok()) {
- nodeSuccessor = nodeSuccessors.node();
+ nodesuccessors = graph.getSuccessorNeighbours(node);
+ nodesuccessorsIt = nodesuccessors.iterator();
+ while (nodesuccessorsIt.hasNext()) {
+ nodeSuccessor = nodesuccessorsIt.next();
Integer joinIteration = memberships.get(nodeSuccessor);
if (nodeSuccessor.equals(leader) ||
( joinIteration != null && joinIteration < iterationCount)) {
profitability++;
}
- nodeSuccessors.next();
}
- if (profitability / nodeSuccessors.size() > profitabilityThreshold) {
+ if (profitability / nodesuccessors.size() > profitabilityThreshold) {
memberships.put(node, iterationCount);
}
}
@@ -494,32 +486,30 @@ protected Map executeLabelPropagation(CustomGraph graph,
protected Set getBehaviorPredecessors(CustomGraph graph,
Map memberships, Node leader) throws InterruptedException {
Set neighbors = new HashSet();
- NodeCursor leaderPredecessors = leader.predecessors();
+ Iterator leaderpredecessorsIt = graph.getPredecessorNeighbours(leader).iterator();
Node leaderPredecessor;
- while (leaderPredecessors.ok()) {
+ while (leaderpredecessorsIt.hasNext()) {
if(Thread.interrupted()) {
throw new InterruptedException();
}
- leaderPredecessor = leaderPredecessors.node();
+ leaderPredecessor = leaderpredecessorsIt.next();
if (!memberships.containsKey(leaderPredecessor)) {
neighbors.add(leaderPredecessor);
}
- leaderPredecessors.next();
}
- NodeCursor memberPredecessors;
+ Iterator memberpredecessorsIt;
Node memberPredecessor;
for (Node member : memberships.keySet()) {
if(Thread.interrupted()) {
throw new InterruptedException();
}
- memberPredecessors = member.predecessors();
- while (memberPredecessors.ok()) {
- memberPredecessor = memberPredecessors.node();
+ memberpredecessorsIt = graph.getPredecessorNeighbours(member).iterator();
+ while (memberpredecessorsIt.hasNext()) {
+ memberPredecessor = memberpredecessorsIt.next();
if (!memberPredecessor.equals(leader)
&& !memberships.containsKey(memberPredecessor)) {
neighbors.add(memberPredecessor);
}
- memberPredecessors.next();
}
}
return neighbors;
@@ -541,15 +531,12 @@ protected Set getBehaviorPredecessors(CustomGraph graph,
protected boolean areAllNodesAssigned(CustomGraph graph,
Map> communities) throws InterruptedException {
boolean allNodesAreAssigned = true;
- NodeCursor nodes = graph.nodes();
boolean nodeIsAssigned;
- Node node;
- while (nodes.ok()) {
+ for (Node node : graph.nodes().toArray(Node[]::new)) {
if(Thread.interrupted()) {
throw new InterruptedException();
}
nodeIsAssigned = false;
- node = nodes.node();
for (Map.Entry> entry : communities
.entrySet()) {
if (entry.getValue().containsKey(node)) {
@@ -561,7 +548,6 @@ protected boolean areAllNodesAssigned(CustomGraph graph,
allNodesAreAssigned = false;
break;
}
- nodes.next();
}
return allNodesAreAssigned;
}
@@ -580,7 +566,7 @@ protected boolean areAllNodesAssigned(CustomGraph graph,
*/
protected Cover getMembershipDegrees(CustomGraph graph,
Map> communities) throws InterruptedException {
- Matrix membershipMatrix = new Basic2DMatrix(graph.nodeCount(),
+ Matrix membershipMatrix = new Basic2DMatrix(graph.getNodeCount(),
communities.size());
int communityIndex = 0;
double membershipDegree;
@@ -588,11 +574,11 @@ protected Cover getMembershipDegrees(CustomGraph graph,
if(Thread.interrupted()) {
throw new InterruptedException();
}
- membershipMatrix.set(leader.index(), communityIndex, 1.0);
+ membershipMatrix.set(leader.getIndex(), communityIndex, 1.0);
for (Map.Entry entry : communities.get(leader)
.entrySet()) {
membershipDegree = 1.0 / Math.pow(entry.getValue(), 2);
- membershipMatrix.set(entry.getKey().index(), communityIndex,
+ membershipMatrix.set(entry.getKey().getIndex(), communityIndex,
membershipDegree);
}
communityIndex++;
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/ClizzAlgorithm.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/ClizzAlgorithm.java
index 37cb61eb..737c6789 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/ClizzAlgorithm.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/ClizzAlgorithm.java
@@ -21,8 +21,9 @@
import org.la4j.vector.Vectors;
import org.la4j.vector.functor.VectorAccumulator;
-import y.base.Node;
-import y.base.NodeCursor;
+import org.graphstream.graph.Graph;
+import org.graphstream.graph.Node;
+import org.graphstream.graph.Edge;
/**
* The original version of the overlapping community detection algorithm introduced in 2012 by H.J. Li, J. Zhang, Z.P. Liu, L. Chen and X.S. Zhang:
@@ -152,36 +153,32 @@ protected Matrix calculateMemberships(CustomGraph graph, Map lead
Matrix updatedMemberships = initMembershipMatrix(graph, leaders);
Vector membershipContributionVector;
Vector updatedMembershipVector;
- NodeCursor nodes = graph.nodes();
+ Iterator nodesIt = graph.iterator();
Node node;
- NodeCursor successors;
- Node successor;
+ Set successors;
int iteration = 0;
do {
memberships = updatedMemberships;
updatedMemberships = new CCSMatrix(memberships.rows(), memberships.columns());
- while(nodes.ok()) {
+ while(nodesIt.hasNext()) {
if(Thread.interrupted()) {
throw new InterruptedException();
}
- node = nodes.node();
+ node = nodesIt.next();
if(!leaders.keySet().contains(node)) {
- successors = node.successors();
- updatedMembershipVector = memberships.getRow(node.index());
- while(successors.ok()) {
- successor = successors.node();
- membershipContributionVector = memberships.getRow(successor.index());
+ successors = graph.getSuccessorNeighbours(node);
+ updatedMembershipVector = memberships.getRow(node.getIndex());
+ for(Node successor : successors) {
+ membershipContributionVector = memberships.getRow(successor.getIndex());
updatedMembershipVector = updatedMembershipVector.add(membershipContributionVector);
- successors.next();
}
- updatedMemberships.setRow(node.index(), updatedMembershipVector.divide(1 + successors.size()));
+ updatedMemberships.setRow(node.getIndex(), updatedMembershipVector.divide(1 + successors.size()));
}
else {
- updatedMemberships.set(node.index(), leaders.get(node), 1);
+ updatedMemberships.set(node.getIndex(), leaders.get(node), 1);
}
- nodes.next();
}
- nodes.toFirst();
+ nodesIt = graph.iterator();
iteration++;
} while (getMaxDifference(updatedMemberships, memberships) > membershipsPrecisionFactor
&& iteration < membershipsIterationBound);
@@ -225,23 +222,22 @@ protected double getMaxDifference(Matrix matA, Matrix matB) throws InterruptedEx
*/
protected Matrix initMembershipMatrix(CustomGraph graph, Map leaders) throws InterruptedException {
int communityCount = Collections.max(leaders.values()) + 1;
- Matrix memberships = new CCSMatrix(graph.nodeCount(), communityCount);
- NodeCursor nodes = graph.nodes();
+ Matrix memberships = new CCSMatrix(graph.getNodeCount(), communityCount);
+ Iterator nodesIt = graph.iterator();
Node node;
- while(nodes.ok()) {
+ while(nodesIt.hasNext()) {
if(Thread.interrupted()) {
throw new InterruptedException();
}
- node = nodes.node();
+ node = nodesIt.next();
if(leaders.keySet().contains(node)) {
- memberships.set(node.index(), leaders.get(node), 1);
+ memberships.set(node.getIndex(), leaders.get(node), 1);
}
else {
for(int i=0; i lead
* @throws InterruptedException if the thread was interrupted
*/
protected Map determineCommunityLeaders(CustomGraph graph, Matrix distances, Map leadershipValues) throws InterruptedException {
- Node[] nodeArray = graph.getNodeArray();
+ Node[] nodeArray = graph.nodes().toArray(Node[]::new);
Map communityLeaders = new HashMap();
int communityCount = 0;
Set leaders = determineLeaders(graph, distances, leadershipValues);
@@ -270,7 +266,7 @@ protected Map determineCommunityLeaders(CustomGraph graph, Matrix
leader = leaderIt.next();
communityLeaders.put(leader, communityCount);
leaders.remove(leader);
- for(Integer i : getInfluenceNodes(distances.getRow(leader.index()), distances.getColumn(leader.index()))) {
+ for(Integer i : getInfluenceNodes(distances.getRow(leader.getIndex()), distances.getColumn(leader.getIndex()))) {
influenceNode = nodeArray[i];
if(leaders.contains(influenceNode)) {
communityLeaders.put(influenceNode, communityCount);
@@ -296,29 +292,27 @@ protected Map determineCommunityLeaders(CustomGraph graph, Matrix
*/
protected Set determineLeaders(CustomGraph graph, Matrix distances, Map leadershipValues) throws InterruptedException {
Set leaders = new HashSet();
- NodeCursor nodes = graph.nodes();
- Node[] nodeArray = graph.getNodeArray();
+ Iterator nodesIt = graph.iterator();
+ Node[] nodeArray = graph.nodes().toArray(Node[]::new);
Node node;
- while(nodes.ok()) {
- leaders.add(nodes.node());
- nodes.next();
+ while(nodesIt.hasNext()) {
+ leaders.add(nodesIt.next());
}
- nodes.toFirst();
- while(nodes.ok()) {
+ nodesIt = graph.iterator();
+ while(nodesIt.hasNext()) {
if(Thread.interrupted()) {
throw new InterruptedException();
}
- node = nodes.node();
+ node = nodesIt.next();
if(leaders.contains(node)) {
double nodeLeadershipValue = leadershipValues.get(node);
- for(Integer i : getInfluenceNodes(distances.getRow(node.index()), distances.getColumn(node.index()))) {
+ for(Integer i : getInfluenceNodes(distances.getRow(node.getIndex()), distances.getColumn(node.getIndex()))) {
if(leadershipValues.get(nodeArray[i]) > nodeLeadershipValue) {
leaders.remove(node);
break;
}
}
}
- nodes.next();
}
return leaders;
}
@@ -333,16 +327,15 @@ protected Set determineLeaders(CustomGraph graph, Matrix distances, Map calculateLeadershipValues(CustomGraph graph, Matrix distances) throws InterruptedException {
- NodeCursor nodes = graph.nodes();
+ Iterator nodesIt = graph.iterator();
Node node;
Map leadershipValues = new HashMap();
- while(nodes.ok()) {
+ while(nodesIt.hasNext()) {
if(Thread.interrupted()) {
throw new InterruptedException();
}
- node = nodes.node();
- leadershipValues.put(node, getLeadershipValue(distances.getColumn(node.index())));
- nodes.next();
+ node = nodesIt.next();
+ leadershipValues.put(node, getLeadershipValue(distances.getColumn(node.getIndex())));
}
return leadershipValues;
}
@@ -357,20 +350,20 @@ protected Map calculateLeadershipValues(CustomGraph graph, Matrix
* @throws InterruptedException if the thread was interrupted
*/
protected Matrix calculateNodeDistances(CustomGraph graph) throws InterruptedException {
- NodeCursor nodes = graph.nodes();
+ Iterator nodesIt = graph.iterator();
Node node;
- NodeCursor predecessors;
+ Iterator predecessorsIt;
Node predecessor;
double edgeWeight;
double minEdgeWeight = graph.getMinEdgeWeight();
double maxEdgeWeight = graph.getMaxEdgeWeight();
Map influencedNodeDistances = new HashMap();
Map candidateNodeDistances = new HashMap();
- Matrix nodeDistances = new CCSMatrix(graph.nodeCount(), graph.nodeCount());
+ Matrix nodeDistances = new CCSMatrix(graph.getNodeCount(), graph.getNodeCount());
Node closestCandidate;
double closestCandidateDistance;
double updatedDistance;
- while(nodes.ok()) {
+ while(nodesIt.hasNext()) {
if(Thread.interrupted()) {
throw new InterruptedException();
}
@@ -379,17 +372,16 @@ protected Matrix calculateNodeDistances(CustomGraph graph) throws InterruptedExc
*/
influencedNodeDistances.clear();
candidateNodeDistances.clear();
- node = nodes.node();
+ node = nodesIt.next();
influencedNodeDistances.put(node, 0d);
/*
* Initializes node predecessors.
*/
- predecessors = node.predecessors();
- while(predecessors.ok()) {
- predecessor = predecessors.node();
+ predecessorsIt = graph.getPredecessorNeighbours(node).iterator();
+ while(predecessorsIt.hasNext()) {
+ predecessor = predecessorsIt.next();
edgeWeight = graph.getEdgeWeight(node.getEdgeFrom(predecessor));
candidateNodeDistances.put(predecessor, getEdgeLength(edgeWeight, minEdgeWeight, maxEdgeWeight));
- predecessors.next();
}
/*
* Determines node distances to predecessors.
@@ -413,9 +405,9 @@ protected Matrix calculateNodeDistances(CustomGraph graph) throws InterruptedExc
if(closestCandidateDistance <= distanceBound) {
influencedNodeDistances.put(closestCandidate, closestCandidateDistance);
candidateNodeDistances.remove(closestCandidate);
- predecessors = closestCandidate.predecessors();
- while(predecessors.ok()) {
- predecessor = predecessors.node();
+ predecessorsIt = graph.getPredecessorNeighbours(closestCandidate).iterator();
+ while(predecessorsIt.hasNext()) {
+ predecessor = predecessorsIt.next();
edgeWeight = graph.getEdgeWeight(closestCandidate.getEdgeFrom(predecessor));
updatedDistance = closestCandidateDistance + getEdgeLength(edgeWeight, minEdgeWeight, maxEdgeWeight);
if(candidateNodeDistances.containsKey(predecessor)) {
@@ -425,7 +417,6 @@ protected Matrix calculateNodeDistances(CustomGraph graph) throws InterruptedExc
else if(!influencedNodeDistances.containsKey(predecessor)) {
candidateNodeDistances.put(predecessor, updatedDistance);
}
- predecessors.next();
}
}
@@ -435,9 +426,8 @@ else if(!influencedNodeDistances.containsKey(predecessor)) {
*/
influencedNodeDistances.remove(node);
for(Map.Entry entry : influencedNodeDistances.entrySet()) {
- nodeDistances.set(entry.getKey().index(), node.index(), entry.getValue());
+ nodeDistances.set(entry.getKey().getIndex(), node.getIndex(), entry.getValue());
}
- nodes.next();
}
return nodeDistances;
}
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/ContentBasedWeightingAlgorithm.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/ContentBasedWeightingAlgorithm.java
index 4e7b18f3..0ae8f34e 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/ContentBasedWeightingAlgorithm.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/ContentBasedWeightingAlgorithm.java
@@ -1,9 +1,6 @@
package i5.las2peer.services.ocd.algorithms;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
+import java.util.*;
import org.apache.commons.math3.linear.ArrayRealVector;
@@ -13,9 +10,10 @@
import i5.las2peer.services.ocd.graphs.CustomGraph;
import i5.las2peer.services.ocd.graphs.GraphType;
import i5.las2peer.services.ocd.metrics.ExecutionTime;
-import y.base.Edge;
-import y.base.EdgeCursor;
-import y.base.Node;
+
+import org.graphstream.graph.Graph;
+import org.graphstream.graph.Node;
+import org.graphstream.graph.Edge;
/**
* Implements one of the algorithms by Sabrina Haefele conceived in the thesis:
@@ -65,40 +63,37 @@ public CustomGraph detectOverlappingCommunities(CustomGraph graph, ExecutionTime
//et.stop();
Similarities sim = new Similarities();
//normalize weights
- EdgeCursor edges = graph.edges();
- EdgeCursor comp = graph.edges();
+ Iterator edgeIterator = graph.edges().iterator();
+ Iterator comp = graph.edges().iterator();
Edge edge;
Edge compEdge;
double max = 0;
- while(edges.ok()){
- edge = edges.edge();
- while(comp.ok()){
- compEdge = comp.edge();
- if(edge.source().equals(compEdge.source()) || edge.target().equals(compEdge.source())){
+ while(edgeIterator.hasNext()){
+ edge = edgeIterator.next();
+ while(comp.hasNext()){
+ compEdge = comp.next();
+ if(edge.getSourceNode().equals(compEdge.getSourceNode()) || edge.getTargetNode().equals(compEdge.getSourceNode())){
double temp = graph.getEdgeWeight(compEdge);
if(max < temp){
max = temp;
}
}
- comp.next();
}
- comp.toFirst();
+ comp = graph.edges().iterator();
graph.setEdgeWeight(edge, graph.getEdgeWeight(edge)/max);
- edges.next();
}
- edges.toFirst();
+ edgeIterator = graph.edges().iterator();
//compute and combine content-based weight
- while(edges.ok()){
- edge = edges.edge();
- Node source = edge.source();
- Node target = edge.target();
+ while(edgeIterator.hasNext()){
+ edge = edgeIterator.next();
+ Node source = edge.getSourceNode();
+ Node target = edge.getTargetNode();
ArrayRealVector v = (ArrayRealVector) tm.getMatrix().getRowVector(tm.getNodeIdList().indexOf(source));
ArrayRealVector u = (ArrayRealVector) tm.getMatrix().getRowVector(tm.getNodeIdList().indexOf(target));
double s = sim.cosineSim(v, u);
s = (s + graph.getEdgeWeight(edge))/2;
graph.setEdgeWeight(edge, s);
- edges.next();
}
return graph;
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/CostFunctionOptimizationClusteringAlgorithm.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/CostFunctionOptimizationClusteringAlgorithm.java
index 8edd0000..b3d816d6 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/CostFunctionOptimizationClusteringAlgorithm.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/CostFunctionOptimizationClusteringAlgorithm.java
@@ -21,11 +21,12 @@
import i5.las2peer.services.ocd.metrics.ExecutionTime;
import i5.las2peer.services.ocd.algorithms.utils.Similarities;
import i5.las2peer.services.ocd.algorithms.utils.Point;
-import y.base.Node;
import i5.las2peer.services.ocd.algorithms.utils.Cluster;
import i5.las2peer.services.ocd.algorithms.utils.CostFunction;
import i5.las2peer.services.ocd.algorithms.utils.Clustering;
+import org.graphstream.graph.Node;
+
/**
* Implements one of the algorithms by Sabrina Haefele conceived in the thesis:
* Overlapping Community Detection Based on Content and Authority
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/DetectingOverlappingCommunitiesAlgorithm.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/DetectingOverlappingCommunitiesAlgorithm.java
index 45297076..9177bbba 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/DetectingOverlappingCommunitiesAlgorithm.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/DetectingOverlappingCommunitiesAlgorithm.java
@@ -5,8 +5,6 @@
import i5.las2peer.services.ocd.graphs.CoverCreationType;
import i5.las2peer.services.ocd.graphs.CustomGraph;
import i5.las2peer.services.ocd.graphs.GraphType;
-import y.base.Edge;
-import y.base.Node;
import java.util.ArrayList;
import java.util.HashMap;
@@ -17,6 +15,10 @@
import org.la4j.matrix.Matrix;
import org.la4j.matrix.dense.Basic2DMatrix;
+import org.graphstream.graph.Graph;
+import org.graphstream.graph.Node;
+import org.graphstream.graph.Edge;
+
/**
* This class is an implementation of the algorithm by Nam P. Nguyen, Thang N. Dinh, Dung T. Nguyen, My T. Thai:
* Overlapping community structures and their detection on social networks
@@ -120,7 +122,7 @@ public Cover detectOverlappingCommunities(CustomGraph graph)
public Matrix getMembershipMatrix(CustomGraph graph) {
//DEBUG System.out.println(communities);
- Matrix membershipMatrix = new Basic2DMatrix(graph.nodeCount(), communities.size());
+ Matrix membershipMatrix = new Basic2DMatrix(graph.getNodeCount(), communities.size());
int j=0;
for(Map.Entry> communityPair : communities.entrySet()) {
@@ -149,17 +151,17 @@ public Matrix getMembershipMatrix(CustomGraph graph) {
*/
public void findOverlappingCommunityStructures(CustomGraph graph) throws OcdAlgorithmException, InterruptedException {
communityIntersections = new ArrayList(); // initialize communityIntersections
- nodeDegrees = new HashMap(graph.nodeCount());
- adjacencyList = new HashMap>(graph.nodeCount());
- for(Node node : graph.getNodeArray()) {// Initialize nodeDegree, maxDegree, AdjacencyList
+ nodeDegrees = new HashMap(graph.getNodeCount());
+ adjacencyList = new HashMap>(graph.getNodeCount());
+ for(Node node : graph.nodes().toArray(Node[]::new)) {// Initialize nodeDegree, maxDegree, AdjacencyList
Set neighbours = graph.getNeighbours(node);
- nodeDegrees.put(node.index(), neighbours.size());
+ nodeDegrees.put(node.getIndex(), neighbours.size());
- maxDegree = Math.max(maxDegree, nodeDegrees.get(node.index()));
+ maxDegree = Math.max(maxDegree, nodeDegrees.get(node.getIndex()));
- adjacencyList.put(node.index(), new ArrayList(neighbours.size()));
+ adjacencyList.put(node.getIndex(), new ArrayList(neighbours.size()));
for(Node neighbour : neighbours) {
- adjacencyList.get(node.index()).add(neighbour.index());
+ adjacencyList.get(node.getIndex()).add(neighbour.getIndex());
}
}
@@ -177,10 +179,10 @@ public void findOverlappingCommunityStructures(CustomGraph graph) throws OcdAlgo
*/
public void findDenseCommunities(CustomGraph graph) throws OcdAlgorithmException, InterruptedException {
// initialize nodeCommunities, communityNumbers, intersectionCounters
- communityNumbers = new ArrayList(graph.nodeCount());
+ communityNumbers = new ArrayList(graph.getNodeCount());
intersectionCounters = new HashMap();
- nodeCommunities = new HashMap>(graph.nodeCount());
- for(int i=0; i<=graph.nodeCount(); i++) { // initially, each node has one community ID, TODO: i was 1 first, check if this breaks anything
+ nodeCommunities = new HashMap>(graph.getNodeCount());
+ for(int i=0; i<=graph.getNodeCount(); i++) { // initially, each node has one community ID, TODO: i was 1 first, check if this breaks anything
nodeCommunities.put(i, new HashMap());
communityNumbers.add(0);
}
@@ -191,10 +193,10 @@ public void findDenseCommunities(CustomGraph graph) throws OcdAlgorithmException
communityEdgeSizes = new HashMap();
int numEdge=0;
- for(Edge edge : graph.getEdgeArray()) { // reading from the beginning of file
- if (!sameCommunity(edge.source().index(), edge.target().index()))
+ for(Edge edge : graph.edges().toArray(Edge[]::new)) { // reading from the beginning of file
+ if (!sameCommunity(edge.getSourceNode().getIndex(), edge.getTargetNode().getIndex()))
{ // if a and b are not in a community together
- tryFormingNewCommunity(edge.source().index(), edge.target().index(), graph); // try to form a dense local community from (a,b)
+ tryFormingNewCommunity(edge.getSourceNode().getIndex(), edge.getTargetNode().getIndex(), graph); // try to form a dense local community from (a,b)
}
if(Thread.interrupted()) {
throw new InterruptedException();
@@ -372,7 +374,7 @@ public int findCommunityAdjacencyList(int comA, HashMap commun
updateCounter(); // update the counter
for(i=0; i graph.nodeCount() || x <0) { //TODO: was <= 0, see if this changes anything
+ if (x > graph.getNodeCount() || x <0) { //TODO: was <= 0, see if this changes anything
throw new OcdAlgorithmException("Error: x > N || x <0 in findComAdjList: " + x + " " + communities.get(comA));
}
if (communityNumbers.get(x) < 2) { // skip x if it is in just one community
@@ -625,14 +627,14 @@ public void findCommunityIntersection(int comA, int comB) {
*/
public void findTinyCommunities(CustomGraph graph) throws OcdAlgorithmException {
realCommunityCount = communityCount;
- for(Edge edge : graph.getEdgeArray()) { // Read the adjacent list to find N and M
- if ( communityNumbers.get(edge.source().index())>0 || communityNumbers.get(edge.target().index())>0 ) {
+ for(Edge edge : graph.edges().toArray(Edge[]::new)) { // Read the adjacent list to find N and M
+ if ( communityNumbers.get(edge.getSourceNode().getIndex())>0 || communityNumbers.get(edge.getTargetNode().getIndex())>0 ) {
continue;
}
- findNodeIntersection(edge.source().index(), edge.target().index(), graph); // Find the intersection of the two adjacencyLists
+ findNodeIntersection(edge.getSourceNode().getIndex(), edge.getTargetNode().getIndex(), graph); // Find the intersection of the two adjacencyLists
if (nodeIntersectionCounter == 3) { // If we find a triangle
- if (communityCount >= graph.nodeCount()) { // If communityCount exceeds the upper bound, return error
- throw new OcdAlgorithmException("Error : numCOM >= MULTI_N in findTinyCommunities()" + " " + communities.size() + " " + graph.nodeCount() + "\n" + communities);
+ if (communityCount >= graph.getNodeCount()) { // If communityCount exceeds the upper bound, return error
+ throw new OcdAlgorithmException("Error : numCOM >= MULTI_N in findTinyCommunities()" + " " + communities.size() + " " + graph.getNodeCount() + "\n" + communities);
}
markNodes(communityCount + 1); // Mark all the nodes in the intersection
communityCount++;
@@ -663,7 +665,7 @@ public void visitUnAssignedVertices(CustomGraph graph) throws OcdAlgorithmExcept
maxOutliers = 0; // The number of outliers
findNumDegList(numDegList); // Find the numDegList;
oldCommunityNodeSizes = new HashMap(communityNodeSizes);
- for(i=0; i 0) {
continue;
}
@@ -701,7 +703,7 @@ public void visitUnAssignedVertices(CustomGraph graph) throws OcdAlgorithmExcept
}
}
//finalRefinement(oldCommunityNodeSizes, graph); // Final refinement TODO: Remove
- for(i=1;i<=graph.nodeCount();i++) {
+ for(i=1;i<=graph.getNodeCount();i++) {
maxCommunityNumber = Math.max( maxCommunityNumber, communityNumbers.get(i) );
}
for(i=1;i<=communityCount;i++) {
@@ -745,7 +747,7 @@ private int findTau(int n, CustomGraph graph) throws OcdAlgorithmException { //
if (n <= 3) { // if we dont have enough nodes
return 0;
}
- if (n > graph.nodeCount()) { // if the number of nodes gets too large
+ if (n > graph.getNodeCount()) { // if the number of nodes gets too large
throw new OcdAlgorithmException("Error: Counter too large for findTau");
}
int pn = n*(n-1)/2; // since we have a safety check above, this step should not be a problem
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/EvolutionaryAlgorithmBasedOnSimilarity.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/EvolutionaryAlgorithmBasedOnSimilarity.java
index bc256d13..287c0f28 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/EvolutionaryAlgorithmBasedOnSimilarity.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/EvolutionaryAlgorithmBasedOnSimilarity.java
@@ -1,36 +1,23 @@
package i5.las2peer.services.ocd.algorithms;
import java.io.File;
-//import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
+import java.util.*;
import i5.las2peer.services.ocd.algorithms.mea.MeaAlgorithm;
-import org.apache.commons.exec.CommandLine;
-import org.apache.commons.exec.DefaultExecuteResultHandler;
import org.apache.commons.exec.DefaultExecutor;
-import org.apache.commons.lang3.SystemUtils;
import org.la4j.matrix.Matrix;
import org.la4j.matrix.sparse.CCSMatrix;
-import java.util.Scanner;
-
import i5.las2peer.services.ocd.algorithms.utils.OcdAlgorithmException;
-import i5.las2peer.services.ocd.benchmarks.OcdBenchmarkException;
import i5.las2peer.services.ocd.graphs.Cover;
import i5.las2peer.services.ocd.graphs.CoverCreationType;
import i5.las2peer.services.ocd.graphs.CustomGraph;
import i5.las2peer.services.ocd.graphs.GraphType;
-import y.base.Edge;
-import y.base.EdgeCursor;
-import y.base.Node;
-import y.base.NodeCursor;
+
+import org.graphstream.graph.Node;
+import org.graphstream.graph.Edge;
/**
* Implements the algorithm by C. Liu, J. Liu, and Z. Jiang:
@@ -38,8 +25,8 @@
* https://doi.org/10.1109/TCYB.2014.2305974
* @author YLi
*/
+//TODO: Rework this algorithm implementation so that it doesn't need to produce pajek files anymore, they are an unnecessary extra step
public class EvolutionaryAlgorithmBasedOnSimilarity implements OcdAlgorithm {
-
/**
* Path of the directory reserved for the application.
*/
@@ -100,20 +87,19 @@ public Cover detectOverlappingCommunities(CustomGraph graph) throws OcdAlgorithm
* the network file to have the index 1. If not, the input file
* should be adapted.
*/
- NodeCursor nodes = graph.nodes();
+ Iterator nodes = graph.iterator();
Node node;
int count = 0;
- while (nodes.ok()) {
- node = nodes.node();
+ while (nodes.hasNext()) {
+ node = nodes.next();
if (count == 0) {
- minNodeIndex = node.index();
+ minNodeIndex = node.getIndex();
} else {
- if (node.index() < minNodeIndex) {
- minNodeIndex = node.index();
+ if (node.getIndex() < minNodeIndex) {
+ minNodeIndex = node.getIndex();
}
}
count++;
- nodes.next();
}
writeNetworkFile(graph);
@@ -124,7 +110,7 @@ public Cover detectOverlappingCommunities(CustomGraph graph) throws OcdAlgorithm
}catch(Exception e){}
- int nodeCount = graph.nodeCount();
+ int nodeCount = graph.getNodeCount();
Matrix membershipMatrix = translateCommunityFile(LastResultPath, nodeCount);
Cover cover = new Cover(graph, membershipMatrix);
return cover;
@@ -153,26 +139,25 @@ protected void writeNetworkFile(CustomGraph graph) throws IOException, Interrupt
try {
networkFile.write(String.format("*Vertices "));
networkFile.write("\t");
- networkFile.write(Integer.toString(graph.nodeCount()));
+ networkFile.write(Integer.toString(graph.getNodeCount()));
networkFile.write(System.lineSeparator());
networkFile.write(String.format("*Edges"));
networkFile.write(System.lineSeparator());
- EdgeCursor edges = graph.edges();
+ Iterator edges = graph.edges().iterator();
Edge edge;
- while (edges.ok()) {
+ while (edges.hasNext()) {
if (Thread.interrupted()) {
throw new InterruptedException();
}
- edge = edges.edge();
- if (edge.source().index() <= edge.target().index()) {
- networkFile.write(Integer.toString(edge.source().index() + (1 - minNodeIndex)));// networkFile.write(Integer.toString(edge.source().index()+1));
+ edge = edges.next();
+ if (edge.getSourceNode().getIndex() <= edge.getTargetNode().getIndex()) {
+ networkFile.write(Integer.toString(edge.getSourceNode().getIndex() + (1 - minNodeIndex)));// networkFile.write(Integer.toString(edge.getSourceNode().getIndex()+1));
networkFile.write("\t");
- networkFile.write(Integer.toString(edge.target().index() + (1 - minNodeIndex)));// networkFile.write(Integer.toString(edge.source().index()+1));
+ networkFile.write(Integer.toString(edge.getTargetNode().getIndex() + (1 - minNodeIndex)));// networkFile.write(Integer.toString(edge.getSourceNode().getIndex()+1));
networkFile.write("\t");
networkFile.write(Double.toString(graph.getEdgeWeight(edge)));
networkFile.write(System.lineSeparator());
}
- edges.next();
}
} finally {
networkFile.close();
diff --git a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/ExtendedSpeakerListenerLabelPropagationAlgorithm.java b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/ExtendedSpeakerListenerLabelPropagationAlgorithm.java
index 704f31d1..318044e9 100644
--- a/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/ExtendedSpeakerListenerLabelPropagationAlgorithm.java
+++ b/rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/ExtendedSpeakerListenerLabelPropagationAlgorithm.java
@@ -24,8 +24,9 @@
import org.la4j.vector.Vector;
import org.la4j.vector.sparse.CompressedVector;
-import y.base.Node;
-import y.base.NodeCursor;
+import org.graphstream.graph.Graph;
+import org.graphstream.graph.Node;
+import org.graphstream.graph.Edge;
/**
* Implements a custom extended version of the original Speaker Listener Label Propagation Algorithm by J. Xie, B. K. Szymanski, and X. Liu:
@@ -138,12 +139,12 @@ public Cover detectOverlappingCommunities(
List memory;
for(int t=0; t+1> memories, List nodeOrder) throws InterruptedException {
List memory;
- for(int i=0; i();
memory.add(i);
memories.add(memory);
- nodeOrder.add(graph.getNodeArray()[i]);
+ nodeOrder.add(nodeArray[i]);
}
}
@@ -173,15 +175,15 @@ protected void initializeCommunityDetection(CustomGraph graph, List> memories, Node listener) {
+ protected int getNextLabel(CustomGraph graph, List> memories, Node listener) throws InterruptedException {
Map