Skip to content
Snippets Groups Projects
Commit 967946c5 authored by Thiemo Belmega's avatar Thiemo Belmega
Browse files

Migrate project to maven webapp archetype

parent 5546ad47
No related branches found
No related tags found
No related merge requests found
Showing
with 1140 additions and 0 deletions
pom.xml 0 → 100644
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>de.unipotsdam.cs</groupId>
<artifactId>toolup</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>toolup Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.9.9</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20151123</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.19</version>
</dependency>
</dependencies>
<build>
<finalName>toolup</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
package de.unipotsdam.cs.toolup.database;
import de.unipotsdam.cs.toolup.exceptions.InvalidIdException;
import de.unipotsdam.cs.toolup.model.*;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
public class DatabaseController {
public static final String TABLE_NAME_FEATURE = "feature";
public static final String TABLE_NAME_CATEGORY = "category";
public static final String TABLE_NAME_APPLICATION = "application";
public static final String TABLE_NAME_APPLICATION_FEATURE = "application_has_feature";
public static final String TABLE_NAME_APPLICATION_CATEGORY = "application_belongs_to_category";
private static final String COLUMN_SUFFIX_UUID = "_uuid";
private static DatabaseController instance;
private SqlStatementFactory sqlStatementFactory;
protected DatabaseController() throws IOException, SQLException {
sqlStatementFactory = new SqlStatementFactory();
}
public static DatabaseController getInstance() throws IOException, SQLException {
if (instance == null) {
instance = new DatabaseController();
}
return instance;
}
public BusinessObject load(String uuid) throws SQLException, InvalidIdException {
String tableName = BusinessObject.getTableNameFromId(uuid);
PreparedStatement prepQuery = sqlStatementFactory.getSelectAllFrom(tableName);
prepQuery.setString(1, uuid);
ResultSet res = prepQuery.executeQuery();
return BusinessObjectFactory.createBusinessObjectFromSingleResult(res);
}
public Set<String> loadRelatedBusinessObjectsForId(String tableName, String targetBusinessObjectType, String id) throws SQLException, InvalidIdException {
String criteriaBusinessObjectType = BusinessObject.getTableNameFromId(id);
PreparedStatement prepQuery = sqlStatementFactory.getSelectRelation(tableName, criteriaBusinessObjectType + COLUMN_SUFFIX_UUID);
prepQuery.setString(1, id);
ResultSet res = prepQuery.executeQuery();
return getRelatedIdsFromResultSet(targetBusinessObjectType + COLUMN_SUFFIX_UUID,
res);
}
private Set<String> getRelatedIdsFromResultSet(
String resultColumnName, ResultSet res) throws SQLException {
Set<String> relatedIds = new HashSet<>();
while (res.next()) {
relatedIds.add(res.getString(resultColumnName));
}
return relatedIds;
}
public Set<String> loadRelatedCategoriesForApp(String id) throws SQLException, InvalidIdException {
return loadRelatedBusinessObjectsForId(TABLE_NAME_APPLICATION_CATEGORY, TABLE_NAME_CATEGORY, id);
}
public Set<String> loadRelatedApplicationsForCat(String id) throws SQLException, InvalidIdException {
return loadRelatedBusinessObjectsForId(TABLE_NAME_APPLICATION_CATEGORY, TABLE_NAME_APPLICATION, id);
}
public Set<String> loadRelatedFeaturesForApp(String id) throws SQLException, InvalidIdException {
return loadRelatedBusinessObjectsForId(TABLE_NAME_APPLICATION_FEATURE, TABLE_NAME_FEATURE, id);
}
public Collection<String> loadRelatedApplicationsForFeat(String id) throws SQLException, InvalidIdException {
return loadRelatedBusinessObjectsForId(TABLE_NAME_APPLICATION_FEATURE, TABLE_NAME_APPLICATION, id);
}
public boolean checkIfExistsInDB(BusinessObject aBusinessObject) throws SQLException, InvalidIdException {
return checkIfExistsInDB(aBusinessObject.getUuid());
}
public boolean checkIfExistsInDB(String id) throws SQLException, InvalidIdException {
BusinessObject objectFromDB = load(id);
return !(objectFromDB instanceof NullBusinessObject);
}
public void storeToDatabase(BusinessObject aBusinessObject) throws SQLException, InvalidIdException {
boolean exists = checkIfExistsInDB(aBusinessObject);
if (exists) {
updateDatabase(aBusinessObject);
} else {
insertIntoDatabase(aBusinessObject);
}
}
private void insertIntoDatabase(BusinessObject aBusinessObject)
throws SQLException, InvalidIdException {
String tableName = BusinessObject.getTableNameFromId(aBusinessObject.getUuid());
insertBO(aBusinessObject, tableName);
insertRelations(aBusinessObject, tableName);
}
private void insertRelations(BusinessObject aBusinessObject,
String tableName) throws SQLException {
if (aBusinessObject.getRelatedBOs().isEmpty()) return;
switch (tableName) {
case TABLE_NAME_APPLICATION: {
Application app = (Application) aBusinessObject;
insertSingleRelationInto(TABLE_NAME_APPLICATION_FEATURE, app.getUuid(), 1, app.getRelatedFeatures());
insertSingleRelationInto(TABLE_NAME_APPLICATION_CATEGORY, app.getUuid(), 1, app.getRelatedCategories());
break;
}
case TABLE_NAME_CATEGORY: {
Category cat = (Category) aBusinessObject;
insertSingleRelationInto(TABLE_NAME_APPLICATION_CATEGORY, cat.getUuid(), 2, cat.getRelatedApplications());
break;
}
case TABLE_NAME_FEATURE: {
Feature feat = (Feature) aBusinessObject;
insertSingleRelationInto(TABLE_NAME_APPLICATION_FEATURE, feat.getUuid(), 2, feat.getRelatedApplications());
break;
}
default:
throw new NotImplementedException();
}
}
/**
* @param tableName the name of the relation table
* @param uuid the BO thats relations are to be stored
* @param uuidColumnNumber column number of the BOs id in the table. 1 if BO is Application, 2 otherwise.
* @param relatedIds a collection of the uuid's of related BOs
* @throws SQLException
*/
private void insertSingleRelationInto(String tableName, String uuid,
int uuidColumnNumber, Collection<String> relatedIds) throws SQLException {
for (String foreignKey : relatedIds) {
PreparedStatement prepQuery;
prepQuery = sqlStatementFactory.getInsertRelation(tableName);
prepQuery.setString(uuidColumnNumber, uuid);
prepQuery.setString((uuidColumnNumber % 2) + 1, foreignKey);
prepQuery.executeUpdate();
}
}
private void insertBO(BusinessObject aBusinessObject,
String tableName) throws SQLException {
PreparedStatement prepQuery;
prepQuery = sqlStatementFactory.getInsertInto(tableName);
prepQuery.setString(1, aBusinessObject.getUuid());
prepQuery.setString(2, aBusinessObject.getTitle());
prepQuery.setString(3, aBusinessObject.getDescription());
prepQuery.executeUpdate();
}
private void updateDatabase(BusinessObject aBusinessObject)
throws SQLException, InvalidIdException {
String tableName = BusinessObject.getTableNameFromId(aBusinessObject.getUuid());
updateBO(aBusinessObject, tableName);
updateRelations(aBusinessObject, tableName);
}
private void updateRelations(BusinessObject aBusinessObject,
String tableName) throws SQLException {
if (aBusinessObject.getRelatedBOs().isEmpty()) return;
switch (tableName) {
case TABLE_NAME_APPLICATION: {
Application app = (Application) aBusinessObject;
updateSingleRelation(TABLE_NAME_APPLICATION_FEATURE, app.getUuid(), 1, app.getRelatedFeatures());
updateSingleRelation(TABLE_NAME_APPLICATION_CATEGORY, app.getUuid(), 1, app.getRelatedCategories());
break;
}
case TABLE_NAME_CATEGORY: {
Category cat = (Category) aBusinessObject;
updateSingleRelation(TABLE_NAME_APPLICATION_CATEGORY, cat.getUuid(), 2, cat.getRelatedApplications());
break;
}
case TABLE_NAME_FEATURE: {
Feature feat = (Feature) aBusinessObject;
updateSingleRelation(TABLE_NAME_APPLICATION_FEATURE, feat.getUuid(), 2, feat.getRelatedApplications());
break;
}
default:
throw new NotImplementedException();
}
}
private void updateSingleRelation(
String tableName, String uuid, int uuidColumnNumber,
Collection<String> relatedIds) throws SQLException {
for (String foreignKey : relatedIds) {
PreparedStatement prepQuery;
prepQuery = sqlStatementFactory.getInsertRelation(tableName);
prepQuery.setString(uuidColumnNumber, uuid);
prepQuery.setString((uuidColumnNumber % 2) + 1, foreignKey);
prepQuery.executeUpdate();
}
}
private void updateBO(BusinessObject aBusinessObject,
String tableName) throws SQLException {
PreparedStatement prepQuery;
prepQuery = sqlStatementFactory.getUpdate(tableName);
prepQuery.setString(1, aBusinessObject.getTitle());
prepQuery.setString(2, aBusinessObject.getDescription());
prepQuery.setString(3, aBusinessObject.getUuid());
prepQuery.executeUpdate();
}
public void deleteFromDatabase(String id) throws SQLException, InvalidIdException {
String tableName = BusinessObject.getTableNameFromId(id);
PreparedStatement prepQuery = sqlStatementFactory.getDeleteFrom(tableName);
prepQuery.setString(1, id);
prepQuery.executeUpdate();
}
}
package de.unipotsdam.cs.toolup.database;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
public class SqlStatementFactory {
private static final String TOKEN_TABLE_NAME = "TABLE_NAME";
private static final File SQL_STATEMENT_FILE = new File("SQL_Statements.xml").getAbsoluteFile();
private static final CharSequence TOKEN_FOREIGN_KEY = "FOREIGN_KEY";
private final Connection connection;
private Properties sqlStatements;
public SqlStatementFactory() throws IOException, SQLException {
sqlStatements = new Properties();
sqlStatements.loadFromXML(new FileInputStream(SQL_STATEMENT_FILE));
connection = DriverManager.getConnection(ToolUpProperties.getDatabaseUrl());
}
public PreparedStatement getSelectRelation(
String relationName, String criteriaAttribute) throws SQLException {
String preparedQuery = sqlStatements.getProperty("selectRelation");
preparedQuery = preparedQuery.replace(TOKEN_TABLE_NAME, relationName).replace(TOKEN_FOREIGN_KEY, criteriaAttribute);
return connection.prepareStatement(preparedQuery);
}
public PreparedStatement getSelectAllFrom(String tableName) throws SQLException {
return getCustomizedStatement("selectBO", tableName);
}
public PreparedStatement getInsertInto(String tableName) throws SQLException {
return getCustomizedStatement("insertBO", tableName);
}
public PreparedStatement getInsertRelation(String tableName) throws SQLException {
return getCustomizedStatement("insertRelation", tableName);
}
public PreparedStatement getDeleteFrom(String tableName) throws SQLException {
return getCustomizedStatement("deleteBO", tableName);
}
public PreparedStatement getUpdate(String tableName) throws SQLException {
return getCustomizedStatement("updateBO", tableName);
}
private PreparedStatement getCustomizedStatement(String statementKey, String tableName) throws SQLException {
String preparedQuery;
preparedQuery = sqlStatements.getProperty(statementKey);
preparedQuery = preparedQuery.replace(TOKEN_TABLE_NAME, tableName);
return connection.prepareStatement(preparedQuery);
}
}
package de.unipotsdam.cs.toolup.database;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class ToolUpProperties {
private static final String KEY_SERVERADRESS = "database server adress";
private static final String KEY_SERVERPORT = "database server port";
private static final String KEY_USERNAME = "database user name";
private static final String KEY_PASSWORD = "database password";
private static final String KEY_SCHEMA = "database schema";
private static final String DATABASE_CONNECTOR = "jdbc:mysql://";
static File PROPERTIES_FILE = new File("Tool.UP_cfg.xml");
private static String DATABASE_URL = null;
private static Properties PROPERTIES = null;
/**
* Constructs the database url out of the read properties.
*
* @return the url of the configured DB
* @throws IOException
*/
public static String getDatabaseUrl() throws IOException {
if (DATABASE_URL == null) {
DATABASE_URL = DATABASE_CONNECTOR +
getProperties().getProperty(KEY_SERVERADRESS) +
":" +
getProperties().getProperty(KEY_SERVERPORT) +
"/" +
getProperties().getProperty(KEY_SCHEMA) +
"?user=" +
getProperties().getProperty(KEY_USERNAME + "&pw=") +
getProperties().getProperty(KEY_PASSWORD);
}
return DATABASE_URL;
}
/**
* @return the ToolUp singleton Properties object
* @throws IOException
*/
public static Properties getProperties() throws IOException {
if (PROPERTIES == null) {
loadPropertiesFromFile();
}
return PROPERTIES;
}
private static synchronized void loadPropertiesFromFile() throws IOException {
if (PROPERTIES == null) {
PROPERTIES = new Properties();
PROPERTIES.loadFromXML(new FileInputStream(PROPERTIES_FILE));
}
}
}
package de.unipotsdam.cs.toolup.exceptions;
public class InvalidIdException extends Exception {
/**
*
*/
private static final long serialVersionUID = 2665632580697692893L;
}
package de.unipotsdam.cs.toolup.model;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import static de.unipotsdam.cs.toolup.database.DatabaseController.TABLE_NAME_CATEGORY;
import static de.unipotsdam.cs.toolup.database.DatabaseController.TABLE_NAME_FEATURE;
public class Application extends BusinessObject {
public Application(String uuid, String title, String description, Set<String> relatedCategories, Set<String> relatedFeatures) {
super(uuid, title, description);
this.relations.put(TABLE_NAME_CATEGORY, relatedCategories);
this.relations.put(TABLE_NAME_FEATURE, relatedFeatures);
}
public Application(String uuid) {
this(uuid, "", "", new HashSet<String>(), new HashSet<String>());
}
public Collection<String> getRelatedCategories() {
return new HashSet<>(this.relations.get(TABLE_NAME_CATEGORY));
}
public Collection<String> getRelatedFeatures() {
return new HashSet<>(this.relations.get(TABLE_NAME_FEATURE));
}
}
package de.unipotsdam.cs.toolup.model;
import de.unipotsdam.cs.toolup.exceptions.InvalidIdException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.*;
import static de.unipotsdam.cs.toolup.database.DatabaseController.*;
public abstract class BusinessObject {
static final String JSON_KEY_ID = "id";
static final String JSON_KEY_DESCRIPTION = "description";
static final String JSON_KEY_TITLE = "title";
static final String JSON_KEY_FEATURES = "features";
static final String JSON_KEY_CATEGORIES = "categories";
static final String JSON_KEY_APPLICATIONS = "applications";
static Map<String, String> keyMappingSqlJson = new HashMap<>(); //TODO Move to config file
static {
keyMappingSqlJson.put(TABLE_NAME_APPLICATION, JSON_KEY_APPLICATIONS);
keyMappingSqlJson.put(TABLE_NAME_CATEGORY, JSON_KEY_CATEGORIES);
keyMappingSqlJson.put(TABLE_NAME_FEATURE, JSON_KEY_FEATURES);
}
protected final HashMap<String, Collection<String>> relations = new HashMap<>();
protected String uuid;
protected String title;
protected String description;
public BusinessObject(String uuid, String title, String description) {
this.uuid = uuid;
this.title = title;
this.description = description;
}
public BusinessObject(String uuid) {
this(uuid, "", "");
}
/**
* Extract the table name out of the uuid.
* The uuid is structured like this: tablename/1234567
*
* @param uuid the id of a BO
* @return an SQL table name
* @throws InvalidIdException
*/
public static String getTableNameFromId(String uuid) throws InvalidIdException {
if (!uuid.contains("/")) {
throw new InvalidIdException();
}
int indexOfFirstSlash = uuid.indexOf('/');
return uuid.substring(0, indexOfFirstSlash);
}
/**
* Create a new BusinessObject with the values of a JSON representation.
*
* @param jsonRepresentation the JSON representation of a BO
* @return a BO represented by the JSON input
* @throws JSONException
* @throws InvalidIdException
*/
public static BusinessObject createBusinessObjectFromJson(
JSONObject jsonRepresentation) throws JSONException, InvalidIdException {
String id = jsonRepresentation.getString(JSON_KEY_ID);
BusinessObject newlyCreatedBO = BusinessObjectFactory.createInstance(id);
newlyCreatedBO.title = jsonRepresentation.getString(JSON_KEY_TITLE);
newlyCreatedBO.description = jsonRepresentation.getString(JSON_KEY_DESCRIPTION);
addRelationFromJson(newlyCreatedBO, jsonRepresentation, JSON_KEY_APPLICATIONS);
addRelationFromJson(newlyCreatedBO, jsonRepresentation, JSON_KEY_FEATURES);
addRelationFromJson(newlyCreatedBO, jsonRepresentation, JSON_KEY_CATEGORIES);
return newlyCreatedBO;
}
private static void addRelationFromJson(BusinessObject newlyCreatedBO,
JSONObject jsonRepresentation, String relationKey) throws JSONException, InvalidIdException {
if (jsonRepresentation.has(relationKey)) {
JSONArray relationElements = jsonRepresentation.getJSONArray(relationKey);
addIdsOfAllElements(newlyCreatedBO, relationElements);
}
}
private static void addIdsOfAllElements(BusinessObject newlyCreatedBO,
JSONArray relationElements) throws JSONException, InvalidIdException {
for (int i = 0; i < relationElements.length(); i++) {
JSONObject app = relationElements.getJSONObject(i);
newlyCreatedBO.addRelation(app.getString(JSON_KEY_ID));
}
}
public String getUuid() {
return this.uuid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
/**
* A BusinesObject is defined to equal an other, if the uuid is equal.
*
* @param anOtherBO a BusinessObject instance to compare with
* @return true, if and only if the uuid is equal.
*/
public boolean equals(BusinessObject anOtherBO) {
return this.uuid.equals(anOtherBO.getUuid());
}
/**
* Checks if all the properties of the other BO has the same values as this BO.
*
* @param anOtherBO a BusinessObject instance to compare with
* @return true, if and only if the field values are equal.
*/
public boolean equalsInAllProperties(BusinessObject anOtherBO) {
if (!this.uuid.equals(anOtherBO.getUuid())) return false;
if (!this.title.equals(anOtherBO.getTitle())) return false;
if (!this.description.equals(anOtherBO.getDescription())) return false;
for (String relationName : this.relations.keySet()) {
if (!this.relations.get(relationName).equals(anOtherBO.relations.get(relationName))) {
return false;
}
}
return true;
}
/**
* Extract the table name out of the uuid.
* The uuid is structured like this: tablename/1234567
*
* @return an SQL table name
* @throws InvalidIdException
*/
public String getTableName() throws InvalidIdException {
return getTableNameFromId(this.uuid);
}
/**
* Converts a collection of uuids into a JSONArray, which contains JSONObjects of the pattern {"id":<uuid>"}
*
* @param relation a collection of related business objects
* @return a JSONArray representation of the input collection
* @throws JSONException
*/
protected JSONArray relationAsJsonArray(Collection<String> relation) throws JSONException {
JSONArray categories = new JSONArray();
for (String s : relation) {
categories.put(new JSONObject("{\"id\":\"" + s + "\"}"));
}
return categories;
}
/**
* Creates a JSONObject with the values of this business objects' fields.
*/
public JSONObject convertToJson() throws JSONException {
JSONObject result = new JSONObject();
result.put(JSON_KEY_ID, this.uuid);
result.put(JSON_KEY_TITLE, this.title);
result.put(JSON_KEY_DESCRIPTION, this.description);
createRelationRepresentations(result);
return result;
}
private void createRelationRepresentations(JSONObject result)
throws JSONException {
for (String key : this.relations.keySet()) {
String relationName = keyMappingSqlJson.get(key);
Collection<String> relatedIds = this.relations.get(key);
result.put(relationName, relationAsJsonArray(relatedIds));
}
}
/**
* Gets a union of this object's related ids.
*
* @return a union of this object's related ids.
*/
public Set<String> getRelatedBOs() {
Set<String> relatedBOs = new HashSet<>();
for (Collection<String> relationToSingleType : relations.values()) {
relatedBOs.addAll(relationToSingleType);
}
return relatedBOs;
}
/**
* Adds the given id to this object's relations.
*
* @param id the id of a BO
* @throws InvalidIdException
*/
public void addRelation(String id) throws InvalidIdException {
String tableName = getTableNameFromId(id);
if (!relations.containsKey(tableName)) {
throw new IllegalArgumentException("Business Object of this type can not be related to an application: " + id);
}
this.relations.get(tableName).add(id);
}
}
package de.unipotsdam.cs.toolup.model;
import de.unipotsdam.cs.toolup.database.DatabaseController;
import de.unipotsdam.cs.toolup.exceptions.InvalidIdException;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;
import static de.unipotsdam.cs.toolup.model.BusinessObject.*;
public class BusinessObjectFactory {
private static final String KEY_UUID = "uuid";
private static final String TABLENAME_FEATURE = "feature";
private static final String TABLENAME_CATEGORY = "category";
private static final String TABLENAME_APPLICATION = "application";
private static DatabaseController db;
static {
try {
db = DatabaseController.getInstance();
} catch (IOException | SQLException e) {
throw new RuntimeException("Could not create DatabaseController.", e);
}
}
private static BusinessObject createBusinessObjectWithLoadedRelations(String id, String title,
String description) throws SQLException, InvalidIdException {
int indexOfFirstSlash = id.indexOf('/');
String className = id.substring(0, indexOfFirstSlash);
switch (className.toLowerCase()) {
case TABLENAME_APPLICATION:
return new Application(id, title, description, db.loadRelatedCategoriesForApp(id), db.loadRelatedFeaturesForApp(id));
case TABLENAME_CATEGORY:
return new Category(id, title, description, db.loadRelatedApplicationsForCat(id));
case TABLENAME_FEATURE:
return new Feature(id, title, description, db.loadRelatedApplicationsForFeat(id));
default:
throw new UnsupportedOperationException("No class defined for this prefix:" + className);
}
}
/**
* @param res the result of a database query
* @return NullBusinessObject if result set set is empty,
* otherwise an instance of the matching subclass of BusinessObject with the loaded data.
* @throws SQLException
* @throws InvalidIdException
*/
public static BusinessObject createBusinessObjectFromSingleResult(
ResultSet res) throws SQLException, InvalidIdException {
if (!res.first()) {
return NullBusinessObject.getInstance();
}
String id = res.getString(KEY_UUID);
String title = res.getString(JSON_KEY_TITLE);
String description = res.getString(JSON_KEY_DESCRIPTION);
return createBusinessObjectWithLoadedRelations(id, title, description);
}
public static BusinessObject createInstance(String id) throws InvalidIdException {
String type = getTableNameFromId(id);
switch (type.toLowerCase()) {
case TABLENAME_APPLICATION:
return new Application(id);
case TABLENAME_CATEGORY:
return new Category(id);
case TABLENAME_FEATURE:
return new Feature(id);
default:
throw new UnsupportedOperationException("No class defined for this prefix:" + type);
}
}
public static BusinessObject createInstance(String id, String title,
String description) throws InvalidIdException {
BusinessObject bo = createInstance(id);
bo.setTitle(title);
bo.setDescription(description);
return bo;
}
public static BusinessObject createInstanceWithNewUuid(String tablename) throws InvalidIdException {
return createInstance(tablename + "/" + UUID.randomUUID());
}
}
package de.unipotsdam.cs.toolup.model;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import static de.unipotsdam.cs.toolup.database.DatabaseController.TABLE_NAME_APPLICATION;
public class Category extends BusinessObject {
public Category(String uuid, String title, String description, Set<String> relatedApplications) {
super(uuid, title, description);
this.relations.put(TABLE_NAME_APPLICATION, relatedApplications);
}
public Category(String uuid) {
this(uuid, "", "", new HashSet<String>());
}
public Collection<String> getRelatedApplications() {
return new HashSet<>(this.relations.get(TABLE_NAME_APPLICATION));
}
}
package de.unipotsdam.cs.toolup.model;
import java.util.Collection;
import java.util.HashSet;
import static de.unipotsdam.cs.toolup.database.DatabaseController.TABLE_NAME_APPLICATION;
public class Feature extends BusinessObject {
public Feature(String uuid, String title, String description, Collection<String> relatedApplications) {
super(uuid, title, description);
this.relations.put(TABLE_NAME_APPLICATION, relatedApplications);
}
public Feature(String uuid) {
this(uuid, "", "", new HashSet<String>());
}
public Collection<String> getRelatedApplications() {
return new HashSet<>(this.relations.get(TABLE_NAME_APPLICATION));
}
}
package de.unipotsdam.cs.toolup.model;
/**
* NullBusinessObject represents the absence of a {@link BusinessObject} according to the NullObjectPattern.
*
* @author Thiemo
*/
public class NullBusinessObject extends BusinessObject {
private static NullBusinessObject instance = null;
private NullBusinessObject() {
super("", "Null Object", "This object represents null.");
}
/**
* NullBusinessObject represents the absence of a {@link BusinessObject}.
*
* @return The singleton instance of {@link NullBusinessObject}
*/
public static BusinessObject getInstance() {
//Singleton implementation without synchronization, does not matter
if (instance == null) {
instance = new NullBusinessObject();
}
return instance;
}
@Override
public void addRelation(String string) {
}
}
package de.unipotsdam.cs.toolup.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class FileUtil {
public static final String UTF_8 = StandardCharsets.UTF_8.toString();
private static final String END_OF_FILE = "\\A";
/**
* Returns the content of a text file as String.
*/
public static String readFile(File f) throws IOException {
return readFile(new FileInputStream(f));
}
/**
* Returns the content of a text file as String.
*
* @param s path to an existing text file
*/
public static String readFile(String s) throws IOException {
return readFile(new File(s));
}
/**
* Returns the content of a text file as String.
*/
public static String readFile(InputStream i) throws IOException {
Scanner scan = new Scanner(i, UTF_8);
scan.useDelimiter(END_OF_FILE);
String content = scan.next();
scan.close();
return content;
}
}
package de.unipotsdam.cs.toolup.util;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import static org.testng.AssertJUnit.fail;
public class JSONUtil {
/**
* If actualJson does not contain the equal content to expectedJson, this method calls testng's fail().
* The order of elements is not relevant.
*/
public static void assertEqualJSONContent(JSONObject expectedJson,
JSONObject actualJson) throws JSONException {
if (!equalJSONContent(expectedJson, actualJson)) {
fail();
}
}
public static boolean equalJSONContent(JSONObject firstJson,
JSONObject secondJson) throws JSONException {
return containsJSONContent(firstJson, secondJson) && containsJSONContent(secondJson, firstJson);
}
/**
* Returns true, only if the first JSONObject contains all the content of the second JSONObject.
*/
public static boolean containsJSONContent(JSONObject firstJson,
JSONObject secondJson) throws JSONException {
boolean equal = true;
String[] keys = JSONObject.getNames(secondJson);
for (String key : keys) {
Object value = secondJson.get(key);
equal = thisJSONhasEqualProperty(firstJson, key, value);
}
return equal;
}
private static boolean thisJSONhasEqualProperty(JSONObject firstJson,
String key, Object value) throws JSONException {
Object compareValue = firstJson.opt(key);
return equalJsonValues(value, compareValue);
}
private static boolean equalJsonValues(Object value, Object compareValue)
throws JSONException {
if (compareValue instanceof JSONObject) {
return containsJSONContent((JSONObject) compareValue, (JSONObject) value);
} else if (compareValue instanceof JSONArray) {
return containsJSONContent((JSONArray) compareValue, (JSONArray) value);
} else {
return value.equals(compareValue);
}
}
private static boolean containsJSONContent(JSONArray firstJson,
JSONArray secondJson) throws JSONException {
for (int i = 0; i < secondJson.length(); i++) {
Object value = secondJson.get(i);
if (arrayDoesNotContainValue(firstJson, value)) {
return false;
}
}
return true;
}
private static boolean arrayDoesNotContainValue(JSONArray firstJson,
Object value) throws JSONException {
for (int i = 0; i < firstJson.length(); i++) {
Object compareValue = firstJson.get(i);
if (equalJsonValues(value, compareValue)) {
return false;
}
}
return true;
}
}
package de.unipotsdam.cs.toolup.ws.resource;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path(BusinessObjectResource.PATH_APPLICATION)
public class ApplicationResource extends BusinessObjectResource {
@GET
@Path("{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response get(@PathParam(PARAM_ID) String id) {
return getBusinessObject(id);
}
}
package de.unipotsdam.cs.toolup.ws.resource;
import de.unipotsdam.cs.toolup.database.DatabaseController;
import de.unipotsdam.cs.toolup.exceptions.InvalidIdException;
import de.unipotsdam.cs.toolup.model.BusinessObject;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import java.io.IOException;
import java.sql.SQLException;
public class BusinessObjectResource {
protected static final String PATH_APPLICATION = "/application";
protected static final String PATH_FEATURE = "/feature";
protected static final String PATH_CATEGORY = "/category";
protected static final String PARAM_ID = "id";
protected Response getBusinessObject(String id) {
Response response;
try {
BusinessObject app = DatabaseController.getInstance().load(id);
response = Response.ok(app).build();
} catch (SQLException | IOException e) {
e.printStackTrace();
response = Response.serverError().build();
} catch (InvalidIdException e) {
response = Response.status(Status.NOT_FOUND).build();
}
return response;
}
}
package de.unipotsdam.cs.toolup.ws.resource;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path(BusinessObjectResource.PATH_CATEGORY)
public class CategoryResource extends BusinessObjectResource {
@GET
@Path("{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response get(@PathParam(PARAM_ID) String id) {
return getBusinessObject(id);
}
}
package de.unipotsdam.cs.toolup.ws.resource;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path(BusinessObjectResource.PATH_FEATURE)
public class FeatureResource extends BusinessObjectResource {
@GET
@Path("{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response get(@PathParam(PARAM_ID) String id) {
return getBusinessObject(id);
}
}
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="selectBO">SELECT * FROM TABLE_NAME WHERE uuid = ?;</entry>
<entry key="insertBO">INSERT INTO TABLE_NAME VALUES (?,?,?);</entry>
<entry key="updateBO">UPDATE TABLE_NAME SET title = ?, description = ? WHERE uuid = ?;</entry>
<entry key="deleteBO">DELETE FROM TABLE_NAME WHERE uuid = ?;</entry>
<entry key="selectRelation">SELECT * FROM TABLE_NAME WHERE FOREIGN_KEY = ?;</entry>
<entry key="deleteRelation">DELETE FROM FROM TABLE_NAME WHERE FOREIGN_KEY = ?;</entry>
<entry key="insertRelation">INSERT INTO TABLE_NAME VALUES (?,?);</entry>
</properties>
DROP SCHEMA test;
CREATE SCHEMA test;
USE test;
CREATE TABLE application (
uuid VARCHAR(64) NOT NULL,
title VARCHAR(128) NOT NULL,
description LONGTEXT,
PRIMARY KEY (uuid)
);
CREATE TABLE category (
uuid VARCHAR(64) NOT NULL,
title VARCHAR(128) NOT NULL,
description LONGTEXT,
PRIMARY KEY (uuid)
);
CREATE TABLE feature (
uuid VARCHAR(64) NOT NULL,
title VARCHAR(128) NOT NULL,
description LONGTEXT,
PRIMARY KEY (uuid)
);
CREATE TABLE application_belongs_to_category (
application_uuid VARCHAR(64) NOT NULL,
category_uuid VARCHAR(64) NOT NULL,
PRIMARY KEY (application_uuid, category_uuid),
FOREIGN KEY (application_uuid) REFERENCES application (uuid)
ON DELETE CASCADE,
FOREIGN KEY (category_uuid) REFERENCES category (uuid)
ON DELETE CASCADE
);
CREATE TABLE application_has_feature (
application_uuid VARCHAR(64) NOT NULL,
feature_uuid VARCHAR(64) NOT NULL,
PRIMARY KEY (application_uuid, feature_uuid),
FOREIGN KEY (application_uuid) REFERENCES application (uuid)
ON DELETE CASCADE,
FOREIGN KEY (feature_uuid) REFERENCES feature (uuid)
ON DELETE CASCADE
);
INSERT INTO application VALUES ('application/test_id_1', 'Dropbox', 'Dropbox Description');
INSERT INTO application VALUES ('application/test_id_2', 'Box.UP', 'Box.UP Description');
INSERT INTO category VALUES ('category/test_id_11', 'Cloud Speicher', 'Cloud Speicher Description');
INSERT INTO category VALUES ('category/test_id_12', 'Wiki', 'Wiki Description');
INSERT INTO feature VALUES ('feature/test_id_21', 'Kalender anlegen', 'Kalender anlegen Description');
INSERT INTO feature VALUES ('feature/test_id_22', 'Termine teilen', 'Termine teilen Description');
INSERT INTO application_belongs_to_category VALUES ('application/test_id_1', 'category/test_id_11');
INSERT INTO application_belongs_to_category VALUES ('application/test_id_2', 'category/test_id_11');
INSERT INTO application_has_feature VALUES ('application/test_id_1', 'feature/test_id_21');
INSERT INTO application_has_feature VALUES ('application/test_id_1', 'feature/test_id_22');
INSERT INTO application_has_feature VALUES ('application/test_id_2', 'feature/test_id_21');
\ No newline at end of file
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="database server adress">localhost</entry>
<entry key="database server port">3306</entry>
<entry key="database schema">test</entry>
<entry key="database user name">root</entry>
<entry key="database password"/>
</properties>
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment