diff --git a/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/TaskanaHistoryEngine.java b/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/TaskanaHistoryEngine.java index 365afb056..7b8102711 100644 --- a/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/TaskanaHistoryEngine.java +++ b/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/TaskanaHistoryEngine.java @@ -2,14 +2,12 @@ package pro.taskana.simplehistory; import pro.taskana.history.api.TaskanaHistory; -/** - * The TaskanaHistoryEngine represents an overall set of all needed services. - */ +/** The TaskanaHistoryEngine represents an overall set of all needed services. */ public interface TaskanaHistoryEngine { - /** - * The TaskanaHistory can be used for operations on all history events. - * - * @return the HistoryService - */ - TaskanaHistory getTaskanaHistoryService(); + /** + * The TaskanaHistory can be used for operations on all history events. + * + * @return the HistoryService + */ + TaskanaHistory getTaskanaHistoryService(); } diff --git a/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/configuration/DbSchemaCreator.java b/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/configuration/DbSchemaCreator.java index 770a9e096..324a05bdc 100644 --- a/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/configuration/DbSchemaCreator.java +++ b/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/configuration/DbSchemaCreator.java @@ -10,73 +10,70 @@ import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.SQLException; - import javax.sql.DataSource; - import org.apache.ibatis.jdbc.ScriptRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * Create the schema for the taskana history. - */ +/** Create the schema for the taskana history. */ public class DbSchemaCreator { - private static final Logger LOGGER = LoggerFactory.getLogger(DbSchemaCreator.class); - private static final String DB_SCHEMA = "/sql/taskana-history-schema.sql"; - private DataSource dataSource; - private String schemaName; - private StringWriter outWriter = new StringWriter(); - private PrintWriter logWriter = new PrintWriter(outWriter); - private StringWriter errorWriter = new StringWriter(); - private PrintWriter errorLogWriter = new PrintWriter(errorWriter); + private static final Logger LOGGER = LoggerFactory.getLogger(DbSchemaCreator.class); + private static final String DB_SCHEMA = "/sql/taskana-history-schema.sql"; + private DataSource dataSource; + private String schemaName; + private StringWriter outWriter = new StringWriter(); + private PrintWriter logWriter = new PrintWriter(outWriter); + private StringWriter errorWriter = new StringWriter(); + private PrintWriter errorLogWriter = new PrintWriter(errorWriter); - public DbSchemaCreator(DataSource dataSource, String schema) throws SQLException { - this.dataSource = dataSource; - this.schemaName = schema; + public DbSchemaCreator(DataSource dataSource, String schema) throws SQLException { + this.dataSource = dataSource; + this.schemaName = schema; + } + + /** + * Run all db scripts. + * + * @throws SQLException will be thrown if there will be some incorrect SQL statements invoked. + */ + public void run() throws SQLException { + Connection connection = dataSource.getConnection(); + connection.setSchema(schemaName); + ScriptRunner runner = new ScriptRunner(connection); + runner.setStopOnError(true); + runner.setLogWriter(logWriter); + runner.setErrorLogWriter(errorLogWriter); + try { + InputStream resourceAsStream = this.getClass().getResourceAsStream(DB_SCHEMA); + BufferedReader reader = + new BufferedReader(new InputStreamReader(resourceAsStream, StandardCharsets.UTF_8)); + runner.runScript(getSqlWithSchemaNameParsed(reader)); + } finally { + runner.closeConnection(); } - - /** - * Run all db scripts. - * - * @throws SQLException - * will be thrown if there will be some incorrect SQL statements invoked. - */ - public void run() throws SQLException { - Connection connection = dataSource.getConnection(); - connection.setSchema(schemaName); - ScriptRunner runner = new ScriptRunner(connection); - runner.setStopOnError(true); - runner.setLogWriter(logWriter); - runner.setErrorLogWriter(errorLogWriter); - try { - InputStream resourceAsStream = this.getClass().getResourceAsStream(DB_SCHEMA); - BufferedReader reader = new BufferedReader(new InputStreamReader(resourceAsStream, StandardCharsets.UTF_8)); - runner.runScript(getSqlWithSchemaNameParsed(reader)); - } finally { - runner.closeConnection(); - } - LOGGER.debug(outWriter.toString()); - if (!errorWriter.toString().trim().isEmpty()) { - LOGGER.error(errorWriter.toString()); - } + LOGGER.debug(outWriter.toString()); + if (!errorWriter.toString().trim().isEmpty()) { + LOGGER.error(errorWriter.toString()); } + } - private StringReader getSqlWithSchemaNameParsed(BufferedReader reader) { - StringBuilder content = new StringBuilder(); - try { - String line = ""; - while (line != null) { - line = reader.readLine(); - if (line != null) { - content.append(line.replaceAll("%schemaName%", schemaName)).append(System.lineSeparator()); - } - } - } catch (IOException e) { - e.printStackTrace(); - LOGGER.error("SchemaName sql parsing failed for schemaName {}", schemaName); + private StringReader getSqlWithSchemaNameParsed(BufferedReader reader) { + StringBuilder content = new StringBuilder(); + try { + String line = ""; + while (line != null) { + line = reader.readLine(); + if (line != null) { + content + .append(line.replaceAll("%schemaName%", schemaName)) + .append(System.lineSeparator()); } - return new StringReader(content.toString()); + } + } catch (IOException e) { + e.printStackTrace(); + LOGGER.error("SchemaName sql parsing failed for schemaName {}", schemaName); } - + return new StringReader(content.toString()); + } } diff --git a/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/impl/HistoryEventImpl.java b/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/impl/HistoryEventImpl.java index 21c5d13c5..6006975be 100644 --- a/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/impl/HistoryEventImpl.java +++ b/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/impl/HistoryEventImpl.java @@ -2,13 +2,10 @@ package pro.taskana.simplehistory.impl; import pro.taskana.history.api.TaskanaHistoryEvent; -/** - * This entity contains the most important information about a history event. - */ +/** This entity contains the most important information about a history event. */ public class HistoryEventImpl extends TaskanaHistoryEvent { - public HistoryEventImpl() { - super(); - } - + public HistoryEventImpl() { + super(); + } } diff --git a/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/impl/HistoryQueryImpl.java b/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/impl/HistoryQueryImpl.java index e5f18aca4..74b6d46a5 100644 --- a/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/impl/HistoryQueryImpl.java +++ b/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/impl/HistoryQueryImpl.java @@ -3,7 +3,6 @@ package pro.taskana.simplehistory.impl; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -13,631 +12,635 @@ import pro.taskana.simplehistory.impl.mappings.HistoryQueryMapper; import pro.taskana.simplehistory.query.HistoryQuery; import pro.taskana.simplehistory.query.HistoryQueryColumnName; -/** - * Implementation for generating dynamic sql. - */ +/** Implementation for generating dynamic sql. */ public class HistoryQueryImpl implements HistoryQuery { - private static final Logger LOGGER = LoggerFactory.getLogger(HistoryQueryImpl.class); - - private TaskanaHistoryEngineImpl taskanaHistoryEngine; - private HistoryQueryMapper historyQueryMapper; - - private HistoryQueryColumnName columnName; - private List orderBy; - private List orderColumns; - private int maxRows; // limit for rows. used to make list(offset, limit) and single() more efficient. - - private String[] idIn; - private String[] businessProcessIdIn; - private String[] parentBusinessProcessIdIn; - private String[] taskIdIn; - private String[] eventTypeIn; - private TimeInterval[] createdIn; - private String[] userIdIn; - private String[] domainIn; - private String[] workbasketKeyIn; - private String[] porCompanyIn; - private String[] porSystemIn; - private String[] porInstanceIn; - private String[] porTypeIn; - private String[] porValueIn; - private String[] taskClassificationKeyIn; - private String[] taskClassificationCategoryIn; - private String[] attachmentClassificationKeyIn; - private String[] commentIn; - private String[] oldValueIn; - private String[] newValueIn; - private String[] custom1In; - private String[] custom2In; - private String[] custom3In; - private String[] custom4In; - private String[] oldDataIn; - private String[] newDataIn; - - private String[] businessProcessIdLike; - private String[] parentBusinessProcessIdLike; - private String[] taskIdLike; - private String[] eventTypeLike; - private String[] userIdLike; - private String[] domainLike; - private String[] workbasketKeyLike; - private String[] porCompanyLike; - private String[] porSystemLike; - private String[] porInstanceLike; - private String[] porTypeLike; - private String[] porValueLike; - private String[] taskClassificationKeyLike; - private String[] taskClassificationCategoryLike; - private String[] attachmentClassificationKeyLike; - private String[] commentLike; - private String[] oldValueLike; - private String[] newValueLike; - private String[] custom1Like; - private String[] custom2Like; - private String[] custom3Like; - private String[] custom4Like; - private String[] oldDataLike; - private String[] newDataLike; - - public HistoryQueryImpl(TaskanaHistoryEngineImpl taskanaHistoryEngineImpl, HistoryQueryMapper historyQueryMapper) { - this.taskanaHistoryEngine = taskanaHistoryEngineImpl; - this.historyQueryMapper = historyQueryMapper; - this.orderBy = new ArrayList<>(); - this.orderColumns = new ArrayList<>(); - this.maxRows = -1; - } - - @Override - public HistoryQuery idIn(String... idIn) { - this.idIn = toUpperCopy(idIn); - return this; - } - - @Override - public HistoryQuery businessProcessIdIn(String... businessProcessId) { - this.businessProcessIdIn = toUpperCopy(businessProcessId); - return this; - } - - @Override - public HistoryQuery parentBusinessProcessIdIn(String... parentBusinessProcessId) { - this.parentBusinessProcessIdIn = toUpperCopy(parentBusinessProcessId); - return this; - } - - @Override - public HistoryQuery taskIdIn(String... taskId) { - this.taskIdIn = toUpperCopy(taskId); - return this; - } - - @Override - public HistoryQuery eventTypeIn(String... eventType) { - this.eventTypeIn = toUpperCopy(eventType); - return this; - } - - @Override - public HistoryQuery createdWithin(TimeInterval... createdIn) { - this.createdIn = createdIn; - return this; - } - - @Override - public HistoryQuery userIdIn(String... userId) { - this.userIdIn = toUpperCopy(userId); - return this; - } - - @Override - public HistoryQuery domainIn(String... domain) { - this.domainIn = toUpperCopy(domain); - return this; - } - - @Override - public HistoryQuery workbasketKeyIn(String... workbasketKey) { - this.workbasketKeyIn = toUpperCopy(workbasketKey); - return this; - } - - @Override - public HistoryQuery porCompanyIn(String... porCompany) { - this.porCompanyIn = toUpperCopy(porCompany); - return this; - } - - @Override - public HistoryQuery porSystemIn(String... porSystem) { - this.porSystemIn = toUpperCopy(porSystem); - return this; - } - - @Override - public HistoryQuery porInstanceIn(String... porInstance) { - this.porInstanceIn = toUpperCopy(porInstance); - return this; - } - - @Override - public HistoryQuery porTypeIn(String... porType) { - this.porTypeIn = toUpperCopy(porType); - return this; - } - - @Override - public HistoryQuery porValueIn(String... porValue) { - this.porValueIn = toUpperCopy(porValue); - return this; - } - - @Override - public HistoryQuery taskClassificationKeyIn(String... taskClassificationKey) { - this.taskClassificationKeyIn = toUpperCopy(taskClassificationKey); - return this; - } - - @Override - public HistoryQuery taskClassificationCategoryIn(String... taskClassificationCategory) { - this.taskClassificationCategoryIn = toUpperCopy(taskClassificationCategory); - return this; - } - - @Override - public HistoryQuery attachmentClassificationKeyIn(String... attachmentClassificationKey) { - this.attachmentClassificationKeyIn = toUpperCopy(attachmentClassificationKey); - return this; - } - - @Override - public HistoryQuery commentIn(String... commentIn) { - this.commentIn = toUpperCopy(commentIn); - return this; - } - - @Override - public HistoryQuery oldValueIn(String... oldValueIn) { - this.oldValueIn = toUpperCopy(oldValueIn); - return this; - } - - @Override - public HistoryQuery newValueIn(String... newValueIn) { - this.newValueIn = toUpperCopy(newValueIn); - return this; - } - - @Override - public HistoryQuery custom1In(String... custom1) { - this.custom1In = toUpperCopy(custom1); - return this; - } - - @Override - public HistoryQuery custom2In(String... custom2) { - this.custom2In = toUpperCopy(custom2); - return this; - } - - @Override - public HistoryQuery custom3In(String... custom3) { - this.custom3In = toUpperCopy(custom3); - return this; - } - - @Override - public HistoryQuery custom4In(String... custom4) { - this.custom4In = toUpperCopy(custom4); - return this; - } - - @Override - public HistoryQuery oldDataIn(String... oldDataIn) { - this.oldDataIn = toUpperCopy(oldDataIn); - return this; - } - - @Override - public HistoryQuery newDataIn(String... newDataIn) { - this.newDataIn = toUpperCopy(newDataIn); - return this; - } - - @Override - public HistoryQuery businessProcessIdLike(String... businessProcessId) { - this.businessProcessIdLike = toUpperCopy(businessProcessId); - return this; - } - - @Override - public HistoryQuery parentBusinessProcessIdLike(String... parentBusinessProcessId) { - this.parentBusinessProcessIdLike = toUpperCopy(parentBusinessProcessId); - return this; - } - - @Override - public HistoryQuery taskIdLike(String... taskId) { - this.taskIdLike = toUpperCopy(taskId); - return this; - } - - @Override - public HistoryQuery eventTypeLike(String... eventType) { - this.eventTypeLike = toUpperCopy(eventType); - return this; - } - - @Override - public HistoryQuery userIdLike(String... userId) { - this.userIdLike = toUpperCopy(userId); - return this; - } - - @Override - public HistoryQuery domainLike(String... domain) { - this.domainLike = toUpperCopy(domain); - return this; - } - - @Override - public HistoryQuery workbasketKeyLike(String... workbasketKey) { - this.workbasketKeyLike = toUpperCopy(workbasketKey); - return this; - } - - @Override - public HistoryQuery porCompanyLike(String... porCompany) { - this.porCompanyLike = toUpperCopy(porCompany); - return this; - } - - @Override - public HistoryQuery porSystemLike(String... porSystem) { - this.porSystemLike = toUpperCopy(porSystem); - return this; - } - - @Override - public HistoryQuery porInstanceLike(String... porInstance) { - this.porInstanceLike = toUpperCopy(porInstance); - return this; - } - - @Override - public HistoryQuery porTypeLike(String... porType) { - this.porTypeLike = toUpperCopy(porType); - return this; - } - - @Override - public HistoryQuery porValueLike(String... porValue) { - this.porValueLike = toUpperCopy(porValue); - return this; - } - - @Override - public HistoryQuery taskClassificationKeyLike(String... taskClassificationKey) { - this.taskClassificationKeyLike = toUpperCopy(taskClassificationKey); - return this; - } - - @Override - public HistoryQuery taskClassificationCategoryLike(String... taskClassificationCategory) { - this.taskClassificationCategoryLike = toUpperCopy(taskClassificationCategory); - return this; - } - - @Override - public HistoryQuery attachmentClassificationKeyLike(String... attachmentClassificationKey) { - this.attachmentClassificationKeyLike = toUpperCopy(attachmentClassificationKey); - return this; - } - - @Override - public HistoryQuery commentLike(String... comment) { - this.commentLike = toUpperCopy(comment); - return this; - } - - @Override - public HistoryQuery oldValueLike(String... oldValue) { - this.oldValueLike = toUpperCopy(oldValue); - return this; - } - - @Override - public HistoryQuery newValueLike(String... newValue) { - this.newValueLike = toUpperCopy(newValue); - return this; - } - - @Override - public HistoryQuery custom1Like(String... custom1) { - this.custom1Like = toUpperCopy(custom1); - return this; - } - - @Override - public HistoryQuery custom2Like(String... custom2) { - this.custom2Like = toUpperCopy(custom2); - return this; - } - - @Override - public HistoryQuery custom3Like(String... custom3) { - this.custom3Like = toUpperCopy(custom3); - return this; - } - - @Override - public HistoryQuery custom4Like(String... custom4) { - this.custom4Like = toUpperCopy(custom4); - return this; - } - - @Override - public HistoryQuery oldDataLike(String... oldData) { - this.oldDataLike = toUpperCopy(oldData); - return this; - } - - @Override - public HistoryQuery newDataLike(String... newData) { - this.newDataLike = toUpperCopy(newData); - return this; - } - - @Override - public HistoryQuery orderByBusinessProcessId(SortDirection sortDirection) { - return addOrderCriteria("BUSINESS_PROCESS_ID", sortDirection); - } - - @Override - public HistoryQuery orderByParentBusinessProcessId(SortDirection sortDirection) { - return addOrderCriteria("PARENT_BUSINESS_PROCESS_ID", sortDirection); - } - - @Override - public HistoryQuery orderByTaskId(SortDirection sortDirection) { - return addOrderCriteria("TASK_ID", sortDirection); - } - - @Override - public HistoryQuery orderByEventType(SortDirection sortDirection) { - return addOrderCriteria("EVENT_TYPE", sortDirection); - } - - @Override - public HistoryQuery orderByCreated(SortDirection sortDirection) { - return addOrderCriteria("CREATED", sortDirection); - } - - @Override - public HistoryQuery orderByUserId(SortDirection sortDirection) { - return addOrderCriteria("USER_ID", sortDirection); - } - - @Override - public HistoryQuery orderByDomain(SortDirection sortDirection) { - return addOrderCriteria("DOMAIN", sortDirection); - } - - @Override - public HistoryQuery orderByWorkbasketKey(SortDirection sortDirection) { - return addOrderCriteria("WORKBASKET_KEY", sortDirection); - } - - @Override - public HistoryQuery orderByPorCompany(SortDirection sortDirection) { - return addOrderCriteria("POR_COMPANY", sortDirection); - } - - @Override - public HistoryQuery orderByPorSystem(SortDirection sortDirection) { - return addOrderCriteria("POR_SYSTEM", sortDirection); - } - - @Override - public HistoryQuery orderByPorInstance(SortDirection sortDirection) { - return addOrderCriteria("POR_INSTANCE", sortDirection); - } - - @Override - public HistoryQuery orderByPorType(SortDirection sortDirection) { - return addOrderCriteria("POR_TYPE", sortDirection); - } - - @Override - public HistoryQuery orderByPorValue(SortDirection sortDirection) { - return addOrderCriteria("POR_VALUE", sortDirection); - } - - @Override - public HistoryQuery orderByTaskClassificationKey(SortDirection sortDirection) { - return addOrderCriteria("TASK_CLASSIFICATION_KEY", sortDirection); - } - - @Override - public HistoryQuery orderByTaskClassificationCategory(SortDirection sortDirection) { - return addOrderCriteria("TASK_CLASSIFICATION_CATEGORY", sortDirection); - } - - @Override - public HistoryQuery orderByAttachmentClassificationKey(SortDirection sortDirection) { - return addOrderCriteria("ATTACHMENT_CLASSIFICATION_KEY", sortDirection); - } - - @Override - public HistoryQuery orderByComment(SortDirection sortDirection) { - return addOrderCriteria("COMMENT", sortDirection); - } - - @Override - public HistoryQuery orderByOldValue(SortDirection sortDirection) { - return addOrderCriteria("OLD_VALUE", sortDirection); - } - - @Override - public HistoryQuery orderByNewValue(SortDirection sortDirection) { - return addOrderCriteria("NEW_VALUE", sortDirection); - } - - @Override - public HistoryQuery orderByOldData(SortDirection sortDirection) { - return addOrderCriteria("OLD_DATA", sortDirection); - } - - @Override - public HistoryQuery orderByNewData(SortDirection sortDirection) { - return addOrderCriteria("NEW_DATA", sortDirection); - } - - @Override - public HistoryQuery orderByCustomAttribute(int num, SortDirection sortDirection) - throws InvalidArgumentException { - - switch (num) { - case 1: - return addOrderCriteria("CUSTOM_1", sortDirection); - case 2: - return addOrderCriteria("CUSTOM_2", sortDirection); - case 3: - return addOrderCriteria("CUSTOM_3", sortDirection); - case 4: - return addOrderCriteria("CUSTOM_4", sortDirection); - default: - throw new InvalidArgumentException("Custom number has to be between 1 and 4, but this is: " + num); - } - } - - @Override - public List list() { - LOGGER.debug("entry to list(), this = {}", this); - List result = new ArrayList<>(); - try { - taskanaHistoryEngine.openConnection(); - result = historyQueryMapper.queryHistoryEvent(this); - LOGGER.debug("transaction was successful. Result: {}", result.toString()); - return result; - } catch (SQLException e) { - LOGGER.error("Method openConnection() could not open a connection to the database.", - e.getCause()); - return result; - } catch (NullPointerException npe) { - LOGGER.error("No History Event found."); - return result; - } finally { - taskanaHistoryEngine.returnConnection(); - } - } - - @Override - public List list(int offset, int limit) { - LOGGER.debug("entry to list({},{}), this = {}", offset, limit, this); - List result = new ArrayList<>(); - try { - taskanaHistoryEngine.openConnection(); - this.maxRows = offset + limit; - result = historyQueryMapper.queryHistoryEvent(this); - LOGGER.debug("transaction was successful. Result: {}", result.toString()); - limit = Math.min(result.size() - offset, limit); - if (result.size() > offset) { - return result.subList(offset, offset + limit); - } else { - return new ArrayList<>(); - } - } catch (SQLException e) { - LOGGER.error("Method openConnection() could not open a connection to the database.", - e.getCause()); - return result; - } catch (NullPointerException npe) { - LOGGER.error("No History Event found."); - return result; - } finally { - taskanaHistoryEngine.returnConnection(); - this.maxRows = -1; - } - } - - @Override - public List listValues(HistoryQueryColumnName dbColumnName, SortDirection sortDirection) { - LOGGER.debug("entry to listValues() of column {} with sortDirection {}, this {}", dbColumnName, sortDirection, - this); - List result = new ArrayList<>(); - this.columnName = dbColumnName; - List cacheOrderBy = this.orderBy; - this.orderBy.clear(); - this.addOrderCriteria(columnName.toString(), sortDirection); - - try { - taskanaHistoryEngine.openConnection(); - result = historyQueryMapper.queryHistoryColumnValues(this); - LOGGER.debug("transaction was successful. Result: {}", result.toString()); - return result; - } catch (SQLException e) { - LOGGER.error("Method openConnection() could not open a connection to the database.", - e.getCause()); - return result; - } catch (NullPointerException npe) { - LOGGER.error("No History Event found."); - return result; - } finally { - this.orderBy = cacheOrderBy; - this.columnName = null; - this.orderColumns.remove(orderColumns.size() - 1); - taskanaHistoryEngine.returnConnection(); - } - } - - @Override - public HistoryEventImpl single() { - LOGGER.debug("entry to list(), this = {}", this); - HistoryEventImpl result = new HistoryEventImpl(); - try { - taskanaHistoryEngine.openConnection(); - this.maxRows = 1; - result = historyQueryMapper.queryHistoryEvent(this).get(0); - LOGGER.debug("transaction was successful. Result: {}", result.toString()); - return result; - } catch (SQLException e) { - LOGGER.error("Method openConnection() could not open a connection to the database.", - e.getCause()); - return result; - } catch (NullPointerException npe) { - LOGGER.error("No History Event found."); - return result; - } finally { - taskanaHistoryEngine.returnConnection(); - this.maxRows = -1; - } - } - - @Override - public long count() { - LOGGER.debug("entry to count(), this = {}", this); - try { - taskanaHistoryEngine.openConnection(); - long result = historyQueryMapper.countHistoryEvent(this); - LOGGER.debug("transaction was successful. Result: {}", result); - return result; - } catch (SQLException e) { - LOGGER.error("Method openConnection() could not open a connection to the database.", - e.getCause()); - return -1; - } catch (NullPointerException npe) { - LOGGER.error("No History Event found."); - return -1; - } finally { - taskanaHistoryEngine.returnConnection(); - } - } - - private HistoryQueryImpl addOrderCriteria(String columnName, SortDirection sortDirection) { - String orderByDirection = " " + (sortDirection == null ? SortDirection.ASCENDING : sortDirection); - orderBy.add(columnName.toString() + orderByDirection); - orderColumns.add(columnName.toString()); - return this; - } - + private static final Logger LOGGER = LoggerFactory.getLogger(HistoryQueryImpl.class); + + private TaskanaHistoryEngineImpl taskanaHistoryEngine; + private HistoryQueryMapper historyQueryMapper; + + private HistoryQueryColumnName columnName; + private List orderBy; + private List orderColumns; + private int + maxRows; // limit for rows. used to make list(offset, limit) and single() more efficient. + + private String[] idIn; + private String[] businessProcessIdIn; + private String[] parentBusinessProcessIdIn; + private String[] taskIdIn; + private String[] eventTypeIn; + private TimeInterval[] createdIn; + private String[] userIdIn; + private String[] domainIn; + private String[] workbasketKeyIn; + private String[] porCompanyIn; + private String[] porSystemIn; + private String[] porInstanceIn; + private String[] porTypeIn; + private String[] porValueIn; + private String[] taskClassificationKeyIn; + private String[] taskClassificationCategoryIn; + private String[] attachmentClassificationKeyIn; + private String[] commentIn; + private String[] oldValueIn; + private String[] newValueIn; + private String[] custom1In; + private String[] custom2In; + private String[] custom3In; + private String[] custom4In; + private String[] oldDataIn; + private String[] newDataIn; + + private String[] businessProcessIdLike; + private String[] parentBusinessProcessIdLike; + private String[] taskIdLike; + private String[] eventTypeLike; + private String[] userIdLike; + private String[] domainLike; + private String[] workbasketKeyLike; + private String[] porCompanyLike; + private String[] porSystemLike; + private String[] porInstanceLike; + private String[] porTypeLike; + private String[] porValueLike; + private String[] taskClassificationKeyLike; + private String[] taskClassificationCategoryLike; + private String[] attachmentClassificationKeyLike; + private String[] commentLike; + private String[] oldValueLike; + private String[] newValueLike; + private String[] custom1Like; + private String[] custom2Like; + private String[] custom3Like; + private String[] custom4Like; + private String[] oldDataLike; + private String[] newDataLike; + + public HistoryQueryImpl( + TaskanaHistoryEngineImpl taskanaHistoryEngineImpl, HistoryQueryMapper historyQueryMapper) { + this.taskanaHistoryEngine = taskanaHistoryEngineImpl; + this.historyQueryMapper = historyQueryMapper; + this.orderBy = new ArrayList<>(); + this.orderColumns = new ArrayList<>(); + this.maxRows = -1; + } + + @Override + public HistoryQuery idIn(String... idIn) { + this.idIn = toUpperCopy(idIn); + return this; + } + + @Override + public HistoryQuery businessProcessIdIn(String... businessProcessId) { + this.businessProcessIdIn = toUpperCopy(businessProcessId); + return this; + } + + @Override + public HistoryQuery parentBusinessProcessIdIn(String... parentBusinessProcessId) { + this.parentBusinessProcessIdIn = toUpperCopy(parentBusinessProcessId); + return this; + } + + @Override + public HistoryQuery taskIdIn(String... taskId) { + this.taskIdIn = toUpperCopy(taskId); + return this; + } + + @Override + public HistoryQuery eventTypeIn(String... eventType) { + this.eventTypeIn = toUpperCopy(eventType); + return this; + } + + @Override + public HistoryQuery createdWithin(TimeInterval... createdIn) { + this.createdIn = createdIn; + return this; + } + + @Override + public HistoryQuery userIdIn(String... userId) { + this.userIdIn = toUpperCopy(userId); + return this; + } + + @Override + public HistoryQuery domainIn(String... domain) { + this.domainIn = toUpperCopy(domain); + return this; + } + + @Override + public HistoryQuery workbasketKeyIn(String... workbasketKey) { + this.workbasketKeyIn = toUpperCopy(workbasketKey); + return this; + } + + @Override + public HistoryQuery porCompanyIn(String... porCompany) { + this.porCompanyIn = toUpperCopy(porCompany); + return this; + } + + @Override + public HistoryQuery porSystemIn(String... porSystem) { + this.porSystemIn = toUpperCopy(porSystem); + return this; + } + + @Override + public HistoryQuery porInstanceIn(String... porInstance) { + this.porInstanceIn = toUpperCopy(porInstance); + return this; + } + + @Override + public HistoryQuery porTypeIn(String... porType) { + this.porTypeIn = toUpperCopy(porType); + return this; + } + + @Override + public HistoryQuery porValueIn(String... porValue) { + this.porValueIn = toUpperCopy(porValue); + return this; + } + + @Override + public HistoryQuery taskClassificationKeyIn(String... taskClassificationKey) { + this.taskClassificationKeyIn = toUpperCopy(taskClassificationKey); + return this; + } + + @Override + public HistoryQuery taskClassificationCategoryIn(String... taskClassificationCategory) { + this.taskClassificationCategoryIn = toUpperCopy(taskClassificationCategory); + return this; + } + + @Override + public HistoryQuery attachmentClassificationKeyIn(String... attachmentClassificationKey) { + this.attachmentClassificationKeyIn = toUpperCopy(attachmentClassificationKey); + return this; + } + + @Override + public HistoryQuery commentIn(String... commentIn) { + this.commentIn = toUpperCopy(commentIn); + return this; + } + + @Override + public HistoryQuery oldValueIn(String... oldValueIn) { + this.oldValueIn = toUpperCopy(oldValueIn); + return this; + } + + @Override + public HistoryQuery newValueIn(String... newValueIn) { + this.newValueIn = toUpperCopy(newValueIn); + return this; + } + + @Override + public HistoryQuery custom1In(String... custom1) { + this.custom1In = toUpperCopy(custom1); + return this; + } + + @Override + public HistoryQuery custom2In(String... custom2) { + this.custom2In = toUpperCopy(custom2); + return this; + } + + @Override + public HistoryQuery custom3In(String... custom3) { + this.custom3In = toUpperCopy(custom3); + return this; + } + + @Override + public HistoryQuery custom4In(String... custom4) { + this.custom4In = toUpperCopy(custom4); + return this; + } + + @Override + public HistoryQuery oldDataIn(String... oldDataIn) { + this.oldDataIn = toUpperCopy(oldDataIn); + return this; + } + + @Override + public HistoryQuery newDataIn(String... newDataIn) { + this.newDataIn = toUpperCopy(newDataIn); + return this; + } + + @Override + public HistoryQuery businessProcessIdLike(String... businessProcessId) { + this.businessProcessIdLike = toUpperCopy(businessProcessId); + return this; + } + + @Override + public HistoryQuery parentBusinessProcessIdLike(String... parentBusinessProcessId) { + this.parentBusinessProcessIdLike = toUpperCopy(parentBusinessProcessId); + return this; + } + + @Override + public HistoryQuery taskIdLike(String... taskId) { + this.taskIdLike = toUpperCopy(taskId); + return this; + } + + @Override + public HistoryQuery eventTypeLike(String... eventType) { + this.eventTypeLike = toUpperCopy(eventType); + return this; + } + + @Override + public HistoryQuery userIdLike(String... userId) { + this.userIdLike = toUpperCopy(userId); + return this; + } + + @Override + public HistoryQuery domainLike(String... domain) { + this.domainLike = toUpperCopy(domain); + return this; + } + + @Override + public HistoryQuery workbasketKeyLike(String... workbasketKey) { + this.workbasketKeyLike = toUpperCopy(workbasketKey); + return this; + } + + @Override + public HistoryQuery porCompanyLike(String... porCompany) { + this.porCompanyLike = toUpperCopy(porCompany); + return this; + } + + @Override + public HistoryQuery porSystemLike(String... porSystem) { + this.porSystemLike = toUpperCopy(porSystem); + return this; + } + + @Override + public HistoryQuery porInstanceLike(String... porInstance) { + this.porInstanceLike = toUpperCopy(porInstance); + return this; + } + + @Override + public HistoryQuery porTypeLike(String... porType) { + this.porTypeLike = toUpperCopy(porType); + return this; + } + + @Override + public HistoryQuery porValueLike(String... porValue) { + this.porValueLike = toUpperCopy(porValue); + return this; + } + + @Override + public HistoryQuery taskClassificationKeyLike(String... taskClassificationKey) { + this.taskClassificationKeyLike = toUpperCopy(taskClassificationKey); + return this; + } + + @Override + public HistoryQuery taskClassificationCategoryLike(String... taskClassificationCategory) { + this.taskClassificationCategoryLike = toUpperCopy(taskClassificationCategory); + return this; + } + + @Override + public HistoryQuery attachmentClassificationKeyLike(String... attachmentClassificationKey) { + this.attachmentClassificationKeyLike = toUpperCopy(attachmentClassificationKey); + return this; + } + + @Override + public HistoryQuery commentLike(String... comment) { + this.commentLike = toUpperCopy(comment); + return this; + } + + @Override + public HistoryQuery oldValueLike(String... oldValue) { + this.oldValueLike = toUpperCopy(oldValue); + return this; + } + + @Override + public HistoryQuery newValueLike(String... newValue) { + this.newValueLike = toUpperCopy(newValue); + return this; + } + + @Override + public HistoryQuery custom1Like(String... custom1) { + this.custom1Like = toUpperCopy(custom1); + return this; + } + + @Override + public HistoryQuery custom2Like(String... custom2) { + this.custom2Like = toUpperCopy(custom2); + return this; + } + + @Override + public HistoryQuery custom3Like(String... custom3) { + this.custom3Like = toUpperCopy(custom3); + return this; + } + + @Override + public HistoryQuery custom4Like(String... custom4) { + this.custom4Like = toUpperCopy(custom4); + return this; + } + + @Override + public HistoryQuery oldDataLike(String... oldData) { + this.oldDataLike = toUpperCopy(oldData); + return this; + } + + @Override + public HistoryQuery newDataLike(String... newData) { + this.newDataLike = toUpperCopy(newData); + return this; + } + + @Override + public HistoryQuery orderByBusinessProcessId(SortDirection sortDirection) { + return addOrderCriteria("BUSINESS_PROCESS_ID", sortDirection); + } + + @Override + public HistoryQuery orderByParentBusinessProcessId(SortDirection sortDirection) { + return addOrderCriteria("PARENT_BUSINESS_PROCESS_ID", sortDirection); + } + + @Override + public HistoryQuery orderByTaskId(SortDirection sortDirection) { + return addOrderCriteria("TASK_ID", sortDirection); + } + + @Override + public HistoryQuery orderByEventType(SortDirection sortDirection) { + return addOrderCriteria("EVENT_TYPE", sortDirection); + } + + @Override + public HistoryQuery orderByCreated(SortDirection sortDirection) { + return addOrderCriteria("CREATED", sortDirection); + } + + @Override + public HistoryQuery orderByUserId(SortDirection sortDirection) { + return addOrderCriteria("USER_ID", sortDirection); + } + + @Override + public HistoryQuery orderByDomain(SortDirection sortDirection) { + return addOrderCriteria("DOMAIN", sortDirection); + } + + @Override + public HistoryQuery orderByWorkbasketKey(SortDirection sortDirection) { + return addOrderCriteria("WORKBASKET_KEY", sortDirection); + } + + @Override + public HistoryQuery orderByPorCompany(SortDirection sortDirection) { + return addOrderCriteria("POR_COMPANY", sortDirection); + } + + @Override + public HistoryQuery orderByPorSystem(SortDirection sortDirection) { + return addOrderCriteria("POR_SYSTEM", sortDirection); + } + + @Override + public HistoryQuery orderByPorInstance(SortDirection sortDirection) { + return addOrderCriteria("POR_INSTANCE", sortDirection); + } + + @Override + public HistoryQuery orderByPorType(SortDirection sortDirection) { + return addOrderCriteria("POR_TYPE", sortDirection); + } + + @Override + public HistoryQuery orderByPorValue(SortDirection sortDirection) { + return addOrderCriteria("POR_VALUE", sortDirection); + } + + @Override + public HistoryQuery orderByTaskClassificationKey(SortDirection sortDirection) { + return addOrderCriteria("TASK_CLASSIFICATION_KEY", sortDirection); + } + + @Override + public HistoryQuery orderByTaskClassificationCategory(SortDirection sortDirection) { + return addOrderCriteria("TASK_CLASSIFICATION_CATEGORY", sortDirection); + } + + @Override + public HistoryQuery orderByAttachmentClassificationKey(SortDirection sortDirection) { + return addOrderCriteria("ATTACHMENT_CLASSIFICATION_KEY", sortDirection); + } + + @Override + public HistoryQuery orderByComment(SortDirection sortDirection) { + return addOrderCriteria("COMMENT", sortDirection); + } + + @Override + public HistoryQuery orderByOldValue(SortDirection sortDirection) { + return addOrderCriteria("OLD_VALUE", sortDirection); + } + + @Override + public HistoryQuery orderByNewValue(SortDirection sortDirection) { + return addOrderCriteria("NEW_VALUE", sortDirection); + } + + @Override + public HistoryQuery orderByOldData(SortDirection sortDirection) { + return addOrderCriteria("OLD_DATA", sortDirection); + } + + @Override + public HistoryQuery orderByNewData(SortDirection sortDirection) { + return addOrderCriteria("NEW_DATA", sortDirection); + } + + @Override + public HistoryQuery orderByCustomAttribute(int num, SortDirection sortDirection) + throws InvalidArgumentException { + + switch (num) { + case 1: + return addOrderCriteria("CUSTOM_1", sortDirection); + case 2: + return addOrderCriteria("CUSTOM_2", sortDirection); + case 3: + return addOrderCriteria("CUSTOM_3", sortDirection); + case 4: + return addOrderCriteria("CUSTOM_4", sortDirection); + default: + throw new InvalidArgumentException( + "Custom number has to be between 1 and 4, but this is: " + num); + } + } + + @Override + public List list() { + LOGGER.debug("entry to list(), this = {}", this); + List result = new ArrayList<>(); + try { + taskanaHistoryEngine.openConnection(); + result = historyQueryMapper.queryHistoryEvent(this); + LOGGER.debug("transaction was successful. Result: {}", result.toString()); + return result; + } catch (SQLException e) { + LOGGER.error( + "Method openConnection() could not open a connection to the database.", e.getCause()); + return result; + } catch (NullPointerException npe) { + LOGGER.error("No History Event found."); + return result; + } finally { + taskanaHistoryEngine.returnConnection(); + } + } + + @Override + public List list(int offset, int limit) { + LOGGER.debug("entry to list({},{}), this = {}", offset, limit, this); + List result = new ArrayList<>(); + try { + taskanaHistoryEngine.openConnection(); + this.maxRows = offset + limit; + result = historyQueryMapper.queryHistoryEvent(this); + LOGGER.debug("transaction was successful. Result: {}", result.toString()); + limit = Math.min(result.size() - offset, limit); + if (result.size() > offset) { + return result.subList(offset, offset + limit); + } else { + return new ArrayList<>(); + } + } catch (SQLException e) { + LOGGER.error( + "Method openConnection() could not open a connection to the database.", e.getCause()); + return result; + } catch (NullPointerException npe) { + LOGGER.error("No History Event found."); + return result; + } finally { + taskanaHistoryEngine.returnConnection(); + this.maxRows = -1; + } + } + + @Override + public List listValues(HistoryQueryColumnName dbColumnName, SortDirection sortDirection) { + LOGGER.debug( + "entry to listValues() of column {} with sortDirection {}, this {}", + dbColumnName, + sortDirection, + this); + List result = new ArrayList<>(); + this.columnName = dbColumnName; + List cacheOrderBy = this.orderBy; + this.orderBy.clear(); + this.addOrderCriteria(columnName.toString(), sortDirection); + + try { + taskanaHistoryEngine.openConnection(); + result = historyQueryMapper.queryHistoryColumnValues(this); + LOGGER.debug("transaction was successful. Result: {}", result.toString()); + return result; + } catch (SQLException e) { + LOGGER.error( + "Method openConnection() could not open a connection to the database.", e.getCause()); + return result; + } catch (NullPointerException npe) { + LOGGER.error("No History Event found."); + return result; + } finally { + this.orderBy = cacheOrderBy; + this.columnName = null; + this.orderColumns.remove(orderColumns.size() - 1); + taskanaHistoryEngine.returnConnection(); + } + } + + @Override + public HistoryEventImpl single() { + LOGGER.debug("entry to list(), this = {}", this); + HistoryEventImpl result = new HistoryEventImpl(); + try { + taskanaHistoryEngine.openConnection(); + this.maxRows = 1; + result = historyQueryMapper.queryHistoryEvent(this).get(0); + LOGGER.debug("transaction was successful. Result: {}", result.toString()); + return result; + } catch (SQLException e) { + LOGGER.error( + "Method openConnection() could not open a connection to the database.", e.getCause()); + return result; + } catch (NullPointerException npe) { + LOGGER.error("No History Event found."); + return result; + } finally { + taskanaHistoryEngine.returnConnection(); + this.maxRows = -1; + } + } + + @Override + public long count() { + LOGGER.debug("entry to count(), this = {}", this); + try { + taskanaHistoryEngine.openConnection(); + long result = historyQueryMapper.countHistoryEvent(this); + LOGGER.debug("transaction was successful. Result: {}", result); + return result; + } catch (SQLException e) { + LOGGER.error( + "Method openConnection() could not open a connection to the database.", e.getCause()); + return -1; + } catch (NullPointerException npe) { + LOGGER.error("No History Event found."); + return -1; + } finally { + taskanaHistoryEngine.returnConnection(); + } + } + + private HistoryQueryImpl addOrderCriteria(String columnName, SortDirection sortDirection) { + String orderByDirection = + " " + (sortDirection == null ? SortDirection.ASCENDING : sortDirection); + orderBy.add(columnName.toString() + orderByDirection); + orderColumns.add(columnName.toString()); + return this; + } } diff --git a/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/impl/SimpleHistoryServiceImpl.java b/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/impl/SimpleHistoryServiceImpl.java index 0df0f1ea1..3215df04d 100644 --- a/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/impl/SimpleHistoryServiceImpl.java +++ b/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/impl/SimpleHistoryServiceImpl.java @@ -2,7 +2,6 @@ package pro.taskana.simplehistory.impl; import java.sql.SQLException; import java.time.Instant; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -13,51 +12,52 @@ import pro.taskana.simplehistory.impl.mappings.HistoryEventMapper; import pro.taskana.simplehistory.impl.mappings.HistoryQueryMapper; import pro.taskana.simplehistory.query.HistoryQuery; -/** - * This is the implementation of TaskanaHistory. - */ +/** This is the implementation of TaskanaHistory. */ public class SimpleHistoryServiceImpl implements TaskanaHistory { - private static final Logger LOGGER = LoggerFactory.getLogger(SimpleHistoryServiceImpl.class); - private TaskanaHistoryEngineImpl taskanaHistoryEngine; - private HistoryEventMapper historyEventMapper; - private HistoryQueryMapper historyQueryMapper; - - @Override - public void initialize(TaskanaEngineConfiguration taskanaEngineConfiguration) { - try { - this.taskanaHistoryEngine = TaskanaHistoryEngineImpl.createTaskanaEngine(taskanaEngineConfiguration); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Simple history service implementation initialized with schemaName: {} ", - taskanaEngineConfiguration.getSchemaName()); - } - } catch (SQLException e) { - LOGGER.error("There was an error creating Taskana history engine", e); - e.printStackTrace(); - } - this.historyEventMapper = this.taskanaHistoryEngine.getSqlSession().getMapper(HistoryEventMapper.class); - this.historyQueryMapper = this.taskanaHistoryEngine.getSqlSession().getMapper(HistoryQueryMapper.class); + private static final Logger LOGGER = LoggerFactory.getLogger(SimpleHistoryServiceImpl.class); + private TaskanaHistoryEngineImpl taskanaHistoryEngine; + private HistoryEventMapper historyEventMapper; + private HistoryQueryMapper historyQueryMapper; + @Override + public void initialize(TaskanaEngineConfiguration taskanaEngineConfiguration) { + try { + this.taskanaHistoryEngine = + TaskanaHistoryEngineImpl.createTaskanaEngine(taskanaEngineConfiguration); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "Simple history service implementation initialized with schemaName: {} ", + taskanaEngineConfiguration.getSchemaName()); + } + } catch (SQLException e) { + LOGGER.error("There was an error creating Taskana history engine", e); + e.printStackTrace(); } + this.historyEventMapper = + this.taskanaHistoryEngine.getSqlSession().getMapper(HistoryEventMapper.class); + this.historyQueryMapper = + this.taskanaHistoryEngine.getSqlSession().getMapper(HistoryQueryMapper.class); + } - @Override - public void create(TaskanaHistoryEvent event) { - try { - taskanaHistoryEngine.openConnection(); - if (event.getCreated() == null) { - Instant now = Instant.now(); - event.setCreated(now); - } - historyEventMapper.insert(event); - } catch (SQLException e) { - e.printStackTrace(); - } finally { - taskanaHistoryEngine.returnConnection(); - LOGGER.debug("exit from create(TaskanaHistoryEvent event). Returning object = {}.", event); - } + @Override + public void create(TaskanaHistoryEvent event) { + try { + taskanaHistoryEngine.openConnection(); + if (event.getCreated() == null) { + Instant now = Instant.now(); + event.setCreated(now); + } + historyEventMapper.insert(event); + } catch (SQLException e) { + e.printStackTrace(); + } finally { + taskanaHistoryEngine.returnConnection(); + LOGGER.debug("exit from create(TaskanaHistoryEvent event). Returning object = {}.", event); } + } - public HistoryQuery createHistoryQuery() { - return new HistoryQueryImpl(taskanaHistoryEngine, historyQueryMapper); - } + public HistoryQuery createHistoryQuery() { + return new HistoryQueryImpl(taskanaHistoryEngine, historyQueryMapper); + } } diff --git a/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/impl/TaskanaHistoryEngineImpl.java b/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/impl/TaskanaHistoryEngineImpl.java index 9b0b7beee..84ed0b364 100644 --- a/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/impl/TaskanaHistoryEngineImpl.java +++ b/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/impl/TaskanaHistoryEngineImpl.java @@ -3,7 +3,6 @@ package pro.taskana.simplehistory.impl; import java.sql.SQLException; import java.util.ArrayDeque; import java.util.Deque; - import org.apache.ibatis.mapping.Environment; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSession; @@ -21,155 +20,151 @@ import pro.taskana.simplehistory.configuration.DbSchemaCreator; import pro.taskana.simplehistory.impl.mappings.HistoryEventMapper; import pro.taskana.simplehistory.impl.mappings.HistoryQueryMapper; -/** - * This is the implementation of TaskanaHistoryEngine. - */ +/** This is the implementation of TaskanaHistoryEngine. */ public class TaskanaHistoryEngineImpl implements TaskanaHistoryEngine { - private static final String DEFAULT = "default"; + protected static final ThreadLocal> SESSION_STACK = new ThreadLocal<>(); + private static final String DEFAULT = "default"; + TaskanaEngineConfiguration taskanaEngineConfiguration; + protected SqlSessionManager sessionManager; + protected TransactionFactory transactionFactory; + protected TaskanaHistory taskanaHistoryService; - TaskanaEngineConfiguration taskanaEngineConfiguration; + protected TaskanaHistoryEngineImpl(TaskanaEngineConfiguration taskanaEngineConfiguration) + throws SQLException { + this.taskanaEngineConfiguration = taskanaEngineConfiguration; - protected SqlSessionManager sessionManager; + createTransactionFactory(this.taskanaEngineConfiguration.getUseManagedTransactions()); + this.sessionManager = createSqlSessionManager(); + new DbSchemaCreator( + taskanaEngineConfiguration.getDatasource(), taskanaEngineConfiguration.getSchemaName()) + .run(); + } - protected TransactionFactory transactionFactory; + public static TaskanaHistoryEngineImpl createTaskanaEngine( + TaskanaEngineConfiguration taskanaEngineConfiguration) throws SQLException { + return new TaskanaHistoryEngineImpl(taskanaEngineConfiguration); + } - protected static final ThreadLocal> SESSION_STACK = new ThreadLocal<>(); - - protected TaskanaHistory taskanaHistoryService; - - protected TaskanaHistoryEngineImpl(TaskanaEngineConfiguration taskanaEngineConfiguration) throws SQLException { - this.taskanaEngineConfiguration = taskanaEngineConfiguration; - - createTransactionFactory(this.taskanaEngineConfiguration.getUseManagedTransactions()); - this.sessionManager = createSqlSessionManager(); - new DbSchemaCreator(taskanaEngineConfiguration.getDatasource(), - taskanaEngineConfiguration.getSchemaName()). - run(); + @Override + public TaskanaHistory getTaskanaHistoryService() { + if (taskanaHistoryService == null) { + SimpleHistoryServiceImpl historyService = new SimpleHistoryServiceImpl(); + historyService.initialize(taskanaEngineConfiguration); + this.taskanaHistoryService = historyService; } + return this.taskanaHistoryService; + } - public static TaskanaHistoryEngineImpl createTaskanaEngine( - TaskanaEngineConfiguration taskanaEngineConfiguration) throws SQLException { - return new TaskanaHistoryEngineImpl(taskanaEngineConfiguration); + /** + * Open the connection to the database. to be called at the begin of each Api call that accesses + * the database + * + * @throws SQLException thrown if the connection could not be opened. + */ + void openConnection() throws SQLException { + initSqlSession(); + this.sessionManager.getConnection().setSchema(taskanaEngineConfiguration.getSchemaName()); + } + + /** + * Returns the database connection into the pool. In the case of nested calls, simply pops the + * latest session from the session stack. Closes the connection if the session stack is empty. In + * mode AUTOCOMMIT commits before the connection is closed. To be called at the end of each Api + * call that accesses the database + */ + void returnConnection() { + popSessionFromStack(); + if (getSessionStack().isEmpty() + && this.sessionManager != null + && this.sessionManager.isManagedSessionStarted()) { + try { + this.sessionManager.commit(); + } catch (Exception e) { + } + this.sessionManager.close(); } + } - @Override - public TaskanaHistory getTaskanaHistoryService() { - if (taskanaHistoryService == null) { - SimpleHistoryServiceImpl historyService = new SimpleHistoryServiceImpl(); - historyService.initialize(taskanaEngineConfiguration); - this.taskanaHistoryService = historyService; - } - return this.taskanaHistoryService; + /** Initializes the SqlSessionManager. */ + void initSqlSession() { + this.sessionManager.startManagedSession(); + } + + /** + * retrieve the SqlSession used by taskana. + * + * @return the myBatis SqlSession object used by taskana + */ + SqlSession getSqlSession() { + return this.sessionManager; + } + + protected SqlSessionManager createSqlSessionManager() { + Environment environment = + new Environment( + DEFAULT, this.transactionFactory, taskanaEngineConfiguration.getDatasource()); + Configuration configuration = new Configuration(environment); + + // add mappers + configuration.addMapper(HistoryEventMapper.class); + configuration.addMapper(HistoryQueryMapper.class); + SqlSessionFactory localSessionFactory = new SqlSessionFactoryBuilder().build(configuration); + return SqlSessionManager.newInstance(localSessionFactory); + } + + protected static void pushSessionToStack(SqlSessionManager session) { + getSessionStack().push(session); + } + + protected static void popSessionFromStack() { + Deque stack = getSessionStack(); + if (!stack.isEmpty()) { + stack.pop(); } + } - /** - * Open the connection to the database. to be called at the begin of each Api call that accesses the database - * - * @throws SQLException - * thrown if the connection could not be opened. - */ - void openConnection() throws SQLException { - initSqlSession(); - this.sessionManager.getConnection().setSchema(taskanaEngineConfiguration.getSchemaName()); + /** + * With sessionStack, we maintain a Stack of SqlSessionManager objects on a per thread basis. + * SqlSessionManager is the MyBatis object that wraps database connections. The purpose of this + * stack is to keep track of nested calls. Each external API call is wrapped into + * taskanaEngineImpl.openConnection(); ..... taskanaEngineImpl.returnConnection(); calls. In order + * to avoid duplicate opening / closing of connections, we use the sessionStack in the following + * way: Each time, an openConnection call is received, we push the current sessionManager onto the + * stack. On the first call to openConnection, we call sessionManager.startManagedSession() to + * open a database connection. On each call to returnConnection() we pop one instance of + * sessionManager from the stack. When the stack becomes empty, we close the database connection + * by calling sessionManager.close() + * + * @return Stack of SqlSessionManager + */ + protected static Deque getSessionStack() { + Deque stack = SESSION_STACK.get(); + if (stack == null) { + stack = new ArrayDeque<>(); + SESSION_STACK.set(stack); } + return stack; + } - /** - * Returns the database connection into the pool. In the case of nested calls, simply pops the latest session from - * the session stack. Closes the connection if the session stack is empty. In mode AUTOCOMMIT commits before the - * connection is closed. To be called at the end of each Api call that accesses the database - */ - void returnConnection() { - popSessionFromStack(); - if (getSessionStack().isEmpty() - && this.sessionManager != null && this.sessionManager.isManagedSessionStarted()) { - try { - this.sessionManager.commit(); - } catch (Exception e) { - } - this.sessionManager.close(); - } + protected static SqlSessionManager getSessionFromStack() { + Deque stack = getSessionStack(); + if (stack.isEmpty()) { + return null; } + return stack.peek(); + } - /** - * Initializes the SqlSessionManager. - */ - void initSqlSession() { - this.sessionManager.startManagedSession(); - } - - /** - * retrieve the SqlSession used by taskana. - * - * @return the myBatis SqlSession object used by taskana - */ - SqlSession getSqlSession() { - return this.sessionManager; - } - - /** - * creates the MyBatis transaction factory. - * - * @param useManagedTransactions - * true if TASKANA should use a ManagedTransactionFactory. - */ - private void createTransactionFactory(boolean useManagedTransactions) { - if (useManagedTransactions) { - this.transactionFactory = new ManagedTransactionFactory(); - } else { - this.transactionFactory = new JdbcTransactionFactory(); - } - } - - protected SqlSessionManager createSqlSessionManager() { - Environment environment = new Environment(DEFAULT, this.transactionFactory, - taskanaEngineConfiguration.getDatasource()); - Configuration configuration = new Configuration(environment); - - // add mappers - configuration.addMapper(HistoryEventMapper.class); - configuration.addMapper(HistoryQueryMapper.class); - SqlSessionFactory localSessionFactory = new SqlSessionFactoryBuilder().build(configuration); - return SqlSessionManager.newInstance(localSessionFactory); - } - - protected static void pushSessionToStack(SqlSessionManager session) { - getSessionStack().push(session); - } - - protected static void popSessionFromStack() { - Deque stack = getSessionStack(); - if (!stack.isEmpty()) { - stack.pop(); - } - } - - /** - * With sessionStack, we maintain a Stack of SqlSessionManager objects on a per thread basis. SqlSessionManager is - * the MyBatis object that wraps database connections. The purpose of this stack is to keep track of nested calls. - * Each external API call is wrapped into taskanaEngineImpl.openConnection(); ..... - * taskanaEngineImpl.returnConnection(); calls. In order to avoid duplicate opening / closing of connections, we use - * the sessionStack in the following way: Each time, an openConnection call is received, we push the current - * sessionManager onto the stack. On the first call to openConnection, we call sessionManager.startManagedSession() - * to open a database connection. On each call to returnConnection() we pop one instance of sessionManager from the - * stack. When the stack becomes empty, we close the database connection by calling sessionManager.close() - * - * @return Stack of SqlSessionManager - */ - protected static Deque getSessionStack() { - Deque stack = SESSION_STACK.get(); - if (stack == null) { - stack = new ArrayDeque<>(); - SESSION_STACK.set(stack); - } - return stack; - } - - protected static SqlSessionManager getSessionFromStack() { - Deque stack = getSessionStack(); - if (stack.isEmpty()) { - return null; - } - return stack.peek(); + /** + * creates the MyBatis transaction factory. + * + * @param useManagedTransactions true if TASKANA should use a ManagedTransactionFactory. + */ + private void createTransactionFactory(boolean useManagedTransactions) { + if (useManagedTransactions) { + this.transactionFactory = new ManagedTransactionFactory(); + } else { + this.transactionFactory = new JdbcTransactionFactory(); } + } } diff --git a/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/impl/mappings/HistoryEventMapper.java b/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/impl/mappings/HistoryEventMapper.java index 4887b0578..f75f1a6db 100644 --- a/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/impl/mappings/HistoryEventMapper.java +++ b/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/impl/mappings/HistoryEventMapper.java @@ -5,24 +5,21 @@ import org.apache.ibatis.annotations.Param; import pro.taskana.history.api.TaskanaHistoryEvent; -/** - * This class is the mybatis mapping of workbaskets. - */ +/** This class is the mybatis mapping of workbaskets. */ public interface HistoryEventMapper { - @Insert( - "") - void insert(@Param("historyEvent") TaskanaHistoryEvent historyEvent); - + @Insert( + "") + void insert(@Param("historyEvent") TaskanaHistoryEvent historyEvent); } diff --git a/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/impl/mappings/HistoryQueryMapper.java b/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/impl/mappings/HistoryQueryMapper.java index 8d99490e2..b11b811e7 100644 --- a/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/impl/mappings/HistoryQueryMapper.java +++ b/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/impl/mappings/HistoryQueryMapper.java @@ -1,7 +1,6 @@ package pro.taskana.simplehistory.impl.mappings; import java.util.List; - import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; @@ -9,221 +8,221 @@ import org.apache.ibatis.annotations.Select; import pro.taskana.simplehistory.impl.HistoryEventImpl; import pro.taskana.simplehistory.impl.HistoryQueryImpl; -/** - * This class is the mybatis mapping of historyQueries. - */ +/** This class is the mybatis mapping of historyQueries. */ public interface HistoryQueryMapper { - @Select( - "") - @Results(value = { - @Result(property = "id", column = "ID"), - @Result(property = "businessProcessId", column = "BUSINESS_PROCESS_ID"), - @Result(property = "parentBusinessProcessId", column = "PARENT_BUSINESS_PROCESS_ID"), - @Result(property = "taskId", column = "TASK_ID"), - @Result(property = "eventType", column = "EVENT_TYPE"), - @Result(property = "created", column = "CREATED"), - @Result(property = "userId", column = "USER_ID"), - @Result(property = "domain", column = "DOMAIN"), - @Result(property = "workbasketKey", column = "WORKBASKET_KEY"), - @Result(property = "porCompany", column = "POR_COMPANY"), - @Result(property = "porSystem", column = "POR_SYSTEM"), - @Result(property = "porInstance", column = "POR_INSTANCE"), - @Result(property = "porType", column = "POR_TYPE"), - @Result(property = "porValue", column = "POR_VALUE"), - @Result(property = "taskClassificationKey", column = "TASK_CLASSIFICATION_KEY"), - @Result(property = "taskClassificationCategory", column = "TASK_CLASSIFICATION_CATEGORY"), - @Result(property = "attachmentClassificationKey", column = "ATTACHMENT_CLASSIFICATION_KEY"), - @Result(property = "comment", column = "COMMENT"), - @Result(property = "oldValue", column = "OLD_VALUE"), - @Result(property = "newValue", column = "NEW_VALUE"), - @Result(property = "custom1", column = "CUSTOM_1"), - @Result(property = "custom2", column = "CUSTOM_2"), - @Result(property = "custom3", column = "CUSTOM_3"), - @Result(property = "custom4", column = "CUSTOM_4"), - @Result(property = "oldData", column = "OLD_DATA"), - @Result(property = "newData", column = "NEW_DATA") - }) - List queryHistoryEvent(HistoryQueryImpl historyEventQuery); + @Select( + "") + @Results( + value = { + @Result(property = "id", column = "ID"), + @Result(property = "businessProcessId", column = "BUSINESS_PROCESS_ID"), + @Result(property = "parentBusinessProcessId", column = "PARENT_BUSINESS_PROCESS_ID"), + @Result(property = "taskId", column = "TASK_ID"), + @Result(property = "eventType", column = "EVENT_TYPE"), + @Result(property = "created", column = "CREATED"), + @Result(property = "userId", column = "USER_ID"), + @Result(property = "domain", column = "DOMAIN"), + @Result(property = "workbasketKey", column = "WORKBASKET_KEY"), + @Result(property = "porCompany", column = "POR_COMPANY"), + @Result(property = "porSystem", column = "POR_SYSTEM"), + @Result(property = "porInstance", column = "POR_INSTANCE"), + @Result(property = "porType", column = "POR_TYPE"), + @Result(property = "porValue", column = "POR_VALUE"), + @Result(property = "taskClassificationKey", column = "TASK_CLASSIFICATION_KEY"), + @Result(property = "taskClassificationCategory", column = "TASK_CLASSIFICATION_CATEGORY"), + @Result(property = "attachmentClassificationKey", column = "ATTACHMENT_CLASSIFICATION_KEY"), + @Result(property = "comment", column = "COMMENT"), + @Result(property = "oldValue", column = "OLD_VALUE"), + @Result(property = "newValue", column = "NEW_VALUE"), + @Result(property = "custom1", column = "CUSTOM_1"), + @Result(property = "custom2", column = "CUSTOM_2"), + @Result(property = "custom3", column = "CUSTOM_3"), + @Result(property = "custom4", column = "CUSTOM_4"), + @Result(property = "oldData", column = "OLD_DATA"), + @Result(property = "newData", column = "NEW_DATA") + }) + List queryHistoryEvent(HistoryQueryImpl historyEventQuery); - @Select( - "") - long countHistoryEvent(HistoryQueryImpl historyEventQuery); + @Select( + "") + long countHistoryEvent(HistoryQueryImpl historyEventQuery); - @Select("") - List queryHistoryColumnValues(HistoryQueryImpl historyQuery); + @Select( + "") + List queryHistoryColumnValues(HistoryQueryImpl historyQuery); } diff --git a/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/query/HistoryQuery.java b/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/query/HistoryQuery.java index edd3f26b7..5e71df5e3 100644 --- a/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/query/HistoryQuery.java +++ b/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/query/HistoryQuery.java @@ -5,706 +5,632 @@ import pro.taskana.TimeInterval; import pro.taskana.exceptions.InvalidArgumentException; import pro.taskana.simplehistory.impl.HistoryEventImpl; -/** - * HistoryQuery for generating dynamic sql. - */ +/** HistoryQuery for generating dynamic sql. */ public interface HistoryQuery extends BaseQuery { - /** - * Add your Id to your query. - * - * @param idIn - * as String - * @return the query - */ - HistoryQuery idIn(String... idIn); - - /** - * Add your businessProcessId to your query. - * - * @param businessProcessId - * as String - * @return the query - */ - HistoryQuery businessProcessIdIn(String... businessProcessId); - - /** - * Add your parentBusinessProcessId to your query. - * - * @param parentBusinessProcessId - * as String - * @return the query - */ - HistoryQuery parentBusinessProcessIdIn(String... parentBusinessProcessId); - - /** - * Add your taskId to your query. - * - * @param taskId - * as String - * @return the query - */ - HistoryQuery taskIdIn(String... taskId); - - /** - * Add your eventType to your query. - * - * @param eventType - * as String - * @return the query - */ - HistoryQuery eventTypeIn(String... eventType); - - /** - * Add your created TimeInterval to your query. - * - * @param createdWithin - * the {@link TimeInterval} within which the searched-for classifications were created. - * @return the query - */ - HistoryQuery createdWithin(TimeInterval... createdWithin); - - /** - * Add your userId to your query. - * - * @param userId - * as String - * @return the query - */ - HistoryQuery userIdIn(String... userId); - - /** - * Add your domain to your query. - * - * @param domain - * as String - * @return the query - */ - HistoryQuery domainIn(String... domain); - - /** - * Add your workbasketKey to your query. - * - * @param workbasketKey - * as String - * @return the query - */ - HistoryQuery workbasketKeyIn(String... workbasketKey); - - /** - * Add your porCompany to your query. - * - * @param porCompany - * as String - * @return the query - */ - HistoryQuery porCompanyIn(String... porCompany); - - /** - * Add your porSystem to your query. - * - * @param porSystem - * as String - * @return the query - */ - HistoryQuery porSystemIn(String... porSystem); - - /** - * Add your porInstance to your query. - * - * @param porInstance - * as String - * @return the query - */ - HistoryQuery porInstanceIn(String... porInstance); - - /** - * Add your porType to your query. - * - * @param porType - * as String - * @return the query - */ - HistoryQuery porTypeIn(String... porType); - - /** - * Add your porValue to your query. - * - * @param porValue - * as String - * @return the query - */ - HistoryQuery porValueIn(String... porValue); - - /** - * Add your taskClassificationKey to your query. - * - * @param taskClassificationKey - * as String - * @return the query - */ - HistoryQuery taskClassificationKeyIn(String... taskClassificationKey); - - /** - * Add your taskClassificationCategory to your query. - * - * @param taskClassificationCategory - * as String - * @return the query - */ - HistoryQuery taskClassificationCategoryIn(String... taskClassificationCategory); - - /** - * Add your attachmentClassificationKey to your query. - * - * @param attachmentClassificationKey - * as String - * @return the query - */ - HistoryQuery attachmentClassificationKeyIn(String... attachmentClassificationKey); - - /** - * Add your comment to your query. - * - * @param comment - * as String - * @return the query - */ - HistoryQuery commentIn(String... comment); - - /** - * Add your oldValue to your query. - * - * @param oldValue - * as String - * @return the query - */ - HistoryQuery oldValueIn(String... oldValue); - - /** - * Add your newValue to your query. - * - * @param newValue - * as String - * @return the query - */ - HistoryQuery newValueIn(String... newValue); - - /** - * Add your custom1 to your query. - * - * @param custom1 - * as String - * @return the query - */ - HistoryQuery custom1In(String... custom1); - - /** - * Add your custom2 to your query. - * - * @param custom2 - * as String - * @return the query - */ - HistoryQuery custom2In(String... custom2); - - /** - * Add your custom3 to your query. - * - * @param custom3 - * as String - * @return the query - */ - HistoryQuery custom3In(String... custom3); - - /** - * Add your custom4 to your query. - * - * @param custom4 - * as String - * @return the query - */ - HistoryQuery custom4In(String... custom4); - - /** - * Add your oldData to your query. - * - * @param oldData - * as String - * @return the query - */ - HistoryQuery oldDataIn(String... oldData); - - /** - * Add your newData to your query. - * - * @param newData - * as String - * @return the query - */ - HistoryQuery newDataIn(String... newData); - - /** - * Add your businessProcessId to your query. It will be compared in SQL with an LIKE. If you use a wildcard like % then it - * will be transmitted to the database. - * - * @param businessProcessId - * as String - * @return the query - */ - HistoryQuery businessProcessIdLike(String... businessProcessId); - - /** - * Add your parentBusinessProcessId to your query. It will be compared in SQL with an LIKE. If you use a wildcard like % then it - * will be transmitted to the database. - * - * @param parentBusinessProcessId - * as String - * @return the query - */ - HistoryQuery parentBusinessProcessIdLike(String... parentBusinessProcessId); - - /** - * Add your taskId to your query. It will be compared in SQL with an LIKE. If you use a wildcard like % then it - * will be transmitted to the database. - * - * @param taskId - * as String - * @return the query - */ - HistoryQuery taskIdLike(String... taskId); - - /** - * Add your eventType to your query. It will be compared in SQL with an LIKE. If you use a wildcard like % then it - * will be transmitted to the database. - * - * @param eventType - * as String - * @return the query - */ - HistoryQuery eventTypeLike(String... eventType); - - /** - * Add your userId to your query. It will be compared in SQL with an LIKE. If you use a wildcard like % then it - * will be transmitted to the database. - * - * @param userId - * as String - * @return the query - */ - HistoryQuery userIdLike(String... userId); - - /** - * Add your domain to your query. It will be compared in SQL with an LIKE. If you use a wildcard like % then it - * will be transmitted to the database. - * - * @param domain - * as String - * @return the query - */ - HistoryQuery domainLike(String... domain); - - /** - * Add your workbasketKey to your query. It will be compared in SQL with an LIKE. If you use a wildcard like % then it - * will be transmitted to the database. - * - * @param workbasketKey - * as String - * @return the query - */ - HistoryQuery workbasketKeyLike(String... workbasketKey); - - /** - * Add your porCompany to your query. It will be compared in SQL with an LIKE. If you use a wildcard like % then it - * will be transmitted to the database. - * - * @param porCompany - * as String - * @return the query - */ - HistoryQuery porCompanyLike(String... porCompany); - - /** - * Add your porSystem to your query. It will be compared in SQL with an LIKE. If you use a wildcard like % then it - * will be transmitted to the database. - * - * @param porSystem - * as String - * @return the query - */ - HistoryQuery porSystemLike(String... porSystem); - - /** - * Add your porInstance to your query. It will be compared in SQL with an LIKE. If you use a wildcard like % then it - * will be transmitted to the database. - * - * @param porInstance - * as String - * @return the query - */ - HistoryQuery porInstanceLike(String... porInstance); - - /** - * Add your porType to your query. It will be compared in SQL with an LIKE. If you use a wildcard like % then it - * will be transmitted to the database. - * - * @param porType - * as String - * @return the query - */ - HistoryQuery porTypeLike(String... porType); - - /** - * Add your porValue to your query. It will be compared in SQL with an LIKE. If you use a wildcard like % then it - * will be transmitted to the database. - * - * @param porValue - * as String - * @return the query - */ - HistoryQuery porValueLike(String... porValue); - - /** - * Add your taskClassificationKey to your query. It will be compared in SQL with an LIKE. If you use a wildcard like % then it - * will be transmitted to the database. - * - * @param taskClassificationKey - * as String - * @return the query - */ - HistoryQuery taskClassificationKeyLike(String... taskClassificationKey); - - /** - * Add your taskClassificationCategory to your query. It will be compared in SQL with an LIKE. If you use a wildcard like % then it - * will be transmitted to the database. - * - * @param taskClassificationCategory - * as String - * @return the query - */ - HistoryQuery taskClassificationCategoryLike(String... taskClassificationCategory); - - /** - * Add your attachmentClassificationKey to your query. It will be compared in SQL with an LIKE. If you use a wildcard like % then it - * will be transmitted to the database. - * - * @param attachmentClassificationKey - * as String - * @return the query - */ - HistoryQuery attachmentClassificationKeyLike(String... attachmentClassificationKey); - - /** - * Add your comment to your query. It will be compared in SQL with an LIKE. If you use a wildcard like % then it - * will be transmitted to the database. - * - * @param comment - * as String - * @return the query - */ - HistoryQuery commentLike(String... comment); - - /** - * Add your oldValue to your query. It will be compared in SQL with an LIKE. If you use a wildcard like % then it - * will be transmitted to the database. - * - * @param oldValue - * as String - * @return the query - */ - HistoryQuery oldValueLike(String... oldValue); - - /** - * Add your newValue to your query. It will be compared in SQL with an LIKE. If you use a wildcard like % then it - * will be transmitted to the database. - * - * @param newValue - * as String - * @return the query - */ - HistoryQuery newValueLike(String... newValue); - - /** - * Add your custom1 to your query. It will be compared in SQL with an LIKE. If you use a wildcard like % then it - * will be transmitted to the database. - * - * @param custom1 - * as String - * @return the query - */ - HistoryQuery custom1Like(String... custom1); - - /** - * Add your custom2 to your query. It will be compared in SQL with an LIKE. If you use a wildcard like % then it - * will be transmitted to the database. - * - * @param custom2 - * as String - * @return the query - */ - HistoryQuery custom2Like(String... custom2); - - /** - * Add your custom3 to your query. It will be compared in SQL with an LIKE. If you use a wildcard like % then it - * will be transmitted to the database. - * - * @param custom3 - * as String - * @return the query - */ - HistoryQuery custom3Like(String... custom3); - - /** - * Add your custom4 to your query. It will be compared in SQL with an LIKE. If you use a wildcard like % then it - * will be transmitted to the database. - * - * @param custom4 - * as String - * @return the query - */ - HistoryQuery custom4Like(String... custom4); - - /** - * Add your oldData to your query. It will be compared in SQL with an LIKE. If you use a wildcard like % then it - * will be transmitted to the database. - * - * @param oldData - * as String - * @return the query - */ - HistoryQuery oldDataLike(String... oldData); - - /** - * Add your newData to your query. It will be compared in SQL with an LIKE. If you use a wildcard like % then it - * will be transmitted to the database. - * - * @param newData - * as String - * @return the query - */ - HistoryQuery newDataLike(String... newData); - - /** - * Sort the query result by businessProcessId. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - HistoryQuery orderByBusinessProcessId(SortDirection sortDirection); - - /** - * Sort the query result by parentBusinessProcessId. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - HistoryQuery orderByParentBusinessProcessId(SortDirection sortDirection); - - /** - * Sort the query result by taskId. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - HistoryQuery orderByTaskId(SortDirection sortDirection); - - /** - * Sort the query result by eventType. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - HistoryQuery orderByEventType(SortDirection sortDirection); - - /** - * Sort the query result by created. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - HistoryQuery orderByCreated(SortDirection sortDirection); - - /** - * Sort the query result by userId. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - HistoryQuery orderByUserId(SortDirection sortDirection); - - /** - * Sort the query result by Domain. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - HistoryQuery orderByDomain(SortDirection sortDirection); - - /** - * Sort the query result by WorkbasketKey. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - HistoryQuery orderByWorkbasketKey(SortDirection sortDirection); - - /** - * Sort the query result by porCompany. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - HistoryQuery orderByPorCompany(SortDirection sortDirection); - - /** - * Sort the query result by porSystem. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - HistoryQuery orderByPorSystem(SortDirection sortDirection); - - /** - * Sort the query result by porInstance. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - HistoryQuery orderByPorInstance(SortDirection sortDirection); - - /** - * Sort the query result by porType. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - HistoryQuery orderByPorType(SortDirection sortDirection); - - /** - * Sort the query result by porValue. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - HistoryQuery orderByPorValue(SortDirection sortDirection); - - /** - * Sort the query result by taskClassificationKey. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - HistoryQuery orderByTaskClassificationKey(SortDirection sortDirection); - - /** - * Sort the query result by taskClassificationCategory. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - HistoryQuery orderByTaskClassificationCategory(SortDirection sortDirection); - - /** - * Sort the query result by attachmentClassificationKey. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - HistoryQuery orderByAttachmentClassificationKey(SortDirection sortDirection); - - /** - * Sort the query result by comment. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - HistoryQuery orderByComment(SortDirection sortDirection); - - /** - * Sort the query result by oldValue. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - HistoryQuery orderByOldValue(SortDirection sortDirection); - - /** - * Sort the query result by newValue. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - HistoryQuery orderByNewValue(SortDirection sortDirection); - - /** - * Sort the query result by oldData. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - HistoryQuery orderByOldData(SortDirection sortDirection); - - /** - * Sort the query result by newData. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - HistoryQuery orderByNewData(SortDirection sortDirection); - - /** - * Sort the query result by a custom. - * - * @param num - * the number of the custom as String (eg "4") - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - * @throws InvalidArgumentException - * when the number of the custom is incorrect. - */ - HistoryQuery orderByCustomAttribute(int num, SortDirection sortDirection) throws InvalidArgumentException; + /** + * Add your Id to your query. + * + * @param idIn as String + * @return the query + */ + HistoryQuery idIn(String... idIn); + + /** + * Add your businessProcessId to your query. + * + * @param businessProcessId as String + * @return the query + */ + HistoryQuery businessProcessIdIn(String... businessProcessId); + + /** + * Add your parentBusinessProcessId to your query. + * + * @param parentBusinessProcessId as String + * @return the query + */ + HistoryQuery parentBusinessProcessIdIn(String... parentBusinessProcessId); + + /** + * Add your taskId to your query. + * + * @param taskId as String + * @return the query + */ + HistoryQuery taskIdIn(String... taskId); + + /** + * Add your eventType to your query. + * + * @param eventType as String + * @return the query + */ + HistoryQuery eventTypeIn(String... eventType); + + /** + * Add your created TimeInterval to your query. + * + * @param createdWithin the {@link TimeInterval} within which the searched-for classifications + * were created. + * @return the query + */ + HistoryQuery createdWithin(TimeInterval... createdWithin); + + /** + * Add your userId to your query. + * + * @param userId as String + * @return the query + */ + HistoryQuery userIdIn(String... userId); + + /** + * Add your domain to your query. + * + * @param domain as String + * @return the query + */ + HistoryQuery domainIn(String... domain); + + /** + * Add your workbasketKey to your query. + * + * @param workbasketKey as String + * @return the query + */ + HistoryQuery workbasketKeyIn(String... workbasketKey); + + /** + * Add your porCompany to your query. + * + * @param porCompany as String + * @return the query + */ + HistoryQuery porCompanyIn(String... porCompany); + + /** + * Add your porSystem to your query. + * + * @param porSystem as String + * @return the query + */ + HistoryQuery porSystemIn(String... porSystem); + + /** + * Add your porInstance to your query. + * + * @param porInstance as String + * @return the query + */ + HistoryQuery porInstanceIn(String... porInstance); + + /** + * Add your porType to your query. + * + * @param porType as String + * @return the query + */ + HistoryQuery porTypeIn(String... porType); + + /** + * Add your porValue to your query. + * + * @param porValue as String + * @return the query + */ + HistoryQuery porValueIn(String... porValue); + + /** + * Add your taskClassificationKey to your query. + * + * @param taskClassificationKey as String + * @return the query + */ + HistoryQuery taskClassificationKeyIn(String... taskClassificationKey); + + /** + * Add your taskClassificationCategory to your query. + * + * @param taskClassificationCategory as String + * @return the query + */ + HistoryQuery taskClassificationCategoryIn(String... taskClassificationCategory); + + /** + * Add your attachmentClassificationKey to your query. + * + * @param attachmentClassificationKey as String + * @return the query + */ + HistoryQuery attachmentClassificationKeyIn(String... attachmentClassificationKey); + + /** + * Add your comment to your query. + * + * @param comment as String + * @return the query + */ + HistoryQuery commentIn(String... comment); + + /** + * Add your oldValue to your query. + * + * @param oldValue as String + * @return the query + */ + HistoryQuery oldValueIn(String... oldValue); + + /** + * Add your newValue to your query. + * + * @param newValue as String + * @return the query + */ + HistoryQuery newValueIn(String... newValue); + + /** + * Add your custom1 to your query. + * + * @param custom1 as String + * @return the query + */ + HistoryQuery custom1In(String... custom1); + + /** + * Add your custom2 to your query. + * + * @param custom2 as String + * @return the query + */ + HistoryQuery custom2In(String... custom2); + + /** + * Add your custom3 to your query. + * + * @param custom3 as String + * @return the query + */ + HistoryQuery custom3In(String... custom3); + + /** + * Add your custom4 to your query. + * + * @param custom4 as String + * @return the query + */ + HistoryQuery custom4In(String... custom4); + + /** + * Add your oldData to your query. + * + * @param oldData as String + * @return the query + */ + HistoryQuery oldDataIn(String... oldData); + + /** + * Add your newData to your query. + * + * @param newData as String + * @return the query + */ + HistoryQuery newDataIn(String... newData); + + /** + * Add your businessProcessId to your query. It will be compared in SQL with an LIKE. If you use a + * wildcard like % then it will be transmitted to the database. + * + * @param businessProcessId as String + * @return the query + */ + HistoryQuery businessProcessIdLike(String... businessProcessId); + + /** + * Add your parentBusinessProcessId to your query. It will be compared in SQL with an LIKE. If you + * use a wildcard like % then it will be transmitted to the database. + * + * @param parentBusinessProcessId as String + * @return the query + */ + HistoryQuery parentBusinessProcessIdLike(String... parentBusinessProcessId); + + /** + * Add your taskId to your query. It will be compared in SQL with an LIKE. If you use a wildcard + * like % then it will be transmitted to the database. + * + * @param taskId as String + * @return the query + */ + HistoryQuery taskIdLike(String... taskId); + + /** + * Add your eventType to your query. It will be compared in SQL with an LIKE. If you use a + * wildcard like % then it will be transmitted to the database. + * + * @param eventType as String + * @return the query + */ + HistoryQuery eventTypeLike(String... eventType); + + /** + * Add your userId to your query. It will be compared in SQL with an LIKE. If you use a wildcard + * like % then it will be transmitted to the database. + * + * @param userId as String + * @return the query + */ + HistoryQuery userIdLike(String... userId); + + /** + * Add your domain to your query. It will be compared in SQL with an LIKE. If you use a wildcard + * like % then it will be transmitted to the database. + * + * @param domain as String + * @return the query + */ + HistoryQuery domainLike(String... domain); + + /** + * Add your workbasketKey to your query. It will be compared in SQL with an LIKE. If you use a + * wildcard like % then it will be transmitted to the database. + * + * @param workbasketKey as String + * @return the query + */ + HistoryQuery workbasketKeyLike(String... workbasketKey); + + /** + * Add your porCompany to your query. It will be compared in SQL with an LIKE. If you use a + * wildcard like % then it will be transmitted to the database. + * + * @param porCompany as String + * @return the query + */ + HistoryQuery porCompanyLike(String... porCompany); + + /** + * Add your porSystem to your query. It will be compared in SQL with an LIKE. If you use a + * wildcard like % then it will be transmitted to the database. + * + * @param porSystem as String + * @return the query + */ + HistoryQuery porSystemLike(String... porSystem); + + /** + * Add your porInstance to your query. It will be compared in SQL with an LIKE. If you use a + * wildcard like % then it will be transmitted to the database. + * + * @param porInstance as String + * @return the query + */ + HistoryQuery porInstanceLike(String... porInstance); + + /** + * Add your porType to your query. It will be compared in SQL with an LIKE. If you use a wildcard + * like % then it will be transmitted to the database. + * + * @param porType as String + * @return the query + */ + HistoryQuery porTypeLike(String... porType); + + /** + * Add your porValue to your query. It will be compared in SQL with an LIKE. If you use a wildcard + * like % then it will be transmitted to the database. + * + * @param porValue as String + * @return the query + */ + HistoryQuery porValueLike(String... porValue); + + /** + * Add your taskClassificationKey to your query. It will be compared in SQL with an LIKE. If you + * use a wildcard like % then it will be transmitted to the database. + * + * @param taskClassificationKey as String + * @return the query + */ + HistoryQuery taskClassificationKeyLike(String... taskClassificationKey); + + /** + * Add your taskClassificationCategory to your query. It will be compared in SQL with an LIKE. If + * you use a wildcard like % then it will be transmitted to the database. + * + * @param taskClassificationCategory as String + * @return the query + */ + HistoryQuery taskClassificationCategoryLike(String... taskClassificationCategory); + + /** + * Add your attachmentClassificationKey to your query. It will be compared in SQL with an LIKE. If + * you use a wildcard like % then it will be transmitted to the database. + * + * @param attachmentClassificationKey as String + * @return the query + */ + HistoryQuery attachmentClassificationKeyLike(String... attachmentClassificationKey); + + /** + * Add your comment to your query. It will be compared in SQL with an LIKE. If you use a wildcard + * like % then it will be transmitted to the database. + * + * @param comment as String + * @return the query + */ + HistoryQuery commentLike(String... comment); + + /** + * Add your oldValue to your query. It will be compared in SQL with an LIKE. If you use a wildcard + * like % then it will be transmitted to the database. + * + * @param oldValue as String + * @return the query + */ + HistoryQuery oldValueLike(String... oldValue); + + /** + * Add your newValue to your query. It will be compared in SQL with an LIKE. If you use a wildcard + * like % then it will be transmitted to the database. + * + * @param newValue as String + * @return the query + */ + HistoryQuery newValueLike(String... newValue); + + /** + * Add your custom1 to your query. It will be compared in SQL with an LIKE. If you use a wildcard + * like % then it will be transmitted to the database. + * + * @param custom1 as String + * @return the query + */ + HistoryQuery custom1Like(String... custom1); + + /** + * Add your custom2 to your query. It will be compared in SQL with an LIKE. If you use a wildcard + * like % then it will be transmitted to the database. + * + * @param custom2 as String + * @return the query + */ + HistoryQuery custom2Like(String... custom2); + + /** + * Add your custom3 to your query. It will be compared in SQL with an LIKE. If you use a wildcard + * like % then it will be transmitted to the database. + * + * @param custom3 as String + * @return the query + */ + HistoryQuery custom3Like(String... custom3); + + /** + * Add your custom4 to your query. It will be compared in SQL with an LIKE. If you use a wildcard + * like % then it will be transmitted to the database. + * + * @param custom4 as String + * @return the query + */ + HistoryQuery custom4Like(String... custom4); + + /** + * Add your oldData to your query. It will be compared in SQL with an LIKE. If you use a wildcard + * like % then it will be transmitted to the database. + * + * @param oldData as String + * @return the query + */ + HistoryQuery oldDataLike(String... oldData); + + /** + * Add your newData to your query. It will be compared in SQL with an LIKE. If you use a wildcard + * like % then it will be transmitted to the database. + * + * @param newData as String + * @return the query + */ + HistoryQuery newDataLike(String... newData); + + /** + * Sort the query result by businessProcessId. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + HistoryQuery orderByBusinessProcessId(SortDirection sortDirection); + + /** + * Sort the query result by parentBusinessProcessId. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + HistoryQuery orderByParentBusinessProcessId(SortDirection sortDirection); + + /** + * Sort the query result by taskId. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + HistoryQuery orderByTaskId(SortDirection sortDirection); + + /** + * Sort the query result by eventType. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + HistoryQuery orderByEventType(SortDirection sortDirection); + + /** + * Sort the query result by created. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + HistoryQuery orderByCreated(SortDirection sortDirection); + + /** + * Sort the query result by userId. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + HistoryQuery orderByUserId(SortDirection sortDirection); + + /** + * Sort the query result by Domain. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + HistoryQuery orderByDomain(SortDirection sortDirection); + + /** + * Sort the query result by WorkbasketKey. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + HistoryQuery orderByWorkbasketKey(SortDirection sortDirection); + + /** + * Sort the query result by porCompany. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + HistoryQuery orderByPorCompany(SortDirection sortDirection); + + /** + * Sort the query result by porSystem. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + HistoryQuery orderByPorSystem(SortDirection sortDirection); + + /** + * Sort the query result by porInstance. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + HistoryQuery orderByPorInstance(SortDirection sortDirection); + + /** + * Sort the query result by porType. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + HistoryQuery orderByPorType(SortDirection sortDirection); + + /** + * Sort the query result by porValue. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + HistoryQuery orderByPorValue(SortDirection sortDirection); + + /** + * Sort the query result by taskClassificationKey. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + HistoryQuery orderByTaskClassificationKey(SortDirection sortDirection); + + /** + * Sort the query result by taskClassificationCategory. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + HistoryQuery orderByTaskClassificationCategory(SortDirection sortDirection); + + /** + * Sort the query result by attachmentClassificationKey. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + HistoryQuery orderByAttachmentClassificationKey(SortDirection sortDirection); + + /** + * Sort the query result by comment. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + HistoryQuery orderByComment(SortDirection sortDirection); + + /** + * Sort the query result by oldValue. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + HistoryQuery orderByOldValue(SortDirection sortDirection); + + /** + * Sort the query result by newValue. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + HistoryQuery orderByNewValue(SortDirection sortDirection); + + /** + * Sort the query result by oldData. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + HistoryQuery orderByOldData(SortDirection sortDirection); + + /** + * Sort the query result by newData. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + HistoryQuery orderByNewData(SortDirection sortDirection); + + /** + * Sort the query result by a custom. + * + * @param num the number of the custom as String (eg "4") + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + * @throws InvalidArgumentException when the number of the custom is incorrect. + */ + HistoryQuery orderByCustomAttribute(int num, SortDirection sortDirection) + throws InvalidArgumentException; } diff --git a/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/query/HistoryQueryColumnName.java b/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/query/HistoryQueryColumnName.java index 79f4410ec..0043a0e8d 100644 --- a/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/query/HistoryQueryColumnName.java +++ b/history/taskana-simplehistory-provider/src/main/java/pro/taskana/simplehistory/query/HistoryQueryColumnName.java @@ -3,46 +3,48 @@ package pro.taskana.simplehistory.query; import pro.taskana.QueryColumnName; /** - * Enum containing the column names for @see pro.taskana.simplehistory.mappings.HistoryQueryMapper#queryHistoryColumnValues(pro.taskana.simplehistory.impl.HistoryQueryImpl). + * Enum containing the column names for @see + * pro.taskana.simplehistory.mappings.HistoryQueryMapper#queryHistoryColumnValues(pro.taskana.simplehistory.impl.HistoryQueryImpl). * * @author bv */ public enum HistoryQueryColumnName implements QueryColumnName { - ID("id"), - BUSINESS_PROCESS_ID("business_process_id"), - PARENT_BUSINESS_PROCESS_ID("parent_business_process_id"), - TASK_ID("task_id"), - EVENT_TYPE("event_type"), - CREATED("created"), - USER_ID("user_id"), - DOMAIN("domain"), - WORKBASKET_KEY("workbasket_key"), - POR_COMPANY("por_company"), - POR_SYSTEM("por_system"), - POR_INSTANCE("por_instance"), - POR_TYPE("por_type"), - POR_VALUE("por_value"), - TASK_CLASSIFICATION_KEY("task_classification_key"), - TASK_CLASSIFICATION_CATEGORY("task_classification_category"), - ATTACHMENT_CLASSIFICATION_KEY("attachment_classification_key"), - COMMENT("comment"), - OLD_VALUE("old_value"), - NEW_VALUE("new_value"), - CUSTOM_1("custom_1"), - CUSTOM_2("custom_2"), - CUSTOM_3("custom_3"), - CUSTOM_4("custom_4"), - OLD_DATA("old_data"), - NEW_DATA("new_data"), - TYPE("type"); + ID("id"), + BUSINESS_PROCESS_ID("business_process_id"), + PARENT_BUSINESS_PROCESS_ID("parent_business_process_id"), + TASK_ID("task_id"), + EVENT_TYPE("event_type"), + CREATED("created"), + USER_ID("user_id"), + DOMAIN("domain"), + WORKBASKET_KEY("workbasket_key"), + POR_COMPANY("por_company"), + POR_SYSTEM("por_system"), + POR_INSTANCE("por_instance"), + POR_TYPE("por_type"), + POR_VALUE("por_value"), + TASK_CLASSIFICATION_KEY("task_classification_key"), + TASK_CLASSIFICATION_CATEGORY("task_classification_category"), + ATTACHMENT_CLASSIFICATION_KEY("attachment_classification_key"), + COMMENT("comment"), + OLD_VALUE("old_value"), + NEW_VALUE("new_value"), + CUSTOM_1("custom_1"), + CUSTOM_2("custom_2"), + CUSTOM_3("custom_3"), + CUSTOM_4("custom_4"), + OLD_DATA("old_data"), + NEW_DATA("new_data"), + TYPE("type"); - private String name; - HistoryQueryColumnName(String name) { - this.name = name; - } + private String name; - @Override - public String toString() { - return name; - } + HistoryQueryColumnName(String name) { + this.name = name; + } + + @Override + public String toString() { + return name; + } } diff --git a/history/taskana-simplehistory-provider/src/test/java/acceptance/AbstractAccTest.java b/history/taskana-simplehistory-provider/src/test/java/acceptance/AbstractAccTest.java index 03024c0cb..66c7c1dc9 100644 --- a/history/taskana-simplehistory-provider/src/test/java/acceptance/AbstractAccTest.java +++ b/history/taskana-simplehistory-provider/src/test/java/acceptance/AbstractAccTest.java @@ -1,5 +1,6 @@ package acceptance; +import configuration.DBWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -7,234 +8,239 @@ import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import java.util.Properties; - import javax.sql.DataSource; - import org.apache.ibatis.datasource.pooled.PooledDataSource; import org.junit.BeforeClass; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import configuration.DBWriter; import pro.taskana.configuration.TaskanaEngineConfiguration; import pro.taskana.simplehistory.impl.HistoryEventImpl; import pro.taskana.simplehistory.impl.SimpleHistoryServiceImpl; -/** - * Set up database for tests. - */ +/** Set up database for tests. */ public class AbstractAccTest { - public static SimpleHistoryServiceImpl historyService; + private static final Logger LOGGER = LoggerFactory.getLogger(AbstractAccTest.class); + private static final int POOL_TIME_TO_WAIT = 50; + public static SimpleHistoryServiceImpl historyService; + protected static TaskanaEngineConfiguration taskanaEngineConfiguration; + private static DataSource dataSource = null; + private static String schemaName = null; - protected static TaskanaEngineConfiguration taskanaEngineConfiguration; + protected AbstractAccTest() { + // not called + } - private static DataSource dataSource = null; + @BeforeClass + public static void setupTest() throws Exception { + resetDb(null); + } - private static String schemaName = null; - - private static final Logger LOGGER = LoggerFactory.getLogger(AbstractAccTest.class); - - private static final int POOL_TIME_TO_WAIT = 50; - - protected AbstractAccTest() { - // not called - } - - @BeforeClass - public static void setupTest() throws Exception { - resetDb(null); - } - - public static void resetDb(String schemaName) throws SQLException { - DataSource dataSource = getDataSource(); - DBWriter writer = new DBWriter(); - taskanaEngineConfiguration = new TaskanaEngineConfiguration(dataSource, false, + public static void resetDb(String schemaName) throws SQLException { + DataSource dataSource = getDataSource(); + DBWriter writer = new DBWriter(); + taskanaEngineConfiguration = + new TaskanaEngineConfiguration( + dataSource, + false, schemaName != null && !schemaName.isEmpty() ? schemaName : getSchemaName()); - historyService = new SimpleHistoryServiceImpl(); - historyService.initialize(taskanaEngineConfiguration); + historyService = new SimpleHistoryServiceImpl(); + historyService.initialize(taskanaEngineConfiguration); - writer.clearDB(dataSource); - writer.generateTestData(dataSource); + writer.clearDB(dataSource); + writer.generateTestData(dataSource); + } + + /** + * returns the DataSource used for Junit test. If the file {user.home}/taskanaUnitTest.properties + * is present, the Datasource is created according to the properties jdbcDriver, jdbcUrl, + * dbUserName and dbPassword. Assuming, the database has the name tskdb, a sample properties file + * for DB2 looks as follows: jdbcDriver=com.ibm.db2.jcc.DB2Driver + * jdbcUrl=jdbc:db2://localhost:50000/tskdb dbUserName=db2user dbPassword=db2password If any of + * these properties is missing, or the file doesn't exist, the default Datasource for h2 in-memory + * db is created. + * + * @return dataSource for unit test + */ + public static DataSource getDataSource() { + if (dataSource == null) { + String userHomeDirectroy = System.getProperty("user.home"); + String propertiesFileName = userHomeDirectroy + "/taskanaUnitTest.properties"; + File f = new File(propertiesFileName); + if (f.exists() && !f.isDirectory()) { + dataSource = createDataSourceFromProperties(propertiesFileName); + } else { + dataSource = createDefaultDataSource(); + } + } + return dataSource; + } + + /** + * returns the SchemaName used for Junit test. If the file {user.home}/taskanaUnitTest.properties + * is present, the SchemaName is created according to the property schemaName. a sample properties + * file for DB2 looks as follows: jdbcDriver=com.ibm.db2.jcc.DB2Driver + * jdbcUrl=jdbc:db2://localhost:50000/tskdb dbUserName=db2user dbPassword=db2password + * schemaName=TASKANA If any of these properties is missing, or the file doesn't exist, the + * default schemaName TASKANA is created used. + * + * @return String for unit test + */ + public static String getSchemaName() { + if (schemaName == null) { + String userHomeDirectroy = System.getProperty("user.home"); + String propertiesFileName = userHomeDirectroy + "/taskanaUnitTest.properties"; + File f = new File(propertiesFileName); + if (f.exists() && !f.isDirectory()) { + schemaName = getSchemaNameFromPropertiesObject(propertiesFileName); + } else { + schemaName = "TASKANA"; + } + } + return schemaName; + } + + /** + * create historyEvent object. + * + * @param workbasketKey the workbasketKey, the task currently resides in. + * @param taskId the taskid the event belongs to. + * @param type the type of the event. + * @param comment the individual comment. + * @param previousWorkbasketId the workbasketId of the previous workbasket (if applicable). + * @return History event object created. + */ + public static HistoryEventImpl createHistoryEvent( + String workbasketKey, + String taskId, + String type, + String comment, + String previousWorkbasketId) { + HistoryEventImpl historyEvent = new HistoryEventImpl(); + historyEvent.setWorkbasketKey(workbasketKey); + historyEvent.setTaskId(taskId); + historyEvent.setEventType(type); + historyEvent.setComment(comment); + historyEvent.setOldValue(previousWorkbasketId); + return historyEvent; + } + + /** + * create Default DataSource for in-memory database. + * + * @return the TASKANA default datasource. + */ + private static DataSource createDefaultDataSource() { + + String jdbcDriver = "org.h2.Driver"; + String jdbcUrl = "jdbc:h2:mem:taskana;IGNORECASE=TRUE;LOCK_MODE=0"; + String dbUserName = "sa"; + String dbPassword = "sa"; + DataSource ds = + new PooledDataSource( + Thread.currentThread().getContextClassLoader(), + jdbcDriver, + jdbcUrl, + dbUserName, + dbPassword); + ((PooledDataSource) ds).setPoolTimeToWait(POOL_TIME_TO_WAIT); + ((PooledDataSource) ds) + .forceCloseAll(); // otherwise the MyBatis pool is not initialized correctly + + return ds; + } + + /** + * create data source from properties file. + * + * @param propertiesFileName the name of the properties file. + * @return the datasource constructed from the information in the properties file. + */ + private static DataSource createDataSourceFromProperties(String propertiesFileName) { + DataSource ds = null; + try (InputStream input = new FileInputStream(propertiesFileName)) { + Properties prop = new Properties(); + prop.load(input); + boolean propertiesFileIsComplete = true; + String warningMessage = ""; + String jdbcDriver = prop.getProperty("jdbcDriver"); + if (jdbcDriver == null || jdbcDriver.length() == 0) { + propertiesFileIsComplete = false; + warningMessage += ", jdbcDriver property missing"; + } + String jdbcUrl = prop.getProperty("jdbcUrl"); + if (jdbcUrl == null || jdbcUrl.length() == 0) { + propertiesFileIsComplete = false; + warningMessage += ", jdbcUrl property missing"; + } + String dbUserName = prop.getProperty("dbUserName"); + if (dbUserName == null || dbUserName.length() == 0) { + propertiesFileIsComplete = false; + warningMessage += ", dbUserName property missing"; + } + String dbPassword = prop.getProperty("dbPassword"); + if (dbPassword == null || dbPassword.length() == 0) { + propertiesFileIsComplete = false; + warningMessage += ", dbPassword property missing"; + } + + if (propertiesFileIsComplete) { + ds = + new PooledDataSource( + Thread.currentThread().getContextClassLoader(), + jdbcDriver, + jdbcUrl, + dbUserName, + dbPassword); + ((PooledDataSource) ds) + .forceCloseAll(); // otherwise the MyBatis pool is not initialized correctly + } else { + LOGGER.warn("propertiesFile " + propertiesFileName + " is incomplete" + warningMessage); + LOGGER.warn("Using default Datasource for Test"); + ds = createDefaultDataSource(); + } + + } catch (FileNotFoundException e) { + LOGGER.warn("createDataSourceFromProperties caught Exception " + e); + LOGGER.warn("Using default Datasource for Test"); + ds = createDefaultDataSource(); + } catch (IOException e) { + LOGGER.warn("createDataSourceFromProperties caught Exception " + e); + LOGGER.warn("Using default Datasource for Test"); + ds = createDefaultDataSource(); } - /** - * returns the DataSource used for Junit test. If the file {user.home}/taskanaUnitTest.properties is present, the - * Datasource is created according to the properties jdbcDriver, jdbcUrl, dbUserName and dbPassword. Assuming, the - * database has the name tskdb, a sample properties file for DB2 looks as follows: - * jdbcDriver=com.ibm.db2.jcc.DB2Driver jdbcUrl=jdbc:db2://localhost:50000/tskdb dbUserName=db2user - * dbPassword=db2password If any of these properties is missing, or the file doesn't exist, the default Datasource - * for h2 in-memory db is created. - * - * @return dataSource for unit test - */ - public static DataSource getDataSource() { - if (dataSource == null) { - String userHomeDirectroy = System.getProperty("user.home"); - String propertiesFileName = userHomeDirectroy + "/taskanaUnitTest.properties"; - File f = new File(propertiesFileName); - if (f.exists() && !f.isDirectory()) { - dataSource = createDataSourceFromProperties(propertiesFileName); - } else { - dataSource = createDefaultDataSource(); - } - } - return dataSource; + return ds; + } + + private static String getSchemaNameFromPropertiesObject(String propertiesFileName) { + String schemaName = "TASKANA"; + try (InputStream input = new FileInputStream(propertiesFileName)) { + Properties prop = new Properties(); + prop.load(input); + boolean propertiesFileIsComplete = true; + String warningMessage = ""; + schemaName = prop.getProperty("schemaName"); + if (schemaName == null || schemaName.length() == 0) { + propertiesFileIsComplete = false; + warningMessage += ", schemaName property missing"; + } + + if (!propertiesFileIsComplete) { + LOGGER.warn("propertiesFile " + propertiesFileName + " is incomplete" + warningMessage); + LOGGER.warn("Using default Datasource for Test"); + schemaName = "TASKANA"; + } + + } catch (FileNotFoundException e) { + LOGGER.warn("getSchemaNameFromPropertiesObject caught Exception " + e); + LOGGER.warn("Using default schemaName for Test"); + } catch (IOException e) { + LOGGER.warn("createDataSourceFromProperties caught Exception " + e); + LOGGER.warn("Using default Datasource for Test"); } - /** - * create Default DataSource for in-memory database. - * - * @return the TASKANA default datasource. - */ - private static DataSource createDefaultDataSource() { - - String jdbcDriver = "org.h2.Driver"; - String jdbcUrl = "jdbc:h2:mem:taskana;IGNORECASE=TRUE;LOCK_MODE=0"; - String dbUserName = "sa"; - String dbPassword = "sa"; - DataSource ds = new PooledDataSource(Thread.currentThread().getContextClassLoader(), jdbcDriver, - jdbcUrl, dbUserName, dbPassword); - ((PooledDataSource) ds).setPoolTimeToWait(POOL_TIME_TO_WAIT); - ((PooledDataSource) ds).forceCloseAll(); // otherwise the MyBatis pool is not initialized correctly - - return ds; - } - - /** - * returns the SchemaName used for Junit test. If the file {user.home}/taskanaUnitTest.properties is present, the - * SchemaName is created according to the property schemaName. a sample properties file for DB2 looks as follows: - * jdbcDriver=com.ibm.db2.jcc.DB2Driver jdbcUrl=jdbc:db2://localhost:50000/tskdb dbUserName=db2user - * dbPassword=db2password schemaName=TASKANA If any of these properties is missing, or the file doesn't exist, the - * default schemaName TASKANA is created used. - * - * @return String for unit test - */ - public static String getSchemaName() { - if (schemaName == null) { - String userHomeDirectroy = System.getProperty("user.home"); - String propertiesFileName = userHomeDirectroy + "/taskanaUnitTest.properties"; - File f = new File(propertiesFileName); - if (f.exists() && !f.isDirectory()) { - schemaName = getSchemaNameFromPropertiesObject(propertiesFileName); - } else { - schemaName = "TASKANA"; - } - } - return schemaName; - } - - /** - * create historyEvent object. - * - * @param workbasketKey - * the workbasketKey, the task currently resides in. - * @param taskId - * the taskid the event belongs to. - * @param type - * the type of the event. - * @param comment - * the individual comment. - * @param previousWorkbasketId - * the workbasketId of the previous workbasket (if applicable). - * @return History event object created. - */ - public static HistoryEventImpl createHistoryEvent(String workbasketKey, String taskId, String type, String comment, - String previousWorkbasketId) { - HistoryEventImpl historyEvent = new HistoryEventImpl(); - historyEvent.setWorkbasketKey(workbasketKey); - historyEvent.setTaskId(taskId); - historyEvent.setEventType(type); - historyEvent.setComment(comment); - historyEvent.setOldValue(previousWorkbasketId); - return historyEvent; - } - - /** - * create data source from properties file. - * - * @param propertiesFileName - * the name of the properties file. - * @return the datasource constructed from the information in the properties file. - */ - private static DataSource createDataSourceFromProperties(String propertiesFileName) { - DataSource ds = null; - try (InputStream input = new FileInputStream(propertiesFileName)) { - Properties prop = new Properties(); - prop.load(input); - boolean propertiesFileIsComplete = true; - String warningMessage = ""; - String jdbcDriver = prop.getProperty("jdbcDriver"); - if (jdbcDriver == null || jdbcDriver.length() == 0) { - propertiesFileIsComplete = false; - warningMessage += ", jdbcDriver property missing"; - } - String jdbcUrl = prop.getProperty("jdbcUrl"); - if (jdbcUrl == null || jdbcUrl.length() == 0) { - propertiesFileIsComplete = false; - warningMessage += ", jdbcUrl property missing"; - } - String dbUserName = prop.getProperty("dbUserName"); - if (dbUserName == null || dbUserName.length() == 0) { - propertiesFileIsComplete = false; - warningMessage += ", dbUserName property missing"; - } - String dbPassword = prop.getProperty("dbPassword"); - if (dbPassword == null || dbPassword.length() == 0) { - propertiesFileIsComplete = false; - warningMessage += ", dbPassword property missing"; - } - - if (propertiesFileIsComplete) { - ds = new PooledDataSource(Thread.currentThread().getContextClassLoader(), jdbcDriver, - jdbcUrl, dbUserName, dbPassword); - ((PooledDataSource) ds).forceCloseAll(); // otherwise the MyBatis pool is not initialized correctly - } else { - LOGGER.warn("propertiesFile " + propertiesFileName + " is incomplete" + warningMessage); - LOGGER.warn("Using default Datasource for Test"); - ds = createDefaultDataSource(); - } - - } catch (FileNotFoundException e) { - LOGGER.warn("createDataSourceFromProperties caught Exception " + e); - LOGGER.warn("Using default Datasource for Test"); - ds = createDefaultDataSource(); - } catch (IOException e) { - LOGGER.warn("createDataSourceFromProperties caught Exception " + e); - LOGGER.warn("Using default Datasource for Test"); - ds = createDefaultDataSource(); - } - - return ds; - } - - private static String getSchemaNameFromPropertiesObject(String propertiesFileName) { - String schemaName = "TASKANA"; - try (InputStream input = new FileInputStream(propertiesFileName)) { - Properties prop = new Properties(); - prop.load(input); - boolean propertiesFileIsComplete = true; - String warningMessage = ""; - schemaName = prop.getProperty("schemaName"); - if (schemaName == null || schemaName.length() == 0) { - propertiesFileIsComplete = false; - warningMessage += ", schemaName property missing"; - } - - if (!propertiesFileIsComplete) { - LOGGER.warn("propertiesFile " + propertiesFileName + " is incomplete" + warningMessage); - LOGGER.warn("Using default Datasource for Test"); - schemaName = "TASKANA"; - } - - } catch (FileNotFoundException e) { - LOGGER.warn("getSchemaNameFromPropertiesObject caught Exception " + e); - LOGGER.warn("Using default schemaName for Test"); - } catch (IOException e) { - LOGGER.warn("createDataSourceFromProperties caught Exception " + e); - LOGGER.warn("Using default Datasource for Test"); - } - - return schemaName; - } + return schemaName; + } } diff --git a/history/taskana-simplehistory-provider/src/test/java/acceptance/query/QueryHistoryAccTest.java b/history/taskana-simplehistory-provider/src/test/java/acceptance/query/QueryHistoryAccTest.java index 3e6d85909..158b12977 100644 --- a/history/taskana-simplehistory-provider/src/test/java/acceptance/query/QueryHistoryAccTest.java +++ b/history/taskana-simplehistory-provider/src/test/java/acceptance/query/QueryHistoryAccTest.java @@ -5,308 +5,345 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; +import acceptance.AbstractAccTest; import java.time.Instant; import java.util.List; - import org.junit.Test; -import acceptance.AbstractAccTest; import pro.taskana.BaseQuery.SortDirection; import pro.taskana.TimeInterval; import pro.taskana.simplehistory.impl.HistoryEventImpl; import pro.taskana.simplehistory.query.HistoryQuery; import pro.taskana.simplehistory.query.HistoryQueryColumnName; -/** - * Test for History queries. - */ +/** Test for History queries. */ public class QueryHistoryAccTest extends AbstractAccTest { - public QueryHistoryAccTest() { - super(); - } + public QueryHistoryAccTest() { + super(); + } - @Test - public void testListValuesAscendingAndDescending() { - List defaultList = historyService.createHistoryQuery().listValues(HistoryQueryColumnName.COMMENT, null); - List ascendingList = historyService.createHistoryQuery() + @Test + public void testListValuesAscendingAndDescending() { + List defaultList = + historyService.createHistoryQuery().listValues(HistoryQueryColumnName.COMMENT, null); + List ascendingList = + historyService + .createHistoryQuery() .listValues(HistoryQueryColumnName.COMMENT, SortDirection.ASCENDING); - List descendingList = historyService.createHistoryQuery() + List descendingList = + historyService + .createHistoryQuery() .listValues(HistoryQueryColumnName.COMMENT, SortDirection.DESCENDING); - assertEquals(3, ascendingList.size()); - assertArrayEquals(defaultList.toArray(), ascendingList.toArray()); - assertEquals(ascendingList.get(2), descendingList.get(0)); - } + assertEquals(3, ascendingList.size()); + assertArrayEquals(defaultList.toArray(), ascendingList.toArray()); + assertEquals(ascendingList.get(2), descendingList.get(0)); + } - @Test - public void testComplexQuery() { - HistoryQuery query = historyService.createHistoryQuery() + @Test + public void testComplexQuery() { + HistoryQuery query = + historyService + .createHistoryQuery() .businessProcessIdLike("just some string", "BPI:%") .domainLike("%A") .orderByCreated(SortDirection.DESCENDING); - List results = query.list(); - assertEquals(2, results.size()); - assertEquals("admin", results.get(0).getUserId()); - assertEquals("peter", results.get(1).getUserId()); + List results = query.list(); + assertEquals(2, results.size()); + assertEquals("admin", results.get(0).getUserId()); + assertEquals("peter", results.get(1).getUserId()); - results = query.orderByUserId(SortDirection.DESCENDING).list(); - assertEquals(2, results.size()); - assertEquals("admin", results.get(0).getUserId()); - assertEquals("peter", results.get(1).getUserId()); - assertEquals(3, query.domainLike().count()); + results = query.orderByUserId(SortDirection.DESCENDING).list(); + assertEquals(2, results.size()); + assertEquals("admin", results.get(0).getUserId()); + assertEquals("peter", results.get(1).getUserId()); + assertEquals(3, query.domainLike().count()); + } - } + @Test + public void testQueryListOffset() { + List result = historyService.createHistoryQuery().list(1, 2); + List wrongList = historyService.createHistoryQuery().list(); - @Test - public void testQueryListOffset() { - List result = historyService.createHistoryQuery().list(1, 2); - List wrongList = historyService.createHistoryQuery().list(); + assertEquals(2, result.size()); - assertEquals(2, result.size()); + assertNotEquals(wrongList.get(0).getUserId(), result.get(0).getUserId()); + assertEquals(wrongList.get(1).getUserId(), result.get(0).getUserId()); + } - assertNotEquals(wrongList.get(0).getUserId(), result.get(0).getUserId()); - assertEquals(wrongList.get(1).getUserId(), result.get(0).getUserId()); - } + @Test + public void testCorrectResultWithWrongConstraints() { + List result = historyService.createHistoryQuery().list(1, 1000); + assertEquals(2, result.size()); + assertEquals("created by Peter", result.get(0).getComment()); - @Test - public void testCorrectResultWithWrongConstraints() { - List result = historyService.createHistoryQuery().list(1, 1000); - assertEquals(2, result.size()); - assertEquals("created by Peter", result.get(0).getComment()); + result = historyService.createHistoryQuery().list(100, 1000); + assertTrue(result.isEmpty()); + } - result = historyService.createHistoryQuery().list(100, 1000); - assertTrue(result.isEmpty()); + @Test + public void testSingle() { + HistoryEventImpl single = historyService.createHistoryQuery().userIdIn("peter").single(); + assertEquals("CREATE", single.getEventType()); - } + single = historyService.createHistoryQuery().eventTypeIn("CREATE", "xy").single(); + assertEquals("admin", single.getUserId()); + } - @Test - public void testSingle() { - HistoryEventImpl single = historyService.createHistoryQuery().userIdIn("peter").single(); - assertEquals("CREATE", single.getEventType()); + @Test + public void testCount() { + long count = historyService.createHistoryQuery().userIdIn("peter").count(); + assertEquals(1, count); - single = historyService.createHistoryQuery().eventTypeIn("CREATE", "xy").single(); - assertEquals("admin", single.getUserId()); - } + count = historyService.createHistoryQuery().count(); + assertEquals(3, count); - @Test - public void testCount() { - long count = historyService.createHistoryQuery().userIdIn("peter").count(); - assertEquals(1, count); + count = historyService.createHistoryQuery().userIdIn("klaus", "arnold", "benni").count(); + assertEquals(0, count); + } - count = historyService.createHistoryQuery().count(); - assertEquals(3, count); + @Test + public void testQueryAttributesIn() { + List returnValues = + historyService.createHistoryQuery().businessProcessIdIn("BPI:01", "BPI:02").list(); + assertEquals(2, returnValues.size()); - count = historyService.createHistoryQuery().userIdIn("klaus", "arnold", "benni").count(); - assertEquals(0, count); - } + returnValues = historyService.createHistoryQuery().parentBusinessProcessIdIn("BPI:01").list(); + assertEquals(1, returnValues.size()); - @Test - public void testQueryAttributesIn() { - List returnValues = historyService.createHistoryQuery() - .businessProcessIdIn("BPI:01", "BPI:02") + returnValues = + historyService + .createHistoryQuery() + .taskIdIn("TKI:000000000000000000000000000000000000") .list(); - assertEquals(2, returnValues.size()); + assertEquals(2, returnValues.size()); - returnValues = historyService.createHistoryQuery().parentBusinessProcessIdIn("BPI:01").list(); - assertEquals(1, returnValues.size()); + returnValues = historyService.createHistoryQuery().eventTypeIn("CREATE").list(); + assertEquals(3, returnValues.size()); - returnValues = historyService.createHistoryQuery().taskIdIn("TKI:000000000000000000000000000000000000").list(); - assertEquals(2, returnValues.size()); + TimeInterval timeInterval = new TimeInterval(Instant.now().minusSeconds(10), Instant.now()); + returnValues = historyService.createHistoryQuery().createdWithin(timeInterval).list(); + assertEquals(2, returnValues.size()); - returnValues = historyService.createHistoryQuery().eventTypeIn("CREATE").list(); - assertEquals(3, returnValues.size()); + returnValues = historyService.createHistoryQuery().userIdIn("admin").list(); + assertEquals(2, returnValues.size()); - TimeInterval timeInterval = new TimeInterval(Instant.now().minusSeconds(10), Instant.now()); - returnValues = historyService.createHistoryQuery().createdWithin(timeInterval).list(); - assertEquals(2, returnValues.size()); + returnValues = historyService.createHistoryQuery().domainIn("DOMAIN_A").list(); + assertEquals(2, returnValues.size()); - returnValues = historyService.createHistoryQuery().userIdIn("admin").list(); - assertEquals(2, returnValues.size()); - - returnValues = historyService.createHistoryQuery().domainIn("DOMAIN_A").list(); - assertEquals(2, returnValues.size()); - - returnValues = historyService.createHistoryQuery() + returnValues = + historyService + .createHistoryQuery() .workbasketKeyIn("WBI:100000000000000000000000000000000001") .list(); - assertEquals(2, returnValues.size()); + assertEquals(2, returnValues.size()); - returnValues = historyService.createHistoryQuery().porCompanyIn("00").list(); - assertEquals(2, returnValues.size()); + returnValues = historyService.createHistoryQuery().porCompanyIn("00").list(); + assertEquals(2, returnValues.size()); - returnValues = historyService.createHistoryQuery().porSystemIn("PASystem").list(); - assertEquals(2, returnValues.size()); + returnValues = historyService.createHistoryQuery().porSystemIn("PASystem").list(); + assertEquals(2, returnValues.size()); - returnValues = historyService.createHistoryQuery().porInstanceIn("22").list(); - assertEquals(1, returnValues.size()); + returnValues = historyService.createHistoryQuery().porInstanceIn("22").list(); + assertEquals(1, returnValues.size()); - returnValues = historyService.createHistoryQuery().porTypeIn("VN").list(); - assertEquals(0, returnValues.size()); + returnValues = historyService.createHistoryQuery().porTypeIn("VN").list(); + assertEquals(0, returnValues.size()); - returnValues = historyService.createHistoryQuery().porValueIn("11223344").list(); - assertEquals(2, returnValues.size()); + returnValues = historyService.createHistoryQuery().porValueIn("11223344").list(); + assertEquals(2, returnValues.size()); - returnValues = historyService.createHistoryQuery().taskClassificationKeyIn("L140101").list(); - assertEquals(2, returnValues.size()); + returnValues = historyService.createHistoryQuery().taskClassificationKeyIn("L140101").list(); + assertEquals(2, returnValues.size()); - returnValues = historyService.createHistoryQuery().taskClassificationCategoryIn("TASK").list(); - assertEquals(2, returnValues.size()); + returnValues = historyService.createHistoryQuery().taskClassificationCategoryIn("TASK").list(); + assertEquals(2, returnValues.size()); - returnValues = historyService.createHistoryQuery().attachmentClassificationKeyIn("DOCTYPE_DEFAULT").list(); - assertEquals(1, returnValues.size()); + returnValues = + historyService.createHistoryQuery().attachmentClassificationKeyIn("DOCTYPE_DEFAULT").list(); + assertEquals(1, returnValues.size()); - returnValues = historyService.createHistoryQuery().custom1In("custom1").list(); - assertEquals(3, returnValues.size()); + returnValues = historyService.createHistoryQuery().custom1In("custom1").list(); + assertEquals(3, returnValues.size()); - returnValues = historyService.createHistoryQuery().custom2In("custom2").list(); - assertEquals(1, returnValues.size()); + returnValues = historyService.createHistoryQuery().custom2In("custom2").list(); + assertEquals(1, returnValues.size()); - returnValues = historyService.createHistoryQuery().custom3In("custom3").list(); - assertEquals(2, returnValues.size()); + returnValues = historyService.createHistoryQuery().custom3In("custom3").list(); + assertEquals(2, returnValues.size()); - returnValues = historyService.createHistoryQuery().custom4In("custom4").list(); - assertEquals(1, returnValues.size()); + returnValues = historyService.createHistoryQuery().custom4In("custom4").list(); + assertEquals(1, returnValues.size()); - returnValues = historyService.createHistoryQuery().commentIn("created a bug").list(); - assertEquals(1, returnValues.size()); + returnValues = historyService.createHistoryQuery().commentIn("created a bug").list(); + assertEquals(1, returnValues.size()); - returnValues = historyService.createHistoryQuery().oldValueIn("old_val").list(); - assertEquals(1, returnValues.size()); + returnValues = historyService.createHistoryQuery().oldValueIn("old_val").list(); + assertEquals(1, returnValues.size()); - returnValues = historyService.createHistoryQuery().newValueIn("new_val").list(); - assertEquals(1, returnValues.size()); + returnValues = historyService.createHistoryQuery().newValueIn("new_val").list(); + assertEquals(1, returnValues.size()); - returnValues = historyService.createHistoryQuery().oldDataIn("123").list(); - assertEquals(2, returnValues.size()); + returnValues = historyService.createHistoryQuery().oldDataIn("123").list(); + assertEquals(2, returnValues.size()); - returnValues = historyService.createHistoryQuery().newDataIn("456").list(); - assertEquals(3, returnValues.size()); - returnValues = historyService.createHistoryQuery().oldValueLike("old%").list(); - assertEquals(1, returnValues.size()); + returnValues = historyService.createHistoryQuery().newDataIn("456").list(); + assertEquals(3, returnValues.size()); + returnValues = historyService.createHistoryQuery().oldValueLike("old%").list(); + assertEquals(1, returnValues.size()); - returnValues = historyService.createHistoryQuery().newValueLike("new_%").list(); - assertEquals(2, returnValues.size()); + returnValues = historyService.createHistoryQuery().newValueLike("new_%").list(); + assertEquals(2, returnValues.size()); - returnValues = historyService.createHistoryQuery().oldDataLike("%23%").list(); - assertEquals(3, returnValues.size()); + returnValues = historyService.createHistoryQuery().oldDataLike("%23%").list(); + assertEquals(3, returnValues.size()); - returnValues = historyService.createHistoryQuery().newDataLike("456%").list(); - assertEquals(3, returnValues.size()); + returnValues = historyService.createHistoryQuery().newDataLike("456%").list(); + assertEquals(3, returnValues.size()); + } - } + @Test + public void testSomeLikeMethods() { + List returnValues = + historyService.createHistoryQuery().businessProcessIdLike("BPI:0%").list(); + assertEquals(3, returnValues.size()); - @Test - public void testSomeLikeMethods() { - List returnValues = historyService.createHistoryQuery() - .businessProcessIdLike("BPI:0%") - .list(); - assertEquals(3, returnValues.size()); + returnValues = + historyService.createHistoryQuery().parentBusinessProcessIdLike("BPI:01", " %").list(); + assertEquals(1, returnValues.size()); - returnValues = historyService.createHistoryQuery().parentBusinessProcessIdLike("BPI:01", " %").list(); - assertEquals(1, returnValues.size()); + returnValues = historyService.createHistoryQuery().taskIdLike("TKI:000000000000000%").list(); + assertEquals(3, returnValues.size()); - returnValues = historyService.createHistoryQuery().taskIdLike("TKI:000000000000000%").list(); - assertEquals(3, returnValues.size()); + returnValues = historyService.createHistoryQuery().oldValueLike("old%").list(); + assertEquals(1, returnValues.size()); - returnValues = historyService.createHistoryQuery().oldValueLike("old%").list(); - assertEquals(1, returnValues.size()); + returnValues = historyService.createHistoryQuery().newValueLike("new_%").list(); + assertEquals(2, returnValues.size()); - returnValues = historyService.createHistoryQuery().newValueLike("new_%").list(); - assertEquals(2, returnValues.size()); + returnValues = historyService.createHistoryQuery().oldDataLike("%23%").list(); + assertEquals(3, returnValues.size()); - returnValues = historyService.createHistoryQuery().oldDataLike("%23%").list(); - assertEquals(3, returnValues.size()); + returnValues = historyService.createHistoryQuery().newDataLike("456%").list(); + assertEquals(3, returnValues.size()); + } - returnValues = historyService.createHistoryQuery().newDataLike("456%").list(); - assertEquals(3, returnValues.size()); + @Test + public void testListValues() { + List returnedList = + historyService.createHistoryQuery().listValues(HistoryQueryColumnName.ID, null); + assertEquals(3, returnedList.size()); - } + returnedList = + historyService + .createHistoryQuery() + .listValues(HistoryQueryColumnName.BUSINESS_PROCESS_ID, null); + assertEquals(3, returnedList.size()); - @Test - public void testListValues() { - List returnedList = historyService.createHistoryQuery().listValues(HistoryQueryColumnName.ID, null); - assertEquals(3, returnedList.size()); - - returnedList = historyService.createHistoryQuery().listValues(HistoryQueryColumnName.BUSINESS_PROCESS_ID, null); - assertEquals(3, returnedList.size()); - - returnedList = historyService.createHistoryQuery() + returnedList = + historyService + .createHistoryQuery() .listValues(HistoryQueryColumnName.PARENT_BUSINESS_PROCESS_ID, null); - assertEquals(2, returnedList.size()); + assertEquals(2, returnedList.size()); - returnedList = historyService.createHistoryQuery().listValues(HistoryQueryColumnName.TASK_ID, null); - assertEquals(2, returnedList.size()); + returnedList = + historyService.createHistoryQuery().listValues(HistoryQueryColumnName.TASK_ID, null); + assertEquals(2, returnedList.size()); - returnedList = historyService.createHistoryQuery().listValues(HistoryQueryColumnName.EVENT_TYPE, null); - assertEquals(1, returnedList.size()); + returnedList = + historyService.createHistoryQuery().listValues(HistoryQueryColumnName.EVENT_TYPE, null); + assertEquals(1, returnedList.size()); - returnedList = historyService.createHistoryQuery().listValues(HistoryQueryColumnName.CREATED, null); - assertEquals(2, returnedList.size()); + returnedList = + historyService.createHistoryQuery().listValues(HistoryQueryColumnName.CREATED, null); + assertEquals(2, returnedList.size()); - returnedList = historyService.createHistoryQuery().listValues(HistoryQueryColumnName.USER_ID, null); - assertEquals(2, returnedList.size()); + returnedList = + historyService.createHistoryQuery().listValues(HistoryQueryColumnName.USER_ID, null); + assertEquals(2, returnedList.size()); - returnedList = historyService.createHistoryQuery().listValues(HistoryQueryColumnName.DOMAIN, null); - assertEquals(2, returnedList.size()); + returnedList = + historyService.createHistoryQuery().listValues(HistoryQueryColumnName.DOMAIN, null); + assertEquals(2, returnedList.size()); - returnedList = historyService.createHistoryQuery().listValues(HistoryQueryColumnName.WORKBASKET_KEY, null); - assertEquals(2, returnedList.size()); + returnedList = + historyService.createHistoryQuery().listValues(HistoryQueryColumnName.WORKBASKET_KEY, null); + assertEquals(2, returnedList.size()); - returnedList = historyService.createHistoryQuery().listValues(HistoryQueryColumnName.POR_COMPANY, null); - assertEquals(2, returnedList.size()); + returnedList = + historyService.createHistoryQuery().listValues(HistoryQueryColumnName.POR_COMPANY, null); + assertEquals(2, returnedList.size()); - returnedList = historyService.createHistoryQuery().listValues(HistoryQueryColumnName.POR_SYSTEM, null); - assertEquals(2, returnedList.size()); + returnedList = + historyService.createHistoryQuery().listValues(HistoryQueryColumnName.POR_SYSTEM, null); + assertEquals(2, returnedList.size()); - returnedList = historyService.createHistoryQuery().listValues(HistoryQueryColumnName.POR_INSTANCE, null); - assertEquals(2, returnedList.size()); + returnedList = + historyService.createHistoryQuery().listValues(HistoryQueryColumnName.POR_INSTANCE, null); + assertEquals(2, returnedList.size()); - returnedList = historyService.createHistoryQuery().listValues(HistoryQueryColumnName.POR_TYPE, null); - assertEquals(2, returnedList.size()); + returnedList = + historyService.createHistoryQuery().listValues(HistoryQueryColumnName.POR_TYPE, null); + assertEquals(2, returnedList.size()); - returnedList = historyService.createHistoryQuery().listValues(HistoryQueryColumnName.POR_VALUE, null); - assertEquals(2, returnedList.size()); + returnedList = + historyService.createHistoryQuery().listValues(HistoryQueryColumnName.POR_VALUE, null); + assertEquals(2, returnedList.size()); - returnedList = historyService.createHistoryQuery() + returnedList = + historyService + .createHistoryQuery() .listValues(HistoryQueryColumnName.TASK_CLASSIFICATION_KEY, null); - assertEquals(2, returnedList.size()); + assertEquals(2, returnedList.size()); - returnedList = historyService.createHistoryQuery() + returnedList = + historyService + .createHistoryQuery() .listValues(HistoryQueryColumnName.TASK_CLASSIFICATION_CATEGORY, null); - assertEquals(2, returnedList.size()); + assertEquals(2, returnedList.size()); - returnedList = historyService.createHistoryQuery() + returnedList = + historyService + .createHistoryQuery() .listValues(HistoryQueryColumnName.ATTACHMENT_CLASSIFICATION_KEY, null); - assertEquals(2, returnedList.size()); + assertEquals(2, returnedList.size()); - returnedList = historyService.createHistoryQuery().listValues(HistoryQueryColumnName.COMMENT, null); - assertEquals(3, returnedList.size()); + returnedList = + historyService.createHistoryQuery().listValues(HistoryQueryColumnName.COMMENT, null); + assertEquals(3, returnedList.size()); - returnedList = historyService.createHistoryQuery().listValues(HistoryQueryColumnName.OLD_VALUE, null); - assertEquals(3, returnedList.size()); + returnedList = + historyService.createHistoryQuery().listValues(HistoryQueryColumnName.OLD_VALUE, null); + assertEquals(3, returnedList.size()); - returnedList = historyService.createHistoryQuery().listValues(HistoryQueryColumnName.NEW_VALUE, null); - assertEquals(3, returnedList.size()); + returnedList = + historyService.createHistoryQuery().listValues(HistoryQueryColumnName.NEW_VALUE, null); + assertEquals(3, returnedList.size()); - returnedList = historyService.createHistoryQuery().listValues(HistoryQueryColumnName.CUSTOM_1, null); - assertEquals(1, returnedList.size()); + returnedList = + historyService.createHistoryQuery().listValues(HistoryQueryColumnName.CUSTOM_1, null); + assertEquals(1, returnedList.size()); - returnedList = historyService.createHistoryQuery().listValues(HistoryQueryColumnName.CUSTOM_2, null); - assertEquals(2, returnedList.size()); + returnedList = + historyService.createHistoryQuery().listValues(HistoryQueryColumnName.CUSTOM_2, null); + assertEquals(2, returnedList.size()); - returnedList = historyService.createHistoryQuery().listValues(HistoryQueryColumnName.CUSTOM_3, null); - assertEquals(2, returnedList.size()); + returnedList = + historyService.createHistoryQuery().listValues(HistoryQueryColumnName.CUSTOM_3, null); + assertEquals(2, returnedList.size()); - returnedList = historyService.createHistoryQuery().listValues(HistoryQueryColumnName.CUSTOM_4, null); - assertEquals(2, returnedList.size()); + returnedList = + historyService.createHistoryQuery().listValues(HistoryQueryColumnName.CUSTOM_4, null); + assertEquals(2, returnedList.size()); - returnedList = historyService.createHistoryQuery().listValues(HistoryQueryColumnName.OLD_DATA, null); - assertEquals(2, returnedList.size()); - - returnedList = historyService.createHistoryQuery().listValues(HistoryQueryColumnName.NEW_DATA, null); - assertEquals(1, returnedList.size()); - } + returnedList = + historyService.createHistoryQuery().listValues(HistoryQueryColumnName.OLD_DATA, null); + assertEquals(2, returnedList.size()); + returnedList = + historyService.createHistoryQuery().listValues(HistoryQueryColumnName.NEW_DATA, null); + assertEquals(1, returnedList.size()); + } } diff --git a/history/taskana-simplehistory-provider/src/test/java/configuration/DBWriter.java b/history/taskana-simplehistory-provider/src/test/java/configuration/DBWriter.java index 973d03a35..386a9071d 100644 --- a/history/taskana-simplehistory-provider/src/test/java/configuration/DBWriter.java +++ b/history/taskana-simplehistory-provider/src/test/java/configuration/DBWriter.java @@ -6,75 +6,69 @@ import java.io.StringReader; import java.io.StringWriter; import java.sql.Connection; import java.sql.SQLException; - import javax.sql.DataSource; - import org.apache.ibatis.jdbc.ScriptRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * Set up the database's writer and generates data for tests. - */ +/** Set up the database's writer and generates data for tests. */ public class DBWriter { - private static final Logger LOGGER = LoggerFactory.getLogger(DBWriter.class); - private static final String INSERTVALUES = "/sql/history-events.sql"; - private StringWriter outWriter = new StringWriter(); - private PrintWriter logWriter; - private StringWriter errorWriter; - private PrintWriter errorLogWriter; + private static final Logger LOGGER = LoggerFactory.getLogger(DBWriter.class); + private static final String INSERTVALUES = "/sql/history-events.sql"; + private StringWriter outWriter = new StringWriter(); + private PrintWriter logWriter; + private StringWriter errorWriter; + private PrintWriter errorLogWriter; - public DBWriter() { - this.logWriter = new PrintWriter(this.outWriter); - this.errorWriter = new StringWriter(); - this.errorLogWriter = new PrintWriter(this.errorWriter); - } + public DBWriter() { + this.logWriter = new PrintWriter(this.outWriter); + this.errorWriter = new StringWriter(); + this.errorLogWriter = new PrintWriter(this.errorWriter); + } - public void generateTestData(DataSource dataSource) throws SQLException { - ScriptRunner runner = null; - try { - runner = configScriptRunner(dataSource); - runner.runScript( - new InputStreamReader( - this.getClass().getResourceAsStream(INSERTVALUES))); - } finally { - if (runner != null) { - runner.closeConnection(); - } - LOGGER.debug(outWriter.toString()); - if (!errorWriter.toString().trim().isEmpty()) { - LOGGER.error(errorWriter.toString()); - } - } + public void generateTestData(DataSource dataSource) throws SQLException { + ScriptRunner runner = null; + try { + runner = configScriptRunner(dataSource); + runner.runScript(new InputStreamReader(this.getClass().getResourceAsStream(INSERTVALUES))); + } finally { + if (runner != null) { + runner.closeConnection(); + } + LOGGER.debug(outWriter.toString()); + if (!errorWriter.toString().trim().isEmpty()) { + LOGGER.error(errorWriter.toString()); + } } + } - public void clearDB(DataSource dataSource) throws SQLException { - ScriptRunner runner = null; - try { - runner = configScriptRunner(dataSource); - runner.runScript(new StringReader("DELETE FROM HISTORY_EVENTS;")); - } finally { - if (runner != null) { - runner.closeConnection(); - } - LOGGER.debug(outWriter.toString()); - if (!errorWriter.toString().trim().isEmpty()) { - LOGGER.error(errorWriter.toString()); - } - } + public void clearDB(DataSource dataSource) throws SQLException { + ScriptRunner runner = null; + try { + runner = configScriptRunner(dataSource); + runner.runScript(new StringReader("DELETE FROM HISTORY_EVENTS;")); + } finally { + if (runner != null) { + runner.closeConnection(); + } + LOGGER.debug(outWriter.toString()); + if (!errorWriter.toString().trim().isEmpty()) { + LOGGER.error(errorWriter.toString()); + } } + } - private ScriptRunner configScriptRunner(DataSource dataSource) throws SQLException { - Connection connection = dataSource.getConnection(); - LOGGER.debug(connection.getMetaData().toString()); - ScriptRunner runner = new ScriptRunner(connection); - runner.setStopOnError(true); - runner.setLogWriter(this.logWriter); - runner.setErrorLogWriter(this.errorLogWriter); - runner.setStopOnError(true); - runner.setLogWriter(this.logWriter); - runner.setErrorLogWriter(this.errorLogWriter); - return runner; - } + private ScriptRunner configScriptRunner(DataSource dataSource) throws SQLException { + Connection connection = dataSource.getConnection(); + LOGGER.debug(connection.getMetaData().toString()); + ScriptRunner runner = new ScriptRunner(connection); + runner.setStopOnError(true); + runner.setLogWriter(this.logWriter); + runner.setErrorLogWriter(this.errorLogWriter); + runner.setStopOnError(true); + runner.setLogWriter(this.logWriter); + runner.setErrorLogWriter(this.errorLogWriter); + return runner; + } } diff --git a/history/taskana-simplehistory-provider/src/test/java/configuration/TaskanaEngineConfigurationTest.java b/history/taskana-simplehistory-provider/src/test/java/configuration/TaskanaEngineConfigurationTest.java index 03092fe9a..97c9f76ac 100644 --- a/history/taskana-simplehistory-provider/src/test/java/configuration/TaskanaEngineConfigurationTest.java +++ b/history/taskana-simplehistory-provider/src/test/java/configuration/TaskanaEngineConfigurationTest.java @@ -2,14 +2,12 @@ package configuration; import static org.junit.Assert.assertEquals; +import acceptance.AbstractAccTest; import java.sql.SQLException; - import javax.sql.DataSource; - import org.junit.Assert; import org.junit.Test; -import acceptance.AbstractAccTest; import pro.taskana.TaskanaEngine; import pro.taskana.configuration.TaskanaEngineConfiguration; @@ -20,27 +18,25 @@ import pro.taskana.configuration.TaskanaEngineConfiguration; */ public class TaskanaEngineConfigurationTest extends AbstractAccTest { - @Test - public void testCreateTaskanaEngine() throws SQLException { - DataSource ds = getDataSource(); - TaskanaEngineConfiguration taskEngineConfiguration = new TaskanaEngineConfiguration(ds, false, - getSchemaName()); + @Test + public void testCreateTaskanaEngine() throws SQLException { + DataSource ds = getDataSource(); + TaskanaEngineConfiguration taskEngineConfiguration = + new TaskanaEngineConfiguration(ds, false, getSchemaName()); - TaskanaEngine te = taskEngineConfiguration.buildTaskanaEngine(); + TaskanaEngine te = taskEngineConfiguration.buildTaskanaEngine(); - Assert.assertNotNull(te); - } - - @Test - public void testCreateTaskanaHistoryEventWithNonDefaultSchemaName() throws SQLException { - resetDb("SOMECUSTOMSCHEMANAME"); - long count = historyService.createHistoryQuery().workbasketKeyIn("wbKey1").count(); - assertEquals(0, count); - historyService.create( - AbstractAccTest.createHistoryEvent("wbKey1", "taskId1", "type1", "Some comment", "wbKey2")); - count = historyService.createHistoryQuery().workbasketKeyIn("wbKey1").count(); - assertEquals(1, count); - - } + Assert.assertNotNull(te); + } + @Test + public void testCreateTaskanaHistoryEventWithNonDefaultSchemaName() throws SQLException { + resetDb("SOMECUSTOMSCHEMANAME"); + long count = historyService.createHistoryQuery().workbasketKeyIn("wbKey1").count(); + assertEquals(0, count); + historyService.create( + AbstractAccTest.createHistoryEvent("wbKey1", "taskId1", "type1", "Some comment", "wbKey2")); + count = historyService.createHistoryQuery().workbasketKeyIn("wbKey1").count(); + assertEquals(1, count); + } } diff --git a/history/taskana-simplehistory-provider/src/test/java/pro/taskana/simplehistory/impl/HistoryQueryImplTest.java b/history/taskana-simplehistory-provider/src/test/java/pro/taskana/simplehistory/impl/HistoryQueryImplTest.java index c4ea15c1c..39ef5b5e5 100644 --- a/history/taskana-simplehistory-provider/src/test/java/pro/taskana/simplehistory/impl/HistoryQueryImplTest.java +++ b/history/taskana-simplehistory-provider/src/test/java/pro/taskana/simplehistory/impl/HistoryQueryImplTest.java @@ -9,7 +9,6 @@ import java.sql.SQLException; import java.time.Instant; import java.util.ArrayList; import java.util.List; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -27,50 +26,55 @@ import pro.taskana.simplehistory.impl.mappings.HistoryQueryMapper; @RunWith(MockitoJUnitRunner.class) public class HistoryQueryImplTest { - private HistoryQueryImpl historyQueryImpl; + private HistoryQueryImpl historyQueryImpl; - @Mock - private TaskanaHistoryEngineImpl taskanaHistoryEngineMock; + @Mock private TaskanaHistoryEngineImpl taskanaHistoryEngineMock; - @Mock - private HistoryQueryMapper historyQueryMock; + @Mock private HistoryQueryMapper historyQueryMock; - @Before - public void setup() { - historyQueryImpl = new HistoryQueryImpl(taskanaHistoryEngineMock, historyQueryMock); - } + @Before + public void setup() { + historyQueryImpl = new HistoryQueryImpl(taskanaHistoryEngineMock, historyQueryMock); + } - @Test - public void testShouldReturnList() throws SQLException { - List returnList = new ArrayList<>(); - returnList.add(createHistoryEvent("abcd", "T22", "car", "BV", "this was important", null)); - TimeInterval interval = new TimeInterval(Instant.now().minusNanos(1000), Instant.now()); + @Test + public void testShouldReturnList() throws SQLException { + List returnList = new ArrayList<>(); + returnList.add(createHistoryEvent("abcd", "T22", "car", "BV", "this was important", null)); + TimeInterval interval = new TimeInterval(Instant.now().minusNanos(1000), Instant.now()); - doNothing().when(taskanaHistoryEngineMock).openConnection(); - doNothing().when(taskanaHistoryEngineMock).returnConnection(); - doReturn(returnList).when(historyQueryMock).queryHistoryEvent(historyQueryImpl); + doNothing().when(taskanaHistoryEngineMock).openConnection(); + doNothing().when(taskanaHistoryEngineMock).returnConnection(); + doReturn(returnList).when(historyQueryMock).queryHistoryEvent(historyQueryImpl); - List result = historyQueryImpl + List result = + historyQueryImpl .taskIdIn("TKI:01") - .workbasketKeyIn("T22", "some_long_long, long loooooooooooooooooooooooooooooooooooong String.") + .workbasketKeyIn( + "T22", "some_long_long, long loooooooooooooooooooooooooooooooooooong String.") .userIdIn("BV") .commentLike("%as important") .createdWithin(interval) .list(); - validateMockitoUsage(); - assertArrayEquals(returnList.toArray(), result.toArray()); - } + validateMockitoUsage(); + assertArrayEquals(returnList.toArray(), result.toArray()); + } - private HistoryEventImpl createHistoryEvent(String taskId, String workbasketKey, String type, String userId, - String comment, Instant created) { - HistoryEventImpl he = new HistoryEventImpl(); - he.setTaskId(taskId); - he.setWorkbasketKey(workbasketKey); - he.setEventType(type); - he.setUserId(userId); - he.setComment(comment); - he.setCreated(created); - return he; - } + private HistoryEventImpl createHistoryEvent( + String taskId, + String workbasketKey, + String type, + String userId, + String comment, + Instant created) { + HistoryEventImpl he = new HistoryEventImpl(); + he.setTaskId(taskId); + he.setWorkbasketKey(workbasketKey); + he.setEventType(type); + he.setUserId(userId); + he.setComment(comment); + he.setCreated(created); + return he; + } } diff --git a/history/taskana-simplehistory-provider/src/test/java/pro/taskana/simplehistory/impl/SimpleHistoryServiceImplTest.java b/history/taskana-simplehistory-provider/src/test/java/pro/taskana/simplehistory/impl/SimpleHistoryServiceImplTest.java index 6a9239cea..dca3cc1ce 100644 --- a/history/taskana-simplehistory-provider/src/test/java/pro/taskana/simplehistory/impl/SimpleHistoryServiceImplTest.java +++ b/history/taskana-simplehistory-provider/src/test/java/pro/taskana/simplehistory/impl/SimpleHistoryServiceImplTest.java @@ -8,10 +8,10 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import acceptance.AbstractAccTest; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; - import org.apache.ibatis.session.SqlSessionManager; import org.junit.Before; import org.junit.Test; @@ -25,7 +25,6 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import acceptance.AbstractAccTest; import pro.taskana.configuration.TaskanaEngineConfiguration; import pro.taskana.simplehistory.impl.mappings.HistoryEventMapper; import pro.taskana.simplehistory.impl.mappings.HistoryQueryMapper; @@ -40,83 +39,86 @@ import pro.taskana.simplehistory.impl.mappings.HistoryQueryMapper; @PowerMockIgnore("javax.management.*") public class SimpleHistoryServiceImplTest { - @InjectMocks - private SimpleHistoryServiceImpl cutSpy; + @InjectMocks private SimpleHistoryServiceImpl cutSpy; - @Mock - private HistoryEventMapper historyEventMapperMock; + @Mock private HistoryEventMapper historyEventMapperMock; - @Mock - private HistoryQueryMapper historyQueryMapperMock; + @Mock private HistoryQueryMapper historyQueryMapperMock; - @Mock - private TaskanaHistoryEngineImpl taskanaHistoryEngineMock; + @Mock private TaskanaHistoryEngineImpl taskanaHistoryEngineMock; - @Mock - private TaskanaEngineConfiguration taskanaEngineConfiguration; + @Mock private TaskanaEngineConfiguration taskanaEngineConfiguration; - @Mock - private SqlSessionManager sqlSessionManagerMock; + @Mock private SqlSessionManager sqlSessionManagerMock; - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - } + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } - @Test - public void testInitializeSimpleHistoryService() throws SQLException { - doReturn(historyEventMapperMock).when(sqlSessionManagerMock).getMapper(HistoryEventMapper.class); - doReturn(historyQueryMapperMock).when(sqlSessionManagerMock).getMapper(HistoryQueryMapper.class); - doReturn(sqlSessionManagerMock).when(taskanaHistoryEngineMock).getSqlSession(); - PowerMockito.mockStatic(TaskanaHistoryEngineImpl.class); - Mockito.when(TaskanaHistoryEngineImpl.createTaskanaEngine(taskanaEngineConfiguration)) - .thenReturn(taskanaHistoryEngineMock); - cutSpy.initialize(taskanaEngineConfiguration); + @Test + public void testInitializeSimpleHistoryService() throws SQLException { + doReturn(historyEventMapperMock) + .when(sqlSessionManagerMock) + .getMapper(HistoryEventMapper.class); + doReturn(historyQueryMapperMock) + .when(sqlSessionManagerMock) + .getMapper(HistoryQueryMapper.class); + doReturn(sqlSessionManagerMock).when(taskanaHistoryEngineMock).getSqlSession(); + PowerMockito.mockStatic(TaskanaHistoryEngineImpl.class); + Mockito.when(TaskanaHistoryEngineImpl.createTaskanaEngine(taskanaEngineConfiguration)) + .thenReturn(taskanaHistoryEngineMock); + cutSpy.initialize(taskanaEngineConfiguration); - verify(sqlSessionManagerMock, times(2)).getMapper(any()); - verify(taskanaHistoryEngineMock, times(2)).getSqlSession(); - } + verify(sqlSessionManagerMock, times(2)).getMapper(any()); + verify(taskanaHistoryEngineMock, times(2)).getSqlSession(); + } - @Test - public void testInitializeSimpleHistoryServiceWithNonDefaultSchemaName() throws SQLException { + @Test + public void testInitializeSimpleHistoryServiceWithNonDefaultSchemaName() throws SQLException { - doReturn(historyEventMapperMock).when(sqlSessionManagerMock).getMapper(HistoryEventMapper.class); - doReturn(historyQueryMapperMock).when(sqlSessionManagerMock).getMapper(HistoryQueryMapper.class); - doReturn(sqlSessionManagerMock).when(taskanaHistoryEngineMock).getSqlSession(); - PowerMockito.mockStatic(TaskanaHistoryEngineImpl.class); - Mockito.when(TaskanaHistoryEngineImpl.createTaskanaEngine(taskanaEngineConfiguration)) - .thenReturn(taskanaHistoryEngineMock); - cutSpy.initialize(taskanaEngineConfiguration); + doReturn(historyEventMapperMock) + .when(sqlSessionManagerMock) + .getMapper(HistoryEventMapper.class); + doReturn(historyQueryMapperMock) + .when(sqlSessionManagerMock) + .getMapper(HistoryQueryMapper.class); + doReturn(sqlSessionManagerMock).when(taskanaHistoryEngineMock).getSqlSession(); + PowerMockito.mockStatic(TaskanaHistoryEngineImpl.class); + Mockito.when(TaskanaHistoryEngineImpl.createTaskanaEngine(taskanaEngineConfiguration)) + .thenReturn(taskanaHistoryEngineMock); + cutSpy.initialize(taskanaEngineConfiguration); - verify(sqlSessionManagerMock, times(2)).getMapper(any()); - verify(taskanaHistoryEngineMock, times(2)).getSqlSession(); - } + verify(sqlSessionManagerMock, times(2)).getMapper(any()); + verify(taskanaHistoryEngineMock, times(2)).getSqlSession(); + } - @Test - public void testCreateEvent() throws SQLException { - HistoryEventImpl expectedWb = AbstractAccTest.createHistoryEvent("wbKey1", "taskId1", "type1", "Some comment", - "wbKey2"); - doNothing().when(historyEventMapperMock).insert(expectedWb); + @Test + public void testCreateEvent() throws SQLException { + HistoryEventImpl expectedWb = + AbstractAccTest.createHistoryEvent("wbKey1", "taskId1", "type1", "Some comment", "wbKey2"); + doNothing().when(historyEventMapperMock).insert(expectedWb); - cutSpy.create(expectedWb); - verify(taskanaHistoryEngineMock, times(1)).openConnection(); - verify(historyEventMapperMock, times(1)).insert(expectedWb); - verify(taskanaHistoryEngineMock, times(1)).returnConnection(); - assertNotNull(expectedWb.getCreated()); - } + cutSpy.create(expectedWb); + verify(taskanaHistoryEngineMock, times(1)).openConnection(); + verify(historyEventMapperMock, times(1)).insert(expectedWb); + verify(taskanaHistoryEngineMock, times(1)).returnConnection(); + assertNotNull(expectedWb.getCreated()); + } - @Test - public void testQueryEvent() throws SQLException { - List returnList = new ArrayList<>(); - returnList.add(AbstractAccTest.createHistoryEvent("wbKey1", "taskId1", "type1", "Some comment", "wbKey2")); - doReturn(returnList).when(historyQueryMapperMock).queryHistoryEvent(any()); + @Test + public void testQueryEvent() throws SQLException { + List returnList = new ArrayList<>(); + returnList.add( + AbstractAccTest.createHistoryEvent("wbKey1", "taskId1", "type1", "Some comment", "wbKey2")); + doReturn(returnList).when(historyQueryMapperMock).queryHistoryEvent(any()); - List result = cutSpy.createHistoryQuery().taskIdIn("taskId1").list(); + List result = cutSpy.createHistoryQuery().taskIdIn("taskId1").list(); - verify(taskanaHistoryEngineMock, times(1)).openConnection(); - verify(historyQueryMapperMock, times(1)).queryHistoryEvent(any()); - verify(taskanaHistoryEngineMock, times(1)).returnConnection(); - assertEquals(returnList.size(), result.size()); - assertEquals(returnList.get(0).getWorkbasketKey(), result.get(0).getWorkbasketKey()); - } + verify(taskanaHistoryEngineMock, times(1)).openConnection(); + verify(historyQueryMapperMock, times(1)).queryHistoryEvent(any()); + verify(taskanaHistoryEngineMock, times(1)).returnConnection(); + assertEquals(returnList.size(), result.size()); + assertEquals(returnList.get(0).getWorkbasketKey(), result.get(0).getWorkbasketKey()); + } } diff --git a/history/taskana-simplehistory-rest-spring-example/src/main/java/rest/pro/taskana/rest/simplehistory/ExampleRestApplication.java b/history/taskana-simplehistory-rest-spring-example/src/main/java/rest/pro/taskana/rest/simplehistory/ExampleRestApplication.java index 6108cc104..7af922c97 100644 --- a/history/taskana-simplehistory-rest-spring-example/src/main/java/rest/pro/taskana/rest/simplehistory/ExampleRestApplication.java +++ b/history/taskana-simplehistory-rest-spring-example/src/main/java/rest/pro/taskana/rest/simplehistory/ExampleRestApplication.java @@ -1,9 +1,7 @@ package rest.pro.taskana.rest.simplehistory; import java.sql.SQLException; - import javax.sql.DataSource; - import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -20,47 +18,47 @@ import org.springframework.transaction.PlatformTransactionManager; import pro.taskana.rest.simplehistory.TaskHistoryRestConfiguration; import pro.taskana.rest.simplehistory.sampledata.SampleDataGenerator; -/** - * Example Application showing the implementation of taskana-rest-spring. - */ +/** Example Application showing the implementation of taskana-rest-spring. */ @SpringBootApplication @ComponentScan(basePackages = "pro.taskana.rest.simplehistory") @Import({TaskHistoryRestConfiguration.class, WebMvcConfig.class}) public class ExampleRestApplication { - @Value("${taskana.schemaName:TASKANA}") - public String schemaName; + @Value("${taskana.schemaName:TASKANA}") + public String schemaName; - private SampleDataGenerator sampleDataGenerator; + private SampleDataGenerator sampleDataGenerator; - public static void main(String[] args) { - SpringApplication.run(ExampleRestApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(ExampleRestApplication.class, args); + } - @Bean - @Primary - @ConfigurationProperties(prefix = "datasource") - public DataSourceProperties dataSourceProperties() { - DataSourceProperties props = new DataSourceProperties(); - props.setUrl("jdbc:h2:mem:taskana;IGNORECASE=TRUE;LOCK_MODE=0;INIT=CREATE SCHEMA IF NOT EXISTS " + schemaName); - return props; - } + @Bean + @Primary + @ConfigurationProperties(prefix = "datasource") + public DataSourceProperties dataSourceProperties() { + DataSourceProperties props = new DataSourceProperties(); + props.setUrl( + "jdbc:h2:mem:taskana;IGNORECASE=TRUE;LOCK_MODE=0;INIT=CREATE SCHEMA IF NOT EXISTS " + + schemaName); + return props; + } - @Bean - public DataSource dataSource(DataSourceProperties properties) { - return properties.initializeDataSourceBuilder().build(); - } + @Bean + public DataSource dataSource(DataSourceProperties properties) { + return properties.initializeDataSourceBuilder().build(); + } - @Bean - public PlatformTransactionManager txManager(DataSource dataSource) { - return new DataSourceTransactionManager(dataSource); - } + @Bean + public PlatformTransactionManager txManager(DataSource dataSource) { + return new DataSourceTransactionManager(dataSource); + } - @Bean - @DependsOn("getTaskanaEngine") // generate sample data after schema was inserted - public SampleDataGenerator generateSampleData(DataSource dataSource) throws SQLException { - sampleDataGenerator = new SampleDataGenerator(dataSource); - sampleDataGenerator.generateSampleData(schemaName); - return sampleDataGenerator; - } + @Bean + @DependsOn("getTaskanaEngine") // generate sample data after schema was inserted + public SampleDataGenerator generateSampleData(DataSource dataSource) throws SQLException { + sampleDataGenerator = new SampleDataGenerator(dataSource); + sampleDataGenerator.generateSampleData(schemaName); + return sampleDataGenerator; + } } diff --git a/history/taskana-simplehistory-rest-spring-example/src/main/java/rest/pro/taskana/rest/simplehistory/WebMvcConfig.java b/history/taskana-simplehistory-rest-spring-example/src/main/java/rest/pro/taskana/rest/simplehistory/WebMvcConfig.java index 6b50c06f7..7c7a0198b 100644 --- a/history/taskana-simplehistory-rest-spring-example/src/main/java/rest/pro/taskana/rest/simplehistory/WebMvcConfig.java +++ b/history/taskana-simplehistory-rest-spring-example/src/main/java/rest/pro/taskana/rest/simplehistory/WebMvcConfig.java @@ -1,9 +1,9 @@ package rest.pro.taskana.rest.simplehistory; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import java.util.List; - import javax.annotation.PostConstruct; - import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; @@ -11,50 +11,47 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; - -/** - * The Web MVC Configuration. - */ +/** The Web MVC Configuration. */ @Configuration @EnableWebMvc public class WebMvcConfig implements WebMvcConfigurer { - private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { - "classpath:/META-INF/resources/", "classpath:/resources/", - "classpath:/static/", "classpath:/public/"}; + private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { + "classpath:/META-INF/resources/", "classpath:/resources/", + "classpath:/static/", "classpath:/public/" + }; - private ObjectMapper objectMapper; + private ObjectMapper objectMapper; - WebMvcConfig(ObjectMapper objectMapper) { - this.objectMapper = objectMapper; + WebMvcConfig(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + } + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + if (!registry.hasMappingForPattern("/webjars/**")) { + registry + .addResourceHandler("/webjars/**") + .addResourceLocations("classpath:/META-INF/resources/webjars/"); } - - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - if (!registry.hasMappingForPattern("/webjars/**")) { - registry.addResourceHandler("/webjars/**").addResourceLocations( - "classpath:/META-INF/resources/webjars/"); - } - if (!registry.hasMappingForPattern("/**")) { - registry.addResourceHandler("/**").addResourceLocations( - CLASSPATH_RESOURCE_LOCATIONS); - } + if (!registry.hasMappingForPattern("/**")) { + registry.addResourceHandler("/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS); } + } - @Override - public void extendMessageConverters(List> converters) { - for (HttpMessageConverter converter : converters) { - if (converter instanceof MappingJackson2HttpMessageConverter) { - MappingJackson2HttpMessageConverter jacksonConverter = (MappingJackson2HttpMessageConverter) converter; - jacksonConverter.setPrettyPrint(true); - } - } + @Override + public void extendMessageConverters(List> converters) { + for (HttpMessageConverter converter : converters) { + if (converter instanceof MappingJackson2HttpMessageConverter) { + MappingJackson2HttpMessageConverter jacksonConverter = + (MappingJackson2HttpMessageConverter) converter; + jacksonConverter.setPrettyPrint(true); + } } + } - @PostConstruct - public void enableObjectIndent() { - objectMapper.enable(SerializationFeature.INDENT_OUTPUT); - } + @PostConstruct + public void enableObjectIndent() { + objectMapper.enable(SerializationFeature.INDENT_OUTPUT); + } } diff --git a/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/resource/TaskHistoryEventAssembler.java b/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/resource/TaskHistoryEventAssembler.java index ff9729fff..2e9449e47 100644 --- a/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/resource/TaskHistoryEventAssembler.java +++ b/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/resource/TaskHistoryEventAssembler.java @@ -6,24 +6,23 @@ import org.springframework.hateoas.mvc.ResourceAssemblerSupport; import pro.taskana.history.api.TaskanaHistoryEvent; import pro.taskana.simplehistory.impl.HistoryEventImpl; -/** - * Transforms any {@link HistoryEventImpl} into its {@link TaskHistoryEventResource}. - */ -public class TaskHistoryEventAssembler extends ResourceAssemblerSupport { +/** Transforms any {@link HistoryEventImpl} into its {@link TaskHistoryEventResource}. */ +public class TaskHistoryEventAssembler + extends ResourceAssemblerSupport { - public TaskHistoryEventAssembler() { - super(HistoryEventImpl.class, TaskHistoryEventResource.class); - } + public TaskHistoryEventAssembler() { + super(HistoryEventImpl.class, TaskHistoryEventResource.class); + } - @Override - public TaskHistoryEventResource toResource(TaskanaHistoryEvent historyEvent) { - TaskHistoryEventResource resource = createResourceWithId(historyEvent.getId(), historyEvent); - BeanUtils.copyProperties(historyEvent, resource); - if (historyEvent.getCreated() != null) { - resource.setCreated(historyEvent.getCreated().toString()); - } - resource.setTaskHistoryId(String.valueOf(historyEvent.getId())); - resource.removeLinks(); - return resource; + @Override + public TaskHistoryEventResource toResource(TaskanaHistoryEvent historyEvent) { + TaskHistoryEventResource resource = createResourceWithId(historyEvent.getId(), historyEvent); + BeanUtils.copyProperties(historyEvent, resource); + if (historyEvent.getCreated() != null) { + resource.setCreated(historyEvent.getCreated().toString()); } + resource.setTaskHistoryId(String.valueOf(historyEvent.getId())); + resource.removeLinks(); + return resource; + } } diff --git a/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/resource/TaskHistoryEventListAssembler.java b/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/resource/TaskHistoryEventListAssembler.java index 1ea2965b9..45310db46 100644 --- a/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/resource/TaskHistoryEventListAssembler.java +++ b/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/resource/TaskHistoryEventListAssembler.java @@ -3,48 +3,45 @@ package pro.taskana.rest.resource; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import java.util.List; - import org.springframework.hateoas.Link; import pro.taskana.rest.resource.PagedResources.PageMetadata; import pro.taskana.rest.simplehistory.TaskHistoryEventController; import pro.taskana.simplehistory.impl.HistoryEventImpl; -/** - * Mapper to convert from a list of HistoryEventImpl to a TaskHistoryEventResource. - */ +/** Mapper to convert from a list of HistoryEventImpl to a TaskHistoryEventResource. */ public class TaskHistoryEventListAssembler extends AbstractRessourcesAssembler { - public TaskHistoryEventListAssembler() { + public TaskHistoryEventListAssembler() {} + + public TaskHistoryEventListResource toResources( + List historyEvents, PageMetadata pageMetadata) { + + TaskHistoryEventAssembler assembler = new TaskHistoryEventAssembler(); + List resources = assembler.toResources(historyEvents); + TaskHistoryEventListResource pagedResources = + new TaskHistoryEventListResource(resources, pageMetadata); + + pagedResources.add(new Link(original.toUriString()).withSelfRel()); + if (pageMetadata != null) { + pagedResources.add(linkTo(TaskHistoryEventController.class).withRel("allTaskHistoryEvent")); + pagedResources.add( + new Link(original.replaceQueryParam("page", 1).toUriString()).withRel(Link.REL_FIRST)); + pagedResources.add( + new Link(original.replaceQueryParam("page", pageMetadata.getTotalPages()).toUriString()) + .withRel(Link.REL_LAST)); + if (pageMetadata.getNumber() > 1) { + pagedResources.add( + new Link(original.replaceQueryParam("page", pageMetadata.getNumber() - 1).toUriString()) + .withRel(Link.REL_PREVIOUS)); + } + if (pageMetadata.getNumber() < pageMetadata.getTotalPages()) { + pagedResources.add( + new Link(original.replaceQueryParam("page", pageMetadata.getNumber() + 1).toUriString()) + .withRel(Link.REL_NEXT)); + } } - public TaskHistoryEventListResource toResources(List historyEvents, - PageMetadata pageMetadata) { - - TaskHistoryEventAssembler assembler = new TaskHistoryEventAssembler(); - List resources = assembler.toResources(historyEvents); - TaskHistoryEventListResource pagedResources = new TaskHistoryEventListResource( - resources, - pageMetadata); - - pagedResources.add(new Link(original.toUriString()).withSelfRel()); - if (pageMetadata != null) { - pagedResources.add(linkTo(TaskHistoryEventController.class).withRel("allTaskHistoryEvent")); - pagedResources.add(new Link(original.replaceQueryParam("page", 1).toUriString()).withRel(Link.REL_FIRST)); - pagedResources.add(new Link(original.replaceQueryParam("page", pageMetadata.getTotalPages()).toUriString()) - .withRel(Link.REL_LAST)); - if (pageMetadata.getNumber() > 1) { - pagedResources - .add(new Link(original.replaceQueryParam("page", pageMetadata.getNumber() - 1).toUriString()) - .withRel(Link.REL_PREVIOUS)); - } - if (pageMetadata.getNumber() < pageMetadata.getTotalPages()) { - pagedResources - .add(new Link(original.replaceQueryParam("page", pageMetadata.getNumber() + 1).toUriString()) - .withRel(Link.REL_NEXT)); - } - } - - return pagedResources; - } + return pagedResources; + } } diff --git a/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/resource/TaskHistoryEventListResource.java b/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/resource/TaskHistoryEventListResource.java index 9226c2bf7..db00effbe 100644 --- a/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/resource/TaskHistoryEventListResource.java +++ b/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/resource/TaskHistoryEventListResource.java @@ -1,34 +1,29 @@ package pro.taskana.rest.resource; -import java.util.Collection; - -import org.springframework.hateoas.Link; -import org.springframework.hateoas.PagedResources.PageMetadata; - import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Collection; +import org.springframework.hateoas.Link; -/** - * Resource class for {@link TaskHistoryEventResource} with Pagination. - */ +/** Resource class for {@link TaskHistoryEventResource} with Pagination. */ public class TaskHistoryEventListResource extends PagedResources { - public TaskHistoryEventListResource() { - super(); - } + public TaskHistoryEventListResource() { + super(); + } - public TaskHistoryEventListResource(Collection content, PageMetadata metadata, - Link... links) { - super(content, metadata, links); - } + public TaskHistoryEventListResource( + Collection content, PageMetadata metadata, Link... links) { + super(content, metadata, links); + } - public TaskHistoryEventListResource(Collection content, PageMetadata metadata, - Iterable links) { - super(content, metadata, links); - } + public TaskHistoryEventListResource( + Collection content, PageMetadata metadata, Iterable links) { + super(content, metadata, links); + } - @Override - @JsonProperty("taskHistoryEvents") - public Collection getContent() { - return super.getContent(); - } + @Override + @JsonProperty("taskHistoryEvents") + public Collection getContent() { + return super.getContent(); + } } diff --git a/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/resource/TaskHistoryEventResource.java b/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/resource/TaskHistoryEventResource.java index f10f885ed..1566dc7e3 100644 --- a/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/resource/TaskHistoryEventResource.java +++ b/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/resource/TaskHistoryEventResource.java @@ -1,266 +1,275 @@ package pro.taskana.rest.resource; import javax.validation.constraints.NotNull; - import org.springframework.hateoas.ResourceSupport; -/** - * Resource class for {@link pro.taskana.history.api.TaskanaHistoryEvent}. - */ +/** Resource class for {@link pro.taskana.history.api.TaskanaHistoryEvent}. */ public class TaskHistoryEventResource extends ResourceSupport { - @NotNull - private String taskHistoryEventId; + @NotNull private String taskHistoryEventId; - private String businessProcessId; - private String parentBusinessProcessId; - private String taskId; - private String eventType; - private String created; - private String userId; - private String domain; - private String workbasketKey; - private String porCompany; - private String porType; - private String porSystem; - private String porInstance; - private String porValue; - private String taskClassificationKey; - private String taskClassificationCategory; - private String attachmentClassificationKey; - private String comment; - private String oldValue; - private String newValue; - private String custom1; - private String custom2; - private String custom3; - private String custom4; - private String oldData; - private String newData; + private String businessProcessId; + private String parentBusinessProcessId; + private String taskId; + private String eventType; + private String created; + private String userId; + private String domain; + private String workbasketKey; + private String porCompany; + private String porType; + private String porSystem; + private String porInstance; + private String porValue; + private String taskClassificationKey; + private String taskClassificationCategory; + private String attachmentClassificationKey; + private String comment; + private String oldValue; + private String newValue; + private String custom1; + private String custom2; + private String custom3; + private String custom4; + private String oldData; + private String newData; - public String getTaskHistoryId() { - return taskHistoryEventId; - } + public String getTaskHistoryId() { + return taskHistoryEventId; + } - public void setTaskHistoryId(String taskHistoryId) { - this.taskHistoryEventId = taskHistoryId; - } + public void setTaskHistoryId(String taskHistoryId) { + this.taskHistoryEventId = taskHistoryId; + } - public String getBusinessProcessId() { - return businessProcessId; - } + public String getBusinessProcessId() { + return businessProcessId; + } - public void setBusinessProcessId(String businessProcessId) { - this.businessProcessId = businessProcessId; - } + public void setBusinessProcessId(String businessProcessId) { + this.businessProcessId = businessProcessId; + } - public String getParentBusinessProcessId() { - return parentBusinessProcessId; - } + public String getParentBusinessProcessId() { + return parentBusinessProcessId; + } - public void setParentBusinessProcessId(String parentBusinessProcessId) { - this.parentBusinessProcessId = parentBusinessProcessId; - } + public void setParentBusinessProcessId(String parentBusinessProcessId) { + this.parentBusinessProcessId = parentBusinessProcessId; + } - public String getTaskId() { - return taskId; - } + public String getTaskId() { + return taskId; + } - public void setTaskId(String taskId) { - this.taskId = taskId; - } + public void setTaskId(String taskId) { + this.taskId = taskId; + } - public String getEventType() { - return eventType; - } + public String getEventType() { + return eventType; + } - public void setEventType(String eventType) { - this.eventType = eventType; - } + public void setEventType(String eventType) { + this.eventType = eventType; + } - public String getCreated() { - return created; - } + public String getCreated() { + return created; + } - public void setCreated(String created) { - this.created = created; - } + public void setCreated(String created) { + this.created = created; + } - public String getUserId() { - return userId; - } + public String getUserId() { + return userId; + } - public void setUserId(String userId) { - this.userId = userId; - } + public void setUserId(String userId) { + this.userId = userId; + } - public String getDomain() { - return domain; - } + public String getDomain() { + return domain; + } - public void setDomain(String domain) { - this.domain = domain; - } + public void setDomain(String domain) { + this.domain = domain; + } - public String getWorkbasketKey() { - return workbasketKey; - } + public String getWorkbasketKey() { + return workbasketKey; + } - public void setWorkbasketKey(String workbasketKey) { - this.workbasketKey = workbasketKey; - } + public void setWorkbasketKey(String workbasketKey) { + this.workbasketKey = workbasketKey; + } - public String getPorCompany() { - return porCompany; - } + public String getPorCompany() { + return porCompany; + } - public void setPorCompany(String porCompany) { - this.porCompany = porCompany; - } + public void setPorCompany(String porCompany) { + this.porCompany = porCompany; + } - public String getPorType() { - return porType; - } + public String getPorType() { + return porType; + } - public void setPorType(String porType) { - this.porType = porType; - } + public void setPorType(String porType) { + this.porType = porType; + } - public String getPorSystem() { - return porSystem; - } + public String getPorSystem() { + return porSystem; + } - public void setPorSystem(String porSystem) { - this.porSystem = porSystem; - } + public void setPorSystem(String porSystem) { + this.porSystem = porSystem; + } - public String getPorInstance() { - return porInstance; - } + public String getPorInstance() { + return porInstance; + } - public void setPorInstance(String porInstance) { - this.porInstance = porInstance; - } + public void setPorInstance(String porInstance) { + this.porInstance = porInstance; + } - public String getPorValue() { - return porValue; - } + public String getPorValue() { + return porValue; + } - public void setPorValue(String porValue) { - this.porValue = porValue; - } + public void setPorValue(String porValue) { + this.porValue = porValue; + } - public String getTaskClassificationKey() { - return taskClassificationKey; - } + public String getTaskClassificationKey() { + return taskClassificationKey; + } - public void setTaskClassificationKey(String taskClassificationKey) { - this.taskClassificationKey = taskClassificationKey; - } + public void setTaskClassificationKey(String taskClassificationKey) { + this.taskClassificationKey = taskClassificationKey; + } - public String getTaskClassificationCategory() { - return taskClassificationCategory; - } + public String getTaskClassificationCategory() { + return taskClassificationCategory; + } - public void setTaskClassificationCategory(String taskClassificationCategory) { - this.taskClassificationCategory = taskClassificationCategory; - } + public void setTaskClassificationCategory(String taskClassificationCategory) { + this.taskClassificationCategory = taskClassificationCategory; + } - public String getAttachmentClassificationKey() { - return attachmentClassificationKey; - } + public String getAttachmentClassificationKey() { + return attachmentClassificationKey; + } - public void setAttachmentClassificationKey(String attachmentClassificationKey) { - this.attachmentClassificationKey = attachmentClassificationKey; - } + public void setAttachmentClassificationKey(String attachmentClassificationKey) { + this.attachmentClassificationKey = attachmentClassificationKey; + } - public String getComment() { - return comment; - } + public String getComment() { + return comment; + } - public void setComment(String comment) { - this.comment = comment; - } + public void setComment(String comment) { + this.comment = comment; + } - public String getOldValue() { - return oldValue; - } + public String getOldValue() { + return oldValue; + } - public void setOldValue(String oldValue) { - this.oldValue = oldValue; - } + public void setOldValue(String oldValue) { + this.oldValue = oldValue; + } - public String getNewValue() { - return newValue; - } + public String getNewValue() { + return newValue; + } - public void setNewValue(String newValue) { - this.newValue = newValue; - } + public void setNewValue(String newValue) { + this.newValue = newValue; + } - public String getCustom1() { - return custom1; - } + public String getCustom1() { + return custom1; + } - public void setCustom1(String custom1) { - this.custom1 = custom1; - } + public void setCustom1(String custom1) { + this.custom1 = custom1; + } - public String getCustom2() { - return custom2; - } + public String getCustom2() { + return custom2; + } - public void setCustom2(String custom2) { - this.custom2 = custom2; - } + public void setCustom2(String custom2) { + this.custom2 = custom2; + } - public String getCustom3() { - return custom3; - } + public String getCustom3() { + return custom3; + } - public void setCustom3(String custom3) { - this.custom3 = custom3; - } + public void setCustom3(String custom3) { + this.custom3 = custom3; + } - public String getCustom4() { - return custom4; - } + public String getCustom4() { + return custom4; + } - public void setCustom4(String custom4) { - this.custom4 = custom4; - } + public void setCustom4(String custom4) { + this.custom4 = custom4; + } - public String getOldData() { - return oldData; - } + public String getOldData() { + return oldData; + } - public void setOldData(String oldData) { - this.oldData = oldData; - } + public void setOldData(String oldData) { + this.oldData = oldData; + } - public String getNewData() { - return newData; - } + public String getNewData() { + return newData; + } - public void setNewData(String newData) { - this.newData = newData; - } + public void setNewData(String newData) { + this.newData = newData; + } - @Override - public String toString() { - return "TaskHistoryEventResource [" - + "taskHistoryEventId= " + this.taskHistoryEventId - + "businessProcessId= " + this.businessProcessId - + "parentBusinessProcessId= " + this.parentBusinessProcessId - + "taskId= " + this.taskId - + "eventType= " + this.eventType - + "created= " + this.created - + "userId= " + this.userId - + "domain= " + this.domain - + "workbasketKey= " + this.workbasketKey - + "oldValue= " + this.oldValue - + "newValue= " + this.newValue - + "oldData= " + this.oldData - + "newData= " + this.newData - + "]"; - } + @Override + public String toString() { + return "TaskHistoryEventResource [" + + "taskHistoryEventId= " + + this.taskHistoryEventId + + "businessProcessId= " + + this.businessProcessId + + "parentBusinessProcessId= " + + this.parentBusinessProcessId + + "taskId= " + + this.taskId + + "eventType= " + + this.eventType + + "created= " + + this.created + + "userId= " + + this.userId + + "domain= " + + this.domain + + "workbasketKey= " + + this.workbasketKey + + "oldValue= " + + this.oldValue + + "newValue= " + + this.newValue + + "oldData= " + + this.oldData + + "newData= " + + this.newData + + "]"; + } } diff --git a/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/simplehistory/TaskHistoryEventController.java b/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/simplehistory/TaskHistoryEventController.java index 92a75bfb0..9fc44f592 100644 --- a/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/simplehistory/TaskHistoryEventController.java +++ b/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/simplehistory/TaskHistoryEventController.java @@ -4,7 +4,6 @@ import java.time.Instant; import java.time.LocalDate; import java.time.ZoneId; import java.util.List; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.hateoas.config.EnableHypermediaSupport; @@ -30,445 +29,456 @@ import pro.taskana.simplehistory.impl.HistoryEventImpl; import pro.taskana.simplehistory.impl.SimpleHistoryServiceImpl; import pro.taskana.simplehistory.query.HistoryQuery; -/** - * Controller for all TaskHistoryEvent related endpoints. - */ +/** Controller for all TaskHistoryEvent related endpoints. */ @RestController @EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL) @RequestMapping(path = "/api/v1/task-history-event", produces = "application/hal+json") public class TaskHistoryEventController extends AbstractPagingController { - private static final Logger LOGGER = LoggerFactory.getLogger(TaskHistoryEventController.class); + private static final Logger LOGGER = LoggerFactory.getLogger(TaskHistoryEventController.class); - private static final String LIKE = "%"; + private static final String LIKE = "%"; - private static final String BUSINESS_PROCESS_ID = "business-process-id"; + private static final String BUSINESS_PROCESS_ID = "business-process-id"; - private static final String BUSINESS_PROCESS_ID_LIKE = "business-process-id-like"; + private static final String BUSINESS_PROCESS_ID_LIKE = "business-process-id-like"; - private static final String PARENT_BUSINESS_PROCESS_ID = "parent-business-process-id"; + private static final String PARENT_BUSINESS_PROCESS_ID = "parent-business-process-id"; - private static final String PARENT_BUSINESS_PROCESS_ID_LIKE = "parent-business-process-id-like"; + private static final String PARENT_BUSINESS_PROCESS_ID_LIKE = "parent-business-process-id-like"; - private static final String TASK_ID = "task-id"; + private static final String TASK_ID = "task-id"; - private static final String TASK_ID_LIKE = "task-id-like"; + private static final String TASK_ID_LIKE = "task-id-like"; - private static final String EVENT_TYPE = "event-type"; + private static final String EVENT_TYPE = "event-type"; - private static final String EVENT_TYPE_LIKE = "event-type-like"; + private static final String EVENT_TYPE_LIKE = "event-type-like"; - private static final String CREATED = "created"; + private static final String CREATED = "created"; - private static final String USER_ID = "user-id"; + private static final String USER_ID = "user-id"; - private static final String USER_ID_LIKE = "user-id-like"; + private static final String USER_ID_LIKE = "user-id-like"; - private static final String DOMAIN = "domain"; + private static final String DOMAIN = "domain"; - private static final String WORKBASKET_KEY = "workbasket-key"; + private static final String WORKBASKET_KEY = "workbasket-key"; - private static final String WORKBASKET_KEY_LIKE = "workbasket-key-like"; + private static final String WORKBASKET_KEY_LIKE = "workbasket-key-like"; - private static final String POR_COMPANY = "por-company"; + private static final String POR_COMPANY = "por-company"; - private static final String POR_COMPANY_LIKE = "por-company-like"; + private static final String POR_COMPANY_LIKE = "por-company-like"; - private static final String POR_SYSTEM = "por-system"; + private static final String POR_SYSTEM = "por-system"; - private static final String POR_SYSTEM_LIKE = "por-system-like"; + private static final String POR_SYSTEM_LIKE = "por-system-like"; - private static final String POR_INSTANCE = "por-instance"; + private static final String POR_INSTANCE = "por-instance"; - private static final String POR_INSTANCE_LIKE = "por-instance-like"; + private static final String POR_INSTANCE_LIKE = "por-instance-like"; - private static final String POR_TYPE = "por-type"; + private static final String POR_TYPE = "por-type"; - private static final String POR_TYPE_LIKE = "por-type-like"; + private static final String POR_TYPE_LIKE = "por-type-like"; - private static final String POR_VALUE = "por-value"; + private static final String POR_VALUE = "por-value"; - private static final String POR_VALUE_LIKE = "por-value-like"; + private static final String POR_VALUE_LIKE = "por-value-like"; - private static final String TASK_CLASSIFICATION_KEY = "task-classification-key"; + private static final String TASK_CLASSIFICATION_KEY = "task-classification-key"; - private static final String TASK_CLASSIFICATION_KEY_LIKE = "task-classification-key-like"; + private static final String TASK_CLASSIFICATION_KEY_LIKE = "task-classification-key-like"; - private static final String TASK_CLASSIFICATION_CATEGORY = "task-classification-category"; + private static final String TASK_CLASSIFICATION_CATEGORY = "task-classification-category"; - private static final String TASK_CLASSIFICATION_CATEGORY_LIKE = "task-classification-category-like"; + private static final String TASK_CLASSIFICATION_CATEGORY_LIKE = + "task-classification-category-like"; - private static final String ATTACHMENT_CLASSIFICATION_KEY = "attachment-classification-key"; + private static final String ATTACHMENT_CLASSIFICATION_KEY = "attachment-classification-key"; - private static final String ATTACHMENT_CLASSIFICATION_KEY_LIKE = "attachment-classification-key-like"; + private static final String ATTACHMENT_CLASSIFICATION_KEY_LIKE = + "attachment-classification-key-like"; - private static final String CUSTOM_1 = "custom-1"; + private static final String CUSTOM_1 = "custom-1"; - private static final String CUSTOM_1_LIKE = "custom-1-like"; + private static final String CUSTOM_1_LIKE = "custom-1-like"; - private static final String CUSTOM_2 = "custom-2"; + private static final String CUSTOM_2 = "custom-2"; - private static final String CUSTOM_2_LIKE = "custom-2-like"; + private static final String CUSTOM_2_LIKE = "custom-2-like"; - private static final String CUSTOM_3 = "custom-3"; + private static final String CUSTOM_3 = "custom-3"; - private static final String CUSTOM_3_LIKE = "custom-3-like"; + private static final String CUSTOM_3_LIKE = "custom-3-like"; - private static final String CUSTOM_4 = "custom-4"; + private static final String CUSTOM_4 = "custom-4"; - private static final String CUSTOM_4_LIKE = "custom-4-like"; + private static final String CUSTOM_4_LIKE = "custom-4-like"; - private static final String SORT_BY = "sort-by"; + private static final String SORT_BY = "sort-by"; - private static final String SORT_DIRECTION = "order"; + private static final String SORT_DIRECTION = "order"; - private static final String PAGING_PAGE = "page"; + private static final String PAGING_PAGE = "page"; - private static final String PAGING_PAGE_SIZE = "page-size"; + private static final String PAGING_PAGE_SIZE = "page-size"; - private SimpleHistoryServiceImpl simpleHistoryService; + private SimpleHistoryServiceImpl simpleHistoryService; - private TaskanaEngineConfiguration taskanaEngineConfiguration; + private TaskanaEngineConfiguration taskanaEngineConfiguration; - public TaskHistoryEventController(TaskanaEngineConfiguration taskanaEngineConfiguration, - SimpleHistoryServiceImpl simpleHistoryServiceImpl) { - this.taskanaEngineConfiguration = taskanaEngineConfiguration; - this.simpleHistoryService = simpleHistoryServiceImpl; - simpleHistoryService.initialize(taskanaEngineConfiguration); + public TaskHistoryEventController( + TaskanaEngineConfiguration taskanaEngineConfiguration, + SimpleHistoryServiceImpl simpleHistoryServiceImpl) { + this.taskanaEngineConfiguration = taskanaEngineConfiguration; + this.simpleHistoryService = simpleHistoryServiceImpl; + simpleHistoryService.initialize(taskanaEngineConfiguration); + } + + @GetMapping + @Transactional(readOnly = true, rollbackFor = Exception.class) + public ResponseEntity getTaskHistoryEvent( + @RequestParam MultiValueMap params) throws InvalidArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Entry to getTaskHistoryEvent(params= {})", LoggerUtils.mapToString(params)); } - @GetMapping - @Transactional(readOnly = true, rollbackFor = Exception.class) - public ResponseEntity getTaskHistoryEvent( - @RequestParam MultiValueMap params) throws InvalidArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Entry to getTaskHistoryEvent(params= {})", LoggerUtils.mapToString(params)); - } + HistoryQuery query = simpleHistoryService.createHistoryQuery(); + query = applySortingParams(query, params); + query = applyFilterParams(query, params); - HistoryQuery query = simpleHistoryService.createHistoryQuery(); - query = applySortingParams(query, params); - query = applyFilterParams(query, params); - - PageMetadata pageMetadata = null; - List historyEvents = null; - String page = params.getFirst(PAGING_PAGE); - String pageSize = params.getFirst(PAGING_PAGE_SIZE); - params.remove(PAGING_PAGE); - params.remove(PAGING_PAGE_SIZE); - validateNoInvalidParameterIsLeft(params); - if (page != null && pageSize != null) { - long totalElements = query.count(); - pageMetadata = initPageMetadata(pageSize, page, totalElements); - historyEvents = query.listPage((int) pageMetadata.getNumber(), - (int) pageMetadata.getSize()); - } else if (page == null && pageSize == null) { - historyEvents = query.list(); - } else { - throw new InvalidArgumentException("Paging information is incomplete."); - } - - TaskHistoryEventListAssembler assembler = new TaskHistoryEventListAssembler(); - TaskHistoryEventListResource pagedResources = assembler.toResources(historyEvents, pageMetadata); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from getTaskHistoryEvent(), returning {}", - new ResponseEntity<>(pagedResources, HttpStatus.OK)); - } - - return new ResponseEntity<>(pagedResources, HttpStatus.OK); + PageMetadata pageMetadata = null; + List historyEvents = null; + String page = params.getFirst(PAGING_PAGE); + String pageSize = params.getFirst(PAGING_PAGE_SIZE); + params.remove(PAGING_PAGE); + params.remove(PAGING_PAGE_SIZE); + validateNoInvalidParameterIsLeft(params); + if (page != null && pageSize != null) { + long totalElements = query.count(); + pageMetadata = initPageMetadata(pageSize, page, totalElements); + historyEvents = query.listPage((int) pageMetadata.getNumber(), (int) pageMetadata.getSize()); + } else if (page == null && pageSize == null) { + historyEvents = query.list(); + } else { + throw new InvalidArgumentException("Paging information is incomplete."); } - private HistoryQuery applySortingParams(HistoryQuery query, MultiValueMap params) - throws IllegalArgumentException, InvalidArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Entry to applySortingParams(params= {})", LoggerUtils.mapToString(params)); - } + TaskHistoryEventListAssembler assembler = new TaskHistoryEventListAssembler(); + TaskHistoryEventListResource pagedResources = + assembler.toResources(historyEvents, pageMetadata); - String sortBy = params.getFirst(SORT_BY); - if (sortBy != null) { - BaseQuery.SortDirection sortDirection; - if (params.getFirst(SORT_DIRECTION) != null && "desc".equals(params.getFirst(SORT_DIRECTION))) { - sortDirection = BaseQuery.SortDirection.DESCENDING; - } else { - sortDirection = BaseQuery.SortDirection.ASCENDING; - } - switch (sortBy) { - case (BUSINESS_PROCESS_ID): - query = query.orderByBusinessProcessId(sortDirection); - break; - case (PARENT_BUSINESS_PROCESS_ID): - query = query.orderByParentBusinessProcessId(sortDirection); - break; - case (TASK_ID): - query = query.orderByTaskId(sortDirection); - break; - case (EVENT_TYPE): - query = query.orderByEventType(sortDirection); - break; - case (CREATED): - query = query.orderByCreated(sortDirection); - break; - case (USER_ID): - query = query.orderByUserId(sortDirection); - break; - case (DOMAIN): - query = query.orderByDomain(sortDirection); - break; - case (WORKBASKET_KEY): - query = query.orderByWorkbasketKey(sortDirection); - break; - case (POR_COMPANY): - query = query.orderByPorCompany(sortDirection); - break; - case (POR_SYSTEM): - query = query.orderByPorSystem(sortDirection); - break; - case (POR_INSTANCE): - query = query.orderByPorInstance(sortDirection); - break; - case (POR_TYPE): - query = query.orderByPorType(sortDirection); - break; - case (POR_VALUE): - query = query.orderByPorValue(sortDirection); - break; - case (TASK_CLASSIFICATION_KEY): - query = query.orderByTaskClassificationKey(sortDirection); - break; - case (TASK_CLASSIFICATION_CATEGORY): - query = query.orderByTaskClassificationCategory(sortDirection); - break; - case (ATTACHMENT_CLASSIFICATION_KEY): - query = query.orderByAttachmentClassificationKey(sortDirection); - break; - case (CUSTOM_1): - query = query.orderByCustomAttribute(1, sortDirection); - break; - case (CUSTOM_2): - query = query.orderByCustomAttribute(2, sortDirection); - break; - case (CUSTOM_3): - query = query.orderByCustomAttribute(3, sortDirection); - break; - case (CUSTOM_4): - query = query.orderByCustomAttribute(4, sortDirection); - break; - default: - throw new IllegalArgumentException("Unknown order '" + sortBy + "'"); - } - } - params.remove(SORT_BY); - params.remove(SORT_DIRECTION); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from applySortingParams(), returning {}", query); - } - - return query; + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "Exit from getTaskHistoryEvent(), returning {}", + new ResponseEntity<>(pagedResources, HttpStatus.OK)); } - private HistoryQuery applyFilterParams(HistoryQuery query, - MultiValueMap params) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Entry to applyFilterParams(query= {}, params= {})", query, params); - } + return new ResponseEntity<>(pagedResources, HttpStatus.OK); + } - if (params.containsKey(BUSINESS_PROCESS_ID)) { - String[] businessProcessId = extractCommaSeparatedFields(params.get(BUSINESS_PROCESS_ID)); - query.businessProcessIdIn(businessProcessId); - params.remove(BUSINESS_PROCESS_ID); - } - if (params.containsKey(BUSINESS_PROCESS_ID_LIKE)) { - query.businessProcessIdLike(LIKE + params.get(BUSINESS_PROCESS_ID_LIKE).get(0) + LIKE); - params.remove(BUSINESS_PROCESS_ID_LIKE); - } - if (params.containsKey(PARENT_BUSINESS_PROCESS_ID)) { - String[] parentBusinessProcessId = extractCommaSeparatedFields(params.get(PARENT_BUSINESS_PROCESS_ID)); - query.parentBusinessProcessIdIn(parentBusinessProcessId); - params.remove(PARENT_BUSINESS_PROCESS_ID); - } - if (params.containsKey(PARENT_BUSINESS_PROCESS_ID_LIKE)) { - query.parentBusinessProcessIdLike(LIKE + params.get(PARENT_BUSINESS_PROCESS_ID_LIKE).get(0) + LIKE); - params.remove(PARENT_BUSINESS_PROCESS_ID_LIKE); - } - if (params.containsKey(TASK_ID)) { - String[] taskId = extractCommaSeparatedFields(params.get(TASK_ID)); - query.taskIdIn(taskId); - params.remove(TASK_ID); - } - if (params.containsKey(TASK_ID_LIKE)) { - query.taskIdLike(LIKE + params.get(TASK_ID_LIKE).get(0) + LIKE); - params.remove(TASK_ID_LIKE); - } - if (params.containsKey(EVENT_TYPE)) { - String[] eventType = extractCommaSeparatedFields(params.get(EVENT_TYPE)); - query.eventTypeIn(eventType); - params.remove(EVENT_TYPE); - } - if (params.containsKey(EVENT_TYPE_LIKE)) { - query.eventTypeLike(LIKE + params.get(EVENT_TYPE_LIKE).get(0) + LIKE); - params.remove(EVENT_TYPE_LIKE); - } - if (params.containsKey(CREATED)) { - String[] created = extractCommaSeparatedFields(params.get(CREATED)); - TimeInterval timeInterval = getTimeIntervalOf(created); - query.createdWithin(timeInterval); - params.remove(CREATED); - } - if (params.containsKey(USER_ID)) { - String[] userId = extractCommaSeparatedFields(params.get(USER_ID)); - query.userIdIn(userId); - params.remove(USER_ID); - } - if (params.containsKey(USER_ID_LIKE)) { - query.userIdLike(LIKE + params.get(USER_ID_LIKE).get(0) + LIKE); - params.remove(USER_ID_LIKE); - } - if (params.containsKey(DOMAIN)) { - query.domainIn(extractCommaSeparatedFields(params.get(DOMAIN))); - params.remove(DOMAIN); - } - if (params.containsKey(WORKBASKET_KEY)) { - String[] workbasketKey = extractCommaSeparatedFields(params.get(WORKBASKET_KEY)); - query.workbasketKeyIn(workbasketKey); - params.remove(WORKBASKET_KEY); - } - if (params.containsKey(WORKBASKET_KEY_LIKE)) { - query.workbasketKeyLike(LIKE + params.get(WORKBASKET_KEY_LIKE).get(0) + LIKE); - params.remove(WORKBASKET_KEY_LIKE); - } - if (params.containsKey(POR_COMPANY)) { - String[] porCompany = extractCommaSeparatedFields(params.get(POR_COMPANY)); - query.porCompanyIn(porCompany); - params.remove(POR_COMPANY); - } - if (params.containsKey(POR_COMPANY_LIKE)) { - query.porCompanyLike(LIKE + params.get(POR_COMPANY_LIKE).get(0) + LIKE); - params.remove(POR_COMPANY_LIKE); - } - if (params.containsKey(POR_SYSTEM)) { - String[] porSystem = extractCommaSeparatedFields(params.get(POR_SYSTEM)); - query.porSystemIn(porSystem); - params.remove(POR_SYSTEM); - } - if (params.containsKey(POR_SYSTEM_LIKE)) { - query.porSystemLike(LIKE + params.get(POR_SYSTEM_LIKE).get(0) + LIKE); - params.remove(POR_SYSTEM_LIKE); - } - if (params.containsKey(POR_INSTANCE)) { - String[] porInstance = extractCommaSeparatedFields(params.get(POR_INSTANCE)); - query.porInstanceIn(porInstance); - params.remove(POR_INSTANCE); - } - if (params.containsKey(POR_INSTANCE_LIKE)) { - query.porInstanceLike(LIKE + params.get(POR_INSTANCE_LIKE).get(0) + LIKE); - params.remove(POR_INSTANCE_LIKE); - } - if (params.containsKey(POR_TYPE)) { - String[] porType = extractCommaSeparatedFields(params.get(POR_TYPE)); - query.porTypeIn(porType); - params.remove(POR_TYPE); - } - if (params.containsKey(POR_TYPE_LIKE)) { - query.porTypeLike(LIKE + params.get(POR_TYPE_LIKE).get(0) + LIKE); - params.remove(POR_TYPE_LIKE); - } - if (params.containsKey(POR_VALUE)) { - String[] porValue = extractCommaSeparatedFields(params.get(POR_VALUE)); - query.porValueIn(porValue); - params.remove(POR_VALUE); - } - if (params.containsKey(POR_VALUE_LIKE)) { - query.porValueLike(LIKE + params.get(POR_VALUE_LIKE).get(0) + LIKE); - params.remove(POR_VALUE_LIKE); - } - if (params.containsKey(TASK_CLASSIFICATION_KEY)) { - String[] taskClassificationKey = extractCommaSeparatedFields(params.get(TASK_CLASSIFICATION_KEY)); - query.taskClassificationKeyIn(taskClassificationKey); - params.remove(TASK_CLASSIFICATION_KEY); - } - if (params.containsKey(TASK_CLASSIFICATION_KEY_LIKE)) { - query.taskClassificationKeyLike(LIKE + params.get(TASK_CLASSIFICATION_KEY_LIKE).get(0) + LIKE); - params.remove(TASK_CLASSIFICATION_KEY_LIKE); - } - if (params.containsKey(TASK_CLASSIFICATION_CATEGORY)) { - String[] taskClassificationCategory = extractCommaSeparatedFields(params.get(TASK_CLASSIFICATION_CATEGORY)); - query.taskClassificationCategoryIn(taskClassificationCategory); - params.remove(TASK_CLASSIFICATION_CATEGORY); - } - if (params.containsKey(TASK_CLASSIFICATION_CATEGORY_LIKE)) { - query.taskClassificationCategoryLike(LIKE + params.get(TASK_CLASSIFICATION_CATEGORY_LIKE).get(0) + LIKE); - params.remove(TASK_CLASSIFICATION_CATEGORY_LIKE); - } - if (params.containsKey(ATTACHMENT_CLASSIFICATION_KEY)) { - String[] attachmentClassificationKey = extractCommaSeparatedFields( - params.get(ATTACHMENT_CLASSIFICATION_KEY)); - query.attachmentClassificationKeyIn(attachmentClassificationKey); - params.remove(ATTACHMENT_CLASSIFICATION_KEY); - } - if (params.containsKey(ATTACHMENT_CLASSIFICATION_KEY_LIKE)) { - query.attachmentClassificationKeyLike(LIKE + params.get(ATTACHMENT_CLASSIFICATION_KEY_LIKE).get(0) + LIKE); - params.remove(ATTACHMENT_CLASSIFICATION_KEY_LIKE); - } - if (params.containsKey(CUSTOM_1)) { - String[] custom1 = extractCommaSeparatedFields(params.get(CUSTOM_1)); - query.custom1In(custom1); - params.remove(CUSTOM_1); - } - if (params.containsKey(CUSTOM_1_LIKE)) { - query.custom1Like(LIKE + params.get(CUSTOM_1_LIKE).get(0) + LIKE); - params.remove(CUSTOM_1_LIKE); - } - if (params.containsKey(CUSTOM_2)) { - String[] custom2 = extractCommaSeparatedFields(params.get(CUSTOM_2)); - query.custom2In(custom2); - params.remove(CUSTOM_2); - } - if (params.containsKey(CUSTOM_2_LIKE)) { - query.custom2Like(LIKE + params.get(CUSTOM_2_LIKE).get(0) + LIKE); - params.remove(CUSTOM_2_LIKE); - } - if (params.containsKey(CUSTOM_3)) { - String[] custom3 = extractCommaSeparatedFields(params.get(CUSTOM_3)); - query.custom3In(custom3); - params.remove(CUSTOM_3); - } - if (params.containsKey(CUSTOM_3_LIKE)) { - query.custom3Like(LIKE + params.get(CUSTOM_3_LIKE).get(0) + LIKE); - params.remove(CUSTOM_3_LIKE); - } - if (params.containsKey(CUSTOM_4)) { - String[] custom4 = extractCommaSeparatedFields(params.get(CUSTOM_4)); - query.custom4In(custom4); - params.remove(CUSTOM_4); - } - if (params.containsKey(CUSTOM_4_LIKE)) { - query.custom4Like(LIKE + params.get(CUSTOM_4_LIKE).get(0) + LIKE); - params.remove(CUSTOM_4_LIKE); - } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from applyFilterParams(), returning {}", query); - } - - return query; + private HistoryQuery applySortingParams(HistoryQuery query, MultiValueMap params) + throws IllegalArgumentException, InvalidArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Entry to applySortingParams(params= {})", LoggerUtils.mapToString(params)); } - private TimeInterval getTimeIntervalOf(String[] created) { - LocalDate begin; - LocalDate end; - try { - begin = LocalDate.parse(created[0]); - } catch (Exception e) { - throw new IllegalArgumentException( - "Cannot parse String '" + created[0] + "'. Expected a String of the Format 'yyyy-MM-dd'."); - } - if (created.length < 2) { - end = begin.plusDays(1); - } else { - end = LocalDate.parse(created[1]); - } - Instant beginInst = begin.atStartOfDay(ZoneId.systemDefault()).toInstant(); - Instant endInst = end.atStartOfDay(ZoneId.systemDefault()).toInstant(); - TimeInterval timeInterval = new TimeInterval(beginInst, endInst); - return timeInterval; + String sortBy = params.getFirst(SORT_BY); + if (sortBy != null) { + BaseQuery.SortDirection sortDirection; + if (params.getFirst(SORT_DIRECTION) != null + && "desc".equals(params.getFirst(SORT_DIRECTION))) { + sortDirection = BaseQuery.SortDirection.DESCENDING; + } else { + sortDirection = BaseQuery.SortDirection.ASCENDING; + } + switch (sortBy) { + case (BUSINESS_PROCESS_ID): + query = query.orderByBusinessProcessId(sortDirection); + break; + case (PARENT_BUSINESS_PROCESS_ID): + query = query.orderByParentBusinessProcessId(sortDirection); + break; + case (TASK_ID): + query = query.orderByTaskId(sortDirection); + break; + case (EVENT_TYPE): + query = query.orderByEventType(sortDirection); + break; + case (CREATED): + query = query.orderByCreated(sortDirection); + break; + case (USER_ID): + query = query.orderByUserId(sortDirection); + break; + case (DOMAIN): + query = query.orderByDomain(sortDirection); + break; + case (WORKBASKET_KEY): + query = query.orderByWorkbasketKey(sortDirection); + break; + case (POR_COMPANY): + query = query.orderByPorCompany(sortDirection); + break; + case (POR_SYSTEM): + query = query.orderByPorSystem(sortDirection); + break; + case (POR_INSTANCE): + query = query.orderByPorInstance(sortDirection); + break; + case (POR_TYPE): + query = query.orderByPorType(sortDirection); + break; + case (POR_VALUE): + query = query.orderByPorValue(sortDirection); + break; + case (TASK_CLASSIFICATION_KEY): + query = query.orderByTaskClassificationKey(sortDirection); + break; + case (TASK_CLASSIFICATION_CATEGORY): + query = query.orderByTaskClassificationCategory(sortDirection); + break; + case (ATTACHMENT_CLASSIFICATION_KEY): + query = query.orderByAttachmentClassificationKey(sortDirection); + break; + case (CUSTOM_1): + query = query.orderByCustomAttribute(1, sortDirection); + break; + case (CUSTOM_2): + query = query.orderByCustomAttribute(2, sortDirection); + break; + case (CUSTOM_3): + query = query.orderByCustomAttribute(3, sortDirection); + break; + case (CUSTOM_4): + query = query.orderByCustomAttribute(4, sortDirection); + break; + default: + throw new IllegalArgumentException("Unknown order '" + sortBy + "'"); + } } + params.remove(SORT_BY); + params.remove(SORT_DIRECTION); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from applySortingParams(), returning {}", query); + } + + return query; + } + + private HistoryQuery applyFilterParams(HistoryQuery query, MultiValueMap params) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Entry to applyFilterParams(query= {}, params= {})", query, params); + } + + if (params.containsKey(BUSINESS_PROCESS_ID)) { + String[] businessProcessId = extractCommaSeparatedFields(params.get(BUSINESS_PROCESS_ID)); + query.businessProcessIdIn(businessProcessId); + params.remove(BUSINESS_PROCESS_ID); + } + if (params.containsKey(BUSINESS_PROCESS_ID_LIKE)) { + query.businessProcessIdLike(LIKE + params.get(BUSINESS_PROCESS_ID_LIKE).get(0) + LIKE); + params.remove(BUSINESS_PROCESS_ID_LIKE); + } + if (params.containsKey(PARENT_BUSINESS_PROCESS_ID)) { + String[] parentBusinessProcessId = + extractCommaSeparatedFields(params.get(PARENT_BUSINESS_PROCESS_ID)); + query.parentBusinessProcessIdIn(parentBusinessProcessId); + params.remove(PARENT_BUSINESS_PROCESS_ID); + } + if (params.containsKey(PARENT_BUSINESS_PROCESS_ID_LIKE)) { + query.parentBusinessProcessIdLike( + LIKE + params.get(PARENT_BUSINESS_PROCESS_ID_LIKE).get(0) + LIKE); + params.remove(PARENT_BUSINESS_PROCESS_ID_LIKE); + } + if (params.containsKey(TASK_ID)) { + String[] taskId = extractCommaSeparatedFields(params.get(TASK_ID)); + query.taskIdIn(taskId); + params.remove(TASK_ID); + } + if (params.containsKey(TASK_ID_LIKE)) { + query.taskIdLike(LIKE + params.get(TASK_ID_LIKE).get(0) + LIKE); + params.remove(TASK_ID_LIKE); + } + if (params.containsKey(EVENT_TYPE)) { + String[] eventType = extractCommaSeparatedFields(params.get(EVENT_TYPE)); + query.eventTypeIn(eventType); + params.remove(EVENT_TYPE); + } + if (params.containsKey(EVENT_TYPE_LIKE)) { + query.eventTypeLike(LIKE + params.get(EVENT_TYPE_LIKE).get(0) + LIKE); + params.remove(EVENT_TYPE_LIKE); + } + if (params.containsKey(CREATED)) { + String[] created = extractCommaSeparatedFields(params.get(CREATED)); + TimeInterval timeInterval = getTimeIntervalOf(created); + query.createdWithin(timeInterval); + params.remove(CREATED); + } + if (params.containsKey(USER_ID)) { + String[] userId = extractCommaSeparatedFields(params.get(USER_ID)); + query.userIdIn(userId); + params.remove(USER_ID); + } + if (params.containsKey(USER_ID_LIKE)) { + query.userIdLike(LIKE + params.get(USER_ID_LIKE).get(0) + LIKE); + params.remove(USER_ID_LIKE); + } + if (params.containsKey(DOMAIN)) { + query.domainIn(extractCommaSeparatedFields(params.get(DOMAIN))); + params.remove(DOMAIN); + } + if (params.containsKey(WORKBASKET_KEY)) { + String[] workbasketKey = extractCommaSeparatedFields(params.get(WORKBASKET_KEY)); + query.workbasketKeyIn(workbasketKey); + params.remove(WORKBASKET_KEY); + } + if (params.containsKey(WORKBASKET_KEY_LIKE)) { + query.workbasketKeyLike(LIKE + params.get(WORKBASKET_KEY_LIKE).get(0) + LIKE); + params.remove(WORKBASKET_KEY_LIKE); + } + if (params.containsKey(POR_COMPANY)) { + String[] porCompany = extractCommaSeparatedFields(params.get(POR_COMPANY)); + query.porCompanyIn(porCompany); + params.remove(POR_COMPANY); + } + if (params.containsKey(POR_COMPANY_LIKE)) { + query.porCompanyLike(LIKE + params.get(POR_COMPANY_LIKE).get(0) + LIKE); + params.remove(POR_COMPANY_LIKE); + } + if (params.containsKey(POR_SYSTEM)) { + String[] porSystem = extractCommaSeparatedFields(params.get(POR_SYSTEM)); + query.porSystemIn(porSystem); + params.remove(POR_SYSTEM); + } + if (params.containsKey(POR_SYSTEM_LIKE)) { + query.porSystemLike(LIKE + params.get(POR_SYSTEM_LIKE).get(0) + LIKE); + params.remove(POR_SYSTEM_LIKE); + } + if (params.containsKey(POR_INSTANCE)) { + String[] porInstance = extractCommaSeparatedFields(params.get(POR_INSTANCE)); + query.porInstanceIn(porInstance); + params.remove(POR_INSTANCE); + } + if (params.containsKey(POR_INSTANCE_LIKE)) { + query.porInstanceLike(LIKE + params.get(POR_INSTANCE_LIKE).get(0) + LIKE); + params.remove(POR_INSTANCE_LIKE); + } + if (params.containsKey(POR_TYPE)) { + String[] porType = extractCommaSeparatedFields(params.get(POR_TYPE)); + query.porTypeIn(porType); + params.remove(POR_TYPE); + } + if (params.containsKey(POR_TYPE_LIKE)) { + query.porTypeLike(LIKE + params.get(POR_TYPE_LIKE).get(0) + LIKE); + params.remove(POR_TYPE_LIKE); + } + if (params.containsKey(POR_VALUE)) { + String[] porValue = extractCommaSeparatedFields(params.get(POR_VALUE)); + query.porValueIn(porValue); + params.remove(POR_VALUE); + } + if (params.containsKey(POR_VALUE_LIKE)) { + query.porValueLike(LIKE + params.get(POR_VALUE_LIKE).get(0) + LIKE); + params.remove(POR_VALUE_LIKE); + } + if (params.containsKey(TASK_CLASSIFICATION_KEY)) { + String[] taskClassificationKey = + extractCommaSeparatedFields(params.get(TASK_CLASSIFICATION_KEY)); + query.taskClassificationKeyIn(taskClassificationKey); + params.remove(TASK_CLASSIFICATION_KEY); + } + if (params.containsKey(TASK_CLASSIFICATION_KEY_LIKE)) { + query.taskClassificationKeyLike( + LIKE + params.get(TASK_CLASSIFICATION_KEY_LIKE).get(0) + LIKE); + params.remove(TASK_CLASSIFICATION_KEY_LIKE); + } + if (params.containsKey(TASK_CLASSIFICATION_CATEGORY)) { + String[] taskClassificationCategory = + extractCommaSeparatedFields(params.get(TASK_CLASSIFICATION_CATEGORY)); + query.taskClassificationCategoryIn(taskClassificationCategory); + params.remove(TASK_CLASSIFICATION_CATEGORY); + } + if (params.containsKey(TASK_CLASSIFICATION_CATEGORY_LIKE)) { + query.taskClassificationCategoryLike( + LIKE + params.get(TASK_CLASSIFICATION_CATEGORY_LIKE).get(0) + LIKE); + params.remove(TASK_CLASSIFICATION_CATEGORY_LIKE); + } + if (params.containsKey(ATTACHMENT_CLASSIFICATION_KEY)) { + String[] attachmentClassificationKey = + extractCommaSeparatedFields(params.get(ATTACHMENT_CLASSIFICATION_KEY)); + query.attachmentClassificationKeyIn(attachmentClassificationKey); + params.remove(ATTACHMENT_CLASSIFICATION_KEY); + } + if (params.containsKey(ATTACHMENT_CLASSIFICATION_KEY_LIKE)) { + query.attachmentClassificationKeyLike( + LIKE + params.get(ATTACHMENT_CLASSIFICATION_KEY_LIKE).get(0) + LIKE); + params.remove(ATTACHMENT_CLASSIFICATION_KEY_LIKE); + } + if (params.containsKey(CUSTOM_1)) { + String[] custom1 = extractCommaSeparatedFields(params.get(CUSTOM_1)); + query.custom1In(custom1); + params.remove(CUSTOM_1); + } + if (params.containsKey(CUSTOM_1_LIKE)) { + query.custom1Like(LIKE + params.get(CUSTOM_1_LIKE).get(0) + LIKE); + params.remove(CUSTOM_1_LIKE); + } + if (params.containsKey(CUSTOM_2)) { + String[] custom2 = extractCommaSeparatedFields(params.get(CUSTOM_2)); + query.custom2In(custom2); + params.remove(CUSTOM_2); + } + if (params.containsKey(CUSTOM_2_LIKE)) { + query.custom2Like(LIKE + params.get(CUSTOM_2_LIKE).get(0) + LIKE); + params.remove(CUSTOM_2_LIKE); + } + if (params.containsKey(CUSTOM_3)) { + String[] custom3 = extractCommaSeparatedFields(params.get(CUSTOM_3)); + query.custom3In(custom3); + params.remove(CUSTOM_3); + } + if (params.containsKey(CUSTOM_3_LIKE)) { + query.custom3Like(LIKE + params.get(CUSTOM_3_LIKE).get(0) + LIKE); + params.remove(CUSTOM_3_LIKE); + } + if (params.containsKey(CUSTOM_4)) { + String[] custom4 = extractCommaSeparatedFields(params.get(CUSTOM_4)); + query.custom4In(custom4); + params.remove(CUSTOM_4); + } + if (params.containsKey(CUSTOM_4_LIKE)) { + query.custom4Like(LIKE + params.get(CUSTOM_4_LIKE).get(0) + LIKE); + params.remove(CUSTOM_4_LIKE); + } + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from applyFilterParams(), returning {}", query); + } + + return query; + } + + private TimeInterval getTimeIntervalOf(String[] created) { + LocalDate begin; + LocalDate end; + try { + begin = LocalDate.parse(created[0]); + } catch (Exception e) { + throw new IllegalArgumentException( + "Cannot parse String '" + + created[0] + + "'. Expected a String of the Format 'yyyy-MM-dd'."); + } + if (created.length < 2) { + end = begin.plusDays(1); + } else { + end = LocalDate.parse(created[1]); + } + Instant beginInst = begin.atStartOfDay(ZoneId.systemDefault()).toInstant(); + Instant endInst = end.atStartOfDay(ZoneId.systemDefault()).toInstant(); + TimeInterval timeInterval = new TimeInterval(beginInst, endInst); + return timeInterval; + } } diff --git a/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/simplehistory/TaskHistoryRestConfiguration.java b/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/simplehistory/TaskHistoryRestConfiguration.java index 453be5143..1959d2cd6 100644 --- a/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/simplehistory/TaskHistoryRestConfiguration.java +++ b/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/simplehistory/TaskHistoryRestConfiguration.java @@ -7,17 +7,14 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; import pro.taskana.simplehistory.impl.SimpleHistoryServiceImpl; -/** - * Configuration for Taskana history REST service. - */ +/** Configuration for Taskana history REST service. */ @Configuration @ComponentScan(basePackages = {"pro.taskana.rest", "pro.taskana.rest.simplehistory"}) @EnableTransactionManagement public class TaskHistoryRestConfiguration { - @Bean - public SimpleHistoryServiceImpl getSimpleHistoryService() { - return new SimpleHistoryServiceImpl(); - } - + @Bean + public SimpleHistoryServiceImpl getSimpleHistoryService() { + return new SimpleHistoryServiceImpl(); + } } diff --git a/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/simplehistory/sampledata/SampleDataGenerator.java b/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/simplehistory/sampledata/SampleDataGenerator.java index 6719ddec4..17b8e247c 100644 --- a/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/simplehistory/sampledata/SampleDataGenerator.java +++ b/history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/simplehistory/sampledata/SampleDataGenerator.java @@ -8,76 +8,75 @@ import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.SQLException; - import javax.sql.DataSource; - import org.apache.ibatis.jdbc.ScriptRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pro.taskana.configuration.DB; -/** - * This class generates sample data for manual testing purposes. - */ +/** This class generates sample data for manual testing purposes. */ public class SampleDataGenerator { - private static final Logger LOGGER = LoggerFactory.getLogger(SampleDataGenerator.class); - private static final String TEST_DATA = "/sql.sample-data"; - private static final String CLEAR = TEST_DATA + "/clear-db.sql"; - private static final String HISTORY_EVENT = TEST_DATA + "/history-event.sql"; - private ScriptRunner runner; + private static final Logger LOGGER = LoggerFactory.getLogger(SampleDataGenerator.class); + private static final String TEST_DATA = "/sql.sample-data"; + private static final String CLEAR = TEST_DATA + "/clear-db.sql"; + private static final String HISTORY_EVENT = TEST_DATA + "/history-event.sql"; + DataSource dataSource; + String dbProductName; + private ScriptRunner runner; - DataSource dataSource; - String dbProductName; + public SampleDataGenerator(DataSource dataSource) throws SQLException { + try (Connection connection = dataSource.getConnection()) { + dbProductName = connection.getMetaData().getDatabaseProductName(); + if (LOGGER.isTraceEnabled()) { + String msg = connection.getMetaData().toString(); + LOGGER.trace(msg); + } + } + this.dataSource = dataSource; - public SampleDataGenerator(DataSource dataSource) throws SQLException { - try (Connection connection = dataSource.getConnection()) { - dbProductName = connection.getMetaData().getDatabaseProductName(); - if (LOGGER.isTraceEnabled()) { - String msg = connection.getMetaData().toString(); - LOGGER.trace(msg); - } - } - this.dataSource = dataSource; + runner = new ScriptRunner(dataSource.getConnection()); + } - runner = new ScriptRunner(dataSource.getConnection()); + public void generateSampleData(String schemaName) { + StringWriter outWriter = new StringWriter(); + PrintWriter logWriter = new PrintWriter(outWriter); + + StringWriter errorWriter = new StringWriter(); + PrintWriter errorLogWriter = new PrintWriter(errorWriter); + try { + runner.runScript(selectSchemaScript(dbProductName, schemaName)); + runner.setStopOnError(false); + runner.runScript( + new BufferedReader( + new InputStreamReader( + this.getClass().getResourceAsStream(CLEAR), StandardCharsets.UTF_8))); + } catch (Exception e) { + LOGGER.error("caught Exception {}", e, e); } - public void generateSampleData(String schemaName) { - StringWriter outWriter = new StringWriter(); - PrintWriter logWriter = new PrintWriter(outWriter); + runner.setStopOnError(true); + runner.setLogWriter(logWriter); + runner.setErrorLogWriter(errorLogWriter); - StringWriter errorWriter = new StringWriter(); - PrintWriter errorLogWriter = new PrintWriter(errorWriter); - try { - runner.runScript(selectSchemaScript(dbProductName, schemaName)); - runner.setStopOnError(false); - runner.runScript(new BufferedReader( - new InputStreamReader(this.getClass().getResourceAsStream(CLEAR), StandardCharsets.UTF_8))); - } catch (Exception e) { - LOGGER.error("caught Exception {}", e, e); - } + runner.runScript( + new BufferedReader( + new InputStreamReader( + this.getClass().getResourceAsStream(HISTORY_EVENT), StandardCharsets.UTF_8))); - runner.setStopOnError(true); - runner.setLogWriter(logWriter); - runner.setErrorLogWriter(errorLogWriter); + runner.closeConnection(); - runner.runScript(new BufferedReader( - new InputStreamReader(this.getClass().getResourceAsStream(HISTORY_EVENT), StandardCharsets.UTF_8))); - - runner.closeConnection(); - - LOGGER.trace(outWriter.toString()); - if (!errorWriter.toString().trim().isEmpty()) { - LOGGER.error(errorWriter.toString()); - } + LOGGER.trace(outWriter.toString()); + if (!errorWriter.toString().trim().isEmpty()) { + LOGGER.error(errorWriter.toString()); } + } - private StringReader selectSchemaScript(String dbProductName, String schemaName) { - return new StringReader(DB.isPostgreSQL(dbProductName) + private StringReader selectSchemaScript(String dbProductName, String schemaName) { + return new StringReader( + DB.isPostgreSQL(dbProductName) ? "SET search_path TO " + schemaName + ";" : "SET SCHEMA " + schemaName + ";"); - } - + } } diff --git a/history/taskana-simplehistory-spring-test/src/main/java/pro/taskana/rest/ExampleDocumentationApplication.java b/history/taskana-simplehistory-spring-test/src/main/java/pro/taskana/rest/ExampleDocumentationApplication.java index 0e94735f0..2e0dd53cb 100644 --- a/history/taskana-simplehistory-spring-test/src/main/java/pro/taskana/rest/ExampleDocumentationApplication.java +++ b/history/taskana-simplehistory-spring-test/src/main/java/pro/taskana/rest/ExampleDocumentationApplication.java @@ -1,9 +1,7 @@ package pro.taskana.rest; import java.sql.SQLException; - import javax.sql.DataSource; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; @@ -21,48 +19,47 @@ import org.springframework.transaction.PlatformTransactionManager; import pro.taskana.rest.simplehistory.TaskHistoryRestConfiguration; import pro.taskana.rest.simplehistory.sampledata.SampleDataGenerator; -/** - * Example Application to create the documentation. - */ +/** Example Application to create the documentation. */ @SpringBootApplication @ComponentScan(basePackages = "pro.taskana.rest.simplehistory") @Import({TaskHistoryRestConfiguration.class}) public class ExampleDocumentationApplication { - @Value("${taskana.schemaName:TASKANA}") - private String schemaName; + @Value("${taskana.schemaName:TASKANA}") + private String schemaName; - @Autowired - private SampleDataGenerator sampleDataGenerator; + @Autowired private SampleDataGenerator sampleDataGenerator; - public static void main(String[] args) { - SpringApplication.run(ExampleDocumentationApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(ExampleDocumentationApplication.class, args); + } - @Bean - @Primary - @ConfigurationProperties(prefix = "datasource") - public DataSourceProperties dataSourceProperties() { - DataSourceProperties props = new DataSourceProperties(); - props.setUrl("jdbc:h2:mem:taskana;IGNORECASE=TRUE;LOCK_MODE=0;INIT=CREATE SCHEMA IF NOT EXISTS " + schemaName); - return props; - } + @Bean + @Primary + @ConfigurationProperties(prefix = "datasource") + public DataSourceProperties dataSourceProperties() { + DataSourceProperties props = new DataSourceProperties(); + props.setUrl( + "jdbc:h2:mem:taskana;IGNORECASE=TRUE;LOCK_MODE=0;INIT=CREATE SCHEMA IF NOT EXISTS " + + schemaName); + return props; + } - @Bean - public DataSource dataSource(DataSourceProperties properties) { - return properties.initializeDataSourceBuilder().build(); - } + @Bean + public DataSource dataSource(DataSourceProperties properties) { + return properties.initializeDataSourceBuilder().build(); + } - @Bean - public PlatformTransactionManager txManager(DataSource dataSource) { - return new DataSourceTransactionManager(dataSource); - } + @Bean + public PlatformTransactionManager txManager(DataSource dataSource) { + return new DataSourceTransactionManager(dataSource); + } - @Bean - @DependsOn("getTaskanaEngine") // generate sample data after schema was inserted - public SampleDataGenerator generateSampleData(DataSource dataSource) throws SQLException { - sampleDataGenerator = new SampleDataGenerator(dataSource); - sampleDataGenerator.generateSampleData(schemaName); - return sampleDataGenerator; - } + @Bean + @DependsOn("getTaskanaEngine") // generate sample data after schema was inserted + public SampleDataGenerator generateSampleData(DataSource dataSource) throws SQLException { + sampleDataGenerator = new SampleDataGenerator(dataSource); + sampleDataGenerator.generateSampleData(schemaName); + return sampleDataGenerator; + } } diff --git a/history/taskana-simplehistory-spring-test/src/test/java/pro/taskana/TaskHistoryEventControllerIntTest.java b/history/taskana-simplehistory-spring-test/src/test/java/pro/taskana/TaskHistoryEventControllerIntTest.java index 3a765d92e..62888b493 100644 --- a/history/taskana-simplehistory-spring-test/src/test/java/pro/taskana/TaskHistoryEventControllerIntTest.java +++ b/history/taskana-simplehistory-spring-test/src/test/java/pro/taskana/TaskHistoryEventControllerIntTest.java @@ -5,12 +5,12 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; import java.sql.SQLException; import java.time.LocalDateTime; import java.util.Collections; - import javax.sql.DataSource; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -35,171 +35,176 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; - import pro.taskana.exceptions.SystemException; import pro.taskana.rest.resource.TaskHistoryEventListResource; import pro.taskana.rest.simplehistory.TaskHistoryRestConfiguration; import pro.taskana.rest.simplehistory.sampledata.SampleDataGenerator; -/** - * Controller for integration test. - */ +/** Controller for integration test. */ @EnableAutoConfiguration @RunWith(SpringRunner.class) -@SpringBootTest(classes = {TaskHistoryRestConfiguration.class}, +@SpringBootTest( + classes = {TaskHistoryRestConfiguration.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class TaskHistoryEventControllerIntTest { - @Value("${taskana.schemaName:TASKANA}") - public String schemaName; + private static final Logger LOGGER = + LoggerFactory.getLogger(TaskHistoryEventControllerIntTest.class); + @Value("${taskana.schemaName:TASKANA}") + public String schemaName; + String server = "http://127.0.0.1:"; - private static final Logger LOGGER = LoggerFactory.getLogger(TaskHistoryEventControllerIntTest.class); + RestTemplate template; - String server = "http://127.0.0.1:"; + HttpEntity request; - RestTemplate template; + @LocalServerPort int port; - HttpEntity request; + @Autowired private DataSource dataSource; - @LocalServerPort - int port; - - @Autowired - private DataSource dataSource; - - @Before - public void before() { - template = getRestTemplate(); - SampleDataGenerator sampleDataGenerator; - try { - sampleDataGenerator = new SampleDataGenerator(dataSource); - sampleDataGenerator.generateSampleData(schemaName); - } catch (SQLException e) { - throw new SystemException("tried to reset DB and caught Exception " + e, e); - } + @Before + public void before() { + template = getRestTemplate(); + SampleDataGenerator sampleDataGenerator; + try { + sampleDataGenerator = new SampleDataGenerator(dataSource); + sampleDataGenerator.generateSampleData(schemaName); + } catch (SQLException e) { + throw new SystemException("tried to reset DB and caught Exception " + e, e); } + } - @Test - public void testGetAllHistoryEvent() { - ResponseEntity response = template.exchange( - server + port + "/api/v1/task-history-event", HttpMethod.GET, request, - new ParameterizedTypeReference() { - }); - assertNotNull(response.getBody().getLink(Link.REL_SELF)); - assertEquals(50, response.getBody().getContent().size()); - } + @Test + public void testGetAllHistoryEvent() { + ResponseEntity response = + template.exchange( + server + port + "/api/v1/task-history-event", + HttpMethod.GET, + request, + new ParameterizedTypeReference() {}); + assertNotNull(response.getBody().getLink(Link.REL_SELF)); + assertEquals(50, response.getBody().getContent().size()); + } - @Test - public void testGetAllHistoryEventDescendingOrder() { - String parameters = "/api/v1/task-history-event?sort-by=business-process-id&order=desc&page-size=3&page=1"; - ResponseEntity response = template.exchange( - server + port + parameters, HttpMethod.GET, request, - new ParameterizedTypeReference() { - }); - assertNotNull(response.getBody().getLink(Link.REL_SELF)); - assertEquals(3, response.getBody().getContent().size()); - assertTrue(response.getBody() - .getLink(Link.REL_SELF) - .getHref() - .endsWith(parameters)); - } + @Test + public void testGetAllHistoryEventDescendingOrder() { + String parameters = + "/api/v1/task-history-event?sort-by=business-process-id&order=desc&page-size=3&page=1"; + ResponseEntity response = + template.exchange( + server + port + parameters, + HttpMethod.GET, + request, + new ParameterizedTypeReference() {}); + assertNotNull(response.getBody().getLink(Link.REL_SELF)); + assertEquals(3, response.getBody().getContent().size()); + assertTrue(response.getBody().getLink(Link.REL_SELF).getHref().endsWith(parameters)); + } - @Test - public void testGetSpecificTaskHistoryEvent() { - ResponseEntity response = template.exchange( - server + port + @Test + public void testGetSpecificTaskHistoryEvent() { + ResponseEntity response = + template.exchange( + server + + port + "/api/v1/task-history-event?business-process-id=BPI:01&sort-by=business-process-id&order=asc&page-size=6&page=1", - HttpMethod.GET, request, - new ParameterizedTypeReference() { + HttpMethod.GET, + request, + new ParameterizedTypeReference() {}); - }); - assertNotNull(response.getBody().getLink(Link.REL_SELF)); - assertNotNull(response.getBody().getLinks()); - assertNotNull(response.getBody().getMetadata()); - assertEquals(1, response.getBody().getContent().size()); + assertNotNull(response.getBody().getLink(Link.REL_SELF)); + assertNotNull(response.getBody().getLinks()); + assertNotNull(response.getBody().getMetadata()); + assertEquals(1, response.getBody().getContent().size()); + } + + @Test + public void testThrowsExceptionIfInvalidFilterIsUsed() { + try { + template.exchange( + server + port + "/api/v1/task-history-event?invalid=BPI:01", + HttpMethod.GET, + request, + new ParameterizedTypeReference() {}); + fail(); + } catch (HttpClientErrorException e) { + assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); + assertTrue(e.getResponseBodyAsString().contains("[invalid]")); + } + } + + @Test + public void testGetHistoryEventOfDate() { + String currentTime = LocalDateTime.now().toString(); + + try { + template.exchange( + server + port + "/api/v1/task-history-event?created=" + currentTime, + HttpMethod.GET, + request, + new ParameterizedTypeReference() {}); + fail(); + } catch (HttpClientErrorException e) { + assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); + assertTrue(e.getResponseBodyAsString().contains(currentTime)); } - @Test - public void testThrowsExceptionIfInvalidFilterIsUsed() { - try { - template.exchange( - server + port + "/api/v1/task-history-event?invalid=BPI:01", HttpMethod.GET, request, - new ParameterizedTypeReference() { - }); - fail(); - } catch (HttpClientErrorException e) { - assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); - assertTrue(e.getResponseBodyAsString().contains("[invalid]")); - } - } + // correct Format 'yyyy-MM-dd' + currentTime = currentTime.substring(0, 10); + ResponseEntity response = + template.exchange( + server + port + "/api/v1/task-history-event?created=" + currentTime, + HttpMethod.GET, + request, + new ParameterizedTypeReference() {}); + assertNotNull(response.getBody().getLink(Link.REL_SELF)); + assertEquals(25, response.getBody().getContent().size()); + } - @Test - public void testGetHistoryEventOfDate() { - String currentTime = LocalDateTime.now().toString(); + @Test + public void testGetSecondPageSortedByKey() { + String parameters = + "/api/v1/task-history-event?sort-by=workbasket-key&order=desc&page=2&page-size=2"; + ResponseEntity response = + template.exchange( + server + port + parameters, + HttpMethod.GET, + request, + new ParameterizedTypeReference() {}); - try { - template.exchange( - server + port + "/api/v1/task-history-event?created=" + currentTime, HttpMethod.GET, request, - new ParameterizedTypeReference() { - }); - fail(); - } catch (HttpClientErrorException e) { - assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); - assertTrue(e.getResponseBodyAsString().contains(currentTime)); - } - - // correct Format 'yyyy-MM-dd' - currentTime = currentTime.substring(0, 10); - ResponseEntity response = template.exchange( - server + port + "/api/v1/task-history-event?created=" + currentTime, HttpMethod.GET, request, - new ParameterizedTypeReference() { - }); - assertNotNull(response.getBody().getLink(Link.REL_SELF)); - assertEquals(25, response.getBody().getContent().size()); - } - - @Test - public void testGetSecondPageSortedByKey() { - String parameters = "/api/v1/task-history-event?sort-by=workbasket-key&order=desc&page=2&page-size=2"; - ResponseEntity response = template.exchange( - server + port + parameters, HttpMethod.GET, request, - new ParameterizedTypeReference() { - - }); - assertEquals(2, response.getBody().getContent().size()); - assertEquals("WBI:100000000000000000000000000000000002", - response.getBody().getContent().iterator().next().getWorkbasketKey()); - assertNotNull(response.getBody().getLink(Link.REL_SELF)); - assertTrue(response.getBody() - .getLink(Link.REL_SELF) - .getHref() - .endsWith(parameters)); - assertNotNull(response.getBody().getLink("allTaskHistoryEvent")); - assertTrue(response.getBody() + assertEquals(2, response.getBody().getContent().size()); + assertEquals( + "WBI:100000000000000000000000000000000002", + response.getBody().getContent().iterator().next().getWorkbasketKey()); + assertNotNull(response.getBody().getLink(Link.REL_SELF)); + assertTrue(response.getBody().getLink(Link.REL_SELF).getHref().endsWith(parameters)); + assertNotNull(response.getBody().getLink("allTaskHistoryEvent")); + assertTrue( + response + .getBody() .getLink("allTaskHistoryEvent") .getHref() .endsWith("/api/v1/task-history-event")); - assertNotNull(response.getBody().getLink(Link.REL_FIRST)); - assertNotNull(response.getBody().getLink(Link.REL_LAST)); - } + assertNotNull(response.getBody().getLink(Link.REL_FIRST)); + assertNotNull(response.getBody().getLink(Link.REL_LAST)); + } - /** - * Return a REST template which is capable of dealing with responses in HAL format. - * - * @return RestTemplate - */ - private RestTemplate getRestTemplate() { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.registerModule(new Jackson2HalModule()); + /** + * Return a REST template which is capable of dealing with responses in HAL format. + * + * @return RestTemplate + */ + private RestTemplate getRestTemplate() { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.registerModule(new Jackson2HalModule()); - MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); - converter.setSupportedMediaTypes(MediaType.parseMediaTypes("application/hal+json")); - converter.setObjectMapper(mapper); + MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); + converter.setSupportedMediaTypes(MediaType.parseMediaTypes("application/hal+json")); + converter.setObjectMapper(mapper); - RestTemplate template = new RestTemplate(Collections.> singletonList(converter)); - return template; - } + RestTemplate template = + new RestTemplate(Collections.>singletonList(converter)); + return template; + } } diff --git a/history/taskana-simplehistory-spring-test/src/test/java/pro/taskana/doc/api/TaskHistoryEventControllerRestDocumentation.java b/history/taskana-simplehistory-spring-test/src/test/java/pro/taskana/doc/api/TaskHistoryEventControllerRestDocumentation.java index f731412f6..fba70cdc0 100644 --- a/history/taskana-simplehistory-spring-test/src/test/java/pro/taskana/doc/api/TaskHistoryEventControllerRestDocumentation.java +++ b/history/taskana-simplehistory-spring-test/src/test/java/pro/taskana/doc/api/TaskHistoryEventControllerRestDocumentation.java @@ -10,7 +10,6 @@ import static org.springframework.restdocs.payload.PayloadDocumentation.response import static org.springframework.restdocs.payload.PayloadDocumentation.subsectionWithPath; import java.util.HashMap; - import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -30,168 +29,177 @@ import org.springframework.web.context.WebApplicationContext; import pro.taskana.rest.simplehistory.TaskHistoryRestConfiguration; -/** - * Generate documentation for the history event controller. - */ +/** Generate documentation for the history event controller. */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = TaskHistoryRestConfiguration.class, +@SpringBootTest( + classes = TaskHistoryRestConfiguration.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class TaskHistoryEventControllerRestDocumentation { - @LocalServerPort - int port; + @Rule public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); + @LocalServerPort int port; + @Autowired private WebApplicationContext context; - @Rule - public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); + private MockMvc mockMvc; - @Autowired - private WebApplicationContext context; + private HashMap taskHistoryEventFieldDescriptionsMap = + new HashMap(); - private MockMvc mockMvc; + private FieldDescriptor[] allTaskHistoryEventFieldDescriptors; - private HashMap taskHistoryEventFieldDescriptionsMap = new HashMap(); + private FieldDescriptor[] taskHistoryEventFieldDescriptors; - private FieldDescriptor[] allTaskHistoryEventFieldDescriptors; + @Before + public void setUp() { + document("{methodName}", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint())); - private FieldDescriptor[] taskHistoryEventFieldDescriptors; - - @Before - public void setUp() { - document("{methodName}", - preprocessRequest(prettyPrint()), - preprocessResponse(prettyPrint())); - - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation) - .operationPreprocessors() - .withResponseDefaults(prettyPrint()) - .withRequestDefaults(prettyPrint())) + this.mockMvc = + MockMvcBuilders.webAppContextSetup(this.context) + .apply( + documentationConfiguration(this.restDocumentation) + .operationPreprocessors() + .withResponseDefaults(prettyPrint()) + .withRequestDefaults(prettyPrint())) .build(); - taskHistoryEventFieldDescriptionsMap.put("taskHistoryId", "Unique ID"); - taskHistoryEventFieldDescriptionsMap.put("businessProcessId", "The id of the business process"); - taskHistoryEventFieldDescriptionsMap.put("parentBusinessProcessId", - "The id of the parent business process"); - taskHistoryEventFieldDescriptionsMap.put("taskId", "The id of the task"); - taskHistoryEventFieldDescriptionsMap.put("eventType", "The type of the event"); - taskHistoryEventFieldDescriptionsMap.put("created", "The time was created"); - taskHistoryEventFieldDescriptionsMap.put("userId", "The id of the user"); - taskHistoryEventFieldDescriptionsMap.put("domain", "Domain"); - taskHistoryEventFieldDescriptionsMap.put("workbasketKey", "The key of workbasket"); - taskHistoryEventFieldDescriptionsMap.put("porCompany", ""); - taskHistoryEventFieldDescriptionsMap.put("porSystem", ""); - taskHistoryEventFieldDescriptionsMap.put("porInstance", ""); - taskHistoryEventFieldDescriptionsMap.put("porValue", ""); - taskHistoryEventFieldDescriptionsMap.put("porType", ""); - taskHistoryEventFieldDescriptionsMap.put("taskClassificationKey", "The key of classification task"); - taskHistoryEventFieldDescriptionsMap.put("taskClassificationCategory", - "The category of classification"); - taskHistoryEventFieldDescriptionsMap.put("attachmentClassificationKey", ""); - taskHistoryEventFieldDescriptionsMap.put("comment", ""); - taskHistoryEventFieldDescriptionsMap.put("oldValue", "The old value"); - taskHistoryEventFieldDescriptionsMap.put("newValue", "The new value"); - taskHistoryEventFieldDescriptionsMap.put("custom1", "A custom property with name \"1\""); - taskHistoryEventFieldDescriptionsMap.put("custom2", "A custom property with name \"2\""); - taskHistoryEventFieldDescriptionsMap.put("custom3", "A custom property with name \"3\""); - taskHistoryEventFieldDescriptionsMap.put("custom4", "A custom property with name \"4\""); - taskHistoryEventFieldDescriptionsMap.put("oldData", "The old data"); - taskHistoryEventFieldDescriptionsMap.put("newData", "The new data"); - taskHistoryEventFieldDescriptionsMap.put("_links.self.href", "The links of this task history event"); - taskHistoryEventFieldDescriptionsMap.put("_links.allTaskHistoryEvent.href", "Link to all task history event"); - taskHistoryEventFieldDescriptionsMap.put("_links.first.href", "Link to the first result"); - taskHistoryEventFieldDescriptionsMap.put("_links.last.href", "Link to the last result"); + taskHistoryEventFieldDescriptionsMap.put("taskHistoryId", "Unique ID"); + taskHistoryEventFieldDescriptionsMap.put("businessProcessId", "The id of the business process"); + taskHistoryEventFieldDescriptionsMap.put( + "parentBusinessProcessId", "The id of the parent business process"); + taskHistoryEventFieldDescriptionsMap.put("taskId", "The id of the task"); + taskHistoryEventFieldDescriptionsMap.put("eventType", "The type of the event"); + taskHistoryEventFieldDescriptionsMap.put("created", "The time was created"); + taskHistoryEventFieldDescriptionsMap.put("userId", "The id of the user"); + taskHistoryEventFieldDescriptionsMap.put("domain", "Domain"); + taskHistoryEventFieldDescriptionsMap.put("workbasketKey", "The key of workbasket"); + taskHistoryEventFieldDescriptionsMap.put("porCompany", ""); + taskHistoryEventFieldDescriptionsMap.put("porSystem", ""); + taskHistoryEventFieldDescriptionsMap.put("porInstance", ""); + taskHistoryEventFieldDescriptionsMap.put("porValue", ""); + taskHistoryEventFieldDescriptionsMap.put("porType", ""); + taskHistoryEventFieldDescriptionsMap.put( + "taskClassificationKey", "The key of classification task"); + taskHistoryEventFieldDescriptionsMap.put( + "taskClassificationCategory", "The category of classification"); + taskHistoryEventFieldDescriptionsMap.put("attachmentClassificationKey", ""); + taskHistoryEventFieldDescriptionsMap.put("comment", ""); + taskHistoryEventFieldDescriptionsMap.put("oldValue", "The old value"); + taskHistoryEventFieldDescriptionsMap.put("newValue", "The new value"); + taskHistoryEventFieldDescriptionsMap.put("custom1", "A custom property with name \"1\""); + taskHistoryEventFieldDescriptionsMap.put("custom2", "A custom property with name \"2\""); + taskHistoryEventFieldDescriptionsMap.put("custom3", "A custom property with name \"3\""); + taskHistoryEventFieldDescriptionsMap.put("custom4", "A custom property with name \"4\""); + taskHistoryEventFieldDescriptionsMap.put("oldData", "The old data"); + taskHistoryEventFieldDescriptionsMap.put("newData", "The new data"); + taskHistoryEventFieldDescriptionsMap.put( + "_links.self.href", "The links of this task history event"); + taskHistoryEventFieldDescriptionsMap.put( + "_links.allTaskHistoryEvent.href", "Link to all task history event"); + taskHistoryEventFieldDescriptionsMap.put("_links.first.href", "Link to the first result"); + taskHistoryEventFieldDescriptionsMap.put("_links.last.href", "Link to the last result"); - allTaskHistoryEventFieldDescriptors = new FieldDescriptor[] { - subsectionWithPath("taskHistoryEvents").description("An array of Task history event"), - fieldWithPath("_links.allTaskHistoryEvent.href").ignored(), - fieldWithPath("_links.self.href").ignored(), - fieldWithPath("_links.first.href").ignored(), - fieldWithPath("_links.last.href").ignored(), - fieldWithPath("_links.next.href").ignored(), - fieldWithPath("page.size").ignored(), - fieldWithPath("page.totalElements").ignored(), - fieldWithPath("page.totalPages").ignored(), - fieldWithPath("page.number").ignored() + allTaskHistoryEventFieldDescriptors = + new FieldDescriptor[] { + subsectionWithPath("taskHistoryEvents").description("An array of Task history event"), + fieldWithPath("_links.allTaskHistoryEvent.href").ignored(), + fieldWithPath("_links.self.href").ignored(), + fieldWithPath("_links.first.href").ignored(), + fieldWithPath("_links.last.href").ignored(), + fieldWithPath("_links.next.href").ignored(), + fieldWithPath("page.size").ignored(), + fieldWithPath("page.totalElements").ignored(), + fieldWithPath("page.totalPages").ignored(), + fieldWithPath("page.number").ignored() }; - taskHistoryEventFieldDescriptors = new FieldDescriptor[] { - fieldWithPath("taskHistoryEvents[].taskHistoryId").description( - taskHistoryEventFieldDescriptionsMap.get("taskHistoryId")), - fieldWithPath("taskHistoryEvents[].businessProcessId").description( - taskHistoryEventFieldDescriptionsMap.get("businessProcessId")), - fieldWithPath("taskHistoryEvents[].parentBusinessProcessId").description( - taskHistoryEventFieldDescriptionsMap.get("parentBusinessProcessId")), - fieldWithPath("taskHistoryEvents[].taskId").description( - taskHistoryEventFieldDescriptionsMap.get("taskId")), - fieldWithPath("taskHistoryEvents[].eventType").description( - taskHistoryEventFieldDescriptionsMap.get("eventType")), - fieldWithPath("taskHistoryEvents[].created").description( - taskHistoryEventFieldDescriptionsMap.get("created")), - fieldWithPath("taskHistoryEvents[].userId").description( - taskHistoryEventFieldDescriptionsMap.get("userId")), - fieldWithPath("taskHistoryEvents[].domain").description( - taskHistoryEventFieldDescriptionsMap.get("domain")), - fieldWithPath("taskHistoryEvents[].workbasketKey").description( - taskHistoryEventFieldDescriptionsMap.get("workbasketKey")), - fieldWithPath("taskHistoryEvents[].porCompany").description( - taskHistoryEventFieldDescriptionsMap.get("porCompany")), - fieldWithPath("taskHistoryEvents[].porSystem").description( - taskHistoryEventFieldDescriptionsMap.get("porSystem")), - fieldWithPath("taskHistoryEvents[].porInstance").description( - taskHistoryEventFieldDescriptionsMap.get("porInstance")), - fieldWithPath("taskHistoryEvents[].porValue").description( - taskHistoryEventFieldDescriptionsMap.get("porValue")), - fieldWithPath("taskHistoryEvents[].porType").description( - taskHistoryEventFieldDescriptionsMap.get("porType")), - fieldWithPath("taskHistoryEvents[].taskClassificationKey").description( - taskHistoryEventFieldDescriptionsMap.get("taskClassificationKey")), - fieldWithPath("taskHistoryEvents[].taskClassificationCategory").description( - taskHistoryEventFieldDescriptionsMap.get("taskClassificationCategory")), - fieldWithPath("taskHistoryEvents[].attachmentClassificationKey").description( - taskHistoryEventFieldDescriptionsMap.get("attachmentClassificationKey")), - fieldWithPath("taskHistoryEvents[].comment").description( - taskHistoryEventFieldDescriptionsMap.get("comment")), - fieldWithPath("taskHistoryEvents[].oldValue").description( - taskHistoryEventFieldDescriptionsMap.get("oldValue")), - fieldWithPath("taskHistoryEvents[].newValue").description( - taskHistoryEventFieldDescriptionsMap.get("newValue")), - fieldWithPath("taskHistoryEvents[].custom1").description( - taskHistoryEventFieldDescriptionsMap.get("custom1")), - fieldWithPath("taskHistoryEvents[].custom2").description( - taskHistoryEventFieldDescriptionsMap.get("custom2")), - fieldWithPath("taskHistoryEvents[].custom3").description( - taskHistoryEventFieldDescriptionsMap.get("custom3")), - fieldWithPath("taskHistoryEvents[].custom4").description( - taskHistoryEventFieldDescriptionsMap.get("custom4")), - fieldWithPath("taskHistoryEvents[].oldData").description( - taskHistoryEventFieldDescriptionsMap.get("oldData")), - fieldWithPath("taskHistoryEvents[].newData").description( - taskHistoryEventFieldDescriptionsMap.get("newData")), - fieldWithPath("_links.self.href").ignored(), - fieldWithPath("page").ignored() + taskHistoryEventFieldDescriptors = + new FieldDescriptor[] { + fieldWithPath("taskHistoryEvents[].taskHistoryId") + .description(taskHistoryEventFieldDescriptionsMap.get("taskHistoryId")), + fieldWithPath("taskHistoryEvents[].businessProcessId") + .description(taskHistoryEventFieldDescriptionsMap.get("businessProcessId")), + fieldWithPath("taskHistoryEvents[].parentBusinessProcessId") + .description(taskHistoryEventFieldDescriptionsMap.get("parentBusinessProcessId")), + fieldWithPath("taskHistoryEvents[].taskId") + .description(taskHistoryEventFieldDescriptionsMap.get("taskId")), + fieldWithPath("taskHistoryEvents[].eventType") + .description(taskHistoryEventFieldDescriptionsMap.get("eventType")), + fieldWithPath("taskHistoryEvents[].created") + .description(taskHistoryEventFieldDescriptionsMap.get("created")), + fieldWithPath("taskHistoryEvents[].userId") + .description(taskHistoryEventFieldDescriptionsMap.get("userId")), + fieldWithPath("taskHistoryEvents[].domain") + .description(taskHistoryEventFieldDescriptionsMap.get("domain")), + fieldWithPath("taskHistoryEvents[].workbasketKey") + .description(taskHistoryEventFieldDescriptionsMap.get("workbasketKey")), + fieldWithPath("taskHistoryEvents[].porCompany") + .description(taskHistoryEventFieldDescriptionsMap.get("porCompany")), + fieldWithPath("taskHistoryEvents[].porSystem") + .description(taskHistoryEventFieldDescriptionsMap.get("porSystem")), + fieldWithPath("taskHistoryEvents[].porInstance") + .description(taskHistoryEventFieldDescriptionsMap.get("porInstance")), + fieldWithPath("taskHistoryEvents[].porValue") + .description(taskHistoryEventFieldDescriptionsMap.get("porValue")), + fieldWithPath("taskHistoryEvents[].porType") + .description(taskHistoryEventFieldDescriptionsMap.get("porType")), + fieldWithPath("taskHistoryEvents[].taskClassificationKey") + .description(taskHistoryEventFieldDescriptionsMap.get("taskClassificationKey")), + fieldWithPath("taskHistoryEvents[].taskClassificationCategory") + .description(taskHistoryEventFieldDescriptionsMap.get("taskClassificationCategory")), + fieldWithPath("taskHistoryEvents[].attachmentClassificationKey") + .description(taskHistoryEventFieldDescriptionsMap.get("attachmentClassificationKey")), + fieldWithPath("taskHistoryEvents[].comment") + .description(taskHistoryEventFieldDescriptionsMap.get("comment")), + fieldWithPath("taskHistoryEvents[].oldValue") + .description(taskHistoryEventFieldDescriptionsMap.get("oldValue")), + fieldWithPath("taskHistoryEvents[].newValue") + .description(taskHistoryEventFieldDescriptionsMap.get("newValue")), + fieldWithPath("taskHistoryEvents[].custom1") + .description(taskHistoryEventFieldDescriptionsMap.get("custom1")), + fieldWithPath("taskHistoryEvents[].custom2") + .description(taskHistoryEventFieldDescriptionsMap.get("custom2")), + fieldWithPath("taskHistoryEvents[].custom3") + .description(taskHistoryEventFieldDescriptionsMap.get("custom3")), + fieldWithPath("taskHistoryEvents[].custom4") + .description(taskHistoryEventFieldDescriptionsMap.get("custom4")), + fieldWithPath("taskHistoryEvents[].oldData") + .description(taskHistoryEventFieldDescriptionsMap.get("oldData")), + fieldWithPath("taskHistoryEvents[].newData") + .description(taskHistoryEventFieldDescriptionsMap.get("newData")), + fieldWithPath("_links.self.href").ignored(), + fieldWithPath("page").ignored() }; - } + } - @Test - public void getAllTaskHistoryEventDocTest() throws Exception { - this.mockMvc.perform( + @Test + public void getAllTaskHistoryEventDocTest() throws Exception { + this.mockMvc + .perform( RestDocumentationRequestBuilders.get( - "http://127.0.0.1:" + port + "/api/v1/task-history-event?page=1&page-size=3") + "http://127.0.0.1:" + port + "/api/v1/task-history-event?page=1&page-size=3") .accept("application/hal+json") .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("GetAllTaskHistoryEventDocTest", + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "GetAllTaskHistoryEventDocTest", responseFields(allTaskHistoryEventFieldDescriptors))); - } + } - @Test - public void getSpecificTaskHistoryEventDocTest() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders.get( - "http://127.0.0.1:" + port + "/api/v1/task-history-event?business-process-id=BPI:02") - .accept("application/hal+json") - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("GetSpecificTaskHistoryEventDocTest", + @Test + public void getSpecificTaskHistoryEventDocTest() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get( + "http://127.0.0.1:" + + port + + "/api/v1/task-history-event?business-process-id=BPI:02") + .accept("application/hal+json") + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "GetSpecificTaskHistoryEventDocTest", responseFields(taskHistoryEventFieldDescriptors))); - } + } } diff --git a/lib/taskana-cdi-example/src/main/java/pro/taskana/ExampleBootstrap.java b/lib/taskana-cdi-example/src/main/java/pro/taskana/ExampleBootstrap.java index 51ed947f3..2405208e3 100644 --- a/lib/taskana-cdi-example/src/main/java/pro/taskana/ExampleBootstrap.java +++ b/lib/taskana-cdi-example/src/main/java/pro/taskana/ExampleBootstrap.java @@ -15,37 +15,33 @@ import pro.taskana.exceptions.TaskAlreadyExistException; import pro.taskana.exceptions.TaskNotFoundException; import pro.taskana.exceptions.WorkbasketNotFoundException; -/** - * Example Bootstrap Application. - */ +/** Example Bootstrap Application. */ @ApplicationScoped public class ExampleBootstrap { - @EJB - private TaskanaEjb taskanaEjb; - - @PostConstruct - public void init(@Observes @Initialized(ApplicationScoped.class) Object init) - throws TaskNotFoundException, NotAuthorizedException, WorkbasketNotFoundException, - ClassificationNotFoundException, InvalidStateException, InvalidOwnerException, TaskAlreadyExistException, - InvalidArgumentException { - System.out.println("---------------------------> Start App"); - Task task = taskanaEjb.getTaskService().newTask(null); - ObjectReference objRef = new ObjectReference(); - objRef.setCompany("aCompany"); - objRef.setSystem("aSystem"); - objRef.setSystemInstance("anInstance"); - objRef.setType("aType"); - objRef.setValue("aValue"); - task.setPrimaryObjRef(objRef); - task = taskanaEjb.getTaskService().createTask(task); - System.out.println("---------------------------> Task started: " + task.getId()); - taskanaEjb.getTaskService().claim(task.getId()); - System.out.println( - "---------------------------> Task claimed: " - + taskanaEjb.getTaskService().getTask(task.getId()).getOwner()); - taskanaEjb.getTaskService().completeTask(task.getId()); - System.out.println("---------------------------> Task completed"); - } + @EJB private TaskanaEjb taskanaEjb; + @PostConstruct + public void init(@Observes @Initialized(ApplicationScoped.class) Object init) + throws TaskNotFoundException, NotAuthorizedException, WorkbasketNotFoundException, + ClassificationNotFoundException, InvalidStateException, InvalidOwnerException, + TaskAlreadyExistException, InvalidArgumentException { + System.out.println("---------------------------> Start App"); + Task task = taskanaEjb.getTaskService().newTask(null); + ObjectReference objRef = new ObjectReference(); + objRef.setCompany("aCompany"); + objRef.setSystem("aSystem"); + objRef.setSystemInstance("anInstance"); + objRef.setType("aType"); + objRef.setValue("aValue"); + task.setPrimaryObjRef(objRef); + task = taskanaEjb.getTaskService().createTask(task); + System.out.println("---------------------------> Task started: " + task.getId()); + taskanaEjb.getTaskService().claim(task.getId()); + System.out.println( + "---------------------------> Task claimed: " + + taskanaEjb.getTaskService().getTask(task.getId()).getOwner()); + taskanaEjb.getTaskService().completeTask(task.getId()); + System.out.println("---------------------------> Task completed"); + } } diff --git a/lib/taskana-cdi-example/src/main/java/pro/taskana/TaskanaEjb.java b/lib/taskana-cdi-example/src/main/java/pro/taskana/TaskanaEjb.java index a337772dd..664ccaad3 100644 --- a/lib/taskana-cdi-example/src/main/java/pro/taskana/TaskanaEjb.java +++ b/lib/taskana-cdi-example/src/main/java/pro/taskana/TaskanaEjb.java @@ -3,16 +3,13 @@ package pro.taskana; import javax.ejb.Stateless; import javax.inject.Inject; -/** - * example Taskana EJB. - */ +/** example Taskana EJB. */ @Stateless public class TaskanaEjb { - @Inject - private TaskService taskService; + @Inject private TaskService taskService; - public TaskService getTaskService() { - return taskService; - } + public TaskService getTaskService() { + return taskService; + } } diff --git a/lib/taskana-cdi/src/main/java/pro/taskana/TaskanaProducers.java b/lib/taskana-cdi/src/main/java/pro/taskana/TaskanaProducers.java index eb9624ec2..120f11fc9 100644 --- a/lib/taskana-cdi/src/main/java/pro/taskana/TaskanaProducers.java +++ b/lib/taskana-cdi/src/main/java/pro/taskana/TaskanaProducers.java @@ -6,7 +6,6 @@ import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.util.Properties; - import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Produces; @@ -15,71 +14,67 @@ import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pro.taskana.configuration.TaskanaEngineConfiguration; -/** - * TODO. - */ +/** TODO. */ @ApplicationScoped public class TaskanaProducers { - private static final Logger LOGGER = LoggerFactory.getLogger(TaskanaProducers.class); + private static final Logger LOGGER = LoggerFactory.getLogger(TaskanaProducers.class); - private static final String TASKANA_PROPERTIES = "taskana.properties"; + private static final String TASKANA_PROPERTIES = "taskana.properties"; - @Inject - private TaskanaEngine taskanaEngine; + @Inject private TaskanaEngine taskanaEngine; - private TaskanaEngineConfiguration taskanaEngineConfiguration; + private TaskanaEngineConfiguration taskanaEngineConfiguration; - @PostConstruct - public void init() { - // Load Properties and get Datasource via Context - // Load DataSource via Container - Context ctx; - DataSource dataSource; - ClassLoader classloader = Thread.currentThread().getContextClassLoader(); - try (InputStream propertyStream = classloader.getResourceAsStream(TASKANA_PROPERTIES)) { - Properties properties = new Properties(); - ctx = new InitialContext(); - properties.load(propertyStream); - dataSource = (DataSource) ctx.lookup(properties.getProperty("datasource.jndi")); - try (Connection connection = dataSource.getConnection()) { - DatabaseMetaData metaData = connection.getMetaData(); - LOGGER.debug("---------------> " + metaData); - } - this.taskanaEngineConfiguration = new TaskanaEngineConfiguration(dataSource, true, false, "TASKANA"); - } catch (NamingException | SQLException | IOException e) { - LOGGER.error("Could not start Taskana: ", e); - } + @PostConstruct + public void init() { + // Load Properties and get Datasource via Context + // Load DataSource via Container + Context ctx; + DataSource dataSource; + ClassLoader classloader = Thread.currentThread().getContextClassLoader(); + try (InputStream propertyStream = classloader.getResourceAsStream(TASKANA_PROPERTIES)) { + Properties properties = new Properties(); + ctx = new InitialContext(); + properties.load(propertyStream); + dataSource = (DataSource) ctx.lookup(properties.getProperty("datasource.jndi")); + try (Connection connection = dataSource.getConnection()) { + DatabaseMetaData metaData = connection.getMetaData(); + LOGGER.debug("---------------> " + metaData); + } + this.taskanaEngineConfiguration = + new TaskanaEngineConfiguration(dataSource, true, false, "TASKANA"); + } catch (NamingException | SQLException | IOException e) { + LOGGER.error("Could not start Taskana: ", e); } + } - @ApplicationScoped - @Produces - public TaskanaEngine generateTaskEngine() { - return taskanaEngineConfiguration.buildTaskanaEngine(); - } + @ApplicationScoped + @Produces + public TaskanaEngine generateTaskEngine() { + return taskanaEngineConfiguration.buildTaskanaEngine(); + } - @ApplicationScoped - @Produces - public TaskService generateTaskService() { - return taskanaEngine.getTaskService(); - } + @ApplicationScoped + @Produces + public TaskService generateTaskService() { + return taskanaEngine.getTaskService(); + } - @ApplicationScoped - @Produces - public ClassificationService generateClassificationService() { - return taskanaEngine.getClassificationService(); - } - - @ApplicationScoped - @Produces - public WorkbasketService generateWorkbasketService() { - return taskanaEngine.getWorkbasketService(); - } + @ApplicationScoped + @Produces + public ClassificationService generateClassificationService() { + return taskanaEngine.getClassificationService(); + } + @ApplicationScoped + @Produces + public WorkbasketService generateWorkbasketService() { + return taskanaEngine.getWorkbasketService(); + } } diff --git a/lib/taskana-cdi/src/test/java/pro/taskana/RestApplication.java b/lib/taskana-cdi/src/test/java/pro/taskana/RestApplication.java index e9db78234..3c2aaa986 100644 --- a/lib/taskana-cdi/src/test/java/pro/taskana/RestApplication.java +++ b/lib/taskana-cdi/src/test/java/pro/taskana/RestApplication.java @@ -3,9 +3,6 @@ package pro.taskana; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; -/** - * TODO Why does this test exist? - */ +/** TODO Why does this test exist? */ @ApplicationPath("/rest") -public class RestApplication extends Application { -} +public class RestApplication extends Application {} diff --git a/lib/taskana-cdi/src/test/java/pro/taskana/TaskanaEjb.java b/lib/taskana-cdi/src/test/java/pro/taskana/TaskanaEjb.java index f90180d05..332b88739 100644 --- a/lib/taskana-cdi/src/test/java/pro/taskana/TaskanaEjb.java +++ b/lib/taskana-cdi/src/test/java/pro/taskana/TaskanaEjb.java @@ -9,47 +9,42 @@ import pro.taskana.exceptions.NotAuthorizedException; import pro.taskana.exceptions.TaskAlreadyExistException; import pro.taskana.exceptions.WorkbasketNotFoundException; -/** - * TODO. - */ +/** TODO. */ @Stateless public class TaskanaEjb { - @Inject - private TaskService taskService; + @Inject private TaskService taskService; - @Inject - private ClassificationService classificationService; + @Inject private ClassificationService classificationService; - @Inject - private WorkbasketService workbasketService; + @Inject private WorkbasketService workbasketService; - public TaskService getTaskService() { - return taskService; - } + public TaskService getTaskService() { + return taskService; + } - public ClassificationService getClassificationService() { - return classificationService; - } + public ClassificationService getClassificationService() { + return classificationService; + } - public WorkbasketService getWorkbasketService() { - return workbasketService; - } + public WorkbasketService getWorkbasketService() { + return workbasketService; + } - public void triggerRollback() throws NotAuthorizedException, WorkbasketNotFoundException, - ClassificationNotFoundException, TaskAlreadyExistException, InvalidArgumentException { - Task task = taskService.newTask(null); - ObjectReference objRef = new ObjectReference(); - objRef.setCompany("aCompany"); - objRef.setSystem("aSystem"); - objRef.setSystemInstance("anInstance"); - objRef.setType("aType"); - objRef.setValue("aValue"); - task.setPrimaryObjRef(objRef); - - taskService.createTask(task); - System.out.println("---------------->" + task.getId()); - throw new RuntimeException(); - } + public void triggerRollback() + throws NotAuthorizedException, WorkbasketNotFoundException, ClassificationNotFoundException, + TaskAlreadyExistException, InvalidArgumentException { + Task task = taskService.newTask(null); + ObjectReference objRef = new ObjectReference(); + objRef.setCompany("aCompany"); + objRef.setSystem("aSystem"); + objRef.setSystemInstance("anInstance"); + objRef.setType("aType"); + objRef.setValue("aValue"); + task.setPrimaryObjRef(objRef); + taskService.createTask(task); + System.out.println("---------------->" + task.getId()); + throw new RuntimeException(); + } } diff --git a/lib/taskana-cdi/src/test/java/pro/taskana/TaskanaProducersTest.java b/lib/taskana-cdi/src/test/java/pro/taskana/TaskanaProducersTest.java index 55e464311..96d4cf54e 100644 --- a/lib/taskana-cdi/src/test/java/pro/taskana/TaskanaProducersTest.java +++ b/lib/taskana-cdi/src/test/java/pro/taskana/TaskanaProducersTest.java @@ -4,10 +4,8 @@ import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; - import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; - import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.Archive; @@ -17,64 +15,66 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.swarm.undertow.WARArchive; -/** - * TODO. - */ +/** TODO. */ @RunWith(Arquillian.class) public class TaskanaProducersTest { - @Deployment(testable = false) - public static Archive createDeployment() throws Exception { - WARArchive deployment = ShrinkWrap.create(WARArchive.class); - deployment.addPackage("pro.taskana"); - deployment.addClass(TaskanaProducers.class); - deployment.addAllDependencies(); - deployment.addDependency("org.mybatis:mybatis:3.4.2"); - deployment.addDependency("org.mybatis:mybatis-cdi:1.0.0"); - deployment.addDependency("pro.taskana:taskana-core"); - deployment.addAsResource("META-INF/beans.xml"); - deployment.addAsResource("taskana.properties"); - deployment.addAsResource("project-defaults.yml"); - return deployment; - } + @Deployment(testable = false) + public static Archive createDeployment() throws Exception { + WARArchive deployment = ShrinkWrap.create(WARArchive.class); + deployment.addPackage("pro.taskana"); + deployment.addClass(TaskanaProducers.class); + deployment.addAllDependencies(); + deployment.addDependency("org.mybatis:mybatis:3.4.2"); + deployment.addDependency("org.mybatis:mybatis-cdi:1.0.0"); + deployment.addDependency("pro.taskana:taskana-core"); + deployment.addAsResource("META-INF/beans.xml"); + deployment.addAsResource("taskana.properties"); + deployment.addAsResource("project-defaults.yml"); + return deployment; + } - @Test - public void testCommit() throws SQLException, ClassNotFoundException { + @Test + public void testCommit() throws SQLException, ClassNotFoundException { - Client client = ClientBuilder.newClient(); - client.target("http://127.0.0.1:8090/rest/test").request().get(); + Client client = ClientBuilder.newClient(); + client.target("http://127.0.0.1:8090/rest/test").request().get(); - Class.forName("org.h2.Driver"); - int resultCount = 0; - try (Connection conn = DriverManager.getConnection( + Class.forName("org.h2.Driver"); + int resultCount = 0; + try (Connection conn = + DriverManager.getConnection( "jdbc:h2:~/taskana-h2-data/testdb;AUTO_SERVER=TRUE;IGNORECASE=TRUE;LOCK_MODE=0", - "SA", "SA")) { - ResultSet rs = conn.createStatement().executeQuery("SELECT ID, OWNER FROM TASKANA.TASK"); + "SA", + "SA")) { + ResultSet rs = conn.createStatement().executeQuery("SELECT ID, OWNER FROM TASKANA.TASK"); - while (rs.next()) { - resultCount++; - } - } - Assert.assertEquals(0, resultCount); + while (rs.next()) { + resultCount++; + } } + Assert.assertEquals(0, resultCount); + } - @Test - public void testRollback() throws SQLException, ClassNotFoundException { - Client client = ClientBuilder.newClient(); - client.target("http://127.0.0.1:8090/rest/test").request().post(null); + @Test + public void testRollback() throws SQLException, ClassNotFoundException { + Client client = ClientBuilder.newClient(); + client.target("http://127.0.0.1:8090/rest/test").request().post(null); - Class.forName("org.h2.Driver"); - int resultCount = 0; - try (Connection conn = DriverManager.getConnection( + Class.forName("org.h2.Driver"); + int resultCount = 0; + try (Connection conn = + DriverManager.getConnection( "jdbc:h2:~/taskana-h2-data/testdb;AUTO_SERVER=TRUE;IGNORECASE=TRUE;LOCK_MODE=0", - "SA", "SA")) { - ResultSet rs = conn.createStatement().executeQuery("SELECT ID, OWNER FROM TASKANA.TASK"); + "SA", + "SA")) { + ResultSet rs = conn.createStatement().executeQuery("SELECT ID, OWNER FROM TASKANA.TASK"); - while (rs.next()) { - resultCount++; - } - } - - Assert.assertEquals(0, resultCount); + while (rs.next()) { + resultCount++; + } } + + Assert.assertEquals(0, resultCount); + } } diff --git a/lib/taskana-cdi/src/test/java/pro/taskana/TaskanaRestTest.java b/lib/taskana-cdi/src/test/java/pro/taskana/TaskanaRestTest.java index 8f35df6ba..97916c325 100644 --- a/lib/taskana-cdi/src/test/java/pro/taskana/TaskanaRestTest.java +++ b/lib/taskana-cdi/src/test/java/pro/taskana/TaskanaRestTest.java @@ -8,7 +8,6 @@ import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.Response; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -25,61 +24,60 @@ import pro.taskana.exceptions.TaskNotFoundException; import pro.taskana.exceptions.WorkbasketAlreadyExistException; import pro.taskana.exceptions.WorkbasketNotFoundException; -/** - * TODO. - */ +/** TODO. */ @Path("/test") public class TaskanaRestTest { - private static final Logger LOGGER = LoggerFactory.getLogger(TaskanaRestTest.class); + private static final Logger LOGGER = LoggerFactory.getLogger(TaskanaRestTest.class); - @EJB - private TaskanaEjb taskanaEjb; + @EJB private TaskanaEjb taskanaEjb; - @Inject - private ClassificationService classificationService; + @Inject private ClassificationService classificationService; - @GET - public Response startTask() throws NotAuthorizedException, WorkbasketNotFoundException, - ClassificationNotFoundException, ClassificationAlreadyExistException, InvalidWorkbasketException, - TaskAlreadyExistException, InvalidArgumentException, WorkbasketAlreadyExistException, DomainNotFoundException { - Workbasket workbasket = taskanaEjb.getWorkbasketService().newWorkbasket("key", "cdiDomain"); - workbasket.setName("wb"); - workbasket.setType(WorkbasketType.PERSONAL); - taskanaEjb.getWorkbasketService().createWorkbasket(workbasket); - Classification classification = classificationService.newClassification("TEST", "cdiDomain", "t1"); - taskanaEjb.getClassificationService().createClassification(classification); + @GET + public Response startTask() + throws NotAuthorizedException, WorkbasketNotFoundException, ClassificationNotFoundException, + ClassificationAlreadyExistException, InvalidWorkbasketException, + TaskAlreadyExistException, InvalidArgumentException, WorkbasketAlreadyExistException, + DomainNotFoundException { + Workbasket workbasket = taskanaEjb.getWorkbasketService().newWorkbasket("key", "cdiDomain"); + workbasket.setName("wb"); + workbasket.setType(WorkbasketType.PERSONAL); + taskanaEjb.getWorkbasketService().createWorkbasket(workbasket); + Classification classification = + classificationService.newClassification("TEST", "cdiDomain", "t1"); + taskanaEjb.getClassificationService().createClassification(classification); - Task task = taskanaEjb.getTaskService().newTask(workbasket.getKey()); - task.setClassificationKey(classification.getKey()); - ObjectReference objRef = new ObjectReference(); - objRef.setCompany("aCompany"); - objRef.setSystem("aSystem"); - objRef.setSystemInstance("anInstance"); - objRef.setType("aType"); - objRef.setValue("aValue"); - task.setPrimaryObjRef(objRef); + Task task = taskanaEjb.getTaskService().newTask(workbasket.getKey()); + task.setClassificationKey(classification.getKey()); + ObjectReference objRef = new ObjectReference(); + objRef.setCompany("aCompany"); + objRef.setSystem("aSystem"); + objRef.setSystemInstance("anInstance"); + objRef.setType("aType"); + objRef.setValue("aValue"); + task.setPrimaryObjRef(objRef); - Task result = taskanaEjb.getTaskService().createTask(task); + Task result = taskanaEjb.getTaskService().createTask(task); - LOGGER.info(result.getId() + ":" + result.getOwner()); - return Response.status(200).entity(result.getId()).build(); - } + LOGGER.info(result.getId() + ":" + result.getOwner()); + return Response.status(200).entity(result.getId()).build(); + } - @POST - public Response rollbackTask() - throws NotAuthorizedException, WorkbasketNotFoundException, ClassificationNotFoundException, - TaskAlreadyExistException, InvalidArgumentException { - taskanaEjb.triggerRollback(); - return Response.status(204).build(); - } - - @DELETE - @Path("{id}") - public void completeTask(@PathParam("id") String id) - throws TaskNotFoundException, InvalidOwnerException, InvalidStateException, NotAuthorizedException { - LOGGER.info(id); - taskanaEjb.getTaskService().forceCompleteTask(id); - } + @POST + public Response rollbackTask() + throws NotAuthorizedException, WorkbasketNotFoundException, ClassificationNotFoundException, + TaskAlreadyExistException, InvalidArgumentException { + taskanaEjb.triggerRollback(); + return Response.status(204).build(); + } + @DELETE + @Path("{id}") + public void completeTask(@PathParam("id") String id) + throws TaskNotFoundException, InvalidOwnerException, InvalidStateException, + NotAuthorizedException { + LOGGER.info(id); + taskanaEjb.getTaskService().forceCompleteTask(id); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/AbstractWorkbasketAccessItemQuery.java b/lib/taskana-core/src/main/java/pro/taskana/AbstractWorkbasketAccessItemQuery.java index b236f13f3..9d6f78bb1 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/AbstractWorkbasketAccessItemQuery.java +++ b/lib/taskana-core/src/main/java/pro/taskana/AbstractWorkbasketAccessItemQuery.java @@ -6,64 +6,58 @@ package pro.taskana; * @param the actual WorkbasketAccessItemQuery behind this interface class * @param the workbasket access item */ -public interface AbstractWorkbasketAccessItemQuery, T extends WorkbasketAccessItem> +public interface AbstractWorkbasketAccessItemQuery< + Q extends AbstractWorkbasketAccessItemQuery, T extends WorkbasketAccessItem> extends BaseQuery { - /** - * Add your unique entry id to your query as filter. - * - * @param ids - * the unique entry IDs - * @return the query - */ - Q idIn(String... ids); + /** + * Add your unique entry id to your query as filter. + * + * @param ids the unique entry IDs + * @return the query + */ + Q idIn(String... ids); - /** - * Add your workbasket id to your query. - * - * @param workbasketId - * the workbasket Id - * @return the query - */ - Q workbasketIdIn(String... workbasketId); + /** + * Add your workbasket id to your query. + * + * @param workbasketId the workbasket Id + * @return the query + */ + Q workbasketIdIn(String... workbasketId); - /** - * Add your accessIds to your query. - * - * @param accessId - * as access Ids - * @return the query - */ - Q accessIdIn(String... accessId); + /** + * Add your accessIds to your query. + * + * @param accessId as access Ids + * @return the query + */ + Q accessIdIn(String... accessId); - /** - * Sort the query result by workbasket id. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - Q orderByWorkbasketId(SortDirection sortDirection); + /** + * Sort the query result by workbasket id. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + Q orderByWorkbasketId(SortDirection sortDirection); - /** - * Sort the query result by access Id. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - Q orderByAccessId(SortDirection sortDirection); - - /** - * Sort the query result by Id. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - Q orderById(SortDirection sortDirection); + /** + * Sort the query result by access Id. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + Q orderByAccessId(SortDirection sortDirection); + /** + * Sort the query result by Id. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + Q orderById(SortDirection sortDirection); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/AccessItemQueryColumnName.java b/lib/taskana-core/src/main/java/pro/taskana/AccessItemQueryColumnName.java index b95ae9ad3..04a28f0fe 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/AccessItemQueryColumnName.java +++ b/lib/taskana-core/src/main/java/pro/taskana/AccessItemQueryColumnName.java @@ -1,24 +1,25 @@ package pro.taskana; /** - * Enum containing the column names for @see pro.taskana.mappings.QueryMapper#queryWorkbasketAccessItemColumnValues(WorkbasketAccessItemQuery). + * Enum containing the column names for @see + * pro.taskana.mappings.QueryMapper#queryWorkbasketAccessItemColumnValues(WorkbasketAccessItemQuery). * * @author jsa */ public enum AccessItemQueryColumnName implements QueryColumnName { + ID("id"), + WORKBASKET_ID("workbasket_id"), + WORKBASKET_KEY("wb.key"), + ACCESS_ID("access_id"); - ID("id"), - WORKBASKET_ID("workbasket_id"), - WORKBASKET_KEY("wb.key"), - ACCESS_ID("access_id"); + private String name; - private String name; - AccessItemQueryColumnName(String name) { - this.name = name; - } + AccessItemQueryColumnName(String name) { + this.name = name; + } - @Override - public String toString() { - return name; - } + @Override + public String toString() { + return name; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/Attachment.java b/lib/taskana-core/src/main/java/pro/taskana/Attachment.java index 1543c4721..6e094b235 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/Attachment.java +++ b/lib/taskana-core/src/main/java/pro/taskana/Attachment.java @@ -3,119 +3,112 @@ package pro.taskana; import java.time.Instant; import java.util.Map; -/** - * Attachment-Interface to specify Attachment Attributes. - */ +/** Attachment-Interface to specify Attachment Attributes. */ public interface Attachment { - /** - * Returns the current id of the attachment. - * - * @return ID of attachment - */ - String getId(); + /** + * Returns the current id of the attachment. + * + * @return ID of attachment + */ + String getId(); - /** - * Returns the id of the associated task. - * - * @return taskId - */ - String getTaskId(); + /** + * Returns the id of the associated task. + * + * @return taskId + */ + String getTaskId(); - /** - * Returns the time when the attachment was created. - * - * @return the created time as {@link Instant} - */ - Instant getCreated(); + /** + * Returns the time when the attachment was created. + * + * @return the created time as {@link Instant} + */ + Instant getCreated(); - /** - * Returns the time when the attachment was last modified. - * - * @return modified {@link Instant} of the attachment - */ - Instant getModified(); + /** + * Returns the time when the attachment was last modified. + * + * @return modified {@link Instant} of the attachment + */ + Instant getModified(); - /** - * Returns the classification summary of the attachment. - * - * @return the {@link ClassificationSummary} of this attachment - */ - ClassificationSummary getClassificationSummary(); + /** + * Returns the classification summary of the attachment. + * + * @return the {@link ClassificationSummary} of this attachment + */ + ClassificationSummary getClassificationSummary(); - /** - * Set the classification summary for this attachment. - * - * @param classificationSummary - * the {@link ClassificationSummary} for this attachment - */ - void setClassificationSummary(ClassificationSummary classificationSummary); + /** + * Set the classification summary for this attachment. + * + * @param classificationSummary the {@link ClassificationSummary} for this attachment + */ + void setClassificationSummary(ClassificationSummary classificationSummary); - /** - * Returns the {@link ObjectReference primaryObjectReference} of the attachment. - * - * @return {@link ObjectReference primaryObjectReference} of the attachment - **/ - ObjectReference getObjectReference(); + /** + * Returns the {@link ObjectReference primaryObjectReference} of the attachment. + * + * @return {@link ObjectReference primaryObjectReference} of the attachment + */ + ObjectReference getObjectReference(); - /** - * Sets the {@link ObjectReference primaryObjectReference} of the attachment. - * - * @param objectReference - * the {@link ObjectReference primaryObjectReference} of the attachment - */ - void setObjectReference(ObjectReference objectReference); + /** + * Sets the {@link ObjectReference primaryObjectReference} of the attachment. + * + * @param objectReference the {@link ObjectReference primaryObjectReference} of the attachment + */ + void setObjectReference(ObjectReference objectReference); - /** - * Returns the Channel on which the attachment was received. - * - * @return the Channel on which the attachment was received. - **/ - String getChannel(); + /** + * Returns the Channel on which the attachment was received. + * + * @return the Channel on which the attachment was received. + */ + String getChannel(); - /** - * Sets the Channel on which the attachment was received. - * - * @param channel - * the channel on which the attachment was received - */ - void setChannel(String channel); + /** + * Sets the Channel on which the attachment was received. + * + * @param channel the channel on which the attachment was received + */ + void setChannel(String channel); - /** - * Returns the time when this attachment was received. - * - * @return received time as exact {@link Instant} - */ - Instant getReceived(); + /** + * Returns the time when this attachment was received. + * + * @return received time as exact {@link Instant} + */ + Instant getReceived(); - /** - * Sets the time when the attachment was received. - * - * @param received - * the time as {@link Instant} when the attachment was received - **/ - void setReceived(Instant received); + /** + * Sets the time when the attachment was received. + * + * @param received the time as {@link Instant} when the attachment was received + */ + void setReceived(Instant received); - /** - * Returns the custom attributes of this attachment. - * - * @return customAttributes as {@link Map} - */ - Map getCustomAttributes(); + /** + * Returns the custom attributes of this attachment. + * + * @return customAttributes as {@link Map} + */ + Map getCustomAttributes(); - /** - * Sets the custom attribute Map of the attachment. - * - * @param customAttributes - * a {@link Map} that contains the custom attributes of the attachment as key, value pairs - */ - void setCustomAttributes(Map customAttributes); - - /** - * Return a summary of the current Attachment. - * - * @return the AttachmentSummary object for the current attachment - */ - AttachmentSummary asSummary(); + /** + * Sets the custom attribute Map of the attachment. + * + * @param customAttributes a {@link Map} that contains the custom attributes of the attachment as + * key, value pairs + */ + void setCustomAttributes(Map customAttributes); + /** + * Return a summary of the current Attachment. + * + * @return the AttachmentSummary object for the current attachment + */ + AttachmentSummary asSummary(); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/AttachmentSummary.java b/lib/taskana-core/src/main/java/pro/taskana/AttachmentSummary.java index dd85d802a..35cae1e1f 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/AttachmentSummary.java +++ b/lib/taskana-core/src/main/java/pro/taskana/AttachmentSummary.java @@ -3,64 +3,64 @@ package pro.taskana; import java.time.Instant; /** - * Interface for AttachmentSummaries. This is a specific short model-object which only contains the most important - * information. + * Interface for AttachmentSummaries. This is a specific short model-object which only contains the + * most important information. */ public interface AttachmentSummary { - /** - * Gets the id of the attachment. - * - * @return attachmentId - */ - String getId(); + /** + * Gets the id of the attachment. + * + * @return attachmentId + */ + String getId(); - /** - * Gets the id of the associated task. - * - * @return taskId - */ - String getTaskId(); + /** + * Gets the id of the associated task. + * + * @return taskId + */ + String getTaskId(); - /** - * Gets the time when the attachment was created. - * - * @return the created Instant - */ - Instant getCreated(); + /** + * Gets the time when the attachment was created. + * + * @return the created Instant + */ + Instant getCreated(); - /** - * Gets the time when the attachment was last modified. - * - * @return the last modified Instant - */ - Instant getModified(); + /** + * Gets the time when the attachment was last modified. + * + * @return the last modified Instant + */ + Instant getModified(); - /** - * Gets the {@link ObjectReference primaryObjectReference} of the attachment. - * - * @return {@link ObjectReference primaryObjectReference} of the attachment - **/ - ObjectReference getObjectReference(); + /** + * Gets the {@link ObjectReference primaryObjectReference} of the attachment. + * + * @return {@link ObjectReference primaryObjectReference} of the attachment + */ + ObjectReference getObjectReference(); - /** - * Gets the Channel on which the attachment was received. - * - * @return the channel - **/ - String getChannel(); + /** + * Gets the Channel on which the attachment was received. + * + * @return the channel + */ + String getChannel(); - /** - * Gets the classificationSummary of the attachment. - * - * @return the classification summary - */ - ClassificationSummary getClassificationSummary(); + /** + * Gets the classificationSummary of the attachment. + * + * @return the classification summary + */ + ClassificationSummary getClassificationSummary(); - /** - * Gets the time when the attachment was received. - * - * @return received Instant - */ - Instant getReceived(); + /** + * Gets the time when the attachment was received. + * + * @return received Instant + */ + Instant getReceived(); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/BaseQuery.java b/lib/taskana-core/src/main/java/pro/taskana/BaseQuery.java index 01046d845..9f0f71634 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/BaseQuery.java +++ b/lib/taskana-core/src/main/java/pro/taskana/BaseQuery.java @@ -6,112 +6,105 @@ import java.util.List; * Main query interface. * * @author EH - * @param - * specifies the return type of the follwing methods - * @param - * specifies the type of the enum used + * @param specifies the return type of the follwing methods + * @param specifies the type of the enum used */ public interface BaseQuery & QueryColumnName> { - /** - * This method will return a list of defined {@link T} objects. In case of a TaskQuery, this method can throw a - * NotAuthorizedToQueryWorkbasketException. - * - * @return List containing elements of type T - */ - List list(); + /** + * This method will return a list of defined {@link T} objects. In case of a TaskQuery, this + * method can throw a NotAuthorizedToQueryWorkbasketException. + * + * @return List containing elements of type T + */ + List list(); - /** - * This method will return a list of defined {@link T} objects with specified offset and an limit. In case of a - * TaskQuery, this method can throw a NotAuthorizedToQueryWorkbasketException. - * - * @param offset - * index of the first element which should be returned. - * @param limit - * number of elements which should be returned beginning with offset. - * @return List containing elements of type T - */ - List list(int offset, int limit); + /** + * This method will return a list of defined {@link T} objects with specified offset and an limit. + * In case of a TaskQuery, this method can throw a NotAuthorizedToQueryWorkbasketException. + * + * @param offset index of the first element which should be returned. + * @param limit number of elements which should be returned beginning with offset. + * @return List containing elements of type T + */ + List list(int offset, int limit); - /** - * This method will return all currently existing values of a DB-Table once. The order of the returning values can - * be configured ASC oder DEC - DEFAULT at NULL is ASC.
- * All called orderBy()-Methods will be override. Just the current column-values will be ordered itself by the given - * direction. - * - * @param dbColumnName - * column name of a existing DB Table. - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return a list of all existing values. - */ - List listValues(U dbColumnName, SortDirection sortDirection); + /** + * This method will return all currently existing values of a DB-Table once. The order of the + * returning values can be configured ASC oder DEC - DEFAULT at NULL is ASC.
+ * All called orderBy()-Methods will be override. Just the current column-values will be ordered + * itself by the given direction. + * + * @param dbColumnName column name of a existing DB Table. + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return a list of all existing values. + */ + List listValues(U dbColumnName, SortDirection sortDirection); - /** - * This method will return all results for page X with a size of Y of the current query.
- * Negative pageNumber/size will be changed to 1 or 0 and the last page might contains less elements. In case of a - * TaskQuery, this method can throw a NotAuthorizedToQueryWorkbasketException. - * - * @param pageNumber - * current pagination page starting at 1. - * @param pageSize - * amount of elements for this page. - * @return resulList for the current query starting at X and returning max Y elements. - */ - default List listPage(int pageNumber, int pageSize) { - int offset = (pageNumber < 1) ? 0 : ((pageNumber - 1) * pageSize); - int limit = (pageSize < 0) ? 0 : pageSize; - return list(offset, limit); + /** + * This method will return all results for page X with a size of Y of the current query.
+ * Negative pageNumber/size will be changed to 1 or 0 and the last page might contains less + * elements. In case of a TaskQuery, this method can throw a + * NotAuthorizedToQueryWorkbasketException. + * + * @param pageNumber current pagination page starting at 1. + * @param pageSize amount of elements for this page. + * @return resulList for the current query starting at X and returning max Y elements. + */ + default List listPage(int pageNumber, int pageSize) { + int offset = (pageNumber < 1) ? 0 : ((pageNumber - 1) * pageSize); + int limit = (pageSize < 0) ? 0 : pageSize; + return list(offset, limit); + } + + /** + * This method will return a single object of {@link T}. In case of a TaskQuery, this method can + * throw a NotAuthorizedToQueryWorkbasketException. + * + * @return T a single object of given Type. + */ + T single(); + + /** + * Counting the amount of rows/results for the current query. This can be used for a pagination + * afterwards. In case of a TaskQuery, this method can throw a + * NotAuthorizedToQueryWorkbasketException. + * + * @return resultRowCount + */ + long count(); + + default String[] toUpperCopy(String... source) { + if (source == null || source.length == 0) { + return null; + } else { + String[] target = new String[source.length]; + for (int i = 0; i < source.length; i++) { + target[i] = source[i].toUpperCase(); + } + return target; + } + } + + /** + * Determines the sort direction. + * + * @author bbr + */ + enum SortDirection { + ASCENDING("ASC"), + DESCENDING("DESC"); + + private final String sortDirection; + + SortDirection(String sortDirection) { + this.sortDirection = sortDirection; } - /** - * This method will return a single object of {@link T}. In case of a TaskQuery, this method can throw a - * NotAuthorizedToQueryWorkbasketException. - * - * @return T a single object of given Type. - */ - T single(); - - /** - * Counting the amount of rows/results for the current query. This can be used for a pagination afterwards. In case - * of a TaskQuery, this method can throw a NotAuthorizedToQueryWorkbasketException. - * - * @return resultRowCount - */ - long count(); - - /** - * Determines the sort direction. - * - * @author bbr - */ - enum SortDirection { - ASCENDING("ASC"), - DESCENDING("DESC"); - - private final String sortDirection; - - SortDirection(String sortDirection) { - this.sortDirection = sortDirection; - } - - @Override - public String toString() { - return sortDirection; - } + @Override + public String toString() { + return sortDirection; } - - default String[] toUpperCopy(String... source) { - if (source == null || source.length == 0) { - return null; - } else { - String[] target = new String[source.length]; - for (int i = 0; i < source.length; i++) { - target[i] = source[i].toUpperCase(); - } - return target; - } - } - + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/BulkOperationResults.java b/lib/taskana-core/src/main/java/pro/taskana/BulkOperationResults.java index d46a7381a..e15a3db4b 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/BulkOperationResults.java +++ b/lib/taskana-core/src/main/java/pro/taskana/BulkOperationResults.java @@ -4,135 +4,132 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pro.taskana.impl.util.LoggerUtils; /** - * Returning type for a bulk db interaction with errors. This wrapper is storing them with a matching object ID. + * Returning type for a bulk db interaction with errors. This wrapper is storing them with a + * matching object ID. * - * @param - * unique keys for the logs. - * @param - * type of the stored informations + * @param unique keys for the logs. + * @param type of the stored informations */ public class BulkOperationResults { - private Map errorMap = new HashMap<>(); - private static final Logger LOGGER = LoggerFactory.getLogger(BulkOperationResults.class); + private static final Logger LOGGER = LoggerFactory.getLogger(BulkOperationResults.class); + private Map errorMap = new HashMap<>(); - /** - * Returning a list of current errors as map. If there are no errors the result will be empty. - * - * @return map of errors which can´t be null. - */ - public Map getErrorMap() { - return this.errorMap; + /** + * Returning a list of current errors as map. If there are no errors the result will be empty. + * + * @return map of errors which can´t be null. + */ + public Map getErrorMap() { + return this.errorMap; + } + + /** + * Adding an appearing error to the map and list them by a unique ID as key. NULL keys will be + * ignored. + * + * @param objectId unique key of a entity. + * @param error occurred error of a interaction with the entity + * @return status of adding the values. + */ + public boolean addError(K objectId, V error) { + boolean status = false; + try { + if (objectId != null) { + this.errorMap.put(objectId, error); + status = true; + } + } catch (Exception e) { + LOGGER.warn( + "Can´t add bulkoperation-error, because of a map failure. ID={}, error={} and current failure={}", + objectId, + error, + e); + } + return status; + } + + /** + * Returning the status of a bulk-error-log. + * + * @return true if there are logged errors. + */ + public boolean containsErrors() { + boolean isContainingErrors = false; + if (!this.errorMap.isEmpty()) { + isContainingErrors = true; + } + return isContainingErrors; + } + + /** + * Returns the stored error for a unique ID or NULL if there is no error stored or ID invalid. + * + * @param idKey which is mapped with an error + * @return stored error for ID + */ + public V getErrorForId(K idKey) { + V result = null; + if (idKey != null) { + result = this.errorMap.get(idKey); + } + return result; + } + + /** + * Returns the IDs of the Object with failed requests. + * + * @return a List of IDs that could not be processed successfully. + */ + public List getFailedIds() { + return new ArrayList<>(this.errorMap.keySet()); + } + + /** Clearing the map - all entries will be removed. */ + public void clearErrors() { + this.errorMap.clear(); + } + + /** + * Add all errors from another BulkOperationResult to this. + * + * @param log the other log + */ + public void addAllErrors(BulkOperationResults log) { + if (log != null && log.containsErrors()) { + List failedIds = log.getFailedIds(); + for (K id : failedIds) { + addError(id, log.getErrorForId(id)); + } + } + } + + /** + * Map from any exception type to Exception. + * + * @return map of errors which can´t be null. + */ + public BulkOperationResults mapBulkOperationResults() { + BulkOperationResults bulkLogMapped = new BulkOperationResults<>(); + + List failedIds = this.getFailedIds(); + for (K id : failedIds) { + bulkLogMapped.addError(id, (Exception) this.getErrorForId(id)); } - /** - * Adding an appearing error to the map and list them by a unique ID as key. NULL keys will be ignored. - * - * @param objectId - * unique key of a entity. - * @param error - * occurred error of a interaction with the entity - * @return status of adding the values. - */ - public boolean addError(K objectId, V error) { - boolean status = false; - try { - if (objectId != null) { - this.errorMap.put(objectId, error); - status = true; - } - } catch (Exception e) { - LOGGER.warn( - "Can´t add bulkoperation-error, because of a map failure. ID={}, error={} and current failure={}", - objectId, error, e); - } - return status; - } + return bulkLogMapped; + } - /** - * Returning the status of a bulk-error-log. - * - * @return true if there are logged errors. - */ - public boolean containsErrors() { - boolean isContainingErrors = false; - if (!this.errorMap.isEmpty()) { - isContainingErrors = true; - } - return isContainingErrors; - } - - /** - * Returns the stored error for a unique ID or NULL if there is no error stored or ID invalid. - * - * @param idKey - * which is mapped with an error - * @return stored error for ID - */ - public V getErrorForId(K idKey) { - V result = null; - if (idKey != null) { - result = this.errorMap.get(idKey); - } - return result; - } - - /** - * Returns the IDs of the Object with failed requests. - * - * @return a List of IDs that could not be processed successfully. - */ - public List getFailedIds() { - return new ArrayList<>(this.errorMap.keySet()); - } - - /** - * Clearing the map - all entries will be removed. - */ - public void clearErrors() { - this.errorMap.clear(); - } - - /** - * Add all errors from another BulkOperationResult to this. - * - * @param log - * the other log - */ - public void addAllErrors(BulkOperationResults log) { - if (log != null && log.containsErrors()) { - List failedIds = log.getFailedIds(); - for (K id : failedIds) { - addError(id, log.getErrorForId(id)); - } - } - } - - /** - * Map from any exception type to Exception. - * - * @return map of errors which can´t be null. - */ - public BulkOperationResults mapBulkOperationResults() { - BulkOperationResults bulkLogMapped = new BulkOperationResults<>(); - - List failedIds = this.getFailedIds(); - for (K id : failedIds) { - bulkLogMapped.addError(id, (Exception) this.getErrorForId(id)); - } - - return bulkLogMapped; - } - - @Override - public String toString() { - return "BulkOperationResults [BulkOperationResults= " + LoggerUtils.mapToString(this.errorMap) + "]"; - } + @Override + public String toString() { + return "BulkOperationResults [BulkOperationResults= " + + LoggerUtils.mapToString(this.errorMap) + + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/CallbackState.java b/lib/taskana-core/src/main/java/pro/taskana/CallbackState.java index 91e020dcc..ed9ab5fe8 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/CallbackState.java +++ b/lib/taskana-core/src/main/java/pro/taskana/CallbackState.java @@ -1,8 +1,12 @@ package pro.taskana; /** - * This enum contains all status of synchronization between a taskana task and a task in a remote system. + * This enum contains all status of synchronization between a taskana task and a task in a remote + * system. */ public enum CallbackState { - NONE, CALLBACK_PROCESSING_REQUIRED, CLAIMED, CALLBACK_PROCESSING_COMPLETED + NONE, + CALLBACK_PROCESSING_REQUIRED, + CLAIMED, + CALLBACK_PROCESSING_COMPLETED } diff --git a/lib/taskana-core/src/main/java/pro/taskana/Classification.java b/lib/taskana-core/src/main/java/pro/taskana/Classification.java index e74847447..ce9137a4a 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/Classification.java +++ b/lib/taskana-core/src/main/java/pro/taskana/Classification.java @@ -1,200 +1,183 @@ package pro.taskana; -import java.time.Instant; - import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.time.Instant; import pro.taskana.impl.ClassificationImpl; -/** - * Interface used to specify the Classification-Model. - */ +/** Interface used to specify the Classification-Model. */ @JsonDeserialize(as = ClassificationImpl.class) public interface Classification extends ClassificationSummary { - /** - * Set/Change a reference to the current parent classification via ID. EMPTY if there is no parent. - * - * @param parentId - * The ID of the parent classification. - */ - void setParentId(String parentId); + /** + * Set/Change a reference to the current parent classification via ID. EMPTY if there is no + * parent. + * + * @param parentId The ID of the parent classification. + */ + void setParentId(String parentId); - /** - * Set/Change a reference to the current parent classification via key. EMPTY if there is no parent. - * - * @param parentKey - * The key of the parent classification. - */ - void setParentKey(String parentKey); + /** + * Set/Change a reference to the current parent classification via key. EMPTY if there is no + * parent. + * + * @param parentKey The key of the parent classification. + */ + void setParentKey(String parentKey); - /** - * Set/Change the category of this classification. - * - * @param category - * The category of the classification. - */ - void setCategory(String category); + /** + * Set/Change the category of this classification. + * + * @param category The category of the classification. + */ + void setCategory(String category); - /** - * Get the current domain-name of this classification. - * - * @return domain name - */ - String getDomain(); + /** + * Get the current domain-name of this classification. + * + * @return domain name + */ + String getDomain(); - /** - * Get a flag if the classification if currently valid in the used domain. - * - * @return isValidInDomain - flag - */ - Boolean getIsValidInDomain(); + /** + * Get a flag if the classification if currently valid in the used domain. + * + * @return isValidInDomain - flag + */ + Boolean getIsValidInDomain(); - /** - * Set/Change the flag which marks the classification as valid/invalid in the currently used domain. - * - * @param isValidInDomain - * - flag - */ - void setIsValidInDomain(Boolean isValidInDomain); + /** + * Set/Change the flag which marks the classification as valid/invalid in the currently used + * domain. + * + * @param isValidInDomain - flag + */ + void setIsValidInDomain(Boolean isValidInDomain); - /** - * Get the timestamp when this classification was as created. - * - * @return created as instant - */ - Instant getCreated(); + /** + * Get the timestamp when this classification was as created. + * + * @return created as instant + */ + Instant getCreated(); - /** - * Get the timestamp when this classification was as modified the last time. - * - * @return modified as instant - */ - Instant getModified(); + /** + * Get the timestamp when this classification was as modified the last time. + * + * @return modified as instant + */ + Instant getModified(); - /** - * Set/Change the classification name. - * - * @param name - * the name of the Classification - */ - void setName(String name); + /** + * Set/Change the classification name. + * + * @param name the name of the Classification + */ + void setName(String name); - /** - * Get the description of a classification. - * - * @return description - */ - String getDescription(); + /** + * Get the description of a classification. + * + * @return description + */ + String getDescription(); - /** - * Set/Change the classification description. - * - * @param description - * the description of the Classification - */ - void setDescription(String description); + /** + * Set/Change the classification description. + * + * @param description the description of the Classification + */ + void setDescription(String description); - /** - * Set/Change the numeric priority of a classification. - * - * @param priority - * the Priority of the Classification - */ - void setPriority(int priority); + /** + * Set/Change the numeric priority of a classification. + * + * @param priority the Priority of the Classification + */ + void setPriority(int priority); - /** - * Set/Change the service level. - * - * @param serviceLevel - * the service level. Must be a String in ISO-8601 duration format. See the parse() method of - * {@code Duration} for details. - */ - void setServiceLevel(String serviceLevel); + /** + * Set/Change the service level. + * + * @param serviceLevel the service level. Must be a String in ISO-8601 duration format. See the + * parse() method of {@code Duration} for details. + */ + void setServiceLevel(String serviceLevel); - /** - * Get the logical name of the associated application entry point. - * - * @return applicationEntryPoint - */ - String getApplicationEntryPoint(); + /** + * Get the logical name of the associated application entry point. + * + * @return applicationEntryPoint + */ + String getApplicationEntryPoint(); - /** - * Set the logical name of the associated application entry point. - * - * @param applicationEntryPoint - * The application entry point - */ - void setApplicationEntryPoint(String applicationEntryPoint); + /** + * Set the logical name of the associated application entry point. + * + * @param applicationEntryPoint The application entry point + */ + void setApplicationEntryPoint(String applicationEntryPoint); - /** - * Set/Change the 1. custom-attribute. - * - * @param custom1 - * the first custom attribute - */ - void setCustom1(String custom1); + /** + * Set/Change the 1. custom-attribute. + * + * @param custom1 the first custom attribute + */ + void setCustom1(String custom1); - /** - * Set/Change the 2. custom-attribute. - * - * @param custom2 - * the second custom attribute - */ - void setCustom2(String custom2); + /** + * Set/Change the 2. custom-attribute. + * + * @param custom2 the second custom attribute + */ + void setCustom2(String custom2); - /** - * Set/Change the 3. custom-attribute. - * - * @param custom3 - * the third custom attribute - */ - void setCustom3(String custom3); + /** + * Set/Change the 3. custom-attribute. + * + * @param custom3 the third custom attribute + */ + void setCustom3(String custom3); - /** - * Set/Change the 4. custom-attribute. - * - * @param custom4 - * the fourth custom attribute - */ - void setCustom4(String custom4); + /** + * Set/Change the 4. custom-attribute. + * + * @param custom4 the fourth custom attribute + */ + void setCustom4(String custom4); - /** - * Set/Change the 5. custom-attribute. - * - * @param custom5 - * the fifth custom attribute - */ - void setCustom5(String custom5); + /** + * Set/Change the 5. custom-attribute. + * + * @param custom5 the fifth custom attribute + */ + void setCustom5(String custom5); - /** - * Set/Change the 6. custom-attribute. - * - * @param custom6 - * the sixth custom attribute - */ - void setCustom6(String custom6); + /** + * Set/Change the 6. custom-attribute. + * + * @param custom6 the sixth custom attribute + */ + void setCustom6(String custom6); - /** - * Set/Change the 7. custom-attribute. - * - * @param custom7 - * the seventh custom attribute - */ - void setCustom7(String custom7); + /** + * Set/Change the 7. custom-attribute. + * + * @param custom7 the seventh custom attribute + */ + void setCustom7(String custom7); - /** - * Set/Change the 8. custom-attribute. - * - * @param custom8 - * the eight custom attribute - */ - void setCustom8(String custom8); + /** + * Set/Change the 8. custom-attribute. + * + * @param custom8 the eight custom attribute + */ + void setCustom8(String custom8); - /** - * Return a summary of the current Classification. - * - * @return the ClassificationSummary object for the current classification - */ - ClassificationSummary asSummary(); + /** + * Return a summary of the current Classification. + * + * @return the ClassificationSummary object for the current classification + */ + ClassificationSummary asSummary(); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/ClassificationQuery.java b/lib/taskana-core/src/main/java/pro/taskana/ClassificationQuery.java index d1570fe4a..173c28cf4 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/ClassificationQuery.java +++ b/lib/taskana-core/src/main/java/pro/taskana/ClassificationQuery.java @@ -2,302 +2,269 @@ package pro.taskana; import pro.taskana.exceptions.InvalidArgumentException; -/** - * ClassificationQuery for generating dynamic sql. - */ -public interface ClassificationQuery extends BaseQuery { +/** ClassificationQuery for generating dynamic sql. */ +public interface ClassificationQuery + extends BaseQuery { - /** - * Add your key to your query. - * - * @param key - * as String - * @return the query - */ - ClassificationQuery keyIn(String... key); + /** + * Add your key to your query. + * + * @param key as String + * @return the query + */ + ClassificationQuery keyIn(String... key); - /** - * Add your Id to your query. - * - * @param id - * as String - * @return the query - */ - ClassificationQuery idIn(String... id); + /** + * Add your Id to your query. + * + * @param id as String + * @return the query + */ + ClassificationQuery idIn(String... id); - /** - * Add your parentIds to your query. - * - * @param parentId - * as an array of Strings - * @return the query - */ - ClassificationQuery parentIdIn(String... parentId); + /** + * Add your parentIds to your query. + * + * @param parentId as an array of Strings + * @return the query + */ + ClassificationQuery parentIdIn(String... parentId); - /** - * Add your parentKeys to your query. - * - * @param parentKey - * as an array of Strings - * @return the query - */ - ClassificationQuery parentKeyIn(String... parentKey); + /** + * Add your parentKeys to your query. + * + * @param parentKey as an array of Strings + * @return the query + */ + ClassificationQuery parentKeyIn(String... parentKey); - /** - * Add your category to your query. - * - * @param category - * as String - * @return the query - */ - ClassificationQuery categoryIn(String... category); + /** + * Add your category to your query. + * + * @param category as String + * @return the query + */ + ClassificationQuery categoryIn(String... category); - /** - * Add your type to your query. - * - * @param type - * as String - * @return the query - */ - ClassificationQuery typeIn(String... type); + /** + * Add your type to your query. + * + * @param type as String + * @return the query + */ + ClassificationQuery typeIn(String... type); - /** - * Add your domains to your query which are used as filter. - * - * @param domain - * or domains for filtering. - * @return the query - */ - ClassificationQuery domainIn(String... domain); + /** + * Add your domains to your query which are used as filter. + * + * @param domain or domains for filtering. + * @return the query + */ + ClassificationQuery domainIn(String... domain); - /** - * Add to your query if the Classification shall be valid in its domain. - * - * @param validInDomain - * a simple flag showing if domain is valid - * @return the query - */ - ClassificationQuery validInDomainEquals(Boolean validInDomain); + /** + * Add to your query if the Classification shall be valid in its domain. + * + * @param validInDomain a simple flag showing if domain is valid + * @return the query + */ + ClassificationQuery validInDomainEquals(Boolean validInDomain); - /** - * Add your created-Dates to your query. - * - * @param createdIn - * the {@link TimeInterval} within which the searched-for classifications were created. - * @return the query - */ - ClassificationQuery createdWithin(TimeInterval... createdIn); + /** + * Add your created-Dates to your query. + * + * @param createdIn the {@link TimeInterval} within which the searched-for classifications were + * created. + * @return the query + */ + ClassificationQuery createdWithin(TimeInterval... createdIn); - /** - * Add your modified-Dates to your query. - * - * @param modifiedIn - * the {@link TimeInterval} within which the searched-for classifications were modified the last time. - * @return the query - */ - ClassificationQuery modifiedWithin(TimeInterval... modifiedIn); + /** + * Add your modified-Dates to your query. + * + * @param modifiedIn the {@link TimeInterval} within which the searched-for classifications were + * modified the last time. + * @return the query + */ + ClassificationQuery modifiedWithin(TimeInterval... modifiedIn); - /** - * Add your name to your query. - * - * @param nameIn - * as String - * @return the query - */ - ClassificationQuery nameIn(String... nameIn); + /** + * Add your name to your query. + * + * @param nameIn as String + * @return the query + */ + ClassificationQuery nameIn(String... nameIn); - /** - * Add your name to your query. It will be compared in SQL with an LIKE. - * - * @param nameLike - * as String - * @return the query - */ - ClassificationQuery nameLike(String... nameLike); + /** + * Add your name to your query. It will be compared in SQL with an LIKE. + * + * @param nameLike as String + * @return the query + */ + ClassificationQuery nameLike(String... nameLike); - /** - * Add your description to your query. It will be compared in SQL with an LIKE. If you use a wildcard like % then it - * will be transmitted to the database. - * - * @param descriptionLike - * your description - * @return the query - */ - ClassificationQuery descriptionLike(String descriptionLike); + /** + * Add your description to your query. It will be compared in SQL with an LIKE. If you use a + * wildcard like % then it will be transmitted to the database. + * + * @param descriptionLike your description + * @return the query + */ + ClassificationQuery descriptionLike(String descriptionLike); - /** - * Add your priority to your query. - * - * @param priorities - * as integers - * @return the query - */ - ClassificationQuery priorityIn(int... priorities); + /** + * Add your priority to your query. + * + * @param priorities as integers + * @return the query + */ + ClassificationQuery priorityIn(int... priorities); - /** - * Add your serviceLevel to your query. - * - * @param serviceLevelIn - * as String - * @return the query - */ - ClassificationQuery serviceLevelIn(String... serviceLevelIn); + /** + * Add your serviceLevel to your query. + * + * @param serviceLevelIn as String + * @return the query + */ + ClassificationQuery serviceLevelIn(String... serviceLevelIn); - /** - * Add your serviceLevel to your query. It will be compared in SQL with an LIKE. - * - * @param serviceLevelLike - * as String - * @return the query - */ - ClassificationQuery serviceLevelLike(String... serviceLevelLike); + /** + * Add your serviceLevel to your query. It will be compared in SQL with an LIKE. + * + * @param serviceLevelLike as String + * @return the query + */ + ClassificationQuery serviceLevelLike(String... serviceLevelLike); - /** - * Add your applicationEntryPoint to your query. - * - * @param applicationEntryPointIn - * name of the applications entrypoint - * @return the query - */ - ClassificationQuery applicationEntryPointIn(String... applicationEntryPointIn); + /** + * Add your applicationEntryPoint to your query. + * + * @param applicationEntryPointIn name of the applications entrypoint + * @return the query + */ + ClassificationQuery applicationEntryPointIn(String... applicationEntryPointIn); - /** - * Add your applicationEntryPoint to your query. It will be compared in SQL with an LIKE. - * - * @param applicationEntryPointLike - * name of the applications entrypoint - * @return the query - */ - ClassificationQuery applicationEntryPointLike(String... applicationEntryPointLike); + /** + * Add your applicationEntryPoint to your query. It will be compared in SQL with an LIKE. + * + * @param applicationEntryPointLike name of the applications entrypoint + * @return the query + */ + ClassificationQuery applicationEntryPointLike(String... applicationEntryPointLike); - /** - * Add a custom to your query. - * - * @param num - * the number of the custom as String (eg "4") - * @param customIn - * filter for this custom - * @return the query - * @throws InvalidArgumentException - * when the number of the custom is incorrect. - */ - ClassificationQuery customAttributeIn(String num, String... customIn) throws InvalidArgumentException; + /** + * Add a custom to your query. + * + * @param num the number of the custom as String (eg "4") + * @param customIn filter for this custom + * @return the query + * @throws InvalidArgumentException when the number of the custom is incorrect. + */ + ClassificationQuery customAttributeIn(String num, String... customIn) + throws InvalidArgumentException; - /** - * Add a custom to your query. - * - * @param num - * the number of the custom as String (eg "4") - * @param customLike - * filter for this custom with a LIKE-query - * @return the query - * @throws InvalidArgumentException - * when the number of the custom is incorrect. - */ - ClassificationQuery customAttributeLike(String num, String... customLike) throws InvalidArgumentException; + /** + * Add a custom to your query. + * + * @param num the number of the custom as String (eg "4") + * @param customLike filter for this custom with a LIKE-query + * @return the query + * @throws InvalidArgumentException when the number of the custom is incorrect. + */ + ClassificationQuery customAttributeLike(String num, String... customLike) + throws InvalidArgumentException; - /** - * Sort the query result by key. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - ClassificationQuery orderByKey(SortDirection sortDirection); + /** + * Sort the query result by key. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + ClassificationQuery orderByKey(SortDirection sortDirection); - /** - * Sort the query result by the parent classification ID. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - ClassificationQuery orderByParentId(SortDirection sortDirection); + /** + * Sort the query result by the parent classification ID. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + ClassificationQuery orderByParentId(SortDirection sortDirection); - /** - * Sort the query result by the parent classification key. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - ClassificationQuery orderByParentKey(SortDirection sortDirection); + /** + * Sort the query result by the parent classification key. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + ClassificationQuery orderByParentKey(SortDirection sortDirection); - /** - * Sort the query result by category. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - ClassificationQuery orderByCategory(SortDirection sortDirection); + /** + * Sort the query result by category. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + ClassificationQuery orderByCategory(SortDirection sortDirection); - /** - * Sort the query result by domain. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - ClassificationQuery orderByDomain(SortDirection sortDirection); + /** + * Sort the query result by domain. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + ClassificationQuery orderByDomain(SortDirection sortDirection); - /** - * Sort the query result by name. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - ClassificationQuery orderByName(SortDirection sortDirection); + /** + * Sort the query result by name. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + ClassificationQuery orderByName(SortDirection sortDirection); - /** - * Sort the query result by service level. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - ClassificationQuery orderByServiceLevel(SortDirection sortDirection); + /** + * Sort the query result by service level. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + ClassificationQuery orderByServiceLevel(SortDirection sortDirection); - /** - * Sort the query result by priority. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - ClassificationQuery orderByPriority(SortDirection sortDirection); + /** + * Sort the query result by priority. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + ClassificationQuery orderByPriority(SortDirection sortDirection); - /** - * Sort the query result by the application entry point name. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - ClassificationQuery orderByApplicationEntryPoint(SortDirection sortDirection); - - /** - * Sort the query result by a custom. - * - * @param num - * the number of the custom as String (eg "4") - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - * @throws InvalidArgumentException - * when the number of the custom is incorrect. - */ - ClassificationQuery orderByCustomAttribute(String num, SortDirection sortDirection) throws InvalidArgumentException; + /** + * Sort the query result by the application entry point name. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + ClassificationQuery orderByApplicationEntryPoint(SortDirection sortDirection); + /** + * Sort the query result by a custom. + * + * @param num the number of the custom as String (eg "4") + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + * @throws InvalidArgumentException when the number of the custom is incorrect. + */ + ClassificationQuery orderByCustomAttribute(String num, SortDirection sortDirection) + throws InvalidArgumentException; } diff --git a/lib/taskana-core/src/main/java/pro/taskana/ClassificationQueryColumnName.java b/lib/taskana-core/src/main/java/pro/taskana/ClassificationQueryColumnName.java index c388c710f..6e80ad5e2 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/ClassificationQueryColumnName.java +++ b/lib/taskana-core/src/main/java/pro/taskana/ClassificationQueryColumnName.java @@ -1,42 +1,44 @@ package pro.taskana; /** - * Enum containing the column names for @see pro.taskana.mappings.QueryMapper#queryClassificationColumnValues(pro.taskana.impl.ClassificationQueryImpl). + * Enum containing the column names for @see + * pro.taskana.mappings.QueryMapper#queryClassificationColumnValues(pro.taskana.impl.ClassificationQueryImpl). * * @author jsa */ public enum ClassificationQueryColumnName implements QueryColumnName { - ID("id"), - KEY("key"), - PARENT_ID("parent_id"), - PARENT_KEY("parent_key"), - CATEGORY("category"), - TYPE("type"), - DOMAIN("domain"), - VALID_IN_DOMAIN("valid_in_domain"), - CREATED("created"), - MODIFIED("modified"), - NAME("name"), - DESCRIPTION("description"), - PRIORITY("priority"), - SERVICELEVEL("serviceLevel"), - APPLICATION_ENTRY_POINT("application_entry_point"), - CUSTOM_1("custom_1"), - CUSTOM_2("custom_2"), - CUSTOM_3("custom_3"), - CUSTOM_4("custom_4"), - CUSTOM_5("custom_5"), - CUSTOM_6("custom_6"), - CUSTOM_7("custom_7"), - CUSTOM_8("custom_8"); + ID("id"), + KEY("key"), + PARENT_ID("parent_id"), + PARENT_KEY("parent_key"), + CATEGORY("category"), + TYPE("type"), + DOMAIN("domain"), + VALID_IN_DOMAIN("valid_in_domain"), + CREATED("created"), + MODIFIED("modified"), + NAME("name"), + DESCRIPTION("description"), + PRIORITY("priority"), + SERVICELEVEL("serviceLevel"), + APPLICATION_ENTRY_POINT("application_entry_point"), + CUSTOM_1("custom_1"), + CUSTOM_2("custom_2"), + CUSTOM_3("custom_3"), + CUSTOM_4("custom_4"), + CUSTOM_5("custom_5"), + CUSTOM_6("custom_6"), + CUSTOM_7("custom_7"), + CUSTOM_8("custom_8"); - private String name; - ClassificationQueryColumnName(String name) { - this.name = name; - } + private String name; - @Override - public String toString() { - return name; - } + ClassificationQueryColumnName(String name) { + this.name = name; + } + + @Override + public String toString() { + return name; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/ClassificationService.java b/lib/taskana-core/src/main/java/pro/taskana/ClassificationService.java index 98c2dcdc9..60813084b 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/ClassificationService.java +++ b/lib/taskana-core/src/main/java/pro/taskana/ClassificationService.java @@ -8,125 +8,111 @@ import pro.taskana.exceptions.DomainNotFoundException; import pro.taskana.exceptions.InvalidArgumentException; import pro.taskana.exceptions.NotAuthorizedException; -/** - * This class manages the classifications. - */ +/** This class manages the classifications. */ public interface ClassificationService { - /** - * Get the Classification for key and domain. If there's no Classification in the given domain, return the - * Classification from the master domain. - * - * @param key - * the key of the searched-for classifications - * @param domain - * the domain of the searched-for classifications - * @return If exist: domain-specific classification, else master classification - * @throws ClassificationNotFoundException - * if no classification is found that matches the key either in domain or in the master domain. - */ - Classification getClassification(String key, String domain) throws ClassificationNotFoundException; + /** + * Get the Classification for key and domain. If there's no Classification in the given domain, + * return the Classification from the master domain. + * + * @param key the key of the searched-for classifications + * @param domain the domain of the searched-for classifications + * @return If exist: domain-specific classification, else master classification + * @throws ClassificationNotFoundException if no classification is found that matches the key + * either in domain or in the master domain. + */ + Classification getClassification(String key, String domain) + throws ClassificationNotFoundException; - /** - * Get the Classification by id. - * - * @param id - * the id of the searched-for classifications - * @return the classification identified by id - * @throws ClassificationNotFoundException - * if no classification is found that matches the id. - */ - Classification getClassification(String id) throws ClassificationNotFoundException; + /** + * Get the Classification by id. + * + * @param id the id of the searched-for classifications + * @return the classification identified by id + * @throws ClassificationNotFoundException if no classification is found that matches the id. + */ + Classification getClassification(String id) throws ClassificationNotFoundException; - /** - * Delete a classification with all child classifications. - * - * @param id - * the id of the searched-for classifications - * @throws ClassificationInUseException - * if there are Task existing, which refer to this classification. - * @throws ClassificationNotFoundException - * if for an domain no classification specification is found. - * @throws NotAuthorizedException - * if the current user is not member of role BUSINESS_ADMIN or ADMIN - */ - void deleteClassification(String id) - throws ClassificationInUseException, ClassificationNotFoundException, NotAuthorizedException; + /** + * Delete a classification with all child classifications. + * + * @param id the id of the searched-for classifications + * @throws ClassificationInUseException if there are Task existing, which refer to this + * classification. + * @throws ClassificationNotFoundException if for an domain no classification specification is + * found. + * @throws NotAuthorizedException if the current user is not member of role BUSINESS_ADMIN or + * ADMIN + */ + void deleteClassification(String id) + throws ClassificationInUseException, ClassificationNotFoundException, NotAuthorizedException; - /** - * Delete a classification with all child classifications. - * - * @param classificationKey - * the key of the classification you want to delete. - * @param domain - * the domains for which you want to delete the classification. if "", the function tries to delete the - * "master domain" classification and any other classification with this key. - * @throws ClassificationInUseException - * if there are Task existing, which refer to this classification. - * @throws ClassificationNotFoundException - * if for an domain no classification specification is found. - * @throws NotAuthorizedException - * if the current user is not member of role BUSINESS_ADMIN or ADMIN - */ - void deleteClassification(String classificationKey, String domain) - throws ClassificationInUseException, ClassificationNotFoundException, NotAuthorizedException; + /** + * Delete a classification with all child classifications. + * + * @param classificationKey the key of the classification you want to delete. + * @param domain the domains for which you want to delete the classification. if "", the function + * tries to delete the "master domain" classification and any other classification with this + * key. + * @throws ClassificationInUseException if there are Task existing, which refer to this + * classification. + * @throws ClassificationNotFoundException if for an domain no classification specification is + * found. + * @throws NotAuthorizedException if the current user is not member of role BUSINESS_ADMIN or + * ADMIN + */ + void deleteClassification(String classificationKey, String domain) + throws ClassificationInUseException, ClassificationNotFoundException, NotAuthorizedException; - /** - * Persists a new classification after adding default values.
- * The classification will be added to master-domain, too - if not already existing. - * - * @param classification - * the classification to insert - * @return classification which is persisted with unique ID. - * @throws ClassificationAlreadyExistException - * when the classification does already exists at the given domain. - * @throws NotAuthorizedException - * if the current user is not member of role BUSINESS_ADMIN or ADMIN - * @throws DomainNotFoundException - * if the domain does not exist in the configuration - * @throws InvalidArgumentException - * if the ServiceLevel property does not comply with the ISO 8601 specification - */ - Classification createClassification(Classification classification) - throws ClassificationAlreadyExistException, NotAuthorizedException, - DomainNotFoundException, InvalidArgumentException; + /** + * Persists a new classification after adding default values.
+ * The classification will be added to master-domain, too - if not already existing. + * + * @param classification the classification to insert + * @return classification which is persisted with unique ID. + * @throws ClassificationAlreadyExistException when the classification does already exists at the + * given domain. + * @throws NotAuthorizedException if the current user is not member of role BUSINESS_ADMIN or + * ADMIN + * @throws DomainNotFoundException if the domain does not exist in the configuration + * @throws InvalidArgumentException if the ServiceLevel property does not comply with the ISO 8601 + * specification + */ + Classification createClassification(Classification classification) + throws ClassificationAlreadyExistException, NotAuthorizedException, DomainNotFoundException, + InvalidArgumentException; - /** - * Updates a Classification. - * - * @param classification - * the Classification to update - * @return the updated Classification. - * @throws ClassificationNotFoundException - * when the classification OR it´s parent does not exist. - * @throws NotAuthorizedException - * when the caller got no ADMIN or BUSINESS_ADMIN permissions. - * @throws ConcurrencyException - * when the Classification was modified meanwhile and is not latest anymore. - * @throws InvalidArgumentException - * if the ServiceLevel property does not comply with the ISO 8601 specification - */ - Classification updateClassification(Classification classification) - throws ClassificationNotFoundException, NotAuthorizedException, ConcurrencyException, InvalidArgumentException; + /** + * Updates a Classification. + * + * @param classification the Classification to update + * @return the updated Classification. + * @throws ClassificationNotFoundException when the classification OR it´s parent does not exist. + * @throws NotAuthorizedException when the caller got no ADMIN or BUSINESS_ADMIN permissions. + * @throws ConcurrencyException when the Classification was modified meanwhile and is not latest + * anymore. + * @throws InvalidArgumentException if the ServiceLevel property does not comply with the ISO 8601 + * specification + */ + Classification updateClassification(Classification classification) + throws ClassificationNotFoundException, NotAuthorizedException, ConcurrencyException, + InvalidArgumentException; - /** - * This method provides a query builder for quering the database. - * - * @return a {@link ClassificationQuery} - */ - ClassificationQuery createClassificationQuery(); + /** + * This method provides a query builder for quering the database. + * + * @return a {@link ClassificationQuery} + */ + ClassificationQuery createClassificationQuery(); - /** - * Creating a new {@link Classification} with unchangeable default values. It will be only generated and is not - * persisted until CREATE-call. - * - * @param key - * the key of the classification - * @param domain - * the domain of the new classification - * @param type - * the type of the new classification - * @return classification to specify - */ - Classification newClassification(String key, String domain, String type); + /** + * Creating a new {@link Classification} with unchangeable default values. It will be only + * generated and is not persisted until CREATE-call. + * + * @param key the key of the classification + * @param domain the domain of the new classification + * @param type the type of the new classification + * @return classification to specify + */ + Classification newClassification(String key, String domain, String type); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/ClassificationSummary.java b/lib/taskana-core/src/main/java/pro/taskana/ClassificationSummary.java index fcc188439..5c991b5e0 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/ClassificationSummary.java +++ b/lib/taskana-core/src/main/java/pro/taskana/ClassificationSummary.java @@ -1,136 +1,135 @@ package pro.taskana; /** - * Interface for ClassificationSummaries. This is a specific short model-object which only requieres the most important - * informations. Specific ones can be load afterwards via ID. + * Interface for ClassificationSummaries. This is a specific short model-object which only requieres + * the most important informations. Specific ones can be load afterwards via ID. */ public interface ClassificationSummary { - /** - * Gets the id of the classification. - * - * @return classificationId - */ - String getId(); + /** + * Gets the id of the classification. + * + * @return classificationId + */ + String getId(); - /** - * Gets the key of the classification. - * - * @return classificationKey - */ - String getKey(); + /** + * Gets the key of the classification. + * + * @return classificationKey + */ + String getKey(); - /** - * Gets the category of the classification. - * - * @return classificationCategory - */ - String getCategory(); + /** + * Gets the category of the classification. + * + * @return classificationCategory + */ + String getCategory(); - /** - * Gets the type of the classification. - * - * @return classificationType - */ - String getType(); + /** + * Gets the type of the classification. + * + * @return classificationType + */ + String getType(); - /** - * Gets the domain of the classification. - * - * @return classificationDomain - */ - String getDomain(); + /** + * Gets the domain of the classification. + * + * @return classificationDomain + */ + String getDomain(); - /** - * Gets the name of the classification. - * - * @return classificationName - */ - String getName(); + /** + * Gets the name of the classification. + * + * @return classificationName + */ + String getName(); - /** - * Gets the ID of the parent classification. - * - * @return parentId - */ - String getParentId(); + /** + * Gets the ID of the parent classification. + * + * @return parentId + */ + String getParentId(); - /** - * Gets the key of the parent classification. - * - * @return parentKey - */ - String getParentKey(); + /** + * Gets the key of the parent classification. + * + * @return parentKey + */ + String getParentKey(); - /** - * Gets the service level of the parent classification. It is a String in ISO-8601 duration format. See the parse() - * method of {@code Duration} for details. - * - * @return the service level - */ - String getServiceLevel(); + /** + * Gets the service level of the parent classification. It is a String in ISO-8601 duration + * format. See the parse() method of {@code Duration} for details. + * + * @return the service level + */ + String getServiceLevel(); - /** - * Gets the priority of the classification. - * - * @return the priority - */ - int getPriority(); + /** + * Gets the priority of the classification. + * + * @return the priority + */ + int getPriority(); - /** - * Get the 1. custom-attribute. - * - * @return custom1 - */ - String getCustom1(); + /** + * Get the 1. custom-attribute. + * + * @return custom1 + */ + String getCustom1(); - /** - * Get the 2. custom-attribute. - * - * @return custom2 - */ - String getCustom2(); + /** + * Get the 2. custom-attribute. + * + * @return custom2 + */ + String getCustom2(); - /** - * Get the 3. custom-attribute. - * - * @return custom3 - */ - String getCustom3(); + /** + * Get the 3. custom-attribute. + * + * @return custom3 + */ + String getCustom3(); - /** - * Get the 4. custom-attribute. - * - * @return custom4 - */ - String getCustom4(); + /** + * Get the 4. custom-attribute. + * + * @return custom4 + */ + String getCustom4(); - /** - * Get the 5. custom-attribute. - * - * @return custom5 - */ - String getCustom5(); + /** + * Get the 5. custom-attribute. + * + * @return custom5 + */ + String getCustom5(); - /** - * Get the 6. custom-attribute. - * - * @return custom6 - */ - String getCustom6(); + /** + * Get the 6. custom-attribute. + * + * @return custom6 + */ + String getCustom6(); - /** - * Get the 7. custom-attribute. - * - * @return custom7 - */ - String getCustom7(); - - /** - * Get the 8. custom-attribute. - * - * @return custom8 - */ - String getCustom8(); + /** + * Get the 7. custom-attribute. + * + * @return custom7 + */ + String getCustom7(); + /** + * Get the 8. custom-attribute. + * + * @return custom8 + */ + String getCustom8(); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/CustomField.java b/lib/taskana-core/src/main/java/pro/taskana/CustomField.java index ecb3fa4db..73797f498 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/CustomField.java +++ b/lib/taskana-core/src/main/java/pro/taskana/CustomField.java @@ -1,23 +1,21 @@ package pro.taskana; -/** - * This enum contains the fields CUSTOM_1 - CUSTOM_10 for the task entity. - */ +/** This enum contains the fields CUSTOM_1 - CUSTOM_10 for the task entity. */ public enum CustomField { - CUSTOM_1, - CUSTOM_2, - CUSTOM_3, - CUSTOM_4, - CUSTOM_5, - CUSTOM_6, - CUSTOM_7, - CUSTOM_8, - CUSTOM_9, - CUSTOM_10, - CUSTOM_11, - CUSTOM_12, - CUSTOM_13, - CUSTOM_14, - CUSTOM_15, - CUSTOM_16 + CUSTOM_1, + CUSTOM_2, + CUSTOM_3, + CUSTOM_4, + CUSTOM_5, + CUSTOM_6, + CUSTOM_7, + CUSTOM_8, + CUSTOM_9, + CUSTOM_10, + CUSTOM_11, + CUSTOM_12, + CUSTOM_13, + CUSTOM_14, + CUSTOM_15, + CUSTOM_16 } diff --git a/lib/taskana-core/src/main/java/pro/taskana/JobService.java b/lib/taskana-core/src/main/java/pro/taskana/JobService.java index 8b3bfed7c..2b541be02 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/JobService.java +++ b/lib/taskana-core/src/main/java/pro/taskana/JobService.java @@ -2,18 +2,14 @@ package pro.taskana; import pro.taskana.jobs.ScheduledJob; -/** - * Service to manage the TASKANA jobs. - */ +/** Service to manage the TASKANA jobs. */ public interface JobService { - /** - * Create a schedule a new job. - * - * @param job - * {@link ScheduledJob} The job to be created. - * @return {@link ScheduledJob} The created job. - */ - ScheduledJob createJob(ScheduledJob job); - + /** + * Create a schedule a new job. + * + * @param job {@link ScheduledJob} The job to be created. + * @return {@link ScheduledJob} The created job. + */ + ScheduledJob createJob(ScheduledJob job); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/KeyDomain.java b/lib/taskana-core/src/main/java/pro/taskana/KeyDomain.java index 370a7b818..a60db0159 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/KeyDomain.java +++ b/lib/taskana-core/src/main/java/pro/taskana/KeyDomain.java @@ -7,74 +7,70 @@ package pro.taskana; */ public class KeyDomain { - private String key; - private String domain; + private String key; + private String domain; - public KeyDomain(String key, String domain) { - this.key = key; - this.domain = domain; + public KeyDomain(String key, String domain) { + this.key = key; + this.domain = domain; + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getDomain() { + return domain; + } + + public void setDomain(String domain) { + this.domain = domain; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((domain == null) ? 0 : domain.hashCode()); + result = prime * result + ((key == null) ? 0 : key.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; } - - public String getKey() { - return key; + if (obj == null) { + return false; } - - public void setKey(String key) { - this.key = key; + if (!getClass().isAssignableFrom(obj.getClass())) { + return false; } - - public String getDomain() { - return domain; + KeyDomain other = (KeyDomain) obj; + if (domain == null) { + if (other.domain != null) { + return false; + } + } else if (!domain.equals(other.domain)) { + return false; } - - public void setDomain(String domain) { - this.domain = domain; - } - - @Override - public String toString() { - return "KeyDomain [" - + "key=" + this.key - + ", domain=" + this.domain - + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((domain == null) ? 0 : domain.hashCode()); - result = prime * result + ((key == null) ? 0 : key.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!getClass().isAssignableFrom(obj.getClass())) { - return false; - } - KeyDomain other = (KeyDomain) obj; - if (domain == null) { - if (other.domain != null) { - return false; - } - } else if (!domain.equals(other.domain)) { - return false; - } - if (key == null) { - if (other.key != null) { - return false; - } - } else if (!key.equals(other.key)) { - return false; - } - return true; + if (key == null) { + if (other.key != null) { + return false; + } + } else if (!key.equals(other.key)) { + return false; } + return true; + } + @Override + public String toString() { + return "KeyDomain [" + "key=" + this.key + ", domain=" + this.domain + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/ObjectReference.java b/lib/taskana-core/src/main/java/pro/taskana/ObjectReference.java index 4e9b6298b..986ba76cf 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/ObjectReference.java +++ b/lib/taskana-core/src/main/java/pro/taskana/ObjectReference.java @@ -1,136 +1,143 @@ package pro.taskana; -/** - * ObjectReference entity. - */ +/** ObjectReference entity. */ public class ObjectReference { - private String id; - private String company; - private String system; - private String systemInstance; - private String type; - private String value; + private String id; + private String company; + private String system; + private String systemInstance; + private String type; + private String value; - public String getId() { - return id; + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getCompany() { + return company; + } + + public void setCompany(String company) { + this.company = company; + } + + public String getSystem() { + return system; + } + + public void setSystem(String system) { + this.system = system; + } + + public String getSystemInstance() { + return systemInstance; + } + + public void setSystemInstance(String systemInstance) { + this.systemInstance = systemInstance; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((company == null) ? 0 : company.hashCode()); + result = prime * result + ((system == null) ? 0 : system.hashCode()); + result = prime * result + ((systemInstance == null) ? 0 : systemInstance.hashCode()); + result = prime * result + ((type == null) ? 0 : type.hashCode()); + result = prime * result + ((value == null) ? 0 : value.hashCode()); + return result; + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; } - - public void setId(String id) { - this.id = id; + if (other == null) { + return false; } - - public String getCompany() { - return company; + if (!getClass().isAssignableFrom(other.getClass())) { + return false; } + ObjectReference o = (ObjectReference) other; - public void setCompany(String company) { - this.company = company; + if (id == null && o.id != null) { + return false; } - - public String getSystem() { - return system; + if (id != null && !(id.equals(o.id))) { + return false; } - - public void setSystem(String system) { - this.system = system; + if (company == null && o.company != null) { + return false; } - - public String getSystemInstance() { - return systemInstance; + if (company != null && !(company.equals(o.company))) { + return false; } - - public void setSystemInstance(String systemInstance) { - this.systemInstance = systemInstance; + if (system == null && o.system != null) { + return false; } - - public String getType() { - return type; + if (system != null && !(system.equals(o.system))) { + return false; } - - public void setType(String type) { - this.type = type; + if (systemInstance == null && o.systemInstance != null) { + return false; } - - public String getValue() { - return value; + if (systemInstance != null && !(systemInstance.equals(o.systemInstance))) { + return false; } - - public void setValue(String value) { - this.value = value; + if (type == null && o.type != null) { + return false; } - - @Override - public String toString() { - return "ObjectReference [" - + "id=" + this.id + ", company=" - + this.company + ", system=" + this.system - + ", systemInstance=" + this.systemInstance - + ", type=" + this.type + ", value=" + this.value + "]"; + if (type != null && !(type.equals(o.type))) { + return false; } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((company == null) ? 0 : company.hashCode()); - result = prime * result + ((system == null) ? 0 : system.hashCode()); - result = prime * result + ((systemInstance == null) ? 0 : systemInstance.hashCode()); - result = prime * result + ((type == null) ? 0 : type.hashCode()); - result = prime * result + ((value == null) ? 0 : value.hashCode()); - return result; + if (value == null && o.value != null) { + return false; } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (other == null) { - return false; - } - if (!getClass().isAssignableFrom(other.getClass())) { - return false; - } - ObjectReference o = (ObjectReference) other; - - if (id == null && o.id != null) { - return false; - } - if (id != null && !(id.equals(o.id))) { - return false; - } - if (company == null && o.company != null) { - return false; - } - if (company != null && !(company.equals(o.company))) { - return false; - } - if (system == null && o.system != null) { - return false; - } - if (system != null && !(system.equals(o.system))) { - return false; - } - if (systemInstance == null && o.systemInstance != null) { - return false; - } - if (systemInstance != null && !(systemInstance.equals(o.systemInstance))) { - return false; - } - if (type == null && o.type != null) { - return false; - } - if (type != null && !(type.equals(o.type))) { - return false; - } - if (value == null && o.value != null) { - return false; - } - if (value != null && !(value.equals(o.value))) { - return false; - } - return true; + if (value != null && !(value.equals(o.value))) { + return false; } + return true; + } + + @Override + public String toString() { + return "ObjectReference [" + + "id=" + + this.id + + ", company=" + + this.company + + ", system=" + + this.system + + ", systemInstance=" + + this.systemInstance + + ", type=" + + this.type + + ", value=" + + this.value + + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/ObjectReferenceQuery.java b/lib/taskana-core/src/main/java/pro/taskana/ObjectReferenceQuery.java index 56ab660a8..3e7729fe7 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/ObjectReferenceQuery.java +++ b/lib/taskana-core/src/main/java/pro/taskana/ObjectReferenceQuery.java @@ -1,52 +1,46 @@ package pro.taskana; -/** - * ObjectReferenceQuery for generating dynamic sql. - */ -public interface ObjectReferenceQuery extends BaseQuery { +/** ObjectReferenceQuery for generating dynamic sql. */ +public interface ObjectReferenceQuery + extends BaseQuery { - /** - * Add your company to your query. - * - * @param companies - * as Strings - * @return the query - */ - ObjectReferenceQuery companyIn(String... companies); + /** + * Add your company to your query. + * + * @param companies as Strings + * @return the query + */ + ObjectReferenceQuery companyIn(String... companies); - /** - * Add your system to your query. - * - * @param systems - * as Strings - * @return the query - */ - ObjectReferenceQuery systemIn(String... systems); + /** + * Add your system to your query. + * + * @param systems as Strings + * @return the query + */ + ObjectReferenceQuery systemIn(String... systems); - /** - * Add your systemInstance to your query. - * - * @param systemInstances - * as Strings - * @return the query - */ - ObjectReferenceQuery systemInstanceIn(String... systemInstances); + /** + * Add your systemInstance to your query. + * + * @param systemInstances as Strings + * @return the query + */ + ObjectReferenceQuery systemInstanceIn(String... systemInstances); - /** - * Add your type to your query. - * - * @param types - * as Strings - * @return the query - */ - ObjectReferenceQuery typeIn(String... types); + /** + * Add your type to your query. + * + * @param types as Strings + * @return the query + */ + ObjectReferenceQuery typeIn(String... types); - /** - * Add your value to your query. - * - * @param values - * as Strings - * @return the query - */ - ObjectReferenceQuery valueIn(String... values); + /** + * Add your value to your query. + * + * @param values as Strings + * @return the query + */ + ObjectReferenceQuery valueIn(String... values); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/ObjectReferenceQueryColumnName.java b/lib/taskana-core/src/main/java/pro/taskana/ObjectReferenceQueryColumnName.java index 776bb7ae9..b334e0d32 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/ObjectReferenceQueryColumnName.java +++ b/lib/taskana-core/src/main/java/pro/taskana/ObjectReferenceQueryColumnName.java @@ -1,26 +1,27 @@ package pro.taskana; /** - * Enum containing the column names for @see {@link pro.taskana.mappings.QueryMapper#queryObjectReferenceColumnValues(pro.taskana.impl.ObjectReferenceQueryImpl)}. + * Enum containing the column names for @see {@link + * pro.taskana.mappings.QueryMapper#queryObjectReferenceColumnValues(pro.taskana.impl.ObjectReferenceQueryImpl)}. * * @author jsa */ public enum ObjectReferenceQueryColumnName implements QueryColumnName { - ID("id"), - COMPANY("company"), - SYSTEM("system"), - SYSTEM_INSTANCE("system_instance"), - TYPE("type"), - VALUE("value"); + ID("id"), + COMPANY("company"), + SYSTEM("system"), + SYSTEM_INSTANCE("system_instance"), + TYPE("type"), + VALUE("value"); - private String name; - ObjectReferenceQueryColumnName(String name) { - this.name = name; - } + private String name; - @Override - public String toString() { - return name; - } + ObjectReferenceQueryColumnName(String name) { + this.name = name; + } + + @Override + public String toString() { + return name; + } } - diff --git a/lib/taskana-core/src/main/java/pro/taskana/QueryColumnName.java b/lib/taskana-core/src/main/java/pro/taskana/QueryColumnName.java index 10dbf9d5c..4a3f43856 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/QueryColumnName.java +++ b/lib/taskana-core/src/main/java/pro/taskana/QueryColumnName.java @@ -5,5 +5,4 @@ package pro.taskana; * * @author jsa */ -public interface QueryColumnName { -} +public interface QueryColumnName {} diff --git a/lib/taskana-core/src/main/java/pro/taskana/Task.java b/lib/taskana-core/src/main/java/pro/taskana/Task.java index ba5f93daa..9db317a0e 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/Task.java +++ b/lib/taskana-core/src/main/java/pro/taskana/Task.java @@ -6,376 +6,357 @@ import java.util.Map; import pro.taskana.exceptions.InvalidArgumentException; -/** - * task-Interface to specify attribute interactions. - */ +/** task-Interface to specify attribute interactions. */ public interface Task { - /** - * Returns the current id of the task. - * - * @return taskId - */ - String getId(); + /** + * The key that is used to supply Callback_state within the CallbackInfo map. The Callback_state + * is used predominantly by the taskana adapter. It controls synchronization between taskana and + * the external system. + */ + String CALLBACK_STATE = "callbackState"; - /** - * Returns the external id of the task. This Id can be used to correlate the task to a task in an external - * system and to enforce idempotency of task creation. If not set by the client, it will be set by taskana. - * - * @return external Id - */ - String getExternalId(); + /** + * Returns the current id of the task. + * + * @return taskId + */ + String getId(); - /** - * Sets the external Id. It can be used to correlate the task to a task in an external system. - * The external Id is enforced to be unique. An attempt to create a task with - * an existing external Id will be rejected. So, this Id can be used to enforce idempotency of task creation. - * The externalId can only be set before the task is persisted. Taskana rejects attempts to modify externalId. - * - * @param externalId the external Id - * - */ - void setExternalId(String externalId); + /** + * Returns the external id of the task. This Id can be used to correlate the task to a task in an + * external system and to enforce idempotency of task creation. If not set by the client, it will + * be set by taskana. + * + * @return external Id + */ + String getExternalId(); - /** - * Gets the UserId of the task-creator. - * - * @return creator - */ - String getCreator(); + /** + * Sets the external Id. It can be used to correlate the task to a task in an external system. The + * external Id is enforced to be unique. An attempt to create a task with an existing external Id + * will be rejected. So, this Id can be used to enforce idempotency of task creation. The + * externalId can only be set before the task is persisted. Taskana rejects attempts to modify + * externalId. + * + * @param externalId the external Id + */ + void setExternalId(String externalId); - /** - * Returns the time when the task was {@link TaskState#READY}. - * - * @return created as exact {@link Instant} - */ - Instant getCreated(); + /** + * Gets the UserId of the task-creator. + * + * @return creator + */ + String getCreator(); - /** - * Returns the time when the task was set to {@link TaskState#CLAIMED} by/to a user. - * - * @return claimed as exact {@link Instant} - */ - Instant getClaimed(); + /** + * Returns the time when the task was {@link TaskState#READY}. + * + * @return created as exact {@link Instant} + */ + Instant getCreated(); - /** - * Returns the time when the task was set into {@link TaskState#COMPLETED}. - * - * @return completed as exact {@link Instant} - */ - Instant getCompleted(); + /** + * Returns the time when the task was set to {@link TaskState#CLAIMED} by/to a user. + * + * @return claimed as exact {@link Instant} + */ + Instant getClaimed(); - /** - * Returns the time when the task was modified the last time. - * - * @return modified as exact {@link Instant} - */ - Instant getModified(); + /** + * Returns the time when the task was set into {@link TaskState#COMPLETED}. + * + * @return completed as exact {@link Instant} + */ + Instant getCompleted(); - /** - * Returns the time when the work on this task was planned to be started. - * - * @return planned as exact {@link Instant} - */ - Instant getPlanned(); + /** + * Returns the time when the task was modified the last time. + * + * @return modified as exact {@link Instant} + */ + Instant getModified(); - /** - * Sets the time when the work on this task should be started. - * - * @param planned - * as exact {@link Instant} - */ - void setPlanned(Instant planned); + /** + * Returns the time when the work on this task was planned to be started. + * + * @return planned as exact {@link Instant} + */ + Instant getPlanned(); - /** - * Returns the time when this task should be finished. - * - * @return due as exact {@link Instant} - */ - Instant getDue(); + /** + * Sets the time when the work on this task should be started. + * + * @param planned as exact {@link Instant} + */ + void setPlanned(Instant planned); - /** - * Sets the time when the work on this task should be finished. - * - * @param due - * as exact {@link Instant} - */ - void setDue(Instant due); + /** + * Returns the time when this task should be finished. + * + * @return due as exact {@link Instant} + */ + Instant getDue(); - /** - * Return the name of the current task. - * - * @return name of the task - */ - String getName(); + /** + * Sets the time when the work on this task should be finished. + * + * @param due as exact {@link Instant} + */ + void setDue(Instant due); - /** - * Sets the name of the current task. - * - * @param name - * the name of the task - */ - void setName(String name); + /** + * Return the name of the current task. + * + * @return name of the task + */ + String getName(); - /** - * Return the task-description. - * - * @return description of a task - */ - String getDescription(); + /** + * Sets the name of the current task. + * + * @param name the name of the task + */ + void setName(String name); - /** - * Sets the description of the task. - * - * @param description - * the description of the task - */ - void setDescription(String description); + /** + * Return the task-description. + * + * @return description of a task + */ + String getDescription(); - /** - * Returns the numeric priority of a task. - * - * @return priority of the task - */ - int getPriority(); + /** + * Sets the description of the task. + * + * @param description the description of the task + */ + void setDescription(String description); - /** - * Returns the current {@link TaskState} of the task. - * - * @return taskState - */ - TaskState getState(); + /** + * Returns the numeric priority of a task. + * + * @return priority of the task + */ + int getPriority(); - /** - * Returns the {@link ClassificationSummary} of the task. - * - * @return classification summary for the task - */ - ClassificationSummary getClassificationSummary(); + /** + * Returns the current {@link TaskState} of the task. + * + * @return taskState + */ + TaskState getState(); - /** - * Sets the Classification key that - together with the Domain from this task's work basket - selects the - * appropriate {@link Classification} for this task. - * - * @param classificationKey - * the classification key for the task - */ - void setClassificationKey(String classificationKey); + /** + * Returns the {@link ClassificationSummary} of the task. + * + * @return classification summary for the task + */ + ClassificationSummary getClassificationSummary(); - /** - * Returns the key of the Workbasket where the task is stored in. - * - * @return workbasketKey - */ - String getWorkbasketKey(); + /** + * Sets the Classification key that - together with the Domain from this task's work basket - + * selects the appropriate {@link Classification} for this task. + * + * @param classificationKey the classification key for the task + */ + void setClassificationKey(String classificationKey); - /** - * Returns the the Summary of the workbasket where the task is stored in. - * - * @return workbasketSummary - */ - WorkbasketSummary getWorkbasketSummary(); + /** + * Returns the key of the Workbasket where the task is stored in. + * + * @return workbasketKey + */ + String getWorkbasketKey(); - /** - * Returns the Domain, to which the Task belongs at this moment. - * - * @return domain the current domain of the task - */ - String getDomain(); + /** + * Returns the the Summary of the workbasket where the task is stored in. + * + * @return workbasketSummary + */ + WorkbasketSummary getWorkbasketSummary(); - /** - * Returns the businessProcessId of a task. - * - * @return businessProcessId Gets the business process id the task belongs to. - */ - String getBusinessProcessId(); + /** + * Returns the Domain, to which the Task belongs at this moment. + * + * @return domain the current domain of the task + */ + String getDomain(); - /** - * Sets the external business process id. - * - * @param businessProcessId - * Sets the business process id the task belongs to. - */ - void setBusinessProcessId(String businessProcessId); + /** + * Returns the businessProcessId of a task. + * + * @return businessProcessId Gets the business process id the task belongs to. + */ + String getBusinessProcessId(); - /** - * Returns the parentBusinessProcessId of a task. - * - * @return parentBusinessProcessId Gets the parent business process id the task belongs to - */ - String getParentBusinessProcessId(); + /** + * Sets the external business process id. + * + * @param businessProcessId Sets the business process id the task belongs to. + */ + void setBusinessProcessId(String businessProcessId); - /** - * Sets the parent business process id to group associated processes. - * - * @param parentBusinessProcessId - * Sets the parent business process id the task belongs to - */ - void setParentBusinessProcessId(String parentBusinessProcessId); + /** + * Returns the parentBusinessProcessId of a task. + * + * @return parentBusinessProcessId Gets the parent business process id the task belongs to + */ + String getParentBusinessProcessId(); - /** - * Return the id of the task-owner. - * - * @return taskOwnerId - */ - String getOwner(); + /** + * Sets the parent business process id to group associated processes. + * + * @param parentBusinessProcessId Sets the parent business process id the task belongs to + */ + void setParentBusinessProcessId(String parentBusinessProcessId); - /** - * Sets the ownerId of this task. - * - * @param taskOwnerId - * the user id of the task's owner - */ - void setOwner(String taskOwnerId); + /** + * Return the id of the task-owner. + * + * @return taskOwnerId + */ + String getOwner(); - /** - * Returns the {@link ObjectReference primaryObjectReference} of the task. - * - * @return primaryObjRef to task main-subject - */ - ObjectReference getPrimaryObjRef(); + /** + * Sets the ownerId of this task. + * + * @param taskOwnerId the user id of the task's owner + */ + void setOwner(String taskOwnerId); - /** - * Sets the {@link ObjectReference primaryObjectReference} of the task. - * - * @param primaryObjRef - * to task main-subject - */ - void setPrimaryObjRef(ObjectReference primaryObjRef); + /** + * Returns the {@link ObjectReference primaryObjectReference} of the task. + * + * @return primaryObjRef to task main-subject + */ + ObjectReference getPrimaryObjRef(); - /** - * Return the isRead-flag, which flags a task as viewed at least one time. - * - * @return isRead-flag - */ - boolean isRead(); + /** + * Sets the {@link ObjectReference primaryObjectReference} of the task. + * + * @param primaryObjRef to task main-subject + */ + void setPrimaryObjRef(ObjectReference primaryObjRef); - /** - * Return the isTransferred-flag, which flags a task as transfered into an other workbasket. - * - * @return isTransferred-flag - */ - boolean isTransferred(); + /** + * Return the isRead-flag, which flags a task as viewed at least one time. + * + * @return isRead-flag + */ + boolean isRead(); - /** - * Returns a Map of custom Attributes. - * - * @return customAttributes as {@link Map} - */ - Map getCustomAttributes(); + /** + * Return the isTransferred-flag, which flags a task as transfered into an other workbasket. + * + * @return isTransferred-flag + */ + boolean isTransferred(); - /** - * Sets a Map of custom Attributes. - * - * @param customAttributes - * a {@link Map} that contains the custom attributes - */ - void setCustomAttributes(Map customAttributes); + /** + * Returns a Map of custom Attributes. + * + * @return customAttributes as {@link Map} + */ + Map getCustomAttributes(); - /** - * Returns a Map of Callback info. - * - * @return callbackInfo as {@link Map} - */ - Map getCallbackInfo(); + /** + * Sets a Map of custom Attributes. + * + * @param customAttributes a {@link Map} that contains the custom attributes + */ + void setCustomAttributes(Map customAttributes); - /** - * Sets a Map of callback info. - * - * @param callbackInfo - * a {@link Map} that contains the callback info - */ - void setCallbackInfo(Map callbackInfo); + /** + * Returns a Map of Callback info. + * + * @return callbackInfo as {@link Map} + */ + Map getCallbackInfo(); - /** - * Return the value for custom Attribute number num. - * - * @param num - * identifies which custom attribute is requested. Taskana concatenates "custom_" with num and the - * resulting String must match the name of the database column that contains the custom attribute. Valid - * values are "1", "2" .. "16" - * @return the value of custom attribute number num - * @throws InvalidArgumentException - * if num has not a value of "1", "2" ... "16" - */ - String getCustomAttribute(String num) throws InvalidArgumentException; + /** + * Sets a Map of callback info. + * + * @param callbackInfo a {@link Map} that contains the callback info + */ + void setCallbackInfo(Map callbackInfo); - /** - * Sets the value for custom Attribute number num. - * - * @param num - * identifies which custom attribute is to be set. Taskana concatenates "custom_" with num and the - * resulting String must match the name of the database column that contains the custom attribute. Valid - * values are "1", "2" .. "16" - * @param value - * the value of the custom attribute to be set - * @throws InvalidArgumentException - * if num has not a value of "1", "2" ... "16" - */ - void setCustomAttribute(String num, String value) throws InvalidArgumentException; + /** + * Return the value for custom Attribute number num. + * + * @param num identifies which custom attribute is requested. Taskana concatenates "custom_" with + * num and the resulting String must match the name of the database column that contains the + * custom attribute. Valid values are "1", "2" .. "16" + * @return the value of custom attribute number num + * @throws InvalidArgumentException if num has not a value of "1", "2" ... "16" + */ + String getCustomAttribute(String num) throws InvalidArgumentException; - /** - * Add an attachment.
- * NULL will be ignored and an attachment with the same ID will be replaced by the newer one.
- * - * @param attachment - * the {@link Attachment attachment} to be added to the task - */ - void addAttachment(Attachment attachment); + /** + * Sets the value for custom Attribute number num. + * + * @param num identifies which custom attribute is to be set. Taskana concatenates "custom_" with + * num and the resulting String must match the name of the database column that contains the + * custom attribute. Valid values are "1", "2" .. "16" + * @param value the value of the custom attribute to be set + * @throws InvalidArgumentException if num has not a value of "1", "2" ... "16" + */ + void setCustomAttribute(String num, String value) throws InvalidArgumentException; - /** - * Return the attachments for this task.
- * Do not use List.add()/addAll() for adding Elements, because it can cause redundant data. Use addAttachment(). - * Clear() and remove() can be used, because it´s a controllable change. - * - * @return the {@link List list} of {@link Attachment attachments} for this task - */ - List getAttachments(); + /** + * Add an attachment.
+ * NULL will be ignored and an attachment with the same ID will be replaced by the newer one.
+ * + * @param attachment the {@link Attachment attachment} to be added to the task + */ + void addAttachment(Attachment attachment); - /** - * Returns the custom note for this Task. - * - * @return the custom note for this TAsk - */ - String getNote(); + /** + * Return the attachments for this task.
+ * Do not use List.add()/addAll() for adding Elements, because it can cause redundant data. Use + * addAttachment(). Clear() and remove() can be used, because it´s a controllable change. + * + * @return the {@link List list} of {@link Attachment attachments} for this task + */ + List getAttachments(); - /** - * Sets/Changing the custom note for this Task. - * - * @param note - * the custom note for this Task. - */ - void setNote(String note); + /** + * Returns the custom note for this Task. + * + * @return the custom note for this TAsk + */ + String getNote(); - /** - * Return a summary of the current Task. - * - * @return the TaskSummary object for the current task - */ - TaskSummary asSummary(); + /** + * Sets/Changing the custom note for this Task. + * + * @param note the custom note for this Task. + */ + void setNote(String note); - /** - * Removes an attachment of the current task locally, when the ID is represented and does return the removed - * attachment or null if there was no match.
- * The changed Task need to be updated calling the {@link TaskService#updateTask(Task)}. - * - * @param attachmentID - * ID of the attachment which should be removed. - * @return attachment which will be removed after updating OR null if there was no matching attachment - */ - Attachment removeAttachment(String attachmentID); + /** + * Return a summary of the current Task. + * + * @return the TaskSummary object for the current task + */ + TaskSummary asSummary(); - /** - * Returns the category of the current classification. - * - * @return classificationCategory - */ - String getClassificationCategory(); + /** + * Removes an attachment of the current task locally, when the ID is represented and does return + * the removed attachment or null if there was no match.
+ * The changed Task need to be updated calling the {@link TaskService#updateTask(Task)}. + * + * @param attachmentID ID of the attachment which should be removed. + * @return attachment which will be removed after updating OR null if there was no matching + * attachment + */ + Attachment removeAttachment(String attachmentID); - /** - * The key that is used to supply Callback_state within the CallbackInfo map. - * The Callback_state is used predominantly by the taskana adapter. It controls synchronization between taskana and the external system. - * - */ - String CALLBACK_STATE = "callbackState"; + /** + * Returns the category of the current classification. + * + * @return classificationCategory + */ + String getClassificationCategory(); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/TaskMonitorService.java b/lib/taskana-core/src/main/java/pro/taskana/TaskMonitorService.java index e02b81238..bec72fe6c 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/TaskMonitorService.java +++ b/lib/taskana-core/src/main/java/pro/taskana/TaskMonitorService.java @@ -3,62 +3,58 @@ package pro.taskana; import pro.taskana.report.CategoryReport; import pro.taskana.report.ClassificationReport; import pro.taskana.report.CustomFieldValueReport; -import pro.taskana.report.TimestampReport; import pro.taskana.report.TaskStatusReport; +import pro.taskana.report.TimestampReport; import pro.taskana.report.WorkbasketReport; -/** - * The Task Monitor Service manages operations on tasks regarding the monitoring. - */ +/** The Task Monitor Service manages operations on tasks regarding the monitoring. */ public interface TaskMonitorService { - /** - * Provides a {@link WorkbasketReport.Builder} for creating a {@link WorkbasketReport}, list the task ids of this report - * and list the values of an entered custom attribute. - * - * @return a {@link WorkbasketReport.Builder} - */ - WorkbasketReport.Builder createWorkbasketReportBuilder(); + /** + * Provides a {@link WorkbasketReport.Builder} for creating a {@link WorkbasketReport}, list the + * task ids of this report and list the values of an entered custom attribute. + * + * @return a {@link WorkbasketReport.Builder} + */ + WorkbasketReport.Builder createWorkbasketReportBuilder(); - /** - * Provides a {@link CategoryReport.Builder} for creating a {@link CategoryReport}, list the task ids of this report and list - * the values of an entered custom attribute. - * - * @return a {@link CategoryReport.Builder} - */ - CategoryReport.Builder createCategoryReportBuilder(); + /** + * Provides a {@link CategoryReport.Builder} for creating a {@link CategoryReport}, list the task + * ids of this report and list the values of an entered custom attribute. + * + * @return a {@link CategoryReport.Builder} + */ + CategoryReport.Builder createCategoryReportBuilder(); - /** - * Provides a {@link ClassificationReport.Builder} for creating a {@link ClassificationReport} or a - * DetailedClassificationReport, list the task ids of these reports and list the values of an entered custom - * attribute. - * - * @return a {@link ClassificationReport.Builder} - */ - ClassificationReport.Builder createClassificationReportBuilder(); + /** + * Provides a {@link ClassificationReport.Builder} for creating a {@link ClassificationReport} or + * a DetailedClassificationReport, list the task ids of these reports and list the values of an + * entered custom attribute. + * + * @return a {@link ClassificationReport.Builder} + */ + ClassificationReport.Builder createClassificationReportBuilder(); - /** - * Provides a {@link CustomFieldValueReport.Builder} for creating a {@link CustomFieldValueReport} and list the values of - * an entered custom attribute. - * - * @param customField - * the customField whose values should appear in the report - * @return a {@link CustomFieldValueReport.Builder} - */ - CustomFieldValueReport.Builder createCustomFieldValueReportBuilder(CustomField customField); + /** + * Provides a {@link CustomFieldValueReport.Builder} for creating a {@link CustomFieldValueReport} + * and list the values of an entered custom attribute. + * + * @param customField the customField whose values should appear in the report + * @return a {@link CustomFieldValueReport.Builder} + */ + CustomFieldValueReport.Builder createCustomFieldValueReportBuilder(CustomField customField); - /** - * Provides a {@link TaskStatusReport.Builder} for creating a {@link TaskStatusReport}. - * - * @return a {@link TaskStatusReport.Builder} - */ - TaskStatusReport.Builder createTaskStatusReportBuilder(); - - /** - * Provides a {@link TimestampReport.Builder} for creating a {@link TimestampReport}. - * - * @return a {@link TimestampReport.Builder} - */ - TimestampReport.Builder createTimestampReportBuilder(); + /** + * Provides a {@link TaskStatusReport.Builder} for creating a {@link TaskStatusReport}. + * + * @return a {@link TaskStatusReport.Builder} + */ + TaskStatusReport.Builder createTaskStatusReportBuilder(); + /** + * Provides a {@link TimestampReport.Builder} for creating a {@link TimestampReport}. + * + * @return a {@link TimestampReport.Builder} + */ + TimestampReport.Builder createTimestampReportBuilder(); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/TaskQuery.java b/lib/taskana-core/src/main/java/pro/taskana/TaskQuery.java index be540e0c7..ad7cb8348 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/TaskQuery.java +++ b/lib/taskana-core/src/main/java/pro/taskana/TaskQuery.java @@ -2,960 +2,872 @@ package pro.taskana; import pro.taskana.exceptions.InvalidArgumentException; -/** - * TaskQuery for generating dynamic sql. - */ +/** TaskQuery for generating dynamic sql. */ public interface TaskQuery extends BaseQuery { - /** - * Add your names to your query. - * - * @param names - * the names as Strings - * @return the query - */ - TaskQuery nameIn(String... names); - - /** - * Add your name for pattern matching to your query. It will be compared in SQL with the LIKE operator. You may use - * a wildcard like % to specify the pattern. If you specify multiple arguments they are combined with the OR - * keyword. - * - * @param names - * your names - * @return the query - */ - TaskQuery nameLike(String... names); - - /** - * Add your external ids to your query. - * - * @param externalIds - * the external ids as Strings - * @return the query - */ - TaskQuery externalIdIn(String... externalIds); - - /** - * Add your external id for pattern matching to your query. It will be compared in SQL with the LIKE operator. You may use - * a wildcard like % to specify the pattern. If you specify multiple arguments they are combined with the OR - * keyword. - * - * @param externalIds - * your external ids - * @return the query - */ - TaskQuery externalIdLike(String... externalIds); - - - /** - * Add the UserIds of the creator to your query. - * - * @param creators - * of the queried tasks - * @return the query - */ - TaskQuery creatorIn(String... creators); - - /** - * Add the UserIds of the creator for pattern matching to your query. It will be compared in SQL with the LIKE - * operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments they are - * combined with the OR keyword. - * - * @param creators - * of the queried tasks - * @return the query - */ - TaskQuery creatorLike(String... creators); - - /** - * Add your description for pattern matching to your query. It will be compared in SQL with the LIKE operator. You - * may use a wildcard like % to specify the pattern. If you specify multiple arguments they are combined with the OR - * keyword. - * - * @param description - * your description - * @return the query - */ - TaskQuery descriptionLike(String... description); - - /** - * Add your custom note for pattern matching to your query. It will be compared in SQL with the LIKE operator. You - * may use a wildcard like % to specify the pattern. If you specify multiple arguments they are combined with the OR - * keyword. - * - * @param note - * your custom note - * @return the query - */ - TaskQuery noteLike(String... note); - - /** - * Add your priorities to your query. - * - * @param priorities - * as a integer - * @return the query - */ - TaskQuery priorityIn(int... priorities); - - /** - * Add your state to your query. - * - * @param states - * the states as {@link TaskState} - * @return the query - */ - TaskQuery stateIn(TaskState... states); - - /** - * Exclude these states from your query. - * - * @param states - * the states as {@link TaskState} - * @return the query - */ - TaskQuery stateNotIn(TaskState... states); - - /** - * Add your classificationKey to your query. - * - * @param classificationKeys - * the classification key - * @return the query - */ - TaskQuery classificationKeyIn(String... classificationKeys); - - /** - * Exlude these classificationKeys from your query. - * - * @param classificationKeys - * the classification key - * @return the query - */ - TaskQuery classificationKeyNotIn(String... classificationKeys); - - /** - * Add your classificationKey for pattern matching to your query. It will be compared in SQL with the LIKE operator. - * You may use a wildcard like % to specify the pattern. If you specify multiple arguments they are combined with - * the OR keyword. - * - * @param classificationKeys - * the classification key - * @return the query - */ - TaskQuery classificationKeyLike(String... classificationKeys); - - /** - * Add your classificationId to your query. - * - * @param classificationIds - * the classification Ids - * @return the query - */ - TaskQuery classificationIdIn(String... classificationIds); - - /** - * Add your classificationCategory to your query. - * - * @param classificationCategories - * the classification category for filtering - * @return the query - */ - TaskQuery classificationCategoryIn(String... classificationCategories); - - /** - * Add your classificationCategory for pattern matching to your query. It will be compared in SQL with the LIKE - * operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments they are - * combined with the OR keyword. - * - * @param classificationCategories - * the classification categories for filtering - * @return the query - */ - TaskQuery classificationCategoryLike(String... classificationCategories); - - /** - * Add your classificationName to your query. - * - * @param classificationNames - * the classification name - * @return the query - */ - TaskQuery classificationNameIn(String... classificationNames); - - /** - * Add your classificationName for pattern matching to your query. It will be compared in SQL with the LIKE operator. - * You may use a wildcard like % to specify the pattern. If you specify multiple arguments they are combined with - * the OR keyword. - * * - * @param classificationNames - * the classification name - * @return the query - */ - TaskQuery classificationNameLike(String... classificationNames); - - /** - * Add your workbasket key to the query. - * - * @param workbasketIdentifiers - * the key - domain combinations that identify workbaskets - * @return the query - */ - TaskQuery workbasketKeyDomainIn(KeyDomain... workbasketIdentifiers); - - /** - * Add your workbasket id to the query. - * - * @param workbasketIds - * the ids of workbaskets - * @return the query - */ - TaskQuery workbasketIdIn(String... workbasketIds); - - /** - * Add the owners to your query. - * - * @param owners - * the owners as String - * @return the query - */ - TaskQuery ownerIn(String... owners); - - /** - * Add the owner for pattern matching to your query. It will be compared in SQL with the LIKE operator. You may use - * a wildcard like % to specify the pattern. If you specify multiple arguments they are combined with the OR - * keyword. - * - * @param owners - * the owners of the searched tasks - * @return the query - */ - TaskQuery ownerLike(String... owners); - - /** - * Add the companies of the primary object reference for exact matching to your query. - * - * @param companies - * the companies of your primary object reference - * @return the query - */ - TaskQuery primaryObjectReferenceCompanyIn(String... companies); - - /** - * Add the company of the primary object reference for pattern matching to your query. It will be compared in SQL - * with the LIKE operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments - * they are combined with the OR keyword. - * - * @param company - * the company of your primary object reference - * @return the query - */ - TaskQuery primaryObjectReferenceCompanyLike(String... company); - - /** - * Add the systems of the primary object reference for exact matching to your query. - * - * @param systems - * the systems of your primary object reference - * @return the query - */ - TaskQuery primaryObjectReferenceSystemIn(String... systems); - - /** - * Add the system of the primary object reference for pattern matching to your query. It will be compared in SQL - * with the LIKE operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments - * they are combined with the OR keyword. - * - * @param systems - * the system of your primary object reference - * @return the query - */ - TaskQuery primaryObjectReferenceSystemLike(String... systems); - - /** - * Add the system instances of the primary object reference for exact matching to your query. - * - * @param systemInstances - * the system instances of your primary object reference - * @return the query - */ - TaskQuery primaryObjectReferenceSystemInstanceIn(String... systemInstances); - - /** - * Add the system instance of the primary object reference for pattern matching to your query. It will be compared - * in SQL with the LIKE operator. You may use a wildcard like % to specify the pattern. If you specify multiple - * arguments they are combined with the OR keyword. - * - * @param systemInstances - * the system instances of your primary object reference - * @return the query - */ - TaskQuery primaryObjectReferenceSystemInstanceLike(String... systemInstances); - - /** - * Add the types of the primary object reference for exact matching to your query. - * - * @param types - * the types your primary object reference - * @return the query - */ - TaskQuery primaryObjectReferenceTypeIn(String... types); - - /** - * Add the type of the primary object reference for pattern matching to your query. It will be compared in SQL with - * the LIKE operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments they - * are combined with the OR keyword. - * - * @param types - * the types of your primary object reference - * @return the query - */ - TaskQuery primaryObjectReferenceTypeLike(String... types); - - /** - * Add the value of the primary object reference for pattern matching to your query. It will be compared in SQL with - * the LIKE operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments they - * are combined with the OR keyword. - * - * @param values - * the values of your primary object reference - * @return the query - */ - TaskQuery primaryObjectReferenceValueLike(String... values); - - /** - * Add the values of the primary object reference for exact matching to your query. - * - * @param values - * the values of your primary object reference - * @return the query - */ - TaskQuery primaryObjectReferenceValueIn(String... values); - - /** - * Add the time intervals within which the task was created to your query. For each time interval, the database - * query will search for tasks whose created timestamp is after or at the interval's begin and before or at the - * interval's end. If more than one interval is specified, the query will connect them with the OR keyword. If - * either begin or end of an interval are null, these values will not be specified in the query. - * - * @param intervals - * - the TimeIntervals within which the task was created - * @return the query - */ - TaskQuery createdWithin(TimeInterval... intervals); - - /** - * Add the time intervals within which the task was claimed to your query. For each time interval, the database - * query will search for tasks whose claimed timestamp is after or at the interval's begin and before or at the - * interval's end. If more than one interval is specified, the query will connect them with the OR keyword. If - * either begin or end of an interval are null, these values will not be specified in the query. - * - * @param intervals - * - the TimeIntervals within which the task was claimed - * @return the query - */ - TaskQuery claimedWithin(TimeInterval... intervals); - - /** - * Add the time intervals within which the task was completed to your query. For each time interval, the database - * query will search for tasks whose completed timestamp is after or at the interval's begin and before or at the - * interval's end. If more than one interval is specified, the query will connect them with the OR keyword. If - * either begin or end of an interval are null, these values will not be specified in the query. - * - * @param intervals - * - the TimeIntervals within which the task was completed - * @return the query - */ - TaskQuery completedWithin(TimeInterval... intervals); - - /** - * Add the time intervals within which the task was modified to your query. For each time interval, the database - * query will search for tasks whose modified timestamp is after or at the interval's begin and before or at the - * interval's end. If more than one interval is specified, the query will connect them with the OR keyword. If - * either begin or end of an interval are null, these values will not be specified in the query. - * - * @param intervals - * - the TimeIntervals within which the task was modified - * @return the query - */ - TaskQuery modifiedWithin(TimeInterval... intervals); - - /** - * Add the time intervals within which the task is planned to your query. For each time interval, the database query - * will search for tasks whose planned timestamp is after or at the interval's begin and before or at the interval's - * end. If more than one interval is specified, the query will connect them with the OR keyword. If either begin or - * end of an interval are null, these values will not be specified in the query. - * - * @param intervals - * - the TimeIntervals within which the task is planned - * @return the query - */ - TaskQuery plannedWithin(TimeInterval... intervals); - - /** - * Add the time intervals within which the task is due to your query. For each time interval, the database query - * will search for tasks whose due timestamp is after or at the interval's begin and before or at the interval's - * end. If more than one interval is specified, the query will connect them with the OR keyword. If either begin or - * end of an interval are null, these values will not be specified in the query. - * - * @param intervals - * - the TimeIntervals within which the task is due - * @return the query - */ - TaskQuery dueWithin(TimeInterval... intervals); - - /** - * Add the isRead flag to the query. - * - * @param isRead - * as Boolean. If null, it won't be integrated into the statement. You have to set false. - * @return the query - */ - TaskQuery readEquals(Boolean isRead); - - /** - * Add the isTransferred flag to the query. - * - * @param isTransferred - * as Boolean. If null, it won't be integrated into the statement. You have to set false. - * @return the query - */ - TaskQuery transferredEquals(Boolean isTransferred); - - /** - * Add the parent business process ids for exact matching to your query. - * - * @param parentBusinessProcessIds - * the parent businessProcessIds of the searched for tasks - * @return the query - */ - TaskQuery parentBusinessProcessIdIn(String... parentBusinessProcessIds); - - /** - * Add the parent business process id for pattern matching to your query. It will be compared in SQL with the LIKE - * operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments they are - * combined with the OR keyword. - * - * @param parentBusinessProcessIds - * the parent businessprocess ids of the searched for tasks - * @return the query - */ - TaskQuery parentBusinessProcessIdLike(String... parentBusinessProcessIds); - - /** - * Add the business process ids for exact matching to your query. - * - * @param businessProcessIds - * the businessProcessIds of the searched for tasks - * @return the query - */ - TaskQuery businessProcessIdIn(String... businessProcessIds); - - /** - * Add the business process id for pattern matching to your query. It will be compared in SQL with the LIKE - * operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments they are - * combined with the OR keyword. - * - * @param businessProcessIds - * the business process ids of the searched-for tasks - * @return the query - */ - TaskQuery businessProcessIdLike(String... businessProcessIds); - - /** - * Add the values of custom attribute number num for exact matching to your query. - * - * @param num - * identifies which custom attribute is affected. Taskana concatenates "custom_" with num and the - * resulting String must match the name of the database column that contains the custom attribute. Valid - * values are "1", "2" .. "16" - * @param searchArguments - * the custom_num values of the searched for tasks - * @return the query - * @throws InvalidArgumentException - * if num has not a value of "1", "2" ... "16" - */ - TaskQuery customAttributeIn(String num, String... searchArguments) throws InvalidArgumentException; - - /** - * Add the values of custom attribute number num for pattern matching to your query. They will be compared in SQL - * with the LIKE operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments - * they are combined with the OR keyword. - * - * @param num - * identifies which custom attribute is affected. Taskana concatenates "custom_" with num and the - * resulting String must match the name of the database column that contains the custom attribute. Valid - * values are "1", "2" .. "16" - * @param searchArguments - * the custom_num values of the searched-for tasks - * @return the query - * @throws InvalidArgumentException - * if num has not a value of "1", "2" ... "16" - */ - TaskQuery customAttributeLike(String num, String... searchArguments) throws InvalidArgumentException; - - - /** - * Add the attachment classification keys for exact matching to your query. - * - * @param attachmentClassificationKeys - * the attachmentClassificationKeys values of the searched for tasks - * @return the query - */ - TaskQuery attachmentClassificationKeyIn(String... attachmentClassificationKeys); - - /** - * Add the attachment classification Keys for pattern matching to your query. It will be compared in SQL with the LIKE - * operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments they are - * combined with the OR keyword. - * - * @param attachmentClassificationKey - * the attachmentClassificationKeys values of the searched for tasks - * @return the query - */ - TaskQuery attachmentClassificationKeyLike(String... attachmentClassificationKey); - - - /** - * Add the attachment classification Ids for exact matching to your query. - * - * @param attachmentClassificationId - * the attachmentClassificationId values of the searched for tasks - * @return the query - */ - TaskQuery attachmentClassificationIdIn(String... attachmentClassificationId); - - /** - * Add the values of attachment classification ids for pattern matching to your query. They will be compared in SQL - * with the LIKE operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments - * they are combined with the OR keyword. - * - * @param attachmentClassificationId - * the attachmentClassificationId values of the searched-for tasks - * @return the query - */ - TaskQuery attachmentClassificationIdLike(String... attachmentClassificationId); - - /** - * Add the attachment classification names for exact matching to your query. - * - * @param attachmentClassificationName - * the attachmentClassificationName values of the searched for tasks - * @return the query - */ - TaskQuery attachmentClassificationNameIn(String... attachmentClassificationName); - - /** - * Add the values of attachment classification names for pattern matching to your query. They will be compared in SQL - * with the LIKE operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments - * they are combined with the OR keyword. - * - * @param attachmentClassificationName - * the attachmentClassificationName values of the searched-for tasks - * @return the query - */ - TaskQuery attachmentClassificationNameLike(String... attachmentClassificationName); - - /** - * Add the values of attachment channel for exact matching to your query. - * - * @param attachmentChannel - * the attachmentChannel values of the searched for tasks - * @return the query - */ - TaskQuery attachmentChannelIn(String... attachmentChannel); - - /** - * Add the values of attachment channel for pattern matching to your query. They will be compared in SQL - * with the LIKE operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments - * they are combined with the OR keyword. - * - * @param attachmentChannel - * the attachmentChannel values of the searched-for tasks - * @return the query - */ - TaskQuery attachmentChannelLike(String... attachmentChannel); - - /** - * Add the values of reference values for exact matching to your query. - * - * @param referenceValue - * the referenceValue values of the searched for tasks - * @return the query - */ - TaskQuery attachmentReferenceValueIn(String... referenceValue); - - /** - * Add the values of reference values for pattern matching to your query. They will be compared in SQL - * with the LIKE operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments - * they are combined with the OR keyword. - * - * @param referenceValue - * the referenceValue values of the searched-for tasks - * @return the query - */ - TaskQuery attachmentReferenceValueLike(String... referenceValue); - - - /** - * Add your received-dates to your query. - * - * @param receivedIn - * the {@link TimeInterval} within which the searched-for tasks attachment were received the last time. - * @return the query - */ - - TaskQuery attachmentReceivedWithin(TimeInterval... receivedIn); - - /** - * Add your callbackState to your query. - * - * @param states - * the callback states as {@link CallbackState} - * @return the query - */ - TaskQuery callbackStateIn(CallbackState... states); - - /** - * This method provides a query builder for quering the database. - * - * @return a {@link ObjectReferenceQuery} - */ - ObjectReferenceQuery createObjectReferenceQuery(); - - /** - * This method sorts the query result according to the business process id. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByBusinessProcessId(SortDirection sortDirection); - - /** - * This method sorts the query result according to the claimed timestamp. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByClaimed(SortDirection sortDirection); - - /** - * This method sorts the query result according to the classification key. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByClassificationKey(SortDirection sortDirection); - - /** - * This method sorts the query result according to the classification name. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByClassificationName(SortDirection sortDirection); - - /** - * This method sorts the query result according to the completed timestamp. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByCompleted(SortDirection sortDirection); - - /** - * This method sorts the query result according to the created timestamp. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByCreated(SortDirection sortDirection); - - /** - * This method sorts the query result according to the domain. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByDomain(SortDirection sortDirection); - - /** - * This method sorts the query result according to the due timestamp. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByDue(SortDirection sortDirection); - - /** - * This method sorts the query result according to the modified timestamp. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByModified(SortDirection sortDirection); - - /** - * This method sorts the query result according to name. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByName(SortDirection sortDirection); - - /** - * This method sorts the query result according to creators name. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByCreator(SortDirection sortDirection); - - /** - * This method sorts the query result according to the note. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByNote(SortDirection sortDirection); - - /** - * This method sorts the query result according to the owner. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByOwner(SortDirection sortDirection); - - /** - * This method sorts the query result according to the parent business process id. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByParentBusinessProcessId(SortDirection sortDirection); - - /** - * This method sorts the query result according to the planned timestamp. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByPlanned(SortDirection sortDirection); - - /** - * This method sorts the query result according to the company of the primary object reference. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByPrimaryObjectReferenceCompany(SortDirection sortDirection); - - /** - * This method sorts the query result according to the system of the primary object reference. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByPrimaryObjectReferenceSystem(SortDirection sortDirection); - - /** - * This method sorts the query result according to the system instance of the primary object reference. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByPrimaryObjectReferenceSystemInstance(SortDirection sortDirection); - - /** - * This method sorts the query result according to the type of the primary object reference. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByPrimaryObjectReferenceType(SortDirection sortDirection); - - /** - * This method sorts the query result according to the value of the primary object reference. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByPrimaryObjectReferenceValue(SortDirection sortDirection); - - /** - * This method sorts the query result according to the priority. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByPriority(SortDirection sortDirection); - - /** - * This method sorts the query result according to the state. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByState(SortDirection sortDirection); - - /** - * This method sorts the query result according to the workbasket key. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByWorkbasketKey(SortDirection sortDirection); - - /** - * This method sorts the query result according to the value of a custom field. - * The custom field is choosen by parameter num. - * - * @param num - * identifies which custom attribute is affected. Taskana concatenates "custom_" with num and the - * resulting String must match the name of the database column that contains the custom attribute. Valid - * values are "1", "2" .. "16" - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - * @throws InvalidArgumentException when number is not a valid number between 1 and 16 - */ - TaskQuery orderByCustomAttribute(String num, SortDirection sortDirection) throws InvalidArgumentException; - - /** - * Filter for summaries which are containing one of the given taskIds. - * - * @param taskIds - * The ids of the searched-for tasks. - * @return the taskQuery - */ - TaskQuery idIn(String... taskIds); - - /** - * This method sorts the query result according to the workbasket-Id of the tasks. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByWorkbasketId(SortDirection sortDirection); - - /** - * This method sorts the query result according to the attachment classification key. - * (Should only be used if there is one attachment per task in other case the result would be wrong.) - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByAttachmentClassificationKey(SortDirection sortDirection); - - /** - * This method sorts the query result according to the attachment classification name. - * (Should only be used if there is one attachment per task in other case the result would be wrong.) - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByAttachmentClassificationName(SortDirection sortDirection); - - /** - * This method sorts the query result according to the attachment classification id. - * (Should only be used if there is one attachment per task in other case the result would be wrong.) - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByAttachmentClassificationId(SortDirection sortDirection); - - /** - * This method sorts the query result according to the attachment channel. - * (Should only be used if there is one attachment per task in other case the result would be wrong.) - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByAttachmentChannel(SortDirection sortDirection); - - - - /** - * This method sorts the query result according to the attachment reference value. - * (Should only be used if there is one attachment per task in other case the result would be wrong.) - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByAttachmentReference(SortDirection sortDirection); - - - /** - * This method sorts the query result according to the attachment received. - * (Should only be used if there is one attachment per task in other case the result would be wrong.) - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - TaskQuery orderByAttachmentReceived(SortDirection sortDirection); - + /** + * Add your names to your query. + * + * @param names the names as Strings + * @return the query + */ + TaskQuery nameIn(String... names); + + /** + * Add your name for pattern matching to your query. It will be compared in SQL with the LIKE + * operator. You may use a wildcard like % to specify the pattern. If you specify multiple + * arguments they are combined with the OR keyword. + * + * @param names your names + * @return the query + */ + TaskQuery nameLike(String... names); + + /** + * Add your external ids to your query. + * + * @param externalIds the external ids as Strings + * @return the query + */ + TaskQuery externalIdIn(String... externalIds); + + /** + * Add your external id for pattern matching to your query. It will be compared in SQL with the + * LIKE operator. You may use a wildcard like % to specify the pattern. If you specify multiple + * arguments they are combined with the OR keyword. + * + * @param externalIds your external ids + * @return the query + */ + TaskQuery externalIdLike(String... externalIds); + + /** + * Add the UserIds of the creator to your query. + * + * @param creators of the queried tasks + * @return the query + */ + TaskQuery creatorIn(String... creators); + + /** + * Add the UserIds of the creator for pattern matching to your query. It will be compared in SQL + * with the LIKE operator. You may use a wildcard like % to specify the pattern. If you specify + * multiple arguments they are combined with the OR keyword. + * + * @param creators of the queried tasks + * @return the query + */ + TaskQuery creatorLike(String... creators); + + /** + * Add your description for pattern matching to your query. It will be compared in SQL with the + * LIKE operator. You may use a wildcard like % to specify the pattern. If you specify multiple + * arguments they are combined with the OR keyword. + * + * @param description your description + * @return the query + */ + TaskQuery descriptionLike(String... description); + + /** + * Add your custom note for pattern matching to your query. It will be compared in SQL with the + * LIKE operator. You may use a wildcard like % to specify the pattern. If you specify multiple + * arguments they are combined with the OR keyword. + * + * @param note your custom note + * @return the query + */ + TaskQuery noteLike(String... note); + + /** + * Add your priorities to your query. + * + * @param priorities as a integer + * @return the query + */ + TaskQuery priorityIn(int... priorities); + + /** + * Add your state to your query. + * + * @param states the states as {@link TaskState} + * @return the query + */ + TaskQuery stateIn(TaskState... states); + + /** + * Exclude these states from your query. + * + * @param states the states as {@link TaskState} + * @return the query + */ + TaskQuery stateNotIn(TaskState... states); + + /** + * Add your classificationKey to your query. + * + * @param classificationKeys the classification key + * @return the query + */ + TaskQuery classificationKeyIn(String... classificationKeys); + + /** + * Exlude these classificationKeys from your query. + * + * @param classificationKeys the classification key + * @return the query + */ + TaskQuery classificationKeyNotIn(String... classificationKeys); + + /** + * Add your classificationKey for pattern matching to your query. It will be compared in SQL with + * the LIKE operator. You may use a wildcard like % to specify the pattern. If you specify + * multiple arguments they are combined with the OR keyword. + * + * @param classificationKeys the classification key + * @return the query + */ + TaskQuery classificationKeyLike(String... classificationKeys); + + /** + * Add your classificationId to your query. + * + * @param classificationIds the classification Ids + * @return the query + */ + TaskQuery classificationIdIn(String... classificationIds); + + /** + * Add your classificationCategory to your query. + * + * @param classificationCategories the classification category for filtering + * @return the query + */ + TaskQuery classificationCategoryIn(String... classificationCategories); + + /** + * Add your classificationCategory for pattern matching to your query. It will be compared in SQL + * with the LIKE operator. You may use a wildcard like % to specify the pattern. If you specify + * multiple arguments they are combined with the OR keyword. + * + * @param classificationCategories the classification categories for filtering + * @return the query + */ + TaskQuery classificationCategoryLike(String... classificationCategories); + + /** + * Add your classificationName to your query. + * + * @param classificationNames the classification name + * @return the query + */ + TaskQuery classificationNameIn(String... classificationNames); + + /** + * Add your classificationName for pattern matching to your query. It will be compared in SQL with + * the LIKE operator. You may use a wildcard like % to specify the pattern. If you specify + * multiple arguments they are combined with the OR keyword. * + * + * @param classificationNames the classification name + * @return the query + */ + TaskQuery classificationNameLike(String... classificationNames); + + /** + * Add your workbasket key to the query. + * + * @param workbasketIdentifiers the key - domain combinations that identify workbaskets + * @return the query + */ + TaskQuery workbasketKeyDomainIn(KeyDomain... workbasketIdentifiers); + + /** + * Add your workbasket id to the query. + * + * @param workbasketIds the ids of workbaskets + * @return the query + */ + TaskQuery workbasketIdIn(String... workbasketIds); + + /** + * Add the owners to your query. + * + * @param owners the owners as String + * @return the query + */ + TaskQuery ownerIn(String... owners); + + /** + * Add the owner for pattern matching to your query. It will be compared in SQL with the LIKE + * operator. You may use a wildcard like % to specify the pattern. If you specify multiple + * arguments they are combined with the OR keyword. + * + * @param owners the owners of the searched tasks + * @return the query + */ + TaskQuery ownerLike(String... owners); + + /** + * Add the companies of the primary object reference for exact matching to your query. + * + * @param companies the companies of your primary object reference + * @return the query + */ + TaskQuery primaryObjectReferenceCompanyIn(String... companies); + + /** + * Add the company of the primary object reference for pattern matching to your query. It will be + * compared in SQL with the LIKE operator. You may use a wildcard like % to specify the pattern. + * If you specify multiple arguments they are combined with the OR keyword. + * + * @param company the company of your primary object reference + * @return the query + */ + TaskQuery primaryObjectReferenceCompanyLike(String... company); + + /** + * Add the systems of the primary object reference for exact matching to your query. + * + * @param systems the systems of your primary object reference + * @return the query + */ + TaskQuery primaryObjectReferenceSystemIn(String... systems); + + /** + * Add the system of the primary object reference for pattern matching to your query. It will be + * compared in SQL with the LIKE operator. You may use a wildcard like % to specify the pattern. + * If you specify multiple arguments they are combined with the OR keyword. + * + * @param systems the system of your primary object reference + * @return the query + */ + TaskQuery primaryObjectReferenceSystemLike(String... systems); + + /** + * Add the system instances of the primary object reference for exact matching to your query. + * + * @param systemInstances the system instances of your primary object reference + * @return the query + */ + TaskQuery primaryObjectReferenceSystemInstanceIn(String... systemInstances); + + /** + * Add the system instance of the primary object reference for pattern matching to your query. It + * will be compared in SQL with the LIKE operator. You may use a wildcard like % to specify the + * pattern. If you specify multiple arguments they are combined with the OR keyword. + * + * @param systemInstances the system instances of your primary object reference + * @return the query + */ + TaskQuery primaryObjectReferenceSystemInstanceLike(String... systemInstances); + + /** + * Add the types of the primary object reference for exact matching to your query. + * + * @param types the types your primary object reference + * @return the query + */ + TaskQuery primaryObjectReferenceTypeIn(String... types); + + /** + * Add the type of the primary object reference for pattern matching to your query. It will be + * compared in SQL with the LIKE operator. You may use a wildcard like % to specify the pattern. + * If you specify multiple arguments they are combined with the OR keyword. + * + * @param types the types of your primary object reference + * @return the query + */ + TaskQuery primaryObjectReferenceTypeLike(String... types); + + /** + * Add the value of the primary object reference for pattern matching to your query. It will be + * compared in SQL with the LIKE operator. You may use a wildcard like % to specify the pattern. + * If you specify multiple arguments they are combined with the OR keyword. + * + * @param values the values of your primary object reference + * @return the query + */ + TaskQuery primaryObjectReferenceValueLike(String... values); + + /** + * Add the values of the primary object reference for exact matching to your query. + * + * @param values the values of your primary object reference + * @return the query + */ + TaskQuery primaryObjectReferenceValueIn(String... values); + + /** + * Add the time intervals within which the task was created to your query. For each time interval, + * the database query will search for tasks whose created timestamp is after or at the interval's + * begin and before or at the interval's end. If more than one interval is specified, the query + * will connect them with the OR keyword. If either begin or end of an interval are null, these + * values will not be specified in the query. + * + * @param intervals - the TimeIntervals within which the task was created + * @return the query + */ + TaskQuery createdWithin(TimeInterval... intervals); + + /** + * Add the time intervals within which the task was claimed to your query. For each time interval, + * the database query will search for tasks whose claimed timestamp is after or at the interval's + * begin and before or at the interval's end. If more than one interval is specified, the query + * will connect them with the OR keyword. If either begin or end of an interval are null, these + * values will not be specified in the query. + * + * @param intervals - the TimeIntervals within which the task was claimed + * @return the query + */ + TaskQuery claimedWithin(TimeInterval... intervals); + + /** + * Add the time intervals within which the task was completed to your query. For each time + * interval, the database query will search for tasks whose completed timestamp is after or at the + * interval's begin and before or at the interval's end. If more than one interval is specified, + * the query will connect them with the OR keyword. If either begin or end of an interval are + * null, these values will not be specified in the query. + * + * @param intervals - the TimeIntervals within which the task was completed + * @return the query + */ + TaskQuery completedWithin(TimeInterval... intervals); + + /** + * Add the time intervals within which the task was modified to your query. For each time + * interval, the database query will search for tasks whose modified timestamp is after or at the + * interval's begin and before or at the interval's end. If more than one interval is specified, + * the query will connect them with the OR keyword. If either begin or end of an interval are + * null, these values will not be specified in the query. + * + * @param intervals - the TimeIntervals within which the task was modified + * @return the query + */ + TaskQuery modifiedWithin(TimeInterval... intervals); + + /** + * Add the time intervals within which the task is planned to your query. For each time interval, + * the database query will search for tasks whose planned timestamp is after or at the interval's + * begin and before or at the interval's end. If more than one interval is specified, the query + * will connect them with the OR keyword. If either begin or end of an interval are null, these + * values will not be specified in the query. + * + * @param intervals - the TimeIntervals within which the task is planned + * @return the query + */ + TaskQuery plannedWithin(TimeInterval... intervals); + + /** + * Add the time intervals within which the task is due to your query. For each time interval, the + * database query will search for tasks whose due timestamp is after or at the interval's begin + * and before or at the interval's end. If more than one interval is specified, the query will + * connect them with the OR keyword. If either begin or end of an interval are null, these values + * will not be specified in the query. + * + * @param intervals - the TimeIntervals within which the task is due + * @return the query + */ + TaskQuery dueWithin(TimeInterval... intervals); + + /** + * Add the isRead flag to the query. + * + * @param isRead as Boolean. If null, it won't be integrated into the statement. You have to set + * false. + * @return the query + */ + TaskQuery readEquals(Boolean isRead); + + /** + * Add the isTransferred flag to the query. + * + * @param isTransferred as Boolean. If null, it won't be integrated into the statement. You have + * to set false. + * @return the query + */ + TaskQuery transferredEquals(Boolean isTransferred); + + /** + * Add the parent business process ids for exact matching to your query. + * + * @param parentBusinessProcessIds the parent businessProcessIds of the searched for tasks + * @return the query + */ + TaskQuery parentBusinessProcessIdIn(String... parentBusinessProcessIds); + + /** + * Add the parent business process id for pattern matching to your query. It will be compared in + * SQL with the LIKE operator. You may use a wildcard like % to specify the pattern. If you + * specify multiple arguments they are combined with the OR keyword. + * + * @param parentBusinessProcessIds the parent businessprocess ids of the searched for tasks + * @return the query + */ + TaskQuery parentBusinessProcessIdLike(String... parentBusinessProcessIds); + + /** + * Add the business process ids for exact matching to your query. + * + * @param businessProcessIds the businessProcessIds of the searched for tasks + * @return the query + */ + TaskQuery businessProcessIdIn(String... businessProcessIds); + + /** + * Add the business process id for pattern matching to your query. It will be compared in SQL with + * the LIKE operator. You may use a wildcard like % to specify the pattern. If you specify + * multiple arguments they are combined with the OR keyword. + * + * @param businessProcessIds the business process ids of the searched-for tasks + * @return the query + */ + TaskQuery businessProcessIdLike(String... businessProcessIds); + + /** + * Add the values of custom attribute number num for exact matching to your query. + * + * @param num identifies which custom attribute is affected. Taskana concatenates "custom_" with + * num and the resulting String must match the name of the database column that contains the + * custom attribute. Valid values are "1", "2" .. "16" + * @param searchArguments the custom_num values of the searched for tasks + * @return the query + * @throws InvalidArgumentException if num has not a value of "1", "2" ... "16" + */ + TaskQuery customAttributeIn(String num, String... searchArguments) + throws InvalidArgumentException; + + /** + * Add the values of custom attribute number num for pattern matching to your query. They will be + * compared in SQL with the LIKE operator. You may use a wildcard like % to specify the pattern. + * If you specify multiple arguments they are combined with the OR keyword. + * + * @param num identifies which custom attribute is affected. Taskana concatenates "custom_" with + * num and the resulting String must match the name of the database column that contains the + * custom attribute. Valid values are "1", "2" .. "16" + * @param searchArguments the custom_num values of the searched-for tasks + * @return the query + * @throws InvalidArgumentException if num has not a value of "1", "2" ... "16" + */ + TaskQuery customAttributeLike(String num, String... searchArguments) + throws InvalidArgumentException; + + /** + * Add the attachment classification keys for exact matching to your query. + * + * @param attachmentClassificationKeys the attachmentClassificationKeys values of the searched for + * tasks + * @return the query + */ + TaskQuery attachmentClassificationKeyIn(String... attachmentClassificationKeys); + + /** + * Add the attachment classification Keys for pattern matching to your query. It will be compared + * in SQL with the LIKE operator. You may use a wildcard like % to specify the pattern. If you + * specify multiple arguments they are combined with the OR keyword. + * + * @param attachmentClassificationKey the attachmentClassificationKeys values of the searched for + * tasks + * @return the query + */ + TaskQuery attachmentClassificationKeyLike(String... attachmentClassificationKey); + + /** + * Add the attachment classification Ids for exact matching to your query. + * + * @param attachmentClassificationId the attachmentClassificationId values of the searched for + * tasks + * @return the query + */ + TaskQuery attachmentClassificationIdIn(String... attachmentClassificationId); + + /** + * Add the values of attachment classification ids for pattern matching to your query. They will + * be compared in SQL with the LIKE operator. You may use a wildcard like % to specify the + * pattern. If you specify multiple arguments they are combined with the OR keyword. + * + * @param attachmentClassificationId the attachmentClassificationId values of the searched-for + * tasks + * @return the query + */ + TaskQuery attachmentClassificationIdLike(String... attachmentClassificationId); + + /** + * Add the attachment classification names for exact matching to your query. + * + * @param attachmentClassificationName the attachmentClassificationName values of the searched for + * tasks + * @return the query + */ + TaskQuery attachmentClassificationNameIn(String... attachmentClassificationName); + + /** + * Add the values of attachment classification names for pattern matching to your query. They will + * be compared in SQL with the LIKE operator. You may use a wildcard like % to specify the + * pattern. If you specify multiple arguments they are combined with the OR keyword. + * + * @param attachmentClassificationName the attachmentClassificationName values of the searched-for + * tasks + * @return the query + */ + TaskQuery attachmentClassificationNameLike(String... attachmentClassificationName); + + /** + * Add the values of attachment channel for exact matching to your query. + * + * @param attachmentChannel the attachmentChannel values of the searched for tasks + * @return the query + */ + TaskQuery attachmentChannelIn(String... attachmentChannel); + + /** + * Add the values of attachment channel for pattern matching to your query. They will be compared + * in SQL with the LIKE operator. You may use a wildcard like % to specify the pattern. If you + * specify multiple arguments they are combined with the OR keyword. + * + * @param attachmentChannel the attachmentChannel values of the searched-for tasks + * @return the query + */ + TaskQuery attachmentChannelLike(String... attachmentChannel); + + /** + * Add the values of reference values for exact matching to your query. + * + * @param referenceValue the referenceValue values of the searched for tasks + * @return the query + */ + TaskQuery attachmentReferenceValueIn(String... referenceValue); + + /** + * Add the values of reference values for pattern matching to your query. They will be compared in + * SQL with the LIKE operator. You may use a wildcard like % to specify the pattern. If you + * specify multiple arguments they are combined with the OR keyword. + * + * @param referenceValue the referenceValue values of the searched-for tasks + * @return the query + */ + TaskQuery attachmentReferenceValueLike(String... referenceValue); + + /** + * Add your received-dates to your query. + * + * @param receivedIn the {@link TimeInterval} within which the searched-for tasks attachment were + * received the last time. + * @return the query + */ + TaskQuery attachmentReceivedWithin(TimeInterval... receivedIn); + + /** + * Add your callbackState to your query. + * + * @param states the callback states as {@link CallbackState} + * @return the query + */ + TaskQuery callbackStateIn(CallbackState... states); + + /** + * This method provides a query builder for quering the database. + * + * @return a {@link ObjectReferenceQuery} + */ + ObjectReferenceQuery createObjectReferenceQuery(); + + /** + * This method sorts the query result according to the business process id. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByBusinessProcessId(SortDirection sortDirection); + + /** + * This method sorts the query result according to the claimed timestamp. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByClaimed(SortDirection sortDirection); + + /** + * This method sorts the query result according to the classification key. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByClassificationKey(SortDirection sortDirection); + + /** + * This method sorts the query result according to the classification name. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByClassificationName(SortDirection sortDirection); + + /** + * This method sorts the query result according to the completed timestamp. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByCompleted(SortDirection sortDirection); + + /** + * This method sorts the query result according to the created timestamp. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByCreated(SortDirection sortDirection); + + /** + * This method sorts the query result according to the domain. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByDomain(SortDirection sortDirection); + + /** + * This method sorts the query result according to the due timestamp. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByDue(SortDirection sortDirection); + + /** + * This method sorts the query result according to the modified timestamp. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByModified(SortDirection sortDirection); + + /** + * This method sorts the query result according to name. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByName(SortDirection sortDirection); + + /** + * This method sorts the query result according to creators name. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByCreator(SortDirection sortDirection); + + /** + * This method sorts the query result according to the note. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByNote(SortDirection sortDirection); + + /** + * This method sorts the query result according to the owner. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByOwner(SortDirection sortDirection); + + /** + * This method sorts the query result according to the parent business process id. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByParentBusinessProcessId(SortDirection sortDirection); + + /** + * This method sorts the query result according to the planned timestamp. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByPlanned(SortDirection sortDirection); + + /** + * This method sorts the query result according to the company of the primary object reference. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByPrimaryObjectReferenceCompany(SortDirection sortDirection); + + /** + * This method sorts the query result according to the system of the primary object reference. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByPrimaryObjectReferenceSystem(SortDirection sortDirection); + + /** + * This method sorts the query result according to the system instance of the primary object + * reference. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByPrimaryObjectReferenceSystemInstance(SortDirection sortDirection); + + /** + * This method sorts the query result according to the type of the primary object reference. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByPrimaryObjectReferenceType(SortDirection sortDirection); + + /** + * This method sorts the query result according to the value of the primary object reference. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByPrimaryObjectReferenceValue(SortDirection sortDirection); + + /** + * This method sorts the query result according to the priority. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByPriority(SortDirection sortDirection); + + /** + * This method sorts the query result according to the state. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByState(SortDirection sortDirection); + + /** + * This method sorts the query result according to the workbasket key. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByWorkbasketKey(SortDirection sortDirection); + + /** + * This method sorts the query result according to the value of a custom field. The custom field + * is choosen by parameter num. + * + * @param num identifies which custom attribute is affected. Taskana concatenates "custom_" with + * num and the resulting String must match the name of the database column that contains the + * custom attribute. Valid values are "1", "2" .. "16" + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + * @throws InvalidArgumentException when number is not a valid number between 1 and 16 + */ + TaskQuery orderByCustomAttribute(String num, SortDirection sortDirection) + throws InvalidArgumentException; + + /** + * Filter for summaries which are containing one of the given taskIds. + * + * @param taskIds The ids of the searched-for tasks. + * @return the taskQuery + */ + TaskQuery idIn(String... taskIds); + + /** + * This method sorts the query result according to the workbasket-Id of the tasks. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByWorkbasketId(SortDirection sortDirection); + + /** + * This method sorts the query result according to the attachment classification key. (Should only + * be used if there is one attachment per task in other case the result would be wrong.) + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByAttachmentClassificationKey(SortDirection sortDirection); + + /** + * This method sorts the query result according to the attachment classification name. (Should + * only be used if there is one attachment per task in other case the result would be wrong.) + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByAttachmentClassificationName(SortDirection sortDirection); + + /** + * This method sorts the query result according to the attachment classification id. (Should only + * be used if there is one attachment per task in other case the result would be wrong.) + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByAttachmentClassificationId(SortDirection sortDirection); + + /** + * This method sorts the query result according to the attachment channel. (Should only be used if + * there is one attachment per task in other case the result would be wrong.) + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByAttachmentChannel(SortDirection sortDirection); + + /** + * This method sorts the query result according to the attachment reference value. (Should only be + * used if there is one attachment per task in other case the result would be wrong.) + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByAttachmentReference(SortDirection sortDirection); + + /** + * This method sorts the query result according to the attachment received. (Should only be used + * if there is one attachment per task in other case the result would be wrong.) + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + TaskQuery orderByAttachmentReceived(SortDirection sortDirection); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/TaskQueryColumnName.java b/lib/taskana-core/src/main/java/pro/taskana/TaskQueryColumnName.java index 55f263615..e46a71da7 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/TaskQueryColumnName.java +++ b/lib/taskana-core/src/main/java/pro/taskana/TaskQueryColumnName.java @@ -1,75 +1,77 @@ package pro.taskana; /** - * Enum containing the column names for @see pro.taskana.mappings.QueryMapper#queryTaskColumnValues(pro.taskana.impl.TaskQueryImpl). + * Enum containing the column names for @see + * pro.taskana.mappings.QueryMapper#queryTaskColumnValues(pro.taskana.impl.TaskQueryImpl). * * @author jsa */ public enum TaskQueryColumnName implements QueryColumnName { - ID("t.id"), - EXTERNAL_ID("t.external_id"), - CREATED("t.created"), - CLAIMED("t.claimed"), - COMPLETED("t.completed"), - MODIFIED("t.modified"), - PLANNED("t.planned"), - DUE("t.due"), - NAME("t.name"), - CREATOR("t.creator"), - DESCRIPTION("t.description"), - NOTE("t.note"), - PRIORITY("t.priority"), - STATE("t.state"), - CLASSIFICATION_CATEGORY("t.classification_category"), - CLASSIFICATION_KEY("t.classification_key"), - CLASSIFICATION_ID("t.classification_id"), - CLASSIFICATION_NAME("c.name"), - WORKBASKET_ID("t.workbasket_id"), - WORKBASKET_KEY("t.workbasket_key"), - DOMAIN("t.domain"), - BUSINESS_PROCESS_ID("t.business_process_id"), - PARENT_BUSINESS_PROCESS_ID("t.parent_business_process_id"), - OWNER("t.owner"), - POR_COMPANY("t.por_company"), - POR_SYSTEM("t.por_system"), - POR_INSTANCE("t.por_instance"), - POR_TYPE("t.por_type"), - POR_VALUE("t.por_value"), - IS_READ("t.is_read"), - IS_TRANSFERRED("t.is_transferred"), - CUSTOM_1("t.custom_1"), - CUSTOM_2("t.custom_2"), - CUSTOM_3("t.custom_3"), - CUSTOM_4("t.custom_4"), - CUSTOM_5("t.custom_5"), - CUSTOM_6("t.custom_6"), - CUSTOM_7("t.custom_7"), - CUSTOM_8("t.custom_8"), - CUSTOM_9("t.custom_9"), - CUSTOM_10("t.custom_10"), - CUSTOM_11("t.custom_11"), - CUSTOM_12("t.custom_12"), - CUSTOM_13("t.custom_13"), - CUSTOM_14("t.custom_14"), - CUSTOM_15("t.custom_15"), - CUSTOM_16("t.custom_16"), - A_CLASSIFICATION_KEY("a.classification_key"), - A_CLASSIFICATION_ID("a.classification_id"), - A_CLASSIFICATION_NAME("ac.name"), - A_CHANNEL("a.channel"), - A_REF_VALUE("a.ref_value"); + ID("t.id"), + EXTERNAL_ID("t.external_id"), + CREATED("t.created"), + CLAIMED("t.claimed"), + COMPLETED("t.completed"), + MODIFIED("t.modified"), + PLANNED("t.planned"), + DUE("t.due"), + NAME("t.name"), + CREATOR("t.creator"), + DESCRIPTION("t.description"), + NOTE("t.note"), + PRIORITY("t.priority"), + STATE("t.state"), + CLASSIFICATION_CATEGORY("t.classification_category"), + CLASSIFICATION_KEY("t.classification_key"), + CLASSIFICATION_ID("t.classification_id"), + CLASSIFICATION_NAME("c.name"), + WORKBASKET_ID("t.workbasket_id"), + WORKBASKET_KEY("t.workbasket_key"), + DOMAIN("t.domain"), + BUSINESS_PROCESS_ID("t.business_process_id"), + PARENT_BUSINESS_PROCESS_ID("t.parent_business_process_id"), + OWNER("t.owner"), + POR_COMPANY("t.por_company"), + POR_SYSTEM("t.por_system"), + POR_INSTANCE("t.por_instance"), + POR_TYPE("t.por_type"), + POR_VALUE("t.por_value"), + IS_READ("t.is_read"), + IS_TRANSFERRED("t.is_transferred"), + CUSTOM_1("t.custom_1"), + CUSTOM_2("t.custom_2"), + CUSTOM_3("t.custom_3"), + CUSTOM_4("t.custom_4"), + CUSTOM_5("t.custom_5"), + CUSTOM_6("t.custom_6"), + CUSTOM_7("t.custom_7"), + CUSTOM_8("t.custom_8"), + CUSTOM_9("t.custom_9"), + CUSTOM_10("t.custom_10"), + CUSTOM_11("t.custom_11"), + CUSTOM_12("t.custom_12"), + CUSTOM_13("t.custom_13"), + CUSTOM_14("t.custom_14"), + CUSTOM_15("t.custom_15"), + CUSTOM_16("t.custom_16"), + A_CLASSIFICATION_KEY("a.classification_key"), + A_CLASSIFICATION_ID("a.classification_id"), + A_CLASSIFICATION_NAME("ac.name"), + A_CHANNEL("a.channel"), + A_REF_VALUE("a.ref_value"); - private String name; - TaskQueryColumnName(String name) { - this.name = name; - } + private String name; - @Override - public String toString() { - return name; - } + TaskQueryColumnName(String name) { + this.name = name; + } - public boolean isAttachmentColumn() { - return this.name().startsWith("A_"); - } + public boolean isAttachmentColumn() { + return this.name().startsWith("A_"); + } + + @Override + public String toString() { + return name; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/TaskService.java b/lib/taskana-core/src/main/java/pro/taskana/TaskService.java index 79fbe42d5..47f027172 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/TaskService.java +++ b/lib/taskana-core/src/main/java/pro/taskana/TaskService.java @@ -15,418 +15,356 @@ import pro.taskana.exceptions.TaskNotFoundException; import pro.taskana.exceptions.TaskanaException; import pro.taskana.exceptions.WorkbasketNotFoundException; -/** - * The Task Service manages all operations on tasks. - */ +/** The Task Service manages all operations on tasks. */ public interface TaskService { - /** - * Claim an existing task for the current user. - * - * @param taskId - * the id of the task to be claimed - * @return claimed Task - * @throws TaskNotFoundException - * if the task with taskId was not found - * @throws InvalidStateException - * if the state of the task with taskId is not READY - * @throws InvalidOwnerException - * if the task with taskId is claimed by some else - * @throws NotAuthorizedException - * if the current user has no read permission for the workbasket the task is in - */ - Task claim(String taskId) - throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, NotAuthorizedException; + /** + * Claim an existing task for the current user. + * + * @param taskId the id of the task to be claimed + * @return claimed Task + * @throws TaskNotFoundException if the task with taskId was not found + * @throws InvalidStateException if the state of the task with taskId is not READY + * @throws InvalidOwnerException if the task with taskId is claimed by some else + * @throws NotAuthorizedException if the current user has no read permission for the workbasket + * the task is in + */ + Task claim(String taskId) + throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, + NotAuthorizedException; - /** - * Claim an existing task for the current user even if it is already claimed by someone else. - * - * @param taskId - * the id of the task to be claimed - * @return claimed Task - * @throws TaskNotFoundException - * if the task with taskId was not found - * @throws InvalidStateException - * if the state of the task with taskId is not READY - * @throws InvalidOwnerException - * if the task with taskId is claimed by someone else - * @throws NotAuthorizedException - * if the current user has no read permission for the workbasket the task is in - */ - Task forceClaim(String taskId) - throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, NotAuthorizedException; + /** + * Claim an existing task for the current user even if it is already claimed by someone else. + * + * @param taskId the id of the task to be claimed + * @return claimed Task + * @throws TaskNotFoundException if the task with taskId was not found + * @throws InvalidStateException if the state of the task with taskId is not READY + * @throws InvalidOwnerException if the task with taskId is claimed by someone else + * @throws NotAuthorizedException if the current user has no read permission for the workbasket + * the task is in + */ + Task forceClaim(String taskId) + throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, + NotAuthorizedException; - /** - * Cancel the claim of an existing task if it was claimed by the current user before. - * - * @param taskId - * id of the task which should be unclaimed. - * @return updated unclaimed task - * @throws TaskNotFoundException - * if the task can´t be found or does not exist - * @throws InvalidStateException - * when the task is already completed. - * @throws InvalidOwnerException - * when the task is claimed by another user. - * @throws NotAuthorizedException - * if the current user has no read permission for the workbasket the task is in - */ - Task cancelClaim(String taskId) - throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, NotAuthorizedException; + /** + * Cancel the claim of an existing task if it was claimed by the current user before. + * + * @param taskId id of the task which should be unclaimed. + * @return updated unclaimed task + * @throws TaskNotFoundException if the task can´t be found or does not exist + * @throws InvalidStateException when the task is already completed. + * @throws InvalidOwnerException when the task is claimed by another user. + * @throws NotAuthorizedException if the current user has no read permission for the workbasket + * the task is in + */ + Task cancelClaim(String taskId) + throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, + NotAuthorizedException; - /** - * Cancel the claim of an existing task even if it was claimed by another user. - * - * @param taskId - * id of the task which should be unclaimed. - * @return updated unclaimed task - * @throws TaskNotFoundException - * if the task can´t be found or does not exist - * @throws InvalidStateException - * when the task is already completed. - * @throws InvalidOwnerException - * when forceCancel is false and the task is claimed by another user. - * @throws NotAuthorizedException - * if the current user has no read permission for the workbasket the task is in - */ - Task forceCancelClaim(String taskId) - throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, NotAuthorizedException; + /** + * Cancel the claim of an existing task even if it was claimed by another user. + * + * @param taskId id of the task which should be unclaimed. + * @return updated unclaimed task + * @throws TaskNotFoundException if the task can´t be found or does not exist + * @throws InvalidStateException when the task is already completed. + * @throws InvalidOwnerException when forceCancel is false and the task is claimed by another + * user. + * @throws NotAuthorizedException if the current user has no read permission for the workbasket + * the task is in + */ + Task forceCancelClaim(String taskId) + throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, + NotAuthorizedException; - /** - * Complete a claimed Task as owner/admin and update State and Timestamps. If task is already completed, the task is - * returned as itself. - * - * @param taskId - * - Id of the Task which should be completed. - * @return Task - updated task after completion. - * @throws InvalidStateException - * when Task wasn´t claimed before. - * @throws TaskNotFoundException - * if the given Task can´t be found in DB. - * @throws InvalidOwnerException - * if current user is not the task-owner or administrator. - * @throws NotAuthorizedException - * if the current user has no read permission for the workbasket the task is in - */ - Task completeTask(String taskId) - throws TaskNotFoundException, InvalidOwnerException, InvalidStateException, NotAuthorizedException; + /** + * Complete a claimed Task as owner/admin and update State and Timestamps. If task is already + * completed, the task is returned as itself. + * + * @param taskId - Id of the Task which should be completed. + * @return Task - updated task after completion. + * @throws InvalidStateException when Task wasn´t claimed before. + * @throws TaskNotFoundException if the given Task can´t be found in DB. + * @throws InvalidOwnerException if current user is not the task-owner or administrator. + * @throws NotAuthorizedException if the current user has no read permission for the workbasket + * the task is in + */ + Task completeTask(String taskId) + throws TaskNotFoundException, InvalidOwnerException, InvalidStateException, + NotAuthorizedException; - /** - * Complete a Task and update State and Timestamps in every case if the Task exists. If task is already completed, - * the task is returned as itself. - * - * @param taskId - * - Id of the Task which should be completed. - * @return Task - updated task after completion. - * @throws InvalidStateException - * when Task wasn´t claimed before. - * @throws TaskNotFoundException - * if the given Task can´t be found in DB. - * @throws InvalidOwnerException - * if current user is not the task-owner or administrator. - * @throws NotAuthorizedException - * if the current user has no read permission for the workbasket the task is in - */ - Task forceCompleteTask(String taskId) - throws TaskNotFoundException, InvalidOwnerException, InvalidStateException, NotAuthorizedException; + /** + * Complete a Task and update State and Timestamps in every case if the Task exists. If task is + * already completed, the task is returned as itself. + * + * @param taskId - Id of the Task which should be completed. + * @return Task - updated task after completion. + * @throws InvalidStateException when Task wasn´t claimed before. + * @throws TaskNotFoundException if the given Task can´t be found in DB. + * @throws InvalidOwnerException if current user is not the task-owner or administrator. + * @throws NotAuthorizedException if the current user has no read permission for the workbasket + * the task is in + */ + Task forceCompleteTask(String taskId) + throws TaskNotFoundException, InvalidOwnerException, InvalidStateException, + NotAuthorizedException; - /** - * Persists a not persisted Task which does not exist already. - * - * @param taskToCreate - * the transient task object to be persisted - * @return the created and persisted task - * @throws TaskAlreadyExistException - * when the Task does already exist. - * @throws NotAuthorizedException - * thrown if the current user is not authorized to create that task - * @throws WorkbasketNotFoundException - * thrown if the work basket referenced by the task is not found - * @throws ClassificationNotFoundException - * thrown if the {@link Classification} referenced by the task is not found - * @throws InvalidArgumentException - * thrown if the primary ObjectReference is invalid - */ - Task createTask(Task taskToCreate) - throws NotAuthorizedException, WorkbasketNotFoundException, ClassificationNotFoundException, - TaskAlreadyExistException, InvalidArgumentException; + /** + * Persists a not persisted Task which does not exist already. + * + * @param taskToCreate the transient task object to be persisted + * @return the created and persisted task + * @throws TaskAlreadyExistException when the Task does already exist. + * @throws NotAuthorizedException thrown if the current user is not authorized to create that task + * @throws WorkbasketNotFoundException thrown if the work basket referenced by the task is not + * found + * @throws ClassificationNotFoundException thrown if the {@link Classification} referenced by the + * task is not found + * @throws InvalidArgumentException thrown if the primary ObjectReference is invalid + */ + Task createTask(Task taskToCreate) + throws NotAuthorizedException, WorkbasketNotFoundException, ClassificationNotFoundException, + TaskAlreadyExistException, InvalidArgumentException; - /** - * Get the details of a task by Id without checking permissions. - * - * @param taskId - * the id of the task - * @return the Task - * @throws TaskNotFoundException - * thrown of the {@link Task} with taskId is not found - * @throws NotAuthorizedException - * if the current user has no READ permission for the workbasket the task is in. - */ - Task getTask(String taskId) throws TaskNotFoundException, NotAuthorizedException; + /** + * Get the details of a task by Id without checking permissions. + * + * @param taskId the id of the task + * @return the Task + * @throws TaskNotFoundException thrown of the {@link Task} with taskId is not found + * @throws NotAuthorizedException if the current user has no READ permission for the workbasket + * the task is in. + */ + Task getTask(String taskId) throws TaskNotFoundException, NotAuthorizedException; - /** - * Transfer a task to another work basket. The transfer sets the transferred flag and resets the read flag. - * - * @param taskId - * The id of the {@link Task} to be transferred - * @param destinationWorkbasketId - * The Id of the target work basket - * @return the transferred task - * @throws TaskNotFoundException - * Thrown if the {@link Task} with taskId was not found. - * @throws WorkbasketNotFoundException - * Thrown if the target work basket was not found. - * @throws NotAuthorizedException - * Thrown if the current user is not authorized to transfer this {@link Task} to the target work basket - * @throws InvalidStateException - * Thrown if the task is in a state which does not allow transferring - */ - Task transfer(String taskId, String destinationWorkbasketId) - throws TaskNotFoundException, WorkbasketNotFoundException, NotAuthorizedException, InvalidStateException; + /** + * Transfer a task to another work basket. The transfer sets the transferred flag and resets the + * read flag. + * + * @param taskId The id of the {@link Task} to be transferred + * @param destinationWorkbasketId The Id of the target work basket + * @return the transferred task + * @throws TaskNotFoundException Thrown if the {@link Task} with taskId was not found. + * @throws WorkbasketNotFoundException Thrown if the target work basket was not found. + * @throws NotAuthorizedException Thrown if the current user is not authorized to transfer this + * {@link Task} to the target work basket + * @throws InvalidStateException Thrown if the task is in a state which does not allow + * transferring + */ + Task transfer(String taskId, String destinationWorkbasketId) + throws TaskNotFoundException, WorkbasketNotFoundException, NotAuthorizedException, + InvalidStateException; - /** - * Transfer a task to another work basket. The transfer sets the transferred flag and resets the read flag. - * - * @param taskId - * The id of the {@link Task} to be transferred - * @param workbasketKey - * The key of the target work basket - * @param domain - * The domain of the target work basket - * @return the transferred task - * @throws TaskNotFoundException - * Thrown if the {@link Task} with taskId was not found. - * @throws WorkbasketNotFoundException - * Thrown if the target work basket was not found. - * @throws NotAuthorizedException - * Thrown if the current user is not authorized to transfer this {@link Task} to the target work basket - * @throws InvalidStateException - * Thrown if the task is in a state which does not allow transferring - */ - Task transfer(String taskId, String workbasketKey, String domain) - throws TaskNotFoundException, WorkbasketNotFoundException, NotAuthorizedException, InvalidStateException; + /** + * Transfer a task to another work basket. The transfer sets the transferred flag and resets the + * read flag. + * + * @param taskId The id of the {@link Task} to be transferred + * @param workbasketKey The key of the target work basket + * @param domain The domain of the target work basket + * @return the transferred task + * @throws TaskNotFoundException Thrown if the {@link Task} with taskId was not found. + * @throws WorkbasketNotFoundException Thrown if the target work basket was not found. + * @throws NotAuthorizedException Thrown if the current user is not authorized to transfer this + * {@link Task} to the target work basket + * @throws InvalidStateException Thrown if the task is in a state which does not allow + * transferring + */ + Task transfer(String taskId, String workbasketKey, String domain) + throws TaskNotFoundException, WorkbasketNotFoundException, NotAuthorizedException, + InvalidStateException; - /** - * Marks a task as read. - * - * @param taskId - * the id of the task to be updated - * @param isRead - * the new status of the read flag. - * @return the updated Task - * @throws TaskNotFoundException - * Thrown if the {@link Task} with taskId was not found - * @throws NotAuthorizedException - * if the current user has no read permission for the workbasket the task is in - */ - Task setTaskRead(String taskId, boolean isRead) - throws TaskNotFoundException, NotAuthorizedException; + /** + * Marks a task as read. + * + * @param taskId the id of the task to be updated + * @param isRead the new status of the read flag. + * @return the updated Task + * @throws TaskNotFoundException Thrown if the {@link Task} with taskId was not found + * @throws NotAuthorizedException if the current user has no read permission for the workbasket + * the task is in + */ + Task setTaskRead(String taskId, boolean isRead) + throws TaskNotFoundException, NotAuthorizedException; - /** - * This method provides a query builder for quering the database. - * - * @return a {@link TaskQuery} - */ - TaskQuery createTaskQuery(); + /** + * This method provides a query builder for quering the database. + * + * @return a {@link TaskQuery} + */ + TaskQuery createTaskQuery(); - /** - * Returns a not persisted instance of {@link Task}. - * The returned task has no workbasket Id set. When createTask() is - * invoked for this task, TaskService will call the TaskRouting SPI to - * determine a workbasket for the task. If the TaskRouting API is not active, - * e.g. because no TaskRouter is registered, or the TaskRouter(s) don't find a workbasket, - * the task will not be persisted. - * - * @return an empty new Task - */ - Task newTask(); + /** + * Returns a not persisted instance of {@link Task}. The returned task has no workbasket Id set. + * When createTask() is invoked for this task, TaskService will call the TaskRouting SPI to + * determine a workbasket for the task. If the TaskRouting API is not active, e.g. because no + * TaskRouter is registered, or the TaskRouter(s) don't find a workbasket, the task will not be + * persisted. + * + * @return an empty new Task + */ + Task newTask(); - /** - * Returns a not persisted instance of {@link Task}. - * - * @param workbasketId - * the id of the workbasket to which the task belongs - * @return an empty new Task - */ - Task newTask(String workbasketId); + /** + * Returns a not persisted instance of {@link Task}. + * + * @param workbasketId the id of the workbasket to which the task belongs + * @return an empty new Task + */ + Task newTask(String workbasketId); - /** - * Returns a not persisted instance of {@link Task}. - * - * @param workbasketKey - * the key of the workbasket to which the task belongs - * @param domain - * the domain of the workbasket to which the task belongs - * @return an empty new Task - */ - Task newTask(String workbasketKey, String domain); + /** + * Returns a not persisted instance of {@link Task}. + * + * @param workbasketKey the key of the workbasket to which the task belongs + * @param domain the domain of the workbasket to which the task belongs + * @return an empty new Task + */ + Task newTask(String workbasketKey, String domain); - /** - * Returns a not persisted instance of {@link Attachment}. - * - * @return an empty new Attachment - */ - Attachment newAttachment(); + /** + * Returns a not persisted instance of {@link Attachment}. + * + * @return an empty new Attachment + */ + Attachment newAttachment(); - /** - * Update a task. - * - * @param task - * the task to be updated in the database - * @return the updated task - * @throws InvalidArgumentException - * if the task to be updated contains invalid properties like e.g. invalid object references - * @throws TaskNotFoundException - * if the id of the task is not found in the database - * @throws ConcurrencyException - * if the task has already been updated by another user - * @throws ClassificationNotFoundException - * if the updated task refers to a classification that cannot be found - * @throws NotAuthorizedException - * if the current user is not authorized to update the task - * @throws AttachmentPersistenceException - * if an Attachment with ID will be added multiple times without using the task-methods. - */ - Task updateTask(Task task) throws InvalidArgumentException, TaskNotFoundException, ConcurrencyException, - ClassificationNotFoundException, NotAuthorizedException, AttachmentPersistenceException; + /** + * Update a task. + * + * @param task the task to be updated in the database + * @return the updated task + * @throws InvalidArgumentException if the task to be updated contains invalid properties like + * e.g. invalid object references + * @throws TaskNotFoundException if the id of the task is not found in the database + * @throws ConcurrencyException if the task has already been updated by another user + * @throws ClassificationNotFoundException if the updated task refers to a classification that + * cannot be found + * @throws NotAuthorizedException if the current user is not authorized to update the task + * @throws AttachmentPersistenceException if an Attachment with ID will be added multiple times + * without using the task-methods. + */ + Task updateTask(Task task) + throws InvalidArgumentException, TaskNotFoundException, ConcurrencyException, + ClassificationNotFoundException, NotAuthorizedException, AttachmentPersistenceException; - /** - * Transfers a list of tasks to an other workbasket. Exceptions will be thrown if the caller got no permissions on - * the target or it doesn´t exist. Other Exceptions will be stored and returned in the end. - * - * @param destinationWorkbasketId - * target workbasket id - * @param taskIds - * source task which will be moved - * @return Bulkresult with ID and Error in it for failed transactions. - * @throws NotAuthorizedException - * if the caller hasn´t permissions on tarket WB. - * @throws InvalidArgumentException - * if the method paramesters are EMPTY or NULL. - * @throws WorkbasketNotFoundException - * if the target WB can´t be found. - */ - BulkOperationResults transferTasks(String destinationWorkbasketId, List taskIds) - throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException; + /** + * Transfers a list of tasks to an other workbasket. Exceptions will be thrown if the caller got + * no permissions on the target or it doesn´t exist. Other Exceptions will be stored and returned + * in the end. + * + * @param destinationWorkbasketId target workbasket id + * @param taskIds source task which will be moved + * @return Bulkresult with ID and Error in it for failed transactions. + * @throws NotAuthorizedException if the caller hasn´t permissions on tarket WB. + * @throws InvalidArgumentException if the method paramesters are EMPTY or NULL. + * @throws WorkbasketNotFoundException if the target WB can´t be found. + */ + BulkOperationResults transferTasks( + String destinationWorkbasketId, List taskIds) + throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException; - /** - * Transfers a list of tasks to an other workbasket. Exceptions will be thrown if the caller got no permissions on - * the target or it doesn´t exist. Other Exceptions will be stored and returned in the end. - * - * @param destinationWorkbasketKey - * target workbasket key - * @param destinationWorkbasketDomain - * target workbasket domain - * @param taskIds - * source task which will be moved - * @return Bulkresult with ID and Error in it for failed transactions. - * @throws NotAuthorizedException - * if the caller hasn´t permissions on tarket WB. - * @throws InvalidArgumentException - * if the method paramesters are EMPTY or NULL. - * @throws WorkbasketNotFoundException - * if the target WB can´t be found. - */ - BulkOperationResults transferTasks(String destinationWorkbasketKey, - String destinationWorkbasketDomain, List taskIds) - throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException; + /** + * Transfers a list of tasks to an other workbasket. Exceptions will be thrown if the caller got + * no permissions on the target or it doesn´t exist. Other Exceptions will be stored and returned + * in the end. + * + * @param destinationWorkbasketKey target workbasket key + * @param destinationWorkbasketDomain target workbasket domain + * @param taskIds source task which will be moved + * @return Bulkresult with ID and Error in it for failed transactions. + * @throws NotAuthorizedException if the caller hasn´t permissions on tarket WB. + * @throws InvalidArgumentException if the method paramesters are EMPTY or NULL. + * @throws WorkbasketNotFoundException if the target WB can´t be found. + */ + BulkOperationResults transferTasks( + String destinationWorkbasketKey, String destinationWorkbasketDomain, List taskIds) + throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException; - /** - * Deletes the task with the given Id. - * - * @param taskId - * The Id of the task to delete. - * @throws TaskNotFoundException - * If the given Id does not refer to an existing task. - * @throws InvalidStateException - * If the state of the referenced task is not Completed. - * @throws NotAuthorizedException - * if the current user is not member of role ADMIN - */ - void deleteTask(String taskId) - throws TaskNotFoundException, InvalidStateException, NotAuthorizedException; + /** + * Deletes the task with the given Id. + * + * @param taskId The Id of the task to delete. + * @throws TaskNotFoundException If the given Id does not refer to an existing task. + * @throws InvalidStateException If the state of the referenced task is not Completed. + * @throws NotAuthorizedException if the current user is not member of role ADMIN + */ + void deleteTask(String taskId) + throws TaskNotFoundException, InvalidStateException, NotAuthorizedException; - /** - * Deletes the task with the given Id even if it is not completed. - * - * @param taskId - * The Id of the task to delete. - * @throws TaskNotFoundException - * If the given Id does not refer to an existing task. - * @throws InvalidStateException - * If the state of the referenced task is not Completed and forceDelet is false. - * @throws NotAuthorizedException - * if the current user is not member of role ADMIN - */ - void forceDeleteTask(String taskId) - throws TaskNotFoundException, InvalidStateException, NotAuthorizedException; + /** + * Deletes the task with the given Id even if it is not completed. + * + * @param taskId The Id of the task to delete. + * @throws TaskNotFoundException If the given Id does not refer to an existing task. + * @throws InvalidStateException If the state of the referenced task is not Completed and + * forceDelet is false. + * @throws NotAuthorizedException if the current user is not member of role ADMIN + */ + void forceDeleteTask(String taskId) + throws TaskNotFoundException, InvalidStateException, NotAuthorizedException; - /** - * Deletes a list of tasks. - * - * @param tasks - * the ids of the tasks to delete. - * @return the result of the operations with Id and Exception for each failed task deletion. - * @throws InvalidArgumentException - * if the TaskIds parameter is NULL - */ - BulkOperationResults deleteTasks(List tasks) throws InvalidArgumentException; + /** + * Deletes a list of tasks. + * + * @param tasks the ids of the tasks to delete. + * @return the result of the operations with Id and Exception for each failed task deletion. + * @throws InvalidArgumentException if the TaskIds parameter is NULL + */ + BulkOperationResults deleteTasks(List tasks) + throws InvalidArgumentException; - /** - * Completes a list of tasks. - * - * @param taskIds - * of the tasks which should be completed. - * @return the result of the operations with Id and Exception for each failed task completion. - * @throws InvalidArgumentException - * If the taskId parameter is NULL. - */ - BulkOperationResults completeTasks(List taskIds) - throws InvalidArgumentException; + /** + * Completes a list of tasks. + * + * @param taskIds of the tasks which should be completed. + * @return the result of the operations with Id and Exception for each failed task completion. + * @throws InvalidArgumentException If the taskId parameter is NULL. + */ + BulkOperationResults completeTasks(List taskIds) + throws InvalidArgumentException; - /** - * Updates tasks with a matching {@link ObjectReference}. - * - * @param selectionCriteria - * the {@link ObjectReference} that is used to select the tasks. - * @param customFieldsToUpdate - * a {@link Map} that contains as key the identification of the custom field and as value the - * corresponding new value of that custom field. The key for identification of the custom field must be a - * String with value "1", "2" ... "16" as in the setCustomAttribute or getCustomAttribute method of - * {@link Task} - * @return a list of the Ids of all modified tasks - * @throws InvalidArgumentException - * If the customFieldsToUpdate map contains an invalid key or if the selectionCriteria is invalid - */ - List updateTasks(ObjectReference selectionCriteria, - Map customFieldsToUpdate) throws InvalidArgumentException; + /** + * Updates tasks with a matching {@link ObjectReference}. + * + * @param selectionCriteria the {@link ObjectReference} that is used to select the tasks. + * @param customFieldsToUpdate a {@link Map} that contains as key the identification of the custom + * field and as value the corresponding new value of that custom field. The key for + * identification of the custom field must be a String with value "1", "2" ... "16" as in the + * setCustomAttribute or getCustomAttribute method of {@link Task} + * @return a list of the Ids of all modified tasks + * @throws InvalidArgumentException If the customFieldsToUpdate map contains an invalid key or if + * the selectionCriteria is invalid + */ + List updateTasks( + ObjectReference selectionCriteria, Map customFieldsToUpdate) + throws InvalidArgumentException; - /** - * Updates tasks with matching taskIds. - * - * @param taskIds - * the taskIds that are used to select the tasks. - * @param customFieldsToUpdate - * a {@link Map} that contains as key the identification of the custom field and as value the - * corresponding new value of that custom field. The key for identification of the custom field must be a - * String with value "1", "2" ... "16" as in the setCustomAttribute or getCustomAttribute method of - * {@link Task} - * @return a list of the Ids of all modified tasks - * @throws InvalidArgumentException - * If the customFieldsToUpdate map contains an invalid key or if the selectionCriteria is invalid - */ - List updateTasks(List taskIds, - Map customFieldsToUpdate) throws InvalidArgumentException; - - /** - * Sets the callback state on a list of tasks. - * Note: this method is primarily intended to be used by the TaskanaAdapter - * - * @param externalIds the EXTERNAL_IDs of the tasks on which the callback state is set. - * @param state the callback state that is to be set on the tasks - * - * @return the result of the operations with Id and Exception for each failed task deletion. - */ - BulkOperationResults setCallbackStateForTasks(List externalIds, CallbackState state); + /** + * Updates tasks with matching taskIds. + * + * @param taskIds the taskIds that are used to select the tasks. + * @param customFieldsToUpdate a {@link Map} that contains as key the identification of the custom + * field and as value the corresponding new value of that custom field. The key for + * identification of the custom field must be a String with value "1", "2" ... "16" as in the + * setCustomAttribute or getCustomAttribute method of {@link Task} + * @return a list of the Ids of all modified tasks + * @throws InvalidArgumentException If the customFieldsToUpdate map contains an invalid key or if + * the selectionCriteria is invalid + */ + List updateTasks(List taskIds, Map customFieldsToUpdate) + throws InvalidArgumentException; + /** + * Sets the callback state on a list of tasks. Note: this method is primarily intended to be used + * by the TaskanaAdapter + * + * @param externalIds the EXTERNAL_IDs of the tasks on which the callback state is set. + * @param state the callback state that is to be set on the tasks + * @return the result of the operations with Id and Exception for each failed task deletion. + */ + BulkOperationResults setCallbackStateForTasks( + List externalIds, CallbackState state); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/TaskState.java b/lib/taskana-core/src/main/java/pro/taskana/TaskState.java index 979c5ff77..389318fa7 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/TaskState.java +++ b/lib/taskana-core/src/main/java/pro/taskana/TaskState.java @@ -1,8 +1,8 @@ package pro.taskana; -/** - * This enum contains all status of the tasks. - */ +/** This enum contains all status of the tasks. */ public enum TaskState { - READY, CLAIMED, COMPLETED + READY, + CLAIMED, + COMPLETED } diff --git a/lib/taskana-core/src/main/java/pro/taskana/TaskSummary.java b/lib/taskana-core/src/main/java/pro/taskana/TaskSummary.java index 30f354dca..ee631f1f6 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/TaskSummary.java +++ b/lib/taskana-core/src/main/java/pro/taskana/TaskSummary.java @@ -6,182 +6,180 @@ import java.util.List; import pro.taskana.exceptions.InvalidArgumentException; /** - * Interface for TaskSummary. This is a specific short model-object which only contains the most important information. + * Interface for TaskSummary. This is a specific short model-object which only contains the most + * important information. */ public interface TaskSummary { - /** - * Gets the id of the task. - * - * @return taskId - */ - String getTaskId(); + /** + * Gets the id of the task. + * + * @return taskId + */ + String getTaskId(); - /** - * Gets the external id of the task. - * - * @return the external Id - */ - String getExternalId(); + /** + * Gets the external id of the task. + * + * @return the external Id + */ + String getExternalId(); - /** - * Gets the name of the task-creator. - * - * @return creator - */ - String getCreator(); + /** + * Gets the name of the task-creator. + * + * @return creator + */ + String getCreator(); - /** - * Gets the time when the task was created. - * - * @return the created Instant - */ - Instant getCreated(); + /** + * Gets the time when the task was created. + * + * @return the created Instant + */ + Instant getCreated(); - /** - * Gets the time when the task was claimed. - * - * @return the claimed Instant - */ - Instant getClaimed(); + /** + * Gets the time when the task was claimed. + * + * @return the claimed Instant + */ + Instant getClaimed(); - /** - * Gets the time when the task was completed. - * - * @return the completed Instant - */ - Instant getCompleted(); + /** + * Gets the time when the task was completed. + * + * @return the completed Instant + */ + Instant getCompleted(); - /** - * Gets the time when the task was last modified. - * - * @return the last modified Instant - */ - Instant getModified(); + /** + * Gets the time when the task was last modified. + * + * @return the last modified Instant + */ + Instant getModified(); - /** - * Gets the time when the task is planned to be executed. - * - * @return the planned Instant - */ - Instant getPlanned(); + /** + * Gets the time when the task is planned to be executed. + * + * @return the planned Instant + */ + Instant getPlanned(); - /** - * Gets the time when the task is due. - * - * @return the due Instant - */ - Instant getDue(); + /** + * Gets the time when the task is due. + * + * @return the due Instant + */ + Instant getDue(); - /** - * Gets the name of the task. - * - * @return the task's name - */ - String getName(); + /** + * Gets the name of the task. + * + * @return the task's name + */ + String getName(); - /** - * Gets the note attached to the task. - * - * @return the task's note - */ - String getNote(); + /** + * Gets the note attached to the task. + * + * @return the task's note + */ + String getNote(); - /** - * Gets the priority of the task. - * - * @return the task's priority - */ - int getPriority(); + /** + * Gets the priority of the task. + * + * @return the task's priority + */ + int getPriority(); - /** - * Gets the state of the task. - * - * @return the task's state - */ - TaskState getState(); + /** + * Gets the state of the task. + * + * @return the task's state + */ + TaskState getState(); - /** - * Gets the classification summary of the task. - * - * @return the task's classificationSummary - */ - ClassificationSummary getClassificationSummary(); + /** + * Gets the classification summary of the task. + * + * @return the task's classificationSummary + */ + ClassificationSummary getClassificationSummary(); - /** - * Gets the workbasket summary of the task. - * - * @return the task's workbasketSummary - */ - WorkbasketSummary getWorkbasketSummary(); + /** + * Gets the workbasket summary of the task. + * + * @return the task's workbasketSummary + */ + WorkbasketSummary getWorkbasketSummary(); - /** - * Gets the attachment summaries of the task. - * - * @return the task's attachment summaries - */ - List getAttachmentSummaries(); + /** + * Gets the attachment summaries of the task. + * + * @return the task's attachment summaries + */ + List getAttachmentSummaries(); - /** - * Gets the domain of the task. - * - * @return the task's domain - */ - String getDomain(); + /** + * Gets the domain of the task. + * + * @return the task's domain + */ + String getDomain(); - /** - * Gets the businessProcessId of the task. - * - * @return the task's businessProcessId - */ - String getBusinessProcessId(); + /** + * Gets the businessProcessId of the task. + * + * @return the task's businessProcessId + */ + String getBusinessProcessId(); - /** - * Gets the parentBusinessProcessId of the task. - * - * @return the task's parentBusinessProcessId - */ - String getParentBusinessProcessId(); + /** + * Gets the parentBusinessProcessId of the task. + * + * @return the task's parentBusinessProcessId + */ + String getParentBusinessProcessId(); - /** - * Gets the owner of the task. - * - * @return the task's owner - */ - String getOwner(); + /** + * Gets the owner of the task. + * + * @return the task's owner + */ + String getOwner(); - /** - * Gets the primary ObjectReference of the task. - * - * @return the task's primary ObjectReference - */ - ObjectReference getPrimaryObjRef(); + /** + * Gets the primary ObjectReference of the task. + * + * @return the task's primary ObjectReference + */ + ObjectReference getPrimaryObjRef(); - /** - * Gets the isRead flag of the task. - * - * @return the task's isRead flag - */ - boolean isRead(); + /** + * Gets the isRead flag of the task. + * + * @return the task's isRead flag + */ + boolean isRead(); - /** - * Gets the isTransferred flag of the task. - * - * @return the task's isTransferred flag. - */ - boolean isTransferred(); - - /** - * Gets the custom attribute number num of the task. - * - * @param num - * identifies which custom attribute is requested. Taskana concatenates "custom_" with num and the - * resulting String must match the name of the database column that contains the custom attribute. Valid - * values are "1", "2" .. "16" - * @return the value of custom attribute number num - * @throws InvalidArgumentException - * if num has not a value of "1", "2" ... "16" - */ - String getCustomAttribute(String num) throws InvalidArgumentException; + /** + * Gets the isTransferred flag of the task. + * + * @return the task's isTransferred flag. + */ + boolean isTransferred(); + /** + * Gets the custom attribute number num of the task. + * + * @param num identifies which custom attribute is requested. Taskana concatenates "custom_" with + * num and the resulting String must match the name of the database column that contains the + * custom attribute. Valid values are "1", "2" .. "16" + * @return the value of custom attribute number num + * @throws InvalidArgumentException if num has not a value of "1", "2" ... "16" + */ + String getCustomAttribute(String num) throws InvalidArgumentException; } diff --git a/lib/taskana-core/src/main/java/pro/taskana/TaskanaEngine.java b/lib/taskana-core/src/main/java/pro/taskana/TaskanaEngine.java index 019a0f423..e819e3678 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/TaskanaEngine.java +++ b/lib/taskana-core/src/main/java/pro/taskana/TaskanaEngine.java @@ -5,123 +5,116 @@ import java.sql.SQLException; import pro.taskana.configuration.TaskanaEngineConfiguration; import pro.taskana.exceptions.NotAuthorizedException; -/** - * The TaskanaEngine represents an overall set of all needed services. - */ +/** The TaskanaEngine represents an overall set of all needed services. */ public interface TaskanaEngine { - /** - * The TaskService can be used for operations on all Tasks. - * - * @return the TaskService - */ - TaskService getTaskService(); + /** + * The TaskService can be used for operations on all Tasks. + * + * @return the TaskService + */ + TaskService getTaskService(); - /** - * The TaskMonitorService can be used for monitoring Tasks. - * - * @return the TaskMonitorService - */ - TaskMonitorService getTaskMonitorService(); + /** + * The TaskMonitorService can be used for monitoring Tasks. + * + * @return the TaskMonitorService + */ + TaskMonitorService getTaskMonitorService(); - /** - * The WorkbasketService can be used for operations on all Workbaskets. - * - * @return the TaskService - */ - WorkbasketService getWorkbasketService(); + /** + * The WorkbasketService can be used for operations on all Workbaskets. + * + * @return the TaskService + */ + WorkbasketService getWorkbasketService(); - /** - * The ClassificationService can be used for operations on all Categories. - * - * @return the TaskService - */ - ClassificationService getClassificationService(); + /** + * The ClassificationService can be used for operations on all Categories. + * + * @return the TaskService + */ + ClassificationService getClassificationService(); - /** - * The JobService can be user for all job operations. - * - * @return the JobService - */ - JobService getJobService(); + /** + * The JobService can be user for all job operations. + * + * @return the JobService + */ + JobService getJobService(); - /** - * The Taskana configuration. - * - * @return the TaskanaConfiguration - */ - TaskanaEngineConfiguration getConfiguration(); + /** + * The Taskana configuration. + * + * @return the TaskanaConfiguration + */ + TaskanaEngineConfiguration getConfiguration(); - /** - * Checks if the history plugin is enabled. - * - * @return true if the history is enabled. Otherwise false. - */ - boolean isHistoryEnabled(); + /** + * Checks if the history plugin is enabled. + * + * @return true if the history is enabled. Otherwise false. + */ + boolean isHistoryEnabled(); - /** - * sets the connection management mode. - * - * @param mode - * the connection management mode Valid values are: - *
    - *
  • PARTICIPATE - taskana participates in global transaction. This is the default mode.
  • - *
  • AUTOCOMMIT - taskana commits each API call separately
  • - *
  • EXPLICIT - commit processing is managed explicitly by the client
  • - *
- */ - void setConnectionManagementMode(ConnectionManagementMode mode); + /** + * sets the connection management mode. + * + * @param mode the connection management mode Valid values are: + *
    + *
  • PARTICIPATE - taskana participates in global transaction. This is the default mode. + *
  • AUTOCOMMIT - taskana commits each API call separately + *
  • EXPLICIT - commit processing is managed explicitly by the client + *
+ */ + void setConnectionManagementMode(ConnectionManagementMode mode); - /** - * Set the connection to be used by taskana in mode CONNECTION_MANAGED_EXTERNALLY. If this Api is called, taskana - * uses the connection passed by the client for all subsequent API calls until the client resets this connection. - * Control over commit and rollback of the connection is the responsibility of the client. In order to close the - * connection, closeConnection() or setConnection(null) has to be called. - * - * @param connection - * - The java.sql.Connection that is controlled by the client - * @throws SQLException - * if a database access error occurs - */ - void setConnection(java.sql.Connection connection) throws SQLException; + /** + * Set the connection to be used by taskana in mode CONNECTION_MANAGED_EXTERNALLY. If this Api is + * called, taskana uses the connection passed by the client for all subsequent API calls until the + * client resets this connection. Control over commit and rollback of the connection is the + * responsibility of the client. In order to close the connection, closeConnection() or + * setConnection(null) has to be called. + * + * @param connection - The java.sql.Connection that is controlled by the client + * @throws SQLException if a database access error occurs + */ + void setConnection(java.sql.Connection connection) throws SQLException; - /** - * Closes the client's connection, sets it to null and switches to mode PARTICIPATE. Only applicable in mode - * EXPLICIT. Has the same effect as setConnection(null). - */ - void closeConnection(); + /** + * Closes the client's connection, sets it to null and switches to mode PARTICIPATE. Only + * applicable in mode EXPLICIT. Has the same effect as setConnection(null). + */ + void closeConnection(); - /** - * check whether the current user is member of one of the roles specified. - * - * @param roles - * The roles that are checked for membership of the current user - * @return true if the current user is a member of at least one of the specified groups - */ - boolean isUserInRole(TaskanaRole... roles); + /** + * check whether the current user is member of one of the roles specified. + * + * @param roles The roles that are checked for membership of the current user + * @return true if the current user is a member of at least one of the specified groups + */ + boolean isUserInRole(TaskanaRole... roles); - /** - * Checks whether current user is member of any of the specified roles. - * - * @param roles - * The roles that are checked for membership of the current user - * @throws NotAuthorizedException - * If the current user is not member of any specified role - */ - void checkRoleMembership(TaskanaRole... roles) throws NotAuthorizedException; - - /** - * Connection management mode. Controls the connection handling of taskana - *
    - *
  • PARTICIPATE - taskana participates in global transaction. This is the default mode
  • - *
  • AUTOCOMMIT - taskana commits each API call separately
  • - *
  • EXPLICIT - commit processing is managed explicitly by the client
  • - *
- */ - enum ConnectionManagementMode { - PARTICIPATE, - AUTOCOMMIT, - EXPLICIT - } + /** + * Checks whether current user is member of any of the specified roles. + * + * @param roles The roles that are checked for membership of the current user + * @throws NotAuthorizedException If the current user is not member of any specified role + */ + void checkRoleMembership(TaskanaRole... roles) throws NotAuthorizedException; + /** + * Connection management mode. Controls the connection handling of taskana + * + *
    + *
  • PARTICIPATE - taskana participates in global transaction. This is the default mode + *
  • AUTOCOMMIT - taskana commits each API call separately + *
  • EXPLICIT - commit processing is managed explicitly by the client + *
+ */ + enum ConnectionManagementMode { + PARTICIPATE, + AUTOCOMMIT, + EXPLICIT + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/TaskanaRole.java b/lib/taskana-core/src/main/java/pro/taskana/TaskanaRole.java index 777d2f06b..77da507b8 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/TaskanaRole.java +++ b/lib/taskana-core/src/main/java/pro/taskana/TaskanaRole.java @@ -6,36 +6,33 @@ import java.util.stream.Collectors; import pro.taskana.exceptions.SystemException; -/** - * This enum contains all roles that are known to taskana. - */ +/** This enum contains all roles that are known to taskana. */ public enum TaskanaRole { - USER("taskana.roles.user"), - BUSINESS_ADMIN("taskana.roles.businessadmin"), - ADMIN("taskana.roles.admin"), - MONITOR("taskana.roles.monitor"); + USER("taskana.roles.user"), + BUSINESS_ADMIN("taskana.roles.businessadmin"), + ADMIN("taskana.roles.admin"), + MONITOR("taskana.roles.monitor"); - private final String propertyName; + private final String propertyName; - TaskanaRole(String propertyName) { - this.propertyName = propertyName; - } + TaskanaRole(String propertyName) { + this.propertyName = propertyName; + } - public static TaskanaRole fromPropertyName(String name) { - return Arrays.stream(TaskanaRole.values()) - .filter(x -> x.propertyName.equalsIgnoreCase(name)) - .findFirst() - .orElseThrow(() -> new SystemException( - "Internal System error when processing role property " + name)); - } + public static TaskanaRole fromPropertyName(String name) { + return Arrays.stream(TaskanaRole.values()) + .filter(x -> x.propertyName.equalsIgnoreCase(name)) + .findFirst() + .orElseThrow( + () -> + new SystemException("Internal System error when processing role property " + name)); + } - public static List getValidPropertyNames() { - return Arrays.stream(values()) - .map(TaskanaRole::getPropertyName) - .collect(Collectors.toList()); - } + public static List getValidPropertyNames() { + return Arrays.stream(values()).map(TaskanaRole::getPropertyName).collect(Collectors.toList()); + } - public String getPropertyName() { - return propertyName; - } + public String getPropertyName() { + return propertyName; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/TimeInterval.java b/lib/taskana-core/src/main/java/pro/taskana/TimeInterval.java index d2aa40945..daf7e0321 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/TimeInterval.java +++ b/lib/taskana-core/src/main/java/pro/taskana/TimeInterval.java @@ -3,95 +3,94 @@ package pro.taskana; import java.time.Instant; /** - * Capture a time interval. A fixed interval has defined begin and end Instant. An open ended interval has either begin - * == null or end ==null. + * Capture a time interval. A fixed interval has defined begin and end Instant. An open ended + * interval has either begin == null or end ==null. * * @author bbr */ public class TimeInterval { - private Instant begin; - private Instant end; + private Instant begin; + private Instant end; - public TimeInterval(Instant begin, Instant end) { - this.begin = begin; - this.end = end; + public TimeInterval(Instant begin, Instant end) { + this.begin = begin; + this.end = end; + } + + public boolean contains(Instant i) { + if (i == null) { + return false; } + boolean isAfterBegin = begin == null ? true : !i.isBefore(begin); + boolean isBeforeEnd = end == null ? true : !i.isAfter(end); + return (isAfterBegin && isBeforeEnd); + } - public boolean contains(Instant i) { - if (i == null) { - return false; - } - boolean isAfterBegin = begin == null ? true : !i.isBefore(begin); - boolean isBeforeEnd = end == null ? true : !i.isAfter(end); - return (isAfterBegin && isBeforeEnd); + public boolean isValid() { + boolean isValid = begin != null || end != null; + if (begin != null && end != null && begin.isAfter(end)) { + isValid = false; } + return isValid; + } - public boolean isValid() { - boolean isValid = begin != null || end != null; - if (begin != null && end != null && begin.isAfter(end)) { - isValid = false; - } - return isValid; + public Instant getBegin() { + return begin; + } + + public void setBegin(Instant begin) { + this.begin = begin; + } + + public Instant getEnd() { + return end; + } + + public void setEnd(Instant end) { + this.end = end; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((begin == null) ? 0 : begin.hashCode()); + result = prime * result + ((end == null) ? 0 : end.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; } - - public Instant getBegin() { - return begin; + if (obj == null) { + return false; } - - public void setBegin(Instant begin) { - this.begin = begin; + if (!getClass().isAssignableFrom(obj.getClass())) { + return false; } - - public Instant getEnd() { - return end; + TimeInterval other = (TimeInterval) obj; + if (begin == null) { + if (other.begin != null) { + return false; + } + } else if (!begin.equals(other.begin)) { + return false; } - - public void setEnd(Instant end) { - this.end = end; - } - - @Override - public String toString() { - return "TimeInterval [" + "begin=" + this.begin + ", end=" + this.end + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((begin == null) ? 0 : begin.hashCode()); - result = prime * result + ((end == null) ? 0 : end.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!getClass().isAssignableFrom(obj.getClass())) { - return false; - } - TimeInterval other = (TimeInterval) obj; - if (begin == null) { - if (other.begin != null) { - return false; - } - } else if (!begin.equals(other.begin)) { - return false; - } - if (end == null) { - if (other.end != null) { - return false; - } - } else if (!end.equals(other.end)) { - return false; - } - return true; + if (end == null) { + if (other.end != null) { + return false; + } + } else if (!end.equals(other.end)) { + return false; } + return true; + } + @Override + public String toString() { + return "TimeInterval [" + "begin=" + this.begin + ", end=" + this.end + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/Workbasket.java b/lib/taskana-core/src/main/java/pro/taskana/Workbasket.java index bdce997d7..344b5644c 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/Workbasket.java +++ b/lib/taskana-core/src/main/java/pro/taskana/Workbasket.java @@ -1,251 +1,235 @@ package pro.taskana; -import java.time.Instant; - import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.time.Instant; import pro.taskana.impl.WorkbasketImpl; -/** - * Workbasket entity interface. - */ +/** Workbasket entity interface. */ @JsonDeserialize(as = WorkbasketImpl.class) public interface Workbasket { - /** - * Returns the unique id of a workbasket. - * - * @return workbasketId - */ - String getId(); + /** + * Returns the unique id of a workbasket. + * + * @return workbasketId + */ + String getId(); - /** - * Returns the date when the workbasket was created. - * - * @return created as Instant - */ - Instant getCreated(); + /** + * Returns the date when the workbasket was created. + * + * @return created as Instant + */ + Instant getCreated(); - /** - * Returns the key of the workbasket. - * - * @return the key of the workbasket - */ - String getKey(); + /** + * Returns the key of the workbasket. + * + * @return the key of the workbasket + */ + String getKey(); - /** - * Returns the domain of the workbasket. - * - * @return domain of the workbasket - */ - String getDomain(); + /** + * Returns the domain of the workbasket. + * + * @return domain of the workbasket + */ + String getDomain(); - /** - * Returns the type of the workbasket. - * - * @return the type of the workbasket - */ - WorkbasketType getType(); + /** + * Returns the type of the workbasket. + * + * @return the type of the workbasket + */ + WorkbasketType getType(); - /** - * Sets the type of the workbasket. - * - * @param type - * the type of the workbasket - */ - void setType(WorkbasketType type); + /** + * Sets the type of the workbasket. + * + * @param type the type of the workbasket + */ + void setType(WorkbasketType type); - /** - * Returns the date when the workbasket was modified the last time. - * - * @return modified as Instant - */ - Instant getModified(); + /** + * Returns the date when the workbasket was modified the last time. + * + * @return modified as Instant + */ + Instant getModified(); - /** - * Returns the name of the workbasket. - * - * @return workbasketName - */ - String getName(); + /** + * Returns the name of the workbasket. + * + * @return workbasketName + */ + String getName(); - /** - * Sets the name of the workbasket. - * - * @param workbasketName - * the name of the workbasket - */ - void setName(String workbasketName); + /** + * Sets the name of the workbasket. + * + * @param workbasketName the name of the workbasket + */ + void setName(String workbasketName); - /** - * Returns the workbasket-descriptions. - * - * @return description - */ - String getDescription(); + /** + * Returns the workbasket-descriptions. + * + * @return description + */ + String getDescription(); - /** - * Sets the workbasket-descriptions. - * - * @param description - * the description of the workbasket - */ - void setDescription(String description); + /** + * Sets the workbasket-descriptions. + * + * @param description the description of the workbasket + */ + void setDescription(String description); - /** - * Returns the Id of the workbasket-owner. - * - * @return ownerId - */ - String getOwner(); + /** + * Returns the Id of the workbasket-owner. + * + * @return ownerId + */ + String getOwner(); - /** - * Sets the owner-ID of the workbasket. - * - * @param owner - * of the current workbasket - */ - void setOwner(String owner); + /** + * Sets the owner-ID of the workbasket. + * + * @param owner of the current workbasket + */ + void setOwner(String owner); - /** - * Return the value for the custom1 attribute. - * - * @return custom1 - */ - String getCustom1(); + /** + * Return the value for the custom1 attribute. + * + * @return custom1 + */ + String getCustom1(); - /** - * Sets the value for custom1 Attribute. - * - * @param custom1 - * the custom1 property of the workbasket - */ - void setCustom1(String custom1); + /** + * Sets the value for custom1 Attribute. + * + * @param custom1 the custom1 property of the workbasket + */ + void setCustom1(String custom1); - /** - * Return the value for the custom2 attribute. - * - * @return custom2 - */ - String getCustom2(); + /** + * Return the value for the custom2 attribute. + * + * @return custom2 + */ + String getCustom2(); - /** - * Sets the value for custom2 attribute. - * - * @param custom2 - * the custom2 property of the workbasket - */ - void setCustom2(String custom2); + /** + * Sets the value for custom2 attribute. + * + * @param custom2 the custom2 property of the workbasket + */ + void setCustom2(String custom2); - /** - * Return the value for the custom3 attribute. - * - * @return custom3 - */ - String getCustom3(); + /** + * Return the value for the custom3 attribute. + * + * @return custom3 + */ + String getCustom3(); - /** - * Sets the value for custom3 attribute. - * - * @param custom3 - * the custom3 property of the workbasket - */ - void setCustom3(String custom3); + /** + * Sets the value for custom3 attribute. + * + * @param custom3 the custom3 property of the workbasket + */ + void setCustom3(String custom3); - /** - * Return the value for the custom4 attribute. - * - * @return custom4 - */ - String getCustom4(); + /** + * Return the value for the custom4 attribute. + * + * @return custom4 + */ + String getCustom4(); - /** - * Sets the value for custom4 attribute. - * - * @param custom4 - * the custom4 property of the workbasket - */ - void setCustom4(String custom4); + /** + * Sets the value for custom4 attribute. + * + * @param custom4 the custom4 property of the workbasket + */ + void setCustom4(String custom4); - /** - * Return the value for the orgLevel1 attribute. - * - * @return orgLevel1 - */ - String getOrgLevel1(); + /** + * Return the value for the orgLevel1 attribute. + * + * @return orgLevel1 + */ + String getOrgLevel1(); - /** - * Sets the value for orgLevel1 attribute. - * - * @param orgLevel1 - * the orgLevel1 property of the workbasket - */ - void setOrgLevel1(String orgLevel1); + /** + * Sets the value for orgLevel1 attribute. + * + * @param orgLevel1 the orgLevel1 property of the workbasket + */ + void setOrgLevel1(String orgLevel1); - /** - * Return the value for the orgLevel2 attribute. - * - * @return orgLevel2 - */ - String getOrgLevel2(); + /** + * Return the value for the orgLevel2 attribute. + * + * @return orgLevel2 + */ + String getOrgLevel2(); - /** - * Sets the value for orgLevel2 attribute. - * - * @param orgLevel2 - * the orgLevel2 property of the workbasket - */ - void setOrgLevel2(String orgLevel2); + /** + * Sets the value for orgLevel2 attribute. + * + * @param orgLevel2 the orgLevel2 property of the workbasket + */ + void setOrgLevel2(String orgLevel2); - /** - * Return the value for the orgLevel3 attribute. - * - * @return orgLevel3 - */ - String getOrgLevel3(); + /** + * Return the value for the orgLevel3 attribute. + * + * @return orgLevel3 + */ + String getOrgLevel3(); - /** - * Sets the value for orgLevel3 attribute. - * - * @param orgLevel3 - * the orgLevel3 property of the workbasket - */ - void setOrgLevel3(String orgLevel3); + /** + * Sets the value for orgLevel3 attribute. + * + * @param orgLevel3 the orgLevel3 property of the workbasket + */ + void setOrgLevel3(String orgLevel3); - /** - * Return the value for the orgLevel4 attribute. - * - * @return orgLevel4 - */ - String getOrgLevel4(); + /** + * Return the value for the orgLevel4 attribute. + * + * @return orgLevel4 + */ + String getOrgLevel4(); - /** - * Sets the value for orgLevel4 attribute. - * - * @param orgLevel4 - * the orgLevel4 property of the workbasket - */ - void setOrgLevel4(String orgLevel4); + /** + * Sets the value for orgLevel4 attribute. + * + * @param orgLevel4 the orgLevel4 property of the workbasket + */ + void setOrgLevel4(String orgLevel4); - /** - * Return the value for the markedForDeletion attribute. - * - * @return markedForDeletion - */ - boolean isMarkedForDeletion(); + /** + * Return the value for the markedForDeletion attribute. + * + * @return markedForDeletion + */ + boolean isMarkedForDeletion(); - /** - * Sets the value for markedForDeletion attribute. - * - * @param markedForDeletion - * the markedForDeletion property of the workbasket - */ - void setMarkedForDeletion(boolean markedForDeletion); + /** + * Sets the value for markedForDeletion attribute. + * + * @param markedForDeletion the markedForDeletion property of the workbasket + */ + void setMarkedForDeletion(boolean markedForDeletion); - /** - * Return a summary of the current workbasket. - * - * @return the WorkbasketSummary object for the current work basket - */ - WorkbasketSummary asSummary(); + /** + * Return a summary of the current workbasket. + * + * @return the WorkbasketSummary object for the current work basket + */ + WorkbasketSummary asSummary(); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/WorkbasketAccessItem.java b/lib/taskana-core/src/main/java/pro/taskana/WorkbasketAccessItem.java index 9800f27e1..f9d59c6ae 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/WorkbasketAccessItem.java +++ b/lib/taskana-core/src/main/java/pro/taskana/WorkbasketAccessItem.java @@ -1,331 +1,318 @@ package pro.taskana; /** - * Interface for WorkbasketAccessItem. This interface is used to control access of users to workbaskets. + * Interface for WorkbasketAccessItem. This interface is used to control access of users to + * workbaskets. * * @author bbr */ public interface WorkbasketAccessItem { - /** - * Returns the current id of the WorkbasketAccessItem. - * - * @return Id - */ - String getId(); + /** + * Returns the current id of the WorkbasketAccessItem. + * + * @return Id + */ + String getId(); - /** - * Returns the Id of the referenced workbasket. - * - * @return the workbasket Id - */ - String getWorkbasketId(); + /** + * Returns the Id of the referenced workbasket. + * + * @return the workbasket Id + */ + String getWorkbasketId(); - /** - * Returns the Key of the referenced workbasket. - * - * @return the workbasket Key - */ - String getWorkbasketKey(); + /** + * Returns the Key of the referenced workbasket. + * + * @return the workbasket Key + */ + String getWorkbasketKey(); - /** - * Returns the group id or user id for which this WorkbasketAccessItem controls access permissions. - * - * @return access id, this is the group id or user id - */ - String getAccessId(); + /** + * Returns the group id or user id for which this WorkbasketAccessItem controls access + * permissions. + * + * @return access id, this is the group id or user id + */ + String getAccessId(); - /** - * Returns the name of the group or user for which this WorkbasketAccessItem controls access permissions. - * - * @return access name, this is the name of the group or user - */ - String getAccessName(); + /** + * Returns the name of the group or user for which this WorkbasketAccessItem controls access + * permissions. + * + * @return access name, this is the name of the group or user + */ + String getAccessName(); - /** - * Set the name of the group or user for which this WorkbasketAccessItem controls access permissions. - * - * @param name - * the name of the group or user for which this WorkbasketAccessItem controls access permissions. - */ - void setAccessName(String name); + /** + * Set the name of the group or user for which this WorkbasketAccessItem controls access + * permissions. + * + * @param name the name of the group or user for which this WorkbasketAccessItem controls access + * permissions. + */ + void setAccessName(String name); - /** - * Returns whether read of the referenced workbasket is permitted. - * - * @return read permission for the referenced workbasket - */ - boolean isPermRead(); + /** + * Returns whether read of the referenced workbasket is permitted. + * + * @return read permission for the referenced workbasket + */ + boolean isPermRead(); - /** - * Sets read permission for the referenced workbasket. - * - * @param permRead - * specifies whether read is permitted for the referenced workbasket. - */ - void setPermRead(boolean permRead); + /** + * Sets read permission for the referenced workbasket. + * + * @param permRead specifies whether read is permitted for the referenced workbasket. + */ + void setPermRead(boolean permRead); - /** - * Returns whether open of the referenced workbasket is permitted. - * - * @return open permission for the referenced workbasket - */ - boolean isPermOpen(); + /** + * Returns whether open of the referenced workbasket is permitted. + * + * @return open permission for the referenced workbasket + */ + boolean isPermOpen(); - /** - * Sets open permission for the referenced workbasket. - * - * @param permOpen - * specifies whether open is permitted for the referenced workbasket. - */ - void setPermOpen(boolean permOpen); + /** + * Sets open permission for the referenced workbasket. + * + * @param permOpen specifies whether open is permitted for the referenced workbasket. + */ + void setPermOpen(boolean permOpen); - /** - * Returns whether append to the referenced workbasket is permitted. - * - * @return append permission for the referenced workbasket - */ - boolean isPermAppend(); + /** + * Returns whether append to the referenced workbasket is permitted. + * + * @return append permission for the referenced workbasket + */ + boolean isPermAppend(); - /** - * Sets append permission for the referenced workbasket. - * - * @param permAppend - * specifies whether append to the referenced workbasket is permitted. - */ - void setPermAppend(boolean permAppend); + /** + * Sets append permission for the referenced workbasket. + * + * @param permAppend specifies whether append to the referenced workbasket is permitted. + */ + void setPermAppend(boolean permAppend); - /** - * Returns whether transfer from the referenced workbasket is permitted. - * - * @return transfer permission for the referenced workbasket - */ - boolean isPermTransfer(); + /** + * Returns whether transfer from the referenced workbasket is permitted. + * + * @return transfer permission for the referenced workbasket + */ + boolean isPermTransfer(); - /** - * Sets transfer permission for the referenced workbasket. - * - * @param permTransfer - * specifies whether transfer from the referenced workbasket is permitted. - */ - void setPermTransfer(boolean permTransfer); + /** + * Sets transfer permission for the referenced workbasket. + * + * @param permTransfer specifies whether transfer from the referenced workbasket is permitted. + */ + void setPermTransfer(boolean permTransfer); - /** - * Returns whether distribute from the referenced workbasket is permitted. - * - * @return distribute permission for the referenced workbasket - */ - boolean isPermDistribute(); + /** + * Returns whether distribute from the referenced workbasket is permitted. + * + * @return distribute permission for the referenced workbasket + */ + boolean isPermDistribute(); - /** - * Sets distribute permission for the referenced workbasket. - * - * @param permDistribute - * specifies whether distribute from the referenced workbasket is permitted. - */ - void setPermDistribute(boolean permDistribute); + /** + * Sets distribute permission for the referenced workbasket. + * + * @param permDistribute specifies whether distribute from the referenced workbasket is permitted. + */ + void setPermDistribute(boolean permDistribute); - /** - * Returns whether custom1 permission is granted for the referenced workbasket. The semantics of this custom - * permission is transparent to taskana. - * - * @return custom1 permission for the referenced workbasket - */ - boolean isPermCustom1(); + /** + * Returns whether custom1 permission is granted for the referenced workbasket. The semantics of + * this custom permission is transparent to taskana. + * + * @return custom1 permission for the referenced workbasket + */ + boolean isPermCustom1(); - /** - * Sets the custom1 permission for the referenced workbasket. The semantics of this custom permission is transparent - * to taskana. - * - * @param permCustom1 - * specifies whether custom1 permission is granted - */ - void setPermCustom1(boolean permCustom1); + /** + * Sets the custom1 permission for the referenced workbasket. The semantics of this custom + * permission is transparent to taskana. + * + * @param permCustom1 specifies whether custom1 permission is granted + */ + void setPermCustom1(boolean permCustom1); - /** - * Returns whether custom2 permission is granted for the referenced workbasket. The semantics of this custom - * permission is transparent to taskana. - * - * @return custom2 permission for the referenced workbasket - */ - boolean isPermCustom2(); + /** + * Returns whether custom2 permission is granted for the referenced workbasket. The semantics of + * this custom permission is transparent to taskana. + * + * @return custom2 permission for the referenced workbasket + */ + boolean isPermCustom2(); - /** - * Sets the custom2 permission for the referenced workbasket. The semantics of this custom permission is transparent - * to taskana. - * - * @param permCustom2 - * specifies whether custom2 permission is granted - */ - void setPermCustom2(boolean permCustom2); + /** + * Sets the custom2 permission for the referenced workbasket. The semantics of this custom + * permission is transparent to taskana. + * + * @param permCustom2 specifies whether custom2 permission is granted + */ + void setPermCustom2(boolean permCustom2); - /** - * Returns whether custom3 permission is granted for the referenced workbasket. The semantics of this custom - * permission is transparent to taskana. - * - * @return custom3 permission for the referenced workbasket - */ - boolean isPermCustom3(); + /** + * Returns whether custom3 permission is granted for the referenced workbasket. The semantics of + * this custom permission is transparent to taskana. + * + * @return custom3 permission for the referenced workbasket + */ + boolean isPermCustom3(); - /** - * Sets the custom3 permission for the referenced workbasket. The semantics of this custom permission is transparent - * to taskana. - * - * @param permCustom3 - * specifies whether custom3 permission is granted - */ - void setPermCustom3(boolean permCustom3); + /** + * Sets the custom3 permission for the referenced workbasket. The semantics of this custom + * permission is transparent to taskana. + * + * @param permCustom3 specifies whether custom3 permission is granted + */ + void setPermCustom3(boolean permCustom3); - /** - * Returns whether custom4 permission is granted for the referenced workbasket. The semantics of this custom - * permission is transparent to taskana. - * - * @return custom4 permission for the referenced workbasket - */ - boolean isPermCustom4(); + /** + * Returns whether custom4 permission is granted for the referenced workbasket. The semantics of + * this custom permission is transparent to taskana. + * + * @return custom4 permission for the referenced workbasket + */ + boolean isPermCustom4(); - /** - * Sets the custom4 permission for the referenced workbasket. The semantics of this custom permission is transparent - * to taskana. - * - * @param permCustom4 - * specifies whether custom4 permission is granted - */ - void setPermCustom4(boolean permCustom4); + /** + * Sets the custom4 permission for the referenced workbasket. The semantics of this custom + * permission is transparent to taskana. + * + * @param permCustom4 specifies whether custom4 permission is granted + */ + void setPermCustom4(boolean permCustom4); - /** - * Returns whether custom5 permission is granted for the referenced workbasket. The semantics of this custom - * permission is transparent to taskana. - * - * @return custom5 permission for the referenced workbasket - */ - boolean isPermCustom5(); + /** + * Returns whether custom5 permission is granted for the referenced workbasket. The semantics of + * this custom permission is transparent to taskana. + * + * @return custom5 permission for the referenced workbasket + */ + boolean isPermCustom5(); - /** - * Sets the custom5 permission for the referenced workbasket. The semantics of this custom permission is transparent - * to taskana. - * - * @param permCustom5 - * specifies whether custom5 permission is granted - */ - void setPermCustom5(boolean permCustom5); + /** + * Sets the custom5 permission for the referenced workbasket. The semantics of this custom + * permission is transparent to taskana. + * + * @param permCustom5 specifies whether custom5 permission is granted + */ + void setPermCustom5(boolean permCustom5); - /** - * Returns whether custom6 permission is granted for the referenced workbasket. The semantics of this custom - * permission is transparent to taskana. - * - * @return custom6 permission for the referenced workbasket - */ - boolean isPermCustom6(); + /** + * Returns whether custom6 permission is granted for the referenced workbasket. The semantics of + * this custom permission is transparent to taskana. + * + * @return custom6 permission for the referenced workbasket + */ + boolean isPermCustom6(); - /** - * Sets the custom6 permission for the referenced workbasket. The semantics of this custom permission is transparent - * to taskana. - * - * @param permCustom6 - * specifies whether custom6 permission is granted - */ - void setPermCustom6(boolean permCustom6); + /** + * Sets the custom6 permission for the referenced workbasket. The semantics of this custom + * permission is transparent to taskana. + * + * @param permCustom6 specifies whether custom6 permission is granted + */ + void setPermCustom6(boolean permCustom6); - /** - * Returns whether custom7 permission is granted for the referenced workbasket. The semantics of this custom - * permission is transparent to taskana. - * - * @return custom7 permission for the referenced workbasket - */ - boolean isPermCustom7(); + /** + * Returns whether custom7 permission is granted for the referenced workbasket. The semantics of + * this custom permission is transparent to taskana. + * + * @return custom7 permission for the referenced workbasket + */ + boolean isPermCustom7(); - /** - * Sets the custom7 permission for the referenced workbasket. The semantics of this custom permission is transparent - * to taskana. - * - * @param permCustom7 - * specifies whether custom7 permission is granted - */ - void setPermCustom7(boolean permCustom7); + /** + * Sets the custom7 permission for the referenced workbasket. The semantics of this custom + * permission is transparent to taskana. + * + * @param permCustom7 specifies whether custom7 permission is granted + */ + void setPermCustom7(boolean permCustom7); - /** - * Returns whether custom8 permission is granted for the referenced workbasket. The semantics of this custom - * permission is transparent to taskana. - * - * @return custom8 permission for the referenced workbasket - */ - boolean isPermCustom8(); + /** + * Returns whether custom8 permission is granted for the referenced workbasket. The semantics of + * this custom permission is transparent to taskana. + * + * @return custom8 permission for the referenced workbasket + */ + boolean isPermCustom8(); - /** - * Sets the custom8 permission for the referenced workbasket. The semantics of this custom permission is transparent - * to taskana. - * - * @param permCustom8 - * specifies whether custom8 permission is granted - */ - void setPermCustom8(boolean permCustom8); + /** + * Sets the custom8 permission for the referenced workbasket. The semantics of this custom + * permission is transparent to taskana. + * + * @param permCustom8 specifies whether custom8 permission is granted + */ + void setPermCustom8(boolean permCustom8); - /** - * Returns whether custom9 permission is granted for the referenced workbasket. The semantics of this custom - * permission is transparent to taskana. - * - * @return custom9 permission for the referenced workbasket - */ - boolean isPermCustom9(); + /** + * Returns whether custom9 permission is granted for the referenced workbasket. The semantics of + * this custom permission is transparent to taskana. + * + * @return custom9 permission for the referenced workbasket + */ + boolean isPermCustom9(); - /** - * Sets the custom9 permission for the referenced workbasket. The semantics of this custom permission is transparent - * to taskana. - * - * @param permCustom9 - * specifies whether custom9 permission is granted - */ - void setPermCustom9(boolean permCustom9); + /** + * Sets the custom9 permission for the referenced workbasket. The semantics of this custom + * permission is transparent to taskana. + * + * @param permCustom9 specifies whether custom9 permission is granted + */ + void setPermCustom9(boolean permCustom9); - /** - * Returns whether custom10 permission is granted for the referenced workbasket. The semantics of this custom - * permission is transparent to taskana. - * - * @return custom10 permission for the referenced workbasket - */ - boolean isPermCustom10(); + /** + * Returns whether custom10 permission is granted for the referenced workbasket. The semantics of + * this custom permission is transparent to taskana. + * + * @return custom10 permission for the referenced workbasket + */ + boolean isPermCustom10(); - /** - * Sets the custom10 permission for the referenced workbasket. The semantics of this custom permission is - * transparent to taskana. - * - * @param permCustom10 - * specifies whether custom10 permission is granted - */ - void setPermCustom10(boolean permCustom10); + /** + * Sets the custom10 permission for the referenced workbasket. The semantics of this custom + * permission is transparent to taskana. + * + * @param permCustom10 specifies whether custom10 permission is granted + */ + void setPermCustom10(boolean permCustom10); - /** - * Returns whether custom11 permission is granted for the referenced workbasket. The semantics of this custom - * permission is transparent to taskana. - * - * @return custom11 permission for the referenced workbasket - */ - boolean isPermCustom11(); + /** + * Returns whether custom11 permission is granted for the referenced workbasket. The semantics of + * this custom permission is transparent to taskana. + * + * @return custom11 permission for the referenced workbasket + */ + boolean isPermCustom11(); - /** - * Sets the custom11 permission for the referenced workbasket. The semantics of this custom permission is - * transparent to taskana. - * - * @param permCustom11 - * specifies whether custom11 permission is granted - */ - void setPermCustom11(boolean permCustom11); + /** + * Sets the custom11 permission for the referenced workbasket. The semantics of this custom + * permission is transparent to taskana. + * + * @param permCustom11 specifies whether custom11 permission is granted + */ + void setPermCustom11(boolean permCustom11); - /** - * Returns whether custom12 permission is granted for the referenced workbasket. The semantics of this custom - * permission is transparent to taskana. - * - * @return custom12 permission for the referenced workbasket - */ - boolean isPermCustom12(); + /** + * Returns whether custom12 permission is granted for the referenced workbasket. The semantics of + * this custom permission is transparent to taskana. + * + * @return custom12 permission for the referenced workbasket + */ + boolean isPermCustom12(); - /** - * Sets the custom12 permission for the referenced workbasket. The semantics of this custom permission is - * transparent to taskana. - * - * @param permCustom12 - * specifies whether custom12 permission is granted - */ - void setPermCustom12(boolean permCustom12); + /** + * Sets the custom12 permission for the referenced workbasket. The semantics of this custom + * permission is transparent to taskana. + * + * @param permCustom12 specifies whether custom12 permission is granted + */ + void setPermCustom12(boolean permCustom12); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/WorkbasketAccessItemQuery.java b/lib/taskana-core/src/main/java/pro/taskana/WorkbasketAccessItemQuery.java index 2d555d4ea..426a9e0cf 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/WorkbasketAccessItemQuery.java +++ b/lib/taskana-core/src/main/java/pro/taskana/WorkbasketAccessItemQuery.java @@ -1,106 +1,96 @@ package pro.taskana; -/** - * WorkbasketAccessItemQuery for generating dynamic SQL. - */ -public interface WorkbasketAccessItemQuery extends BaseQuery { +/** WorkbasketAccessItemQuery for generating dynamic SQL. */ +public interface WorkbasketAccessItemQuery + extends BaseQuery { - /** - * Add your unique entry id to your query as filter. - * - * @param ids - * the unique entry IDs - * @return the query - */ - WorkbasketAccessItemQuery idIn(String... ids); + /** + * Add your unique entry id to your query as filter. + * + * @param ids the unique entry IDs + * @return the query + */ + WorkbasketAccessItemQuery idIn(String... ids); - /** - * Add your workbasket id to your query. - * - * @param workbasketId - * the workbasket Id - * @return the query - */ - WorkbasketAccessItemQuery workbasketIdIn(String... workbasketId); + /** + * Add your workbasket id to your query. + * + * @param workbasketId the workbasket Id + * @return the query + */ + WorkbasketAccessItemQuery workbasketIdIn(String... workbasketId); - /** - * Add your unique entry workbasket key to your query as filter. - * - * @param keys - * the unique entry Keys - * @return the query - */ - WorkbasketAccessItemQuery workbasketKeyIn(String... keys); + /** + * Add your unique entry workbasket key to your query as filter. + * + * @param keys the unique entry Keys + * @return the query + */ + WorkbasketAccessItemQuery workbasketKeyIn(String... keys); - /** - * Add keys to your query. The keys are compared case-insensitively to the keys of access items with the SQL LIKE - * operator. You may add a wildcard like '%' to search generically. If you specify multiple keys they are connected - * with an OR operator, this is, the query searches access items workbaskets whose keys are like key1 or like key2, etc. - * - * @param key - * the keys as Strings - * @return the query - */ - WorkbasketAccessItemQuery workbasketKeyLike(String... key); + /** + * Add keys to your query. The keys are compared case-insensitively to the keys of access items + * with the SQL LIKE operator. You may add a wildcard like '%' to search generically. If you + * specify multiple keys they are connected with an OR operator, this is, the query searches + * access items workbaskets whose keys are like key1 or like key2, etc. + * + * @param key the keys as Strings + * @return the query + */ + WorkbasketAccessItemQuery workbasketKeyLike(String... key); - /** - * Add your accessIds to your query. - * - * @param accessId - * as access Ids - * @return the query - */ - WorkbasketAccessItemQuery accessIdIn(String... accessId); + /** + * Add your accessIds to your query. + * + * @param accessId as access Ids + * @return the query + */ + WorkbasketAccessItemQuery accessIdIn(String... accessId); - /** - * Add keys to your query. The keys are compared case-insensitively to the keys of access items with the SQL LIKE - * operator. You may add a wildcard like '%' to search generically. If you specify multiple keys they are connected - * with an OR operator, this is, the query searches access items whose ids are like id1 or like id2, etc. - * - * @param ids - * the ids as Strings - * @return the query - */ - WorkbasketAccessItemQuery accessIdLike(String... ids); + /** + * Add keys to your query. The keys are compared case-insensitively to the keys of access items + * with the SQL LIKE operator. You may add a wildcard like '%' to search generically. If you + * specify multiple keys they are connected with an OR operator, this is, the query searches + * access items whose ids are like id1 or like id2, etc. + * + * @param ids the ids as Strings + * @return the query + */ + WorkbasketAccessItemQuery accessIdLike(String... ids); - /** - * Sort the query result by workbasket id. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - WorkbasketAccessItemQuery orderByWorkbasketId(SortDirection sortDirection); + /** + * Sort the query result by workbasket id. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + WorkbasketAccessItemQuery orderByWorkbasketId(SortDirection sortDirection); - /** - * Sort the query result by workbasket key. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - WorkbasketAccessItemQuery orderByWorkbasketKey(SortDirection sortDirection); + /** + * Sort the query result by workbasket key. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + WorkbasketAccessItemQuery orderByWorkbasketKey(SortDirection sortDirection); - /** - * Sort the query result by access Id. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - WorkbasketAccessItemQuery orderByAccessId(SortDirection sortDirection); - - /** - * Sort the query result by Id. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - WorkbasketAccessItemQuery orderById(SortDirection sortDirection); + /** + * Sort the query result by access Id. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + WorkbasketAccessItemQuery orderByAccessId(SortDirection sortDirection); + /** + * Sort the query result by Id. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + WorkbasketAccessItemQuery orderById(SortDirection sortDirection); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/WorkbasketPermission.java b/lib/taskana-core/src/main/java/pro/taskana/WorkbasketPermission.java index 3f0980bb0..3478d9748 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/WorkbasketPermission.java +++ b/lib/taskana-core/src/main/java/pro/taskana/WorkbasketPermission.java @@ -1,24 +1,22 @@ package pro.taskana; -/** - * This enum contains all permission values for the workbaskets. - */ +/** This enum contains all permission values for the workbaskets. */ public enum WorkbasketPermission { - READ, - OPEN, - APPEND, - TRANSFER, - DISTRIBUTE, - CUSTOM_1, - CUSTOM_2, - CUSTOM_3, - CUSTOM_4, - CUSTOM_5, - CUSTOM_6, - CUSTOM_7, - CUSTOM_8, - CUSTOM_9, - CUSTOM_10, - CUSTOM_11, - CUSTOM_12 + READ, + OPEN, + APPEND, + TRANSFER, + DISTRIBUTE, + CUSTOM_1, + CUSTOM_2, + CUSTOM_3, + CUSTOM_4, + CUSTOM_5, + CUSTOM_6, + CUSTOM_7, + CUSTOM_8, + CUSTOM_9, + CUSTOM_10, + CUSTOM_11, + CUSTOM_12 } diff --git a/lib/taskana-core/src/main/java/pro/taskana/WorkbasketQuery.java b/lib/taskana-core/src/main/java/pro/taskana/WorkbasketQuery.java index 4f0361585..1721f61a3 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/WorkbasketQuery.java +++ b/lib/taskana-core/src/main/java/pro/taskana/WorkbasketQuery.java @@ -3,492 +3,447 @@ package pro.taskana; import pro.taskana.exceptions.InvalidArgumentException; import pro.taskana.exceptions.NotAuthorizedException; -/** - * WorkitemQuery for generating dynamic sql. - */ +/** WorkitemQuery for generating dynamic sql. */ public interface WorkbasketQuery extends BaseQuery { - /** - * Add your ids to your query. The ids are compared to the ids of workbaskets with the IN operator. - * - * @param id - * the id as Strings - * @return the query - */ - WorkbasketQuery idIn(String... id); + /** + * Add your ids to your query. The ids are compared to the ids of workbaskets with the IN + * operator. + * + * @param id the id as Strings + * @return the query + */ + WorkbasketQuery idIn(String... id); - /** - * Add your keys to your query. The keys are compared case-insensitively to the keys of workbaskets with the IN - * operator. - * @param key - * the keys as Strings - * @return the query - */ - WorkbasketQuery keyIn(String... key); + /** + * Add your keys to your query. The keys are compared case-insensitively to the keys of + * workbaskets with the IN operator. + * + * @param key the keys as Strings + * @return the query + */ + WorkbasketQuery keyIn(String... key); - /** - * Add keys to your query. The keys are compared case-insensitively to the keys of workbaskets with the SQL LIKE - * operator. You may add a wildcard like '%' to search generically. If you specify multiple keys they are connected - * with an OR operator, this is, the query searches workbaskets whose keys are like key1 or like key2, etc. - * - * @param key - * the keys as Strings - * @return the query - */ - WorkbasketQuery keyLike(String... key); + /** + * Add keys to your query. The keys are compared case-insensitively to the keys of workbaskets + * with the SQL LIKE operator. You may add a wildcard like '%' to search generically. If you + * specify multiple keys they are connected with an OR operator, this is, the query searches + * workbaskets whose keys are like key1 or like key2, etc. + * + * @param key the keys as Strings + * @return the query + */ + WorkbasketQuery keyLike(String... key); - /** - * Add your names to your query. The names are compared case-insensitively to the names of workbaskets - * - * @param name - * the names as Strings - * @return the query - */ - WorkbasketQuery nameIn(String... name); + /** + * Add your names to your query. The names are compared case-insensitively to the names of + * workbaskets + * + * @param name the names as Strings + * @return the query + */ + WorkbasketQuery nameIn(String... name); - /** - * Add names to your query. The names are compared case-insensitively to the names of workbaskets with the SQL LIKE - * operator. You may add a wildcard like '%' to search generically. If you specify multiple names, they are - * connected with an OR operator, this is, the query searches workbaskets whose names are like name1 or like name2, - * etc. - * - * @param name - * the names as Strings - * @return the query - */ - WorkbasketQuery nameLike(String... name); + /** + * Add names to your query. The names are compared case-insensitively to the names of workbaskets + * with the SQL LIKE operator. You may add a wildcard like '%' to search generically. If you + * specify multiple names, they are connected with an OR operator, this is, the query searches + * workbaskets whose names are like name1 or like name2, etc. + * + * @param name the names as Strings + * @return the query + */ + WorkbasketQuery nameLike(String... name); - /** - * Add search strings to your query that are searched case-insensitively in the key and name fields of workbaskets. - * You may add a wildcard like '%' to search generically. If you specify multiple keys they are connected with an OR - * operator, this is, the query searches workbaskets whose keys are like string1 or whose names are like string1 or - * whose keys are like string2 or whose names are like string2, etc... - * - * @param searchString - * the seach strings - * @return the query - */ - WorkbasketQuery keyOrNameLike(String... searchString); + /** + * Add search strings to your query that are searched case-insensitively in the key and name + * fields of workbaskets. You may add a wildcard like '%' to search generically. If you specify + * multiple keys they are connected with an OR operator, this is, the query searches workbaskets + * whose keys are like string1 or whose names are like string1 or whose keys are like string2 or + * whose names are like string2, etc... + * + * @param searchString the seach strings + * @return the query + */ + WorkbasketQuery keyOrNameLike(String... searchString); - /** - * Add your domains to your query. - * - * @param domain - * the domains as Strings - * @return the query - */ - WorkbasketQuery domainIn(String... domain); + /** + * Add your domains to your query. + * + * @param domain the domains as Strings + * @return the query + */ + WorkbasketQuery domainIn(String... domain); - /** - * Add your types to your query. - * - * @param type - * the types - * @return the query - */ - WorkbasketQuery typeIn(WorkbasketType... type); + /** + * Add your types to your query. + * + * @param type the types + * @return the query + */ + WorkbasketQuery typeIn(WorkbasketType... type); - /** - * Add the time intervals within which the workbasket was created to your query. For each time interval, the - * database query will search for workbaskets whose created timestamp is after or at the interval's begin and before - * or at the interval's end. If more than one interval is specified, the query will connect them with the OR - * keyword. If either begin or end of an interval are null, these values will not be specified in the query. - * - * @param intervals - * - the TimeIntervals within which the workbasket was created - * @return the query - */ - WorkbasketQuery createdWithin(TimeInterval... intervals); + /** + * Add the time intervals within which the workbasket was created to your query. For each time + * interval, the database query will search for workbaskets whose created timestamp is after or at + * the interval's begin and before or at the interval's end. If more than one interval is + * specified, the query will connect them with the OR keyword. If either begin or end of an + * interval are null, these values will not be specified in the query. + * + * @param intervals - the TimeIntervals within which the workbasket was created + * @return the query + */ + WorkbasketQuery createdWithin(TimeInterval... intervals); - /** - * Add the time intervals within which the workbasket was modified to your query. For each time interval, the - * database query will search for workbaskets whose created timestamp is after or at the interval's begin and before - * or at the interval's end. If more than one interval is specified, the query will connect them with the OR - * keyword. If either begin or end of an interval are null, these values will not be specified in the query. - * - * @param intervals - * - the TimeIntervals within which the workbasket was created - * @return the query - */ - WorkbasketQuery modifiedWithin(TimeInterval... intervals); + /** + * Add the time intervals within which the workbasket was modified to your query. For each time + * interval, the database query will search for workbaskets whose created timestamp is after or at + * the interval's begin and before or at the interval's end. If more than one interval is + * specified, the query will connect them with the OR keyword. If either begin or end of an + * interval are null, these values will not be specified in the query. + * + * @param intervals - the TimeIntervals within which the workbasket was created + * @return the query + */ + WorkbasketQuery modifiedWithin(TimeInterval... intervals); - /** - * Add your description to your query. It will be compared case-insensitively to the descriptions of workbaskets - * using the LIKE operator. You may use a wildcard like '%' to search generically. If you specify multiple arguments - * they are combined with the OR keyword. - * - * @param description - * your description - * @return the query - */ - WorkbasketQuery descriptionLike(String... description); + /** + * Add your description to your query. It will be compared case-insensitively to the descriptions + * of workbaskets using the LIKE operator. You may use a wildcard like '%' to search generically. + * If you specify multiple arguments they are combined with the OR keyword. + * + * @param description your description + * @return the query + */ + WorkbasketQuery descriptionLike(String... description); - /** - * Add the owners to your query. - * - * @param owners - * the owners as String - * @return the query - */ - WorkbasketQuery ownerIn(String... owners); + /** + * Add the owners to your query. + * + * @param owners the owners as String + * @return the query + */ + WorkbasketQuery ownerIn(String... owners); - /** - * Add the owners for pattern matching to your query. It will be compared in SQL with the LIKE operator. You may use - * a wildcard like % to specify the pattern. If you specify multiple arguments they are combined with the OR - * keyword. - * - * @param owners - * the owners as Strings - * @return the query - */ - WorkbasketQuery ownerLike(String... owners); + /** + * Add the owners for pattern matching to your query. It will be compared in SQL with the LIKE + * operator. You may use a wildcard like % to specify the pattern. If you specify multiple + * arguments they are combined with the OR keyword. + * + * @param owners the owners as Strings + * @return the query + */ + WorkbasketQuery ownerLike(String... owners); - /** - * Setting up the permission which should be granted on the result workbaskets and the users which should be - * checked. READ permission will always be checked by default.
- * The AccessIds and the given permission will throw a Exception if they would be NULL. - * - * @param permission - * which should be used for results. - * @param accessIds - * Users which sould be checked for given permissions on workbaskets. - * @return the current query object. - * @throws InvalidArgumentException - * when permission OR the accessIds are NULL. - * @throws NotAuthorizedException - * if the current user is not member of role BUSINESS_ADMIN or ADMIN - */ - WorkbasketQuery accessIdsHavePermission(WorkbasketPermission permission, String... accessIds) - throws InvalidArgumentException, NotAuthorizedException; + /** + * Setting up the permission which should be granted on the result workbaskets and the users which + * should be checked. READ permission will always be checked by default.
+ * The AccessIds and the given permission will throw a Exception if they would be NULL. + * + * @param permission which should be used for results. + * @param accessIds Users which sould be checked for given permissions on workbaskets. + * @return the current query object. + * @throws InvalidArgumentException when permission OR the accessIds are NULL. + * @throws NotAuthorizedException if the current user is not member of role BUSINESS_ADMIN or + * ADMIN + */ + WorkbasketQuery accessIdsHavePermission(WorkbasketPermission permission, String... accessIds) + throws InvalidArgumentException, NotAuthorizedException; - /** - * Add condition to query if the caller (one of the accessIds of the caller) has the given permission on the - * workbasket. - * - * @return the updated query. - * @param permission - * the permission for the query condition. - */ - WorkbasketQuery callerHasPermission(WorkbasketPermission permission); + /** + * Add condition to query if the caller (one of the accessIds of the caller) has the given + * permission on the workbasket. + * + * @return the updated query. + * @param permission the permission for the query condition. + */ + WorkbasketQuery callerHasPermission(WorkbasketPermission permission); - /** - * Sort the query result by name. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - WorkbasketQuery orderByName(SortDirection sortDirection); + /** + * Sort the query result by name. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + WorkbasketQuery orderByName(SortDirection sortDirection); - /** - * Sort the query result by key. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - WorkbasketQuery orderByKey(SortDirection sortDirection); + /** + * Sort the query result by key. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + WorkbasketQuery orderByKey(SortDirection sortDirection); - /** - * Sort the query result by description. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - WorkbasketQuery orderByDescription(SortDirection sortDirection); + /** + * Sort the query result by description. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + WorkbasketQuery orderByDescription(SortDirection sortDirection); - /** - * Sort the query result by owner. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - WorkbasketQuery orderByOwner(SortDirection sortDirection); + /** + * Sort the query result by owner. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + WorkbasketQuery orderByOwner(SortDirection sortDirection); - /** - * Sort the query result by type. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - WorkbasketQuery orderByType(SortDirection sortDirection); + /** + * Sort the query result by type. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + WorkbasketQuery orderByType(SortDirection sortDirection); - /** - * Sort the query result by domain. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - WorkbasketQuery orderByDomain(SortDirection sortDirection); + /** + * Sort the query result by domain. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + WorkbasketQuery orderByDomain(SortDirection sortDirection); - /** - * Add the domains for pattern matching to your query. It will be compared in SQL with the LIKE operator. You may - * use a wildcard like % to specify the pattern. If you specify multiple arguments they are combined with the OR - * keyword. - * - * @param domain - * the domains of workbaskets as Strings - * @return the query - */ - WorkbasketQuery domainLike(String... domain); + /** + * Add the domains for pattern matching to your query. It will be compared in SQL with the LIKE + * operator. You may use a wildcard like % to specify the pattern. If you specify multiple + * arguments they are combined with the OR keyword. + * + * @param domain the domains of workbaskets as Strings + * @return the query + */ + WorkbasketQuery domainLike(String... domain); - /** - * Sort the query result by custom property 1. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - WorkbasketQuery orderByCustom1(SortDirection sortDirection); + /** + * Sort the query result by custom property 1. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + WorkbasketQuery orderByCustom1(SortDirection sortDirection); - /** - * Sort the query result by custom property 2. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - WorkbasketQuery orderByCustom2(SortDirection sortDirection); + /** + * Sort the query result by custom property 2. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + WorkbasketQuery orderByCustom2(SortDirection sortDirection); - /** - * Sort the query result by custom property 3. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - WorkbasketQuery orderByCustom3(SortDirection sortDirection); + /** + * Sort the query result by custom property 3. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + WorkbasketQuery orderByCustom3(SortDirection sortDirection); - /** - * Sort the query result by custom property 4. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - WorkbasketQuery orderByCustom4(SortDirection sortDirection); + /** + * Sort the query result by custom property 4. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + WorkbasketQuery orderByCustom4(SortDirection sortDirection); - /** - * Sort the query result by organization level 1. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - WorkbasketQuery orderByOrgLevel1(SortDirection sortDirection); + /** + * Sort the query result by organization level 1. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + WorkbasketQuery orderByOrgLevel1(SortDirection sortDirection); - /** - * Sort the query result by organization level 2. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - WorkbasketQuery orderByOrgLevel2(SortDirection sortDirection); + /** + * Sort the query result by organization level 2. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + WorkbasketQuery orderByOrgLevel2(SortDirection sortDirection); - /** - * Sort the query result by organization level 3. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - WorkbasketQuery orderByOrgLevel3(SortDirection sortDirection); + /** + * Sort the query result by organization level 3. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + WorkbasketQuery orderByOrgLevel3(SortDirection sortDirection); - /** - * Sort the query result by organization level 4. - * - * @param sortDirection - * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, - * the result is sorted in ascending order - * @return the query - */ - WorkbasketQuery orderByOrgLevel4(SortDirection sortDirection); + /** + * Sort the query result by organization level 4. + * + * @param sortDirection Determines whether the result is sorted in ascending or descending order. + * If sortDirection is null, the result is sorted in ascending order + * @return the query + */ + WorkbasketQuery orderByOrgLevel4(SortDirection sortDirection); - /** - * Add the 1st custom property to your query. - * - * @param custom1 - * the 1st custom property as String - * @return the query - */ - WorkbasketQuery custom1In(String... custom1); + /** + * Add the 1st custom property to your query. + * + * @param custom1 the 1st custom property as String + * @return the query + */ + WorkbasketQuery custom1In(String... custom1); - /** - * Add the 1st custom property for pattern matching to your query. It will be compared in SQL with the LIKE - * operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments they are - * combined with the OR keyword. - * - * @param custom1 - * the 1st custom property of workbaskets as Strings - * @return the query - */ - WorkbasketQuery custom1Like(String... custom1); + /** + * Add the 1st custom property for pattern matching to your query. It will be compared in SQL with + * the LIKE operator. You may use a wildcard like % to specify the pattern. If you specify + * multiple arguments they are combined with the OR keyword. + * + * @param custom1 the 1st custom property of workbaskets as Strings + * @return the query + */ + WorkbasketQuery custom1Like(String... custom1); - /** - * Add the 2nd custom property to your query. - * - * @param custom2 - * the 2nd custom property as String - * @return the query - */ - WorkbasketQuery custom2In(String... custom2); + /** + * Add the 2nd custom property to your query. + * + * @param custom2 the 2nd custom property as String + * @return the query + */ + WorkbasketQuery custom2In(String... custom2); - /** - * Add the 2nd custom property for pattern matching to your query. It will be compared in SQL with the LIKE - * operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments they are - * combined with the OR keyword. - * - * @param custom2 - * the 2nd custom property of workbaskets as Strings - * @return the query - */ - WorkbasketQuery custom2Like(String... custom2); + /** + * Add the 2nd custom property for pattern matching to your query. It will be compared in SQL with + * the LIKE operator. You may use a wildcard like % to specify the pattern. If you specify + * multiple arguments they are combined with the OR keyword. + * + * @param custom2 the 2nd custom property of workbaskets as Strings + * @return the query + */ + WorkbasketQuery custom2Like(String... custom2); - /** - * Add the 3rd custom property to your query. - * - * @param custom3 - * the 3rd custom property as String - * @return the query - */ - WorkbasketQuery custom3In(String... custom3); + /** + * Add the 3rd custom property to your query. + * + * @param custom3 the 3rd custom property as String + * @return the query + */ + WorkbasketQuery custom3In(String... custom3); - /** - * Add the 3rd custom property for pattern matching to your query. It will be compared in SQL with the LIKE - * operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments they are - * combined with the OR keyword. - * - * @param custom3 - * the 3rd custom property of workbaskets as Strings - * @return the query - */ - WorkbasketQuery custom3Like(String... custom3); + /** + * Add the 3rd custom property for pattern matching to your query. It will be compared in SQL with + * the LIKE operator. You may use a wildcard like % to specify the pattern. If you specify + * multiple arguments they are combined with the OR keyword. + * + * @param custom3 the 3rd custom property of workbaskets as Strings + * @return the query + */ + WorkbasketQuery custom3Like(String... custom3); - /** - * Add the 4th custom property to your query. - * - * @param custom4 - * the 4th custom property as String - * @return the query - */ - WorkbasketQuery custom4In(String... custom4); + /** + * Add the 4th custom property to your query. + * + * @param custom4 the 4th custom property as String + * @return the query + */ + WorkbasketQuery custom4In(String... custom4); - /** - * Add the 4th custom property for pattern matching to your query. It will be compared in SQL with the LIKE - * operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments they are - * combined with the OR keyword. - * - * @param custom4 - * the 4th custom property of workbaskets as Strings - * @return the query - */ - WorkbasketQuery custom4Like(String... custom4); + /** + * Add the 4th custom property for pattern matching to your query. It will be compared in SQL with + * the LIKE operator. You may use a wildcard like % to specify the pattern. If you specify + * multiple arguments they are combined with the OR keyword. + * + * @param custom4 the 4th custom property of workbaskets as Strings + * @return the query + */ + WorkbasketQuery custom4Like(String... custom4); - /** - * Add the 1st organization level to your query. - * - * @param orgLevel1 - * the 1st organization level as String - * @return the query - */ - WorkbasketQuery orgLevel1In(String... orgLevel1); + /** + * Add the 1st organization level to your query. + * + * @param orgLevel1 the 1st organization level as String + * @return the query + */ + WorkbasketQuery orgLevel1In(String... orgLevel1); - /** - * Add the 1st organization level for pattern matching to your query. It will be compared in SQL with the LIKE - * operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments they are - * combined with the OR keyword. - * - * @param orgLevel1 - * the 1st organization level as Strings - * @return the query - */ - WorkbasketQuery orgLevel1Like(String... orgLevel1); + /** + * Add the 1st organization level for pattern matching to your query. It will be compared in SQL + * with the LIKE operator. You may use a wildcard like % to specify the pattern. If you specify + * multiple arguments they are combined with the OR keyword. + * + * @param orgLevel1 the 1st organization level as Strings + * @return the query + */ + WorkbasketQuery orgLevel1Like(String... orgLevel1); - /** - * Add the 2nd organization level to your query. - * - * @param orgLevel2 - * the 2nd organization level as String - * @return the query - */ - WorkbasketQuery orgLevel2In(String... orgLevel2); + /** + * Add the 2nd organization level to your query. + * + * @param orgLevel2 the 2nd organization level as String + * @return the query + */ + WorkbasketQuery orgLevel2In(String... orgLevel2); - /** - * Add the 2nd organization level for pattern matching to your query. It will be compared in SQL with the LIKE - * operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments they are - * combined with the OR keyword. - * - * @param orgLevel2 - * the 2nd organization level as Strings - * @return the query - */ - WorkbasketQuery orgLevel2Like(String... orgLevel2); + /** + * Add the 2nd organization level for pattern matching to your query. It will be compared in SQL + * with the LIKE operator. You may use a wildcard like % to specify the pattern. If you specify + * multiple arguments they are combined with the OR keyword. + * + * @param orgLevel2 the 2nd organization level as Strings + * @return the query + */ + WorkbasketQuery orgLevel2Like(String... orgLevel2); - /** - * Add the 3rd organization level to your query. - * - * @param orgLevel3 - * the 3rd organization level as String - * @return the query - */ - WorkbasketQuery orgLevel3In(String... orgLevel3); + /** + * Add the 3rd organization level to your query. + * + * @param orgLevel3 the 3rd organization level as String + * @return the query + */ + WorkbasketQuery orgLevel3In(String... orgLevel3); - /** - * Add the 3rd organization level for pattern matching to your query. It will be compared in SQL with the LIKE - * operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments they are - * combined with the OR keyword. - * - * @param orgLevel3 - * the 3rd organization level as Strings - * @return the query - */ - WorkbasketQuery orgLevel3Like(String... orgLevel3); + /** + * Add the 3rd organization level for pattern matching to your query. It will be compared in SQL + * with the LIKE operator. You may use a wildcard like % to specify the pattern. If you specify + * multiple arguments they are combined with the OR keyword. + * + * @param orgLevel3 the 3rd organization level as Strings + * @return the query + */ + WorkbasketQuery orgLevel3Like(String... orgLevel3); - /** - * Add the 4th organization level to your query. - * - * @param orgLevel4 - * the 4th organization level as String - * @return the query - */ - WorkbasketQuery orgLevel4In(String... orgLevel4); + /** + * Add the 4th organization level to your query. + * + * @param orgLevel4 the 4th organization level as String + * @return the query + */ + WorkbasketQuery orgLevel4In(String... orgLevel4); - /** - * Add the 4th organization level for pattern matching to your query. It will be compared in SQL with the LIKE - * operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments they are - * combined with the OR keyword. - * - * @param orgLevel4 - * the 4th organization level as Strings - * @return the query - */ - WorkbasketQuery orgLevel4Like(String... orgLevel4); - - /** - * Add to your query if the Workbasket shall be marked for deletion. - * - * @param markedForDeletion - * a simple flag showing if the workbasket is marked for deletion - * @return the query - */ - WorkbasketQuery markedForDeletion(boolean markedForDeletion); + /** + * Add the 4th organization level for pattern matching to your query. It will be compared in SQL + * with the LIKE operator. You may use a wildcard like % to specify the pattern. If you specify + * multiple arguments they are combined with the OR keyword. + * + * @param orgLevel4 the 4th organization level as Strings + * @return the query + */ + WorkbasketQuery orgLevel4Like(String... orgLevel4); + /** + * Add to your query if the Workbasket shall be marked for deletion. + * + * @param markedForDeletion a simple flag showing if the workbasket is marked for deletion + * @return the query + */ + WorkbasketQuery markedForDeletion(boolean markedForDeletion); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/WorkbasketQueryColumnName.java b/lib/taskana-core/src/main/java/pro/taskana/WorkbasketQueryColumnName.java index aa2d55271..1809f35d3 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/WorkbasketQueryColumnName.java +++ b/lib/taskana-core/src/main/java/pro/taskana/WorkbasketQueryColumnName.java @@ -1,34 +1,35 @@ package pro.taskana; /** - * Enum containing the column names for @see {@link pro.taskana.mappings.QueryMapper#queryWorkbasketColumnValues(pro.taskana.impl.WorkbasketQueryImpl)}. + * Enum containing the column names for @see {@link + * pro.taskana.mappings.QueryMapper#queryWorkbasketColumnValues(pro.taskana.impl.WorkbasketQueryImpl)}. * * @author jsa */ public enum WorkbasketQueryColumnName implements QueryColumnName { + OWNER("w.owner"), + ID("w.id"), + KEY("w.key"), + NAME("w.name"), + DOMAIN("w.domain"), + TYPE("w.type"), + CUSTOM_1("w.custom_1"), + CUSTOM_2("w.custom_2"), + CUSTOM_3("w.custom_3"), + CUSTOM_4("w.custom_4"), + ORG_LEVEL_1("w.org_level_1"), + ORG_LEVEL_2("w.org_level_2"), + ORG_LEVEL_3("w.org_level_3"), + ORG_LEVEL_4("w.org_level_4"); - OWNER("w.owner"), - ID("w.id"), - KEY("w.key"), - NAME("w.name"), - DOMAIN("w.domain"), - TYPE("w.type"), - CUSTOM_1("w.custom_1"), - CUSTOM_2("w.custom_2"), - CUSTOM_3("w.custom_3"), - CUSTOM_4("w.custom_4"), - ORG_LEVEL_1("w.org_level_1"), - ORG_LEVEL_2("w.org_level_2"), - ORG_LEVEL_3("w.org_level_3"), - ORG_LEVEL_4("w.org_level_4"); + private String name; - private String name; - WorkbasketQueryColumnName(String name) { - this.name = name; - } + WorkbasketQueryColumnName(String name) { + this.name = name; + } - @Override - public String toString() { - return name; - } + @Override + public String toString() { + return name; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/WorkbasketService.java b/lib/taskana-core/src/main/java/pro/taskana/WorkbasketService.java index abcb2ef64..61cf25622 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/WorkbasketService.java +++ b/lib/taskana-core/src/main/java/pro/taskana/WorkbasketService.java @@ -11,366 +11,315 @@ import pro.taskana.exceptions.WorkbasketAlreadyExistException; import pro.taskana.exceptions.WorkbasketInUseException; import pro.taskana.exceptions.WorkbasketNotFoundException; -/** - * This service manages Workbaskets. - */ +/** This service manages Workbaskets. */ public interface WorkbasketService { - /** - * Get Workbasket for a given id. - * - * @param workbasketId - * the Id of the Workbasket requested - * @return the requested Workbasket - * @throws WorkbasketNotFoundException - * If the Workbasket with workbasketId is not found - * @throws NotAuthorizedException - * If the current user or group does not have the permissions for interactions. - */ - Workbasket getWorkbasket(String workbasketId) - throws WorkbasketNotFoundException, NotAuthorizedException; + /** + * Get Workbasket for a given id. + * + * @param workbasketId the Id of the Workbasket requested + * @return the requested Workbasket + * @throws WorkbasketNotFoundException If the Workbasket with workbasketId is not found + * @throws NotAuthorizedException If the current user or group does not have the permissions for + * interactions. + */ + Workbasket getWorkbasket(String workbasketId) + throws WorkbasketNotFoundException, NotAuthorizedException; - /** - * Get Workbasket for a given key. - * - * @param workbasketKey - * the Key of the Workbasket requested - * @param domain - * the domain of the workbasket - * @return the requested Workbasket - * @throws WorkbasketNotFoundException - * If the Workbasket with workbasketId is not found - * @throws NotAuthorizedException - * If the current user or group does not have the permissions for interactions. - */ - Workbasket getWorkbasket(String workbasketKey, String domain) - throws WorkbasketNotFoundException, NotAuthorizedException; + /** + * Get Workbasket for a given key. + * + * @param workbasketKey the Key of the Workbasket requested + * @param domain the domain of the workbasket + * @return the requested Workbasket + * @throws WorkbasketNotFoundException If the Workbasket with workbasketId is not found + * @throws NotAuthorizedException If the current user or group does not have the permissions for + * interactions. + */ + Workbasket getWorkbasket(String workbasketKey, String domain) + throws WorkbasketNotFoundException, NotAuthorizedException; - /** - * Create a new Workbasket. - * - * @param workbasket - * The Workbasket to create - * @return the created and persisted Workbasket - * @throws InvalidWorkbasketException - * If a required property of the Workbasket is not set. - * @throws NotAuthorizedException - * if the current user is not member of role BUSINESS_ADMIN or ADMIN - * @throws WorkbasketAlreadyExistException - * if the workbasket exists already - * @throws DomainNotFoundException - * if the domain does not exist in the configuration. - */ - Workbasket createWorkbasket(Workbasket workbasket) - throws InvalidWorkbasketException, NotAuthorizedException, WorkbasketAlreadyExistException, - DomainNotFoundException; + /** + * Create a new Workbasket. + * + * @param workbasket The Workbasket to create + * @return the created and persisted Workbasket + * @throws InvalidWorkbasketException If a required property of the Workbasket is not set. + * @throws NotAuthorizedException if the current user is not member of role BUSINESS_ADMIN or + * ADMIN + * @throws WorkbasketAlreadyExistException if the workbasket exists already + * @throws DomainNotFoundException if the domain does not exist in the configuration. + */ + Workbasket createWorkbasket(Workbasket workbasket) + throws InvalidWorkbasketException, NotAuthorizedException, WorkbasketAlreadyExistException, + DomainNotFoundException; - /** - * Update a Workbasket. - * - * @param workbasket - * The Workbasket to update - * @return the updated Workbasket - * @throws NotAuthorizedException - * if the current user is not authorized to update the work basket - */ - Workbasket updateWorkbasket(Workbasket workbasket) - throws NotAuthorizedException; + /** + * Update a Workbasket. + * + * @param workbasket The Workbasket to update + * @return the updated Workbasket + * @throws NotAuthorizedException if the current user is not authorized to update the work basket + */ + Workbasket updateWorkbasket(Workbasket workbasket) throws NotAuthorizedException; - /** - * Returns a new WorkbasketAccessItem which is not persisted. - * - * @param workbasketId - * the workbasket id used to identify the referenced workbasket - * @param accessId - * the group id or user id for which access is controlled - * @return new WorkbasketAccessItem - */ - WorkbasketAccessItem newWorkbasketAccessItem(String workbasketId, String accessId); + /** + * Returns a new WorkbasketAccessItem which is not persisted. + * + * @param workbasketId the workbasket id used to identify the referenced workbasket + * @param accessId the group id or user id for which access is controlled + * @return new WorkbasketAccessItem + */ + WorkbasketAccessItem newWorkbasketAccessItem(String workbasketId, String accessId); - /** - * Create and persist a new {@link WorkbasketAccessItem} with a WorkbasketId, an accessId and permissions. - * - * @param workbasketAccessItem - * the new workbasketAccessItem - * @return the created WorkbasketAccessItem - * @throws InvalidArgumentException - * when the preconditions dont match the required ones. - * @throws NotAuthorizedException - * if the current user is not member of role BUSINESS_ADMIN or ADMIN - * @throws WorkbasketNotFoundException - * if the workbasketAccessItem refers to a not existing workbasket - */ - WorkbasketAccessItem createWorkbasketAccessItem(WorkbasketAccessItem workbasketAccessItem) - throws InvalidArgumentException, NotAuthorizedException, WorkbasketNotFoundException; + /** + * Create and persist a new {@link WorkbasketAccessItem} with a WorkbasketId, an accessId and + * permissions. + * + * @param workbasketAccessItem the new workbasketAccessItem + * @return the created WorkbasketAccessItem + * @throws InvalidArgumentException when the preconditions dont match the required ones. + * @throws NotAuthorizedException if the current user is not member of role BUSINESS_ADMIN or + * ADMIN + * @throws WorkbasketNotFoundException if the workbasketAccessItem refers to a not existing + * workbasket + */ + WorkbasketAccessItem createWorkbasketAccessItem(WorkbasketAccessItem workbasketAccessItem) + throws InvalidArgumentException, NotAuthorizedException, WorkbasketNotFoundException; - /** - * This method updates a {@link WorkbasketAccessItem}. - * - * @param workbasketAccessItem - * the {@link WorkbasketAccessItem} - * @return the updated entity - * @throws InvalidArgumentException - * if accessid or workbasketId is changed in the workbasketAccessItem - * @throws NotAuthorizedException - * if the current user is not member of role BUSINESS_ADMIN or ADMIN - */ - WorkbasketAccessItem updateWorkbasketAccessItem(WorkbasketAccessItem workbasketAccessItem) - throws InvalidArgumentException, NotAuthorizedException; + /** + * This method updates a {@link WorkbasketAccessItem}. + * + * @param workbasketAccessItem the {@link WorkbasketAccessItem} + * @return the updated entity + * @throws InvalidArgumentException if accessid or workbasketId is changed in the + * workbasketAccessItem + * @throws NotAuthorizedException if the current user is not member of role BUSINESS_ADMIN or + * ADMIN + */ + WorkbasketAccessItem updateWorkbasketAccessItem(WorkbasketAccessItem workbasketAccessItem) + throws InvalidArgumentException, NotAuthorizedException; - /** - * Deletes a specific {@link WorkbasketAccessItem}. - * - * @param id - * the id of the WorbasketAccessItem to be deleted - * @throws NotAuthorizedException - * if the current user is not member of role BUSINESS_ADMIN or ADMIN - */ - void deleteWorkbasketAccessItem(String id) throws NotAuthorizedException; + /** + * Deletes a specific {@link WorkbasketAccessItem}. + * + * @param id the id of the WorbasketAccessItem to be deleted + * @throws NotAuthorizedException if the current user is not member of role BUSINESS_ADMIN or + * ADMIN + */ + void deleteWorkbasketAccessItem(String id) throws NotAuthorizedException; - /** - * This method checks the authorization for the actual User. - * - * @param workbasketId - * the id of the workbasket we want to access - * @param permission - * the needed {@link WorkbasketPermission} If more than one permission is specified, the current user - * needs all of them. - * @throws NotAuthorizedException - * if the current user has not the requested authorization for the specified workbasket - * @throws WorkbasketNotFoundException - * if the workbasket cannot be found for the given ID. - */ - void checkAuthorization(String workbasketId, WorkbasketPermission... permission) - throws NotAuthorizedException, WorkbasketNotFoundException; + /** + * This method checks the authorization for the actual User. + * + * @param workbasketId the id of the workbasket we want to access + * @param permission the needed {@link WorkbasketPermission} If more than one permission is + * specified, the current user needs all of them. + * @throws NotAuthorizedException if the current user has not the requested authorization for the + * specified workbasket + * @throws WorkbasketNotFoundException if the workbasket cannot be found for the given ID. + */ + void checkAuthorization(String workbasketId, WorkbasketPermission... permission) + throws NotAuthorizedException, WorkbasketNotFoundException; - /** - * This method checks the authorization for the actual User. - * - * @param workbasketKey - * the key of the workbasket we want to access - * @param domain - * the domain of the workbasket we want to access - * @param permission - * the needed {@link WorkbasketPermission}. If more than one permission is specified, the current user - * needs all of them. - * @throws NotAuthorizedException - * if the current user has not the requested permission for the specified workbasket - * @throws WorkbasketNotFoundException - * if no workbasket can be found for the given key+domain values. - */ - void checkAuthorization(String workbasketKey, String domain, WorkbasketPermission... permission) - throws NotAuthorizedException, WorkbasketNotFoundException; + /** + * This method checks the authorization for the actual User. + * + * @param workbasketKey the key of the workbasket we want to access + * @param domain the domain of the workbasket we want to access + * @param permission the needed {@link WorkbasketPermission}. If more than one permission is + * specified, the current user needs all of them. + * @throws NotAuthorizedException if the current user has not the requested permission for the + * specified workbasket + * @throws WorkbasketNotFoundException if no workbasket can be found for the given key+domain + * values. + */ + void checkAuthorization(String workbasketKey, String domain, WorkbasketPermission... permission) + throws NotAuthorizedException, WorkbasketNotFoundException; - /** - * Get all {@link WorkbasketAccessItem s} for a Workbasket. - * - * @param workbasketId - * the id of the Workbasket - * @return List of WorkbasketAccessItems for the Workbasket with workbasketKey - * @throws NotAuthorizedException - * if the current user is not member of role BUSINESS_ADMIN or ADMIN - */ - List getWorkbasketAccessItems(String workbasketId) throws NotAuthorizedException; + /** + * Get all {@link WorkbasketAccessItem s} for a Workbasket. + * + * @param workbasketId the id of the Workbasket + * @return List of WorkbasketAccessItems for the Workbasket with workbasketKey + * @throws NotAuthorizedException if the current user is not member of role BUSINESS_ADMIN or + * ADMIN + */ + List getWorkbasketAccessItems(String workbasketId) + throws NotAuthorizedException; - /** - * Setting up the new WorkbasketAccessItems for a Workbasket. Already stored values will be completely replaced by - * the current ones. - * - * @param workbasketId - * ID of the access-target workbasket. - * @param wbAccessItems - * List of WorkbasketAccessItems which does replace all current stored ones. - * @throws InvalidArgumentException - * will be thrown when the parameter is NULL or member doesn´t match the preconditions - * @throws NotAuthorizedException - * if the current user is not member of role BUSINESS_ADMIN or ADMIN - */ - void setWorkbasketAccessItems(String workbasketId, List wbAccessItems) - throws InvalidArgumentException, NotAuthorizedException; + /** + * Setting up the new WorkbasketAccessItems for a Workbasket. Already stored values will be + * completely replaced by the current ones. + * + * @param workbasketId ID of the access-target workbasket. + * @param wbAccessItems List of WorkbasketAccessItems which does replace all current stored ones. + * @throws InvalidArgumentException will be thrown when the parameter is NULL or member doesn´t + * match the preconditions + * @throws NotAuthorizedException if the current user is not member of role BUSINESS_ADMIN or + * ADMIN + */ + void setWorkbasketAccessItems(String workbasketId, List wbAccessItems) + throws InvalidArgumentException, NotAuthorizedException; - /** - * This method provides a query builder for querying the database. - * - * @return a {@link WorkbasketQuery} - */ - WorkbasketQuery createWorkbasketQuery(); + /** + * This method provides a query builder for querying the database. + * + * @return a {@link WorkbasketQuery} + */ + WorkbasketQuery createWorkbasketQuery(); - /** - * This method provides a query builder for querying the database. - * - * @return a {@link WorkbasketAccessItemQuery} - * @throws NotAuthorizedException - * if the current user is not member of role BUSINESS_ADMIN or ADMIN - */ - WorkbasketAccessItemQuery createWorkbasketAccessItemQuery() throws NotAuthorizedException; + /** + * This method provides a query builder for querying the database. + * + * @return a {@link WorkbasketAccessItemQuery} + * @throws NotAuthorizedException if the current user is not member of role BUSINESS_ADMIN or + * ADMIN + */ + WorkbasketAccessItemQuery createWorkbasketAccessItemQuery() throws NotAuthorizedException; - /** - * Returns a new workbasket which is not persisted. - * - * @param key - * the workbasket key used to identify the workbasket - * @param domain - * the domain of the new workbasket - * @return new Workbasket - */ - Workbasket newWorkbasket(String key, String domain); + /** + * Returns a new workbasket which is not persisted. + * + * @param key the workbasket key used to identify the workbasket + * @param domain the domain of the new workbasket + * @return new Workbasket + */ + Workbasket newWorkbasket(String key, String domain); - /** - * Returns a set with all permissions of the current user at this workbasket.
- * If the workbasketId is invalid, an empty list of permissions is returned since there is no distinction made - * between the situation that the workbasket is not found and the caller has no permissions on the workbasket. - * - * @param workbasketId - * the id of the referenced workbasket - * @return a {@link List} with all {@link WorkbasketPermission}s of the caller on the requested workbasket. - */ - List getPermissionsForWorkbasket(String workbasketId); + /** + * Returns a set with all permissions of the current user at this workbasket.
+ * If the workbasketId is invalid, an empty list of permissions is returned since there is no + * distinction made between the situation that the workbasket is not found and the caller has no + * permissions on the workbasket. + * + * @param workbasketId the id of the referenced workbasket + * @return a {@link List} with all {@link WorkbasketPermission}s of the caller on the requested + * workbasket. + */ + List getPermissionsForWorkbasket(String workbasketId); - /** - * Returns the distribution targets for a given workbasket. - * - * @param workbasketId - * the id of the referenced workbasket - * @return the distribution targets of the specified workbasket - * @throws NotAuthorizedException - * if the current user has no read permission for the specified workbasket - * @throws WorkbasketNotFoundException - * if the workbasket doesn't exist - */ - List getDistributionTargets(String workbasketId) - throws NotAuthorizedException, WorkbasketNotFoundException; + /** + * Returns the distribution targets for a given workbasket. + * + * @param workbasketId the id of the referenced workbasket + * @return the distribution targets of the specified workbasket + * @throws NotAuthorizedException if the current user has no read permission for the specified + * workbasket + * @throws WorkbasketNotFoundException if the workbasket doesn't exist + */ + List getDistributionTargets(String workbasketId) + throws NotAuthorizedException, WorkbasketNotFoundException; - /** - * Returns the distribution targets for a given workbasket. - * - * @param workbasketKey - * the key of the referenced workbasket - * @param domain - * the domain of the referenced workbasket - * @return the distribution targets of the specified workbasket - * @throws NotAuthorizedException - * if the current user has no read permission for the specified workbasket - * @throws WorkbasketNotFoundException - * if the workbasket doesn't exist - */ - List getDistributionTargets(String workbasketKey, String domain) - throws NotAuthorizedException, WorkbasketNotFoundException; + /** + * Returns the distribution targets for a given workbasket. + * + * @param workbasketKey the key of the referenced workbasket + * @param domain the domain of the referenced workbasket + * @return the distribution targets of the specified workbasket + * @throws NotAuthorizedException if the current user has no read permission for the specified + * workbasket + * @throws WorkbasketNotFoundException if the workbasket doesn't exist + */ + List getDistributionTargets(String workbasketKey, String domain) + throws NotAuthorizedException, WorkbasketNotFoundException; - /** - * Set the distribution targets for a workbasket. - * - * @param sourceWorkbasketId - * the id of the source workbasket for which the distribution targets are to be set - * @param targetWorkbasketIds - * a list of the ids of the target workbaskets - * @throws NotAuthorizedException - * if the current used doesn't have READ permission for the source workbasket - * @throws WorkbasketNotFoundException - * if either the source workbasket or any of the target workbaskets don't exist - */ - void setDistributionTargets(String sourceWorkbasketId, List targetWorkbasketIds) - throws NotAuthorizedException, WorkbasketNotFoundException; + /** + * Set the distribution targets for a workbasket. + * + * @param sourceWorkbasketId the id of the source workbasket for which the distribution targets + * are to be set + * @param targetWorkbasketIds a list of the ids of the target workbaskets + * @throws NotAuthorizedException if the current used doesn't have READ permission for the source + * workbasket + * @throws WorkbasketNotFoundException if either the source workbasket or any of the target + * workbaskets don't exist + */ + void setDistributionTargets(String sourceWorkbasketId, List targetWorkbasketIds) + throws NotAuthorizedException, WorkbasketNotFoundException; - /** - * Add a distribution target to a workbasket. If the specified distribution target exists already, the method - * silently returns without doing anything. - * - * @param sourceWorkbasketId - * the id of the source workbasket - * @param targetWorkbasketId - * the id of the target workbasket - * @throws NotAuthorizedException - * if the current user doesn't have READ permission for the source workbasket - * @throws WorkbasketNotFoundException - * if either the source workbasket or the target workbasket doesn't exist - */ - void addDistributionTarget(String sourceWorkbasketId, String targetWorkbasketId) - throws NotAuthorizedException, WorkbasketNotFoundException; + /** + * Add a distribution target to a workbasket. If the specified distribution target exists already, + * the method silently returns without doing anything. + * + * @param sourceWorkbasketId the id of the source workbasket + * @param targetWorkbasketId the id of the target workbasket + * @throws NotAuthorizedException if the current user doesn't have READ permission for the source + * workbasket + * @throws WorkbasketNotFoundException if either the source workbasket or the target workbasket + * doesn't exist + */ + void addDistributionTarget(String sourceWorkbasketId, String targetWorkbasketId) + throws NotAuthorizedException, WorkbasketNotFoundException; - /** - * Remove a distribution target from a workbasket. If the the specified distribution target doesn't exist, the - * method silently returns without doing anything. - * - * @param sourceWorkbasketId - * The id of the source workbasket - * @param targetWorkbasketId - * The id of the target workbasket - * @throws NotAuthorizedException - * If the current user doesn't have READ permission for the source workbasket - */ - void removeDistributionTarget(String sourceWorkbasketId, String targetWorkbasketId) - throws NotAuthorizedException; + /** + * Remove a distribution target from a workbasket. If the the specified distribution target + * doesn't exist, the method silently returns without doing anything. + * + * @param sourceWorkbasketId The id of the source workbasket + * @param targetWorkbasketId The id of the target workbasket + * @throws NotAuthorizedException If the current user doesn't have READ permission for the source + * workbasket + */ + void removeDistributionTarget(String sourceWorkbasketId, String targetWorkbasketId) + throws NotAuthorizedException; - /** - * Deletes the workbasket by the given ID of it. - * - * @param workbasketId - * Id of the workbasket which should be deleted. - * @return true if the workbasket is marked for deletion. False in another case. - * @throws NotAuthorizedException - * if the current user got no permissions for this interaction. - * @throws WorkbasketNotFoundException - * if the workbasket does not exist. - * @throws WorkbasketInUseException - * if the workbasket does contain task-content. - * @throws InvalidArgumentException - * if the workbasketId is NULL or EMPTY - */ - boolean deleteWorkbasket(String workbasketId) - throws NotAuthorizedException, WorkbasketNotFoundException, WorkbasketInUseException, InvalidArgumentException; + /** + * Deletes the workbasket by the given ID of it. + * + * @param workbasketId Id of the workbasket which should be deleted. + * @return true if the workbasket is marked for deletion. False in another case. + * @throws NotAuthorizedException if the current user got no permissions for this interaction. + * @throws WorkbasketNotFoundException if the workbasket does not exist. + * @throws WorkbasketInUseException if the workbasket does contain task-content. + * @throws InvalidArgumentException if the workbasketId is NULL or EMPTY + */ + boolean deleteWorkbasket(String workbasketId) + throws NotAuthorizedException, WorkbasketNotFoundException, WorkbasketInUseException, + InvalidArgumentException; - /** - * Deletes a list of workbaskets. - * - * @param workbasketsIds - * the ids of the workbaskets to delete. - * @return the result of the operations with Id and Exception for each failed workbasket deletion. - * @throws InvalidArgumentException - * if the WorkbasketIds parameter list is NULL or empty - * @throws NotAuthorizedException - * if the current user got no permission for this interaction. - */ - BulkOperationResults deleteWorkbaskets(List workbasketsIds) - throws NotAuthorizedException, InvalidArgumentException; + /** + * Deletes a list of workbaskets. + * + * @param workbasketsIds the ids of the workbaskets to delete. + * @return the result of the operations with Id and Exception for each failed workbasket deletion. + * @throws InvalidArgumentException if the WorkbasketIds parameter list is NULL or empty + * @throws NotAuthorizedException if the current user got no permission for this interaction. + */ + BulkOperationResults deleteWorkbaskets(List workbasketsIds) + throws NotAuthorizedException, InvalidArgumentException; - /** - * Returns the distribution sources for a given workbasket. - * - * @param workbasketId - * the id of the referenced workbasket - * @return the workbaskets that are distribution sources of the specified workbasket. - * @throws NotAuthorizedException - * if the current user has no read permission for the specified workbasket - * @throws WorkbasketNotFoundException - * if the workbasket doesn't exist - */ - List getDistributionSources(String workbasketId) - throws NotAuthorizedException, WorkbasketNotFoundException; + /** + * Returns the distribution sources for a given workbasket. + * + * @param workbasketId the id of the referenced workbasket + * @return the workbaskets that are distribution sources of the specified workbasket. + * @throws NotAuthorizedException if the current user has no read permission for the specified + * workbasket + * @throws WorkbasketNotFoundException if the workbasket doesn't exist + */ + List getDistributionSources(String workbasketId) + throws NotAuthorizedException, WorkbasketNotFoundException; - /** - * Returns the distribution sources for a given workbasket. - * - * @param workbasketKey - * the key of the referenced workbasket - * @param domain - * the domain of the referenced workbasket - * @return the workbaskets that are distribution sources of the specified workbasket. - * @throws NotAuthorizedException - * if the current user has no read permission for the specified workbasket - * @throws WorkbasketNotFoundException - * if the workbasket doesn't exist - */ - List getDistributionSources(String workbasketKey, String domain) - throws NotAuthorizedException, WorkbasketNotFoundException; + /** + * Returns the distribution sources for a given workbasket. + * + * @param workbasketKey the key of the referenced workbasket + * @param domain the domain of the referenced workbasket + * @return the workbaskets that are distribution sources of the specified workbasket. + * @throws NotAuthorizedException if the current user has no read permission for the specified + * workbasket + * @throws WorkbasketNotFoundException if the workbasket doesn't exist + */ + List getDistributionSources(String workbasketKey, String domain) + throws NotAuthorizedException, WorkbasketNotFoundException; - /** - * Deletes all WorkbasketAccessItems using the given AccessId of a user. - * - * @param accessId - * of a taskana-user. - * @throws NotAuthorizedException - * if the current user is not member of role BUSINESS_ADMIN or ADMIN - */ - void deleteWorkbasketAccessItemsForAccessId(String accessId) throws NotAuthorizedException; + /** + * Deletes all WorkbasketAccessItems using the given AccessId of a user. + * + * @param accessId of a taskana-user. + * @throws NotAuthorizedException if the current user is not member of role BUSINESS_ADMIN or + * ADMIN + */ + void deleteWorkbasketAccessItemsForAccessId(String accessId) throws NotAuthorizedException; } diff --git a/lib/taskana-core/src/main/java/pro/taskana/WorkbasketSummary.java b/lib/taskana-core/src/main/java/pro/taskana/WorkbasketSummary.java index 1435c7fda..24f265e85 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/WorkbasketSummary.java +++ b/lib/taskana-core/src/main/java/pro/taskana/WorkbasketSummary.java @@ -1,121 +1,120 @@ package pro.taskana; /** - * Interface for WorkbasketSummary. This is a specific short model-object which only contains the most important - * information. + * Interface for WorkbasketSummary. This is a specific short model-object which only contains the + * most important information. */ public interface WorkbasketSummary { - /** - * Gets the id of the workbasket. - * - * @return workbasketId - */ - String getId(); + /** + * Gets the id of the workbasket. + * + * @return workbasketId + */ + String getId(); - /** - * Gets the key of the workbasket. - * - * @return workbasketKey - */ - String getKey(); + /** + * Gets the key of the workbasket. + * + * @return workbasketKey + */ + String getKey(); - /** - * Gets the name of the workbasket. - * - * @return workbasket's name - */ - String getName(); + /** + * Gets the name of the workbasket. + * + * @return workbasket's name + */ + String getName(); - /** - * Gets the description of the workbasket. - * - * @return workbasket's description - */ - String getDescription(); + /** + * Gets the description of the workbasket. + * + * @return workbasket's description + */ + String getDescription(); - /** - * Gets the owner of the workbasket. - * - * @return workbasket's owner - */ - String getOwner(); + /** + * Gets the owner of the workbasket. + * + * @return workbasket's owner + */ + String getOwner(); - /** - * Gets the domain of the workbasket. - * - * @return workbasket's domain - */ - String getDomain(); + /** + * Gets the domain of the workbasket. + * + * @return workbasket's domain + */ + String getDomain(); - /** - * Gets the type of the workbasket. - * - * @return workbasket's type - */ - WorkbasketType getType(); + /** + * Gets the type of the workbasket. + * + * @return workbasket's type + */ + WorkbasketType getType(); - /** - * Gets the custom1 property of the workbasket. - * - * @return the workbasket's custom1 property. - */ - String getCustom1(); + /** + * Gets the custom1 property of the workbasket. + * + * @return the workbasket's custom1 property. + */ + String getCustom1(); - /** - * Gets the custom2 property of the workbasket. - * - * @return the workbasket's custom2 property. - */ - String getCustom2(); + /** + * Gets the custom2 property of the workbasket. + * + * @return the workbasket's custom2 property. + */ + String getCustom2(); - /** - * Gets the custom3 property of the workbasket. - * - * @return the workbasket's custom3 property. - */ - String getCustom3(); + /** + * Gets the custom3 property of the workbasket. + * + * @return the workbasket's custom3 property. + */ + String getCustom3(); - /** - * Gets the custom4 property of the workbasket. - * - * @return the workbasket's custom4 property. - */ - String getCustom4(); + /** + * Gets the custom4 property of the workbasket. + * + * @return the workbasket's custom4 property. + */ + String getCustom4(); - /** - * Gets the orglevel1 property of the workbasket. - * - * @return the workbasket's orglevel1 property - */ - String getOrgLevel1(); + /** + * Gets the orglevel1 property of the workbasket. + * + * @return the workbasket's orglevel1 property + */ + String getOrgLevel1(); - /** - * Gets the orglevel2 property of the workbasket. - * - * @return the workbasket's orglevel2 property - */ - String getOrgLevel2(); + /** + * Gets the orglevel2 property of the workbasket. + * + * @return the workbasket's orglevel2 property + */ + String getOrgLevel2(); - /** - * Gets the orglevel3 property of the workbasket. - * - * @return the workbasket's orglevel3 property - */ - String getOrgLevel3(); + /** + * Gets the orglevel3 property of the workbasket. + * + * @return the workbasket's orglevel3 property + */ + String getOrgLevel3(); - /** - * Gets the orglevel4 property of the workbasket. - * - * @return the workbasket's orglevel4 property - */ - String getOrgLevel4(); - - /** - * Gets the markedForDeletion property of the workbasket. - * - * @return the workbasket's markedForDeletion property - */ - boolean isMarkedForDeletion(); + /** + * Gets the orglevel4 property of the workbasket. + * + * @return the workbasket's orglevel4 property + */ + String getOrgLevel4(); + /** + * Gets the markedForDeletion property of the workbasket. + * + * @return the workbasket's markedForDeletion property + */ + boolean isMarkedForDeletion(); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/WorkbasketType.java b/lib/taskana-core/src/main/java/pro/taskana/WorkbasketType.java index 099d889b2..89b2fa15b 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/WorkbasketType.java +++ b/lib/taskana-core/src/main/java/pro/taskana/WorkbasketType.java @@ -1,8 +1,9 @@ package pro.taskana; -/** - * This enum contains the supported work basket types. - */ +/** This enum contains the supported work basket types. */ public enum WorkbasketType { - GROUP, PERSONAL, TOPIC, CLEARANCE + GROUP, + PERSONAL, + TOPIC, + CLEARANCE } diff --git a/lib/taskana-core/src/main/java/pro/taskana/configuration/DB.java b/lib/taskana-core/src/main/java/pro/taskana/configuration/DB.java index 7ba3c5148..9caf8121e 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/configuration/DB.java +++ b/lib/taskana-core/src/main/java/pro/taskana/configuration/DB.java @@ -2,45 +2,42 @@ package pro.taskana.configuration; import pro.taskana.exceptions.UnsupportedDatabaseException; -/** - * Supported versions of databases. - */ +/** Supported versions of databases. */ public enum DB { + H2("H2", "h2"), + DB2("DB2", "db2"), + POSTGRESS("PostgreSQL", "postgres"); - H2("H2", "h2"), - DB2("DB2", "db2"), - POSTGRESS("PostgreSQL", "postgres"); + public final String dbProductname; + public final String dbProductId; - public final String dbProductname; - public final String dbProductId; + DB(String dbProductname, String dbProductId) { + this.dbProductname = dbProductname; + this.dbProductId = dbProductId; + } - DB(String dbProductname, String dbProductId) { - this.dbProductname = dbProductname; - this.dbProductId = dbProductId; - } - - public static boolean isDb2(String dbProductName) { - return dbProductName != null && dbProductName.contains(DB2.dbProductname); - } - - public static boolean isH2(String dbProductName) { - return dbProductName != null && dbProductName.contains(H2.dbProductname); - } - - public static boolean isPostgreSQL(String dbProductName) { - return POSTGRESS.dbProductname.equals(dbProductName); - } - - public static String getDatabaseProductId(String dbProductName) { - - if (isDb2(dbProductName)) { - return DB2.dbProductId; - } else if (isH2(dbProductName)) { - return H2.dbProductId; - } else if (isPostgreSQL(dbProductName)) { - return POSTGRESS.dbProductId; - } else { - throw new UnsupportedDatabaseException(dbProductName); - } + public static boolean isDb2(String dbProductName) { + return dbProductName != null && dbProductName.contains(DB2.dbProductname); + } + + public static boolean isH2(String dbProductName) { + return dbProductName != null && dbProductName.contains(H2.dbProductname); + } + + public static boolean isPostgreSQL(String dbProductName) { + return POSTGRESS.dbProductname.equals(dbProductName); + } + + public static String getDatabaseProductId(String dbProductName) { + + if (isDb2(dbProductName)) { + return DB2.dbProductId; + } else if (isH2(dbProductName)) { + return H2.dbProductId; + } else if (isPostgreSQL(dbProductName)) { + return POSTGRESS.dbProductId; + } else { + throw new UnsupportedDatabaseException(dbProductName); } + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/configuration/DbSchemaCreator.java b/lib/taskana-core/src/main/java/pro/taskana/configuration/DbSchemaCreator.java index 8ad5dc04e..0e7e9dfcf 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/configuration/DbSchemaCreator.java +++ b/lib/taskana-core/src/main/java/pro/taskana/configuration/DbSchemaCreator.java @@ -11,163 +11,164 @@ import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.SQLException; import java.util.Map; - import javax.sql.DataSource; - import org.apache.ibatis.jdbc.ScriptRunner; import org.apache.ibatis.jdbc.SqlRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * This class create the schema for taskana. - */ +/** This class create the schema for taskana. */ public class DbSchemaCreator { - private static final Logger LOGGER = LoggerFactory.getLogger(DbSchemaCreator.class); - private static final String SQL = "/sql"; - private static final String DB_SCHEMA = SQL + "/taskana-schema.sql"; - private static final String DB_SCHEMA_DB2 = SQL + "/taskana-schema-db2.sql"; - private static final String DB_SCHEMA_POSTGRES = SQL + "/taskana-schema-postgres.sql"; - private static final String DB_SCHEMA_DETECTION = SQL + "/schema-detection.sql"; - private static final String DB_SCHEMA_DETECTION_POSTGRES = SQL + "/schema-detection-postgres.sql"; + private static final Logger LOGGER = LoggerFactory.getLogger(DbSchemaCreator.class); + private static final String SQL = "/sql"; + private static final String DB_SCHEMA = SQL + "/taskana-schema.sql"; + private static final String DB_SCHEMA_DB2 = SQL + "/taskana-schema-db2.sql"; + private static final String DB_SCHEMA_POSTGRES = SQL + "/taskana-schema-postgres.sql"; + private static final String DB_SCHEMA_DETECTION = SQL + "/schema-detection.sql"; + private static final String DB_SCHEMA_DETECTION_POSTGRES = SQL + "/schema-detection-postgres.sql"; - private DataSource dataSource; - private String schemaName; - private StringWriter outWriter = new StringWriter(); - private PrintWriter logWriter = new PrintWriter(outWriter); - private StringWriter errorWriter = new StringWriter(); - private PrintWriter errorLogWriter = new PrintWriter(errorWriter); + private DataSource dataSource; + private String schemaName; + private StringWriter outWriter = new StringWriter(); + private PrintWriter logWriter = new PrintWriter(outWriter); + private StringWriter errorWriter = new StringWriter(); + private PrintWriter errorLogWriter = new PrintWriter(errorWriter); - public DbSchemaCreator(DataSource dataSource, String schema) { - super(); - this.dataSource = dataSource; - this.schemaName = schema; + public DbSchemaCreator(DataSource dataSource, String schema) { + super(); + this.dataSource = dataSource; + this.schemaName = schema; + } + + /** + * Run all db scripts. + * + * @throws SQLException will be thrown if there will be some incorrect SQL statements invoked. + */ + public void run() throws SQLException { + Connection connection = dataSource.getConnection(); + LOGGER.debug( + "Using database of type {} with url '{}'", + connection.getMetaData().getDatabaseProductName(), + connection.getMetaData().getURL()); + ScriptRunner runner = getScriptRunnerInstance(connection); + try { + if (!isSchemaPreexisting(connection)) { + String scriptPath = + selectDbScriptFileName(connection.getMetaData().getDatabaseProductName()); + InputStream resourceAsStream = this.getClass().getResourceAsStream(scriptPath); + BufferedReader reader = + new BufferedReader(new InputStreamReader(resourceAsStream, StandardCharsets.UTF_8)); + runner.runScript(getSqlSchemaNameParsed(reader)); + } + } finally { + runner.closeConnection(); } - - private static String selectDbScriptFileName(String dbProductName) { - return DB.isPostgreSQL(dbProductName) - ? DB_SCHEMA_POSTGRES - : DB.isH2(dbProductName) ? DB_SCHEMA : DB_SCHEMA_DB2; + LOGGER.debug(outWriter.toString()); + if (!errorWriter.toString().trim().isEmpty()) { + LOGGER.error(errorWriter.toString()); } + } - private static String selectDbSchemaDetectionScript(String dbProductName) { - return DB.isPostgreSQL(dbProductName) ? DB_SCHEMA_DETECTION_POSTGRES : DB_SCHEMA_DETECTION; - } + public boolean isValidSchemaVersion(String expectedVersion) { + SqlRunner runner = null; + try { + Connection connection = dataSource.getConnection(); + connection.setSchema(this.schemaName); + runner = new SqlRunner(connection); + LOGGER.debug(connection.getMetaData().toString()); - /** - * Run all db scripts. - * - * @throws SQLException - * will be thrown if there will be some incorrect SQL statements invoked. - */ - public void run() throws SQLException { - Connection connection = dataSource.getConnection(); - LOGGER.debug("Using database of type {} with url '{}'", connection.getMetaData().getDatabaseProductName(), - connection.getMetaData().getURL()); - ScriptRunner runner = getScriptRunnerInstance(connection); - try { - if (!isSchemaPreexisting(connection)) { - String scriptPath = selectDbScriptFileName(connection.getMetaData().getDatabaseProductName()); - InputStream resourceAsStream = this.getClass().getResourceAsStream(scriptPath); - BufferedReader reader = new BufferedReader( - new InputStreamReader(resourceAsStream, StandardCharsets.UTF_8)); - runner.runScript(getSqlSchemaNameParsed(reader)); - } - } finally { - runner.closeConnection(); - } - LOGGER.debug(outWriter.toString()); - if (!errorWriter.toString().trim().isEmpty()) { - LOGGER.error(errorWriter.toString()); - } - } + String query = + "select VERSION from TASKANA_SCHEMA_VERSION where " + + "VERSION = (select max(VERSION) from TASKANA_SCHEMA_VERSION) " + + "AND VERSION = ?"; - private ScriptRunner getScriptRunnerInstance(Connection connection) { - ScriptRunner runner = new ScriptRunner(connection); - runner.setStopOnError(true); - runner.setLogWriter(logWriter); - runner.setErrorLogWriter(errorLogWriter); - return runner; - } - - private boolean isSchemaPreexisting(Connection connection) { - ScriptRunner runner = getScriptRunnerInstance(connection); - StringWriter errorWriter = new StringWriter(); - runner.setErrorLogWriter(new PrintWriter(errorWriter)); - try { - String scriptPath = selectDbSchemaDetectionScript(connection.getMetaData().getDatabaseProductName()); - InputStream resourceAsStream = this.getClass().getResourceAsStream(scriptPath); - BufferedReader reader = new BufferedReader(new InputStreamReader(resourceAsStream, StandardCharsets.UTF_8)); - runner.runScript(getSqlSchemaNameParsed(reader)); - } catch (Exception e) { - LOGGER.debug("Schema does not exist."); - if (!errorWriter.toString().trim().isEmpty()) { - LOGGER.debug(errorWriter.toString()); - } - return false; - } - LOGGER.debug("Schema does exist."); + Map queryResult = runner.selectOne(query, expectedVersion); + if (queryResult == null || queryResult.isEmpty()) { + LOGGER.error( + "Schema version not valid. The VERSION property in table TASKANA_SCHEMA_VERSION has not the expected value {}", + expectedVersion); + return false; + } else { + LOGGER.debug("Schema version is valid."); return true; + } + + } catch (Exception e) { + LOGGER.error( + "Schema version not valid. The VERSION property in table TASKANA_SCHEMA_VERSION has not the expected value {}", + expectedVersion); + return false; + } finally { + if (runner != null) { + runner.closeConnection(); + } } + } - public boolean isValidSchemaVersion(String expectedVersion) { - SqlRunner runner = null; - try { - Connection connection = dataSource.getConnection(); - connection.setSchema(this.schemaName); - runner = new SqlRunner(connection); - LOGGER.debug(connection.getMetaData().toString()); + public DataSource getDataSource() { + return dataSource; + } - String query = "select VERSION from TASKANA_SCHEMA_VERSION where " - + "VERSION = (select max(VERSION) from TASKANA_SCHEMA_VERSION) " - + "AND VERSION = ?"; + public void setDataSource(DataSource dataSource) { + this.dataSource = dataSource; + } - Map queryResult = runner.selectOne(query, expectedVersion); - if (queryResult == null || queryResult.isEmpty()) { - LOGGER.error( - "Schema version not valid. The VERSION property in table TASKANA_SCHEMA_VERSION has not the expected value {}", - expectedVersion); - return false; - } else { - LOGGER.debug("Schema version is valid."); - return true; - } + private static String selectDbScriptFileName(String dbProductName) { + return DB.isPostgreSQL(dbProductName) + ? DB_SCHEMA_POSTGRES + : DB.isH2(dbProductName) ? DB_SCHEMA : DB_SCHEMA_DB2; + } - } catch (Exception e) { - LOGGER.error( - "Schema version not valid. The VERSION property in table TASKANA_SCHEMA_VERSION has not the expected value {}", - expectedVersion); - return false; - } finally { - if (runner != null) { - runner.closeConnection(); - } + private static String selectDbSchemaDetectionScript(String dbProductName) { + return DB.isPostgreSQL(dbProductName) ? DB_SCHEMA_DETECTION_POSTGRES : DB_SCHEMA_DETECTION; + } + + private ScriptRunner getScriptRunnerInstance(Connection connection) { + ScriptRunner runner = new ScriptRunner(connection); + runner.setStopOnError(true); + runner.setLogWriter(logWriter); + runner.setErrorLogWriter(errorLogWriter); + return runner; + } + + private boolean isSchemaPreexisting(Connection connection) { + ScriptRunner runner = getScriptRunnerInstance(connection); + StringWriter errorWriter = new StringWriter(); + runner.setErrorLogWriter(new PrintWriter(errorWriter)); + try { + String scriptPath = + selectDbSchemaDetectionScript(connection.getMetaData().getDatabaseProductName()); + InputStream resourceAsStream = this.getClass().getResourceAsStream(scriptPath); + BufferedReader reader = + new BufferedReader(new InputStreamReader(resourceAsStream, StandardCharsets.UTF_8)); + runner.runScript(getSqlSchemaNameParsed(reader)); + } catch (Exception e) { + LOGGER.debug("Schema does not exist."); + if (!errorWriter.toString().trim().isEmpty()) { + LOGGER.debug(errorWriter.toString()); + } + return false; + } + LOGGER.debug("Schema does exist."); + return true; + } + + private StringReader getSqlSchemaNameParsed(BufferedReader reader) { + + StringBuffer content = new StringBuffer(); + try { + String line = ""; + while (line != null) { + line = reader.readLine(); + if (line != null) { + content.append(line.replaceAll("%schemaName%", schemaName) + System.lineSeparator()); } + } + } catch (IOException e) { + LOGGER.error("SchemaName sql parsing failed for schemaName {}", schemaName, e); } - - public DataSource getDataSource() { - return dataSource; - } - - public void setDataSource(DataSource dataSource) { - this.dataSource = dataSource; - } - - private StringReader getSqlSchemaNameParsed(BufferedReader reader) { - - StringBuffer content = new StringBuffer(); - try { - String line = ""; - while (line != null) { - line = reader.readLine(); - if (line != null) { - content.append(line.replaceAll("%schemaName%", schemaName) + System.lineSeparator()); - } - } - } catch (IOException e) { - LOGGER.error("SchemaName sql parsing failed for schemaName {}", schemaName, e); - } - return new StringReader(content.toString()); - } + return new StringReader(content.toString()); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/configuration/TaskanaEngineConfiguration.java b/lib/taskana-core/src/main/java/pro/taskana/configuration/TaskanaEngineConfiguration.java index b175c2106..dc4ae4494 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/configuration/TaskanaEngineConfiguration.java +++ b/lib/taskana-core/src/main/java/pro/taskana/configuration/TaskanaEngineConfiguration.java @@ -22,9 +22,7 @@ import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.stream.Collectors; - import javax.sql.DataSource; - import org.apache.ibatis.datasource.pooled.PooledDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -36,492 +34,521 @@ import pro.taskana.impl.TaskanaEngineImpl; import pro.taskana.impl.util.LoggerUtils; /** - * This central class creates the TaskanaEngine and holds all the information about DB and Security.
+ * This central class creates the TaskanaEngine and holds all the information about DB and Security. + *
* Security is enabled by default. */ public class TaskanaEngineConfiguration { - private static final Logger LOGGER = LoggerFactory.getLogger(TaskanaEngineConfiguration.class); + protected static final String TASKANA_SCHEMA_VERSION = + "1.1.5"; // must match the VERSION value in table + private static final Logger LOGGER = LoggerFactory.getLogger(TaskanaEngineConfiguration.class); + private static final String USER_NAME = "sa"; + private static final String USER_PASSWORD = "sa"; + private static final String JDBC_H2_MEM_TASKANA = + "jdbc:h2:mem:taskana;IGNORECASE=TRUE;LOCK_MODE=0"; + private static final String H2_DRIVER = "org.h2.Driver"; + private static final String TASKANA_PROPERTIES = "/taskana.properties"; + private static final String TASKANA_ROLES_SEPARATOR = "|"; + private static final String TASKANA_JOB_BATCHSIZE = "taskana.jobs.batchSize"; + private static final String TASKANA_JOB_RETRIES = "taskana.jobs.maxRetries"; + private static final String TASKANA_JOB_CLEANUP_RUN_EVERY = "taskana.jobs.cleanup.runEvery"; + private static final String TASKANA_JOB_CLEANUP_FIRST_RUN = "taskana.jobs.cleanup.firstRunAt"; + private static final String TASKANA_JOB_CLEANUP_MINIMUM_AGE = "taskana.jobs.cleanup.minimumAge"; + private static final String TASKANA_JOB_TASK_CLEANUP_ALL_COMPLETED_SAME_PARENTE_BUSINESS = + "taskana.jobs.cleanup.allCompletedSameParentBusiness"; + private static final String TASKANA_DOMAINS_PROPERTY = "taskana.domains"; + private static final String TASKANA_CLASSIFICATION_TYPES_PROPERTY = + "taskana.classification.types"; + private static final String TASKANA_CLASSIFICATION_CATEGORIES_PROPERTY = + "taskana.classification.categories"; + // TASKANA_SCHEMA_VERSION + private static final String DEFAULT_SCHEMA_NAME = "TASKANA"; - private static final String USER_NAME = "sa"; - private static final String USER_PASSWORD = "sa"; - private static final String JDBC_H2_MEM_TASKANA = "jdbc:h2:mem:taskana;IGNORECASE=TRUE;LOCK_MODE=0"; - private static final String H2_DRIVER = "org.h2.Driver"; - private static final String TASKANA_PROPERTIES = "/taskana.properties"; - private static final String TASKANA_ROLES_SEPARATOR = "|"; - private static final String TASKANA_JOB_BATCHSIZE = "taskana.jobs.batchSize"; - private static final String TASKANA_JOB_RETRIES = "taskana.jobs.maxRetries"; - private static final String TASKANA_JOB_CLEANUP_RUN_EVERY = "taskana.jobs.cleanup.runEvery"; - private static final String TASKANA_JOB_CLEANUP_FIRST_RUN = "taskana.jobs.cleanup.firstRunAt"; - private static final String TASKANA_JOB_CLEANUP_MINIMUM_AGE = "taskana.jobs.cleanup.minimumAge"; - private static final String TASKANA_JOB_TASK_CLEANUP_ALL_COMPLETED_SAME_PARENTE_BUSINESS = "taskana.jobs.cleanup.allCompletedSameParentBusiness"; + // Taskana properties file + protected String propertiesFileName = TASKANA_PROPERTIES; - private static final String TASKANA_DOMAINS_PROPERTY = "taskana.domains"; - private static final String TASKANA_CLASSIFICATION_TYPES_PROPERTY = "taskana.classification.types"; - private static final String TASKANA_CLASSIFICATION_CATEGORIES_PROPERTY = "taskana.classification.categories"; - protected static final String TASKANA_SCHEMA_VERSION = "1.1.5"; // must match the VERSION value in table - // TASKANA_SCHEMA_VERSION - private static final String DEFAULT_SCHEMA_NAME = "TASKANA"; + // Taskana datasource configuration + protected DataSource dataSource; + protected DbSchemaCreator dbSchemaCreator; + protected String schemaName; - // Taskana properties file - protected String propertiesFileName = TASKANA_PROPERTIES; + // Taskana role configuration + protected String rolesSeparator = TASKANA_ROLES_SEPARATOR; + protected Map> roleMap = new HashMap<>(); - // Taskana datasource configuration - protected DataSource dataSource; - protected DbSchemaCreator dbSchemaCreator; - protected String schemaName; + // global switch to enable JAAS based authentication and Taskana + // authorizations + protected boolean securityEnabled = true; + protected boolean useManagedTransactions; + // List of configured domain names + protected List domains = new ArrayList(); + // List of configured classification types + protected List classificationTypes = new ArrayList(); + protected Map> classificationCategoriesByTypeMap = + new HashMap>(); + // Properties for the monitor + private boolean germanPublicHolidaysEnabled; + private List customHolidays; + // Properties for generalo job execution + private int jobBatchSize = 100; + private int maxNumberOfJobRetries = 3; + // Properties for the cleanup job + private Instant cleanupJobFirstRun = Instant.parse("2018-01-01T00:00:00Z"); + private Duration cleanupJobRunEvery = Duration.parse("P1D"); + private Duration cleanupJobMinimumAge = Duration.parse("P14D"); + private boolean taskCleanupJobAllCompletedSameParentBusiness = true; - // Taskana role configuration - protected String rolesSeparator = TASKANA_ROLES_SEPARATOR; - protected Map> roleMap = new HashMap<>(); + public TaskanaEngineConfiguration( + DataSource dataSource, boolean useManagedTransactions, String schemaName) + throws SQLException { + this(dataSource, useManagedTransactions, true, schemaName); + } - // global switch to enable JAAS based authentication and Taskana - // authorizations - protected boolean securityEnabled = true; - protected boolean useManagedTransactions; + public TaskanaEngineConfiguration( + DataSource dataSource, + boolean useManagedTransactions, + boolean securityEnabled, + String schemaName) + throws SQLException { + this(dataSource, useManagedTransactions, securityEnabled, null, null, schemaName); + } - // Properties for the monitor - private boolean germanPublicHolidaysEnabled; - private List customHolidays; + public TaskanaEngineConfiguration( + DataSource dataSource, + boolean useManagedTransactions, + boolean securityEnabled, + String propertiesFileName, + String rolesSeparator, + String schemaName) + throws SQLException { + this.useManagedTransactions = useManagedTransactions; + this.securityEnabled = securityEnabled; - // Properties for generalo job execution - private int jobBatchSize = 100; - private int maxNumberOfJobRetries = 3; - - // Properties for the cleanup job - private Instant cleanupJobFirstRun = Instant.parse("2018-01-01T00:00:00Z"); - private Duration cleanupJobRunEvery = Duration.parse("P1D"); - private Duration cleanupJobMinimumAge = Duration.parse("P14D"); - private boolean taskCleanupJobAllCompletedSameParentBusiness = true; - - // List of configured domain names - protected List domains = new ArrayList(); - - // List of configured classification types - protected List classificationTypes = new ArrayList(); - - protected Map> classificationCategoriesByTypeMap = new HashMap>(); - - public TaskanaEngineConfiguration(DataSource dataSource, boolean useManagedTransactions, String schemaName) - throws SQLException { - this(dataSource, useManagedTransactions, true, schemaName); + if (propertiesFileName != null) { + this.propertiesFileName = propertiesFileName; } - public TaskanaEngineConfiguration(DataSource dataSource, boolean useManagedTransactions, - boolean securityEnabled, String schemaName) throws SQLException { - this(dataSource, useManagedTransactions, securityEnabled, null, null, schemaName); + if (rolesSeparator != null) { + this.rolesSeparator = rolesSeparator; } - public TaskanaEngineConfiguration(DataSource dataSource, boolean useManagedTransactions, - boolean securityEnabled, String propertiesFileName, String rolesSeparator, String schemaName) - throws SQLException { - this.useManagedTransactions = useManagedTransactions; - this.securityEnabled = securityEnabled; - - if (propertiesFileName != null) { - this.propertiesFileName = propertiesFileName; - } - - if (rolesSeparator != null) { - this.rolesSeparator = rolesSeparator; - } - - if (dataSource != null) { - this.dataSource = dataSource; - } else { - // use default In Memory datasource - this.dataSource = createDefaultDataSource(); - } - - initSchemaName(schemaName); - initTaskanaProperties(this.propertiesFileName, this.rolesSeparator); - - dbSchemaCreator = new DbSchemaCreator(this.dataSource, this.getSchemaName()); - dbSchemaCreator.run(); - - if (!dbSchemaCreator.isValidSchemaVersion(TASKANA_SCHEMA_VERSION)) { - throw new SystemException( - "The Database Schema Version doesn't match the expected version " + TASKANA_SCHEMA_VERSION); - } - + if (dataSource != null) { + this.dataSource = dataSource; + } else { + // use default In Memory datasource + this.dataSource = createDefaultDataSource(); } - public void initTaskanaProperties(String propertiesFile, String rolesSeparator) { - LOGGER.debug("Reading taskana configuration from {} with role separator {}", propertiesFile, rolesSeparator); - Properties props = readPropertiesFromFile(propertiesFile); - initTaskanaRoles(props, rolesSeparator); - initJobParameters(props); - initDomains(props); - initClassificationTypes(props); - initClassificationCategories(props); + initSchemaName(schemaName); + initTaskanaProperties(this.propertiesFileName, this.rolesSeparator); + + dbSchemaCreator = new DbSchemaCreator(this.dataSource, this.getSchemaName()); + dbSchemaCreator.run(); + + if (!dbSchemaCreator.isValidSchemaVersion(TASKANA_SCHEMA_VERSION)) { + throw new SystemException( + "The Database Schema Version doesn't match the expected version " + + TASKANA_SCHEMA_VERSION); } + } - private void initJobParameters(Properties props) { - String jobBatchSizeProperty = props.getProperty(TASKANA_JOB_BATCHSIZE); - if (jobBatchSizeProperty != null && !jobBatchSizeProperty.isEmpty()) { - try { - jobBatchSize = Integer.parseInt(jobBatchSizeProperty); - } catch (Exception e) { - LOGGER.warn("Could not parse jobBatchSizeProperty ({}). Using default. Exception: {} ", - jobBatchSizeProperty, e.getMessage()); - } - } + public void initTaskanaProperties(String propertiesFile, String rolesSeparator) { + LOGGER.debug( + "Reading taskana configuration from {} with role separator {}", + propertiesFile, + rolesSeparator); + Properties props = readPropertiesFromFile(propertiesFile); + initTaskanaRoles(props, rolesSeparator); + initJobParameters(props); + initDomains(props); + initClassificationTypes(props); + initClassificationCategories(props); + } - String maxNumberOfJobRetriesProperty = props.getProperty(TASKANA_JOB_RETRIES); - if (maxNumberOfJobRetriesProperty != null && !maxNumberOfJobRetriesProperty.isEmpty()) { - try { - maxNumberOfJobRetries = Integer.parseInt(maxNumberOfJobRetriesProperty); - } catch (Exception e) { - LOGGER.warn("Could not parse maxNumberOfJobRetriesProperty ({}). Using default. Exception: {} ", - maxNumberOfJobRetriesProperty, e.getMessage()); - } - } - - String taskCleanupJobFirstRunProperty = props.getProperty(TASKANA_JOB_CLEANUP_FIRST_RUN); - if (taskCleanupJobFirstRunProperty != null && !taskCleanupJobFirstRunProperty.isEmpty()) { - try { - cleanupJobFirstRun = Instant.parse(taskCleanupJobFirstRunProperty); - } catch (Exception e) { - LOGGER.warn("Could not parse taskCleanupJobFirstRunProperty ({}). Using default. Exception: {} ", - taskCleanupJobFirstRunProperty, e.getMessage()); - } - } - - String taskCleanupJobRunEveryProperty = props.getProperty(TASKANA_JOB_CLEANUP_RUN_EVERY); - if (taskCleanupJobRunEveryProperty != null && !taskCleanupJobRunEveryProperty.isEmpty()) { - try { - cleanupJobRunEvery = Duration.parse(taskCleanupJobRunEveryProperty); - } catch (Exception e) { - LOGGER.warn("Could not parse taskCleanupJobRunEveryProperty ({}). Using default. Exception: {} ", - taskCleanupJobRunEveryProperty, e.getMessage()); - } - } - - String taskCleanupJobMinimumAgeProperty = props.getProperty(TASKANA_JOB_CLEANUP_MINIMUM_AGE); - if (taskCleanupJobMinimumAgeProperty != null && !taskCleanupJobMinimumAgeProperty.isEmpty()) { - try { - cleanupJobMinimumAge = Duration.parse(taskCleanupJobMinimumAgeProperty); - } catch (Exception e) { - LOGGER.warn("Could not parse taskCleanupJobMinimumAgeProperty ({}). Using default. Exception: {} ", - taskCleanupJobMinimumAgeProperty, e.getMessage()); - } - } - - String taskCleanupJobAllCompletedSameParentBusinessProperty = props.getProperty( - TASKANA_JOB_TASK_CLEANUP_ALL_COMPLETED_SAME_PARENTE_BUSINESS); - if (taskCleanupJobAllCompletedSameParentBusinessProperty != null - && !taskCleanupJobAllCompletedSameParentBusinessProperty.isEmpty()) { - try { - taskCleanupJobAllCompletedSameParentBusiness = Boolean.parseBoolean( - taskCleanupJobAllCompletedSameParentBusinessProperty); - } catch (Exception e) { - LOGGER.warn( - "Could not parse taskCleanupJobAllCompletedSameParentBusinessProperty ({}). Using default. Exception: {} ", - taskCleanupJobAllCompletedSameParentBusinessProperty, e.getMessage()); - } - } - - LOGGER.debug("Configured number of task and workbasket updates per transaction: {}", jobBatchSize); - LOGGER.debug("Number of retries of failed task updates: {}", maxNumberOfJobRetries); - LOGGER.debug("CleanupJob configuration: first run at {}", cleanupJobFirstRun); - LOGGER.debug("CleanupJob configuration: runs every {}", cleanupJobRunEvery); - LOGGER.debug("CleanupJob configuration: minimum age of tasks to be cleanup up is {}", - cleanupJobMinimumAge); - LOGGER.debug("TaskCleanupJob configuration: all completed task with the same parent business property id {}", - taskCleanupJobAllCompletedSameParentBusiness); - } - - private void initDomains(Properties props) { - String domainNames = props.getProperty(TASKANA_DOMAINS_PROPERTY); - if (domainNames != null && !domainNames.isEmpty()) { - StringTokenizer st = new StringTokenizer(domainNames, ","); - while (st.hasMoreTokens()) { - domains.add(st.nextToken().trim().toUpperCase()); - } - } - LOGGER.debug("Configured domains: {}", domains); - } - - private void initClassificationTypes(Properties props) { - String classificationTypesNames = props.getProperty(TASKANA_CLASSIFICATION_TYPES_PROPERTY); - if (classificationTypesNames != null && !classificationTypesNames.isEmpty()) { - StringTokenizer st = new StringTokenizer(classificationTypesNames, ","); - while (st.hasMoreTokens()) { - classificationTypes.add(st.nextToken().trim().toUpperCase()); - } - } else { - LOGGER.warn("Configuration issue. Classification type is missing"); - } - LOGGER.debug("Configured classificationTypes: {}", classificationTypes); - } - - private void initClassificationCategories(Properties props) { - if (classificationTypes != null && !classificationTypes.isEmpty()) { - String classificationCategoryNames; - StringTokenizer st; - List classificationCategoriesAux; - for (String type : classificationTypes) { - classificationCategoriesAux = new ArrayList<>(); - classificationCategoryNames = props.getProperty( - TASKANA_CLASSIFICATION_CATEGORIES_PROPERTY + "." + type.toLowerCase()); - if (classificationCategoryNames != null && !classificationCategoryNames.isEmpty()) { - st = new StringTokenizer(classificationCategoryNames, ","); - while (st.hasMoreTokens()) { - classificationCategoriesAux.add(st.nextToken().trim().toUpperCase()); - } - classificationCategoriesByTypeMap.put(type, classificationCategoriesAux); - } else { - LOGGER.warn("Configuration issue. Classification categories by type is missing"); - } - } - } - LOGGER.debug("Configured classification categories : {}", domains); - } - - private void initSchemaName(String schemaName) { - if (schemaName != null && !schemaName.isEmpty()) { - this.setSchemaName(schemaName); - } else { - this.setSchemaName(DEFAULT_SCHEMA_NAME); - } - - try (Connection connection = dataSource.getConnection()) { - String databaseProductName = connection.getMetaData().getDatabaseProductName(); - if (DB.isPostgreSQL(databaseProductName)) { - this.schemaName = this.schemaName.toLowerCase(); - } else { - this.schemaName = this.schemaName.toUpperCase(); - } - } catch (SQLException ex) { - LOGGER.error("Caught {} when attempting to initialize the schema name", ex); - } - - LOGGER.debug("Using schema name {}", this.getSchemaName()); - } - - private void initTaskanaRoles(Properties props, String rolesSeparator) { - List validPropertyNames = TaskanaRole.getValidPropertyNames(); - - props.keySet() - .stream() - .map(String::valueOf) - .filter(propertyName -> validPropertyNames.contains(propertyName.toLowerCase().trim())) - .forEach(validPropertyName -> roleMap.put(TaskanaRole.fromPropertyName(validPropertyName), - getTokensWithCollection(props.getProperty(validPropertyName), rolesSeparator))); - - ensureRoleMapIsFullyInitialized(); - - if (LOGGER.isDebugEnabled()) { - roleMap.forEach( - (k, v) -> LOGGER.debug("Found Taskana RoleConfig {} : {} ", k, LoggerUtils.setToString(v))); - } - } - - private HashSet getTokensWithCollection(String str, String rolesSeparator) { - return Collections.list(new StringTokenizer(str, rolesSeparator)).stream() - .map(token -> String.valueOf(token).toLowerCase().trim()) - .collect(Collectors.toCollection(HashSet::new)); - } - - private Properties readPropertiesFromFile(String propertiesFile) { - Properties props = new Properties(); - boolean loadFromClasspath = loadFromClasspath(propertiesFile); - try { - if (loadFromClasspath) { - InputStream inputStream = this.getClass().getResourceAsStream(propertiesFile); - if (inputStream == null) { - LOGGER.error("taskana properties file {} was not found on classpath.", - propertiesFile); - } else { - props.load(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); - LOGGER.debug("Role properties were loaded from file {} from classpath.", propertiesFile); - } - } else { - props.load(new FileInputStream(propertiesFile)); - LOGGER.debug("Role properties were loaded from file {}.", propertiesFile); - } - } catch (IOException e) { - LOGGER.error("caught IOException when processing properties file {}.", propertiesFile); - throw new SystemException("internal System error when processing properties file " + propertiesFile, - e.getCause()); - } - return props; - } - - private boolean loadFromClasspath(String propertiesFile) { - boolean loadFromClasspath = true; - File f = new File(propertiesFile); - if (f.exists() && !f.isDirectory()) { - loadFromClasspath = false; - } - return loadFromClasspath; - } - - private void ensureRoleMapIsFullyInitialized() { - // make sure that roleMap does not return null for any role - Arrays.stream(TaskanaRole.values()) - .forEach(role -> roleMap.putIfAbsent(role, new HashSet<>())); - } - - public static DataSource createDefaultDataSource() { - LOGGER.info("No datasource is provided. A inmemory db is used: " + public static DataSource createDefaultDataSource() { + LOGGER.info( + "No datasource is provided. A inmemory db is used: " + "'org.h2.Driver', 'jdbc:h2:mem:taskana;IGNORECASE=TRUE;LOCK_MODE=0', 'sa', 'sa'"); - return createDatasource(H2_DRIVER, JDBC_H2_MEM_TASKANA, USER_NAME, USER_PASSWORD); + return createDatasource(H2_DRIVER, JDBC_H2_MEM_TASKANA, USER_NAME, USER_PASSWORD); + } + + /** + * This method creates the TaskanaEngine without an sqlSessionFactory. + * + * @return the TaskanaEngine + */ + public TaskanaEngine buildTaskanaEngine() { + return TaskanaEngineImpl.createTaskanaEngine(this); + } + + /** + * This method creates a PooledDataSource, if the needed properties are provided. + * + * @param driver the name of the jdbc driver + * @param jdbcUrl the url to which the jdbc driver connects + * @param username the user name for database access + * @param password the password for database access + * @return DataSource + */ + public static DataSource createDatasource( + String driver, String jdbcUrl, String username, String password) { + return new PooledDataSource(driver, jdbcUrl, username, password); + } + + public boolean isSecurityEnabled() { + return this.securityEnabled; + } + + public DataSource getDatasource() { + return this.dataSource; + } + + public boolean getUseManagedTransactions() { + return this.useManagedTransactions; + } + + public String getPropertiesFileName() { + return this.propertiesFileName; + } + + public void setPropertiesFileName(String propertiesFileName) { + this.propertiesFileName = propertiesFileName; + } + + public int getMaxNumberOfUpdatesPerTransaction() { + return jobBatchSize; + } + + public int getMaxNumberOfJobRetries() { + return maxNumberOfJobRetries; + } + + public String getPropertiesSeparator() { + return this.rolesSeparator; + } + + public void setPropertiesSeparator(String propertiesSeparator) { + this.rolesSeparator = propertiesSeparator; + } + + public boolean isGermanPublicHolidaysEnabled() { + return this.germanPublicHolidaysEnabled; + } + + public void setGermanPublicHolidaysEnabled(boolean germanPublicHolidaysEnabled) { + this.germanPublicHolidaysEnabled = germanPublicHolidaysEnabled; + } + + public List getCustomHolidays() { + return customHolidays; + } + + public void setCustomHolidays(List customHolidays) { + this.customHolidays = customHolidays; + } + + public Map> getRoleMap() { + return roleMap; + } + + public void setRoleMap(Map> roleMap) { + this.roleMap = roleMap; + } + + public List getDomains() { + return domains; + } + + public void setDomains(List domains) { + this.domains = domains; + } + + public List getClassificationTypes() { + return classificationTypes; + } + + public void setClassificationTypes(List classificationTypes) { + this.classificationTypes = classificationTypes; + } + + public List getAllClassificationCategories() { + List classificationCategories = new ArrayList<>(); + for (Map.Entry> type : this.classificationCategoriesByTypeMap.entrySet()) { + classificationCategories.addAll(type.getValue()); + } + return classificationCategories; + } + + public List getClassificationCategoriesByType(String type) { + return classificationCategoriesByTypeMap.get(type); + } + + public void setClassificationCategoriesByType( + Map> classificationCategoriesByType) { + this.classificationCategoriesByTypeMap = classificationCategoriesByType; + } + + public Instant getCleanupJobFirstRun() { + return cleanupJobFirstRun; + } + + public Duration getCleanupJobRunEvery() { + return cleanupJobRunEvery; + } + + public Duration getCleanupJobMinimumAge() { + return cleanupJobMinimumAge; + } + + public boolean isTaskCleanupJobAllCompletedSameParentBusiness() { + return taskCleanupJobAllCompletedSameParentBusiness; + } + + public void setTaskCleanupJobAllCompletedSameParentBusiness( + boolean taskCleanupJobAllCompletedSameParentBusiness) { + this.taskCleanupJobAllCompletedSameParentBusiness = + taskCleanupJobAllCompletedSameParentBusiness; + } + + public String getSchemaName() { + return schemaName; + } + + public void setSchemaName(String schemaName) { + this.schemaName = schemaName; + } + + /** + * Helper method to determine whether all access ids (user Id and group ids) should be used in + * lower case. + * + * @return true if all access ids should be used in lower case, false otherwise + */ + public static boolean shouldUseLowerCaseForAccessIds() { + return true; + } + + private void initJobParameters(Properties props) { + String jobBatchSizeProperty = props.getProperty(TASKANA_JOB_BATCHSIZE); + if (jobBatchSizeProperty != null && !jobBatchSizeProperty.isEmpty()) { + try { + jobBatchSize = Integer.parseInt(jobBatchSizeProperty); + } catch (Exception e) { + LOGGER.warn( + "Could not parse jobBatchSizeProperty ({}). Using default. Exception: {} ", + jobBatchSizeProperty, + e.getMessage()); + } } - /** - * This method creates the TaskanaEngine without an sqlSessionFactory. - * - * @return the TaskanaEngine - */ - public TaskanaEngine buildTaskanaEngine() { - return TaskanaEngineImpl.createTaskanaEngine(this); + String maxNumberOfJobRetriesProperty = props.getProperty(TASKANA_JOB_RETRIES); + if (maxNumberOfJobRetriesProperty != null && !maxNumberOfJobRetriesProperty.isEmpty()) { + try { + maxNumberOfJobRetries = Integer.parseInt(maxNumberOfJobRetriesProperty); + } catch (Exception e) { + LOGGER.warn( + "Could not parse maxNumberOfJobRetriesProperty ({}). Using default. Exception: {} ", + maxNumberOfJobRetriesProperty, + e.getMessage()); + } } - /** - * This method creates a PooledDataSource, if the needed properties are provided. - * - * @param driver - * the name of the jdbc driver - * @param jdbcUrl - * the url to which the jdbc driver connects - * @param username - * the user name for database access - * @param password - * the password for database access - * @return DataSource - */ - public static DataSource createDatasource(String driver, String jdbcUrl, String username, String password) { - return new PooledDataSource(driver, jdbcUrl, username, password); + String taskCleanupJobFirstRunProperty = props.getProperty(TASKANA_JOB_CLEANUP_FIRST_RUN); + if (taskCleanupJobFirstRunProperty != null && !taskCleanupJobFirstRunProperty.isEmpty()) { + try { + cleanupJobFirstRun = Instant.parse(taskCleanupJobFirstRunProperty); + } catch (Exception e) { + LOGGER.warn( + "Could not parse taskCleanupJobFirstRunProperty ({}). Using default. Exception: {} ", + taskCleanupJobFirstRunProperty, + e.getMessage()); + } } - public boolean isSecurityEnabled() { - return this.securityEnabled; + String taskCleanupJobRunEveryProperty = props.getProperty(TASKANA_JOB_CLEANUP_RUN_EVERY); + if (taskCleanupJobRunEveryProperty != null && !taskCleanupJobRunEveryProperty.isEmpty()) { + try { + cleanupJobRunEvery = Duration.parse(taskCleanupJobRunEveryProperty); + } catch (Exception e) { + LOGGER.warn( + "Could not parse taskCleanupJobRunEveryProperty ({}). Using default. Exception: {} ", + taskCleanupJobRunEveryProperty, + e.getMessage()); + } } - public DataSource getDatasource() { - return this.dataSource; + String taskCleanupJobMinimumAgeProperty = props.getProperty(TASKANA_JOB_CLEANUP_MINIMUM_AGE); + if (taskCleanupJobMinimumAgeProperty != null && !taskCleanupJobMinimumAgeProperty.isEmpty()) { + try { + cleanupJobMinimumAge = Duration.parse(taskCleanupJobMinimumAgeProperty); + } catch (Exception e) { + LOGGER.warn( + "Could not parse taskCleanupJobMinimumAgeProperty ({}). Using default. Exception: {} ", + taskCleanupJobMinimumAgeProperty, + e.getMessage()); + } } - public boolean getUseManagedTransactions() { - return this.useManagedTransactions; + String taskCleanupJobAllCompletedSameParentBusinessProperty = + props.getProperty(TASKANA_JOB_TASK_CLEANUP_ALL_COMPLETED_SAME_PARENTE_BUSINESS); + if (taskCleanupJobAllCompletedSameParentBusinessProperty != null + && !taskCleanupJobAllCompletedSameParentBusinessProperty.isEmpty()) { + try { + taskCleanupJobAllCompletedSameParentBusiness = + Boolean.parseBoolean(taskCleanupJobAllCompletedSameParentBusinessProperty); + } catch (Exception e) { + LOGGER.warn( + "Could not parse taskCleanupJobAllCompletedSameParentBusinessProperty ({}). Using default. Exception: {} ", + taskCleanupJobAllCompletedSameParentBusinessProperty, + e.getMessage()); + } } - public String getPropertiesFileName() { - return this.propertiesFileName; - } + LOGGER.debug( + "Configured number of task and workbasket updates per transaction: {}", jobBatchSize); + LOGGER.debug("Number of retries of failed task updates: {}", maxNumberOfJobRetries); + LOGGER.debug("CleanupJob configuration: first run at {}", cleanupJobFirstRun); + LOGGER.debug("CleanupJob configuration: runs every {}", cleanupJobRunEvery); + LOGGER.debug( + "CleanupJob configuration: minimum age of tasks to be cleanup up is {}", + cleanupJobMinimumAge); + LOGGER.debug( + "TaskCleanupJob configuration: all completed task with the same parent business property id {}", + taskCleanupJobAllCompletedSameParentBusiness); + } - public int getMaxNumberOfUpdatesPerTransaction() { - return jobBatchSize; + private void initDomains(Properties props) { + String domainNames = props.getProperty(TASKANA_DOMAINS_PROPERTY); + if (domainNames != null && !domainNames.isEmpty()) { + StringTokenizer st = new StringTokenizer(domainNames, ","); + while (st.hasMoreTokens()) { + domains.add(st.nextToken().trim().toUpperCase()); + } } + LOGGER.debug("Configured domains: {}", domains); + } - public int getMaxNumberOfJobRetries() { - return maxNumberOfJobRetries; + private void initClassificationTypes(Properties props) { + String classificationTypesNames = props.getProperty(TASKANA_CLASSIFICATION_TYPES_PROPERTY); + if (classificationTypesNames != null && !classificationTypesNames.isEmpty()) { + StringTokenizer st = new StringTokenizer(classificationTypesNames, ","); + while (st.hasMoreTokens()) { + classificationTypes.add(st.nextToken().trim().toUpperCase()); + } + } else { + LOGGER.warn("Configuration issue. Classification type is missing"); } + LOGGER.debug("Configured classificationTypes: {}", classificationTypes); + } - public void setPropertiesFileName(String propertiesFileName) { - this.propertiesFileName = propertiesFileName; - } - - public String getPropertiesSeparator() { - return this.rolesSeparator; - } - - public void setPropertiesSeparator(String propertiesSeparator) { - this.rolesSeparator = propertiesSeparator; - } - - public boolean isGermanPublicHolidaysEnabled() { - return this.germanPublicHolidaysEnabled; - } - - public void setGermanPublicHolidaysEnabled(boolean germanPublicHolidaysEnabled) { - this.germanPublicHolidaysEnabled = germanPublicHolidaysEnabled; - } - - public List getCustomHolidays() { - return customHolidays; - } - - public void setCustomHolidays(List customHolidays) { - this.customHolidays = customHolidays; - } - - public Map> getRoleMap() { - return roleMap; - } - - public void setRoleMap(Map> roleMap) { - this.roleMap = roleMap; - } - - public List getDomains() { - return domains; - } - - public void setDomains(List domains) { - this.domains = domains; - } - - public List getClassificationTypes() { - return classificationTypes; - } - - public void setClassificationTypes(List classificationTypes) { - this.classificationTypes = classificationTypes; - } - - public List getAllClassificationCategories() { - List classificationCategories = new ArrayList<>(); - for (Map.Entry> type : this.classificationCategoriesByTypeMap.entrySet()) { - classificationCategories.addAll(type.getValue()); + private void initClassificationCategories(Properties props) { + if (classificationTypes != null && !classificationTypes.isEmpty()) { + String classificationCategoryNames; + StringTokenizer st; + List classificationCategoriesAux; + for (String type : classificationTypes) { + classificationCategoriesAux = new ArrayList<>(); + classificationCategoryNames = + props.getProperty( + TASKANA_CLASSIFICATION_CATEGORIES_PROPERTY + "." + type.toLowerCase()); + if (classificationCategoryNames != null && !classificationCategoryNames.isEmpty()) { + st = new StringTokenizer(classificationCategoryNames, ","); + while (st.hasMoreTokens()) { + classificationCategoriesAux.add(st.nextToken().trim().toUpperCase()); + } + classificationCategoriesByTypeMap.put(type, classificationCategoriesAux); + } else { + LOGGER.warn("Configuration issue. Classification categories by type is missing"); } - return classificationCategories; + } + } + LOGGER.debug("Configured classification categories : {}", domains); + } + + private void initSchemaName(String schemaName) { + if (schemaName != null && !schemaName.isEmpty()) { + this.setSchemaName(schemaName); + } else { + this.setSchemaName(DEFAULT_SCHEMA_NAME); } - public List getClassificationCategoriesByType(String type) { - return classificationCategoriesByTypeMap.get(type); + try (Connection connection = dataSource.getConnection()) { + String databaseProductName = connection.getMetaData().getDatabaseProductName(); + if (DB.isPostgreSQL(databaseProductName)) { + this.schemaName = this.schemaName.toLowerCase(); + } else { + this.schemaName = this.schemaName.toUpperCase(); + } + } catch (SQLException ex) { + LOGGER.error("Caught {} when attempting to initialize the schema name", ex); } - public void setClassificationCategoriesByType(Map> classificationCategoriesByType) { - this.classificationCategoriesByTypeMap = classificationCategoriesByType; - } + LOGGER.debug("Using schema name {}", this.getSchemaName()); + } - public Instant getCleanupJobFirstRun() { - return cleanupJobFirstRun; - } + private void initTaskanaRoles(Properties props, String rolesSeparator) { + List validPropertyNames = TaskanaRole.getValidPropertyNames(); - public Duration getCleanupJobRunEvery() { - return cleanupJobRunEvery; - } + props.keySet().stream() + .map(String::valueOf) + .filter(propertyName -> validPropertyNames.contains(propertyName.toLowerCase().trim())) + .forEach( + validPropertyName -> + roleMap.put( + TaskanaRole.fromPropertyName(validPropertyName), + getTokensWithCollection(props.getProperty(validPropertyName), rolesSeparator))); - public Duration getCleanupJobMinimumAge() { - return cleanupJobMinimumAge; - } + ensureRoleMapIsFullyInitialized(); - public void setTaskCleanupJobAllCompletedSameParentBusiness(boolean taskCleanupJobAllCompletedSameParentBusiness) { - this.taskCleanupJobAllCompletedSameParentBusiness = taskCleanupJobAllCompletedSameParentBusiness; + if (LOGGER.isDebugEnabled()) { + roleMap.forEach( + (k, v) -> + LOGGER.debug("Found Taskana RoleConfig {} : {} ", k, LoggerUtils.setToString(v))); } + } - public boolean isTaskCleanupJobAllCompletedSameParentBusiness() { - return taskCleanupJobAllCompletedSameParentBusiness; + private HashSet getTokensWithCollection(String str, String rolesSeparator) { + return Collections.list(new StringTokenizer(str, rolesSeparator)).stream() + .map(token -> String.valueOf(token).toLowerCase().trim()) + .collect(Collectors.toCollection(HashSet::new)); + } + + private Properties readPropertiesFromFile(String propertiesFile) { + Properties props = new Properties(); + boolean loadFromClasspath = loadFromClasspath(propertiesFile); + try { + if (loadFromClasspath) { + InputStream inputStream = this.getClass().getResourceAsStream(propertiesFile); + if (inputStream == null) { + LOGGER.error("taskana properties file {} was not found on classpath.", propertiesFile); + } else { + props.load(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); + LOGGER.debug("Role properties were loaded from file {} from classpath.", propertiesFile); + } + } else { + props.load(new FileInputStream(propertiesFile)); + LOGGER.debug("Role properties were loaded from file {}.", propertiesFile); + } + } catch (IOException e) { + LOGGER.error("caught IOException when processing properties file {}.", propertiesFile); + throw new SystemException( + "internal System error when processing properties file " + propertiesFile, e.getCause()); } + return props; + } - public String getSchemaName() { - return schemaName; - } - - public void setSchemaName(String schemaName) { - this.schemaName = schemaName; - } - - /** - * Helper method to determine whether all access ids (user Id and group ids) should be used in lower case. - * - * @return true if all access ids should be used in lower case, false otherwise - */ - public static boolean shouldUseLowerCaseForAccessIds() { - return true; + private boolean loadFromClasspath(String propertiesFile) { + boolean loadFromClasspath = true; + File f = new File(propertiesFile); + if (f.exists() && !f.isDirectory()) { + loadFromClasspath = false; } + return loadFromClasspath; + } + private void ensureRoleMapIsFullyInitialized() { + // make sure that roleMap does not return null for any role + Arrays.stream(TaskanaRole.values()).forEach(role -> roleMap.putIfAbsent(role, new HashSet<>())); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/exceptions/AttachmentPersistenceException.java b/lib/taskana-core/src/main/java/pro/taskana/exceptions/AttachmentPersistenceException.java index 9ed1483a1..131048a04 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/exceptions/AttachmentPersistenceException.java +++ b/lib/taskana-core/src/main/java/pro/taskana/exceptions/AttachmentPersistenceException.java @@ -2,14 +2,14 @@ package pro.taskana.exceptions; /** * Thrown, when an attachment should be inserted to the DB, but it does already exist.
- * This may happen when a not persisted attachment with ID will be added twice on a task. This can´t be happen it the - * correct Task-Methods will be used instead the List ones. + * This may happen when a not persisted attachment with ID will be added twice on a task. This can´t + * be happen it the correct Task-Methods will be used instead the List ones. */ public class AttachmentPersistenceException extends TaskanaException { - private static final long serialVersionUID = 123L; + private static final long serialVersionUID = 123L; - public AttachmentPersistenceException(String msg, Throwable cause) { - super(msg, cause); - } + public AttachmentPersistenceException(String msg, Throwable cause) { + super(msg, cause); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/exceptions/AutocommitFailedException.java b/lib/taskana-core/src/main/java/pro/taskana/exceptions/AutocommitFailedException.java index 5b931a69e..c051a166c 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/exceptions/AutocommitFailedException.java +++ b/lib/taskana-core/src/main/java/pro/taskana/exceptions/AutocommitFailedException.java @@ -1,12 +1,10 @@ package pro.taskana.exceptions; -/** - * Thrown in ConnectionManagementMode AUTOCOMMIT when an attempt to commit fails. - * - */ +/** Thrown in ConnectionManagementMode AUTOCOMMIT when an attempt to commit fails. */ public class AutocommitFailedException extends TaskanaRuntimeException { - public AutocommitFailedException(Throwable cause) { - super("Autocommit failed", cause); - } - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; + + public AutocommitFailedException(Throwable cause) { + super("Autocommit failed", cause); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/exceptions/ClassificationAlreadyExistException.java b/lib/taskana-core/src/main/java/pro/taskana/exceptions/ClassificationAlreadyExistException.java index e3bf7a7a6..c613c081c 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/exceptions/ClassificationAlreadyExistException.java +++ b/lib/taskana-core/src/main/java/pro/taskana/exceptions/ClassificationAlreadyExistException.java @@ -2,15 +2,19 @@ package pro.taskana.exceptions; import pro.taskana.Classification; -/** - * Thrown, when a classification does already exits, but wanted to create with same ID+domain. - */ +/** Thrown, when a classification does already exits, but wanted to create with same ID+domain. */ public class ClassificationAlreadyExistException extends TaskanaException { - private static final long serialVersionUID = 4716611657569005013L; + private static final long serialVersionUID = 4716611657569005013L; - public ClassificationAlreadyExistException(Classification classification) { - super("ID='" + classification.getId() + "', KEY='" + classification.getKey() + "', DOMAIN='" - + classification.getDomain() + "';"); - } + public ClassificationAlreadyExistException(Classification classification) { + super( + "ID='" + + classification.getId() + + "', KEY='" + + classification.getKey() + + "', DOMAIN='" + + classification.getDomain() + + "';"); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/exceptions/ClassificationInUseException.java b/lib/taskana-core/src/main/java/pro/taskana/exceptions/ClassificationInUseException.java index 28f4acf71..9e8c72411 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/exceptions/ClassificationInUseException.java +++ b/lib/taskana-core/src/main/java/pro/taskana/exceptions/ClassificationInUseException.java @@ -1,17 +1,15 @@ package pro.taskana.exceptions; -/** - * Thrown if a specific task is not in the database. - */ +/** Thrown if a specific task is not in the database. */ public class ClassificationInUseException extends TaskanaException { - public ClassificationInUseException(String msg) { - super(msg); - } + private static final long serialVersionUID = 1L; - public ClassificationInUseException(String msg, Throwable cause) { - super(msg, cause); - } + public ClassificationInUseException(String msg) { + super(msg); + } - private static final long serialVersionUID = 1L; + public ClassificationInUseException(String msg, Throwable cause) { + super(msg, cause); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/exceptions/ClassificationNotFoundException.java b/lib/taskana-core/src/main/java/pro/taskana/exceptions/ClassificationNotFoundException.java index 2a3db0b10..76feb6cce 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/exceptions/ClassificationNotFoundException.java +++ b/lib/taskana-core/src/main/java/pro/taskana/exceptions/ClassificationNotFoundException.java @@ -1,30 +1,27 @@ package pro.taskana.exceptions; -/** - * Thrown if a specific task is not in the database. - */ +/** Thrown if a specific task is not in the database. */ public class ClassificationNotFoundException extends NotFoundException { - private String key; - private String domain; + private static final long serialVersionUID = 1L; + private String key; + private String domain; - public ClassificationNotFoundException(String id, String msg) { - super(id, msg); - } + public ClassificationNotFoundException(String id, String msg) { + super(id, msg); + } - public ClassificationNotFoundException(String key, String domain, String msg) { - super(null, msg); - this.key = key; - this.domain = domain; - } + public ClassificationNotFoundException(String key, String domain, String msg) { + super(null, msg); + this.key = key; + this.domain = domain; + } - public String getKey() { - return key; - } + public String getKey() { + return key; + } - public String getDomain() { - return domain; - } - - private static final long serialVersionUID = 1L; + public String getDomain() { + return domain; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/exceptions/ConcurrencyException.java b/lib/taskana-core/src/main/java/pro/taskana/exceptions/ConcurrencyException.java index bdf14d731..0b953c093 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/exceptions/ConcurrencyException.java +++ b/lib/taskana-core/src/main/java/pro/taskana/exceptions/ConcurrencyException.java @@ -1,15 +1,16 @@ package pro.taskana.exceptions; /** - * This exception is thrown when an attempt is made to update an object that has already been updated by another user. + * This exception is thrown when an attempt is made to update an object that has already been + * updated by another user. * * @author bbr */ public class ConcurrencyException extends TaskanaException { - public ConcurrencyException(String msg) { - super(msg); - } + private static final long serialVersionUID = 1L; - private static final long serialVersionUID = 1L; + public ConcurrencyException(String msg) { + super(msg); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/exceptions/ConnectionNotSetException.java b/lib/taskana-core/src/main/java/pro/taskana/exceptions/ConnectionNotSetException.java index 0a955083f..2da382db9 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/exceptions/ConnectionNotSetException.java +++ b/lib/taskana-core/src/main/java/pro/taskana/exceptions/ConnectionNotSetException.java @@ -1,14 +1,14 @@ package pro.taskana.exceptions; /** - * Thrown if ConnectionManagementMode is CONNECTION_MANAGED_EXTERNALLY and an attempt is made to call an API method before the setConnection() method has been called. - * + * Thrown if ConnectionManagementMode is CONNECTION_MANAGED_EXTERNALLY and an attempt is made to + * call an API method before the setConnection() method has been called. */ public class ConnectionNotSetException extends TaskanaRuntimeException { - public ConnectionNotSetException() { - super("Connection not set"); - } + private static final long serialVersionUID = 1L; - private static final long serialVersionUID = 1L; + public ConnectionNotSetException() { + super("Connection not set"); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/exceptions/DomainNotFoundException.java b/lib/taskana-core/src/main/java/pro/taskana/exceptions/DomainNotFoundException.java index f91e86dcf..dde0a4609 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/exceptions/DomainNotFoundException.java +++ b/lib/taskana-core/src/main/java/pro/taskana/exceptions/DomainNotFoundException.java @@ -5,10 +5,9 @@ package pro.taskana.exceptions; */ public class DomainNotFoundException extends NotFoundException { - public DomainNotFoundException(String domain, String msg) { - super(domain, msg); - } - - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; + public DomainNotFoundException(String domain, String msg) { + super(domain, msg); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/exceptions/InvalidArgumentException.java b/lib/taskana-core/src/main/java/pro/taskana/exceptions/InvalidArgumentException.java index 5f26aa857..59c29471d 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/exceptions/InvalidArgumentException.java +++ b/lib/taskana-core/src/main/java/pro/taskana/exceptions/InvalidArgumentException.java @@ -7,13 +7,13 @@ package pro.taskana.exceptions; */ public class InvalidArgumentException extends TaskanaException { - public InvalidArgumentException(String msg) { - super(msg); - } + private static final long serialVersionUID = 1L; - public InvalidArgumentException(String msg, Throwable cause) { - super(msg, cause); - } + public InvalidArgumentException(String msg) { + super(msg); + } - private static final long serialVersionUID = 1L; + public InvalidArgumentException(String msg, Throwable cause) { + super(msg, cause); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/exceptions/InvalidOwnerException.java b/lib/taskana-core/src/main/java/pro/taskana/exceptions/InvalidOwnerException.java index bd2efb7c7..7fa4e89db 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/exceptions/InvalidOwnerException.java +++ b/lib/taskana-core/src/main/java/pro/taskana/exceptions/InvalidOwnerException.java @@ -2,13 +2,13 @@ package pro.taskana.exceptions; /** * This exception is thrown when the task state doesn't allow the requested operation. - * @author bbr * + * @author bbr */ public class InvalidOwnerException extends TaskanaException { - public InvalidOwnerException(String msg) { - super(msg); - } + private static final long serialVersionUID = 1L; - private static final long serialVersionUID = 1L; + public InvalidOwnerException(String msg) { + super(msg); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/exceptions/InvalidStateException.java b/lib/taskana-core/src/main/java/pro/taskana/exceptions/InvalidStateException.java index 72a7d07f3..e0fa68b72 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/exceptions/InvalidStateException.java +++ b/lib/taskana-core/src/main/java/pro/taskana/exceptions/InvalidStateException.java @@ -2,13 +2,13 @@ package pro.taskana.exceptions; /** * This exception is thrown when the task state doesn't allow the requested operation. - * @author bbr * + * @author bbr */ public class InvalidStateException extends TaskanaException { - public InvalidStateException(String msg) { - super(msg); - } + private static final long serialVersionUID = 1L; - private static final long serialVersionUID = 1L; + public InvalidStateException(String msg) { + super(msg); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/exceptions/InvalidWorkbasketException.java b/lib/taskana-core/src/main/java/pro/taskana/exceptions/InvalidWorkbasketException.java index a0555150c..6fb9af927 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/exceptions/InvalidWorkbasketException.java +++ b/lib/taskana-core/src/main/java/pro/taskana/exceptions/InvalidWorkbasketException.java @@ -1,16 +1,16 @@ package pro.taskana.exceptions; /** - * This exception is thrown when a request is made to insert or update a workbasket that is missing a required property. + * This exception is thrown when a request is made to insert or update a workbasket that is missing + * a required property. * * @author bbr */ - public class InvalidWorkbasketException extends TaskanaException { - public InvalidWorkbasketException(String msg) { - super(msg); - } + private static final long serialVersionUID = 1L; - private static final long serialVersionUID = 1L; + public InvalidWorkbasketException(String msg) { + super(msg); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/exceptions/NotAuthorizedException.java b/lib/taskana-core/src/main/java/pro/taskana/exceptions/NotAuthorizedException.java index 5da65ff23..d53f858ef 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/exceptions/NotAuthorizedException.java +++ b/lib/taskana-core/src/main/java/pro/taskana/exceptions/NotAuthorizedException.java @@ -1,20 +1,17 @@ package pro.taskana.exceptions; -/** - * This exception is used to communicate a not authorized user. - */ +/** This exception is used to communicate a not authorized user. */ public class NotAuthorizedException extends TaskanaException { - private final String currentUserId; + private static final long serialVersionUID = 21235L; + private final String currentUserId; - public NotAuthorizedException(String msg, String currentUserId) { - super(msg + " - [CURRENT USER: {'" + currentUserId + "'}]"); - this.currentUserId = currentUserId; - } + public NotAuthorizedException(String msg, String currentUserId) { + super(msg + " - [CURRENT USER: {'" + currentUserId + "'}]"); + this.currentUserId = currentUserId; + } - public String getCurrentUserId() { - return currentUserId; - } - - private static final long serialVersionUID = 21235L; + public String getCurrentUserId() { + return currentUserId; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/exceptions/NotAuthorizedToQueryWorkbasketException.java b/lib/taskana-core/src/main/java/pro/taskana/exceptions/NotAuthorizedToQueryWorkbasketException.java index 5eb4df3db..0c86b8971 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/exceptions/NotAuthorizedToQueryWorkbasketException.java +++ b/lib/taskana-core/src/main/java/pro/taskana/exceptions/NotAuthorizedToQueryWorkbasketException.java @@ -1,18 +1,15 @@ package pro.taskana.exceptions; -/** - * This exception is used to communicate that a user is not authorized to query a Workbasket. - */ +/** This exception is used to communicate that a user is not authorized to query a Workbasket. */ public class NotAuthorizedToQueryWorkbasketException extends TaskanaRuntimeException { - public NotAuthorizedToQueryWorkbasketException(String msg) { - super(msg); - } + private static final long serialVersionUID = 1L; - public NotAuthorizedToQueryWorkbasketException(String msg, Throwable cause) { - super(msg, cause); - } - - private static final long serialVersionUID = 1L; + public NotAuthorizedToQueryWorkbasketException(String msg) { + super(msg); + } + public NotAuthorizedToQueryWorkbasketException(String msg, Throwable cause) { + super(msg, cause); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/exceptions/NotFoundException.java b/lib/taskana-core/src/main/java/pro/taskana/exceptions/NotFoundException.java index bfb3aeea5..a5dce5391 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/exceptions/NotFoundException.java +++ b/lib/taskana-core/src/main/java/pro/taskana/exceptions/NotFoundException.java @@ -1,20 +1,17 @@ package pro.taskana.exceptions; -/** - * This exception will be thrown if a specific object is not in the database. - */ +/** This exception will be thrown if a specific object is not in the database. */ public class NotFoundException extends TaskanaException { - String id; + private static final long serialVersionUID = 1L; + String id; - public NotFoundException(String id, String message) { - super(message); - this.id = id; - } + public NotFoundException(String id, String message) { + super(message); + this.id = id; + } - public String getId() { - return id; - } - - private static final long serialVersionUID = 1L; + public String getId() { + return id; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/exceptions/SystemException.java b/lib/taskana-core/src/main/java/pro/taskana/exceptions/SystemException.java index f067d75de..74627e5ad 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/exceptions/SystemException.java +++ b/lib/taskana-core/src/main/java/pro/taskana/exceptions/SystemException.java @@ -1,17 +1,15 @@ package pro.taskana.exceptions; -/** - * This exception is thrown when a generic taskana problem is encountered. - */ +/** This exception is thrown when a generic taskana problem is encountered. */ public class SystemException extends TaskanaRuntimeException { - public SystemException(String msg) { - super(msg); - } + private static final long serialVersionUID = 1L; - public SystemException(String msg, Throwable cause) { - super(msg, cause); - } + public SystemException(String msg) { + super(msg); + } - private static final long serialVersionUID = 1L; + public SystemException(String msg, Throwable cause) { + super(msg, cause); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/exceptions/TaskAlreadyExistException.java b/lib/taskana-core/src/main/java/pro/taskana/exceptions/TaskAlreadyExistException.java index c151d34fa..59724e5a8 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/exceptions/TaskAlreadyExistException.java +++ b/lib/taskana-core/src/main/java/pro/taskana/exceptions/TaskAlreadyExistException.java @@ -1,14 +1,14 @@ package pro.taskana.exceptions; /** - * Thrown when a Task is going to be created, but a Task with the same ID does already exist. The Task ID should be - * unique. + * Thrown when a Task is going to be created, but a Task with the same ID does already exist. The + * Task ID should be unique. */ public class TaskAlreadyExistException extends TaskanaException { - public TaskAlreadyExistException(String id) { - super(id); - } + private static final long serialVersionUID = 1L; - private static final long serialVersionUID = 1L; + public TaskAlreadyExistException(String id) { + super(id); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/exceptions/TaskNotFoundException.java b/lib/taskana-core/src/main/java/pro/taskana/exceptions/TaskNotFoundException.java index 4b6fbd133..b8cab3a5e 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/exceptions/TaskNotFoundException.java +++ b/lib/taskana-core/src/main/java/pro/taskana/exceptions/TaskNotFoundException.java @@ -1,13 +1,11 @@ package pro.taskana.exceptions; -/** - * This exception will be thrown if a specific task is not in the database. - */ +/** This exception will be thrown if a specific task is not in the database. */ public class TaskNotFoundException extends NotFoundException { - public TaskNotFoundException(String id, String msg) { - super(id, msg); - } + private static final long serialVersionUID = 1L; - private static final long serialVersionUID = 1L; + public TaskNotFoundException(String id, String msg) { + super(id, msg); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/exceptions/TaskanaException.java b/lib/taskana-core/src/main/java/pro/taskana/exceptions/TaskanaException.java index 53287a993..ee9e9b5f8 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/exceptions/TaskanaException.java +++ b/lib/taskana-core/src/main/java/pro/taskana/exceptions/TaskanaException.java @@ -7,25 +7,26 @@ package pro.taskana.exceptions; */ public class TaskanaException extends Exception { - private static final long serialVersionUID = 123234345123412L; + private static final long serialVersionUID = 123234345123412L; - public TaskanaException() { - super(); - } + public TaskanaException() { + super(); + } - public TaskanaException(String message) { - super(message); - } + public TaskanaException(String message) { + super(message); + } - public TaskanaException(Throwable cause) { - super(cause); - } + public TaskanaException(Throwable cause) { + super(cause); + } - public TaskanaException(String message, Throwable cause) { - super(message, cause); - } + public TaskanaException(String message, Throwable cause) { + super(message, cause); + } - public TaskanaException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } + public TaskanaException( + String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/exceptions/TaskanaRuntimeException.java b/lib/taskana-core/src/main/java/pro/taskana/exceptions/TaskanaRuntimeException.java index 24b096eb8..bf68ad67f 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/exceptions/TaskanaRuntimeException.java +++ b/lib/taskana-core/src/main/java/pro/taskana/exceptions/TaskanaRuntimeException.java @@ -7,26 +7,26 @@ package pro.taskana.exceptions; */ public class TaskanaRuntimeException extends RuntimeException { - private static final long serialVersionUID = 1511142769801824L; + private static final long serialVersionUID = 1511142769801824L; - public TaskanaRuntimeException() { - super(); - } + public TaskanaRuntimeException() { + super(); + } - public TaskanaRuntimeException(String message) { - super(message); - } + public TaskanaRuntimeException(String message) { + super(message); + } - public TaskanaRuntimeException(Throwable cause) { - super(cause); - } + public TaskanaRuntimeException(Throwable cause) { + super(cause); + } - public TaskanaRuntimeException(String message, Throwable cause) { - super(message, cause); - } + public TaskanaRuntimeException(String message, Throwable cause) { + super(message, cause); + } - public TaskanaRuntimeException(String message, Throwable cause, boolean enableSuppression, - boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } + public TaskanaRuntimeException( + String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/exceptions/UnsupportedDatabaseException.java b/lib/taskana-core/src/main/java/pro/taskana/exceptions/UnsupportedDatabaseException.java index c679a5b48..2cb179bcb 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/exceptions/UnsupportedDatabaseException.java +++ b/lib/taskana-core/src/main/java/pro/taskana/exceptions/UnsupportedDatabaseException.java @@ -5,9 +5,9 @@ package pro.taskana.exceptions; */ public class UnsupportedDatabaseException extends RuntimeException { - public UnsupportedDatabaseException(String name) { - super("Database with '" + name + "' not found"); - } + private static final long serialVersionUID = 1L; - private static final long serialVersionUID = 1L; + public UnsupportedDatabaseException(String name) { + super("Database with '" + name + "' not found"); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/exceptions/WorkbasketAlreadyExistException.java b/lib/taskana-core/src/main/java/pro/taskana/exceptions/WorkbasketAlreadyExistException.java index 543732667..112fea404 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/exceptions/WorkbasketAlreadyExistException.java +++ b/lib/taskana-core/src/main/java/pro/taskana/exceptions/WorkbasketAlreadyExistException.java @@ -2,15 +2,19 @@ package pro.taskana.exceptions; import pro.taskana.Workbasket; -/** - * Thrown, when a workbasket does already exits, but wanted to create with same ID. - */ +/** Thrown, when a workbasket does already exits, but wanted to create with same ID. */ public class WorkbasketAlreadyExistException extends TaskanaException { - private static final long serialVersionUID = 6115013L; + private static final long serialVersionUID = 6115013L; - public WorkbasketAlreadyExistException(Workbasket workbasket) { - super("ID='" + workbasket.getId() + "', KEY=' " + workbasket.getKey() + "', DOMAIN='" - + workbasket.getDomain() + "';"); - } + public WorkbasketAlreadyExistException(Workbasket workbasket) { + super( + "ID='" + + workbasket.getId() + + "', KEY=' " + + workbasket.getKey() + + "', DOMAIN='" + + workbasket.getDomain() + + "';"); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/exceptions/WorkbasketInUseException.java b/lib/taskana-core/src/main/java/pro/taskana/exceptions/WorkbasketInUseException.java index 361a8fa2c..2e5097672 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/exceptions/WorkbasketInUseException.java +++ b/lib/taskana-core/src/main/java/pro/taskana/exceptions/WorkbasketInUseException.java @@ -1,13 +1,11 @@ package pro.taskana.exceptions; -/** - * Thrown if a specific Workbasket does have content and should be deleted. - */ +/** Thrown if a specific Workbasket does have content and should be deleted. */ public class WorkbasketInUseException extends TaskanaException { - public WorkbasketInUseException(String msg) { - super(msg); - } + private static final long serialVersionUID = 1234L; - private static final long serialVersionUID = 1234L; + public WorkbasketInUseException(String msg) { + super(msg); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/exceptions/WorkbasketNotFoundException.java b/lib/taskana-core/src/main/java/pro/taskana/exceptions/WorkbasketNotFoundException.java index bcb34ae34..78d4d9259 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/exceptions/WorkbasketNotFoundException.java +++ b/lib/taskana-core/src/main/java/pro/taskana/exceptions/WorkbasketNotFoundException.java @@ -1,30 +1,27 @@ package pro.taskana.exceptions; -/** - * This exception will be thrown if a specific workbasket is not in the database. - */ +/** This exception will be thrown if a specific workbasket is not in the database. */ public class WorkbasketNotFoundException extends NotFoundException { - private String key; - private String domain; + private static final long serialVersionUID = 1L; + private String key; + private String domain; - public WorkbasketNotFoundException(String id, String msg) { - super(id, msg); - } + public WorkbasketNotFoundException(String id, String msg) { + super(id, msg); + } - public WorkbasketNotFoundException(String key, String domain, String msg) { - super(null, msg); - this.key = key; - this.domain = domain; - } + public WorkbasketNotFoundException(String key, String domain, String msg) { + super(null, msg); + this.key = key; + this.domain = domain; + } - public String getKey() { - return key; - } + public String getKey() { + return key; + } - public String getDomain() { - return domain; - } - - private static final long serialVersionUID = 1L; + public String getDomain() { + return domain; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/history/HistoryEventProducer.java b/lib/taskana-core/src/main/java/pro/taskana/history/HistoryEventProducer.java index 7c84e5e54..9a7502991 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/history/HistoryEventProducer.java +++ b/lib/taskana-core/src/main/java/pro/taskana/history/HistoryEventProducer.java @@ -1,7 +1,6 @@ package pro.taskana.history; import java.util.ServiceLoader; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -9,41 +8,40 @@ import pro.taskana.configuration.TaskanaEngineConfiguration; import pro.taskana.history.api.TaskanaHistory; import pro.taskana.history.api.TaskanaHistoryEvent; -/** - * Creates events and emits them to the registered history service providers. - */ +/** Creates events and emits them to the registered history service providers. */ public final class HistoryEventProducer { - private static final Logger LOGGER = LoggerFactory.getLogger(HistoryEventProducer.class); - private static HistoryEventProducer singleton; - private static boolean enabled = false; - private ServiceLoader serviceLoader; + private static final Logger LOGGER = LoggerFactory.getLogger(HistoryEventProducer.class); + private static HistoryEventProducer singleton; + private static boolean enabled = false; + private ServiceLoader serviceLoader; - private HistoryEventProducer(TaskanaEngineConfiguration taskanaEngineConfiguration) { - serviceLoader = ServiceLoader.load(TaskanaHistory.class); - for (TaskanaHistory history : serviceLoader) { - history.initialize(taskanaEngineConfiguration); - LOGGER.info("Registered history provider: {}", history.getClass().getName()); - enabled = true; - } - if (!enabled) { - LOGGER.info("No history provider found. Running without history."); - } + private HistoryEventProducer(TaskanaEngineConfiguration taskanaEngineConfiguration) { + serviceLoader = ServiceLoader.load(TaskanaHistory.class); + for (TaskanaHistory history : serviceLoader) { + history.initialize(taskanaEngineConfiguration); + LOGGER.info("Registered history provider: {}", history.getClass().getName()); + enabled = true; } + if (!enabled) { + LOGGER.info("No history provider found. Running without history."); + } + } - public static synchronized HistoryEventProducer getInstance(TaskanaEngineConfiguration taskanaEngineConfiguration) { - if (singleton == null) { - singleton = new HistoryEventProducer(taskanaEngineConfiguration); - } - return singleton; + public static synchronized HistoryEventProducer getInstance( + TaskanaEngineConfiguration taskanaEngineConfiguration) { + if (singleton == null) { + singleton = new HistoryEventProducer(taskanaEngineConfiguration); } + return singleton; + } - public static boolean isHistoryEnabled() { - return enabled; - } + public static boolean isHistoryEnabled() { + return enabled; + } - public void createEvent(TaskanaHistoryEvent event) { - LOGGER.debug("Sending event to history service providers: {}", event); - serviceLoader.forEach(historyProvider -> historyProvider.create(event)); - } + public void createEvent(TaskanaHistoryEvent event) { + LOGGER.debug("Sending event to history service providers: {}", event); + serviceLoader.forEach(historyProvider -> historyProvider.create(event)); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/history/api/TaskanaHistory.java b/lib/taskana-core/src/main/java/pro/taskana/history/api/TaskanaHistory.java index df71a0b82..f0b3be78b 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/history/api/TaskanaHistory.java +++ b/lib/taskana-core/src/main/java/pro/taskana/history/api/TaskanaHistory.java @@ -2,25 +2,21 @@ package pro.taskana.history.api; import pro.taskana.configuration.TaskanaEngineConfiguration; -/** - * Interface for TASKANA History Service Provider. - */ +/** Interface for TASKANA History Service Provider. */ public interface TaskanaHistory { - /** - * Initialize TaskanaHistory service. - * - * @param taskanaEngineConfiguration - * {@link TaskanaEngineConfiguration} The Taskana engine configuration for needed initialization. - */ - void initialize(TaskanaEngineConfiguration taskanaEngineConfiguration); - - /** - * Create a new history event. - * - * @param event - * {@link TaskanaHistoryEvent} The event to be created. - */ - void create(TaskanaHistoryEvent event); + /** + * Initialize TaskanaHistory service. + * + * @param taskanaEngineConfiguration {@link TaskanaEngineConfiguration} The Taskana engine + * configuration for needed initialization. + */ + void initialize(TaskanaEngineConfiguration taskanaEngineConfiguration); + /** + * Create a new history event. + * + * @param event {@link TaskanaHistoryEvent} The event to be created. + */ + void create(TaskanaHistoryEvent event); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/history/api/TaskanaHistoryEvent.java b/lib/taskana-core/src/main/java/pro/taskana/history/api/TaskanaHistoryEvent.java index b1f9e0eb3..0017779b4 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/history/api/TaskanaHistoryEvent.java +++ b/lib/taskana-core/src/main/java/pro/taskana/history/api/TaskanaHistoryEvent.java @@ -4,253 +4,277 @@ import java.time.Instant; import pro.taskana.security.CurrentUserContext; -/** - * Super class for all specific events from the TASKANA engine. - */ +/** Super class for all specific events from the TASKANA engine. */ public class TaskanaHistoryEvent { - protected long id; - protected String businessProcessId; - protected String parentBusinessProcessId; - protected String taskId; - protected String eventType; - protected Instant created; - protected String userId; - protected String domain; - protected String workbasketKey; - protected String porCompany; - protected String porSystem; - protected String porInstance; - protected String porType; - protected String porValue; - protected String taskClassificationKey; - protected String taskClassificationCategory; - protected String attachmentClassificationKey; - protected String comment; - protected String oldValue; - protected String newValue; - protected String custom1; - protected String custom2; - protected String custom3; - protected String custom4; - protected String oldData; - protected String newData; + protected long id; + protected String businessProcessId; + protected String parentBusinessProcessId; + protected String taskId; + protected String eventType; + protected Instant created; + protected String userId; + protected String domain; + protected String workbasketKey; + protected String porCompany; + protected String porSystem; + protected String porInstance; + protected String porType; + protected String porValue; + protected String taskClassificationKey; + protected String taskClassificationCategory; + protected String attachmentClassificationKey; + protected String comment; + protected String oldValue; + protected String newValue; + protected String custom1; + protected String custom2; + protected String custom3; + protected String custom4; + protected String oldData; + protected String newData; - public TaskanaHistoryEvent() { - userId = CurrentUserContext.getUserid(); - } + public TaskanaHistoryEvent() { + userId = CurrentUserContext.getUserid(); + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public String getBusinessProcessId() { - return businessProcessId; - } + public String getBusinessProcessId() { + return businessProcessId; + } - public void setBusinessProcessId(String businessProcessId) { - this.businessProcessId = businessProcessId; - } + public void setBusinessProcessId(String businessProcessId) { + this.businessProcessId = businessProcessId; + } - public String getParentBusinessProcessId() { - return parentBusinessProcessId; - } + public String getParentBusinessProcessId() { + return parentBusinessProcessId; + } - public void setParentBusinessProcessId(String parentBusinessProcessId) { - this.parentBusinessProcessId = parentBusinessProcessId; - } + public void setParentBusinessProcessId(String parentBusinessProcessId) { + this.parentBusinessProcessId = parentBusinessProcessId; + } - public String getTaskId() { - return taskId; - } + public String getTaskId() { + return taskId; + } - public void setTaskId(String taskId) { - this.taskId = taskId; - } + public void setTaskId(String taskId) { + this.taskId = taskId; + } - public String getEventType() { - return eventType; - } + public String getEventType() { + return eventType; + } - public void setEventType(String eventType) { - this.eventType = eventType; - } + public void setEventType(String eventType) { + this.eventType = eventType; + } - public Instant getCreated() { - return created; - } + public Instant getCreated() { + return created; + } - public void setCreated(Instant created) { - this.created = created; - } + public void setCreated(Instant created) { + this.created = created; + } - public String getUserId() { - return userId; - } + public String getUserId() { + return userId; + } - public void setUserId(String userId) { - this.userId = userId; - } + public void setUserId(String userId) { + this.userId = userId; + } - public String getDomain() { - return domain; - } + public String getDomain() { + return domain; + } - public void setDomain(String domain) { - this.domain = domain; - } + public void setDomain(String domain) { + this.domain = domain; + } - public String getWorkbasketKey() { - return workbasketKey; - } + public String getWorkbasketKey() { + return workbasketKey; + } - public void setWorkbasketKey(String workbasketKey) { - this.workbasketKey = workbasketKey; - } + public void setWorkbasketKey(String workbasketKey) { + this.workbasketKey = workbasketKey; + } - public String getPorCompany() { - return porCompany; - } + public String getPorCompany() { + return porCompany; + } - public void setPorCompany(String porCompany) { - this.porCompany = porCompany; - } + public void setPorCompany(String porCompany) { + this.porCompany = porCompany; + } - public String getPorSystem() { - return porSystem; - } + public String getPorSystem() { + return porSystem; + } - public void setPorSystem(String porSystem) { - this.porSystem = porSystem; - } + public void setPorSystem(String porSystem) { + this.porSystem = porSystem; + } - public String getPorInstance() { - return porInstance; - } + public String getPorInstance() { + return porInstance; + } - public void setPorInstance(String porInstance) { - this.porInstance = porInstance; - } + public void setPorInstance(String porInstance) { + this.porInstance = porInstance; + } - public String getPorType() { - return porType; - } + public String getPorType() { + return porType; + } - public void setPorType(String porType) { - this.porType = porType; - } + public void setPorType(String porType) { + this.porType = porType; + } - public String getPorValue() { - return porValue; - } + public String getPorValue() { + return porValue; + } - public void setPorValue(String porValue) { - this.porValue = porValue; - } + public void setPorValue(String porValue) { + this.porValue = porValue; + } - public String getTaskClassificationKey() { - return taskClassificationKey; - } + public String getTaskClassificationKey() { + return taskClassificationKey; + } - public void setTaskClassificationKey(String taskClassificationKey) { - this.taskClassificationKey = taskClassificationKey; - } + public void setTaskClassificationKey(String taskClassificationKey) { + this.taskClassificationKey = taskClassificationKey; + } - public String getTaskClassificationCategory() { - return taskClassificationCategory; - } + public String getTaskClassificationCategory() { + return taskClassificationCategory; + } - public void setTaskClassificationCategory(String taskClassificationCategory) { - this.taskClassificationCategory = taskClassificationCategory; - } + public void setTaskClassificationCategory(String taskClassificationCategory) { + this.taskClassificationCategory = taskClassificationCategory; + } - public String getAttachmentClassificationKey() { - return attachmentClassificationKey; - } + public String getAttachmentClassificationKey() { + return attachmentClassificationKey; + } - public void setAttachmentClassificationKey(String attachmentClassificationKey) { - this.attachmentClassificationKey = attachmentClassificationKey; - } + public void setAttachmentClassificationKey(String attachmentClassificationKey) { + this.attachmentClassificationKey = attachmentClassificationKey; + } - public String getComment() { - return comment; - } + public String getComment() { + return comment; + } - public void setComment(String comment) { - this.comment = comment; - } + public void setComment(String comment) { + this.comment = comment; + } - public String getOldValue() { - return oldValue; - } + public String getOldValue() { + return oldValue; + } - public void setOldValue(String oldValue) { - this.oldValue = oldValue; - } + public void setOldValue(String oldValue) { + this.oldValue = oldValue; + } - public String getNewValue() { - return newValue; - } + public String getNewValue() { + return newValue; + } - public void setNewValue(String newValue) { - this.newValue = newValue; - } + public void setNewValue(String newValue) { + this.newValue = newValue; + } - public String getCustom1() { - return custom1; - } + public String getCustom1() { + return custom1; + } - public void setCustom1(String custom1) { - this.custom1 = custom1; - } + public void setCustom1(String custom1) { + this.custom1 = custom1; + } - public String getCustom2() { - return custom2; - } + public String getCustom2() { + return custom2; + } - public void setCustom2(String custom2) { - this.custom2 = custom2; - } + public void setCustom2(String custom2) { + this.custom2 = custom2; + } - public String getCustom3() { - return custom3; - } + public String getCustom3() { + return custom3; + } - public void setCustom3(String custom3) { - this.custom3 = custom3; - } + public void setCustom3(String custom3) { + this.custom3 = custom3; + } - public String getCustom4() { - return custom4; - } + public String getCustom4() { + return custom4; + } - public void setCustom4(String custom4) { - this.custom4 = custom4; - } + public void setCustom4(String custom4) { + this.custom4 = custom4; + } - public String getOldData() { - return oldData; - } + public String getOldData() { + return oldData; + } - public void setOldData(String oldData) { - this.oldData = oldData; - } + public void setOldData(String oldData) { + this.oldData = oldData; + } - public String getNewData() { - return newData; - } + public String getNewData() { + return newData; + } - public void setNewData(String newData) { - this.newData = newData; - } + public void setNewData(String newData) { + this.newData = newData; + } - @Override - public String toString() { - return "TaskanaHistoryEvent [" + "id=" + this.id + ", businessProcessId=" + this.businessProcessId - + ", parentBusinessProcessId=" + this.parentBusinessProcessId + ", taskId=" + this.taskId + ", eventType=" - + this.eventType + ", created=" + this.created + ", userId=" + this.userId + ", domain=" + this.domain - + ", workbasketKey=" + this.workbasketKey + ", taskClassificationKey=" + this.taskClassificationKey - + ", attachmentClassificationKey=" + this.attachmentClassificationKey + ", oldValue=" + this.oldValue - + ", newValue=" + this.newValue + ", oldData=" + this.oldData + ", newData=" + this.newData + "]"; - } + @Override + public String toString() { + return "TaskanaHistoryEvent [" + + "id=" + + this.id + + ", businessProcessId=" + + this.businessProcessId + + ", parentBusinessProcessId=" + + this.parentBusinessProcessId + + ", taskId=" + + this.taskId + + ", eventType=" + + this.eventType + + ", created=" + + this.created + + ", userId=" + + this.userId + + ", domain=" + + this.domain + + ", workbasketKey=" + + this.workbasketKey + + ", taskClassificationKey=" + + this.taskClassificationKey + + ", attachmentClassificationKey=" + + this.attachmentClassificationKey + + ", oldValue=" + + this.oldValue + + ", newValue=" + + this.newValue + + ", oldData=" + + this.oldData + + ", newData=" + + this.newData + + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/history/events/task/ClaimCancelledEvent.java b/lib/taskana-core/src/main/java/pro/taskana/history/events/task/ClaimCancelledEvent.java index 2f88fd576..9e5bd36f2 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/history/events/task/ClaimCancelledEvent.java +++ b/lib/taskana-core/src/main/java/pro/taskana/history/events/task/ClaimCancelledEvent.java @@ -2,14 +2,12 @@ package pro.taskana.history.events.task; import pro.taskana.Task; -/** - * Event fired if a task is cancelled to be claimed. - */ +/** Event fired if a task is cancelled to be claimed. */ public class ClaimCancelledEvent extends TaskEvent { - public ClaimCancelledEvent(Task task) { - super(task); - eventType = "TASK_CLAIM_CANCELLED"; - created = task.getModified(); - } + public ClaimCancelledEvent(Task task) { + super(task); + eventType = "TASK_CLAIM_CANCELLED"; + created = task.getModified(); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/history/events/task/ClaimedEvent.java b/lib/taskana-core/src/main/java/pro/taskana/history/events/task/ClaimedEvent.java index 5fe9e274e..c85f14b28 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/history/events/task/ClaimedEvent.java +++ b/lib/taskana-core/src/main/java/pro/taskana/history/events/task/ClaimedEvent.java @@ -1,14 +1,12 @@ package pro.taskana.history.events.task; import pro.taskana.Task; -/** - * Event fired if a task is claimed. - */ +/** Event fired if a task is claimed. */ public class ClaimedEvent extends TaskEvent { - public ClaimedEvent(Task task) { - super(task); - setEventType("TASK_CLAIMED"); - created = task.getClaimed(); - } + public ClaimedEvent(Task task) { + super(task); + setEventType("TASK_CLAIMED"); + created = task.getClaimed(); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/history/events/task/CompletedEvent.java b/lib/taskana-core/src/main/java/pro/taskana/history/events/task/CompletedEvent.java index 3e9992939..4c15d355b 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/history/events/task/CompletedEvent.java +++ b/lib/taskana-core/src/main/java/pro/taskana/history/events/task/CompletedEvent.java @@ -3,21 +3,18 @@ package pro.taskana.history.events.task; import pro.taskana.Task; import pro.taskana.TaskSummary; -/** - * Event fired if a task is completed. - */ +/** Event fired if a task is completed. */ public class CompletedEvent extends TaskEvent { - public CompletedEvent(Task completedTask) { - super(completedTask); - eventType = "TASK_COMPLETED"; - created = completedTask.getCompleted(); - } - - public CompletedEvent(TaskSummary completedTask) { - super(completedTask); - eventType = "TASK_COMPLETED"; - created = completedTask.getCompleted(); - } + public CompletedEvent(Task completedTask) { + super(completedTask); + eventType = "TASK_COMPLETED"; + created = completedTask.getCompleted(); + } + public CompletedEvent(TaskSummary completedTask) { + super(completedTask); + eventType = "TASK_COMPLETED"; + created = completedTask.getCompleted(); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/history/events/task/CreatedEvent.java b/lib/taskana-core/src/main/java/pro/taskana/history/events/task/CreatedEvent.java index 226fde1a7..7f10f41a0 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/history/events/task/CreatedEvent.java +++ b/lib/taskana-core/src/main/java/pro/taskana/history/events/task/CreatedEvent.java @@ -1,14 +1,12 @@ package pro.taskana.history.events.task; import pro.taskana.Task; -/** - * Event fired if a task is created. - */ +/** Event fired if a task is created. */ public class CreatedEvent extends TaskEvent { - public CreatedEvent(Task task) { - super(task); - eventType = "TASK_CREATED"; - created = task.getCreated(); - } + public CreatedEvent(Task task) { + super(task); + eventType = "TASK_CREATED"; + created = task.getCreated(); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/history/events/task/TaskEvent.java b/lib/taskana-core/src/main/java/pro/taskana/history/events/task/TaskEvent.java index d398d5f52..873de257e 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/history/events/task/TaskEvent.java +++ b/lib/taskana-core/src/main/java/pro/taskana/history/events/task/TaskEvent.java @@ -4,168 +4,175 @@ import pro.taskana.Task; import pro.taskana.TaskSummary; import pro.taskana.history.api.TaskanaHistoryEvent; -/** - * Super class for all task related events. - */ +/** Super class for all task related events. */ public class TaskEvent extends TaskanaHistoryEvent { - public TaskEvent(Task task) { - super(); - taskId = task.getId(); - businessProcessId = task.getBusinessProcessId(); - parentBusinessProcessId = task.getParentBusinessProcessId(); - domain = task.getDomain(); - workbasketKey = task.getWorkbasketKey(); - taskClassificationCategory = task.getClassificationCategory(); - if (task.getClassificationSummary() != null) { - taskClassificationKey = task.getClassificationSummary().getKey(); - } - if (!task.getAttachments().isEmpty()) { - attachmentClassificationKey = task.getAttachments().get(0).getClassificationSummary().getKey(); - } - if (task.getPrimaryObjRef() != null) { - porCompany = task.getPrimaryObjRef().getCompany(); - porSystem = task.getPrimaryObjRef().getSystem(); - porInstance = task.getPrimaryObjRef().getSystemInstance(); - porType = task.getPrimaryObjRef().getType(); - porValue = task.getPrimaryObjRef().getValue(); - } + public TaskEvent(Task task) { + super(); + taskId = task.getId(); + businessProcessId = task.getBusinessProcessId(); + parentBusinessProcessId = task.getParentBusinessProcessId(); + domain = task.getDomain(); + workbasketKey = task.getWorkbasketKey(); + taskClassificationCategory = task.getClassificationCategory(); + if (task.getClassificationSummary() != null) { + taskClassificationKey = task.getClassificationSummary().getKey(); } - - public TaskEvent(TaskSummary task) { - super(); - taskId = task.getTaskId(); - businessProcessId = task.getBusinessProcessId(); - parentBusinessProcessId = task.getParentBusinessProcessId(); - domain = task.getDomain(); - if (task.getWorkbasketSummary() != null) { - workbasketKey = task.getWorkbasketSummary().getKey(); - } - if (task.getClassificationSummary() != null) { - taskClassificationKey = task.getClassificationSummary().getKey(); - taskClassificationCategory = task.getClassificationSummary().getCategory(); - } - if (!task.getAttachmentSummaries().isEmpty()) { - attachmentClassificationKey = task.getAttachmentSummaries().get(0).getClassificationSummary().getKey(); - } - if (task.getPrimaryObjRef() != null) { - porCompany = task.getPrimaryObjRef().getCompany(); - porSystem = task.getPrimaryObjRef().getSystem(); - porInstance = task.getPrimaryObjRef().getSystemInstance(); - porType = task.getPrimaryObjRef().getType(); - porValue = task.getPrimaryObjRef().getValue(); - } + if (!task.getAttachments().isEmpty()) { + attachmentClassificationKey = + task.getAttachments().get(0).getClassificationSummary().getKey(); } - - public String getTaskId() { - return taskId; + if (task.getPrimaryObjRef() != null) { + porCompany = task.getPrimaryObjRef().getCompany(); + porSystem = task.getPrimaryObjRef().getSystem(); + porInstance = task.getPrimaryObjRef().getSystemInstance(); + porType = task.getPrimaryObjRef().getType(); + porValue = task.getPrimaryObjRef().getValue(); } + } - public void setTaskId(String taskId) { - this.taskId = taskId; + public TaskEvent(TaskSummary task) { + super(); + taskId = task.getTaskId(); + businessProcessId = task.getBusinessProcessId(); + parentBusinessProcessId = task.getParentBusinessProcessId(); + domain = task.getDomain(); + if (task.getWorkbasketSummary() != null) { + workbasketKey = task.getWorkbasketSummary().getKey(); } - - public String getBusinessProcessId() { - return businessProcessId; + if (task.getClassificationSummary() != null) { + taskClassificationKey = task.getClassificationSummary().getKey(); + taskClassificationCategory = task.getClassificationSummary().getCategory(); } - - public void setBusinessProcessId(String businessProcessId) { - this.businessProcessId = businessProcessId; + if (!task.getAttachmentSummaries().isEmpty()) { + attachmentClassificationKey = + task.getAttachmentSummaries().get(0).getClassificationSummary().getKey(); } - - public String getParentBusinessProcessId() { - return parentBusinessProcessId; + if (task.getPrimaryObjRef() != null) { + porCompany = task.getPrimaryObjRef().getCompany(); + porSystem = task.getPrimaryObjRef().getSystem(); + porInstance = task.getPrimaryObjRef().getSystemInstance(); + porType = task.getPrimaryObjRef().getType(); + porValue = task.getPrimaryObjRef().getValue(); } + } - public void setParentBusinessProcessId(String parentBusinessProcessId) { - this.parentBusinessProcessId = parentBusinessProcessId; - } + public String getTaskId() { + return taskId; + } - public String getDomain() { - return domain; - } + public void setTaskId(String taskId) { + this.taskId = taskId; + } - public void setDomain(String domain) { - this.domain = domain; - } + public String getBusinessProcessId() { + return businessProcessId; + } - public String getWorkbasketKey() { - return workbasketKey; - } + public void setBusinessProcessId(String businessProcessId) { + this.businessProcessId = businessProcessId; + } - public void setWorkbasketKey(String workbasketKey) { - this.workbasketKey = workbasketKey; - } + public String getParentBusinessProcessId() { + return parentBusinessProcessId; + } - public String getTaskClassificationCategory() { - return taskClassificationCategory; - } + public void setParentBusinessProcessId(String parentBusinessProcessId) { + this.parentBusinessProcessId = parentBusinessProcessId; + } - public void setTaskClassificationCategory(String taskClassificationCategory) { - this.taskClassificationCategory = taskClassificationCategory; - } + public String getDomain() { + return domain; + } - public String getTaskClassificationKey() { - return taskClassificationKey; - } + public void setDomain(String domain) { + this.domain = domain; + } - public void setTaskClassificationKey(String taskClassificationKey) { - this.taskClassificationKey = taskClassificationKey; - } + public String getWorkbasketKey() { + return workbasketKey; + } - public String getAttachmentClassificationKey() { - return attachmentClassificationKey; - } + public void setWorkbasketKey(String workbasketKey) { + this.workbasketKey = workbasketKey; + } - public void setAttachmentClassificationKey(String attachmentClassificationKey) { - this.attachmentClassificationKey = attachmentClassificationKey; - } + public String getTaskClassificationCategory() { + return taskClassificationCategory; + } - public String getPorCompany() { - return porCompany; - } + public void setTaskClassificationCategory(String taskClassificationCategory) { + this.taskClassificationCategory = taskClassificationCategory; + } - public void setPorCompany(String porCompany) { - this.porCompany = porCompany; - } + public String getTaskClassificationKey() { + return taskClassificationKey; + } - public String getPorSystem() { - return porSystem; - } + public void setTaskClassificationKey(String taskClassificationKey) { + this.taskClassificationKey = taskClassificationKey; + } - public void setPorSystem(String porSystem) { - this.porSystem = porSystem; - } + public String getAttachmentClassificationKey() { + return attachmentClassificationKey; + } - public String getPorInstance() { - return porInstance; - } + public void setAttachmentClassificationKey(String attachmentClassificationKey) { + this.attachmentClassificationKey = attachmentClassificationKey; + } - public void setPorInstance(String porInstance) { - this.porInstance = porInstance; - } + public String getPorCompany() { + return porCompany; + } - public String getPorType() { - return porType; - } + public void setPorCompany(String porCompany) { + this.porCompany = porCompany; + } - public void setPorType(String porType) { - this.porType = porType; - } + public String getPorSystem() { + return porSystem; + } - public String getPorValue() { - return porValue; - } + public void setPorSystem(String porSystem) { + this.porSystem = porSystem; + } - public void setPorValue(String porValue) { - this.porValue = porValue; - } + public String getPorInstance() { + return porInstance; + } - @Override - public String toString() { - return "TaskEvent [taskId= " + this.taskId + ", businessProcessId= " + this.businessProcessId - + ", parentBusinessProcessId= " + this.parentBusinessProcessId + ", domain= " + this.domain - + ", workbasketKey= " + this.workbasketKey + "]"; - } + public void setPorInstance(String porInstance) { + this.porInstance = porInstance; + } + public String getPorType() { + return porType; + } + + public void setPorType(String porType) { + this.porType = porType; + } + + public String getPorValue() { + return porValue; + } + + public void setPorValue(String porValue) { + this.porValue = porValue; + } + + @Override + public String toString() { + return "TaskEvent [taskId= " + + this.taskId + + ", businessProcessId= " + + this.businessProcessId + + ", parentBusinessProcessId= " + + this.parentBusinessProcessId + + ", domain= " + + this.domain + + ", workbasketKey= " + + this.workbasketKey + + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/history/events/task/TransferredEvent.java b/lib/taskana-core/src/main/java/pro/taskana/history/events/task/TransferredEvent.java index cb8c96a4f..9d02ee3cf 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/history/events/task/TransferredEvent.java +++ b/lib/taskana-core/src/main/java/pro/taskana/history/events/task/TransferredEvent.java @@ -6,18 +6,17 @@ import org.slf4j.LoggerFactory; import pro.taskana.Task; import pro.taskana.WorkbasketSummary; -/** - * Event fired if a task is transferred. - */ +/** Event fired if a task is transferred. */ public class TransferredEvent extends TaskEvent { - private static final Logger LOGGER = LoggerFactory.getLogger(TransferredEvent.class); + private static final Logger LOGGER = LoggerFactory.getLogger(TransferredEvent.class); - public TransferredEvent(Task task, WorkbasketSummary oldWorkbasket, WorkbasketSummary newWorkbasket) { - super(task); - eventType = "TASK_TRANSFERRED"; - created = task.getModified(); - this.oldValue = oldWorkbasket.getId(); - this.newValue = newWorkbasket.getId(); - } + public TransferredEvent( + Task task, WorkbasketSummary oldWorkbasket, WorkbasketSummary newWorkbasket) { + super(task); + eventType = "TASK_TRANSFERRED"; + created = task.getModified(); + this.oldValue = oldWorkbasket.getId(); + this.newValue = newWorkbasket.getId(); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/AbstractWorkbasketAccessItemQueryImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/AbstractWorkbasketAccessItemQueryImpl.java index 58066b751..60acf47a4 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/AbstractWorkbasketAccessItemQueryImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/AbstractWorkbasketAccessItemQueryImpl.java @@ -3,7 +3,6 @@ package pro.taskana.impl; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import org.apache.ibatis.exceptions.PersistenceException; import org.apache.ibatis.session.RowBounds; import org.slf4j.Logger; @@ -21,199 +20,217 @@ import pro.taskana.impl.util.LoggerUtils; * @param the actual WorkbasketAccessItemQuery behind this abstract class * @param the workbasket access item */ -abstract class AbstractWorkbasketAccessItemQueryImpl, T extends WorkbasketAccessItem> +abstract class AbstractWorkbasketAccessItemQueryImpl< + Q extends AbstractWorkbasketAccessItemQuery, T extends WorkbasketAccessItem> implements AbstractWorkbasketAccessItemQuery { - private static final String LINK_TO_COUNTER = "pro.taskana.mappings.QueryMapper.countQueryWorkbasketAccessItems"; + private static final String LINK_TO_COUNTER = + "pro.taskana.mappings.QueryMapper.countQueryWorkbasketAccessItems"; - private static final Logger LOGGER = LoggerFactory.getLogger(AbstractWorkbasketAccessItemQueryImpl.class); - private AccessItemQueryColumnName columnName; - private String[] accessIdIn; - private String[] workbasketIdIn; - private String[] idIn; + private static final Logger LOGGER = + LoggerFactory.getLogger(AbstractWorkbasketAccessItemQueryImpl.class); + private AccessItemQueryColumnName columnName; + private String[] accessIdIn; + private String[] workbasketIdIn; + private String[] idIn; - private InternalTaskanaEngine taskanaEngine; - private List orderBy; - private List orderColumns; + private InternalTaskanaEngine taskanaEngine; + private List orderBy; + private List orderColumns; - AbstractWorkbasketAccessItemQueryImpl(InternalTaskanaEngine taskanaEngine) { - this.taskanaEngine = taskanaEngine; - orderBy = new ArrayList<>(); - orderColumns = new ArrayList<>(); + AbstractWorkbasketAccessItemQueryImpl(InternalTaskanaEngine taskanaEngine) { + this.taskanaEngine = taskanaEngine; + orderBy = new ArrayList<>(); + orderColumns = new ArrayList<>(); + } + + @Override + public Q idIn(String... ids) { + this.idIn = ids; + return _this(); + } + + @Override + public Q workbasketIdIn(String... id) { + this.workbasketIdIn = id; + return _this(); + } + + @Override + public Q accessIdIn(String... accessId) { + this.accessIdIn = accessId; + WorkbasketQueryImpl.lowercaseAccessIds(this.accessIdIn); + return _this(); + } + + @Override + public Q orderById(SortDirection sortDirection) { + return addOrderCriteria("ID", sortDirection); + } + + @Override + public Q orderByWorkbasketId(SortDirection sortDirection) { + return addOrderCriteria("WORKBASKET_ID", sortDirection); + } + + @Override + public Q orderByAccessId(SortDirection sortDirection) { + return addOrderCriteria("ACCESS_ID", sortDirection); + } + + @Override + public List list() { + LOGGER.debug("entry to list(), this = {}", _this()); + List result = new ArrayList<>(); + try { + taskanaEngine.openConnection(); + List foundAccessItms = + taskanaEngine.getSqlSession().selectList(getLinkToMapper(), _this()); + result.addAll(foundAccessItms); + return result; + } finally { + taskanaEngine.returnConnection(); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "exit from list(). Returning {} resulting Objects: {} ", + result.size(), + LoggerUtils.listToString(result)); + } } + } - abstract Q _this(); - - abstract String getLinkToMapper(); - - abstract String getLinkToValueMapper(); - - @Override - public Q idIn(String... ids) { - this.idIn = ids; - return _this(); + @Override + public List listValues( + AccessItemQueryColumnName columnName, SortDirection sortDirection) { + LOGGER.debug("Entry to listValues(dbColumnName={}) this = {}", columnName, _this()); + List result = null; + try { + taskanaEngine.openConnection(); + this.columnName = columnName; + this.orderBy.clear(); + this.addOrderCriteria(columnName.toString(), sortDirection); + result = taskanaEngine.getSqlSession().selectList(getLinkToValueMapper(), _this()); + return result; + } finally { + taskanaEngine.returnConnection(); + if (LOGGER.isDebugEnabled()) { + int numberOfResultObjects = result == null ? 0 : result.size(); + LOGGER.debug( + "Exit from listValues. Returning {} resulting Objects: {} ", + numberOfResultObjects, + LoggerUtils.listToString(result)); + } } + } - @Override - public Q workbasketIdIn(String... id) { - this.workbasketIdIn = id; - return _this(); + @Override + public List list(int offset, int limit) { + LOGGER.debug("entry to list(offset = {}, limit = {}), this = {}", offset, limit, _this()); + List result = new ArrayList<>(); + try { + taskanaEngine.openConnection(); + RowBounds rowBounds = new RowBounds(offset, limit); + List foundAccessItms = + taskanaEngine.getSqlSession().selectList(getLinkToMapper(), _this(), rowBounds); + result.addAll(foundAccessItms); + return result; + } catch (PersistenceException e) { + if (e.getMessage().contains("ERRORCODE=-4470")) { + TaskanaRuntimeException ex = + new TaskanaRuntimeException( + "The offset beginning was set over the amount of result-rows.", e.getCause()); + ex.setStackTrace(e.getStackTrace()); + throw ex; + } + throw e; + } finally { + taskanaEngine.returnConnection(); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "exit from list(offset,limit). Returning {} resulting Objects: {} ", + result.size(), + LoggerUtils.listToString(result)); + } } + } - @Override - public Q accessIdIn(String... accessId) { - this.accessIdIn = accessId; - WorkbasketQueryImpl.lowercaseAccessIds(this.accessIdIn); - return _this(); + @Override + public T single() { + LOGGER.debug("entry to single(), this = {}", _this()); + T accessItem = null; + try { + taskanaEngine.openConnection(); + accessItem = taskanaEngine.getSqlSession().selectOne(getLinkToMapper(), _this()); + return accessItem; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from single(). Returning result {} ", accessItem); } + } - @Override - public Q orderById(SortDirection sortDirection) { - return addOrderCriteria("ID", sortDirection); + @Override + public long count() { + LOGGER.debug("entry to count(), this = {}", _this()); + Long rowCount = null; + try { + taskanaEngine.openConnection(); + rowCount = taskanaEngine.getSqlSession().selectOne(LINK_TO_COUNTER, _this()); + return (rowCount == null) ? 0L : rowCount; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from count(). Returning result {} ", rowCount); } + } - @Override - public Q orderByWorkbasketId(SortDirection sortDirection) { - return addOrderCriteria("WORKBASKET_ID", sortDirection); - } + public String[] getIdIn() { + return this.idIn; + } - @Override - public Q orderByAccessId(SortDirection sortDirection) { - return addOrderCriteria("ACCESS_ID", sortDirection); - } + public String[] getAccessIdIn() { + return accessIdIn; + } - @Override - public List list() { - LOGGER.debug("entry to list(), this = {}", _this()); - List result = new ArrayList<>(); - try { - taskanaEngine.openConnection(); - List foundAccessItms = taskanaEngine.getSqlSession() - .selectList(getLinkToMapper(), _this()); - result.addAll(foundAccessItms); - return result; - } finally { - taskanaEngine.returnConnection(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("exit from list(). Returning {} resulting Objects: {} ", result.size(), - LoggerUtils.listToString(result)); - } - } - } + public String[] getWorkbasketIdIn() { + return workbasketIdIn; + } - @Override - public List listValues(AccessItemQueryColumnName columnName, SortDirection sortDirection) { - LOGGER.debug("Entry to listValues(dbColumnName={}) this = {}", columnName, _this()); - List result = null; - try { - taskanaEngine.openConnection(); - this.columnName = columnName; - this.orderBy.clear(); - this.addOrderCriteria(columnName.toString(), sortDirection); - result = taskanaEngine.getSqlSession().selectList(getLinkToValueMapper(), _this()); - return result; - } finally { - taskanaEngine.returnConnection(); - if (LOGGER.isDebugEnabled()) { - int numberOfResultObjects = result == null ? 0 : result.size(); - LOGGER.debug("Exit from listValues. Returning {} resulting Objects: {} ", numberOfResultObjects, - LoggerUtils.listToString(result)); - } - } - } + public List getOrderBy() { + return orderBy; + } - @Override - public List list(int offset, int limit) { - LOGGER.debug("entry to list(offset = {}, limit = {}), this = {}", offset, limit, _this()); - List result = new ArrayList<>(); - try { - taskanaEngine.openConnection(); - RowBounds rowBounds = new RowBounds(offset, limit); - List foundAccessItms = taskanaEngine.getSqlSession() - .selectList(getLinkToMapper(), _this(), rowBounds); - result.addAll(foundAccessItms); - return result; - } catch (PersistenceException e) { - if (e.getMessage().contains("ERRORCODE=-4470")) { - TaskanaRuntimeException ex = new TaskanaRuntimeException( - "The offset beginning was set over the amount of result-rows.", e.getCause()); - ex.setStackTrace(e.getStackTrace()); - throw ex; - } - throw e; - } finally { - taskanaEngine.returnConnection(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("exit from list(offset,limit). Returning {} resulting Objects: {} ", result.size(), - LoggerUtils.listToString(result)); - } - } - } + public List getOrderColumns() { + return orderColumns; + } - @Override - public T single() { - LOGGER.debug("entry to single(), this = {}", _this()); - T accessItem = null; - try { - taskanaEngine.openConnection(); - accessItem = taskanaEngine.getSqlSession().selectOne(getLinkToMapper(), _this()); - return accessItem; - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from single(). Returning result {} ", accessItem); - } - } + public AccessItemQueryColumnName getColumnName() { + return columnName; + } - @Override - public long count() { - LOGGER.debug("entry to count(), this = {}", _this()); - Long rowCount = null; - try { - taskanaEngine.openConnection(); - rowCount = taskanaEngine.getSqlSession().selectOne(LINK_TO_COUNTER, _this()); - return (rowCount == null) ? 0L : rowCount; - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from count(). Returning result {} ", rowCount); - } - } + abstract Q _this(); - protected Q addOrderCriteria(String colName, SortDirection sortDirection) { - String orderByDirection = " " + (sortDirection == null ? SortDirection.ASCENDING : sortDirection); - orderBy.add(colName + orderByDirection); - orderColumns.add(colName); - return _this(); - } + abstract String getLinkToMapper(); - public String[] getIdIn() { - return this.idIn; - } + abstract String getLinkToValueMapper(); - public String[] getAccessIdIn() { - return accessIdIn; - } - - public String[] getWorkbasketIdIn() { - return workbasketIdIn; - } - - public List getOrderBy() { - return orderBy; - } - - public List getOrderColumns() { - return orderColumns; - } - - public AccessItemQueryColumnName getColumnName() { - return columnName; - } - - @Override - public String toString() { - return "AbstractWorkbasketAccessItemQueryImpl [" + "idIn=" + Arrays.toString(this.idIn) + ", accessIdIn=" - + Arrays.toString(this.accessIdIn) + ", workbasketIdIn=" + Arrays.toString(this.workbasketIdIn) - + ", orderBy=" + this.orderBy + "]"; - } + protected Q addOrderCriteria(String colName, SortDirection sortDirection) { + String orderByDirection = + " " + (sortDirection == null ? SortDirection.ASCENDING : sortDirection); + orderBy.add(colName + orderByDirection); + orderColumns.add(colName); + return _this(); + } + @Override + public String toString() { + return "AbstractWorkbasketAccessItemQueryImpl [" + + "idIn=" + + Arrays.toString(this.idIn) + + ", accessIdIn=" + + Arrays.toString(this.accessIdIn) + + ", workbasketIdIn=" + + Arrays.toString(this.workbasketIdIn) + + ", orderBy=" + + this.orderBy + + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/AttachmentImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/AttachmentImpl.java index 58ab95021..88ab0f4a8 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/AttachmentImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/AttachmentImpl.java @@ -16,231 +16,246 @@ import pro.taskana.ObjectReference; */ public class AttachmentImpl implements Attachment { - private String id; - private String taskId; - private Instant created; - private Instant modified; - private ClassificationSummary classificationSummary; - private ObjectReference objectReference; - private String channel; - private Instant received; - private Map customAttributes = new HashMap(); + private String id; + private String taskId; + private Instant created; + private Instant modified; + private ClassificationSummary classificationSummary; + private ObjectReference objectReference; + private String channel; + private Instant received; + private Map customAttributes = new HashMap(); - AttachmentImpl() { + AttachmentImpl() {} + + @Override + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @Override + public String getTaskId() { + return taskId; + } + + public void setTaskId(String taskId) { + this.taskId = taskId; + } + + @Override + public Instant getCreated() { + return created; + } + + public void setCreated(Instant created) { + this.created = created; + } + + @Override + public Instant getModified() { + return modified; + } + + public void setModified(Instant modified) { + this.modified = modified; + } + + @Override + public ClassificationSummary getClassificationSummary() { + return classificationSummary; + } + + @Override + public void setClassificationSummary(ClassificationSummary classificationSummary) { + this.classificationSummary = classificationSummary; + } + + // auxiliary method to enable MyBatis access to classificationSummary + public ClassificationSummaryImpl getClassificationSummaryImpl() { + return (ClassificationSummaryImpl) classificationSummary; + } + + // auxiliary method to enable MyBatis access to classificationSummary + public void setClassificationSummaryImpl(ClassificationSummaryImpl classificationSummary) { + this.classificationSummary = classificationSummary; + } + + @Override + public ObjectReference getObjectReference() { + return objectReference; + } + + @Override + public void setObjectReference(ObjectReference objectReference) { + this.objectReference = objectReference; + } + + @Override + public String getChannel() { + return channel; + } + + @Override + public void setChannel(String channel) { + this.channel = channel; + } + + @Override + public Instant getReceived() { + return received; + } + + @Override + public void setReceived(Instant received) { + this.received = received; + } + + @Override + public Map getCustomAttributes() { + if (customAttributes == null) { + customAttributes = new HashMap<>(); } + return customAttributes; + } - @Override - public String getId() { - return id; + @Override + public void setCustomAttributes(Map customAttributes) { + this.customAttributes = customAttributes; + } + + @Override + public AttachmentSummary asSummary() { + AttachmentSummaryImpl summary = new AttachmentSummaryImpl(); + summary.setClassificationSummary(this.classificationSummary); + summary.setCreated(this.created); + summary.setId(this.id); + summary.setModified(this.modified); + summary.setReceived(this.received); + summary.setTaskId(this.taskId); + summary.setChannel(this.channel); + summary.setObjectReference(this.objectReference); + return summary; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((channel == null) ? 0 : channel.hashCode()); + result = + prime * result + ((classificationSummary == null) ? 0 : classificationSummary.hashCode()); + result = prime * result + ((created == null) ? 0 : created.hashCode()); + result = prime * result + ((customAttributes == null) ? 0 : customAttributes.hashCode()); + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((modified == null) ? 0 : modified.hashCode()); + result = prime * result + ((objectReference == null) ? 0 : objectReference.hashCode()); + result = prime * result + ((received == null) ? 0 : received.hashCode()); + result = prime * result + ((taskId == null) ? 0 : taskId.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; } - - public void setId(String id) { - this.id = id; + if (obj == null) { + return false; } - - @Override - public String getTaskId() { - return taskId; + if (!getClass().isAssignableFrom(obj.getClass())) { + return false; } - - public void setTaskId(String taskId) { - this.taskId = taskId; + AttachmentImpl other = (AttachmentImpl) obj; + if (channel == null) { + if (other.channel != null) { + return false; + } + } else if (!channel.equals(other.channel)) { + return false; } - - @Override - public Instant getCreated() { - return created; + if (classificationSummary == null) { + if (other.classificationSummary != null) { + return false; + } + } else if (!classificationSummary.equals(other.classificationSummary)) { + return false; } - - public void setCreated(Instant created) { - this.created = created; + if (created == null) { + if (other.created != null) { + return false; + } + } else if (!created.equals(other.created)) { + return false; } - - @Override - public Instant getModified() { - return modified; + if (customAttributes == null) { + if (other.customAttributes != null) { + return false; + } + } else if (!customAttributes.equals(other.customAttributes)) { + return false; } - - public void setModified(Instant modified) { - this.modified = modified; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; } - - @Override - public ClassificationSummary getClassificationSummary() { - return classificationSummary; + if (modified == null) { + if (other.modified != null) { + return false; + } + } else if (!modified.equals(other.modified)) { + return false; } - - @Override - public void setClassificationSummary(ClassificationSummary classificationSummary) { - this.classificationSummary = classificationSummary; + if (objectReference == null) { + if (other.objectReference != null) { + return false; + } + } else if (!objectReference.equals(other.objectReference)) { + return false; } - - // auxiliary method to enable MyBatis access to classificationSummary - public ClassificationSummaryImpl getClassificationSummaryImpl() { - return (ClassificationSummaryImpl) classificationSummary; + if (received == null) { + if (other.received != null) { + return false; + } + } else if (!received.equals(other.received)) { + return false; } - - // auxiliary method to enable MyBatis access to classificationSummary - public void setClassificationSummaryImpl(ClassificationSummaryImpl classificationSummary) { - this.classificationSummary = classificationSummary; - } - - @Override - public ObjectReference getObjectReference() { - return objectReference; - } - - @Override - public void setObjectReference(ObjectReference objectReference) { - this.objectReference = objectReference; - } - - @Override - public String getChannel() { - return channel; - } - - @Override - public void setChannel(String channel) { - this.channel = channel; - } - - @Override - public Instant getReceived() { - return received; - } - - @Override - public void setReceived(Instant received) { - this.received = received; - } - - @Override - public Map getCustomAttributes() { - if (customAttributes == null) { - customAttributes = new HashMap<>(); - } - return customAttributes; - } - - @Override - public void setCustomAttributes(Map customAttributes) { - this.customAttributes = customAttributes; - } - - @Override - public AttachmentSummary asSummary() { - AttachmentSummaryImpl summary = new AttachmentSummaryImpl(); - summary.setClassificationSummary(this.classificationSummary); - summary.setCreated(this.created); - summary.setId(this.id); - summary.setModified(this.modified); - summary.setReceived(this.received); - summary.setTaskId(this.taskId); - summary.setChannel(this.channel); - summary.setObjectReference(this.objectReference); - return summary; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((channel == null) ? 0 : channel.hashCode()); - result = prime * result + ((classificationSummary == null) ? 0 : classificationSummary.hashCode()); - result = prime * result + ((created == null) ? 0 : created.hashCode()); - result = prime * result + ((customAttributes == null) ? 0 : customAttributes.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((modified == null) ? 0 : modified.hashCode()); - result = prime * result + ((objectReference == null) ? 0 : objectReference.hashCode()); - result = prime * result + ((received == null) ? 0 : received.hashCode()); - result = prime * result + ((taskId == null) ? 0 : taskId.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!getClass().isAssignableFrom(obj.getClass())) { - return false; - } - AttachmentImpl other = (AttachmentImpl) obj; - if (channel == null) { - if (other.channel != null) { - return false; - } - } else if (!channel.equals(other.channel)) { - return false; - } - if (classificationSummary == null) { - if (other.classificationSummary != null) { - return false; - } - } else if (!classificationSummary.equals(other.classificationSummary)) { - return false; - } - if (created == null) { - if (other.created != null) { - return false; - } - } else if (!created.equals(other.created)) { - return false; - } - if (customAttributes == null) { - if (other.customAttributes != null) { - return false; - } - } else if (!customAttributes.equals(other.customAttributes)) { - return false; - } - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (modified == null) { - if (other.modified != null) { - return false; - } - } else if (!modified.equals(other.modified)) { - return false; - } - if (objectReference == null) { - if (other.objectReference != null) { - return false; - } - } else if (!objectReference.equals(other.objectReference)) { - return false; - } - if (received == null) { - if (other.received != null) { - return false; - } - } else if (!received.equals(other.received)) { - return false; - } - if (taskId == null) { - if (other.taskId != null) { - return false; - } - } else if (!taskId.equals(other.taskId)) { - return false; - } - return true; - } - - @Override - public String toString() { - return "AttachmentImpl [id=" + id + ", taskId=" + taskId + ", created=" + created + ", modified=" + modified - + ", classificationSummary=" + classificationSummary + ", objectReference=" + objectReference + ", channel=" - + channel + ", received=" + received + ", customAttributes=" + customAttributes + "]"; + if (taskId == null) { + if (other.taskId != null) { + return false; + } + } else if (!taskId.equals(other.taskId)) { + return false; } + return true; + } + @Override + public String toString() { + return "AttachmentImpl [id=" + + id + + ", taskId=" + + taskId + + ", created=" + + created + + ", modified=" + + modified + + ", classificationSummary=" + + classificationSummary + + ", objectReference=" + + objectReference + + ", channel=" + + channel + + ", received=" + + received + + ", customAttributes=" + + customAttributes + + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/AttachmentSummaryImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/AttachmentSummaryImpl.java index 543b6d25c..256fc1b34 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/AttachmentSummaryImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/AttachmentSummaryImpl.java @@ -6,229 +6,239 @@ import pro.taskana.AttachmentSummary; import pro.taskana.ClassificationSummary; import pro.taskana.ObjectReference; -/** - * The most important fields of the Attachment entity. - */ +/** The most important fields of the Attachment entity. */ public class AttachmentSummaryImpl implements AttachmentSummary { - private String id; - private String taskId; - private Instant created; - private Instant modified; - private ClassificationSummary classificationSummary; - private ObjectReference objectReference; - private String channel; - private Instant received; + private String id; + private String taskId; + private Instant created; + private Instant modified; + private ClassificationSummary classificationSummary; + private ObjectReference objectReference; + private String channel; + private Instant received; - AttachmentSummaryImpl() { + AttachmentSummaryImpl() {} + /* + * (non-Javadoc) + * @see pro.taskana.impl.AttachmentSummary#getId() + */ + @Override + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.AttachmentSummary#getTaskId() + */ + @Override + public String getTaskId() { + return taskId; + } + + public void setTaskId(String taskId) { + this.taskId = taskId; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.AttachmentSummary#getCreated() + */ + @Override + public Instant getCreated() { + return created; + } + + public void setCreated(Instant created) { + this.created = created; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.AttachmentSummary#getModified() + */ + @Override + public Instant getModified() { + return modified; + } + + public void setModified(Instant modified) { + this.modified = modified; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.AttachmentSummary#getClassification() + */ + @Override + public ClassificationSummary getClassificationSummary() { + return classificationSummary; + } + + public void setClassificationSummary(ClassificationSummary classificationSummary) { + this.classificationSummary = classificationSummary; + } + + /* + * (non-Javadoc) + * @see pro.taskana.AttachmentSummary#getObjectReference() + */ + @Override + public ObjectReference getObjectReference() { + return objectReference; + } + + public void setObjectReference(ObjectReference objectReference) { + this.objectReference = objectReference; + } + + /* + * (non-Javadoc) + * @see pro.taskana.AttachmentSummary#getChannel() + */ + @Override + public String getChannel() { + return channel; + } + + public void setChannel(String channel) { + this.channel = channel; + } + + // auxiliary method to enable MyBatis access to classificationSummary + public ClassificationSummaryImpl getClassificationSummaryImpl() { + return (ClassificationSummaryImpl) classificationSummary; + } + + // auxiliary method to enable MyBatis access to classificationSummary + public void setClassificationSummaryImpl(ClassificationSummaryImpl classificationSummary) { + this.classificationSummary = classificationSummary; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.AttachmentSummary#getReceived() + */ + @Override + public Instant getReceived() { + return received; + } + + public void setReceived(Instant received) { + this.received = received; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((channel == null) ? 0 : channel.hashCode()); + result = + prime * result + ((classificationSummary == null) ? 0 : classificationSummary.hashCode()); + result = prime * result + ((created == null) ? 0 : created.hashCode()); + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((modified == null) ? 0 : modified.hashCode()); + result = prime * result + ((objectReference == null) ? 0 : objectReference.hashCode()); + result = prime * result + ((received == null) ? 0 : received.hashCode()); + result = prime * result + ((taskId == null) ? 0 : taskId.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.AttachmentSummary#getId() - */ - @Override - public String getId() { - return id; + if (obj == null) { + return false; } - - public void setId(String id) { - this.id = id; + if (!getClass().isAssignableFrom(obj.getClass())) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.AttachmentSummary#getTaskId() - */ - @Override - public String getTaskId() { - return taskId; + AttachmentSummaryImpl other = (AttachmentSummaryImpl) obj; + if (classificationSummary == null) { + if (other.classificationSummary != null) { + return false; + } + } else if (!classificationSummary.equals(other.classificationSummary)) { + return false; } - - public void setTaskId(String taskId) { - this.taskId = taskId; + if (created == null) { + if (other.created != null) { + return false; + } + } else if (!created.equals(other.created)) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.AttachmentSummary#getCreated() - */ - @Override - public Instant getCreated() { - return created; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; } - - public void setCreated(Instant created) { - this.created = created; + if (modified == null) { + if (other.modified != null) { + return false; + } + } else if (!modified.equals(other.modified)) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.AttachmentSummary#getModified() - */ - @Override - public Instant getModified() { - return modified; + if (received == null) { + if (other.received != null) { + return false; + } + } else if (!received.equals(other.received)) { + return false; } - - public void setModified(Instant modified) { - this.modified = modified; + if (taskId == null) { + if (other.taskId != null) { + return false; + } + } else if (!taskId.equals(other.taskId)) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.AttachmentSummary#getClassification() - */ - @Override - public ClassificationSummary getClassificationSummary() { - return classificationSummary; + if (objectReference == null) { + if (other.objectReference != null) { + return false; + } + } else if (!objectReference.equals(other.objectReference)) { + return false; } - - public void setClassificationSummary(ClassificationSummary classificationSummary) { - this.classificationSummary = classificationSummary; - } - - /* - * (non-Javadoc) - * @see pro.taskana.AttachmentSummary#getObjectReference() - */ - @Override - public ObjectReference getObjectReference() { - return objectReference; - } - - public void setObjectReference(ObjectReference objectReference) { - this.objectReference = objectReference; - } - - /* - * (non-Javadoc) - * @see pro.taskana.AttachmentSummary#getChannel() - */ - @Override - public String getChannel() { - return channel; - } - - public void setChannel(String channel) { - this.channel = channel; - } - - // auxiliary method to enable MyBatis access to classificationSummary - public ClassificationSummaryImpl getClassificationSummaryImpl() { - return (ClassificationSummaryImpl) classificationSummary; - } - - // auxiliary method to enable MyBatis access to classificationSummary - public void setClassificationSummaryImpl(ClassificationSummaryImpl classificationSummary) { - this.classificationSummary = classificationSummary; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.AttachmentSummary#getReceived() - */ - @Override - public Instant getReceived() { - return received; - } - - public void setReceived(Instant received) { - this.received = received; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((channel == null) ? 0 : channel.hashCode()); - result = prime * result + ((classificationSummary == null) ? 0 : classificationSummary.hashCode()); - result = prime * result + ((created == null) ? 0 : created.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((modified == null) ? 0 : modified.hashCode()); - result = prime * result + ((objectReference == null) ? 0 : objectReference.hashCode()); - result = prime * result + ((received == null) ? 0 : received.hashCode()); - result = prime * result + ((taskId == null) ? 0 : taskId.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!getClass().isAssignableFrom(obj.getClass())) { - return false; - } - AttachmentSummaryImpl other = (AttachmentSummaryImpl) obj; - if (classificationSummary == null) { - if (other.classificationSummary != null) { - return false; - } - } else if (!classificationSummary.equals(other.classificationSummary)) { - return false; - } - if (created == null) { - if (other.created != null) { - return false; - } - } else if (!created.equals(other.created)) { - return false; - } - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (modified == null) { - if (other.modified != null) { - return false; - } - } else if (!modified.equals(other.modified)) { - return false; - } - if (received == null) { - if (other.received != null) { - return false; - } - } else if (!received.equals(other.received)) { - return false; - } - if (taskId == null) { - if (other.taskId != null) { - return false; - } - } else if (!taskId.equals(other.taskId)) { - return false; - } - if (objectReference == null) { - if (other.objectReference != null) { - return false; - } - } else if (!objectReference.equals(other.objectReference)) { - return false; - } - if (channel == null) { - if (other.channel != null) { - return false; - } - } else if (!channel.equals(other.channel)) { - return false; - } - return true; - } - - @Override - public String toString() { - return "AttachmentSummaryImpl [id=" + id + ", taskId=" + taskId + ", created=" + created + ", modified=" - + modified + ", classificationSummary=" + classificationSummary + ", objectReference=" + objectReference - + ", channel=" + channel + ", received=" + received + "]"; + if (channel == null) { + if (other.channel != null) { + return false; + } + } else if (!channel.equals(other.channel)) { + return false; } + return true; + } + @Override + public String toString() { + return "AttachmentSummaryImpl [id=" + + id + + ", taskId=" + + taskId + + ", created=" + + created + + ", modified=" + + modified + + ", classificationSummary=" + + classificationSummary + + ", objectReference=" + + objectReference + + ", channel=" + + channel + + ", received=" + + received + + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/CategoryReportBuilderImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/CategoryReportBuilderImpl.java index caa6dadd9..ecf80bbb3 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/CategoryReportBuilderImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/CategoryReportBuilderImpl.java @@ -1,7 +1,6 @@ package pro.taskana.impl; import java.util.List; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -14,46 +13,52 @@ import pro.taskana.impl.report.preprocessor.DaysToWorkingDaysPreProcessor; import pro.taskana.mappings.TaskMonitorMapper; import pro.taskana.report.CategoryReport; -/** - * The implementation of CategoryReportBuilder. - */ +/** The implementation of CategoryReportBuilder. */ public class CategoryReportBuilderImpl - extends TimeIntervalReportBuilderImpl + extends TimeIntervalReportBuilderImpl< + CategoryReport.Builder, MonitorQueryItem, TimeIntervalColumnHeader> implements CategoryReport.Builder { - private static final Logger LOGGER = LoggerFactory.getLogger(CategoryReport.Builder.class); + private static final Logger LOGGER = LoggerFactory.getLogger(CategoryReport.Builder.class); - CategoryReportBuilderImpl(InternalTaskanaEngine taskanaEngine, TaskMonitorMapper taskMonitorMapper) { - super(taskanaEngine, taskMonitorMapper); - } + CategoryReportBuilderImpl( + InternalTaskanaEngine taskanaEngine, TaskMonitorMapper taskMonitorMapper) { + super(taskanaEngine, taskMonitorMapper); + } - @Override - protected CategoryReport.Builder _this() { - return this; + @Override + public CategoryReport buildReport() throws InvalidArgumentException, NotAuthorizedException { + LOGGER.debug("entry to buildReport(), this = {}", this); + this.taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.MONITOR); + try { + this.taskanaEngine.openConnection(); + CategoryReport report = new CategoryReport(this.columnHeaders); + List monitorQueryItems = + this.taskMonitorMapper.getTaskCountOfCategories( + this.workbasketIds, + this.states, + this.categories, + this.domains, + this.classificationIds, + this.excludedClassificationIds, + this.customAttributeFilter); + report.addItems( + monitorQueryItems, + new DaysToWorkingDaysPreProcessor<>(this.columnHeaders, this.inWorkingDays)); + return report; + } finally { + this.taskanaEngine.returnConnection(); + LOGGER.debug("exit from buildReport()."); } + } - @Override - protected String determineGroupedBy() { - return "CLASSIFICATION_CATEGORY"; - } + @Override + protected CategoryReport.Builder _this() { + return this; + } - @Override - public CategoryReport buildReport() throws InvalidArgumentException, NotAuthorizedException { - LOGGER.debug("entry to buildReport(), this = {}", this); - this.taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.MONITOR); - try { - this.taskanaEngine.openConnection(); - CategoryReport report = new CategoryReport(this.columnHeaders); - List monitorQueryItems = this.taskMonitorMapper.getTaskCountOfCategories( - this.workbasketIds, - this.states, this.categories, this.domains, this.classificationIds, this.excludedClassificationIds, - this.customAttributeFilter); - report.addItems(monitorQueryItems, - new DaysToWorkingDaysPreProcessor<>(this.columnHeaders, this.inWorkingDays)); - return report; - } finally { - this.taskanaEngine.returnConnection(); - LOGGER.debug("exit from buildReport()."); - } - } + @Override + protected String determineGroupedBy() { + return "CLASSIFICATION_CATEGORY"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/ClassificationImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/ClassificationImpl.java index cf1557bbd..ccb74c5ec 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/ClassificationImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/ClassificationImpl.java @@ -6,164 +6,202 @@ import java.util.Objects; import pro.taskana.Classification; import pro.taskana.ClassificationSummary; -/** - * Classification entity. - */ +/** Classification entity. */ public class ClassificationImpl extends ClassificationSummaryImpl implements Classification { - private Boolean isValidInDomain; - private Instant created; - private Instant modified; - private String description; - private String applicationEntryPoint; + private Boolean isValidInDomain; + private Instant created; + private Instant modified; + private String description; + private String applicationEntryPoint; - ClassificationImpl() { + ClassificationImpl() {} + + ClassificationImpl(ClassificationImpl classification) { + this.id = classification.getId(); + this.key = classification.getKey(); + this.parentId = classification.getParentId(); + this.parentKey = classification.getParentKey(); + this.category = classification.getCategory(); + this.type = classification.getType(); + this.domain = classification.getDomain(); + this.isValidInDomain = classification.getIsValidInDomain(); + this.created = classification.getCreated(); + this.modified = classification.getModified(); + this.name = classification.getName(); + this.description = classification.getDescription(); + this.priority = classification.getPriority(); + this.serviceLevel = classification.getServiceLevel(); + this.applicationEntryPoint = classification.getApplicationEntryPoint(); + this.custom1 = classification.getCustom1(); + this.custom2 = classification.getCustom2(); + this.custom3 = classification.getCustom3(); + this.custom4 = classification.getCustom4(); + this.custom5 = classification.getCustom5(); + this.custom6 = classification.getCustom6(); + this.custom7 = classification.getCustom7(); + this.custom8 = classification.getCustom8(); + } + + @Override + public Boolean getIsValidInDomain() { + return isValidInDomain; + } + + @Override + public void setIsValidInDomain(Boolean isValidInDomain) { + this.isValidInDomain = isValidInDomain; + } + + @Override + public Instant getCreated() { + return created; + } + + public void setCreated(Instant created) { + this.created = created; + } + + @Override + public Instant getModified() { + return modified; + } + + public void setModified(Instant modified) { + this.modified = modified; + } + + @Override + public String getDescription() { + return description; + } + + @Override + public void setDescription(String description) { + this.description = description; + } + + @Override + public String getApplicationEntryPoint() { + return applicationEntryPoint; + } + + @Override + public void setApplicationEntryPoint(String applicationEntryPoint) { + this.applicationEntryPoint = applicationEntryPoint; + } + + @Override + public ClassificationSummary asSummary() { + ClassificationSummaryImpl summary = new ClassificationSummaryImpl(); + summary.setCategory(this.category); + summary.setDomain(this.domain); + summary.setId(this.id); + summary.setKey(this.key); + summary.setName(this.name); + summary.setType(this.type); + summary.setParentId(this.parentId); + summary.setParentKey(this.parentKey); + summary.setPriority(this.priority); + summary.setServiceLevel(this.serviceLevel); + summary.setCustom1(custom1); + summary.setCustom2(custom2); + summary.setCustom3(custom3); + summary.setCustom4(custom4); + summary.setCustom5(custom5); + summary.setCustom6(custom6); + summary.setCustom7(custom7); + summary.setCustom8(custom8); + return summary; + } + + protected boolean canEqual(Object other) { + return (other instanceof ClassificationImpl); + } + + @Override + public int hashCode() { + return Objects.hash( + super.hashCode(), isValidInDomain, created, modified, description, applicationEntryPoint); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null) { + return false; } - ClassificationImpl(ClassificationImpl classification) { - this.id = classification.getId(); - this.key = classification.getKey(); - this.parentId = classification.getParentId(); - this.parentKey = classification.getParentKey(); - this.category = classification.getCategory(); - this.type = classification.getType(); - this.domain = classification.getDomain(); - this.isValidInDomain = classification.getIsValidInDomain(); - this.created = classification.getCreated(); - this.modified = classification.getModified(); - this.name = classification.getName(); - this.description = classification.getDescription(); - this.priority = classification.getPriority(); - this.serviceLevel = classification.getServiceLevel(); - this.applicationEntryPoint = classification.getApplicationEntryPoint(); - this.custom1 = classification.getCustom1(); - this.custom2 = classification.getCustom2(); - this.custom3 = classification.getCustom3(); - this.custom4 = classification.getCustom4(); - this.custom5 = classification.getCustom5(); - this.custom6 = classification.getCustom6(); - this.custom7 = classification.getCustom7(); - this.custom8 = classification.getCustom8(); + if (!getClass().isAssignableFrom(o.getClass())) { + return false; } - @Override - public Boolean getIsValidInDomain() { - return isValidInDomain; + if (!super.equals(o)) { + return false; + } + ClassificationImpl that = (ClassificationImpl) o; + + if (!that.canEqual(this)) { + return false; } - @Override - public void setIsValidInDomain(Boolean isValidInDomain) { - this.isValidInDomain = isValidInDomain; - } + return Objects.equals(isValidInDomain, that.isValidInDomain) + && Objects.equals(created, that.created) + && Objects.equals(modified, that.modified) + && Objects.equals(description, that.description) + && Objects.equals(applicationEntryPoint, that.applicationEntryPoint); + } - @Override - public Instant getCreated() { - return created; - } - - public void setCreated(Instant created) { - this.created = created; - } - - @Override - public Instant getModified() { - return modified; - } - - public void setModified(Instant modified) { - this.modified = modified; - } - - @Override - public String getDescription() { - return description; - } - - @Override - public void setDescription(String description) { - this.description = description; - } - - @Override - public String getApplicationEntryPoint() { - return applicationEntryPoint; - } - - @Override - public void setApplicationEntryPoint(String applicationEntryPoint) { - this.applicationEntryPoint = applicationEntryPoint; - } - - @Override - public ClassificationSummary asSummary() { - ClassificationSummaryImpl summary = new ClassificationSummaryImpl(); - summary.setCategory(this.category); - summary.setDomain(this.domain); - summary.setId(this.id); - summary.setKey(this.key); - summary.setName(this.name); - summary.setType(this.type); - summary.setParentId(this.parentId); - summary.setParentKey(this.parentKey); - summary.setPriority(this.priority); - summary.setServiceLevel(this.serviceLevel); - summary.setCustom1(custom1); - summary.setCustom2(custom2); - summary.setCustom3(custom3); - summary.setCustom4(custom4); - summary.setCustom5(custom5); - summary.setCustom6(custom6); - summary.setCustom7(custom7); - summary.setCustom8(custom8); - return summary; - } - - @Override - public String toString() { - return "ClassificationImpl [id=" + id + ", key=" + key + ", parentId=" + parentId + ", parentKey=" + parentKey - + ", category=" + category + ", type=" + type + ", domain=" + domain + ", isValidInDomain=" - + isValidInDomain + ", created=" + created + ", modified=" + modified + ", name=" + name + ", description=" - + description + ", priority=" + priority + ", serviceLevel=" + serviceLevel + ", applicationEntryPoint=" - + applicationEntryPoint + ", custom1=" + custom1 + ", custom2=" + custom2 + ", custom3=" + custom3 - + ", custom4=" + custom4 + ", custom5=" + custom5 + ", custom6=" + custom6 + ", custom7=" + custom7 - + ", custom8=" + custom8 + "]"; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null) { - return false; - } - - if (!getClass().isAssignableFrom(o.getClass())) { - return false; - } - - if (!super.equals(o)) { - return false; - } - ClassificationImpl that = (ClassificationImpl) o; - - if (!that.canEqual(this)) { - return false; - } - - return Objects.equals(isValidInDomain, that.isValidInDomain) - && Objects.equals(created, that.created) - && Objects.equals(modified, that.modified) - && Objects.equals(description, that.description) - && Objects.equals(applicationEntryPoint, that.applicationEntryPoint); - } - - protected boolean canEqual(Object other) { - return (other instanceof ClassificationImpl); - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), isValidInDomain, created, modified, description, applicationEntryPoint); - } + @Override + public String toString() { + return "ClassificationImpl [id=" + + id + + ", key=" + + key + + ", parentId=" + + parentId + + ", parentKey=" + + parentKey + + ", category=" + + category + + ", type=" + + type + + ", domain=" + + domain + + ", isValidInDomain=" + + isValidInDomain + + ", created=" + + created + + ", modified=" + + modified + + ", name=" + + name + + ", description=" + + description + + ", priority=" + + priority + + ", serviceLevel=" + + serviceLevel + + ", applicationEntryPoint=" + + applicationEntryPoint + + ", custom1=" + + custom1 + + ", custom2=" + + custom2 + + ", custom3=" + + custom3 + + ", custom4=" + + custom4 + + ", custom5=" + + custom5 + + ", custom6=" + + custom6 + + ", custom7=" + + custom7 + + ", custom8=" + + custom8 + + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/ClassificationQueryImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/ClassificationQueryImpl.java index f23211358..55699f909 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/ClassificationQueryImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/ClassificationQueryImpl.java @@ -3,7 +3,6 @@ package pro.taskana.impl; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import org.apache.ibatis.exceptions.PersistenceException; import org.apache.ibatis.session.RowBounds; import org.slf4j.Logger; @@ -24,620 +23,698 @@ import pro.taskana.impl.util.LoggerUtils; */ public class ClassificationQueryImpl implements ClassificationQuery { - private static final String LINK_TO_SUMMARYMAPPER = "pro.taskana.mappings.QueryMapper.queryClassificationSummaries"; - private static final String LINK_TO_COUNTER = "pro.taskana.mappings.QueryMapper.countQueryClassifications"; - private static final String LINK_TO_VALUEMAPPER = "pro.taskana.mappings.QueryMapper.queryClassificationColumnValues"; - private static final Logger LOGGER = LoggerFactory.getLogger(ClassificationQueryImpl.class); - private InternalTaskanaEngine taskanaEngine; - private ClassificationQueryColumnName columnName; - private String[] key; - private String[] idIn; - private String[] parentId; - private String[] parentKey; - private String[] category; - private String[] type; - private String[] domain; - private Boolean validInDomain; - private TimeInterval[] createdIn; - private TimeInterval[] modifiedIn; - private String[] nameIn; - private String[] nameLike; - private String descriptionLike; - private int[] priority; - private String[] serviceLevelIn; - private String[] serviceLevelLike; - private String[] applicationEntryPointIn; - private String[] applicationEntryPointLike; - private String[] custom1In; - private String[] custom1Like; - private String[] custom2In; - private String[] custom2Like; - private String[] custom3In; - private String[] custom3Like; - private String[] custom4In; - private String[] custom4Like; - private String[] custom5In; - private String[] custom5Like; - private String[] custom6In; - private String[] custom6Like; - private String[] custom7In; - private String[] custom7Like; - private String[] custom8In; - private String[] custom8Like; - private List orderBy; - private List orderColumns; + private static final String LINK_TO_SUMMARYMAPPER = + "pro.taskana.mappings.QueryMapper.queryClassificationSummaries"; + private static final String LINK_TO_COUNTER = + "pro.taskana.mappings.QueryMapper.countQueryClassifications"; + private static final String LINK_TO_VALUEMAPPER = + "pro.taskana.mappings.QueryMapper.queryClassificationColumnValues"; + private static final Logger LOGGER = LoggerFactory.getLogger(ClassificationQueryImpl.class); + private InternalTaskanaEngine taskanaEngine; + private ClassificationQueryColumnName columnName; + private String[] key; + private String[] idIn; + private String[] parentId; + private String[] parentKey; + private String[] category; + private String[] type; + private String[] domain; + private Boolean validInDomain; + private TimeInterval[] createdIn; + private TimeInterval[] modifiedIn; + private String[] nameIn; + private String[] nameLike; + private String descriptionLike; + private int[] priority; + private String[] serviceLevelIn; + private String[] serviceLevelLike; + private String[] applicationEntryPointIn; + private String[] applicationEntryPointLike; + private String[] custom1In; + private String[] custom1Like; + private String[] custom2In; + private String[] custom2Like; + private String[] custom3In; + private String[] custom3Like; + private String[] custom4In; + private String[] custom4Like; + private String[] custom5In; + private String[] custom5Like; + private String[] custom6In; + private String[] custom6Like; + private String[] custom7In; + private String[] custom7Like; + private String[] custom8In; + private String[] custom8Like; + private List orderBy; + private List orderColumns; - ClassificationQueryImpl(InternalTaskanaEngine taskanaEngine) { - this.taskanaEngine = taskanaEngine; - this.orderBy = new ArrayList<>(); - this.orderColumns = new ArrayList<>(); + ClassificationQueryImpl(InternalTaskanaEngine taskanaEngine) { + this.taskanaEngine = taskanaEngine; + this.orderBy = new ArrayList<>(); + this.orderColumns = new ArrayList<>(); + } + + @Override + public ClassificationQuery keyIn(String... key) { + this.key = key; + return this; + } + + @Override + public ClassificationQuery idIn(String... id) { + this.idIn = id; + return this; + } + + @Override + public ClassificationQuery parentIdIn(String... parentId) { + this.parentId = parentId; + return this; + } + + @Override + public ClassificationQuery parentKeyIn(String... parentKey) { + this.parentKey = parentKey; + return this; + } + + @Override + public ClassificationQuery categoryIn(String... category) { + this.category = category; + return this; + } + + @Override + public ClassificationQuery typeIn(String... type) { + this.type = type; + return this; + } + + @Override + public ClassificationQuery domainIn(String... domain) { + this.domain = domain; + return this; + } + + @Override + public ClassificationQuery validInDomainEquals(Boolean validInDomain) { + this.validInDomain = validInDomain; + return this; + } + + @Override + public ClassificationQuery createdWithin(TimeInterval... createdIn) { + this.createdIn = createdIn; + for (TimeInterval ti : createdIn) { + if (!ti.isValid()) { + throw new IllegalArgumentException("TimeInterval " + ti + " is invalid."); + } + } + return this; + } + + @Override + public ClassificationQuery modifiedWithin(TimeInterval... modifiedIn) { + this.modifiedIn = modifiedIn; + for (TimeInterval ti : modifiedIn) { + if (!ti.isValid()) { + throw new IllegalArgumentException("TimeInterval " + ti + " is invalid."); + } + } + return this; + } + + @Override + public ClassificationQuery nameIn(String... nameIn) { + this.nameIn = nameIn; + return this; + } + + @Override + public ClassificationQuery nameLike(String... nameLike) { + this.nameLike = toUpperCopy(nameLike); + return this; + } + + @Override + public ClassificationQuery descriptionLike(String description) { + this.descriptionLike = description.toUpperCase(); + return this; + } + + @Override + public ClassificationQuery priorityIn(int... priorities) { + this.priority = priorities; + return this; + } + + @Override + public ClassificationQuery serviceLevelIn(String... serviceLevelIn) { + this.serviceLevelIn = serviceLevelIn; + return this; + } + + @Override + public ClassificationQuery serviceLevelLike(String... serviceLevelLike) { + this.serviceLevelLike = toUpperCopy(serviceLevelLike); + return this; + } + + @Override + public ClassificationQuery applicationEntryPointIn(String... applicationEntryPointIn) { + this.applicationEntryPointIn = applicationEntryPointIn; + return this; + } + + @Override + public ClassificationQuery applicationEntryPointLike(String... applicationEntryPointLike) { + this.applicationEntryPointLike = toUpperCopy(applicationEntryPointLike); + return this; + } + + @Override + public ClassificationQuery customAttributeIn(String number, String... customIn) + throws InvalidArgumentException { + int num = 0; + try { + num = Integer.parseInt(number); + } catch (NumberFormatException e) { + throw new InvalidArgumentException( + "Argument '" + + number + + "' to getCustomAttribute cannot be converted to a number between 1 and 8", + e.getCause()); + } + if (customIn.length == 0) { + throw new InvalidArgumentException( + "At least one string has to be provided as a search parameter"); } - @Override - public ClassificationQuery keyIn(String... key) { - this.key = key; - return this; + switch (num) { + case 1: + this.custom1In = customIn; + break; + case 2: + this.custom2In = customIn; + break; + case 3: + this.custom3In = customIn; + break; + case 4: + this.custom4In = customIn; + break; + case 5: + this.custom5In = customIn; + break; + case 6: + this.custom6In = customIn; + break; + case 7: + this.custom7In = customIn; + break; + case 8: + this.custom8In = customIn; + break; + default: + throw new InvalidArgumentException( + "Argument '" + + number + + "' to getCustomAttribute does not represent a number between 1 and 8"); } - @Override - public ClassificationQuery idIn(String... id) { - this.idIn = id; - return this; + return this; + } + + @Override + public ClassificationQuery customAttributeLike(String number, String... customLike) + throws InvalidArgumentException { + int num = 0; + try { + num = Integer.parseInt(number); + } catch (NumberFormatException e) { + throw new InvalidArgumentException( + "Argument '" + + number + + "' to getCustomAttribute cannot be converted to a number between 1 and 16", + e.getCause()); + } + if (customLike.length == 0) { + throw new InvalidArgumentException( + "At least one string has to be provided as a search parameter"); } - @Override - public ClassificationQuery parentIdIn(String... parentId) { - this.parentId = parentId; - return this; + switch (num) { + case 1: + this.custom1Like = toUpperCopy(customLike); + break; + case 2: + this.custom2Like = toUpperCopy(customLike); + break; + case 3: + this.custom3Like = toUpperCopy(customLike); + break; + case 4: + this.custom4Like = toUpperCopy(customLike); + break; + case 5: + this.custom5Like = toUpperCopy(customLike); + break; + case 6: + this.custom6Like = toUpperCopy(customLike); + break; + case 7: + this.custom7Like = toUpperCopy(customLike); + break; + case 8: + this.custom8Like = toUpperCopy(customLike); + break; + default: + throw new InvalidArgumentException( + "Argument '" + + number + + "' to getCustomAttribute does not represent a number between 1 and 16"); } - @Override - public ClassificationQuery parentKeyIn(String... parentKey) { - this.parentKey = parentKey; - return this; + return this; + } + + @Override + public ClassificationQuery orderByKey(SortDirection sortDirection) { + return addOrderCriteria("KEY", sortDirection); + } + + @Override + public ClassificationQuery orderByParentId(SortDirection sortDirection) { + return addOrderCriteria("PARENT_ID", sortDirection); + } + + @Override + public ClassificationQuery orderByParentKey(SortDirection sortDirection) { + return addOrderCriteria("PARENT_KEY", sortDirection); + } + + @Override + public ClassificationQuery orderByCategory(SortDirection sortDirection) { + return addOrderCriteria("CATEGORY", sortDirection); + } + + @Override + public ClassificationQuery orderByDomain(SortDirection sortDirection) { + return addOrderCriteria("DOMAIN", sortDirection); + } + + @Override + public ClassificationQuery orderByPriority(SortDirection sortDirection) { + return addOrderCriteria("PRIORITY", sortDirection); + } + + @Override + public ClassificationQuery orderByName(SortDirection sortDirection) { + return addOrderCriteria("NAME", sortDirection); + } + + @Override + public ClassificationQuery orderByServiceLevel(SortDirection sortDirection) { + return addOrderCriteria("SERVICE_LEVEL", sortDirection); + } + + @Override + public ClassificationQuery orderByApplicationEntryPoint(SortDirection sortDirection) { + return addOrderCriteria("APPLICATION_ENTRY_POINT", sortDirection); + } + + @Override + public ClassificationQuery orderByCustomAttribute(String number, SortDirection sortDirection) + throws InvalidArgumentException { + int num = 0; + try { + num = Integer.parseInt(number); + } catch (NumberFormatException e) { + throw new InvalidArgumentException( + "Argument '" + + number + + "' to getCustomAttribute cannot be converted to a number between 1 and 16", + e.getCause()); } - @Override - public ClassificationQuery categoryIn(String... category) { - this.category = category; - return this; + switch (num) { + case 1: + return addOrderCriteria("CUSTOM_1", sortDirection); + case 2: + return addOrderCriteria("CUSTOM_2", sortDirection); + case 3: + return addOrderCriteria("CUSTOM_3", sortDirection); + case 4: + return addOrderCriteria("CUSTOM_4", sortDirection); + case 5: + return addOrderCriteria("CUSTOM_5", sortDirection); + case 6: + return addOrderCriteria("CUSTOM_6", sortDirection); + case 7: + return addOrderCriteria("CUSTOM_7", sortDirection); + case 8: + return addOrderCriteria("CUSTOM_8", sortDirection); + default: + throw new InvalidArgumentException( + "Argument '" + + number + + "' to getCustomAttribute does not represent a number between 1 and 16"); } + } - @Override - public ClassificationQuery typeIn(String... type) { - this.type = type; - return this; + @Override + public List list() { + LOGGER.debug("entry to list(), this = {}", this); + List result = new ArrayList<>(); + try { + taskanaEngine.openConnection(); + result = taskanaEngine.getSqlSession().selectList(LINK_TO_SUMMARYMAPPER, this); + return result; + } finally { + taskanaEngine.returnConnection(); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "exit from list(). Returning {} resulting Objects: {} ", + result.size(), + LoggerUtils.listToString(result)); + } } + } - @Override - public ClassificationQuery domainIn(String... domain) { - this.domain = domain; - return this; - } - - @Override - public ClassificationQuery validInDomainEquals(Boolean validInDomain) { - this.validInDomain = validInDomain; - return this; - } - - @Override - public ClassificationQuery createdWithin(TimeInterval... createdIn) { - this.createdIn = createdIn; - for (TimeInterval ti : createdIn) { - if (!ti.isValid()) { - throw new IllegalArgumentException("TimeInterval " + ti + " is invalid."); - } + @Override + public List list(int offset, int limit) { + LOGGER.debug("entry to list(offset = {}, limit = {}), this = {}", offset, limit, this); + List result = new ArrayList<>(); + try { + taskanaEngine.openConnection(); + RowBounds rowBounds = new RowBounds(offset, limit); + result = taskanaEngine.getSqlSession().selectList(LINK_TO_SUMMARYMAPPER, this, rowBounds); + return result; + } catch (Exception e) { + if (e instanceof PersistenceException) { + if (e.getMessage().contains("ERRORCODE=-4470")) { + TaskanaRuntimeException ex = + new TaskanaRuntimeException( + "The offset beginning was set over the amount of result-rows.", e.getCause()); + ex.setStackTrace(e.getStackTrace()); + throw ex; } - return this; - } - - @Override - public ClassificationQuery modifiedWithin(TimeInterval... modifiedIn) { - this.modifiedIn = modifiedIn; - for (TimeInterval ti : modifiedIn) { - if (!ti.isValid()) { - throw new IllegalArgumentException("TimeInterval " + ti + " is invalid."); - } - } - return this; - } - - @Override - public ClassificationQuery nameIn(String... nameIn) { - this.nameIn = nameIn; - return this; - } - - @Override - public ClassificationQuery nameLike(String... nameLike) { - this.nameLike = toUpperCopy(nameLike); - return this; - } - - @Override - public ClassificationQuery descriptionLike(String description) { - this.descriptionLike = description.toUpperCase(); - return this; - } - - @Override - public ClassificationQuery priorityIn(int... priorities) { - this.priority = priorities; - return this; - } - - @Override - public ClassificationQuery serviceLevelIn(String... serviceLevelIn) { - this.serviceLevelIn = serviceLevelIn; - return this; - } - - @Override - public ClassificationQuery serviceLevelLike(String... serviceLevelLike) { - this.serviceLevelLike = toUpperCopy(serviceLevelLike); - return this; - } - - @Override - public ClassificationQuery applicationEntryPointIn(String... applicationEntryPointIn) { - this.applicationEntryPointIn = applicationEntryPointIn; - return this; - } - - @Override - public ClassificationQuery applicationEntryPointLike(String... applicationEntryPointLike) { - this.applicationEntryPointLike = toUpperCopy(applicationEntryPointLike); - return this; - } - - @Override - public ClassificationQuery customAttributeIn(String number, String... customIn) throws InvalidArgumentException { - int num = 0; - try { - num = Integer.parseInt(number); - } catch (NumberFormatException e) { - throw new InvalidArgumentException( - "Argument '" + number + "' to getCustomAttribute cannot be converted to a number between 1 and 8", - e.getCause()); - } - if (customIn.length == 0) { - throw new InvalidArgumentException( - "At least one string has to be provided as a search parameter"); - } - - switch (num) { - case 1: - this.custom1In = customIn; - break; - case 2: - this.custom2In = customIn; - break; - case 3: - this.custom3In = customIn; - break; - case 4: - this.custom4In = customIn; - break; - case 5: - this.custom5In = customIn; - break; - case 6: - this.custom6In = customIn; - break; - case 7: - this.custom7In = customIn; - break; - case 8: - this.custom8In = customIn; - break; - default: - throw new InvalidArgumentException( - "Argument '" + number + "' to getCustomAttribute does not represent a number between 1 and 8"); - } - - return this; - } - - @Override - public ClassificationQuery customAttributeLike(String number, String... customLike) - throws InvalidArgumentException { - int num = 0; - try { - num = Integer.parseInt(number); - } catch (NumberFormatException e) { - throw new InvalidArgumentException( - "Argument '" + number + "' to getCustomAttribute cannot be converted to a number between 1 and 16", - e.getCause()); - } - if (customLike.length == 0) { - throw new InvalidArgumentException( - "At least one string has to be provided as a search parameter"); - } - - switch (num) { - case 1: - this.custom1Like = toUpperCopy(customLike); - break; - case 2: - this.custom2Like = toUpperCopy(customLike); - break; - case 3: - this.custom3Like = toUpperCopy(customLike); - break; - case 4: - this.custom4Like = toUpperCopy(customLike); - break; - case 5: - this.custom5Like = toUpperCopy(customLike); - break; - case 6: - this.custom6Like = toUpperCopy(customLike); - break; - case 7: - this.custom7Like = toUpperCopy(customLike); - break; - case 8: - this.custom8Like = toUpperCopy(customLike); - break; - default: - throw new InvalidArgumentException( - "Argument '" + number + "' to getCustomAttribute does not represent a number between 1 and 16"); - } - - return this; - } - - @Override - public ClassificationQuery orderByKey(SortDirection sortDirection) { - return addOrderCriteria("KEY", sortDirection); - } - - @Override - public ClassificationQuery orderByParentId(SortDirection sortDirection) { - return addOrderCriteria("PARENT_ID", sortDirection); - } - - @Override - public ClassificationQuery orderByParentKey(SortDirection sortDirection) { - return addOrderCriteria("PARENT_KEY", sortDirection); - } - - @Override - public ClassificationQuery orderByCategory(SortDirection sortDirection) { - return addOrderCriteria("CATEGORY", sortDirection); - } - - @Override - public ClassificationQuery orderByDomain(SortDirection sortDirection) { - return addOrderCriteria("DOMAIN", sortDirection); - } - - @Override - public ClassificationQuery orderByPriority(SortDirection sortDirection) { - return addOrderCriteria("PRIORITY", sortDirection); - } - - @Override - public ClassificationQuery orderByName(SortDirection sortDirection) { - return addOrderCriteria("NAME", sortDirection); - } - - @Override - public ClassificationQuery orderByServiceLevel(SortDirection sortDirection) { - return addOrderCriteria("SERVICE_LEVEL", sortDirection); - } - - @Override - public ClassificationQuery orderByApplicationEntryPoint(SortDirection sortDirection) { - return addOrderCriteria("APPLICATION_ENTRY_POINT", sortDirection); - } - - @Override - public ClassificationQuery orderByCustomAttribute(String number, SortDirection sortDirection) - throws InvalidArgumentException { - int num = 0; - try { - num = Integer.parseInt(number); - } catch (NumberFormatException e) { - throw new InvalidArgumentException( - "Argument '" + number + "' to getCustomAttribute cannot be converted to a number between 1 and 16", - e.getCause()); - } - - switch (num) { - case 1: - return addOrderCriteria("CUSTOM_1", sortDirection); - case 2: - return addOrderCriteria("CUSTOM_2", sortDirection); - case 3: - return addOrderCriteria("CUSTOM_3", sortDirection); - case 4: - return addOrderCriteria("CUSTOM_4", sortDirection); - case 5: - return addOrderCriteria("CUSTOM_5", sortDirection); - case 6: - return addOrderCriteria("CUSTOM_6", sortDirection); - case 7: - return addOrderCriteria("CUSTOM_7", sortDirection); - case 8: - return addOrderCriteria("CUSTOM_8", sortDirection); - default: - throw new InvalidArgumentException( - "Argument '" + number + "' to getCustomAttribute does not represent a number between 1 and 16"); - } - } - - @Override - public List list() { - LOGGER.debug("entry to list(), this = {}", this); - List result = new ArrayList<>(); - try { - taskanaEngine.openConnection(); - result = taskanaEngine.getSqlSession().selectList(LINK_TO_SUMMARYMAPPER, this); - return result; - } finally { - taskanaEngine.returnConnection(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("exit from list(). Returning {} resulting Objects: {} ", result.size(), - LoggerUtils.listToString(result)); - } - } - } - - @Override - public List list(int offset, int limit) { - LOGGER.debug("entry to list(offset = {}, limit = {}), this = {}", offset, limit, this); - List result = new ArrayList<>(); - try { - taskanaEngine.openConnection(); - RowBounds rowBounds = new RowBounds(offset, limit); - result = taskanaEngine.getSqlSession().selectList(LINK_TO_SUMMARYMAPPER, this, rowBounds); - return result; - } catch (Exception e) { - if (e instanceof PersistenceException) { - if (e.getMessage().contains("ERRORCODE=-4470")) { - TaskanaRuntimeException ex = new TaskanaRuntimeException( - "The offset beginning was set over the amount of result-rows.", e.getCause()); - ex.setStackTrace(e.getStackTrace()); - throw ex; - } - } - throw e; - } finally { - taskanaEngine.returnConnection(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("exit from list(offset,limit). Returning {} resulting Objects: {} ", result.size(), - LoggerUtils.listToString(result)); - } - } - } - - @Override - public List listValues(ClassificationQueryColumnName columnName, SortDirection sortDirection) { - LOGGER.debug("Entry to listValues(dbColumnName={}) this = {}", columnName, this); - List result = new ArrayList<>(); - try { - taskanaEngine.openConnection(); - this.columnName = columnName; - this.orderBy.clear(); - this.addOrderCriteria(columnName.toString(), sortDirection); - result = taskanaEngine.getSqlSession().selectList(LINK_TO_VALUEMAPPER, this); - return result; - } finally { - taskanaEngine.returnConnection(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from listValues. Returning {} resulting Objects: {} ", result.size(), - LoggerUtils.listToString(result)); - } - } - } - - @Override - public ClassificationSummary single() { - LOGGER.debug("entry to single(), this = {}", this); - ClassificationSummary result = null; - try { - taskanaEngine.openConnection(); - result = taskanaEngine.getSqlSession().selectOne(LINK_TO_SUMMARYMAPPER, this); - return result; - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from single(). Returning result {} ", result); - } - } - - @Override - public long count() { - LOGGER.debug("entry to count(), this = {}", this); - Long rowCount = null; - try { - taskanaEngine.openConnection(); - rowCount = taskanaEngine.getSqlSession().selectOne(LINK_TO_COUNTER, this); - return (rowCount == null) ? 0L : rowCount; - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from count(). Returning result {} ", rowCount); - } - } - - private ClassificationQuery addOrderCriteria(String columnName, SortDirection sortDirection) { - String orderByDirection = " " + (sortDirection == null ? SortDirection.ASCENDING : sortDirection); - orderBy.add(columnName.toString() + orderByDirection); - orderColumns.add(columnName.toString()); - return this; - } - - public String[] getKey() { - return key; - } - - public String[] getIdIn() { - return idIn; - } - - public String[] getparentId() { - return parentId; - } - - public String[] getparentKey() { - return parentKey; - } - - public String[] getCategory() { - return category; - } - - public String[] getType() { - return type; - } - - public String[] getNameIn() { - return nameIn; - } - - public String[] getNameLike() { - return nameLike; - } - - public String getDescriptionLike() { - return descriptionLike; - } - - public int[] getPriority() { - return priority; - } - - public String[] getServiceLevelIn() { - return serviceLevelIn; - } - - public String[] getServiceLevelLike() { - return serviceLevelLike; - } - - public String[] getDomain() { - return domain; - } - - public Boolean getValidInDomain() { - return validInDomain; - } - - public TimeInterval[] getCreatedIn() { - return createdIn; - } - - public TimeInterval[] getModifiedIn() { - return modifiedIn; - } - - public String[] getApplicationEntryPointIn() { - return applicationEntryPointIn; - } - - public String[] getApplicationEntryPointLike() { - return applicationEntryPointLike; - } - - public String[] getCustom1In() { - return custom1In; - } - - public String[] getCustom1Like() { - return custom1Like; - } - - public String[] getCustom2In() { - return custom2In; - } - - public String[] getCustom2Like() { - return custom2Like; - } - - public String[] getCustom3In() { - return custom3In; - } - - public String[] getCustom3Like() { - return custom3Like; - } - - public String[] getCustom4In() { - return custom4In; - } - - public String[] getCustom4Like() { - return custom4Like; - } - - public String[] getCustom5In() { - return custom5In; - } - - public String[] getCustom5Like() { - return custom5Like; - } - - public String[] getCustom6In() { - return custom6In; - } - - public String[] getCustom6Like() { - return custom6Like; - } - - public String[] getCustom7In() { - return custom7In; - } - - public String[] getCustom7Like() { - return custom7Like; - } - - public String[] getCustom8In() { - return custom8In; - } - - public String[] getCustom8Like() { - return custom8Like; - } - - public ClassificationQueryColumnName getColumnName() { - return columnName; - } - - public List getOrderBy() { - return orderBy; - } - - public List getOrderColumns() { - return orderColumns; - } - - @Override - public String toString() { - return "ClassificationQueryImpl [" + "columnName= " + this.columnName + ", key= " + Arrays.toString(this.key) - + ", idIn= " + Arrays.toString(this.idIn) + ", parentId= " + Arrays.toString(this.parentId) - + ", parentKey= " + Arrays.toString(this.parentKey) + ", category= " + Arrays.toString(this.category) - + ", type= " + Arrays.toString(this.type) + ", domain= " + Arrays.toString(this.domain) - + ", validInDomain= " + this.validInDomain + ", createdIn= " + Arrays.toString(this.createdIn) - + ", modifiedIn= " + Arrays.toString(this.modifiedIn) + ", nameIn= " + Arrays.toString(this.nameIn) - + ", nameLike= " + Arrays.toString(this.nameLike) + ", descriptionLike= " + this.descriptionLike - + ", priority= " + Arrays.toString(this.priority) + ", serviceLevelIn= " - + Arrays.toString(this.serviceLevelIn) + ", serviceLevelLike= " + Arrays.toString(this.serviceLevelLike) - + ", applicationEntryPointIn= " + Arrays.toString(this.applicationEntryPointIn) - + ", applicationEntryPointLike= " + Arrays.toString(this.applicationEntryPointLike) + ", custom1In= " - + Arrays.toString(this.custom1In) + ", custom1Like= " + Arrays.toString(this.custom1Like) + ", custom2In= " - + Arrays.toString(this.custom2In) + ", custom2Like= " + Arrays.toString(this.custom2Like) + ", custom3In= " - + Arrays.toString(this.custom3In) + ", custom3Like= " + Arrays.toString(this.custom3Like) + ", custom4In= " - + Arrays.toString(this.custom4In) + ", custom4Like= " + Arrays.toString(this.custom4Like) + ", custom5In= " - + Arrays.toString(this.custom5In) + ", custom5Like= " + Arrays.toString(this.custom5Like) + ", custom6In= " - + Arrays.toString(this.custom6In) + ", custom6Like= " + Arrays.toString(this.custom6Like) + ", custom7In= " - + Arrays.toString(this.custom7In) + ", custom7Like= " + Arrays.toString(this.custom7Like) + ", custom8In= " - + Arrays.toString(this.custom8In) + ", custom8Like= " + Arrays.toString(this.custom8Like) + ", orderBy= " - + this.orderBy + "]"; - } - + } + throw e; + } finally { + taskanaEngine.returnConnection(); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "exit from list(offset,limit). Returning {} resulting Objects: {} ", + result.size(), + LoggerUtils.listToString(result)); + } + } + } + + @Override + public List listValues( + ClassificationQueryColumnName columnName, SortDirection sortDirection) { + LOGGER.debug("Entry to listValues(dbColumnName={}) this = {}", columnName, this); + List result = new ArrayList<>(); + try { + taskanaEngine.openConnection(); + this.columnName = columnName; + this.orderBy.clear(); + this.addOrderCriteria(columnName.toString(), sortDirection); + result = taskanaEngine.getSqlSession().selectList(LINK_TO_VALUEMAPPER, this); + return result; + } finally { + taskanaEngine.returnConnection(); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "Exit from listValues. Returning {} resulting Objects: {} ", + result.size(), + LoggerUtils.listToString(result)); + } + } + } + + @Override + public ClassificationSummary single() { + LOGGER.debug("entry to single(), this = {}", this); + ClassificationSummary result = null; + try { + taskanaEngine.openConnection(); + result = taskanaEngine.getSqlSession().selectOne(LINK_TO_SUMMARYMAPPER, this); + return result; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from single(). Returning result {} ", result); + } + } + + @Override + public long count() { + LOGGER.debug("entry to count(), this = {}", this); + Long rowCount = null; + try { + taskanaEngine.openConnection(); + rowCount = taskanaEngine.getSqlSession().selectOne(LINK_TO_COUNTER, this); + return (rowCount == null) ? 0L : rowCount; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from count(). Returning result {} ", rowCount); + } + } + + public String[] getKey() { + return key; + } + + public String[] getIdIn() { + return idIn; + } + + public String[] getparentId() { + return parentId; + } + + public String[] getparentKey() { + return parentKey; + } + + public String[] getCategory() { + return category; + } + + public String[] getType() { + return type; + } + + public String[] getNameIn() { + return nameIn; + } + + public String[] getNameLike() { + return nameLike; + } + + public String getDescriptionLike() { + return descriptionLike; + } + + public int[] getPriority() { + return priority; + } + + public String[] getServiceLevelIn() { + return serviceLevelIn; + } + + public String[] getServiceLevelLike() { + return serviceLevelLike; + } + + public String[] getDomain() { + return domain; + } + + public Boolean getValidInDomain() { + return validInDomain; + } + + public TimeInterval[] getCreatedIn() { + return createdIn; + } + + public TimeInterval[] getModifiedIn() { + return modifiedIn; + } + + public String[] getApplicationEntryPointIn() { + return applicationEntryPointIn; + } + + public String[] getApplicationEntryPointLike() { + return applicationEntryPointLike; + } + + public String[] getCustom1In() { + return custom1In; + } + + public String[] getCustom1Like() { + return custom1Like; + } + + public String[] getCustom2In() { + return custom2In; + } + + public String[] getCustom2Like() { + return custom2Like; + } + + public String[] getCustom3In() { + return custom3In; + } + + public String[] getCustom3Like() { + return custom3Like; + } + + public String[] getCustom4In() { + return custom4In; + } + + public String[] getCustom4Like() { + return custom4Like; + } + + public String[] getCustom5In() { + return custom5In; + } + + public String[] getCustom5Like() { + return custom5Like; + } + + public String[] getCustom6In() { + return custom6In; + } + + public String[] getCustom6Like() { + return custom6Like; + } + + public String[] getCustom7In() { + return custom7In; + } + + public String[] getCustom7Like() { + return custom7Like; + } + + public String[] getCustom8In() { + return custom8In; + } + + public String[] getCustom8Like() { + return custom8Like; + } + + public ClassificationQueryColumnName getColumnName() { + return columnName; + } + + public List getOrderBy() { + return orderBy; + } + + public List getOrderColumns() { + return orderColumns; + } + + private ClassificationQuery addOrderCriteria(String columnName, SortDirection sortDirection) { + String orderByDirection = + " " + (sortDirection == null ? SortDirection.ASCENDING : sortDirection); + orderBy.add(columnName.toString() + orderByDirection); + orderColumns.add(columnName.toString()); + return this; + } + + @Override + public String toString() { + return "ClassificationQueryImpl [" + + "columnName= " + + this.columnName + + ", key= " + + Arrays.toString(this.key) + + ", idIn= " + + Arrays.toString(this.idIn) + + ", parentId= " + + Arrays.toString(this.parentId) + + ", parentKey= " + + Arrays.toString(this.parentKey) + + ", category= " + + Arrays.toString(this.category) + + ", type= " + + Arrays.toString(this.type) + + ", domain= " + + Arrays.toString(this.domain) + + ", validInDomain= " + + this.validInDomain + + ", createdIn= " + + Arrays.toString(this.createdIn) + + ", modifiedIn= " + + Arrays.toString(this.modifiedIn) + + ", nameIn= " + + Arrays.toString(this.nameIn) + + ", nameLike= " + + Arrays.toString(this.nameLike) + + ", descriptionLike= " + + this.descriptionLike + + ", priority= " + + Arrays.toString(this.priority) + + ", serviceLevelIn= " + + Arrays.toString(this.serviceLevelIn) + + ", serviceLevelLike= " + + Arrays.toString(this.serviceLevelLike) + + ", applicationEntryPointIn= " + + Arrays.toString(this.applicationEntryPointIn) + + ", applicationEntryPointLike= " + + Arrays.toString(this.applicationEntryPointLike) + + ", custom1In= " + + Arrays.toString(this.custom1In) + + ", custom1Like= " + + Arrays.toString(this.custom1Like) + + ", custom2In= " + + Arrays.toString(this.custom2In) + + ", custom2Like= " + + Arrays.toString(this.custom2Like) + + ", custom3In= " + + Arrays.toString(this.custom3In) + + ", custom3Like= " + + Arrays.toString(this.custom3Like) + + ", custom4In= " + + Arrays.toString(this.custom4In) + + ", custom4Like= " + + Arrays.toString(this.custom4Like) + + ", custom5In= " + + Arrays.toString(this.custom5In) + + ", custom5Like= " + + Arrays.toString(this.custom5Like) + + ", custom6In= " + + Arrays.toString(this.custom6In) + + ", custom6Like= " + + Arrays.toString(this.custom6Like) + + ", custom7In= " + + Arrays.toString(this.custom7In) + + ", custom7Like= " + + Arrays.toString(this.custom7Like) + + ", custom8In= " + + Arrays.toString(this.custom8In) + + ", custom8Like= " + + Arrays.toString(this.custom8Like) + + ", orderBy= " + + this.orderBy + + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/ClassificationReportBuilderImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/ClassificationReportBuilderImpl.java index c1424514d..6b7108ae0 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/ClassificationReportBuilderImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/ClassificationReportBuilderImpl.java @@ -1,7 +1,6 @@ package pro.taskana.impl; import java.util.List; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -16,66 +15,82 @@ import pro.taskana.mappings.TaskMonitorMapper; import pro.taskana.report.ClassificationReport; import pro.taskana.report.ClassificationReport.DetailedClassificationReport; -/** - * The implementation of ClassificationReportBuilder. - */ +/** The implementation of ClassificationReportBuilder. */ public class ClassificationReportBuilderImpl - extends TimeIntervalReportBuilderImpl + extends TimeIntervalReportBuilderImpl< + ClassificationReport.Builder, MonitorQueryItem, TimeIntervalColumnHeader> implements ClassificationReport.Builder { - private static final Logger LOGGER = LoggerFactory.getLogger(ClassificationReport.Builder.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ClassificationReport.Builder.class); - ClassificationReportBuilderImpl(InternalTaskanaEngine taskanaEngine, TaskMonitorMapper taskMonitorMapper) { - super(taskanaEngine, taskMonitorMapper); + ClassificationReportBuilderImpl( + InternalTaskanaEngine taskanaEngine, TaskMonitorMapper taskMonitorMapper) { + super(taskanaEngine, taskMonitorMapper); + } + + @Override + public ClassificationReport buildReport() + throws InvalidArgumentException, NotAuthorizedException { + LOGGER.debug("entry to buildReport(), this = {}", this); + this.taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.MONITOR, TaskanaRole.ADMIN); + try { + this.taskanaEngine.openConnection(); + ClassificationReport report = new ClassificationReport(this.columnHeaders); + List monitorQueryItems = + this.taskMonitorMapper.getTaskCountOfClassifications( + this.workbasketIds, + this.states, + this.categories, + this.domains, + this.classificationIds, + this.excludedClassificationIds, + this.customAttributeFilter); + report.addItems( + monitorQueryItems, + new DaysToWorkingDaysPreProcessor<>(this.columnHeaders, this.inWorkingDays)); + return report; + } finally { + this.taskanaEngine.returnConnection(); + LOGGER.debug("exit from buildReport()."); } + } - @Override - protected ClassificationReport.Builder _this() { - return this; + @Override + public DetailedClassificationReport buildDetailedReport() + throws InvalidArgumentException, NotAuthorizedException { + LOGGER.debug("entry to buildDetailedReport(), this = {}", this); + this.taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.MONITOR, TaskanaRole.ADMIN); + try { + this.taskanaEngine.openConnection(); + DetailedClassificationReport report = new DetailedClassificationReport(this.columnHeaders); + List detailedMonitorQueryItems = + this.taskMonitorMapper.getTaskCountOfDetailedClassifications( + this.workbasketIds, + this.states, + this.categories, + this.domains, + this.classificationIds, + this.excludedClassificationIds, + this.customAttributeFilter); + + report.addItems( + detailedMonitorQueryItems, + new DaysToWorkingDaysPreProcessor<>(this.columnHeaders, this.inWorkingDays)); + + return report; + } finally { + this.taskanaEngine.returnConnection(); + LOGGER.debug("exit from buildDetailedReport()."); } + } - @Override - protected String determineGroupedBy() { - return "CLASSIFICATION_KEY"; - } + @Override + protected ClassificationReport.Builder _this() { + return this; + } - @Override - public ClassificationReport buildReport() throws InvalidArgumentException, NotAuthorizedException { - LOGGER.debug("entry to buildReport(), this = {}", this); - this.taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.MONITOR, TaskanaRole.ADMIN); - try { - this.taskanaEngine.openConnection(); - ClassificationReport report = new ClassificationReport(this.columnHeaders); - List monitorQueryItems = this.taskMonitorMapper.getTaskCountOfClassifications( - this.workbasketIds, this.states, this.categories, this.domains, this.classificationIds, - this.excludedClassificationIds, this.customAttributeFilter); - report.addItems(monitorQueryItems, - new DaysToWorkingDaysPreProcessor<>(this.columnHeaders, this.inWorkingDays)); - return report; - } finally { - this.taskanaEngine.returnConnection(); - LOGGER.debug("exit from buildReport()."); - } - } - - @Override - public DetailedClassificationReport buildDetailedReport() throws InvalidArgumentException, NotAuthorizedException { - LOGGER.debug("entry to buildDetailedReport(), this = {}", this); - this.taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.MONITOR, TaskanaRole.ADMIN); - try { - this.taskanaEngine.openConnection(); - DetailedClassificationReport report = new DetailedClassificationReport(this.columnHeaders); - List detailedMonitorQueryItems = this.taskMonitorMapper - .getTaskCountOfDetailedClassifications(this.workbasketIds, this.states, this.categories, this.domains, - this.classificationIds, this.excludedClassificationIds, this.customAttributeFilter); - - report.addItems(detailedMonitorQueryItems, - new DaysToWorkingDaysPreProcessor<>(this.columnHeaders, this.inWorkingDays)); - - return report; - } finally { - this.taskanaEngine.returnConnection(); - LOGGER.debug("exit from buildDetailedReport()."); - } - } + @Override + protected String determineGroupedBy() { + return "CLASSIFICATION_KEY"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/ClassificationServiceImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/ClassificationServiceImpl.java index d6ed3239d..6dddebb74 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/ClassificationServiceImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/ClassificationServiceImpl.java @@ -9,7 +9,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; - import org.apache.ibatis.exceptions.PersistenceException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -33,488 +32,528 @@ import pro.taskana.jobs.ScheduledJob; import pro.taskana.mappings.ClassificationMapper; import pro.taskana.mappings.TaskMapper; -/** - * This is the implementation of ClassificationService. - */ +/** This is the implementation of ClassificationService. */ public class ClassificationServiceImpl implements ClassificationService { - private static final String ID_PREFIX_CLASSIFICATION = "CLI"; - private static final Logger LOGGER = LoggerFactory.getLogger(ClassificationServiceImpl.class); - private ClassificationMapper classificationMapper; - private TaskMapper taskMapper; - private InternalTaskanaEngine taskanaEngine; + private static final String ID_PREFIX_CLASSIFICATION = "CLI"; + private static final Logger LOGGER = LoggerFactory.getLogger(ClassificationServiceImpl.class); + private ClassificationMapper classificationMapper; + private TaskMapper taskMapper; + private InternalTaskanaEngine taskanaEngine; - ClassificationServiceImpl(InternalTaskanaEngine taskanaEngine, ClassificationMapper classificationMapper, - TaskMapper taskMapper) { - this.taskanaEngine = taskanaEngine; - this.classificationMapper = classificationMapper; - this.taskMapper = taskMapper; + ClassificationServiceImpl( + InternalTaskanaEngine taskanaEngine, + ClassificationMapper classificationMapper, + TaskMapper taskMapper) { + this.taskanaEngine = taskanaEngine; + this.classificationMapper = classificationMapper; + this.taskMapper = taskMapper; + } + + @Override + public Classification createClassification(Classification classification) + throws ClassificationAlreadyExistException, NotAuthorizedException, DomainNotFoundException, + InvalidArgumentException { + LOGGER.debug("entry to createClassification(classification = {})", classification); + taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); + if (!taskanaEngine.domainExists(classification.getDomain()) + && !"".equals(classification.getDomain())) { + throw new DomainNotFoundException( + classification.getDomain(), + "Domain " + classification.getDomain() + " does not exist in the configuration."); + } + ClassificationImpl classificationImpl; + final boolean isClassificationExisting; + try { + taskanaEngine.openConnection(); + isClassificationExisting = + doesClassificationExist(classification.getKey(), classification.getDomain()); + if (isClassificationExisting) { + throw new ClassificationAlreadyExistException(classification); + } + classificationImpl = (ClassificationImpl) classification; + this.checkClassificationId(classificationImpl); + classificationImpl.setCreated(Instant.now()); + classificationImpl.setModified(classificationImpl.getCreated()); + this.initDefaultClassificationValues(classificationImpl); + + validateAndPopulateParentInformation(classificationImpl); + + classificationMapper.insert(classificationImpl); + LOGGER.debug("Method createClassification created classification {}.", classificationImpl); + + if (!classification.getDomain().isEmpty()) { + addClassificationToMasterDomain(classificationImpl); + } + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from createClassification()"); + } + return classificationImpl; + } + + @Override + public Classification updateClassification(Classification classification) + throws NotAuthorizedException, ConcurrencyException, ClassificationNotFoundException, + InvalidArgumentException { + LOGGER.debug("entry to updateClassification(Classification = {})", classification); + taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); + ClassificationImpl classificationImpl = null; + try { + taskanaEngine.openConnection(); + if (classification.getKey().equals(classification.getParentKey())) { + throw new InvalidArgumentException( + "The classification " + classification.getName() + " has the same key and parentKey"); + } + + classificationImpl = (ClassificationImpl) classification; + Classification oldClassification = + this.getExistingClassificationAndVerifyTimestampHasNotChanged(classificationImpl); + classificationImpl.setModified(Instant.now()); + this.initDefaultClassificationValues(classificationImpl); + + if (!Objects.equals(oldClassification.getCategory(), classificationImpl.getCategory())) { + this.updateCategoryOnAssociatedTasks(classificationImpl, oldClassification); + } + + this.checkExistenceOfParentClassification(oldClassification, classificationImpl); + classificationMapper.update(classificationImpl); + this.createJobIfPriorityOrServiceLevelHasChanged(oldClassification, classificationImpl); + + LOGGER.debug( + "Method updateClassification() updated the classification {}.", classificationImpl); + return classification; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from updateClassification()."); + } + } + + @Override + public Classification getClassification(String id) throws ClassificationNotFoundException { + if (id == null) { + throw new ClassificationNotFoundException(null, "Classification for null id is invalid."); + } + LOGGER.debug("entry to getClassification(id = {})", id); + Classification result = null; + try { + taskanaEngine.openConnection(); + result = classificationMapper.findById(id); + if (result == null) { + throw new ClassificationNotFoundException( + id, "Classification for id " + id + " was not found"); + } + return result; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from getClassification(). Returning result {} ", result); + } + } + + @Override + public Classification getClassification(String key, String domain) + throws ClassificationNotFoundException { + LOGGER.debug("entry to getClassification(key = {}, domain = {})", key, domain); + if (key == null) { + throw new ClassificationNotFoundException( + null, domain, "Classification for null key and domain " + domain + " was not found."); } - private static void validateServiceLevel(String serviceLevel) throws InvalidArgumentException { - try { - Duration.parse(serviceLevel); - - } catch (Exception e) { - throw new InvalidArgumentException("Invalid service level " + serviceLevel - + ". The formats accepted are based on the ISO-8601 duration format PnDTnHnMn.nS with days considered to be exactly 24 hours. " - + "For example: \"P2D\" represents a period of \"two days.\" ", - e.getCause()); + Classification result = null; + try { + taskanaEngine.openConnection(); + result = classificationMapper.findByKeyAndDomain(key, domain); + if (result == null) { + result = classificationMapper.findByKeyAndDomain(key, ""); + if (result == null) { + throw new ClassificationNotFoundException( + key, domain, "Classification for key = " + key + " and master domain was not found"); } - // check that the duration is based on format PnD, i.e. it must start with a P, end with a D - String serviceLevelLower = serviceLevel.toLowerCase(); - if (!('p' == serviceLevelLower.charAt(0)) - || !('d' == serviceLevelLower.charAt(serviceLevel.length() - 1))) { + } + return result; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from getClassification(). Returning result {} ", result); + } + } + @Override + public ClassificationQuery createClassificationQuery() { + return new ClassificationQueryImpl(taskanaEngine); + } + + @Override + public Classification newClassification(String key, String domain, String type) { + ClassificationImpl classification = new ClassificationImpl(); + classification.setKey(key); + classification.setDomain(domain); + classification.setType(type); + return classification; + } + + @Override + public void deleteClassification(String classificationKey, String domain) + throws ClassificationInUseException, ClassificationNotFoundException, NotAuthorizedException { + LOGGER.debug("entry to deleteClassification(key = {}, domain = {})", classificationKey, domain); + taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); + try { + taskanaEngine.openConnection(); + Classification classification = + this.classificationMapper.findByKeyAndDomain(classificationKey, domain); + if (classification == null) { + throw new ClassificationNotFoundException( + classificationKey, + domain, + "The classification \"" + + classificationKey + + "\" wasn't found in the domain " + + domain); + } + deleteClassification(classification.getId()); + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from deleteClassification(key,domain)"); + } + } + + @Override + public void deleteClassification(String classificationId) + throws ClassificationInUseException, ClassificationNotFoundException, NotAuthorizedException { + LOGGER.debug("entry to deleteClassification(id = {})", classificationId); + taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); + try { + taskanaEngine.openConnection(); + Classification classification = this.classificationMapper.findById(classificationId); + if (classification == null) { + throw new ClassificationNotFoundException( + classificationId, "The classification \"" + classificationId + "\" wasn't found"); + } + + if (classification.getDomain().equals("")) { + // master mode - delete all associated classifications in every domain. + List classificationsInDomain = + createClassificationQuery().keyIn(classification.getKey()).list(); + for (ClassificationSummary classificationInDomain : classificationsInDomain) { + if (!"".equals(classificationInDomain.getDomain())) { + deleteClassification(classificationInDomain.getId()); + } + } + } + + List childClassifications = + createClassificationQuery().parentIdIn(classificationId).list(); + for (ClassificationSummary child : childClassifications) { + this.deleteClassification(child.getId()); + } + + try { + this.classificationMapper.deleteClassification(classificationId); + } catch (PersistenceException e) { + if (isReferentialIntegrityConstraintViolation(e)) { + throw new ClassificationInUseException( + "The classification id = \"" + + classificationId + + "\" and key = \"" + + classification.getKey() + + "\" in domain = \"" + + classification.getDomain() + + "\" is in use and cannot be deleted. There are either tasks or attachments associated with the classification.", + e.getCause()); + } + } + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from deleteClassification()"); + } + } + + private static void validateServiceLevel(String serviceLevel) throws InvalidArgumentException { + try { + Duration.parse(serviceLevel); + + } catch (Exception e) { + throw new InvalidArgumentException( + "Invalid service level " + + serviceLevel + + ". The formats accepted are based on the ISO-8601 duration format PnDTnHnMn.nS with days considered to be exactly 24 hours. " + + "For example: \"P2D\" represents a period of \"two days.\" ", + e.getCause()); + } + // check that the duration is based on format PnD, i.e. it must start with a P, end with a D + String serviceLevelLower = serviceLevel.toLowerCase(); + if (!('p' == serviceLevelLower.charAt(0)) + || !('d' == serviceLevelLower.charAt(serviceLevel.length() - 1))) { + + throw new InvalidArgumentException( + "Invalid service level " + + serviceLevel + + ". Taskana only supports service levels that" + + " contain a number of whole days specified according to the format 'PnD' where n is the number of days"); + } + } + + private void validateAndPopulateParentInformation(ClassificationImpl classificationImpl) + throws InvalidArgumentException { + try { + + if (classificationImpl.getParentId() != null && !classificationImpl.getParentId().isEmpty()) { + Classification parentClassification = + this.getClassification(classificationImpl.getParentId()); + if (classificationImpl.getParentKey() != null + && !classificationImpl.getParentKey().isEmpty()) { + if (!classificationImpl.getParentKey().equals(parentClassification.getKey())) { throw new InvalidArgumentException( - "Invalid service level " + serviceLevel + ". Taskana only supports service levels that" - + " contain a number of whole days specified according to the format 'PnD' where n is the number of days"); + "Given parent key of classification does not match key of parent id."); + } + classificationImpl.setParentKey(parentClassification.getKey()); } + } + + if (classificationImpl.getParentKey() != null + && !classificationImpl.getParentKey().isEmpty()) { + Classification parentClassification = + this.getClassification( + classificationImpl.getParentKey(), classificationImpl.getDomain()); + classificationImpl.setParentId(parentClassification.getId()); + } + + } catch (ClassificationNotFoundException e) { + throw new InvalidArgumentException("Parent classification could not be found.", e); + } + } + + private void checkClassificationId(ClassificationImpl classificationImpl) + throws InvalidArgumentException { + if (classificationImpl.getId() != null && !"".equals(classificationImpl.getId())) { + throw new InvalidArgumentException("ClassificationId should be null on creation"); + } + } + + private void addClassificationToMasterDomain(ClassificationImpl classificationImpl) { + if (!Objects.equals(classificationImpl.getDomain(), "")) { + boolean doesExist = true; + ClassificationImpl masterClassification = new ClassificationImpl(classificationImpl); + masterClassification.setId(IdGenerator.generateWithPrefix(ID_PREFIX_CLASSIFICATION)); + masterClassification.setParentKey(classificationImpl.getParentKey()); + masterClassification.setDomain(""); + masterClassification.setIsValidInDomain(false); + try { + if (classificationImpl.getParentKey() != null + && !"".equals(classificationImpl.getParentKey())) { + masterClassification.setParentId( + getClassification(classificationImpl.getParentKey(), "").getId()); + } + this.getClassification(masterClassification.getKey(), masterClassification.getDomain()); + throw new ClassificationAlreadyExistException(masterClassification); + } catch (ClassificationNotFoundException e) { + doesExist = false; + LOGGER.debug( + "Method createClassification: Classification does not exist in master domain. Classification {}.", + masterClassification); + } catch (ClassificationAlreadyExistException ex) { + LOGGER.warn( + "Method createClassification: Classification does already exist in master domain. Classification {}.", + masterClassification); + } finally { + if (!doesExist) { + classificationMapper.insert(masterClassification); + LOGGER.debug( + "Method createClassification: Classification created in master-domain, too. Classification {}.", + masterClassification); + } + } + } + } + + /** + * Fill missing values and validate classification before saving the classification. + * + * @param classification the classification which will be verified. + * @throws InvalidArgumentException if the given classification has no key. + */ + private void initDefaultClassificationValues(ClassificationImpl classification) + throws InvalidArgumentException { + Instant now = Instant.now(); + if (classification.getId() == null || "".equals(classification.getId())) { + classification.setId(IdGenerator.generateWithPrefix(ID_PREFIX_CLASSIFICATION)); } - @Override - public Classification createClassification(Classification classification) - throws ClassificationAlreadyExistException, NotAuthorizedException, - DomainNotFoundException, InvalidArgumentException { - LOGGER.debug("entry to createClassification(classification = {})", classification); - taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); - if (!taskanaEngine.domainExists(classification.getDomain()) && !"".equals(classification.getDomain())) { - throw new DomainNotFoundException(classification.getDomain(), - "Domain " + classification.getDomain() + " does not exist in the configuration."); - } - ClassificationImpl classificationImpl; - final boolean isClassificationExisting; - try { - taskanaEngine.openConnection(); - isClassificationExisting = doesClassificationExist(classification.getKey(), classification.getDomain()); - if (isClassificationExisting) { - throw new ClassificationAlreadyExistException(classification); - } - classificationImpl = (ClassificationImpl) classification; - this.checkClassificationId(classificationImpl); - classificationImpl.setCreated(Instant.now()); - classificationImpl.setModified(classificationImpl.getCreated()); - this.initDefaultClassificationValues(classificationImpl); - - validateAndPopulateParentInformation(classificationImpl); - - classificationMapper.insert(classificationImpl); - LOGGER.debug("Method createClassification created classification {}.", classificationImpl); - - if (!classification.getDomain().isEmpty()) { - addClassificationToMasterDomain(classificationImpl); - } - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from createClassification()"); - } - return classificationImpl; + if (classification.getCreated() == null) { + classification.setCreated(now); } - private void validateAndPopulateParentInformation(ClassificationImpl classificationImpl) - throws InvalidArgumentException { - try { - - if (classificationImpl.getParentId() != null && !classificationImpl.getParentId().isEmpty()) { - Classification parentClassification = this.getClassification(classificationImpl.getParentId()); - if (classificationImpl.getParentKey() != null && !classificationImpl.getParentKey().isEmpty()) { - if (!classificationImpl.getParentKey().equals(parentClassification.getKey())) { - throw new InvalidArgumentException( - "Given parent key of classification does not match key of parent id."); - } - classificationImpl.setParentKey(parentClassification.getKey()); - } - } - - if (classificationImpl.getParentKey() != null && !classificationImpl.getParentKey().isEmpty()) { - Classification parentClassification = this.getClassification(classificationImpl.getParentKey(), - classificationImpl.getDomain()); - classificationImpl.setParentId(parentClassification.getId()); - } - - } catch (ClassificationNotFoundException e) { - throw new InvalidArgumentException("Parent classification could not be found.", e); - } + if (classification.getModified() == null) { + classification.setModified(now); } - private void checkClassificationId(ClassificationImpl classificationImpl) throws InvalidArgumentException { - if (classificationImpl.getId() != null && !"".equals(classificationImpl.getId())) { - throw new InvalidArgumentException("ClassificationId should be null on creation"); - } + if (classification.getIsValidInDomain() == null) { + classification.setIsValidInDomain(true); } - private void addClassificationToMasterDomain(ClassificationImpl classificationImpl) { - if (!Objects.equals(classificationImpl.getDomain(), "")) { - boolean doesExist = true; - ClassificationImpl masterClassification = new ClassificationImpl(classificationImpl); - masterClassification.setId(IdGenerator.generateWithPrefix(ID_PREFIX_CLASSIFICATION)); - masterClassification.setParentKey(classificationImpl.getParentKey()); - masterClassification.setDomain(""); - masterClassification.setIsValidInDomain(false); - try { - if (classificationImpl.getParentKey() != null && !"".equals(classificationImpl.getParentKey())) { - masterClassification.setParentId(getClassification(classificationImpl.getParentKey(), "").getId()); - } - this.getClassification(masterClassification.getKey(), masterClassification.getDomain()); - throw new ClassificationAlreadyExistException(masterClassification); - } catch (ClassificationNotFoundException e) { - doesExist = false; - LOGGER.debug( - "Method createClassification: Classification does not exist in master domain. Classification {}.", - masterClassification); - } catch (ClassificationAlreadyExistException ex) { - LOGGER.warn( - "Method createClassification: Classification does already exist in master domain. Classification {}.", - masterClassification); - } finally { - if (!doesExist) { - classificationMapper.insert(masterClassification); - LOGGER.debug( - "Method createClassification: Classification created in master-domain, too. Classification {}.", - masterClassification); - } - } - } + if (classification.getServiceLevel() != null && !"".equals(classification.getServiceLevel())) { + validateServiceLevel(classification.getServiceLevel()); } - @Override - public Classification updateClassification(Classification classification) - throws NotAuthorizedException, ConcurrencyException, ClassificationNotFoundException, InvalidArgumentException { - LOGGER.debug("entry to updateClassification(Classification = {})", classification); - taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); - ClassificationImpl classificationImpl = null; - try { - taskanaEngine.openConnection(); - if (classification.getKey().equals(classification.getParentKey())) { - throw new InvalidArgumentException( - "The classification " + classification.getName() + " has the same key and parentKey"); - } - - classificationImpl = (ClassificationImpl) classification; - Classification oldClassification = this.getExistingClassificationAndVerifyTimestampHasNotChanged( - classificationImpl); - classificationImpl.setModified(Instant.now()); - this.initDefaultClassificationValues(classificationImpl); - - if (!Objects.equals(oldClassification.getCategory(), classificationImpl.getCategory())) { - this.updateCategoryOnAssociatedTasks(classificationImpl, oldClassification); - } - - this.checkExistenceOfParentClassification(oldClassification, classificationImpl); - classificationMapper.update(classificationImpl); - this.createJobIfPriorityOrServiceLevelHasChanged(oldClassification, classificationImpl); - - LOGGER.debug("Method updateClassification() updated the classification {}.", classificationImpl); - return classification; - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from updateClassification()."); - } + if (classification.getKey() == null) { + throw new InvalidArgumentException("Classification must contain a key"); } - /** - * Fill missing values and validate classification before saving the classification. - * - * @param classification the classification which will be verified. - * - * @throws InvalidArgumentException if the given classification has no key. - */ - private void initDefaultClassificationValues(ClassificationImpl classification) throws InvalidArgumentException { - Instant now = Instant.now(); - if (classification.getId() == null || "".equals(classification.getId())) { - classification.setId(IdGenerator.generateWithPrefix(ID_PREFIX_CLASSIFICATION)); - } + if (classification.getParentId() == null) { + classification.setParentId(""); + } - if (classification.getCreated() == null) { - classification.setCreated(now); - } + if (classification.getParentKey() == null) { + classification.setParentKey(""); + } - if (classification.getModified() == null) { - classification.setModified(now); - } + if (classification.getType() != null + && !taskanaEngine + .getEngine() + .getConfiguration() + .getClassificationTypes() + .contains(classification.getType())) { + throw new InvalidArgumentException( + "Given classification type " + + classification.getType() + + " is not valid according to the configuration."); + } - if (classification.getIsValidInDomain() == null) { - classification.setIsValidInDomain(true); - } - - if (classification.getServiceLevel() != null && !"".equals(classification.getServiceLevel())) { - validateServiceLevel(classification.getServiceLevel()); - } - - if (classification.getKey() == null) { - throw new InvalidArgumentException("Classification must contain a key"); - } - - if (classification.getParentId() == null) { - classification.setParentId(""); - } - - if (classification.getParentKey() == null) { - classification.setParentKey(""); - } - - if (classification.getType() != null - && !taskanaEngine.getEngine().getConfiguration().getClassificationTypes().contains(classification.getType())) { - throw new InvalidArgumentException("Given classification type " + classification.getType() - + " is not valid according to the configuration."); - } - - if (classification.getCategory() != null - && !taskanaEngine.getEngine().getConfiguration() + if (classification.getCategory() != null + && !taskanaEngine + .getEngine() + .getConfiguration() .getClassificationCategoriesByType(classification.getType()) .contains(classification.getCategory())) { - throw new InvalidArgumentException( - "Given classification category " + classification.getCategory() + " with type " - + classification.getType() - + " is not valid according to the configuration."); - } - - if (classification.getDomain().isEmpty()) { - classification.setIsValidInDomain(false); - } + throw new InvalidArgumentException( + "Given classification category " + + classification.getCategory() + + " with type " + + classification.getType() + + " is not valid according to the configuration."); } - @Override - public Classification getClassification(String id) throws ClassificationNotFoundException { - if (id == null) { - throw new ClassificationNotFoundException(null, - "Classification for null id is invalid."); - } - LOGGER.debug("entry to getClassification(id = {})", id); - Classification result = null; - try { - taskanaEngine.openConnection(); - result = classificationMapper.findById(id); - if (result == null) { - throw new ClassificationNotFoundException(id, "Classification for id " + id + " was not found"); - } - return result; - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from getClassification(). Returning result {} ", result); - } + if (classification.getDomain().isEmpty()) { + classification.setIsValidInDomain(false); } + } - @Override - public Classification getClassification(String key, String domain) throws ClassificationNotFoundException { - LOGGER.debug("entry to getClassification(key = {}, domain = {})", key, domain); - if (key == null) { - throw new ClassificationNotFoundException(null, domain, - "Classification for null key and domain " + domain + " was not found."); - } - - Classification result = null; - try { - taskanaEngine.openConnection(); - result = classificationMapper.findByKeyAndDomain(key, domain); - if (result == null) { - result = classificationMapper.findByKeyAndDomain(key, ""); - if (result == null) { - throw new ClassificationNotFoundException(key, domain, - "Classification for key = " + key + " and master domain was not found"); - } - } - return result; - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from getClassification(). Returning result {} ", result); - } + private boolean doesClassificationExist(String key, String domain) { + boolean isExisting = false; + try { + if (classificationMapper.findByKeyAndDomain(key, domain) != null) { + isExisting = true; + } + } catch (Exception ex) { + LOGGER.warn( + "Classification-Service threw Exception while calling mapper and searching for classification. EX={}", + ex, + ex); } + return isExisting; + } - @Override - public ClassificationQuery createClassificationQuery() { - return new ClassificationQueryImpl(taskanaEngine); + private boolean isReferentialIntegrityConstraintViolation(PersistenceException e) { + return isH2OrPostgresIntegrityConstraintViolation(e) || isDb2IntegrityConstraintViolation(e); + } + + private boolean isDb2IntegrityConstraintViolation(PersistenceException e) { + return e.getCause() instanceof SQLIntegrityConstraintViolationException + && e.getMessage().contains("-532"); + } + + private boolean isH2OrPostgresIntegrityConstraintViolation(PersistenceException e) { + return e.getCause() instanceof SQLException + && ((SQLException) e.getCause()).getSQLState().equals("23503"); + } + + /** + * Check if current object is based on the newest (by modified). + * + * @param classificationImpl the classification + * @return the old classification + * @throws ConcurrencyException if the classification has been modified by some other process. + * @throws ClassificationNotFoundException if the given classification does not exist. + */ + private Classification getExistingClassificationAndVerifyTimestampHasNotChanged( + ClassificationImpl classificationImpl) + throws ConcurrencyException, ClassificationNotFoundException { + Classification oldClassification = + this.getClassification(classificationImpl.getKey(), classificationImpl.getDomain()); + if (!oldClassification.getModified().equals(classificationImpl.getModified())) { + throw new ConcurrencyException( + "The current Classification has been modified while editing. The values can not be updated. Classification " + + classificationImpl.toString()); } + return oldClassification; + } - @Override - public Classification newClassification(String key, String domain, String type) { - ClassificationImpl classification = new ClassificationImpl(); - classification.setKey(key); - classification.setDomain(domain); - classification.setType(type); - return classification; - } - - private boolean doesClassificationExist(String key, String domain) { - boolean isExisting = false; - try { - if (classificationMapper.findByKeyAndDomain(key, domain) != null) { - isExisting = true; - } - } catch (Exception ex) { - LOGGER.warn( - "Classification-Service threw Exception while calling mapper and searching for classification. EX={}", - ex, ex); - } - return isExisting; - } - - @Override - public void deleteClassification(String classificationKey, String domain) - throws ClassificationInUseException, ClassificationNotFoundException, NotAuthorizedException { - LOGGER.debug("entry to deleteClassification(key = {}, domain = {})", classificationKey, domain); - taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); - try { - taskanaEngine.openConnection(); - Classification classification = this.classificationMapper.findByKeyAndDomain(classificationKey, domain); - if (classification == null) { - throw new ClassificationNotFoundException(classificationKey, domain, - "The classification \"" + classificationKey + "\" wasn't found in the domain " + domain); - } - deleteClassification(classification.getId()); - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from deleteClassification(key,domain)"); - } - } - - @Override - public void deleteClassification(String classificationId) - throws ClassificationInUseException, ClassificationNotFoundException, NotAuthorizedException { - LOGGER.debug("entry to deleteClassification(id = {})", classificationId); - taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); - try { - taskanaEngine.openConnection(); - Classification classification = this.classificationMapper.findById(classificationId); - if (classification == null) { - throw new ClassificationNotFoundException(classificationId, - "The classification \"" + classificationId + "\" wasn't found"); - } - - if (classification.getDomain().equals("")) { - // master mode - delete all associated classifications in every domain. - List classificationsInDomain = createClassificationQuery() - .keyIn(classification.getKey()) - .list(); - for (ClassificationSummary classificationInDomain : classificationsInDomain) { - if (!"".equals(classificationInDomain.getDomain())) { - deleteClassification(classificationInDomain.getId()); - } - } - } - - List childClassifications = createClassificationQuery().parentIdIn(classificationId) - .list(); - for (ClassificationSummary child : childClassifications) { - this.deleteClassification(child.getId()); - } - - try { - this.classificationMapper.deleteClassification(classificationId); - } catch (PersistenceException e) { - if (isReferentialIntegrityConstraintViolation(e)) { - throw new ClassificationInUseException( - "The classification id = \"" + classificationId + "\" and key = \"" + classification.getKey() - + "\" in domain = \"" + classification.getDomain() - + "\" is in use and cannot be deleted. There are either tasks or attachments associated with the classification.", - e.getCause()); - } - } - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from deleteClassification()"); - } - } - - private boolean isReferentialIntegrityConstraintViolation(PersistenceException e) { - return isH2OrPostgresIntegrityConstraintViolation(e) || isDb2IntegrityConstraintViolation(e); - } - - private boolean isDb2IntegrityConstraintViolation(PersistenceException e) { - return e.getCause() instanceof SQLIntegrityConstraintViolationException && e.getMessage().contains("-532"); - } - - private boolean isH2OrPostgresIntegrityConstraintViolation(PersistenceException e) { - return e.getCause() instanceof SQLException && ((SQLException) e.getCause()).getSQLState().equals("23503"); - } - - /** - * Check if current object is based on the newest (by modified). - * - * @param classificationImpl the classification - * @return the old classification - * - * @throws ConcurrencyException if the classification has been modified by some other process. - * @throws ClassificationNotFoundException if the given classification does not exist. - */ - private Classification getExistingClassificationAndVerifyTimestampHasNotChanged( - ClassificationImpl classificationImpl) - throws ConcurrencyException, ClassificationNotFoundException { - Classification oldClassification = this.getClassification(classificationImpl.getKey(), - classificationImpl.getDomain()); - if (!oldClassification.getModified().equals(classificationImpl.getModified())) { - throw new ConcurrencyException( - "The current Classification has been modified while editing. The values can not be updated. Classification " - + classificationImpl.toString()); - } - return oldClassification; - } - - /** - * Update classification fields used by tasks. - * - * @param classificationImpl the new classification - * @param oldClassification the old classification - */ - private void updateCategoryOnAssociatedTasks(ClassificationImpl classificationImpl, - Classification oldClassification) { - List taskSummaries = taskanaEngine.getEngine().getTaskService() + /** + * Update classification fields used by tasks. + * + * @param classificationImpl the new classification + * @param oldClassification the old classification + */ + private void updateCategoryOnAssociatedTasks( + ClassificationImpl classificationImpl, Classification oldClassification) { + List taskSummaries = + taskanaEngine + .getEngine() + .getTaskService() .createTaskQuery() .classificationIdIn(oldClassification.getId()) .list(); - if (!taskSummaries.isEmpty()) { - List taskIds = new ArrayList<>(); - taskSummaries.forEach(ts -> taskIds.add(ts.getTaskId())); - taskMapper.updateClassificationCategoryOnChange(taskIds, classificationImpl.getCategory()); - } + if (!taskSummaries.isEmpty()) { + List taskIds = new ArrayList<>(); + taskSummaries.forEach(ts -> taskIds.add(ts.getTaskId())); + taskMapper.updateClassificationCategoryOnChange(taskIds, classificationImpl.getCategory()); + } + } + + /** + * Check if parentId or parentKey were changed and if the classification exist. + * + * @param classificationImpl the new classification + * @param oldClassification the old classification + * @throws ClassificationNotFoundException if the given classification does not exist. + */ + private void checkExistenceOfParentClassification( + Classification oldClassification, ClassificationImpl classificationImpl) + throws ClassificationNotFoundException { + if (!oldClassification.getParentId().equals(classificationImpl.getParentId()) + && classificationImpl.getParentId() != null + && !classificationImpl.getParentId().isEmpty()) { + this.getClassification(classificationImpl.getParentId()); } - /** - * Check if parentId or parentKey were changed and if the classification exist. - * - * @param classificationImpl the new classification - * @param oldClassification the old classification - * - * @throws ClassificationNotFoundException if the given classification does not exist. - */ - private void checkExistenceOfParentClassification(Classification oldClassification, - ClassificationImpl classificationImpl) - throws ClassificationNotFoundException { - if (!oldClassification.getParentId().equals(classificationImpl.getParentId()) - && classificationImpl.getParentId() != null && !classificationImpl.getParentId().isEmpty()) { - this.getClassification(classificationImpl.getParentId()); - } - - if (!oldClassification.getParentKey().equals(classificationImpl.getParentKey()) - && classificationImpl.getParentKey() != null && !classificationImpl.getParentKey().isEmpty()) { - this.getClassification(classificationImpl.getParentKey(), classificationImpl.getDomain()); - } + if (!oldClassification.getParentKey().equals(classificationImpl.getParentKey()) + && classificationImpl.getParentKey() != null + && !classificationImpl.getParentKey().isEmpty()) { + this.getClassification(classificationImpl.getParentKey(), classificationImpl.getDomain()); } + } - /** - * Check if priority or service level were changed and create the new job. - * - * @param classificationImpl the new classification - * @param oldClassification the old classification - */ - private void createJobIfPriorityOrServiceLevelHasChanged(Classification oldClassification, - ClassificationImpl classificationImpl) { - boolean priorityChanged = oldClassification.getPriority() != classificationImpl.getPriority(); - boolean serviceLevelChanged = !Objects.equals(oldClassification.getServiceLevel(), - classificationImpl.getServiceLevel()); + /** + * Check if priority or service level were changed and create the new job. + * + * @param classificationImpl the new classification + * @param oldClassification the old classification + */ + private void createJobIfPriorityOrServiceLevelHasChanged( + Classification oldClassification, ClassificationImpl classificationImpl) { + boolean priorityChanged = oldClassification.getPriority() != classificationImpl.getPriority(); + boolean serviceLevelChanged = + !Objects.equals(oldClassification.getServiceLevel(), classificationImpl.getServiceLevel()); - if (priorityChanged || serviceLevelChanged) { - Map args = new HashMap<>(); - args.put(ClassificationChangedJob.CLASSIFICATION_ID, classificationImpl.getId()); - args.put(ClassificationChangedJob.PRIORITY_CHANGED, String.valueOf(priorityChanged)); - args.put(ClassificationChangedJob.SERVICE_LEVEL_CHANGED, - String.valueOf(serviceLevelChanged)); - ScheduledJob job = new ScheduledJob(); - job.setArguments(args); - job.setType(ScheduledJob.Type.CLASSIFICATIONCHANGEDJOB); - taskanaEngine.getEngine().getJobService().createJob(job); - } + if (priorityChanged || serviceLevelChanged) { + Map args = new HashMap<>(); + args.put(ClassificationChangedJob.CLASSIFICATION_ID, classificationImpl.getId()); + args.put(ClassificationChangedJob.PRIORITY_CHANGED, String.valueOf(priorityChanged)); + args.put(ClassificationChangedJob.SERVICE_LEVEL_CHANGED, String.valueOf(serviceLevelChanged)); + ScheduledJob job = new ScheduledJob(); + job.setArguments(args); + job.setType(ScheduledJob.Type.CLASSIFICATIONCHANGEDJOB); + taskanaEngine.getEngine().getJobService().createJob(job); } - + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/ClassificationSummaryImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/ClassificationSummaryImpl.java index 09cfab9e8..80eb4921f 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/ClassificationSummaryImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/ClassificationSummaryImpl.java @@ -4,251 +4,296 @@ import java.util.Objects; import pro.taskana.ClassificationSummary; -/** - * Implementation for the short summaries of a classification entity. - */ +/** Implementation for the short summaries of a classification entity. */ public class ClassificationSummaryImpl implements ClassificationSummary { - protected String id; - protected String key; - protected String category; - protected String type; - protected String domain; - protected String name; - protected String parentId; - protected String parentKey; - protected int priority; - protected String serviceLevel; // PddDThhHmmM - protected String custom1; - protected String custom2; - protected String custom3; - protected String custom4; - protected String custom5; - protected String custom6; - protected String custom7; - protected String custom8; + protected String id; + protected String key; + protected String category; + protected String type; + protected String domain; + protected String name; + protected String parentId; + protected String parentKey; + protected int priority; + protected String serviceLevel; // PddDThhHmmM + protected String custom1; + protected String custom2; + protected String custom3; + protected String custom4; + protected String custom5; + protected String custom6; + protected String custom7; + protected String custom8; - ClassificationSummaryImpl() { + ClassificationSummaryImpl() {} + + @Override + public int getPriority() { + return priority; + } + + public void setPriority(int priority) { + this.priority = priority; + } + + @Override + public String getServiceLevel() { + return serviceLevel; + } + + public void setServiceLevel(String serviceLevel) { + this.serviceLevel = serviceLevel; + } + + @Override + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @Override + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + @Override + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + @Override + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + @Override + public String getDomain() { + return domain; + } + + public void setDomain(String domain) { + this.domain = domain; + } + + @Override + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String getParentId() { + return parentId; + } + + public void setParentId(String parentId) { + this.parentId = parentId; + } + + @Override + public String getParentKey() { + return parentKey; + } + + public void setParentKey(String parentKey) { + this.parentKey = parentKey; + } + + @Override + public String getCustom1() { + return custom1; + } + + public void setCustom1(String custom1) { + this.custom1 = custom1; + } + + @Override + public String getCustom2() { + return custom2; + } + + public void setCustom2(String custom2) { + this.custom2 = custom2; + } + + @Override + public String getCustom3() { + return custom3; + } + + public void setCustom3(String custom3) { + this.custom3 = custom3; + } + + @Override + public String getCustom4() { + return custom4; + } + + public void setCustom4(String custom4) { + this.custom4 = custom4; + } + + @Override + public String getCustom5() { + return custom5; + } + + public void setCustom5(String custom5) { + this.custom5 = custom5; + } + + @Override + public String getCustom6() { + return custom6; + } + + public void setCustom6(String custom6) { + this.custom6 = custom6; + } + + @Override + public String getCustom7() { + return custom7; + } + + public void setCustom7(String custom7) { + this.custom7 = custom7; + } + + @Override + public String getCustom8() { + return custom8; + } + + public void setCustom8(String custom8) { + this.custom8 = custom8; + } + + protected boolean canEqual(Object other) { + return (other instanceof ClassificationSummaryImpl); + } + + @Override + public int hashCode() { + return Objects.hash( + id, + key, + category, + type, + domain, + name, + parentId, + parentKey, + priority, + serviceLevel, + custom1, + custom2, + custom3, + custom4, + custom5, + custom6, + custom7, + custom8); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null) { + return false; } - @Override - public int getPriority() { - return priority; + if (!getClass().isAssignableFrom(o.getClass())) { + return false; } - public void setPriority(int priority) { - this.priority = priority; + ClassificationSummaryImpl that = (ClassificationSummaryImpl) o; + + if (!that.canEqual(this)) { + return false; } - @Override - public String getServiceLevel() { - return serviceLevel; - } - - public void setServiceLevel(String serviceLevel) { - this.serviceLevel = serviceLevel; - } - - @Override - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - @Override - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - @Override - public String getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } - - @Override - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - @Override - public String getDomain() { - return domain; - } - - public void setDomain(String domain) { - this.domain = domain; - } - - @Override - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public String getParentId() { - return parentId; - } - - public void setParentId(String parentId) { - this.parentId = parentId; - } - - @Override - public String getParentKey() { - return parentKey; - } - - public void setParentKey(String parentKey) { - this.parentKey = parentKey; - } - - @Override - public String getCustom1() { - return custom1; - } - - public void setCustom1(String custom1) { - this.custom1 = custom1; - } - - @Override - public String getCustom2() { - return custom2; - } - - public void setCustom2(String custom2) { - this.custom2 = custom2; - } - - @Override - public String getCustom3() { - return custom3; - } - - public void setCustom3(String custom3) { - this.custom3 = custom3; - } - - @Override - public String getCustom4() { - return custom4; - } - - public void setCustom4(String custom4) { - this.custom4 = custom4; - } - - @Override - public String getCustom5() { - return custom5; - } - - public void setCustom5(String custom5) { - this.custom5 = custom5; - } - - @Override - public String getCustom6() { - return custom6; - } - - public void setCustom6(String custom6) { - this.custom6 = custom6; - } - - @Override - public String getCustom7() { - return custom7; - } - - public void setCustom7(String custom7) { - this.custom7 = custom7; - } - - @Override - public String getCustom8() { - return custom8; - } - - public void setCustom8(String custom8) { - this.custom8 = custom8; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null) { - return false; - } - - if (!getClass().isAssignableFrom(o.getClass())) { - return false; - } - - ClassificationSummaryImpl that = (ClassificationSummaryImpl) o; - - if (!that.canEqual(this)) { - return false; - } - - return priority == that.priority - && Objects.equals(id, that.id) - && Objects.equals(key, that.key) - && Objects.equals(category, that.category) - && Objects.equals(type, that.type) - && Objects.equals(domain, that.domain) - && Objects.equals(name, that.name) - && Objects.equals(parentId, that.parentId) - && Objects.equals(parentKey, that.parentKey) - && Objects.equals(serviceLevel, that.serviceLevel) - && Objects.equals(custom1, that.custom1) - && Objects.equals(custom2, that.custom2) - && Objects.equals(custom3, that.custom3) - && Objects.equals(custom4, that.custom4) - && Objects.equals(custom5, that.custom5) - && Objects.equals(custom6, that.custom6) - && Objects.equals(custom7, that.custom7) - && Objects.equals(custom8, that.custom8); - } - - protected boolean canEqual(Object other) { - return (other instanceof ClassificationSummaryImpl); - } - - @Override - public int hashCode() { - return Objects.hash(id, key, category, type, domain, name, parentId, parentKey, priority, serviceLevel, custom1, - custom2, custom3, custom4, custom5, custom6, custom7, custom8); - } - - @Override - public String toString() { - return "ClassificationSummaryImpl [id=" + id + ", key=" + key + ", category=" + category + ", type=" + type - + ", domain=" + domain + ", name=" + name + ", parentId=" + parentId + ", parentKey=" + parentKey - + ", priority=" + priority + ", serviceLevel=" + serviceLevel + ", custom1=" + custom1 + ", custom2=" - + custom2 + ", custom3=" + custom3 + ", custom4=" + custom4 + ", custom5=" + custom5 + ", custom6=" - + custom6 + ", custom7=" + custom7 + ", custom8=" + custom8 + "]"; - } + return priority == that.priority + && Objects.equals(id, that.id) + && Objects.equals(key, that.key) + && Objects.equals(category, that.category) + && Objects.equals(type, that.type) + && Objects.equals(domain, that.domain) + && Objects.equals(name, that.name) + && Objects.equals(parentId, that.parentId) + && Objects.equals(parentKey, that.parentKey) + && Objects.equals(serviceLevel, that.serviceLevel) + && Objects.equals(custom1, that.custom1) + && Objects.equals(custom2, that.custom2) + && Objects.equals(custom3, that.custom3) + && Objects.equals(custom4, that.custom4) + && Objects.equals(custom5, that.custom5) + && Objects.equals(custom6, that.custom6) + && Objects.equals(custom7, that.custom7) + && Objects.equals(custom8, that.custom8); + } + @Override + public String toString() { + return "ClassificationSummaryImpl [id=" + + id + + ", key=" + + key + + ", category=" + + category + + ", type=" + + type + + ", domain=" + + domain + + ", name=" + + name + + ", parentId=" + + parentId + + ", parentKey=" + + parentKey + + ", priority=" + + priority + + ", serviceLevel=" + + serviceLevel + + ", custom1=" + + custom1 + + ", custom2=" + + custom2 + + ", custom3=" + + custom3 + + ", custom4=" + + custom4 + + ", custom5=" + + custom5 + + ", custom6=" + + custom6 + + ", custom7=" + + custom7 + + ", custom8=" + + custom8 + + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/CustomFieldValueReportBuilderImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/CustomFieldValueReportBuilderImpl.java index 9e36b22e4..b6775b778 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/CustomFieldValueReportBuilderImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/CustomFieldValueReportBuilderImpl.java @@ -1,7 +1,6 @@ package pro.taskana.impl; import java.util.List; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -15,53 +14,61 @@ import pro.taskana.impl.report.preprocessor.DaysToWorkingDaysPreProcessor; import pro.taskana.mappings.TaskMonitorMapper; import pro.taskana.report.CustomFieldValueReport; -/** - * The implementation of CustomFieldValueReportBuilder. - */ +/** The implementation of CustomFieldValueReportBuilder. */ public class CustomFieldValueReportBuilderImpl - extends TimeIntervalReportBuilderImpl + extends TimeIntervalReportBuilderImpl< + CustomFieldValueReport.Builder, MonitorQueryItem, TimeIntervalColumnHeader> implements CustomFieldValueReport.Builder { - private static final Logger LOGGER = LoggerFactory.getLogger(CustomFieldValueReportBuilderImpl.class); + private static final Logger LOGGER = + LoggerFactory.getLogger(CustomFieldValueReportBuilderImpl.class); - private CustomField customField; + private CustomField customField; - CustomFieldValueReportBuilderImpl(InternalTaskanaEngine taskanaEngine, TaskMonitorMapper taskMonitorMapper, - CustomField customField) { - super(taskanaEngine, taskMonitorMapper); - this.customField = customField; + CustomFieldValueReportBuilderImpl( + InternalTaskanaEngine taskanaEngine, + TaskMonitorMapper taskMonitorMapper, + CustomField customField) { + super(taskanaEngine, taskMonitorMapper); + this.customField = customField; + } + + @Override + public CustomFieldValueReport buildReport() + throws InvalidArgumentException, NotAuthorizedException { + LOGGER.debug("entry to buildReport(customField = {}), this = {}", this.customField, this); + this.taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.MONITOR); + try { + this.taskanaEngine.openConnection(); + CustomFieldValueReport report = new CustomFieldValueReport(this.columnHeaders); + List monitorQueryItems = + this.taskMonitorMapper.getTaskCountOfCustomFieldValues( + this.customField, + this.workbasketIds, + this.states, + this.categories, + this.domains, + this.classificationIds, + this.excludedClassificationIds, + this.customAttributeFilter); + + report.addItems( + monitorQueryItems, + new DaysToWorkingDaysPreProcessor<>(this.columnHeaders, this.inWorkingDays)); + return report; + } finally { + this.taskanaEngine.returnConnection(); + LOGGER.debug("exit from buildReport()."); } + } - @Override - protected CustomFieldValueReport.Builder _this() { - return this; - } + @Override + protected CustomFieldValueReport.Builder _this() { + return this; + } - @Override - protected String determineGroupedBy() { - return customField.name(); - } - - @Override - public CustomFieldValueReport buildReport() - throws InvalidArgumentException, NotAuthorizedException { - LOGGER.debug("entry to buildReport(customField = {}), this = {}", this.customField, this); - this.taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.MONITOR); - try { - this.taskanaEngine.openConnection(); - CustomFieldValueReport report = new CustomFieldValueReport(this.columnHeaders); - List monitorQueryItems = this.taskMonitorMapper.getTaskCountOfCustomFieldValues( - this.customField, this.workbasketIds, this.states, this.categories, this.domains, - this.classificationIds, - this.excludedClassificationIds, - this.customAttributeFilter); - - report.addItems(monitorQueryItems, - new DaysToWorkingDaysPreProcessor<>(this.columnHeaders, this.inWorkingDays)); - return report; - } finally { - this.taskanaEngine.returnConnection(); - LOGGER.debug("exit from buildReport()."); - } - } + @Override + protected String determineGroupedBy() { + return customField.name(); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/DaysToWorkingDaysConverter.java b/lib/taskana-core/src/main/java/pro/taskana/impl/DaysToWorkingDaysConverter.java index 70b52f16c..43ff00eb3 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/DaysToWorkingDaysConverter.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/DaysToWorkingDaysConverter.java @@ -14,7 +14,6 @@ import java.util.List; import java.util.Set; import java.util.stream.LongStream; import java.util.stream.Stream; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -23,292 +22,306 @@ import pro.taskana.impl.report.header.TimeIntervalColumnHeader; import pro.taskana.impl.util.LoggerUtils; /** - * The DaysToWorkingDaysConverter provides a method to convert an age in days into an age in working days. Before the - * method convertDaysToWorkingDays() can be used, the DaysToWorkingDaysConverter has to be initialized. For a list of - * {@link TimeIntervalColumnHeader}s the converter creates a "table" with integer that represents the age in days from - * the largest lower limit until the smallest upper limit of the timeIntervalColumnHeaders. This table is valid for a - * whole day until the converter is initialized with bigger limits. + * The DaysToWorkingDaysConverter provides a method to convert an age in days into an age in working + * days. Before the method convertDaysToWorkingDays() can be used, the DaysToWorkingDaysConverter + * has to be initialized. For a list of {@link TimeIntervalColumnHeader}s the converter creates a + * "table" with integer that represents the age in days from the largest lower limit until the + * smallest upper limit of the timeIntervalColumnHeaders. This table is valid for a whole day until + * the converter is initialized with bigger limits. */ public final class DaysToWorkingDaysConverter { - private static final Logger LOGGER = LoggerFactory.getLogger(TaskMonitorServiceImpl.class); - private static boolean germanHolidaysEnabled; - private static Set customHolidays = new HashSet<>(); - private List positiveDaysToWorkingDays; - private List negativeDaysToWorkingDays; - private Instant dateCreated; - private LocalDate easterSunday; + private static final Logger LOGGER = LoggerFactory.getLogger(TaskMonitorServiceImpl.class); + private static boolean germanHolidaysEnabled; + private static Set customHolidays = new HashSet<>(); + private List positiveDaysToWorkingDays; + private List negativeDaysToWorkingDays; + private Instant dateCreated; + private LocalDate easterSunday; - private DaysToWorkingDaysConverter(List columnHeaders, - Instant referenceDate) { - easterSunday = getEasterSunday(LocalDateTime.ofInstant(referenceDate, ZoneId.systemDefault()).getYear()); - dateCreated = referenceDate; - positiveDaysToWorkingDays = generatePositiveDaysToWorkingDays(columnHeaders, referenceDate); - negativeDaysToWorkingDays = generateNegativeDaysToWorkingDays(columnHeaders, referenceDate); + private DaysToWorkingDaysConverter( + List columnHeaders, Instant referenceDate) { + easterSunday = + getEasterSunday(LocalDateTime.ofInstant(referenceDate, ZoneId.systemDefault()).getYear()); + dateCreated = referenceDate; + positiveDaysToWorkingDays = generatePositiveDaysToWorkingDays(columnHeaders, referenceDate); + negativeDaysToWorkingDays = generateNegativeDaysToWorkingDays(columnHeaders, referenceDate); + } + + public static DaysToWorkingDaysConverter initialize() throws InvalidArgumentException { + return initialize(Collections.singletonList(new TimeIntervalColumnHeader(0)), Instant.now()); + } + + /** + * Initializes the DaysToWorkingDaysConverter for a list of {@link TimeIntervalColumnHeader}s and + * the current day. A new table is only created if there are bigger limits or the date has + * changed. + * + * @param columnHeaders a list of {@link TimeIntervalColumnHeader}s that determines the size of + * the table + * @return an instance of the DaysToWorkingDaysConverter + * @throws InvalidArgumentException thrown if columnHeaders is null + */ + public static DaysToWorkingDaysConverter initialize( + List columnHeaders) throws InvalidArgumentException { + return initialize(columnHeaders, Instant.now()); + } + + /** + * Initializes the DaysToWorkingDaysConverter for a list of {@link TimeIntervalColumnHeader}s and + * a referenceDate. A new table is only created if there are bigger limits or the date has + * changed. + * + * @param columnHeaders a list of {@link TimeIntervalColumnHeader}s that determines the size of + * the table + * @param referenceDate a {@link Instant} that represents the current day of the table + * @return an instance of the DaysToWorkingDaysConverter + * @throws InvalidArgumentException thrown if columnHeaders or referenceDate is null + */ + public static DaysToWorkingDaysConverter initialize( + List columnHeaders, Instant referenceDate) + throws InvalidArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "Initialize DaysToWorkingDaysConverter with columnHeaders: {}", + LoggerUtils.listToString(columnHeaders)); + } + if (columnHeaders == null) { + throw new InvalidArgumentException( + "TimeIntervalColumnHeaders can´t be used as NULL-Parameter"); + } + if (referenceDate == null) { + throw new InvalidArgumentException("ReferenceDate can´t be used as NULL-Parameter"); } - public static DaysToWorkingDaysConverter initialize() throws InvalidArgumentException { - return initialize(Collections.singletonList(new TimeIntervalColumnHeader(0)), Instant.now()); + return new DaysToWorkingDaysConverter(columnHeaders, referenceDate); + } + + public static void setGermanPublicHolidaysEnabled(boolean germanPublicHolidaysEnabled) { + germanHolidaysEnabled = germanPublicHolidaysEnabled; + } + + public static void setCustomHolidays(List holidays) { + customHolidays = new HashSet<>(holidays == null ? Collections.emptyList() : holidays); + } + + /** + * Converts an integer, that represents the age in days, to the age in working days by using the + * table that was created by initialization. If the age in days is beyond the limits of the table, + * the integer will be returned unchanged. + * + * @param ageInDays represents the age in days + * @return the age in working days + */ + public int convertDaysToWorkingDays(int ageInDays) { + + int minDay = -(negativeDaysToWorkingDays.size() - 1); + int maxDay = positiveDaysToWorkingDays.size() - 1; + + if (ageInDays >= minDay && ageInDays <= 0) { + return negativeDaysToWorkingDays.get(-ageInDays); + } + if (ageInDays > 0 && ageInDays <= maxDay) { + return positiveDaysToWorkingDays.get(ageInDays); } - /** - * Initializes the DaysToWorkingDaysConverter for a list of {@link TimeIntervalColumnHeader}s and the current day. A - * new table is only created if there are bigger limits or the date has changed. - * - * @param columnHeaders a list of {@link TimeIntervalColumnHeader}s that determines the size of the table - * @return an instance of the DaysToWorkingDaysConverter - * @throws InvalidArgumentException thrown if columnHeaders is null - */ - public static DaysToWorkingDaysConverter initialize(List columnHeaders) - throws InvalidArgumentException { - return initialize(columnHeaders, Instant.now()); - } + return ageInDays; + } - /** - * Initializes the DaysToWorkingDaysConverter for a list of {@link TimeIntervalColumnHeader}s and a referenceDate. A - * new table is only created if there are bigger limits or the date has changed. - * - * @param columnHeaders a list of {@link TimeIntervalColumnHeader}s that determines the size of the table - * @param referenceDate a {@link Instant} that represents the current day of the table - * @return an instance of the DaysToWorkingDaysConverter - * @throws InvalidArgumentException thrown if columnHeaders or referenceDate is null - */ - public static DaysToWorkingDaysConverter initialize(List columnHeaders, - Instant referenceDate) throws InvalidArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Initialize DaysToWorkingDaysConverter with columnHeaders: {}", - LoggerUtils.listToString(columnHeaders)); + /** + * Converts an integer, that represents the age in working days, to the age in days by using the + * table that was created by initialization. Because one age in working days could match to more + * than one age in days, the return value is a list of all days that match to the input parameter. + * If the age in working days is beyond the limits of the table, the integer will be returned + * unchanged. + * + * @param ageInWorkingDays represents the age in working days + * @return a list of age in days + */ + public ArrayList convertWorkingDaysToDays(int ageInWorkingDays) { + + ArrayList list = new ArrayList<>(); + + int minWorkingDay = negativeDaysToWorkingDays.get(negativeDaysToWorkingDays.size() - 1); + int maxWorkingDay = positiveDaysToWorkingDays.get(positiveDaysToWorkingDays.size() - 1); + + if (ageInWorkingDays >= minWorkingDay && ageInWorkingDays < 0) { + for (int ageInDays = 0; ageInDays < negativeDaysToWorkingDays.size(); ageInDays++) { + if (negativeDaysToWorkingDays.get(ageInDays) == ageInWorkingDays) { + list.add(-ageInDays); } - if (columnHeaders == null) { - throw new InvalidArgumentException("TimeIntervalColumnHeaders can´t be used as NULL-Parameter"); + } + return list; + } + if (ageInWorkingDays > 0 && ageInWorkingDays <= maxWorkingDay) { + for (int ageInDays = 0; ageInDays < positiveDaysToWorkingDays.size(); ageInDays++) { + if (positiveDaysToWorkingDays.get(ageInDays) == ageInWorkingDays) { + list.add(ageInDays); } - if (referenceDate == null) { - throw new InvalidArgumentException("ReferenceDate can´t be used as NULL-Parameter"); - } - - return new DaysToWorkingDaysConverter(columnHeaders, referenceDate); + } + return list; } - public static void setGermanPublicHolidaysEnabled(boolean germanPublicHolidaysEnabled) { - germanHolidaysEnabled = germanPublicHolidaysEnabled; - } - - /** - * Computes the date of Easter Sunday for a given year. - * - * @param year for which the date of Easter Sunday should be calculated - * @return the date of Easter Sunday for the given year - */ - static LocalDate getEasterSunday(int year) { - // Formula to compute Easter Sunday by Gauss. - int a = year % 19; - int b = year % 4; - int c = year % 7; - int k = year / 100; - int p = (13 + 8 * k) / 25; - int q = k / 4; - int m = (15 - p + k - q) % 30; - int n = (4 + k - q) % 7; - int d = (19 * a + m) % 30; - - int e = (2 * b + 4 * c + 6 * d + n) % 7; - - if (d == 29 && e == 6) { - return LocalDate.of(year, 3, 15).plusDays(d + e); + if (ageInWorkingDays == 0) { + list.add(0); + for (int ageInDays = 1; ageInDays < positiveDaysToWorkingDays.size(); ageInDays++) { + if (positiveDaysToWorkingDays.get(ageInDays) == ageInWorkingDays) { + list.add(ageInDays); } - if (d == 28 && e == 6 && (11 * m + 11) % 30 < 19) { - return LocalDate.of(year, 3, 15).plusDays(d + e); + } + for (int ageInDays = 1; ageInDays < negativeDaysToWorkingDays.size(); ageInDays++) { + if (negativeDaysToWorkingDays.get(ageInDays) == ageInWorkingDays) { + list.add(-ageInDays); } - return LocalDate.of(year, 3, 22).plusDays(d + e); + } + return list; } - public static void setCustomHolidays(List holidays) { - customHolidays = new HashSet<>(holidays == null ? Collections.emptyList() : holidays); + // If ageInWorkingDays is beyond the limits of the table, the value is returned unchanged. + list.add(ageInWorkingDays); + return list; + } + + public long convertWorkingDaysToDays(Instant startTime, long numberOfDays) { + int direction = numberOfDays >= 0 ? 1 : -1; + long limit = Math.abs(numberOfDays); + return LongStream.iterate(0, i -> i + direction) + .filter(day -> isWorkingDay(day, startTime)) + .skip(limit) + .findFirst() + .orElse(0); + } + + /** + * Computes the date of Easter Sunday for a given year. + * + * @param year for which the date of Easter Sunday should be calculated + * @return the date of Easter Sunday for the given year + */ + static LocalDate getEasterSunday(int year) { + // Formula to compute Easter Sunday by Gauss. + int a = year % 19; + int b = year % 4; + int c = year % 7; + int k = year / 100; + int p = (13 + 8 * k) / 25; + int q = k / 4; + int m = (15 - p + k - q) % 30; + int n = (4 + k - q) % 7; + int d = (19 * a + m) % 30; + + int e = (2 * b + 4 * c + 6 * d + n) % 7; + + if (d == 29 && e == 6) { + return LocalDate.of(year, 3, 15).plusDays(d + e); + } + if (d == 28 && e == 6 && (11 * m + 11) % 30 < 19) { + return LocalDate.of(year, 3, 15).plusDays(d + e); + } + return LocalDate.of(year, 3, 22).plusDays(d + e); + } + + private List generateNegativeDaysToWorkingDays( + List columnHeaders, Instant referenceDate) { + int minUpperLimit = TimeIntervalColumnHeader.getSmallestUpperLimit(columnHeaders); + + List daysToWorkingDays = new ArrayList<>(); + daysToWorkingDays.add(0); + int day = -1; + int workingDay = 0; + while (workingDay > minUpperLimit) { + workingDay -= (isWorkingDay(day--, referenceDate)) ? 1 : 0; + daysToWorkingDays.add(workingDay); + } + return daysToWorkingDays; + } + + private List generatePositiveDaysToWorkingDays( + List columnHeaders, Instant referenceDate) { + int maxLowerLimit = TimeIntervalColumnHeader.getLargestLowerLimit(columnHeaders); + ArrayList daysToWorkingDays = new ArrayList<>(); + daysToWorkingDays.add(0); + + int day = 1; + int workingDay = 0; + while (workingDay < maxLowerLimit) { + workingDay += (isWorkingDay(day++, referenceDate)) ? 1 : 0; + daysToWorkingDays.add(workingDay); + } + return daysToWorkingDays; + } + + private boolean isWorkingDay(long day, Instant referenceDate) { + LocalDateTime dateToCheck = + LocalDateTime.ofInstant(referenceDate, ZoneId.systemDefault()).plusDays(day); + + return !isWeekend(dateToCheck) && !isHoliday(dateToCheck.toLocalDate()); + } + + private boolean isWeekend(LocalDateTime dateToCheck) { + return dateToCheck.getDayOfWeek().equals(DayOfWeek.SATURDAY) + || dateToCheck.getDayOfWeek().equals(DayOfWeek.SUNDAY); + } + + private boolean isHoliday(LocalDate date) { + if (germanHolidaysEnabled && isGermanHoliday(date)) { + return true; + } + // Custom holidays that can be configured in the TaskanaEngineConfiguration + return customHolidays.contains(date); + } + + private boolean isGermanHoliday(LocalDate date) { + // Fix and movable holidays that are valid throughout Germany: New years day, Labour Day, Day of + // German + // Unity, Christmas, + if (Stream.of(GermanFixHolidays.values()).anyMatch(day -> day.matches(date))) { + return true; } - /** - * Converts an integer, that represents the age in days, to the age in working days by using the table that was - * created by initialization. If the age in days is beyond the limits of the table, the integer will be returned - * unchanged. - * - * @param ageInDays represents the age in days - * @return the age in working days - */ - public int convertDaysToWorkingDays(int ageInDays) { + // Easter holidays Good Friday, Easter Monday, Ascension Day, Whit Monday. + long diffFromEasterSunday = DAYS.between(easterSunday, date); + long goodFriday = -2; + long easterMonday = 1; + long ascensionDay = 39; + long whitMonday = 50; - int minDay = -(negativeDaysToWorkingDays.size() - 1); - int maxDay = positiveDaysToWorkingDays.size() - 1; + return LongStream.of(goodFriday, easterMonday, ascensionDay, whitMonday) + .anyMatch(diff -> diff == diffFromEasterSunday); + } - if (ageInDays >= minDay && ageInDays <= 0) { - return negativeDaysToWorkingDays.get(-ageInDays); - } - if (ageInDays > 0 && ageInDays <= maxDay) { - return positiveDaysToWorkingDays.get(ageInDays); - } + @Override + public String toString() { + return "DaysToWorkingDaysConverter{" + + "positiveDaysToWorkingDays=" + + positiveDaysToWorkingDays + + ", negativeDaysToWorkingDays=" + + negativeDaysToWorkingDays + + ", dateCreated=" + + dateCreated + + ", easterSunday=" + + easterSunday + + '}'; + } - return ageInDays; + /** Enumeration of German holidays. */ + private enum GermanFixHolidays { + NEWYEAR(1, 1), + LABOURDAY(5, 1), + GERMANUNITY(10, 3), + CHRISTMAS1(12, 25), + CHRISTMAS2(12, 26); + + private int month; + private int day; + + GermanFixHolidays(int month, int day) { + this.month = month; + this.day = day; } - /** - * Converts an integer, that represents the age in working days, to the age in days by using the table that was - * created by initialization. Because one age in working days could match to more than one age in days, the return - * value is a list of all days that match to the input parameter. If the age in working days is beyond the limits of - * the table, the integer will be returned unchanged. - * - * @param ageInWorkingDays represents the age in working days - * @return a list of age in days - */ - public ArrayList convertWorkingDaysToDays(int ageInWorkingDays) { - - ArrayList list = new ArrayList<>(); - - int minWorkingDay = negativeDaysToWorkingDays.get(negativeDaysToWorkingDays.size() - 1); - int maxWorkingDay = positiveDaysToWorkingDays.get(positiveDaysToWorkingDays.size() - 1); - - if (ageInWorkingDays >= minWorkingDay && ageInWorkingDays < 0) { - for (int ageInDays = 0; ageInDays < negativeDaysToWorkingDays.size(); ageInDays++) { - if (negativeDaysToWorkingDays.get(ageInDays) == ageInWorkingDays) { - list.add(-ageInDays); - } - } - return list; - } - if (ageInWorkingDays > 0 && ageInWorkingDays <= maxWorkingDay) { - for (int ageInDays = 0; ageInDays < positiveDaysToWorkingDays.size(); ageInDays++) { - if (positiveDaysToWorkingDays.get(ageInDays) == ageInWorkingDays) { - list.add(ageInDays); - } - } - return list; - } - - if (ageInWorkingDays == 0) { - list.add(0); - for (int ageInDays = 1; ageInDays < positiveDaysToWorkingDays.size(); ageInDays++) { - if (positiveDaysToWorkingDays.get(ageInDays) == ageInWorkingDays) { - list.add(ageInDays); - } - } - for (int ageInDays = 1; ageInDays < negativeDaysToWorkingDays.size(); ageInDays++) { - if (negativeDaysToWorkingDays.get(ageInDays) == ageInWorkingDays) { - list.add(-ageInDays); - } - } - return list; - } - - // If ageInWorkingDays is beyond the limits of the table, the value is returned unchanged. - list.add(ageInWorkingDays); - return list; - } - - public long convertWorkingDaysToDays(Instant startTime, long numberOfDays) { - int direction = numberOfDays >= 0 ? 1 : -1; - long limit = Math.abs(numberOfDays); - return LongStream.iterate(0, i -> i + direction) - .filter(day -> isWorkingDay(day, startTime)) - .skip(limit) - .findFirst().orElse(0); - } - - private List generateNegativeDaysToWorkingDays( - List columnHeaders, Instant referenceDate) { - int minUpperLimit = TimeIntervalColumnHeader.getSmallestUpperLimit(columnHeaders); - - List daysToWorkingDays = new ArrayList<>(); - daysToWorkingDays.add(0); - int day = -1; - int workingDay = 0; - while (workingDay > minUpperLimit) { - workingDay -= (isWorkingDay(day--, referenceDate)) ? 1 : 0; - daysToWorkingDays.add(workingDay); - } - return daysToWorkingDays; - } - - private List generatePositiveDaysToWorkingDays( - List columnHeaders, Instant referenceDate) { - int maxLowerLimit = TimeIntervalColumnHeader.getLargestLowerLimit(columnHeaders); - ArrayList daysToWorkingDays = new ArrayList<>(); - daysToWorkingDays.add(0); - - int day = 1; - int workingDay = 0; - while (workingDay < maxLowerLimit) { - workingDay += (isWorkingDay(day++, referenceDate)) ? 1 : 0; - daysToWorkingDays.add(workingDay); - } - return daysToWorkingDays; - } - - private boolean isWorkingDay(long day, Instant referenceDate) { - LocalDateTime dateToCheck = LocalDateTime.ofInstant(referenceDate, ZoneId.systemDefault()).plusDays(day); - - return !isWeekend(dateToCheck) - && !isHoliday(dateToCheck.toLocalDate()); - } - - private boolean isWeekend(LocalDateTime dateToCheck) { - return dateToCheck.getDayOfWeek().equals(DayOfWeek.SATURDAY) - || dateToCheck.getDayOfWeek().equals(DayOfWeek.SUNDAY); - } - - private boolean isHoliday(LocalDate date) { - if (germanHolidaysEnabled && isGermanHoliday(date)) { - return true; - } - // Custom holidays that can be configured in the TaskanaEngineConfiguration - return customHolidays.contains(date); - } - - private boolean isGermanHoliday(LocalDate date) { - // Fix and movable holidays that are valid throughout Germany: New years day, Labour Day, Day of German - // Unity, Christmas, - if (Stream.of(GermanFixHolidays.values()).anyMatch(day -> day.matches(date))) { - return true; - } - - // Easter holidays Good Friday, Easter Monday, Ascension Day, Whit Monday. - long diffFromEasterSunday = DAYS.between(easterSunday, date); - long goodFriday = -2; - long easterMonday = 1; - long ascensionDay = 39; - long whitMonday = 50; - - return LongStream.of(goodFriday, easterMonday, ascensionDay, whitMonday) - .anyMatch(diff -> diff == diffFromEasterSunday); - } - - @Override - public String toString() { - return "DaysToWorkingDaysConverter{" - + "positiveDaysToWorkingDays=" + positiveDaysToWorkingDays - + ", negativeDaysToWorkingDays=" + negativeDaysToWorkingDays - + ", dateCreated=" + dateCreated - + ", easterSunday=" + easterSunday - + '}'; - } - - /** - * Enumeration of German holidays. - */ - private enum GermanFixHolidays { - NEWYEAR(1, 1), - LABOURDAY(5, 1), - GERMANUNITY(10, 3), - CHRISTMAS1(12, 25), - CHRISTMAS2(12, 26); - - private int month; - private int day; - - GermanFixHolidays(int month, int day) { - this.month = month; - this.day = day; - } - - public boolean matches(LocalDate date) { - return date.getDayOfMonth() == day && date.getMonthValue() == month; - } + public boolean matches(LocalDate date) { + return date.getDayOfMonth() == day && date.getMonthValue() == month; } + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/InternalTaskanaEngine.java b/lib/taskana-core/src/main/java/pro/taskana/impl/InternalTaskanaEngine.java index bdfd0431d..4300e1fe3 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/InternalTaskanaEngine.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/InternalTaskanaEngine.java @@ -1,7 +1,6 @@ package pro.taskana.impl; import java.util.function.Supplier; - import org.apache.ibatis.session.SqlSession; import pro.taskana.TaskanaEngine; @@ -11,70 +10,69 @@ import pro.taskana.taskrouting.TaskRoutingManager; /** * FOR INTERNAL USE ONLY. * - * Contains all actions which are necessary within taskana. + *

Contains all actions which are necessary within taskana. */ public interface InternalTaskanaEngine { - /** - * Opens the connection to the database. Has to be called at the begin of each Api call that accesses the database - */ - void openConnection(); + /** + * Opens the connection to the database. Has to be called at the begin of each Api call that + * accesses the database + */ + void openConnection(); - /** - * Returns the database connection into the pool. In the case of nested calls, simply pops the latest session from - * the session stack. Closes the connection if the session stack is empty. In mode AUTOCOMMIT commits before the - * connection is closed. To be called at the end of each Api call that accesses the database - */ - void returnConnection(); + /** + * Returns the database connection into the pool. In the case of nested calls, simply pops the + * latest session from the session stack. Closes the connection if the session stack is empty. In + * mode AUTOCOMMIT commits before the connection is closed. To be called at the end of each Api + * call that accesses the database + */ + void returnConnection(); - /** - * - * Executes the supplier after openConnection is called and then returns the connection. - * @param supplier a function that returns something of type T - * @param any type - * @return the result of the supplier - */ - T openAndReturnConnection(Supplier supplier); + /** + * Executes the supplier after openConnection is called and then returns the connection. + * + * @param supplier a function that returns something of type T + * @param any type + * @return the result of the supplier + */ + T openAndReturnConnection(Supplier supplier); - /** - * Initializes the SqlSessionManager. - */ - void initSqlSession(); + /** Initializes the SqlSessionManager. */ + void initSqlSession(); - /** - * Returns true if the given domain does exist in the configuration. - * - * @param domain - * the domain specified in the configuration - * @return true if the domain exists - */ - boolean domainExists(String domain); + /** + * Returns true if the given domain does exist in the configuration. + * + * @param domain the domain specified in the configuration + * @return true if the domain exists + */ + boolean domainExists(String domain); - /** - * retrieve the SqlSession used by taskana. - * - * @return the myBatis SqlSession object used by taskana - */ - SqlSession getSqlSession(); + /** + * retrieve the SqlSession used by taskana. + * + * @return the myBatis SqlSession object used by taskana + */ + SqlSession getSqlSession(); - /** - * Retrieve TaskanaEngine. - * @return The nested TaskanaEngine. - */ - TaskanaEngine getEngine(); + /** + * Retrieve TaskanaEngine. + * + * @return The nested TaskanaEngine. + */ + TaskanaEngine getEngine(); - /** - * Retrieve HistoryEventProducer. - * - * @return the HistoryEventProducer instance. - */ - HistoryEventProducer getHistoryEventProducer(); - - /** - * Retrieve TaskRoutingProducer. - * - * @return the TaskRoutingProducer instance. - */ - TaskRoutingManager getTaskRoutingManager(); + /** + * Retrieve HistoryEventProducer. + * + * @return the HistoryEventProducer instance. + */ + HistoryEventProducer getHistoryEventProducer(); + /** + * Retrieve TaskRoutingProducer. + * + * @return the TaskRoutingProducer instance. + */ + TaskRoutingManager getTaskRoutingManager(); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/JobServiceImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/JobServiceImpl.java index 4bee3e0a7..f8b927dd3 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/JobServiceImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/JobServiceImpl.java @@ -2,7 +2,6 @@ package pro.taskana.impl; import java.time.Instant; import java.util.List; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -10,91 +9,88 @@ import pro.taskana.JobService; import pro.taskana.jobs.ScheduledJob; import pro.taskana.mappings.JobMapper; -/** - * Controls all job activities. - */ +/** Controls all job activities. */ public class JobServiceImpl implements JobService { - public static final Integer JOB_DEFAULT_PRIORITY = 50; - public static final long DEFAULT_LOCK_EXPIRATION_PERIOD = 60000; + public static final Integer JOB_DEFAULT_PRIORITY = 50; + public static final long DEFAULT_LOCK_EXPIRATION_PERIOD = 60000; - private static final Logger LOGGER = LoggerFactory.getLogger(JobServiceImpl.class); - private JobMapper jobMapper; - private InternalTaskanaEngine taskanaEngineImpl; + private static final Logger LOGGER = LoggerFactory.getLogger(JobServiceImpl.class); + private JobMapper jobMapper; + private InternalTaskanaEngine taskanaEngineImpl; - public JobServiceImpl(InternalTaskanaEngine taskanaEngine, JobMapper jobMapper) { - this.taskanaEngineImpl = taskanaEngine; - this.jobMapper = jobMapper; + public JobServiceImpl(InternalTaskanaEngine taskanaEngine, JobMapper jobMapper) { + this.taskanaEngineImpl = taskanaEngine; + this.jobMapper = jobMapper; + } + + @Override + public ScheduledJob createJob(ScheduledJob job) { + LOGGER.debug("Entry to createJob({})", job); + try { + taskanaEngineImpl.openConnection(); + job = initializeJobDefault(job); + jobMapper.insertJob(job); + LOGGER.debug("Created job {}", job); + } finally { + taskanaEngineImpl.returnConnection(); } + LOGGER.debug("Exit from createJob"); + return job; + } - @Override - public ScheduledJob createJob(ScheduledJob job) { - LOGGER.debug("Entry to createJob({})", job); - try { - taskanaEngineImpl.openConnection(); - job = initializeJobDefault(job); - jobMapper.insertJob(job); - LOGGER.debug("Created job {}", job); - } finally { - taskanaEngineImpl.returnConnection(); - } - LOGGER.debug("Exit from createJob"); - return job; + public ScheduledJob lockJob(ScheduledJob job, String owner) { + LOGGER.debug("entry to lockJob(jobId = {}, owner = {})", job.getJobId(), owner); + try { + taskanaEngineImpl.openConnection(); + job.setLockedBy(owner); + job.setLockExpires(Instant.now().plusMillis(DEFAULT_LOCK_EXPIRATION_PERIOD)); + job.setRetryCount(job.getRetryCount() - 1); + jobMapper.update(job); + LOGGER.debug("Job {} locked. Remaining retries: {}", job.getJobId(), job.getRetryCount()); + } finally { + taskanaEngineImpl.returnConnection(); + LOGGER.debug("exit from lockJob()"); } + return job; + } - public ScheduledJob lockJob(ScheduledJob job, String owner) { - LOGGER.debug("entry to lockJob(jobId = {}, owner = {})", job.getJobId(), owner); - try { - taskanaEngineImpl.openConnection(); - job.setLockedBy(owner); - job.setLockExpires(Instant.now().plusMillis(DEFAULT_LOCK_EXPIRATION_PERIOD)); - job.setRetryCount(job.getRetryCount() - 1); - jobMapper.update(job); - LOGGER.debug("Job {} locked. Remaining retries: {}", job.getJobId(), job.getRetryCount()); - } finally { - taskanaEngineImpl.returnConnection(); - LOGGER.debug("exit from lockJob()"); - } - return job; + public List findJobsToRun() { + LOGGER.debug("entry to findJobsToRun"); + List availableJobs; + try { + taskanaEngineImpl.openConnection(); + availableJobs = jobMapper.findJobsToRun(); + LOGGER.debug("Found available jobs: {}", availableJobs); + } finally { + taskanaEngineImpl.returnConnection(); + LOGGER.debug("exit from findJobsToRun()"); } + return availableJobs; + } - public List findJobsToRun() { - LOGGER.debug("entry to findJobsToRun"); - List availableJobs; - try { - taskanaEngineImpl.openConnection(); - availableJobs = jobMapper.findJobsToRun(); - LOGGER.debug("Found available jobs: {}", availableJobs); - } finally { - taskanaEngineImpl.returnConnection(); - LOGGER.debug("exit from findJobsToRun()"); - } - return availableJobs; + public void deleteJob(ScheduledJob job) { + LOGGER.debug("entry to deleteJob(jobId = {})", job.getJobId()); + try { + taskanaEngineImpl.openConnection(); + jobMapper.delete(job); + LOGGER.debug("Deleted job: {}", job); + } finally { + taskanaEngineImpl.returnConnection(); + LOGGER.debug("exit from deleteJob()"); } + } - public void deleteJob(ScheduledJob job) { - LOGGER.debug("entry to deleteJob(jobId = {})", job.getJobId()); - try { - taskanaEngineImpl.openConnection(); - jobMapper.delete(job); - LOGGER.debug("Deleted job: {}", job); - } finally { - taskanaEngineImpl.returnConnection(); - LOGGER.debug("exit from deleteJob()"); - } + private ScheduledJob initializeJobDefault(ScheduledJob job) { + LOGGER.debug("entry to initializeJobDefault(job = {})", job); + job.setCreated(Instant.now()); + job.setState(ScheduledJob.State.READY); + job.setPriority(JOB_DEFAULT_PRIORITY); + if (job.getDue() == null) { + job.setDue(Instant.now()); } - - private ScheduledJob initializeJobDefault(ScheduledJob job) { - LOGGER.debug("entry to initializeJobDefault(job = {})", job); - job.setCreated(Instant.now()); - job.setState(ScheduledJob.State.READY); - job.setPriority(JOB_DEFAULT_PRIORITY); - if (job.getDue() == null) { - job.setDue(Instant.now()); - } - job.setRetryCount(taskanaEngineImpl.getEngine().getConfiguration().getMaxNumberOfJobRetries()); - LOGGER.debug("Job after initialization: {}", job); - return job; - } - + job.setRetryCount(taskanaEngineImpl.getEngine().getConfiguration().getMaxNumberOfJobRetries()); + LOGGER.debug("Job after initialization: {}", job); + return job; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/MinimalTaskSummary.java b/lib/taskana-core/src/main/java/pro/taskana/impl/MinimalTaskSummary.java index 9b9a1008b..4139a80f3 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/MinimalTaskSummary.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/MinimalTaskSummary.java @@ -3,65 +3,65 @@ package pro.taskana.impl; import pro.taskana.CallbackState; import pro.taskana.TaskState; -/** - * A convenience class to represent pairs of task id and task state. - */ +/** A convenience class to represent pairs of task id and task state. */ public class MinimalTaskSummary { - private String taskId; - private String externalId; - private String workbasketId; - private TaskState taskState; - private CallbackState callbackState; + private String taskId; + private String externalId; + private String workbasketId; + private TaskState taskState; + private CallbackState callbackState; - MinimalTaskSummary() { + MinimalTaskSummary() {} - } + public String getTaskId() { + return taskId; + } - public String getTaskId() { - return taskId; - } + public void setTaskId(String taskId) { + this.taskId = taskId; + } - public void setTaskId(String taskId) { - this.taskId = taskId; - } + public String getExternalId() { + return externalId; + } - public String getExternalId() { - return externalId; - } + public void setExternalId(String externalId) { + this.externalId = externalId; + } - public void setExternalId(String externalId) { - this.externalId = externalId; - } + public String getWorkbasketId() { + return workbasketId; + } - public String getWorkbasketId() { - return workbasketId; - } + public void setWorkbasketId(String workbasketKey) { + this.workbasketId = workbasketKey; + } - public void setWorkbasketId(String workbasketKey) { - this.workbasketId = workbasketKey; - } + public TaskState getTaskState() { + return taskState; + } - public TaskState getTaskState() { - return taskState; - } + public void setTaskState(TaskState taskState) { + this.taskState = taskState; + } - public void setTaskState(TaskState taskState) { - this.taskState = taskState; - } + public CallbackState getCallbackState() { + return callbackState; + } - public CallbackState getCallbackState() { - return callbackState; - } - - public void setCallbackState(CallbackState callbackState) { - this.callbackState = callbackState; - } - - @Override - public String toString() { - return "MinimalTaskSummary [taskId=" + taskId + ", workbasketId=" + workbasketId + ", taskState=" + taskState - + "]"; - } + public void setCallbackState(CallbackState callbackState) { + this.callbackState = callbackState; + } + @Override + public String toString() { + return "MinimalTaskSummary [taskId=" + + taskId + + ", workbasketId=" + + workbasketId + + ", taskState=" + + taskState + + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/ObjectReferenceQueryImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/ObjectReferenceQueryImpl.java index 6313f7132..449983e51 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/ObjectReferenceQueryImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/ObjectReferenceQueryImpl.java @@ -3,7 +3,6 @@ package pro.taskana.impl; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import org.apache.ibatis.exceptions.PersistenceException; import org.apache.ibatis.session.RowBounds; import org.slf4j.Logger; @@ -22,203 +21,227 @@ import pro.taskana.impl.util.LoggerUtils; */ public class ObjectReferenceQueryImpl implements ObjectReferenceQuery { - private static final String LINK_TO_MAPPER = "pro.taskana.mappings.QueryMapper.queryObjectReferences"; - private static final String LINK_TO_COUNTER = "pro.taskana.mappings.QueryMapper.countQueryObjectReferences"; - private static final String LINK_TO_VALUEMAPPER = "pro.taskana.mappings.QueryMapper.queryObjectReferenceColumnValues"; - private static final Logger LOGGER = LoggerFactory.getLogger(ObjectReferenceQueryImpl.class); - private InternalTaskanaEngine taskanaEngine; - private ObjectReferenceQueryColumnName columnName; - private String[] company; - private String[] system; - private String[] systemInstance; - private String[] type; - private String[] value; - private List orderBy; + private static final String LINK_TO_MAPPER = + "pro.taskana.mappings.QueryMapper.queryObjectReferences"; + private static final String LINK_TO_COUNTER = + "pro.taskana.mappings.QueryMapper.countQueryObjectReferences"; + private static final String LINK_TO_VALUEMAPPER = + "pro.taskana.mappings.QueryMapper.queryObjectReferenceColumnValues"; + private static final Logger LOGGER = LoggerFactory.getLogger(ObjectReferenceQueryImpl.class); + private InternalTaskanaEngine taskanaEngine; + private ObjectReferenceQueryColumnName columnName; + private String[] company; + private String[] system; + private String[] systemInstance; + private String[] type; + private String[] value; + private List orderBy; - ObjectReferenceQueryImpl(InternalTaskanaEngine taskanaEngine) { - this.taskanaEngine = taskanaEngine; - this.orderBy = new ArrayList<>(); + ObjectReferenceQueryImpl(InternalTaskanaEngine taskanaEngine) { + this.taskanaEngine = taskanaEngine; + this.orderBy = new ArrayList<>(); + } + + @Override + public ObjectReferenceQuery companyIn(String... companies) { + this.company = companies; + return this; + } + + @Override + public ObjectReferenceQuery systemIn(String... systems) { + this.system = systems; + return this; + } + + @Override + public ObjectReferenceQuery systemInstanceIn(String... systemInstances) { + this.systemInstance = systemInstances; + return this; + } + + @Override + public ObjectReferenceQuery typeIn(String... types) { + this.type = types; + return this; + } + + @Override + public ObjectReferenceQuery valueIn(String... values) { + this.value = values; + return this; + } + + @Override + public List list() { + LOGGER.debug("entry to list(), this = {}", this); + List result = new ArrayList<>(); + try { + taskanaEngine.openConnection(); + result = taskanaEngine.getSqlSession().selectList(LINK_TO_MAPPER, this); + return result; + } finally { + taskanaEngine.returnConnection(); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "exit from list(). Returning {} resulting Objects: {} ", + result.size(), + LoggerUtils.listToString(result)); + } } + } - @Override - public ObjectReferenceQuery companyIn(String... companies) { - this.company = companies; - return this; + @Override + public List listValues( + ObjectReferenceQueryColumnName columnName, SortDirection sortDirection) { + LOGGER.debug("Entry to listValues(dbColumnName={}) this = {}", columnName, this); + List result = new ArrayList<>(); + try { + taskanaEngine.openConnection(); + this.columnName = columnName; + this.orderBy.clear(); + this.addOrderCriteria(columnName.toString(), sortDirection); + result = taskanaEngine.getSqlSession().selectList(LINK_TO_VALUEMAPPER, this); + return result; + } finally { + taskanaEngine.returnConnection(); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "Exit from listValues. Returning {} resulting Objects: {} ", + result.size(), + LoggerUtils.listToString(result)); + } } + } - @Override - public ObjectReferenceQuery systemIn(String... systems) { - this.system = systems; - return this; - } - - @Override - public ObjectReferenceQuery systemInstanceIn(String... systemInstances) { - this.systemInstance = systemInstances; - return this; - } - - @Override - public ObjectReferenceQuery typeIn(String... types) { - this.type = types; - return this; - } - - @Override - public ObjectReferenceQuery valueIn(String... values) { - this.value = values; - return this; - } - - @Override - public List list() { - LOGGER.debug("entry to list(), this = {}", this); - List result = new ArrayList<>(); - try { - taskanaEngine.openConnection(); - result = taskanaEngine.getSqlSession().selectList(LINK_TO_MAPPER, this); - return result; - } finally { - taskanaEngine.returnConnection(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("exit from list(). Returning {} resulting Objects: {} ", result.size(), - LoggerUtils.listToString(result)); - } + @Override + public List list(int offset, int limit) { + LOGGER.debug("entry to list(offset = {}, limit = {}), this = {}", offset, limit, this); + List result = new ArrayList<>(); + try { + taskanaEngine.openConnection(); + RowBounds rowBounds = new RowBounds(offset, limit); + result = taskanaEngine.getSqlSession().selectList(LINK_TO_MAPPER, this, rowBounds); + return result; + } catch (Exception e) { + if (e instanceof PersistenceException) { + if (e.getMessage().contains("ERRORCODE=-4470")) { + TaskanaRuntimeException ex = + new TaskanaRuntimeException( + "The offset beginning was set over the amount of result-rows.", e.getCause()); + ex.setStackTrace(e.getStackTrace()); + throw ex; } + } + throw e; + } finally { + taskanaEngine.returnConnection(); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "exit from list(offset,limit). Returning {} resulting Objects: {} ", + result.size(), + LoggerUtils.listToString(result)); + } } + } - @Override - public List listValues(ObjectReferenceQueryColumnName columnName, SortDirection sortDirection) { - LOGGER.debug("Entry to listValues(dbColumnName={}) this = {}", columnName, this); - List result = new ArrayList<>(); - try { - taskanaEngine.openConnection(); - this.columnName = columnName; - this.orderBy.clear(); - this.addOrderCriteria(columnName.toString(), sortDirection); - result = taskanaEngine.getSqlSession().selectList(LINK_TO_VALUEMAPPER, this); - return result; - } finally { - taskanaEngine.returnConnection(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from listValues. Returning {} resulting Objects: {} ", result.size(), - LoggerUtils.listToString(result)); - } - } + @Override + public ObjectReference single() { + LOGGER.debug("entry to single(), this = {}", this); + ObjectReference result = null; + try { + taskanaEngine.openConnection(); + result = taskanaEngine.getSqlSession().selectOne(LINK_TO_MAPPER, this); + return result; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from single(). Returning result {} ", result); } + } - @Override - public List list(int offset, int limit) { - LOGGER.debug("entry to list(offset = {}, limit = {}), this = {}", offset, limit, this); - List result = new ArrayList<>(); - try { - taskanaEngine.openConnection(); - RowBounds rowBounds = new RowBounds(offset, limit); - result = taskanaEngine.getSqlSession().selectList(LINK_TO_MAPPER, this, rowBounds); - return result; - } catch (Exception e) { - if (e instanceof PersistenceException) { - if (e.getMessage().contains("ERRORCODE=-4470")) { - TaskanaRuntimeException ex = new TaskanaRuntimeException( - "The offset beginning was set over the amount of result-rows.", e.getCause()); - ex.setStackTrace(e.getStackTrace()); - throw ex; - } - } - throw e; - } finally { - taskanaEngine.returnConnection(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("exit from list(offset,limit). Returning {} resulting Objects: {} ", result.size(), - LoggerUtils.listToString(result)); - } - } + public String[] getCompany() { + return company; + } + + public void setCompany(String[] company) { + this.company = company; + } + + public String[] getSystem() { + return system; + } + + public void setSystem(String[] system) { + this.system = system; + } + + public String[] getSystemInstance() { + return systemInstance; + } + + public void setSystemInstance(String[] systemInstance) { + this.systemInstance = systemInstance; + } + + public String[] getType() { + return type; + } + + public void setType(String[] type) { + this.type = type; + } + + public String[] getValue() { + return value; + } + + public void setValue(String[] value) { + this.value = value; + } + + public ObjectReferenceQueryColumnName getColumnName() { + return columnName; + } + + @Override + public long count() { + LOGGER.debug("entry to count(), this = {}", this); + Long rowCount = null; + try { + taskanaEngine.openConnection(); + rowCount = taskanaEngine.getSqlSession().selectOne(LINK_TO_COUNTER, this); + return (rowCount == null) ? 0L : rowCount; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from count(). Returning result {} ", rowCount); } + } - @Override - public ObjectReference single() { - LOGGER.debug("entry to single(), this = {}", this); - ObjectReference result = null; - try { - taskanaEngine.openConnection(); - result = taskanaEngine.getSqlSession().selectOne(LINK_TO_MAPPER, this); - return result; - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from single(). Returning result {} ", result); - } - } - - public String[] getCompany() { - return company; - } - - public void setCompany(String[] company) { - this.company = company; - } - - public String[] getSystem() { - return system; - } - - public void setSystem(String[] system) { - this.system = system; - } - - public String[] getSystemInstance() { - return systemInstance; - } - - public void setSystemInstance(String[] systemInstance) { - this.systemInstance = systemInstance; - } - - public String[] getType() { - return type; - } - - public void setType(String[] type) { - this.type = type; - } - - public String[] getValue() { - return value; - } - - public void setValue(String[] value) { - this.value = value; - } - - public ObjectReferenceQueryColumnName getColumnName() { - return columnName; - } - - @Override - public long count() { - LOGGER.debug("entry to count(), this = {}", this); - Long rowCount = null; - try { - taskanaEngine.openConnection(); - rowCount = taskanaEngine.getSqlSession().selectOne(LINK_TO_COUNTER, this); - return (rowCount == null) ? 0L : rowCount; - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from count(). Returning result {} ", rowCount); - } - } - - private ObjectReferenceQuery addOrderCriteria(String colName, SortDirection sortDirection) { - String orderByDirection = " " + (sortDirection == null ? SortDirection.ASCENDING : sortDirection); - orderBy.add(colName + orderByDirection); - return this; - } - - @Override - public String toString() { - return "ObjectReferenceQueryImpl [taskanaEngine=" + taskanaEngine + ", columnName=" + columnName + ", company=" - + Arrays.toString(company) + ", system=" + Arrays.toString(system) + ", systemInstance=" - + Arrays.toString(systemInstance) + ", type=" + Arrays.toString(type) + ", value=" + Arrays.toString(value) - + ", orderBy=" + orderBy + "]"; - } + private ObjectReferenceQuery addOrderCriteria(String colName, SortDirection sortDirection) { + String orderByDirection = + " " + (sortDirection == null ? SortDirection.ASCENDING : sortDirection); + orderBy.add(colName + orderByDirection); + return this; + } + @Override + public String toString() { + return "ObjectReferenceQueryImpl [taskanaEngine=" + + taskanaEngine + + ", columnName=" + + columnName + + ", company=" + + Arrays.toString(company) + + ", system=" + + Arrays.toString(system) + + ", systemInstance=" + + Arrays.toString(systemInstance) + + ", type=" + + Arrays.toString(type) + + ", value=" + + Arrays.toString(value) + + ", orderBy=" + + orderBy + + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/SelectedItem.java b/lib/taskana-core/src/main/java/pro/taskana/impl/SelectedItem.java index 1d9aeb5e4..e650660c4 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/SelectedItem.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/SelectedItem.java @@ -1,52 +1,58 @@ package pro.taskana.impl; /** - * An item that contains information of a selected item of a Report. It is used to get the task ids of the selected item - * of the Report. + * An item that contains information of a selected item of a Report. It is used to get the task ids + * of the selected item of the Report. */ public class SelectedItem { - private String key; - private String subKey; - private int upperAgeLimit; - private int lowerAgeLimit; + private String key; + private String subKey; + private int upperAgeLimit; + private int lowerAgeLimit; - public String getKey() { - return key; - } + public String getKey() { + return key; + } - public void setKey(String key) { - this.key = key; - } + public void setKey(String key) { + this.key = key; + } - public String getSubKey() { - return subKey; - } + public String getSubKey() { + return subKey; + } - public void setSubKey(String subKey) { - this.subKey = subKey; - } + public void setSubKey(String subKey) { + this.subKey = subKey; + } - public int getUpperAgeLimit() { - return upperAgeLimit; - } + public int getUpperAgeLimit() { + return upperAgeLimit; + } - public void setUpperAgeLimit(int upperAgeLimit) { - this.upperAgeLimit = upperAgeLimit; - } + public void setUpperAgeLimit(int upperAgeLimit) { + this.upperAgeLimit = upperAgeLimit; + } - public int getLowerAgeLimit() { - return lowerAgeLimit; - } + public int getLowerAgeLimit() { + return lowerAgeLimit; + } - public void setLowerAgeLimit(int lowerAgeLimit) { - this.lowerAgeLimit = lowerAgeLimit; - } - - @Override - public String toString() { - return "Key: " + this.key + ", SubKey: " + this.subKey + ", Limits: (" + this.lowerAgeLimit + "," - + this.getUpperAgeLimit() + ")"; - } + public void setLowerAgeLimit(int lowerAgeLimit) { + this.lowerAgeLimit = lowerAgeLimit; + } + @Override + public String toString() { + return "Key: " + + this.key + + ", SubKey: " + + this.subKey + + ", Limits: (" + + this.lowerAgeLimit + + "," + + this.getUpperAgeLimit() + + ")"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/TaskImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/TaskImpl.java index dc7869cf5..e891458e4 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/TaskImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/TaskImpl.java @@ -10,9 +10,9 @@ import java.util.Map; import pro.taskana.Attachment; import pro.taskana.AttachmentSummary; +import pro.taskana.CallbackState; import pro.taskana.ClassificationSummary; import pro.taskana.ObjectReference; -import pro.taskana.CallbackState; import pro.taskana.Task; import pro.taskana.TaskState; import pro.taskana.TaskSummary; @@ -20,795 +20,963 @@ import pro.taskana.WorkbasketSummary; import pro.taskana.exceptions.InvalidArgumentException; import pro.taskana.exceptions.SystemException; -/** - * Task entity. - */ +/** Task entity. */ public class TaskImpl implements Task { - private String id; - private String externalId; - private Instant created; - private Instant claimed; - private Instant completed; - private Instant modified; - private Instant planned; - private Instant due; - private String name; - private String creator; - private String description; - private String note; - private int priority; - private TaskState state; - private ClassificationSummary classificationSummary; - private WorkbasketSummary workbasketSummary; - private String businessProcessId; - private String parentBusinessProcessId; - private String owner; - private ObjectReference primaryObjRef; - private boolean isRead; - private boolean isTransferred; - // All objects have to be serializable - private Map customAttributes = Collections.emptyMap(); - private Map callbackInfo = Collections.emptyMap(); - private CallbackState callbackState; - private List attachments = new ArrayList<>(); - private String custom1; - private String custom2; - private String custom3; - private String custom4; - private String custom5; - private String custom6; - private String custom7; - private String custom8; - private String custom9; - private String custom10; - private String custom11; - private String custom12; - private String custom13; - private String custom14; - private String custom15; - private String custom16; - - private static final String ARGUMENT_STR = "Argument '"; - private static final String NOT_A_VALID_NUMBER_GET = "' of getCustomAttribute() cannot be converted to a number between 1 and 16"; - private static final String NOT_A_VALID_NUMBER_SET = "' of setCustomAttribute() cannot be converted to a number between 1 and 16"; - - TaskImpl() { - } - - @Override - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - @Override - public String getExternalId() { - return externalId; - } - - @Override - public void setExternalId(String externalId) { - this.externalId = externalId; - } - - @Override - public Instant getCreated() { - return created; - } - - public void setCreated(Instant created) { - this.created = created; - } - - @Override - public Instant getClaimed() { - return claimed; - } - - public void setClaimed(Instant claimed) { - this.claimed = claimed; - } - - @Override - public Instant getCompleted() { - return completed; - } - - public void setCompleted(Instant completed) { - this.completed = completed; - } - - @Override - public Instant getModified() { - return modified; - } - - public void setModified(Instant modified) { - this.modified = modified; - } - - @Override - public Instant getPlanned() { - return planned; - } - - @Override - public void setPlanned(Instant planned) { - this.planned = planned; - } - - @Override - public Instant getDue() { - return due; - } - - @Override - public void setDue(Instant due) { - this.due = due; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - public void setCreator(String creator) { - this.creator = creator; - } - - @Override - public String getCreator() { - return creator; - } - - @Override - public String getDescription() { - return description; - } - - @Override - public void setDescription(String description) { - this.description = description; - } - - @Override - public String getNote() { - return note; - } - - @Override - public void setNote(String note) { - this.note = note; - } - - @Override - public int getPriority() { - return priority; - } - - public void setPriority(int priority) { - this.priority = priority; - } - - @Override - public TaskState getState() { - return state; - } - - public void setState(TaskState state) { - this.state = state; - } - - @Override - public ClassificationSummary getClassificationSummary() { - return classificationSummary; - } - - @Override - public void setClassificationKey(String classificationKey) { - if (this.classificationSummary == null) { - this.classificationSummary = new ClassificationSummaryImpl(); - } - - ((ClassificationSummaryImpl) this.classificationSummary).setKey(classificationKey); - } - - public void setClassificationCategory(String classificationCategory) { - if (this.classificationSummary == null) { - this.classificationSummary = new ClassificationSummaryImpl(); - } - ((ClassificationSummaryImpl) this.classificationSummary).setCategory(classificationCategory); - } - - @Override - public String getClassificationCategory() { - return this.classificationSummary == null ? null : this.classificationSummary.getCategory(); - } - - @Override - public String getWorkbasketKey() { - return workbasketSummary == null ? null : workbasketSummary.getKey(); - } - - public void setWorkbasketKey(String workbasketKey) { - if (workbasketSummary == null) { - workbasketSummary = new WorkbasketSummaryImpl(); - } - ((WorkbasketSummaryImpl) this.workbasketSummary).setKey(workbasketKey); - } - - @Override - public WorkbasketSummary getWorkbasketSummary() { - return workbasketSummary; - } - - public void setWorkbasketSummary(WorkbasketSummary workbasket) { - this.workbasketSummary = workbasket; - } - - @Override - public String getDomain() { - return workbasketSummary == null ? null : workbasketSummary.getDomain(); - } - - public void setDomain(String domain) { - if (workbasketSummary == null) { - workbasketSummary = new WorkbasketSummaryImpl(); - } - ((WorkbasketSummaryImpl) this.workbasketSummary).setDomain(domain); - } - - @Override - public String getBusinessProcessId() { - return businessProcessId; - } - - @Override - public void setBusinessProcessId(String businessProcessId) { - this.businessProcessId = businessProcessId; - } - - @Override - public String getParentBusinessProcessId() { - return parentBusinessProcessId; - } - - @Override - public void setParentBusinessProcessId(String parentBusinessProcessId) { - this.parentBusinessProcessId = parentBusinessProcessId; - } - - @Override - public String getOwner() { - return owner; - } - - @Override - public void setOwner(String owner) { - this.owner = owner; - } - - @Override - public ObjectReference getPrimaryObjRef() { - return primaryObjRef; - } - - @Override - public void setPrimaryObjRef(ObjectReference primaryObjRef) { - this.primaryObjRef = primaryObjRef; - } - - @Override - public boolean isRead() { - return isRead; - } - - public void setRead(boolean isRead) { - this.isRead = isRead; - } - - @Override - public boolean isTransferred() { - return isTransferred; - } - - public void setTransferred(boolean isTransferred) { - this.isTransferred = isTransferred; - } - - @Override - public Map getCustomAttributes() { - if (customAttributes == null) { - customAttributes = new HashMap<>(); - } - return customAttributes; - } - - @Override - public void setCustomAttributes(Map customAttributes) { - this.customAttributes = customAttributes; - } - - @Override - public Map getCallbackInfo() { - if (callbackInfo == null) { - callbackInfo = new HashMap<>(); - } - return callbackInfo; - } - - @Override - public void setCallbackInfo(Map callbackInfo) { - this.callbackInfo = callbackInfo; - } - - public CallbackState getCallbackState() { - return callbackState; - } - - public void setCallbackState(CallbackState callbackState) { - this.callbackState = callbackState; - } - - @Override - public String getCustomAttribute(String number) throws InvalidArgumentException { - int num = 0; - try { - num = Integer.parseInt(number); - } catch (NumberFormatException e) { - throw new InvalidArgumentException( - ARGUMENT_STR + number + NOT_A_VALID_NUMBER_GET, - e.getCause()); - } - - switch (num) { - case 1: - return custom1; - case 2: - return custom2; - case 3: - return custom3; - case 4: - return custom4; - case 5: - return custom5; - case 6: - return custom6; - case 7: - return custom7; - case 8: - return custom8; - case 9: - return custom9; - case 10: - return custom10; - case 11: - return custom11; - case 12: - return custom12; - case 13: - return custom13; - case 14: - return custom14; - case 15: - return custom15; - case 16: - return custom16; - default: - throw new InvalidArgumentException( - ARGUMENT_STR + number + NOT_A_VALID_NUMBER_GET); - } - - } - - @Override - public void setCustomAttribute(String number, String value) throws InvalidArgumentException { - int num = 0; - try { - num = Integer.parseInt(number); - } catch (NumberFormatException e) { - throw new InvalidArgumentException( - ARGUMENT_STR + number + NOT_A_VALID_NUMBER_SET, - e.getCause()); - } - - switch (num) { - case 1: - custom1 = value; - break; - case 2: - custom2 = value; - break; - case 3: - custom3 = value; - break; - case 4: - custom4 = value; - break; - case 5: - custom5 = value; - break; - case 6: - custom6 = value; - break; - case 7: - custom7 = value; - break; - case 8: - custom8 = value; - break; - case 9: - custom9 = value; - break; - case 10: - custom10 = value; - break; - case 11: - custom11 = value; - break; - case 12: - custom12 = value; - break; - case 13: - custom13 = value; - break; - case 14: - custom14 = value; - break; - case 15: - custom15 = value; - break; - case 16: - custom16 = value; - break; - default: - throw new InvalidArgumentException( - ARGUMENT_STR + number + NOT_A_VALID_NUMBER_SET); - } - - } - - @Override - public void addAttachment(Attachment attachmentToAdd) { - if (attachments == null) { - attachments = new ArrayList<>(); - } - if (attachmentToAdd != null) { - if (attachmentToAdd.getId() != null) { - Iterator i = attachments.iterator(); - while (i.hasNext()) { - Attachment attachment = i.next(); - if (attachmentToAdd.getId().equals(attachment.getId())) { - i.remove(); - } - } - } - attachments.add(attachmentToAdd); - } - } - - @Override - public List getAttachments() { - if (attachments == null) { - attachments = new ArrayList<>(); - } - return attachments; - } - - @Override - public TaskSummary asSummary() { - TaskSummaryImpl taskSummary = new TaskSummaryImpl(); - List attSummaries = new ArrayList<>(); - for (Attachment att : attachments) { - attSummaries.add(att.asSummary()); - } - taskSummary.setAttachmentSummaries(attSummaries); - taskSummary.setBusinessProcessId(this.businessProcessId); - taskSummary.setClaimed(claimed); - if (classificationSummary != null) { - taskSummary.setClassificationSummary(classificationSummary); - } - taskSummary.setExternalId(externalId); - taskSummary.setCompleted(completed); - taskSummary.setCreated(created); - taskSummary.setCustom1(custom1); - taskSummary.setCustom2(custom2); - taskSummary.setCustom3(custom3); - taskSummary.setCustom4(custom4); - taskSummary.setCustom5(custom5); - taskSummary.setCustom6(custom6); - taskSummary.setCustom7(custom7); - taskSummary.setCustom8(custom8); - taskSummary.setCustom9(custom9); - taskSummary.setCustom10(custom10); - taskSummary.setCustom11(custom11); - taskSummary.setCustom12(custom12); - taskSummary.setCustom13(custom13); - taskSummary.setCustom14(custom14); - taskSummary.setCustom15(custom15); - taskSummary.setCustom16(custom16); - taskSummary.setDue(due); - taskSummary.setTaskId(id); - taskSummary.setModified(modified); - taskSummary.setName(name); - taskSummary.setCreator(creator); - taskSummary.setNote(note); - taskSummary.setOwner(owner); - taskSummary.setParentBusinessProcessId(parentBusinessProcessId); - taskSummary.setPlanned(planned); - taskSummary.setPrimaryObjRef(primaryObjRef); - taskSummary.setPriority(priority); - taskSummary.setRead(isRead); - taskSummary.setState(state); - taskSummary.setTransferred(isTransferred); - taskSummary.setWorkbasketSummary(workbasketSummary); - return taskSummary; - - } - - public void setAttachments(List attachments) { - if (attachments != null) { - this.attachments = attachments; - } else if (this.attachments == null) { - this.attachments = new ArrayList<>(); - } - } - - public String getClassificationKey() { - return classificationSummary == null ? null : classificationSummary.getKey(); - } - - public void setClassificationSummary(ClassificationSummary classificationSummary) { - this.classificationSummary = classificationSummary; - } - - public ClassificationSummaryImpl getClassificationSummaryImpl() { - return (ClassificationSummaryImpl) classificationSummary; - } - - public WorkbasketSummaryImpl getWorkbasketSummaryImpl() { - return (WorkbasketSummaryImpl) workbasketSummary; - } - - public void setWorkbasketSummaryImpl(WorkbasketSummaryImpl workbasketSummary) { - this.workbasketSummary = workbasketSummary; - } - - public void setClassificationSummaryImpl(ClassificationSummaryImpl classificationSummary) { - setClassificationSummary(classificationSummary); - } - - public String getCustom1() { + private static final String ARGUMENT_STR = "Argument '"; + private static final String NOT_A_VALID_NUMBER_GET = + "' of getCustomAttribute() cannot be converted to a number between 1 and 16"; + private static final String NOT_A_VALID_NUMBER_SET = + "' of setCustomAttribute() cannot be converted to a number between 1 and 16"; + private String id; + private String externalId; + private Instant created; + private Instant claimed; + private Instant completed; + private Instant modified; + private Instant planned; + private Instant due; + private String name; + private String creator; + private String description; + private String note; + private int priority; + private TaskState state; + private ClassificationSummary classificationSummary; + private WorkbasketSummary workbasketSummary; + private String businessProcessId; + private String parentBusinessProcessId; + private String owner; + private ObjectReference primaryObjRef; + private boolean isRead; + private boolean isTransferred; + // All objects have to be serializable + private Map customAttributes = Collections.emptyMap(); + private Map callbackInfo = Collections.emptyMap(); + private CallbackState callbackState; + private List attachments = new ArrayList<>(); + private String custom1; + private String custom2; + private String custom3; + private String custom4; + private String custom5; + private String custom6; + private String custom7; + private String custom8; + private String custom9; + private String custom10; + private String custom11; + private String custom12; + private String custom13; + private String custom14; + private String custom15; + private String custom16; + + TaskImpl() {} + + @Override + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @Override + public String getExternalId() { + return externalId; + } + + @Override + public void setExternalId(String externalId) { + this.externalId = externalId; + } + + @Override + public Instant getCreated() { + return created; + } + + public void setCreated(Instant created) { + this.created = created; + } + + @Override + public Instant getClaimed() { + return claimed; + } + + public void setClaimed(Instant claimed) { + this.claimed = claimed; + } + + @Override + public Instant getCompleted() { + return completed; + } + + public void setCompleted(Instant completed) { + this.completed = completed; + } + + @Override + public Instant getModified() { + return modified; + } + + public void setModified(Instant modified) { + this.modified = modified; + } + + @Override + public Instant getPlanned() { + return planned; + } + + @Override + public void setPlanned(Instant planned) { + this.planned = planned; + } + + @Override + public Instant getDue() { + return due; + } + + @Override + public void setDue(Instant due) { + this.due = due; + } + + @Override + public String getName() { + return name; + } + + @Override + public void setName(String name) { + this.name = name; + } + + @Override + public String getCreator() { + return creator; + } + + public void setCreator(String creator) { + this.creator = creator; + } + + @Override + public String getDescription() { + return description; + } + + @Override + public void setDescription(String description) { + this.description = description; + } + + @Override + public String getNote() { + return note; + } + + @Override + public void setNote(String note) { + this.note = note; + } + + @Override + public int getPriority() { + return priority; + } + + public void setPriority(int priority) { + this.priority = priority; + } + + @Override + public TaskState getState() { + return state; + } + + public void setState(TaskState state) { + this.state = state; + } + + @Override + public ClassificationSummary getClassificationSummary() { + return classificationSummary; + } + + public void setClassificationSummary(ClassificationSummary classificationSummary) { + this.classificationSummary = classificationSummary; + } + + @Override + public String getClassificationCategory() { + return this.classificationSummary == null ? null : this.classificationSummary.getCategory(); + } + + public void setClassificationCategory(String classificationCategory) { + if (this.classificationSummary == null) { + this.classificationSummary = new ClassificationSummaryImpl(); + } + ((ClassificationSummaryImpl) this.classificationSummary).setCategory(classificationCategory); + } + + @Override + public String getWorkbasketKey() { + return workbasketSummary == null ? null : workbasketSummary.getKey(); + } + + public void setWorkbasketKey(String workbasketKey) { + if (workbasketSummary == null) { + workbasketSummary = new WorkbasketSummaryImpl(); + } + ((WorkbasketSummaryImpl) this.workbasketSummary).setKey(workbasketKey); + } + + @Override + public WorkbasketSummary getWorkbasketSummary() { + return workbasketSummary; + } + + public void setWorkbasketSummary(WorkbasketSummary workbasket) { + this.workbasketSummary = workbasket; + } + + @Override + public String getDomain() { + return workbasketSummary == null ? null : workbasketSummary.getDomain(); + } + + public void setDomain(String domain) { + if (workbasketSummary == null) { + workbasketSummary = new WorkbasketSummaryImpl(); + } + ((WorkbasketSummaryImpl) this.workbasketSummary).setDomain(domain); + } + + @Override + public String getBusinessProcessId() { + return businessProcessId; + } + + @Override + public void setBusinessProcessId(String businessProcessId) { + this.businessProcessId = businessProcessId; + } + + @Override + public String getParentBusinessProcessId() { + return parentBusinessProcessId; + } + + @Override + public void setParentBusinessProcessId(String parentBusinessProcessId) { + this.parentBusinessProcessId = parentBusinessProcessId; + } + + @Override + public String getOwner() { + return owner; + } + + @Override + public void setOwner(String owner) { + this.owner = owner; + } + + @Override + public ObjectReference getPrimaryObjRef() { + return primaryObjRef; + } + + @Override + public void setPrimaryObjRef(ObjectReference primaryObjRef) { + this.primaryObjRef = primaryObjRef; + } + + @Override + public boolean isRead() { + return isRead; + } + + public void setRead(boolean isRead) { + this.isRead = isRead; + } + + @Override + public boolean isTransferred() { + return isTransferred; + } + + public void setTransferred(boolean isTransferred) { + this.isTransferred = isTransferred; + } + + @Override + public Map getCustomAttributes() { + if (customAttributes == null) { + customAttributes = new HashMap<>(); + } + return customAttributes; + } + + @Override + public void setCustomAttributes(Map customAttributes) { + this.customAttributes = customAttributes; + } + + @Override + public Map getCallbackInfo() { + if (callbackInfo == null) { + callbackInfo = new HashMap<>(); + } + return callbackInfo; + } + + @Override + public void setCallbackInfo(Map callbackInfo) { + this.callbackInfo = callbackInfo; + } + + public CallbackState getCallbackState() { + return callbackState; + } + + public void setCallbackState(CallbackState callbackState) { + this.callbackState = callbackState; + } + + @Override + public String getCustomAttribute(String number) throws InvalidArgumentException { + int num = 0; + try { + num = Integer.parseInt(number); + } catch (NumberFormatException e) { + throw new InvalidArgumentException( + ARGUMENT_STR + number + NOT_A_VALID_NUMBER_GET, e.getCause()); + } + + switch (num) { + case 1: return custom1; - } - - public void setCustom1(String custom1) { - this.custom1 = custom1; - } - - public String getCustom2() { + case 2: return custom2; - } - - public void setCustom2(String custom2) { - this.custom2 = custom2; - } - - public String getCustom3() { + case 3: return custom3; - } - - public void setCustom3(String custom3) { - this.custom3 = custom3; - } - - public String getCustom4() { + case 4: return custom4; - } - - public void setCustom4(String custom4) { - this.custom4 = custom4; - } - - public String getCustom5() { + case 5: return custom5; - } - - public void setCustom5(String custom5) { - this.custom5 = custom5; - } - - public String getCustom6() { + case 6: return custom6; - } - - public void setCustom6(String custom6) { - this.custom6 = custom6; - } - - public String getCustom7() { + case 7: return custom7; - } - - public void setCustom7(String custom7) { - this.custom7 = custom7; - } - - public String getCustom8() { + case 8: return custom8; - } - - public void setCustom8(String custom8) { - this.custom8 = custom8; - } - - public String getCustom9() { + case 9: return custom9; - } - - public void setCustom9(String custom9) { - this.custom9 = custom9; - } - - public String getCustom10() { + case 10: return custom10; - } - - public void setCustom10(String custom10) { - this.custom10 = custom10; - } - - public String getCustom11() { + case 11: return custom11; - } - - public void setCustom11(String custom11) { - this.custom11 = custom11; - } - - public String getCustom12() { + case 12: return custom12; - } - - public void setCustom12(String custom12) { - this.custom12 = custom12; - } - - public String getCustom13() { + case 13: return custom13; - } - - public void setCustom13(String custom13) { - this.custom13 = custom13; - } - - public String getCustom14() { + case 14: return custom14; - } - - public void setCustom14(String custom14) { - this.custom14 = custom14; - } - - public String getCustom15() { + case 15: return custom15; - } - - public void setCustom15(String custom15) { - this.custom15 = custom15; - } - - public String getCustom16() { + case 16: return custom16; + default: + throw new InvalidArgumentException(ARGUMENT_STR + number + NOT_A_VALID_NUMBER_GET); + } + } + + @Override + public void setCustomAttribute(String number, String value) throws InvalidArgumentException { + int num = 0; + try { + num = Integer.parseInt(number); + } catch (NumberFormatException e) { + throw new InvalidArgumentException( + ARGUMENT_STR + number + NOT_A_VALID_NUMBER_SET, e.getCause()); } - public void setCustom16(String custom16) { - this.custom16 = custom16; + switch (num) { + case 1: + custom1 = value; + break; + case 2: + custom2 = value; + break; + case 3: + custom3 = value; + break; + case 4: + custom4 = value; + break; + case 5: + custom5 = value; + break; + case 6: + custom6 = value; + break; + case 7: + custom7 = value; + break; + case 8: + custom8 = value; + break; + case 9: + custom9 = value; + break; + case 10: + custom10 = value; + break; + case 11: + custom11 = value; + break; + case 12: + custom12 = value; + break; + case 13: + custom13 = value; + break; + case 14: + custom14 = value; + break; + case 15: + custom15 = value; + break; + case 16: + custom16 = value; + break; + default: + throw new InvalidArgumentException(ARGUMENT_STR + number + NOT_A_VALID_NUMBER_SET); } + } - @Override - public Attachment removeAttachment(String attachmentId) { - Attachment result = null; + @Override + public void addAttachment(Attachment attachmentToAdd) { + if (attachments == null) { + attachments = new ArrayList<>(); + } + if (attachmentToAdd != null) { + if (attachmentToAdd.getId() != null) { Iterator i = attachments.iterator(); while (i.hasNext()) { - Attachment attachment = i.next(); - if (attachment.getId().equals(attachmentId) - && attachments.remove(attachment)) { - result = attachment; - break; - } + Attachment attachment = i.next(); + if (attachmentToAdd.getId().equals(attachment.getId())) { + i.remove(); + } } - return result; + } + attachments.add(attachmentToAdd); + } + } + + @Override + public List getAttachments() { + if (attachments == null) { + attachments = new ArrayList<>(); + } + return attachments; + } + + public void setAttachments(List attachments) { + if (attachments != null) { + this.attachments = attachments; + } else if (this.attachments == null) { + this.attachments = new ArrayList<>(); + } + } + + @Override + public TaskSummary asSummary() { + TaskSummaryImpl taskSummary = new TaskSummaryImpl(); + List attSummaries = new ArrayList<>(); + for (Attachment att : attachments) { + attSummaries.add(att.asSummary()); + } + taskSummary.setAttachmentSummaries(attSummaries); + taskSummary.setBusinessProcessId(this.businessProcessId); + taskSummary.setClaimed(claimed); + if (classificationSummary != null) { + taskSummary.setClassificationSummary(classificationSummary); + } + taskSummary.setExternalId(externalId); + taskSummary.setCompleted(completed); + taskSummary.setCreated(created); + taskSummary.setCustom1(custom1); + taskSummary.setCustom2(custom2); + taskSummary.setCustom3(custom3); + taskSummary.setCustom4(custom4); + taskSummary.setCustom5(custom5); + taskSummary.setCustom6(custom6); + taskSummary.setCustom7(custom7); + taskSummary.setCustom8(custom8); + taskSummary.setCustom9(custom9); + taskSummary.setCustom10(custom10); + taskSummary.setCustom11(custom11); + taskSummary.setCustom12(custom12); + taskSummary.setCustom13(custom13); + taskSummary.setCustom14(custom14); + taskSummary.setCustom15(custom15); + taskSummary.setCustom16(custom16); + taskSummary.setDue(due); + taskSummary.setTaskId(id); + taskSummary.setModified(modified); + taskSummary.setName(name); + taskSummary.setCreator(creator); + taskSummary.setNote(note); + taskSummary.setOwner(owner); + taskSummary.setParentBusinessProcessId(parentBusinessProcessId); + taskSummary.setPlanned(planned); + taskSummary.setPrimaryObjRef(primaryObjRef); + taskSummary.setPriority(priority); + taskSummary.setRead(isRead); + taskSummary.setState(state); + taskSummary.setTransferred(isTransferred); + taskSummary.setWorkbasketSummary(workbasketSummary); + return taskSummary; + } + + public String getClassificationKey() { + return classificationSummary == null ? null : classificationSummary.getKey(); + } + + @Override + public void setClassificationKey(String classificationKey) { + if (this.classificationSummary == null) { + this.classificationSummary = new ClassificationSummaryImpl(); } - @Override - public String toString() { - return "TaskImpl [id=" + id + ", externalId=" + externalId + ", created=" + created + ", claimed=" + claimed - + ", completed=" + completed + ", modified=" + modified + ", planned=" + planned + ", due=" + due - + ", name=" + name + ", creator=" + creator + ", description=" + description + ", note=" + note - + ", priority=" + priority + ", state=" + state + ", classificationSummary=" + classificationSummary - + ", workbasketSummary=" + workbasketSummary + ", businessProcessId=" + businessProcessId - + ", parentBusinessProcessId=" + parentBusinessProcessId + ", owner=" + owner + ", primaryObjRef=" - + primaryObjRef + ", isRead=" + isRead + ", isTransferred=" + isTransferred + ", customAttributes=" - + customAttributes + ", callbackInfo=" + callbackInfo + ", callbackState=" + callbackState - + ", attachments=" + attachments + ", custom1=" + custom1 + ", custom2=" + custom2 + ", custom3=" - + custom3 + ", custom4=" + custom4 + ", custom5=" + custom5 + ", custom6=" + custom6 + ", custom7=" - + custom7 + ", custom8=" + custom8 + ", custom9=" + custom9 + ", custom10=" + custom10 + ", custom11=" - + custom11 + ", custom12=" + custom12 + ", custom13=" + custom13 + ", custom14=" + custom14 + ", custom15=" - + custom15 + ", custom16=" + custom16 + "]"; + ((ClassificationSummaryImpl) this.classificationSummary).setKey(classificationKey); + } + + public ClassificationSummaryImpl getClassificationSummaryImpl() { + return (ClassificationSummaryImpl) classificationSummary; + } + + public void setClassificationSummaryImpl(ClassificationSummaryImpl classificationSummary) { + setClassificationSummary(classificationSummary); + } + + public WorkbasketSummaryImpl getWorkbasketSummaryImpl() { + return (WorkbasketSummaryImpl) workbasketSummary; + } + + public void setWorkbasketSummaryImpl(WorkbasketSummaryImpl workbasketSummary) { + this.workbasketSummary = workbasketSummary; + } + + public String getCustom1() { + return custom1; + } + + public void setCustom1(String custom1) { + this.custom1 = custom1; + } + + public String getCustom2() { + return custom2; + } + + public void setCustom2(String custom2) { + this.custom2 = custom2; + } + + public String getCustom3() { + return custom3; + } + + public void setCustom3(String custom3) { + this.custom3 = custom3; + } + + public String getCustom4() { + return custom4; + } + + public void setCustom4(String custom4) { + this.custom4 = custom4; + } + + public String getCustom5() { + return custom5; + } + + public void setCustom5(String custom5) { + this.custom5 = custom5; + } + + public String getCustom6() { + return custom6; + } + + public void setCustom6(String custom6) { + this.custom6 = custom6; + } + + public String getCustom7() { + return custom7; + } + + public void setCustom7(String custom7) { + this.custom7 = custom7; + } + + public String getCustom8() { + return custom8; + } + + public void setCustom8(String custom8) { + this.custom8 = custom8; + } + + public String getCustom9() { + return custom9; + } + + public void setCustom9(String custom9) { + this.custom9 = custom9; + } + + public String getCustom10() { + return custom10; + } + + public void setCustom10(String custom10) { + this.custom10 = custom10; + } + + public String getCustom11() { + return custom11; + } + + public void setCustom11(String custom11) { + this.custom11 = custom11; + } + + public String getCustom12() { + return custom12; + } + + public void setCustom12(String custom12) { + this.custom12 = custom12; + } + + public String getCustom13() { + return custom13; + } + + public void setCustom13(String custom13) { + this.custom13 = custom13; + } + + public String getCustom14() { + return custom14; + } + + public void setCustom14(String custom14) { + this.custom14 = custom14; + } + + public String getCustom15() { + return custom15; + } + + public void setCustom15(String custom15) { + this.custom15 = custom15; + } + + public String getCustom16() { + return custom16; + } + + public void setCustom16(String custom16) { + this.custom16 = custom16; + } + + @Override + public Attachment removeAttachment(String attachmentId) { + Attachment result = null; + Iterator i = attachments.iterator(); + while (i.hasNext()) { + Attachment attachment = i.next(); + if (attachment.getId().equals(attachmentId) && attachments.remove(attachment)) { + result = attachment; + break; + } + } + return result; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + Object[] myFields = { + externalId, + attachments, + businessProcessId, + claimed, + classificationSummary, + completed, + created, + creator, + custom1, + custom10, + custom11, + custom12, + custom13, + custom14, + custom15, + custom16, + custom2, + custom3, + custom4, + custom5, + custom6, + custom7, + custom8, + custom9, + customAttributes, + callbackInfo, + callbackState, + description, + due, + id, + modified, + name, + note, + owner, + parentBusinessProcessId, + planned, + primaryObjRef, + state, + workbasketSummary + }; + + for (Object property : myFields) { + result = prime * result + (property == null ? 0 : property.hashCode()); + } + result = prime * result + (isRead ? 1231 : 1237); + result = prime * result + (isTransferred ? 1231 : 1237); + result = prime * result + priority; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!getClass().isAssignableFrom(obj.getClass())) { + return false; + } + TaskImpl other = (TaskImpl) obj; + + Object[] myFields = { + externalId, + attachments, + businessProcessId, + claimed, + classificationSummary, + completed, + created, + creator, + custom1, + custom10, + custom11, + custom12, + custom13, + custom14, + custom15, + custom16, + custom2, + custom3, + custom4, + custom5, + custom6, + custom7, + custom8, + custom9, + customAttributes, + callbackInfo, + callbackState, + description, + due, + id, + modified, + name, + note, + owner, + parentBusinessProcessId, + planned, + primaryObjRef, + state, + workbasketSummary + }; + + Object[] otherFields = { + other.externalId, + other.attachments, + other.businessProcessId, + other.claimed, + other.classificationSummary, + other.completed, + other.created, + other.creator, + other.custom1, + other.custom10, + other.custom11, + other.custom12, + other.custom13, + other.custom14, + other.custom15, + other.custom16, + other.custom2, + other.custom3, + other.custom4, + other.custom5, + other.custom6, + other.custom7, + other.custom8, + other.custom9, + other.customAttributes, + other.callbackInfo, + other.callbackState, + other.description, + other.due, + other.id, + other.modified, + other.name, + other.note, + other.owner, + other.parentBusinessProcessId, + other.planned, + other.primaryObjRef, + other.state, + other.workbasketSummary + }; + + if (myFields.length != otherFields.length) { + throw new SystemException("TaskSummaryImpl: length mismatch between internal arrays"); + } + for (int i = 0; i < myFields.length; i++) { + if ((myFields[i] == null && otherFields[i] != null) + || (myFields[i] != null && !myFields[i].equals(otherFields[i]))) { + return false; + } + } + if (isRead != other.isRead) { + return false; + } + if (isTransferred != other.isTransferred) { + return false; } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - Object[] myFields = {externalId, attachments, businessProcessId, claimed, classificationSummary, completed, created, - creator, custom1, custom10, custom11, custom12, custom13, custom14, custom15, custom16, custom2, - custom3, custom4, custom5, custom6, custom7, custom8, custom9, customAttributes, callbackInfo, callbackState, - description, due, id, modified, name, note, owner, parentBusinessProcessId, planned, primaryObjRef, state, - workbasketSummary}; - - for (Object property : myFields) { - result = prime * result + (property == null ? 0 : property.hashCode()); - } - result = prime * result + (isRead ? 1231 : 1237); - result = prime * result + (isTransferred ? 1231 : 1237); - result = prime * result + priority; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!getClass().isAssignableFrom(obj.getClass())) { - return false; - } - TaskImpl other = (TaskImpl) obj; - - Object[] myFields = {externalId, attachments, businessProcessId, claimed, classificationSummary, completed, created, - creator, custom1, custom10, custom11, custom12, custom13, custom14, custom15, custom16, custom2, - custom3, custom4, custom5, custom6, custom7, custom8, custom9, customAttributes, callbackInfo, callbackState, - description, due, id, modified, name, note, owner, parentBusinessProcessId, planned, primaryObjRef, state, - workbasketSummary}; - - Object[] otherFields = {other.externalId, other.attachments, other.businessProcessId, other.claimed, other.classificationSummary, other.completed, - other.created, other.creator, other.custom1, other.custom10, other.custom11, other.custom12, other.custom13, other.custom14, - other.custom15, other.custom16, other.custom2, other.custom3, other.custom4, other.custom5, other.custom6, other.custom7, - other.custom8, other.custom9, other.customAttributes, other.callbackInfo, other.callbackState, other.description, other.due, other.id, other.modified, - other.name, other.note, other.owner, other.parentBusinessProcessId, other.planned, other.primaryObjRef, other.state, other.workbasketSummary}; - - if (myFields.length != otherFields.length) { - throw new SystemException("TaskSummaryImpl: length mismatch between internal arrays"); - } - for (int i = 0; i < myFields.length; i++) { - if ((myFields[i] == null && otherFields[i] != null) - || (myFields[i] != null && !myFields[i].equals(otherFields[i]))) { - return false; - } - } - if (isRead != other.isRead) { - return false; - } - if (isTransferred != other.isTransferred) { - return false; - } - - return (priority == other.priority); - - } + return (priority == other.priority); + } + @Override + public String toString() { + return "TaskImpl [id=" + + id + + ", externalId=" + + externalId + + ", created=" + + created + + ", claimed=" + + claimed + + ", completed=" + + completed + + ", modified=" + + modified + + ", planned=" + + planned + + ", due=" + + due + + ", name=" + + name + + ", creator=" + + creator + + ", description=" + + description + + ", note=" + + note + + ", priority=" + + priority + + ", state=" + + state + + ", classificationSummary=" + + classificationSummary + + ", workbasketSummary=" + + workbasketSummary + + ", businessProcessId=" + + businessProcessId + + ", parentBusinessProcessId=" + + parentBusinessProcessId + + ", owner=" + + owner + + ", primaryObjRef=" + + primaryObjRef + + ", isRead=" + + isRead + + ", isTransferred=" + + isTransferred + + ", customAttributes=" + + customAttributes + + ", callbackInfo=" + + callbackInfo + + ", callbackState=" + + callbackState + + ", attachments=" + + attachments + + ", custom1=" + + custom1 + + ", custom2=" + + custom2 + + ", custom3=" + + custom3 + + ", custom4=" + + custom4 + + ", custom5=" + + custom5 + + ", custom6=" + + custom6 + + ", custom7=" + + custom7 + + ", custom8=" + + custom8 + + ", custom9=" + + custom9 + + ", custom10=" + + custom10 + + ", custom11=" + + custom11 + + ", custom12=" + + custom12 + + ", custom13=" + + custom13 + + ", custom14=" + + custom14 + + ", custom15=" + + custom15 + + ", custom16=" + + custom16 + + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/TaskMonitorServiceImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/TaskMonitorServiceImpl.java index a6a52d010..5a6981cda 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/TaskMonitorServiceImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/TaskMonitorServiceImpl.java @@ -6,52 +6,50 @@ import pro.taskana.mappings.TaskMonitorMapper; import pro.taskana.report.CategoryReport; import pro.taskana.report.ClassificationReport; import pro.taskana.report.CustomFieldValueReport; -import pro.taskana.report.TimestampReport; import pro.taskana.report.TaskStatusReport; +import pro.taskana.report.TimestampReport; import pro.taskana.report.WorkbasketReport; -/** - * This is the implementation of TaskMonitorService. - */ +/** This is the implementation of TaskMonitorService. */ public class TaskMonitorServiceImpl implements TaskMonitorService { - private InternalTaskanaEngine taskanaEngine; - private TaskMonitorMapper taskMonitorMapper; + private InternalTaskanaEngine taskanaEngine; + private TaskMonitorMapper taskMonitorMapper; - TaskMonitorServiceImpl(InternalTaskanaEngine taskanaEngine, TaskMonitorMapper taskMonitorMapper) { - super(); - this.taskanaEngine = taskanaEngine; - this.taskMonitorMapper = taskMonitorMapper; - } + TaskMonitorServiceImpl(InternalTaskanaEngine taskanaEngine, TaskMonitorMapper taskMonitorMapper) { + super(); + this.taskanaEngine = taskanaEngine; + this.taskMonitorMapper = taskMonitorMapper; + } - @Override - public WorkbasketReport.Builder createWorkbasketReportBuilder() { - return new WorkbasketReportBuilderImpl(taskanaEngine, taskMonitorMapper); - } + @Override + public WorkbasketReport.Builder createWorkbasketReportBuilder() { + return new WorkbasketReportBuilderImpl(taskanaEngine, taskMonitorMapper); + } - @Override - public CategoryReport.Builder createCategoryReportBuilder() { - return new CategoryReportBuilderImpl(taskanaEngine, taskMonitorMapper); - } + @Override + public CategoryReport.Builder createCategoryReportBuilder() { + return new CategoryReportBuilderImpl(taskanaEngine, taskMonitorMapper); + } - @Override - public ClassificationReport.Builder createClassificationReportBuilder() { - return new ClassificationReportBuilderImpl(taskanaEngine, taskMonitorMapper); - } + @Override + public ClassificationReport.Builder createClassificationReportBuilder() { + return new ClassificationReportBuilderImpl(taskanaEngine, taskMonitorMapper); + } - @Override - public CustomFieldValueReport.Builder createCustomFieldValueReportBuilder(CustomField customField) { - return new CustomFieldValueReportBuilderImpl(taskanaEngine, taskMonitorMapper, customField); - } + @Override + public CustomFieldValueReport.Builder createCustomFieldValueReportBuilder( + CustomField customField) { + return new CustomFieldValueReportBuilderImpl(taskanaEngine, taskMonitorMapper, customField); + } - @Override - public TaskStatusReport.Builder createTaskStatusReportBuilder() { - return new TaskStatusReportBuilderImpl(taskanaEngine, taskMonitorMapper); - } - - @Override - public TimestampReport.Builder createTimestampReportBuilder() { - return new TimestampReportBuilderImpl(taskanaEngine, taskMonitorMapper); - } + @Override + public TaskStatusReport.Builder createTaskStatusReportBuilder() { + return new TaskStatusReportBuilderImpl(taskanaEngine, taskMonitorMapper); + } + @Override + public TimestampReport.Builder createTimestampReportBuilder() { + return new TimestampReportBuilderImpl(taskanaEngine, taskMonitorMapper); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/TaskQueryImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/TaskQueryImpl.java index 01952ff0e..5865775d9 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/TaskQueryImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/TaskQueryImpl.java @@ -4,7 +4,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; - import org.apache.ibatis.exceptions.PersistenceException; import org.apache.ibatis.session.RowBounds; import org.slf4j.Logger; @@ -29,1697 +28,1868 @@ import pro.taskana.exceptions.WorkbasketNotFoundException; import pro.taskana.impl.util.LoggerUtils; import pro.taskana.security.CurrentUserContext; -/** - * TaskQuery for generating dynamic sql. - */ +/** TaskQuery for generating dynamic sql. */ public class TaskQueryImpl implements TaskQuery { - private static final String ARGUMENT = "Argument '"; - private static final String GET_CUSTOM_ATTRIBUTE_NOT_A_NUMBER_BETWEEN_1_AND_16 = "' to getCustomAttribute does not represent a number between 1 and 16"; - private static final String LINK_TO_MAPPER = "pro.taskana.mappings.QueryMapper.queryTaskSummaries"; - private static final String LINK_TO_MAPPER_DB2 = "pro.taskana.mappings.QueryMapper.queryTaskSummariesDb2"; - private static final String LINK_TO_COUNTER = "pro.taskana.mappings.QueryMapper.countQueryTasks"; - private static final String LINK_TO_COUNTER_DB2 = "pro.taskana.mappings.QueryMapper.countQueryTasksDb2"; - private static final String LINK_TO_VALUEMAPPER = "pro.taskana.mappings.QueryMapper.queryTaskColumnValues"; - private static final String TIME_INTERVAL = "TimeInterval "; - private static final String IS_INVALID = " is invalid."; - private static final Logger LOGGER = LoggerFactory.getLogger(TaskQueryImpl.class); - private InternalTaskanaEngine taskanaEngine; - private TaskServiceImpl taskService; - private TaskQueryColumnName columnName; - private String[] nameIn; - private String[] nameLike; - private String[] externalIdIn; - private String[] externalIdLike; - private String[] creatorIn; - private String[] creatorLike; - private String[] taskIds; - private String[] description; - private String[] note; - private String[] noteLike; - private int[] priority; - private KeyDomain[] workbasketKeyDomainIn; - private String[] workbasketIdIn; - private TaskState[] stateIn; - private String[] classificationIdIn; - private String[] classificationKeyIn; - private String[] classificationKeyLike; - private String[] classificationKeyNotIn; - private String[] classificationCategoryIn; - private String[] classificationCategoryLike; - private String[] classificationNameIn; - private String[] classificationNameLike; - private String[] ownerIn; - private String[] ownerLike; - private Boolean isRead; - private Boolean isTransferred; - private String[] porCompanyIn; - private String[] porCompanyLike; - private String[] porSystemIn; - private String[] porSystemLike; - private String[] porSystemInstanceIn; - private String[] porSystemInstanceLike; - private String[] porTypeIn; - private String[] porTypeLike; - private String[] porValueIn; - private String[] porValueLike; - private String[] parentBusinessProcessIdIn; - private String[] parentBusinessProcessIdLike; - private String[] businessProcessIdIn; - private String[] businessProcessIdLike; - private CallbackState[] callbackStateIn; - private String[] custom1In; - private String[] custom1Like; - private String[] custom2In; - private String[] custom2Like; - private String[] custom3In; - private String[] custom3Like; - private String[] custom4In; - private String[] custom4Like; - private String[] custom5In; - private String[] custom5Like; - private String[] custom6In; - private String[] custom6Like; - private String[] custom7In; - private String[] custom7Like; - private String[] custom8In; - private String[] custom8Like; - private String[] custom9In; - private String[] custom9Like; - private String[] custom10In; - private String[] custom10Like; - private String[] custom11In; - private String[] custom11Like; - private String[] custom12In; - private String[] custom12Like; - private String[] custom13In; - private String[] custom13Like; - private String[] custom14In; - private String[] custom14Like; - private String[] custom15In; - private String[] custom15Like; - private String[] custom16In; - private String[] custom16Like; - private String[] attachmentClassificationKeyIn; - private String[] attachmentClassificationKeyLike; - private String[] attachmentClassificationIdIn; - private String[] attachmentClassificationIdLike; - private String[] attachmentClassificationNameIn; - private String[] attachmentClassificationNameLike; - private String[] attachmentChannelIn; - private String[] attachmentChannelLike; - private String[] attachmentReferenceIn; - private String[] attachmentReferenceLike; - private TimeInterval[] attachmentReceivedIn; - private String[] accessIdIn; - private boolean filterByAccessIdIn; - private TimeInterval[] createdIn; - private TimeInterval[] claimedIn; - private TimeInterval[] completedIn; - private TimeInterval[] modifiedIn; - private TimeInterval[] plannedIn; - private TimeInterval[] dueIn; - private List orderBy; - private List orderColumns; + private static final String ARGUMENT = "Argument '"; + private static final String GET_CUSTOM_ATTRIBUTE_NOT_A_NUMBER_BETWEEN_1_AND_16 = + "' to getCustomAttribute does not represent a number between 1 and 16"; + private static final String LINK_TO_MAPPER = + "pro.taskana.mappings.QueryMapper.queryTaskSummaries"; + private static final String LINK_TO_MAPPER_DB2 = + "pro.taskana.mappings.QueryMapper.queryTaskSummariesDb2"; + private static final String LINK_TO_COUNTER = "pro.taskana.mappings.QueryMapper.countQueryTasks"; + private static final String LINK_TO_COUNTER_DB2 = + "pro.taskana.mappings.QueryMapper.countQueryTasksDb2"; + private static final String LINK_TO_VALUEMAPPER = + "pro.taskana.mappings.QueryMapper.queryTaskColumnValues"; + private static final String TIME_INTERVAL = "TimeInterval "; + private static final String IS_INVALID = " is invalid."; + private static final Logger LOGGER = LoggerFactory.getLogger(TaskQueryImpl.class); + private InternalTaskanaEngine taskanaEngine; + private TaskServiceImpl taskService; + private TaskQueryColumnName columnName; + private String[] nameIn; + private String[] nameLike; + private String[] externalIdIn; + private String[] externalIdLike; + private String[] creatorIn; + private String[] creatorLike; + private String[] taskIds; + private String[] description; + private String[] note; + private String[] noteLike; + private int[] priority; + private KeyDomain[] workbasketKeyDomainIn; + private String[] workbasketIdIn; + private TaskState[] stateIn; + private String[] classificationIdIn; + private String[] classificationKeyIn; + private String[] classificationKeyLike; + private String[] classificationKeyNotIn; + private String[] classificationCategoryIn; + private String[] classificationCategoryLike; + private String[] classificationNameIn; + private String[] classificationNameLike; + private String[] ownerIn; + private String[] ownerLike; + private Boolean isRead; + private Boolean isTransferred; + private String[] porCompanyIn; + private String[] porCompanyLike; + private String[] porSystemIn; + private String[] porSystemLike; + private String[] porSystemInstanceIn; + private String[] porSystemInstanceLike; + private String[] porTypeIn; + private String[] porTypeLike; + private String[] porValueIn; + private String[] porValueLike; + private String[] parentBusinessProcessIdIn; + private String[] parentBusinessProcessIdLike; + private String[] businessProcessIdIn; + private String[] businessProcessIdLike; + private CallbackState[] callbackStateIn; + private String[] custom1In; + private String[] custom1Like; + private String[] custom2In; + private String[] custom2Like; + private String[] custom3In; + private String[] custom3Like; + private String[] custom4In; + private String[] custom4Like; + private String[] custom5In; + private String[] custom5Like; + private String[] custom6In; + private String[] custom6Like; + private String[] custom7In; + private String[] custom7Like; + private String[] custom8In; + private String[] custom8Like; + private String[] custom9In; + private String[] custom9Like; + private String[] custom10In; + private String[] custom10Like; + private String[] custom11In; + private String[] custom11Like; + private String[] custom12In; + private String[] custom12Like; + private String[] custom13In; + private String[] custom13Like; + private String[] custom14In; + private String[] custom14Like; + private String[] custom15In; + private String[] custom15Like; + private String[] custom16In; + private String[] custom16Like; + private String[] attachmentClassificationKeyIn; + private String[] attachmentClassificationKeyLike; + private String[] attachmentClassificationIdIn; + private String[] attachmentClassificationIdLike; + private String[] attachmentClassificationNameIn; + private String[] attachmentClassificationNameLike; + private String[] attachmentChannelIn; + private String[] attachmentChannelLike; + private String[] attachmentReferenceIn; + private String[] attachmentReferenceLike; + private TimeInterval[] attachmentReceivedIn; + private String[] accessIdIn; + private boolean filterByAccessIdIn; + private TimeInterval[] createdIn; + private TimeInterval[] claimedIn; + private TimeInterval[] completedIn; + private TimeInterval[] modifiedIn; + private TimeInterval[] plannedIn; + private TimeInterval[] dueIn; + private List orderBy; + private List orderColumns; - private boolean useDistinctKeyword = false; - private boolean joinWithAttachments = false; - private boolean joinWithClassifications = false; - private boolean joinWithAttachmentClassifications = false; - private boolean addAttachmentColumnsToSelectClauseForOrdering = false; - private boolean addClassificationNameToSelectClauseForOrdering = false; - private boolean addAttachmentClassificationNameToSelectClauseForOrdering = false; + private boolean useDistinctKeyword = false; + private boolean joinWithAttachments = false; + private boolean joinWithClassifications = false; + private boolean joinWithAttachmentClassifications = false; + private boolean addAttachmentColumnsToSelectClauseForOrdering = false; + private boolean addClassificationNameToSelectClauseForOrdering = false; + private boolean addAttachmentClassificationNameToSelectClauseForOrdering = false; - TaskQueryImpl(InternalTaskanaEngine taskanaEngine) { - this.taskanaEngine = taskanaEngine; - this.taskService = (TaskServiceImpl) taskanaEngine.getEngine().getTaskService(); - this.orderBy = new ArrayList<>(); - this.orderColumns = new ArrayList<>(); - this.filterByAccessIdIn = true; + TaskQueryImpl(InternalTaskanaEngine taskanaEngine) { + this.taskanaEngine = taskanaEngine; + this.taskService = (TaskServiceImpl) taskanaEngine.getEngine().getTaskService(); + this.orderBy = new ArrayList<>(); + this.orderColumns = new ArrayList<>(); + this.filterByAccessIdIn = true; + } + + @Override + public TaskQuery idIn(String... taskIds) { + this.taskIds = taskIds; + return this; + } + + @Override + public TaskQuery nameIn(String... names) { + this.nameIn = names; + return this; + } + + @Override + public TaskQuery externalIdIn(String... externalIds) { + this.externalIdIn = externalIds; + return this; + } + + @Override + public TaskQuery externalIdLike(String... externalIds) { + this.externalIdLike = toUpperCopy(externalIds); + return this; + } + + @Override + public TaskQuery nameLike(String... names) { + this.nameLike = toUpperCopy(names); + return this; + } + + @Override + public TaskQuery creatorIn(String... creators) { + this.creatorIn = creators; + return this; + } + + @Override + public TaskQuery creatorLike(String... creators) { + this.creatorLike = toUpperCopy(creators); + return this; + } + + @Override + public TaskQuery createdWithin(TimeInterval... intervals) { + this.createdIn = intervals; + for (TimeInterval ti : intervals) { + if (!ti.isValid()) { + throw new IllegalArgumentException(TIME_INTERVAL + ti + IS_INVALID); + } + } + return this; + } + + @Override + public TaskQuery claimedWithin(TimeInterval... intervals) { + this.claimedIn = intervals; + for (TimeInterval ti : intervals) { + if (!ti.isValid()) { + throw new IllegalArgumentException(TIME_INTERVAL + ti + IS_INVALID); + } + } + return this; + } + + @Override + public TaskQuery completedWithin(TimeInterval... intervals) { + this.completedIn = intervals; + for (TimeInterval ti : intervals) { + if (!ti.isValid()) { + throw new IllegalArgumentException(TIME_INTERVAL + ti + IS_INVALID); + } + } + return this; + } + + @Override + public TaskQuery modifiedWithin(TimeInterval... intervals) { + this.modifiedIn = intervals; + for (TimeInterval ti : intervals) { + if (!ti.isValid()) { + throw new IllegalArgumentException(TIME_INTERVAL + ti + IS_INVALID); + } + } + return this; + } + + @Override + public TaskQuery plannedWithin(TimeInterval... intervals) { + this.plannedIn = intervals; + for (TimeInterval ti : intervals) { + if (!ti.isValid()) { + throw new IllegalArgumentException(TIME_INTERVAL + ti + IS_INVALID); + } + } + return this; + } + + @Override + public TaskQuery dueWithin(TimeInterval... intervals) { + this.dueIn = intervals; + for (TimeInterval ti : intervals) { + if (!ti.isValid()) { + throw new IllegalArgumentException(TIME_INTERVAL + ti + IS_INVALID); + } + } + return this; + } + + @Override + public TaskQuery descriptionLike(String... description) { + this.description = toUpperCopy(description); + return this; + } + + @Override + public TaskQuery noteLike(String... note) { + this.noteLike = toUpperCopy(note); + return this; + } + + @Override + public TaskQuery priorityIn(int... priorities) { + this.priority = priorities; + return this; + } + + @Override + public TaskQuery workbasketKeyDomainIn(KeyDomain... workbasketIdentifiers) { + this.workbasketKeyDomainIn = workbasketIdentifiers; + return this; + } + + @Override + public TaskQuery workbasketIdIn(String... workbasketIds) { + this.workbasketIdIn = workbasketIds; + return this; + } + + @Override + public TaskQuery classificationKeyIn(String... classificationKey) { + this.classificationKeyIn = classificationKey; + return this; + } + + @Override + public TaskQuery classificationKeyNotIn(String... classificationKeys) { + this.classificationKeyNotIn = classificationKeys; + return this; + } + + @Override + public TaskQuery classificationKeyLike(String... classificationKeys) { + this.classificationKeyLike = toUpperCopy(classificationKeys); + return this; + } + + @Override + public TaskQuery classificationIdIn(String... classificationId) { + this.classificationIdIn = classificationId; + return this; + } + + @Override + public TaskQuery classificationCategoryIn(String... classificationCategories) { + this.classificationCategoryIn = classificationCategories; + return this; + } + + @Override + public TaskQuery classificationCategoryLike(String... classificationCategories) { + this.classificationCategoryLike = toUpperCopy(classificationCategories); + return this; + } + + @Override + public TaskQuery ownerIn(String... owners) { + this.ownerIn = owners; + return this; + } + + @Override + public TaskQuery ownerLike(String... owners) { + this.ownerLike = toUpperCopy(owners); + return this; + } + + @Override + public TaskQuery primaryObjectReferenceCompanyIn(String... companies) { + this.porCompanyIn = companies; + return this; + } + + @Override + public TaskQuery primaryObjectReferenceCompanyLike(String... company) { + this.porCompanyLike = toUpperCopy(company); + return this; + } + + @Override + public TaskQuery primaryObjectReferenceSystemIn(String... systems) { + this.porSystemIn = systems; + return this; + } + + @Override + public TaskQuery primaryObjectReferenceSystemLike(String... system) { + this.porSystemLike = toUpperCopy(system); + return this; + } + + @Override + public TaskQuery primaryObjectReferenceSystemInstanceIn(String... systemInstances) { + this.porSystemInstanceIn = systemInstances; + return this; + } + + @Override + public TaskQuery primaryObjectReferenceSystemInstanceLike(String... systemInstance) { + this.porSystemInstanceLike = toUpperCopy(systemInstance); + return this; + } + + @Override + public TaskQuery primaryObjectReferenceTypeIn(String... types) { + this.porTypeIn = types; + return this; + } + + @Override + public TaskQuery primaryObjectReferenceTypeLike(String... type) { + this.porTypeLike = toUpperCopy(type); + return this; + } + + @Override + public TaskQuery primaryObjectReferenceValueIn(String... values) { + this.porValueIn = values; + return this; + } + + @Override + public TaskQuery primaryObjectReferenceValueLike(String... value) { + this.porValueLike = toUpperCopy(value); + return this; + } + + @Override + public TaskQuery readEquals(Boolean isRead) { + this.isRead = isRead; + return this; + } + + @Override + public TaskQuery transferredEquals(Boolean isTransferred) { + this.isTransferred = isTransferred; + return this; + } + + @Override + public TaskQuery parentBusinessProcessIdIn(String... parentBusinessProcessIds) { + this.parentBusinessProcessIdIn = parentBusinessProcessIds; + return this; + } + + @Override + public TaskQuery parentBusinessProcessIdLike(String... parentBusinessProcessId) { + this.parentBusinessProcessIdLike = toUpperCopy(parentBusinessProcessId); + return this; + } + + @Override + public TaskQuery businessProcessIdIn(String... businessProcessIds) { + this.businessProcessIdIn = businessProcessIds; + return this; + } + + @Override + public TaskQuery businessProcessIdLike(String... businessProcessIds) { + this.businessProcessIdLike = toUpperCopy(businessProcessIds); + return this; + } + + @Override + public TaskQuery stateIn(TaskState... states) { + this.stateIn = states; + return this; + } + + @Override + public TaskQuery stateNotIn(TaskState... states) { + // No benefit in introducing a new variable + List stateIn = new LinkedList<>(Arrays.asList(TaskState.values())); + for (TaskState state : states) { + stateIn.remove(state); + } + this.stateIn = stateIn.toArray(new TaskState[0]); + return this; + } + + @Override + public TaskQuery callbackStateIn(CallbackState... states) { + this.callbackStateIn = states; + return this; + } + + @Override + public TaskQuery customAttributeIn(String number, String... strings) + throws InvalidArgumentException { + int num = 0; + try { + num = Integer.parseInt(number); + } catch (NumberFormatException e) { + throw new InvalidArgumentException( + ARGUMENT + number + GET_CUSTOM_ATTRIBUTE_NOT_A_NUMBER_BETWEEN_1_AND_16, e.getCause()); + } + if (strings.length == 0) { + throw new InvalidArgumentException( + "At least one string has to be provided as a search parameter"); } - @Override - public TaskQuery idIn(String... taskIds) { - this.taskIds = taskIds; - return this; + switch (num) { + case 1: + this.custom1In = strings; + break; + case 2: + this.custom2In = strings; + break; + case 3: + this.custom3In = strings; + break; + case 4: + this.custom4In = strings; + break; + case 5: + this.custom5In = strings; + break; + case 6: + this.custom6In = strings; + break; + case 7: + this.custom7In = strings; + break; + case 8: + this.custom8In = strings; + break; + case 9: + this.custom9In = strings; + break; + case 10: + this.custom10In = strings; + break; + case 11: + this.custom11In = strings; + break; + case 12: + this.custom12In = strings; + break; + case 13: + this.custom13In = strings; + break; + case 14: + this.custom14In = strings; + break; + case 15: + this.custom15In = strings; + break; + case 16: + this.custom16In = strings; + break; + default: + throw new InvalidArgumentException( + ARGUMENT + number + GET_CUSTOM_ATTRIBUTE_NOT_A_NUMBER_BETWEEN_1_AND_16); } - @Override - public TaskQuery nameIn(String... names) { - this.nameIn = names; - return this; + return this; + } + + @Override + public TaskQuery customAttributeLike(String number, String... strings) + throws InvalidArgumentException { + int num = 0; + try { + num = Integer.parseInt(number); + } catch (NumberFormatException e) { + throw new InvalidArgumentException( + ARGUMENT + + number + + "' to getCustomAttribute cannot be converted to a number between 1 and 16", + e.getCause()); + } + if (strings.length == 0) { + throw new InvalidArgumentException( + "At least one string has to be provided as a search parameter"); } - @Override - public TaskQuery externalIdIn(String... externalIds) { - this.externalIdIn = externalIds; - return this; + switch (num) { + case 1: + this.custom1Like = toUpperCopy(strings); + break; + case 2: + this.custom2Like = toUpperCopy(strings); + break; + case 3: + this.custom3Like = toUpperCopy(strings); + break; + case 4: + this.custom4Like = toUpperCopy(strings); + break; + case 5: + this.custom5Like = toUpperCopy(strings); + break; + case 6: + this.custom6Like = toUpperCopy(strings); + break; + case 7: + this.custom7Like = toUpperCopy(strings); + break; + case 8: + this.custom8Like = toUpperCopy(strings); + break; + case 9: + this.custom9Like = toUpperCopy(strings); + break; + case 10: + this.custom10Like = toUpperCopy(strings); + break; + case 11: + this.custom11Like = toUpperCopy(strings); + break; + case 12: + this.custom12Like = toUpperCopy(strings); + break; + case 13: + this.custom13Like = toUpperCopy(strings); + break; + case 14: + this.custom14Like = toUpperCopy(strings); + break; + case 15: + this.custom15Like = toUpperCopy(strings); + break; + case 16: + this.custom16Like = toUpperCopy(strings); + break; + default: + throw new InvalidArgumentException( + ARGUMENT + number + GET_CUSTOM_ATTRIBUTE_NOT_A_NUMBER_BETWEEN_1_AND_16); } - @Override - public TaskQuery externalIdLike(String... externalIds) { - this.externalIdLike = toUpperCopy(externalIds); - return this; + return this; + } + + @Override + public TaskQuery attachmentClassificationKeyIn(String... attachmentClassificationKeys) { + joinWithAttachments = true; + this.attachmentClassificationKeyIn = attachmentClassificationKeys; + return this; + } + + @Override + public TaskQuery attachmentClassificationKeyLike(String... attachmentClassificationKey) { + joinWithAttachments = true; + this.attachmentClassificationKeyLike = toUpperCopy(attachmentClassificationKey); + return this; + } + + @Override + public TaskQuery attachmentClassificationIdIn(String... attachmentClassificationId) { + joinWithAttachments = true; + this.attachmentClassificationIdIn = attachmentClassificationId; + return this; + } + + @Override + public TaskQuery attachmentClassificationIdLike(String... attachmentClassificationId) { + joinWithAttachments = true; + this.attachmentClassificationIdLike = toUpperCopy(attachmentClassificationId); + return this; + } + + @Override + public TaskQuery attachmentChannelIn(String... attachmentChannel) { + joinWithAttachments = true; + this.attachmentChannelIn = attachmentChannel; + return this; + } + + @Override + public TaskQuery attachmentChannelLike(String... attachmentChannel) { + joinWithAttachments = true; + this.attachmentChannelLike = toUpperCopy(attachmentChannel); + return this; + } + + @Override + public TaskQuery attachmentReferenceValueIn(String... referenceValue) { + joinWithAttachments = true; + this.attachmentReferenceIn = referenceValue; + return this; + } + + @Override + public TaskQuery attachmentReferenceValueLike(String... referenceValue) { + joinWithAttachments = true; + this.attachmentReferenceLike = toUpperCopy(referenceValue); + return this; + } + + @Override + public TaskQuery attachmentReceivedWithin(TimeInterval... receivedIn) { + joinWithAttachments = true; + this.attachmentReceivedIn = receivedIn; + for (TimeInterval ti : receivedIn) { + if (!ti.isValid()) { + throw new IllegalArgumentException(TIME_INTERVAL + ti + IS_INVALID); + } + } + return this; + } + + @Override + public TaskQuery classificationNameIn(String... classificationNames) { + joinWithClassifications = true; + this.classificationNameIn = classificationNames; + return this; + } + + @Override + public TaskQuery classificationNameLike(String... classificationNames) { + joinWithClassifications = true; + this.classificationNameLike = toUpperCopy(classificationNames); + return this; + } + + @Override + public TaskQuery attachmentClassificationNameIn(String... attachmentClassificationName) { + joinWithAttachmentClassifications = true; + this.attachmentClassificationNameIn = attachmentClassificationName; + return this; + } + + @Override + public TaskQuery attachmentClassificationNameLike(String... attachmentClassificationName) { + joinWithAttachmentClassifications = true; + this.attachmentClassificationNameLike = toUpperCopy(attachmentClassificationName); + return this; + } + + @Override + public TaskQuery orderByClassificationName(SortDirection sortDirection) { + joinWithClassifications = true; + addClassificationNameToSelectClauseForOrdering = true; + return DB.DB2.dbProductId.equals(getDatabaseId()) + ? addOrderCriteria("CNAME", sortDirection) + : addOrderCriteria("c.NAME", sortDirection); + } + + @Override + public TaskQuery orderByAttachmentClassificationName(SortDirection sortDirection) { + joinWithAttachments = true; + addAttachmentClassificationNameToSelectClauseForOrdering = true; + return DB.DB2.dbProductId.equals(getDatabaseId()) + ? addOrderCriteria("ACNAME", sortDirection) + : addOrderCriteria("ac.NAME", sortDirection); + } + + @Override + public TaskQuery orderByClassificationKey(SortDirection sortDirection) { + return DB.DB2.dbProductId.equals(getDatabaseId()) + ? addOrderCriteria("TCLASSIFICATION_KEY", sortDirection) + : addOrderCriteria("t.CLASSIFICATION_KEY", sortDirection); + } + + @Override + public TaskQuery orderByDomain(SortDirection sortDirection) { + return addOrderCriteria("DOMAIN", sortDirection); + } + + @Override + public TaskQuery orderByPlanned(SortDirection sortDirection) { + return addOrderCriteria("PLANNED", sortDirection); + } + + @Override + public TaskQuery orderByDue(SortDirection sortDirection) { + return addOrderCriteria("DUE", sortDirection); + } + + @Override + public TaskQuery orderByModified(SortDirection sortDirection) { + return addOrderCriteria("MODIFIED", sortDirection); + } + + @Override + public TaskQuery orderByName(SortDirection sortDirection) { + return addOrderCriteria("NAME", sortDirection); + } + + @Override + public TaskQuery orderByCreator(SortDirection sortDirection) { + return addOrderCriteria("CREATOR", sortDirection); + } + + @Override + public TaskQuery orderByOwner(SortDirection sortDirection) { + return addOrderCriteria("OWNER", sortDirection); + } + + @Override + public TaskQuery orderByPrimaryObjectReferenceCompany(SortDirection sortDirection) { + return addOrderCriteria("POR_COMPANY", sortDirection); + } + + @Override + public TaskQuery orderByPrimaryObjectReferenceSystem(SortDirection sortDirection) { + return addOrderCriteria("POR_SYSTEM", sortDirection); + } + + @Override + public TaskQuery orderByPrimaryObjectReferenceSystemInstance(SortDirection sortDirection) { + return addOrderCriteria("POR_INSTANCE", sortDirection); + } + + @Override + public TaskQuery orderByPrimaryObjectReferenceType(SortDirection sortDirection) { + return addOrderCriteria("POR_TYPE", sortDirection); + } + + @Override + public TaskQuery orderByPrimaryObjectReferenceValue(SortDirection sortDirection) { + return addOrderCriteria("POR_VALUE", sortDirection); + } + + @Override + public TaskQuery orderByPriority(SortDirection sortDirection) { + return addOrderCriteria("PRIORITY", sortDirection); + } + + @Override + public TaskQuery orderByState(SortDirection sortDirection) { + return addOrderCriteria("STATE", sortDirection); + } + + @Override + public TaskQuery orderByWorkbasketKey(SortDirection sortDirection) { + return addOrderCriteria("WORKBASKET_KEY", sortDirection); + } + + @Override + public TaskQuery orderByWorkbasketId(SortDirection sortDirection) { + return addOrderCriteria("WORKBASKET_ID", sortDirection); + } + + @Override + public TaskQuery orderByAttachmentClassificationKey(SortDirection sortDirection) { + joinWithAttachments = true; + addAttachmentColumnsToSelectClauseForOrdering = true; + return DB.DB2.dbProductId.equals(getDatabaseId()) + ? addOrderCriteria("ACLASSIFICATION_KEY", sortDirection) + : addOrderCriteria("a.CLASSIFICATION_KEY", sortDirection); + } + + @Override + public TaskQuery orderByAttachmentClassificationId(SortDirection sortDirection) { + joinWithAttachments = true; + addAttachmentColumnsToSelectClauseForOrdering = true; + return DB.DB2.dbProductId.equals(getDatabaseId()) + ? addOrderCriteria("ACLASSIFICATION_ID", sortDirection) + : addOrderCriteria("a.CLASSIFICATION_ID", sortDirection); + } + + @Override + public TaskQuery orderByAttachmentChannel(SortDirection sortDirection) { + joinWithAttachments = true; + addAttachmentColumnsToSelectClauseForOrdering = true; + return addOrderCriteria("CHANNEL", sortDirection); + } + + @Override + public TaskQuery orderByAttachmentReference(SortDirection sortDirection) { + joinWithAttachments = true; + addAttachmentColumnsToSelectClauseForOrdering = true; + return addOrderCriteria("REF_VALUE", sortDirection); + } + + @Override + public TaskQuery orderByAttachmentReceived(SortDirection sortDirection) { + joinWithAttachments = true; + addAttachmentColumnsToSelectClauseForOrdering = true; + return addOrderCriteria("RECEIVED", sortDirection); + } + + @Override + public TaskQuery orderByNote(SortDirection sortDirection) { + return addOrderCriteria("NOTE", sortDirection); + } + + @Override + public TaskQuery orderByCustomAttribute(String number, SortDirection sortDirection) + throws InvalidArgumentException { + int num = 0; + try { + num = Integer.parseInt(number); + } catch (NumberFormatException e) { + throw new InvalidArgumentException( + ARGUMENT + + number + + "' to getCustomAttribute cannot be converted to a number between 1 and 16", + e.getCause()); } - @Override - public TaskQuery nameLike(String... names) { - this.nameLike = toUpperCopy(names); - return this; + switch (num) { + case 1: + return addOrderCriteria("CUSTOM_1", sortDirection); + case 2: + return addOrderCriteria("CUSTOM_2", sortDirection); + case 3: + return addOrderCriteria("CUSTOM_3", sortDirection); + case 4: + return addOrderCriteria("CUSTOM_4", sortDirection); + case 5: + return addOrderCriteria("CUSTOM_5", sortDirection); + case 6: + return addOrderCriteria("CUSTOM_6", sortDirection); + case 7: + return addOrderCriteria("CUSTOM_7", sortDirection); + case 8: + return addOrderCriteria("CUSTOM_8", sortDirection); + case 9: + return addOrderCriteria("CUSTOM_9", sortDirection); + case 10: + return addOrderCriteria("CUSTOM_10", sortDirection); + case 11: + return addOrderCriteria("CUSTOM_11", sortDirection); + case 12: + return addOrderCriteria("CUSTOM_12", sortDirection); + case 13: + return addOrderCriteria("CUSTOM_13", sortDirection); + case 14: + return addOrderCriteria("CUSTOM_14", sortDirection); + case 15: + return addOrderCriteria("CUSTOM_15", sortDirection); + case 16: + return addOrderCriteria("CUSTOM_16", sortDirection); + default: + throw new InvalidArgumentException( + ARGUMENT + number + GET_CUSTOM_ATTRIBUTE_NOT_A_NUMBER_BETWEEN_1_AND_16); } + } - @Override - public TaskQuery creatorIn(String... creators) { - this.creatorIn = creators; - return this; + @Override + public TaskQuery orderByBusinessProcessId(SortDirection sortDirection) { + return addOrderCriteria("BUSINESS_PROCESS_ID", sortDirection); + } + + @Override + public TaskQuery orderByClaimed(SortDirection sortDirection) { + return addOrderCriteria("CLAIMED", sortDirection); + } + + @Override + public TaskQuery orderByCompleted(SortDirection sortDirection) { + return addOrderCriteria("COMPLETED", sortDirection); + } + + @Override + public TaskQuery orderByCreated(SortDirection sortDirection) { + return addOrderCriteria("CREATED", sortDirection); + } + + @Override + public TaskQuery orderByParentBusinessProcessId(SortDirection sortDirection) { + return addOrderCriteria("PARENT_BUSINESS_PROCESS_ID", sortDirection); + } + + @Override + public ObjectReferenceQuery createObjectReferenceQuery() { + return new ObjectReferenceQueryImpl(taskanaEngine); + } + + @Override + public List list() { + List result = new ArrayList<>(); + try { + LOGGER.debug("entry to list(), this = {}", this); + taskanaEngine.openConnection(); + checkOpenAndReadPermissionForSpecifiedWorkbaskets(); + setupJoinAndOrderParameters(); + setupAccessIds(); + List tasks = + taskanaEngine.getSqlSession().selectList(getLinkToMapperScript(), this); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "mapper returned {} resulting Objects: {} ", + tasks.size(), + LoggerUtils.listToString(tasks)); + } + result = taskService.augmentTaskSummariesByContainedSummaries(tasks); + return result; + } finally { + taskanaEngine.returnConnection(); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "exit from list(). Returning {} resulting Objects: {} ", + result.size(), + LoggerUtils.listToString(result)); + } } + } - @Override - public TaskQuery creatorLike(String... creators) { - this.creatorLike = toUpperCopy(creators); - return this; - } + public String getLinkToMapperScript() { + return DB.DB2.dbProductId.equals(getDatabaseId()) ? LINK_TO_MAPPER_DB2 : LINK_TO_MAPPER; + } - @Override - public TaskQuery createdWithin(TimeInterval... intervals) { - this.createdIn = intervals; - for (TimeInterval ti : intervals) { - if (!ti.isValid()) { - throw new IllegalArgumentException(TIME_INTERVAL + ti + IS_INVALID); - } - } - return this; - } + public String getLinkToCounterTaskScript() { + return DB.DB2.dbProductId.equals(getDatabaseId()) ? LINK_TO_COUNTER_DB2 : LINK_TO_COUNTER; + } - @Override - public TaskQuery claimedWithin(TimeInterval... intervals) { - this.claimedIn = intervals; - for (TimeInterval ti : intervals) { - if (!ti.isValid()) { - throw new IllegalArgumentException(TIME_INTERVAL + ti + IS_INVALID); - } - } - return this; - } + @Override + public List listValues(TaskQueryColumnName columnName, SortDirection sortDirection) { + LOGGER.debug("Entry to listValues(dbColumnName={}) this = {}", columnName, this); + List result = new ArrayList<>(); + try { + taskanaEngine.openConnection(); + this.columnName = columnName; + this.orderBy.clear(); + this.addOrderCriteria(columnName.toString(), sortDirection); + checkOpenAndReadPermissionForSpecifiedWorkbaskets(); + setupAccessIds(); - @Override - public TaskQuery completedWithin(TimeInterval... intervals) { - this.completedIn = intervals; - for (TimeInterval ti : intervals) { - if (!ti.isValid()) { - throw new IllegalArgumentException(TIME_INTERVAL + ti + IS_INVALID); - } - } - return this; - } - - @Override - public TaskQuery modifiedWithin(TimeInterval... intervals) { - this.modifiedIn = intervals; - for (TimeInterval ti : intervals) { - if (!ti.isValid()) { - throw new IllegalArgumentException(TIME_INTERVAL + ti + IS_INVALID); - } - } - return this; - } - - @Override - public TaskQuery plannedWithin(TimeInterval... intervals) { - this.plannedIn = intervals; - for (TimeInterval ti : intervals) { - if (!ti.isValid()) { - throw new IllegalArgumentException(TIME_INTERVAL + ti + IS_INVALID); - } - } - return this; - } - - @Override - public TaskQuery dueWithin(TimeInterval... intervals) { - this.dueIn = intervals; - for (TimeInterval ti : intervals) { - if (!ti.isValid()) { - throw new IllegalArgumentException(TIME_INTERVAL + ti + IS_INVALID); - } - } - return this; - } - - @Override - public TaskQuery descriptionLike(String... description) { - this.description = toUpperCopy(description); - return this; - } - - @Override - public TaskQuery noteLike(String... note) { - this.noteLike = toUpperCopy(note); - return this; - } - - @Override - public TaskQuery priorityIn(int... priorities) { - this.priority = priorities; - return this; - } - - @Override - public TaskQuery workbasketKeyDomainIn(KeyDomain... workbasketIdentifiers) { - this.workbasketKeyDomainIn = workbasketIdentifiers; - return this; - } - - @Override - public TaskQuery workbasketIdIn(String... workbasketIds) { - this.workbasketIdIn = workbasketIds; - return this; - } - - @Override - public TaskQuery classificationKeyIn(String... classificationKey) { - this.classificationKeyIn = classificationKey; - return this; - } - - @Override - public TaskQuery classificationKeyNotIn(String... classificationKeys) { - this.classificationKeyNotIn = classificationKeys; - return this; - } - - @Override - public TaskQuery classificationKeyLike(String... classificationKeys) { - this.classificationKeyLike = toUpperCopy(classificationKeys); - return this; - } - - @Override - public TaskQuery classificationIdIn(String... classificationId) { - this.classificationIdIn = classificationId; - return this; - } - - @Override - public TaskQuery classificationCategoryIn(String... classificationCategories) { - this.classificationCategoryIn = classificationCategories; - return this; - } - - @Override - public TaskQuery classificationCategoryLike(String... classificationCategories) { - this.classificationCategoryLike = toUpperCopy(classificationCategories); - return this; - } - - @Override - public TaskQuery ownerIn(String... owners) { - this.ownerIn = owners; - return this; - } - - @Override - public TaskQuery ownerLike(String... owners) { - this.ownerLike = toUpperCopy(owners); - return this; - } - - @Override - public TaskQuery primaryObjectReferenceCompanyIn(String... companies) { - this.porCompanyIn = companies; - return this; - } - - @Override - public TaskQuery primaryObjectReferenceCompanyLike(String... company) { - this.porCompanyLike = toUpperCopy(company); - return this; - } - - @Override - public TaskQuery primaryObjectReferenceSystemIn(String... systems) { - this.porSystemIn = systems; - return this; - } - - @Override - public TaskQuery primaryObjectReferenceSystemLike(String... system) { - this.porSystemLike = toUpperCopy(system); - return this; - } - - @Override - public TaskQuery primaryObjectReferenceSystemInstanceIn(String... systemInstances) { - this.porSystemInstanceIn = systemInstances; - return this; - } - - @Override - public TaskQuery primaryObjectReferenceSystemInstanceLike(String... systemInstance) { - this.porSystemInstanceLike = toUpperCopy(systemInstance); - return this; - } - - @Override - public TaskQuery primaryObjectReferenceTypeIn(String... types) { - this.porTypeIn = types; - return this; - } - - @Override - public TaskQuery primaryObjectReferenceTypeLike(String... type) { - this.porTypeLike = toUpperCopy(type); - return this; - } - - @Override - public TaskQuery primaryObjectReferenceValueIn(String... values) { - this.porValueIn = values; - return this; - } - - @Override - public TaskQuery primaryObjectReferenceValueLike(String... value) { - this.porValueLike = toUpperCopy(value); - return this; - } - - @Override - public TaskQuery readEquals(Boolean isRead) { - this.isRead = isRead; - return this; - } - - @Override - public TaskQuery transferredEquals(Boolean isTransferred) { - this.isTransferred = isTransferred; - return this; - } - - @Override - public TaskQuery parentBusinessProcessIdIn(String... parentBusinessProcessIds) { - this.parentBusinessProcessIdIn = parentBusinessProcessIds; - return this; - } - - @Override - public TaskQuery parentBusinessProcessIdLike(String... parentBusinessProcessId) { - this.parentBusinessProcessIdLike = toUpperCopy(parentBusinessProcessId); - return this; - } - - @Override - public TaskQuery businessProcessIdIn(String... businessProcessIds) { - this.businessProcessIdIn = businessProcessIds; - return this; - } - - @Override - public TaskQuery businessProcessIdLike(String... businessProcessIds) { - this.businessProcessIdLike = toUpperCopy(businessProcessIds); - return this; - } - - @Override - public TaskQuery stateIn(TaskState... states) { - this.stateIn = states; - return this; - } - - @Override - public TaskQuery stateNotIn(TaskState... states) { - // No benefit in introducing a new variable - List stateIn = new LinkedList<>(Arrays.asList(TaskState.values())); - for (TaskState state : states) { - stateIn.remove(state); - } - this.stateIn = stateIn.toArray(new TaskState[0]); - return this; - } - - @Override - public TaskQuery callbackStateIn(CallbackState... states) { - this.callbackStateIn = states; - return this; - } - - @Override - public TaskQuery customAttributeIn(String number, String... strings) throws InvalidArgumentException { - int num = 0; - try { - num = Integer.parseInt(number); - } catch (NumberFormatException e) { - throw new InvalidArgumentException( - ARGUMENT + number + GET_CUSTOM_ATTRIBUTE_NOT_A_NUMBER_BETWEEN_1_AND_16, - e.getCause()); - } - if (strings.length == 0) { - throw new InvalidArgumentException( - "At least one string has to be provided as a search parameter"); - } - - switch (num) { - case 1: - this.custom1In = strings; - break; - case 2: - this.custom2In = strings; - break; - case 3: - this.custom3In = strings; - break; - case 4: - this.custom4In = strings; - break; - case 5: - this.custom5In = strings; - break; - case 6: - this.custom6In = strings; - break; - case 7: - this.custom7In = strings; - break; - case 8: - this.custom8In = strings; - break; - case 9: - this.custom9In = strings; - break; - case 10: - this.custom10In = strings; - break; - case 11: - this.custom11In = strings; - break; - case 12: - this.custom12In = strings; - break; - case 13: - this.custom13In = strings; - break; - case 14: - this.custom14In = strings; - break; - case 15: - this.custom15In = strings; - break; - case 16: - this.custom16In = strings; - break; - default: - throw new InvalidArgumentException( - ARGUMENT + number + GET_CUSTOM_ATTRIBUTE_NOT_A_NUMBER_BETWEEN_1_AND_16); - } - - return this; - } - - @Override - public TaskQuery customAttributeLike(String number, String... strings) throws InvalidArgumentException { - int num = 0; - try { - num = Integer.parseInt(number); - } catch (NumberFormatException e) { - throw new InvalidArgumentException( - ARGUMENT + number + "' to getCustomAttribute cannot be converted to a number between 1 and 16", - e.getCause()); - } - if (strings.length == 0) { - throw new InvalidArgumentException( - "At least one string has to be provided as a search parameter"); - } - - switch (num) { - case 1: - this.custom1Like = toUpperCopy(strings); - break; - case 2: - this.custom2Like = toUpperCopy(strings); - break; - case 3: - this.custom3Like = toUpperCopy(strings); - break; - case 4: - this.custom4Like = toUpperCopy(strings); - break; - case 5: - this.custom5Like = toUpperCopy(strings); - break; - case 6: - this.custom6Like = toUpperCopy(strings); - break; - case 7: - this.custom7Like = toUpperCopy(strings); - break; - case 8: - this.custom8Like = toUpperCopy(strings); - break; - case 9: - this.custom9Like = toUpperCopy(strings); - break; - case 10: - this.custom10Like = toUpperCopy(strings); - break; - case 11: - this.custom11Like = toUpperCopy(strings); - break; - case 12: - this.custom12Like = toUpperCopy(strings); - break; - case 13: - this.custom13Like = toUpperCopy(strings); - break; - case 14: - this.custom14Like = toUpperCopy(strings); - break; - case 15: - this.custom15Like = toUpperCopy(strings); - break; - case 16: - this.custom16Like = toUpperCopy(strings); - break; - default: - throw new InvalidArgumentException( - ARGUMENT + number + GET_CUSTOM_ATTRIBUTE_NOT_A_NUMBER_BETWEEN_1_AND_16); - } - - return this; - } - - @Override - public TaskQuery attachmentClassificationKeyIn(String... attachmentClassificationKeys) { - joinWithAttachments = true; - this.attachmentClassificationKeyIn = attachmentClassificationKeys; - return this; - } - - @Override - public TaskQuery attachmentClassificationKeyLike(String... attachmentClassificationKey) { - joinWithAttachments = true; - this.attachmentClassificationKeyLike = toUpperCopy(attachmentClassificationKey); - return this; - } - - @Override - public TaskQuery attachmentClassificationIdIn(String... attachmentClassificationId) { - joinWithAttachments = true; - this.attachmentClassificationIdIn = attachmentClassificationId; - return this; - } - - @Override - public TaskQuery attachmentClassificationIdLike(String... attachmentClassificationId) { - joinWithAttachments = true; - this.attachmentClassificationIdLike = toUpperCopy(attachmentClassificationId); - return this; - } - - @Override - public TaskQuery attachmentChannelIn(String... attachmentChannel) { - joinWithAttachments = true; - this.attachmentChannelIn = attachmentChannel; - return this; - } - - @Override - public TaskQuery attachmentChannelLike(String... attachmentChannel) { - joinWithAttachments = true; - this.attachmentChannelLike = toUpperCopy(attachmentChannel); - return this; - } - - @Override - public TaskQuery attachmentReferenceValueIn(String... referenceValue) { - joinWithAttachments = true; - this.attachmentReferenceIn = referenceValue; - return this; - } - - @Override - public TaskQuery attachmentReferenceValueLike(String... referenceValue) { - joinWithAttachments = true; - this.attachmentReferenceLike = toUpperCopy(referenceValue); - return this; - } - - @Override - public TaskQuery attachmentReceivedWithin(TimeInterval... receivedIn) { - joinWithAttachments = true; - this.attachmentReceivedIn = receivedIn; - for (TimeInterval ti : receivedIn) { - if (!ti.isValid()) { - throw new IllegalArgumentException(TIME_INTERVAL + ti + IS_INVALID); - } - } - return this; - } - - @Override - public TaskQuery classificationNameIn(String... classificationNames) { + if (columnName.equals(TaskQueryColumnName.CLASSIFICATION_NAME)) { joinWithClassifications = true; - this.classificationNameIn = classificationNames; - return this; - } + } - @Override - public TaskQuery classificationNameLike(String... classificationNames) { - joinWithClassifications = true; - this.classificationNameLike = toUpperCopy(classificationNames); - return this; - } - - @Override - public TaskQuery attachmentClassificationNameIn(String... attachmentClassificationName) { + if (columnName.equals(TaskQueryColumnName.A_CLASSIFICATION_NAME)) { joinWithAttachmentClassifications = true; - this.attachmentClassificationNameIn = attachmentClassificationName; - return this; - } + } - @Override - public TaskQuery attachmentClassificationNameLike(String... attachmentClassificationName) { - joinWithAttachmentClassifications = true; - this.attachmentClassificationNameLike = toUpperCopy(attachmentClassificationName); - return this; - } - - @Override - public TaskQuery orderByClassificationName(SortDirection sortDirection) { - joinWithClassifications = true; - addClassificationNameToSelectClauseForOrdering = true; - return DB.DB2.dbProductId.equals(getDatabaseId()) - ? addOrderCriteria("CNAME", sortDirection) - : addOrderCriteria("c.NAME", sortDirection); - } - - private String getDatabaseId() { - return this.taskanaEngine.getSqlSession().getConfiguration().getDatabaseId(); - } - - @Override - public TaskQuery orderByAttachmentClassificationName(SortDirection sortDirection) { + if (columnName.isAttachmentColumn()) { joinWithAttachments = true; - addAttachmentClassificationNameToSelectClauseForOrdering = true; - return DB.DB2.dbProductId.equals(getDatabaseId()) - ? addOrderCriteria("ACNAME", sortDirection) - : addOrderCriteria("ac.NAME", sortDirection); + } + + setupJoinAndOrderParameters(); + result = taskanaEngine.getSqlSession().selectList(LINK_TO_VALUEMAPPER, this); + return result; + } finally { + taskanaEngine.returnConnection(); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "Exit from listValues. Returning {} resulting Objects: {} ", + result.size(), + LoggerUtils.listToString(result)); + } + } + } + + @Override + public List list(int offset, int limit) { + LOGGER.debug("entry to list(offset = {}, limit = {}), this = {}", offset, limit, this); + List result = new ArrayList<>(); + try { + taskanaEngine.openConnection(); + checkOpenAndReadPermissionForSpecifiedWorkbaskets(); + setupAccessIds(); + setupJoinAndOrderParameters(); + RowBounds rowBounds = new RowBounds(offset, limit); + List tasks = + taskanaEngine.getSqlSession().selectList(getLinkToMapperScript(), this, rowBounds); + result = taskService.augmentTaskSummariesByContainedSummaries(tasks); + return result; + } catch (PersistenceException e) { + if (e.getMessage().contains("ERRORCODE=-4470")) { + TaskanaRuntimeException ex = + new TaskanaRuntimeException( + "The offset beginning was set over the amount of result-rows.", e.getCause()); + ex.setStackTrace(e.getStackTrace()); + throw ex; + } + throw e; + } finally { + taskanaEngine.returnConnection(); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "exit from list(offset,limit). Returning {} resulting Objects: {} ", + result.size(), + LoggerUtils.listToString(result)); + } + } + } + + @Override + public TaskSummary single() { + LOGGER.debug("entry to single(), this = {}", this); + TaskSummary result = null; + try { + taskanaEngine.openConnection(); + checkOpenAndReadPermissionForSpecifiedWorkbaskets(); + setupAccessIds(); + setupJoinAndOrderParameters(); + TaskSummaryImpl taskSummaryImpl = + taskanaEngine.getSqlSession().selectOne(getLinkToMapperScript(), this); + if (taskSummaryImpl == null) { + return null; + } + List tasks = new ArrayList<>(); + tasks.add(taskSummaryImpl); + List augmentedList = taskService.augmentTaskSummariesByContainedSummaries(tasks); + result = augmentedList.get(0); + + return result; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from single(). Returning result {} ", result); + } + } + + @Override + public long count() { + LOGGER.debug("entry to count(), this = {}", this); + Long rowCount = null; + try { + taskanaEngine.openConnection(); + checkOpenAndReadPermissionForSpecifiedWorkbaskets(); + setupAccessIds(); + setupJoinAndOrderParameters(); + rowCount = taskanaEngine.getSqlSession().selectOne(getLinkToCounterTaskScript(), this); + return (rowCount == null) ? 0L : rowCount; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from count(). Returning result {} ", rowCount); + } + } + + public boolean isUseDistinctKeyword() { + return useDistinctKeyword; + } + + public void setUseDistinctKeyword(boolean useDistinctKeyword) { + this.useDistinctKeyword = useDistinctKeyword; + } + + public boolean isJoinWithAttachments() { + return joinWithAttachments; + } + + public void setJoinWithAttachments(boolean joinWithAttachments) { + this.joinWithAttachments = joinWithAttachments; + } + + public boolean isJoinWithClassifications() { + return joinWithClassifications; + } + + public void setJoinWithClassifications(boolean joinWithClassifications) { + this.joinWithClassifications = joinWithClassifications; + } + + public boolean isJoinWithAttachmentsClassifications() { + return joinWithAttachmentClassifications; + } + + public void setJoinWithAttachmentsClassifications(boolean joinWithAttachmentsClassifications) { + this.joinWithAttachmentClassifications = joinWithAttachmentsClassifications; + } + + public boolean isAddAttachmentColumnsToSelectClauseForOrdering() { + return addAttachmentColumnsToSelectClauseForOrdering; + } + + public void setAddAttachmentColumnsToSelectClauseForOrdering( + boolean addAttachmentColumnsToSelectClauseForOrdering) { + this.addAttachmentColumnsToSelectClauseForOrdering = + addAttachmentColumnsToSelectClauseForOrdering; + } + + public String[] getTaskIds() { + return taskIds; + } + + public String[] getNameIn() { + return nameIn; + } + + public String[] getExternalIdIn() { + return externalIdIn; + } + + public String[] getExternalIdLike() { + return externalIdLike; + } + + public String[] getCreatorIn() { + return creatorIn; + } + + public String[] getCreatorLike() { + return creatorLike; + } + + public String[] getDescription() { + return description; + } + + public int[] getPriority() { + return priority; + } + + public TaskState[] getStateIn() { + return stateIn; + } + + public String[] getOwnerIn() { + return ownerIn; + } + + public String[] getOwnerLike() { + return ownerLike; + } + + public Boolean getIsRead() { + return isRead; + } + + public Boolean getIsTransferred() { + return isTransferred; + } + + public String[] getPorCompanyIn() { + return porCompanyIn; + } + + public String[] getPorCompanyLike() { + return porCompanyLike; + } + + public String[] getPorSystemIn() { + return porSystemIn; + } + + public String[] getPorSystemLike() { + return porSystemLike; + } + + public String[] getPorSystemInstanceIn() { + return porSystemInstanceIn; + } + + public String[] getPorSystemInstanceLike() { + return porSystemInstanceLike; + } + + public String[] getPorTypeIn() { + return porTypeIn; + } + + public String[] getPorTypeLike() { + return porTypeLike; + } + + public String[] getPorValueIn() { + return porValueIn; + } + + public String[] getPorValueLike() { + return porValueLike; + } + + public List getOrderBy() { + return orderBy; + } + + public List getOrderColumns() { + return orderColumns; + } + + public TimeInterval[] getCreatedIn() { + return createdIn; + } + + public TaskServiceImpl getTaskService() { + return taskService; + } + + public String[] getNote() { + return note; + } + + public String[] getNoteLike() { + return noteLike; + } + + public String[] getParentBusinessProcessIdIn() { + return parentBusinessProcessIdIn; + } + + public String[] getParentBusinessProcessIdLike() { + return parentBusinessProcessIdLike; + } + + public String[] getBusinessProcessIdIn() { + return businessProcessIdIn; + } + + public String[] getBusinessProcessIdLike() { + return businessProcessIdLike; + } + + public String[] getCustom1In() { + return custom1In; + } + + public String[] getCustom1Like() { + return custom1Like; + } + + public String[] getCustom2In() { + return custom2In; + } + + public String[] getCustom2Like() { + return custom2Like; + } + + public String[] getCustom3In() { + return custom3In; + } + + public String[] getCustom3Like() { + return custom3Like; + } + + public String[] getCustom4In() { + return custom4In; + } + + public String[] getCustom4Like() { + return custom4Like; + } + + public String[] getCustom5In() { + return custom5In; + } + + public String[] getCustom5Like() { + return custom5Like; + } + + public String[] getCustom6In() { + return custom6In; + } + + public String[] getCustom6Like() { + return custom6Like; + } + + public String[] getCustom7In() { + return custom7In; + } + + public String[] getCustom7Like() { + return custom7Like; + } + + public String[] getCustom8In() { + return custom8In; + } + + public String[] getCustom8Like() { + return custom8Like; + } + + public String[] getCustom9In() { + return custom9In; + } + + public String[] getCustom9Like() { + return custom9Like; + } + + public String[] getCustom10In() { + return custom10In; + } + + public String[] getCustom10Like() { + return custom10Like; + } + + public String[] getCustom11In() { + return custom11In; + } + + public String[] getCustom11Like() { + return custom11Like; + } + + public String[] getCustom12In() { + return custom12In; + } + + public String[] getCustom12Like() { + return custom12Like; + } + + public String[] getCustom13In() { + return custom13In; + } + + public String[] getCustom13Like() { + return custom13Like; + } + + public String[] getCustom14In() { + return custom14In; + } + + public String[] getCustom14Like() { + return custom14Like; + } + + public String[] getCustom15In() { + return custom15In; + } + + public String[] getCustom15Like() { + return custom15Like; + } + + public String[] getCustom16In() { + return custom16In; + } + + public String[] getCustom16Like() { + return custom16Like; + } + + public String[] getClassificationCategoryIn() { + return classificationCategoryIn; + } + + public String[] getClassificationCategoryLike() { + return classificationCategoryLike; + } + + public TimeInterval[] getClaimedIn() { + return claimedIn; + } + + public TimeInterval[] getCompletedIn() { + return completedIn; + } + + public TimeInterval[] getModifiedIn() { + return modifiedIn; + } + + public TimeInterval[] getPlannedIn() { + return plannedIn; + } + + public TimeInterval[] getDueIn() { + return dueIn; + } + + public String[] getNameLike() { + return nameLike; + } + + public String[] getClassificationKeyIn() { + return classificationKeyIn; + } + + public String[] getClassificationKeyNotIn() { + return classificationKeyNotIn; + } + + public String[] getClassificationKeyLike() { + return classificationKeyLike; + } + + public String[] getClassificationIdIn() { + return classificationIdIn; + } + + public KeyDomain[] getWorkbasketKeyDomainIn() { + return workbasketKeyDomainIn; + } + + public String[] getWorkbasketIdIn() { + return workbasketIdIn; + } + + public TaskQueryColumnName getColumnName() { + return columnName; + } + + public String[] getAttachmentClassificationKeyIn() { + return attachmentClassificationKeyIn; + } + + public void setAttachmentClassificationKeyIn(String[] attachmentClassificationKeyIn) { + this.attachmentClassificationKeyIn = attachmentClassificationKeyIn; + } + + public String[] getAttachmentClassificationKeyLike() { + return attachmentClassificationKeyLike; + } + + public void setAttachmentClassificationKeyLike(String[] attachmentClassificationKeyLike) { + this.attachmentClassificationKeyLike = attachmentClassificationKeyLike; + } + + public String[] getAttachmentClassificationIdIn() { + return attachmentClassificationIdIn; + } + + public void setAttachmentClassificationIdIn(String[] attachmentClassificationIdIn) { + this.attachmentClassificationIdIn = attachmentClassificationIdIn; + } + + public String[] getAttachmentClassificationIdLike() { + return attachmentClassificationIdLike; + } + + public void setAttachmentClassificationIdLike(String[] attachmentclassificationIdLike) { + this.attachmentClassificationIdLike = attachmentclassificationIdLike; + } + + public String[] getAttachmentChannelIn() { + return attachmentChannelIn; + } + + public void setAttachmentChannelIn(String[] attachmentChannelIn) { + this.attachmentChannelIn = attachmentChannelIn; + } + + public String[] getAttachmentChannelLike() { + return attachmentChannelLike; + } + + public void setAttachmentChannelLike(String[] attachmentChannelLike) { + this.attachmentChannelLike = attachmentChannelLike; + } + + public String[] getAttachmentReferenceIn() { + return attachmentReferenceIn; + } + + public void setAttachmentReferenceIn(String[] attachmentReferenceIn) { + this.attachmentReferenceIn = attachmentReferenceIn; + } + + public String[] getAttachmentReferenceLike() { + return attachmentReferenceLike; + } + + public void setAttachmentReferenceLike(String[] attachmentReferenceLike) { + this.attachmentReferenceLike = attachmentReferenceLike; + } + + public TimeInterval[] getAttachmentReceivedIn() { + return attachmentReceivedIn; + } + + public void setAttachmentReceivedIn(TimeInterval[] attachmentReceivedIn) { + this.attachmentReceivedIn = attachmentReceivedIn; + } + + public String[] getClassificationNameIn() { + return classificationNameIn; + } + + public void setClassificationNameIn(String[] classificationNameIn) { + this.classificationNameIn = classificationNameIn; + } + + public String[] getClassificationNameLike() { + return classificationNameLike; + } + + public void setClassificationNameLike(String[] classificationNameLike) { + this.classificationNameLike = classificationNameLike; + } + + public String[] getAttachmentClassificationNameIn() { + return attachmentClassificationNameIn; + } + + public void setAttachmentClassificationNameIn(String[] attachmentClassificationNameIn) { + this.attachmentClassificationNameIn = attachmentClassificationNameIn; + } + + public String[] getAttachmentClassificationNameLike() { + return attachmentClassificationNameLike; + } + + public void setAttachmentClassificationNameLike(String[] attachmentClassificationNameLike) { + this.attachmentClassificationNameLike = attachmentClassificationNameLike; + } + + public boolean isAddClassificationNameToSelectClauseForOrdering() { + return addClassificationNameToSelectClauseForOrdering; + } + + public void setAddClassificationNameToSelectClauseForOrdering( + boolean addClassificationNameToSelectClauseForOrdering) { + this.addClassificationNameToSelectClauseForOrdering = + addClassificationNameToSelectClauseForOrdering; + } + + public boolean isAddAttachmentClassificationNameToSelectClauseForOrdering() { + return addAttachmentClassificationNameToSelectClauseForOrdering; + } + + public void setAddAttachmentClassificationNameToSelectClauseForOrdering( + boolean addAttachmentClassificationNameToSelectClauseForOrdering) { + this.addAttachmentClassificationNameToSelectClauseForOrdering = + addAttachmentClassificationNameToSelectClauseForOrdering; + } + + private String getDatabaseId() { + return this.taskanaEngine.getSqlSession().getConfiguration().getDatabaseId(); + } + + private void setupJoinAndOrderParameters() { + // if classificationName or attachmentClassificationName are added to the result set, and + // multiple + // attachments exist, the addition of these attribute may increase the result set. + // in order to have the same result set independent of sorting yes or no, + // we add the add... flags whenever we join with classification or attachmentClassification + if (joinWithAttachmentClassifications) { + joinWithAttachments = true; + addAttachmentClassificationNameToSelectClauseForOrdering = true; + } + if (joinWithClassifications) { + addClassificationNameToSelectClauseForOrdering = true; } - @Override - public TaskQuery orderByClassificationKey(SortDirection sortDirection) { - return DB.DB2.dbProductId.equals(getDatabaseId()) - ? addOrderCriteria("TCLASSIFICATION_KEY", sortDirection) - : addOrderCriteria("t.CLASSIFICATION_KEY", sortDirection); + if (addClassificationNameToSelectClauseForOrdering) { + joinWithClassifications = true; } - - @Override - public TaskQuery orderByDomain(SortDirection sortDirection) { - return addOrderCriteria("DOMAIN", sortDirection); + if (addAttachmentClassificationNameToSelectClauseForOrdering) { + joinWithAttachments = true; + joinWithAttachmentClassifications = true; } - - @Override - public TaskQuery orderByPlanned(SortDirection sortDirection) { - return addOrderCriteria("PLANNED", sortDirection); + if (joinWithAttachments || joinWithClassifications || joinWithAttachmentClassifications) { + useDistinctKeyword = true; } + } - @Override - public TaskQuery orderByDue(SortDirection sortDirection) { - return addOrderCriteria("DUE", sortDirection); + private void setupAccessIds() { + if (taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN) || !filterByAccessIdIn) { + this.accessIdIn = null; + } else if (this.accessIdIn == null) { + String[] accessIds = new String[0]; + List ucAccessIds = CurrentUserContext.getAccessIds(); + if (ucAccessIds != null && !ucAccessIds.isEmpty()) { + accessIds = new String[ucAccessIds.size()]; + accessIds = ucAccessIds.toArray(accessIds); + } + this.accessIdIn = accessIds; + WorkbasketQueryImpl.lowercaseAccessIds(this.accessIdIn); } + } - @Override - public TaskQuery orderByModified(SortDirection sortDirection) { - return addOrderCriteria("MODIFIED", sortDirection); + private void checkOpenAndReadPermissionForSpecifiedWorkbaskets() { + if (taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN)) { + LOGGER.debug("Skipping permissions check since user is in role ADMIN."); + return; } - - @Override - public TaskQuery orderByName(SortDirection sortDirection) { - return addOrderCriteria("NAME", sortDirection); - } - - @Override - public TaskQuery orderByCreator(SortDirection sortDirection) { - return addOrderCriteria("CREATOR", sortDirection); - } - - @Override - public TaskQuery orderByOwner(SortDirection sortDirection) { - return addOrderCriteria("OWNER", sortDirection); - } - - @Override - public TaskQuery orderByPrimaryObjectReferenceCompany(SortDirection sortDirection) { - return addOrderCriteria("POR_COMPANY", sortDirection); - } - - @Override - public TaskQuery orderByPrimaryObjectReferenceSystem(SortDirection sortDirection) { - return addOrderCriteria("POR_SYSTEM", sortDirection); - } - - @Override - public TaskQuery orderByPrimaryObjectReferenceSystemInstance(SortDirection sortDirection) { - return addOrderCriteria("POR_INSTANCE", sortDirection); - } - - @Override - public TaskQuery orderByPrimaryObjectReferenceType(SortDirection sortDirection) { - return addOrderCriteria("POR_TYPE", sortDirection); - } - - @Override - public TaskQuery orderByPrimaryObjectReferenceValue(SortDirection sortDirection) { - return addOrderCriteria("POR_VALUE", sortDirection); - } - - @Override - public TaskQuery orderByPriority(SortDirection sortDirection) { - return addOrderCriteria("PRIORITY", sortDirection); - } - - @Override - public TaskQuery orderByState(SortDirection sortDirection) { - return addOrderCriteria("STATE", sortDirection); - } - - @Override - public TaskQuery orderByWorkbasketKey(SortDirection sortDirection) { - return addOrderCriteria("WORKBASKET_KEY", sortDirection); - } - - @Override - public TaskQuery orderByWorkbasketId(SortDirection sortDirection) { - return addOrderCriteria("WORKBASKET_ID", sortDirection); - } - - @Override - public TaskQuery orderByAttachmentClassificationKey(SortDirection sortDirection) { - joinWithAttachments = true; - addAttachmentColumnsToSelectClauseForOrdering = true; - return DB.DB2.dbProductId.equals(getDatabaseId()) - ? addOrderCriteria("ACLASSIFICATION_KEY", sortDirection) - : addOrderCriteria("a.CLASSIFICATION_KEY", sortDirection); - } - - @Override - public TaskQuery orderByAttachmentClassificationId(SortDirection sortDirection) { - joinWithAttachments = true; - addAttachmentColumnsToSelectClauseForOrdering = true; - return DB.DB2.dbProductId.equals(getDatabaseId()) - ? addOrderCriteria("ACLASSIFICATION_ID", sortDirection) - : addOrderCriteria("a.CLASSIFICATION_ID", sortDirection); - } - - @Override - public TaskQuery orderByAttachmentChannel(SortDirection sortDirection) { - joinWithAttachments = true; - addAttachmentColumnsToSelectClauseForOrdering = true; - return addOrderCriteria("CHANNEL", sortDirection); - } - - @Override - public TaskQuery orderByAttachmentReference(SortDirection sortDirection) { - joinWithAttachments = true; - addAttachmentColumnsToSelectClauseForOrdering = true; - return addOrderCriteria("REF_VALUE", sortDirection); - } - - @Override - public TaskQuery orderByAttachmentReceived(SortDirection sortDirection) { - joinWithAttachments = true; - addAttachmentColumnsToSelectClauseForOrdering = true; - return addOrderCriteria("RECEIVED", sortDirection); - } - - @Override - public TaskQuery orderByNote(SortDirection sortDirection) { - return addOrderCriteria("NOTE", sortDirection); - } - - @Override - public TaskQuery orderByCustomAttribute(String number, SortDirection sortDirection) - throws InvalidArgumentException { - int num = 0; - try { - num = Integer.parseInt(number); - } catch (NumberFormatException e) { - throw new InvalidArgumentException( - ARGUMENT + number + "' to getCustomAttribute cannot be converted to a number between 1 and 16", - e.getCause()); + try { + if (this.workbasketIdIn != null && this.workbasketIdIn.length > 0) { + filterByAccessIdIn = false; + for (String workbasketId : workbasketIdIn) { + checkOpenAndReadPermissionById(workbasketId); } - - switch (num) { - case 1: - return addOrderCriteria("CUSTOM_1", sortDirection); - case 2: - return addOrderCriteria("CUSTOM_2", sortDirection); - case 3: - return addOrderCriteria("CUSTOM_3", sortDirection); - case 4: - return addOrderCriteria("CUSTOM_4", sortDirection); - case 5: - return addOrderCriteria("CUSTOM_5", sortDirection); - case 6: - return addOrderCriteria("CUSTOM_6", sortDirection); - case 7: - return addOrderCriteria("CUSTOM_7", sortDirection); - case 8: - return addOrderCriteria("CUSTOM_8", sortDirection); - case 9: - return addOrderCriteria("CUSTOM_9", sortDirection); - case 10: - return addOrderCriteria("CUSTOM_10", sortDirection); - case 11: - return addOrderCriteria("CUSTOM_11", sortDirection); - case 12: - return addOrderCriteria("CUSTOM_12", sortDirection); - case 13: - return addOrderCriteria("CUSTOM_13", sortDirection); - case 14: - return addOrderCriteria("CUSTOM_14", sortDirection); - case 15: - return addOrderCriteria("CUSTOM_15", sortDirection); - case 16: - return addOrderCriteria("CUSTOM_16", sortDirection); - default: - throw new InvalidArgumentException( - ARGUMENT + number + GET_CUSTOM_ATTRIBUTE_NOT_A_NUMBER_BETWEEN_1_AND_16); + } + if (workbasketKeyDomainIn != null && workbasketKeyDomainIn.length > 0) { + filterByAccessIdIn = false; + for (KeyDomain keyDomain : workbasketKeyDomainIn) { + checkOpenAndReadPermissionByKeyDomain(keyDomain); } - } - - @Override - public TaskQuery orderByBusinessProcessId(SortDirection sortDirection) { - return addOrderCriteria("BUSINESS_PROCESS_ID", sortDirection); - } - - @Override - public TaskQuery orderByClaimed(SortDirection sortDirection) { - return addOrderCriteria("CLAIMED", sortDirection); - } - - @Override - public TaskQuery orderByCompleted(SortDirection sortDirection) { - return addOrderCriteria("COMPLETED", sortDirection); - } - - @Override - public TaskQuery orderByCreated(SortDirection sortDirection) { - return addOrderCriteria("CREATED", sortDirection); - } - - @Override - public TaskQuery orderByParentBusinessProcessId(SortDirection sortDirection) { - return addOrderCriteria("PARENT_BUSINESS_PROCESS_ID", sortDirection); - } - - @Override - public ObjectReferenceQuery createObjectReferenceQuery() { - return new ObjectReferenceQueryImpl(taskanaEngine); - } - - @Override - public List list() { - List result = new ArrayList<>(); - try { - LOGGER.debug("entry to list(), this = {}", this); - taskanaEngine.openConnection(); - checkOpenAndReadPermissionForSpecifiedWorkbaskets(); - setupJoinAndOrderParameters(); - setupAccessIds(); - List tasks = taskanaEngine.getSqlSession().selectList(getLinkToMapperScript(), this); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("mapper returned {} resulting Objects: {} ", tasks.size(), - LoggerUtils.listToString(tasks)); - } - result = taskService.augmentTaskSummariesByContainedSummaries(tasks); - return result; - } finally { - taskanaEngine.returnConnection(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("exit from list(). Returning {} resulting Objects: {} ", result.size(), - LoggerUtils.listToString(result)); - } - } - } - - private void setupJoinAndOrderParameters() { - // if classificationName or attachmentClassificationName are added to the result set, and multiple - // attachments exist, the addition of these attribute may increase the result set. - // in order to have the same result set independent of sorting yes or no, - // we add the add... flags whenever we join with classification or attachmentClassification - if (joinWithAttachmentClassifications) { - joinWithAttachments = true; - addAttachmentClassificationNameToSelectClauseForOrdering = true; - } - if (joinWithClassifications) { - addClassificationNameToSelectClauseForOrdering = true; - } - - if (addClassificationNameToSelectClauseForOrdering) { - joinWithClassifications = true; - } - if (addAttachmentClassificationNameToSelectClauseForOrdering) { - joinWithAttachments = true; - joinWithAttachmentClassifications = true; - } - if (joinWithAttachments || joinWithClassifications || joinWithAttachmentClassifications) { - useDistinctKeyword = true; - } - } - - public String getLinkToMapperScript() { - return DB.DB2.dbProductId.equals(getDatabaseId()) - ? LINK_TO_MAPPER_DB2 - : LINK_TO_MAPPER; - } - - public String getLinkToCounterTaskScript() { - return DB.DB2.dbProductId.equals(getDatabaseId()) - ? LINK_TO_COUNTER_DB2 - : LINK_TO_COUNTER; - } - - private void setupAccessIds() { - if (taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN) || !filterByAccessIdIn) { - this.accessIdIn = null; - } else if (this.accessIdIn == null) { - String[] accessIds = new String[0]; - List ucAccessIds = CurrentUserContext.getAccessIds(); - if (ucAccessIds != null && !ucAccessIds.isEmpty()) { - accessIds = new String[ucAccessIds.size()]; - accessIds = ucAccessIds.toArray(accessIds); - } - this.accessIdIn = accessIds; - WorkbasketQueryImpl.lowercaseAccessIds(this.accessIdIn); - } - - } - - @Override - public List listValues(TaskQueryColumnName columnName, SortDirection sortDirection) { - LOGGER.debug("Entry to listValues(dbColumnName={}) this = {}", columnName, this); - List result = new ArrayList<>(); - try { - taskanaEngine.openConnection(); - this.columnName = columnName; - this.orderBy.clear(); - this.addOrderCriteria(columnName.toString(), sortDirection); - checkOpenAndReadPermissionForSpecifiedWorkbaskets(); - setupAccessIds(); - - if (columnName.equals(TaskQueryColumnName.CLASSIFICATION_NAME)) { - joinWithClassifications = true; - } - - if (columnName.equals(TaskQueryColumnName.A_CLASSIFICATION_NAME)) { - joinWithAttachmentClassifications = true; - } - - if (columnName.isAttachmentColumn()) { - joinWithAttachments = true; - } - - setupJoinAndOrderParameters(); - result = taskanaEngine.getSqlSession().selectList(LINK_TO_VALUEMAPPER, this); - return result; - } finally { - taskanaEngine.returnConnection(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from listValues. Returning {} resulting Objects: {} ", result.size(), - LoggerUtils.listToString(result)); - } - } - } - - @Override - public List list(int offset, int limit) { - LOGGER.debug("entry to list(offset = {}, limit = {}), this = {}", offset, limit, this); - List result = new ArrayList<>(); - try { - taskanaEngine.openConnection(); - checkOpenAndReadPermissionForSpecifiedWorkbaskets(); - setupAccessIds(); - setupJoinAndOrderParameters(); - RowBounds rowBounds = new RowBounds(offset, limit); - List tasks = taskanaEngine.getSqlSession() - .selectList(getLinkToMapperScript(), this, rowBounds); - result = taskService.augmentTaskSummariesByContainedSummaries(tasks); - return result; - } catch (PersistenceException e) { - if (e.getMessage().contains("ERRORCODE=-4470")) { - TaskanaRuntimeException ex = new TaskanaRuntimeException( - "The offset beginning was set over the amount of result-rows.", e.getCause()); - ex.setStackTrace(e.getStackTrace()); - throw ex; - } - throw e; - } finally { - taskanaEngine.returnConnection(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("exit from list(offset,limit). Returning {} resulting Objects: {} ", result.size(), - LoggerUtils.listToString(result)); - } - } - } - - @Override - public TaskSummary single() { - LOGGER.debug("entry to single(), this = {}", this); - TaskSummary result = null; - try { - taskanaEngine.openConnection(); - checkOpenAndReadPermissionForSpecifiedWorkbaskets(); - setupAccessIds(); - setupJoinAndOrderParameters(); - TaskSummaryImpl taskSummaryImpl = taskanaEngine.getSqlSession().selectOne(getLinkToMapperScript(), this); - if (taskSummaryImpl == null) { - return null; - } - List tasks = new ArrayList<>(); - tasks.add(taskSummaryImpl); - List augmentedList = taskService.augmentTaskSummariesByContainedSummaries(tasks); - result = augmentedList.get(0); - - return result; - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from single(). Returning result {} ", result); - } - } - - @Override - public long count() { - LOGGER.debug("entry to count(), this = {}", this); - Long rowCount = null; - try { - taskanaEngine.openConnection(); - checkOpenAndReadPermissionForSpecifiedWorkbaskets(); - setupAccessIds(); - setupJoinAndOrderParameters(); - rowCount = taskanaEngine.getSqlSession().selectOne(getLinkToCounterTaskScript(), this); - return (rowCount == null) ? 0L : rowCount; - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from count(). Returning result {} ", rowCount); - } - } - - public boolean isUseDistinctKeyword() { - return useDistinctKeyword; - } - - public void setUseDistinctKeyword(boolean useDistinctKeyword) { - this.useDistinctKeyword = useDistinctKeyword; - } - - public boolean isJoinWithAttachments() { - return joinWithAttachments; - } - - public void setJoinWithAttachments(boolean joinWithAttachments) { - this.joinWithAttachments = joinWithAttachments; - } - - public boolean isJoinWithClassifications() { - return joinWithClassifications; - } - - public void setJoinWithClassifications(boolean joinWithClassifications) { - this.joinWithClassifications = joinWithClassifications; - } - - public boolean isJoinWithAttachmentsClassifications() { - return joinWithAttachmentClassifications; - } - - public void setJoinWithAttachmentsClassifications(boolean joinWithAttachmentsClassifications) { - this.joinWithAttachmentClassifications = joinWithAttachmentsClassifications; - } - - public boolean isAddAttachmentColumnsToSelectClauseForOrdering() { - return addAttachmentColumnsToSelectClauseForOrdering; - } - - public void setAddAttachmentColumnsToSelectClauseForOrdering( - boolean addAttachmentColumnsToSelectClauseForOrdering) { - this.addAttachmentColumnsToSelectClauseForOrdering = addAttachmentColumnsToSelectClauseForOrdering; - } - - private void checkOpenAndReadPermissionForSpecifiedWorkbaskets() { - if (taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN)) { - LOGGER.debug("Skipping permissions check since user is in role ADMIN."); - return; - } - try { - if (this.workbasketIdIn != null && this.workbasketIdIn.length > 0) { - filterByAccessIdIn = false; - for (String workbasketId : workbasketIdIn) { - checkOpenAndReadPermissionById(workbasketId); - } - } - if (workbasketKeyDomainIn != null && workbasketKeyDomainIn.length > 0) { - filterByAccessIdIn = false; - for (KeyDomain keyDomain : workbasketKeyDomainIn) { - checkOpenAndReadPermissionByKeyDomain(keyDomain); - } - } - } catch (NotAuthorizedException e) { - throw new NotAuthorizedToQueryWorkbasketException(e.getMessage(), e.getCause()); - } - } - - private void checkOpenAndReadPermissionById(String workbasketId) throws NotAuthorizedException { - try { - taskanaEngine.getEngine().getWorkbasketService().checkAuthorization(workbasketId, - WorkbasketPermission.OPEN, WorkbasketPermission.READ); - } catch (WorkbasketNotFoundException e) { - LOGGER.warn("The workbasket with the ID '" + workbasketId + "' does not exist.", e); - } - } - - private void checkOpenAndReadPermissionByKeyDomain(KeyDomain keyDomain) throws NotAuthorizedException { - try { - taskanaEngine.getEngine().getWorkbasketService().checkAuthorization(keyDomain.getKey(), - keyDomain.getDomain(), WorkbasketPermission.OPEN, WorkbasketPermission.READ); - } catch (WorkbasketNotFoundException e) { - LOGGER.warn("The workbasket with the KEY '" + keyDomain.getKey() + "' and DOMAIN '" - + keyDomain.getDomain() + "'does not exist.", e); - } - } - - public String[] getTaskIds() { - return taskIds; - } - - public String[] getNameIn() { - return nameIn; - } - - public String[] getExternalIdIn() { - return externalIdIn; - } - - public String[] getExternalIdLike() { - return externalIdLike; - } - - public String[] getCreatorIn() { - return creatorIn; - } - - public String[] getCreatorLike() { - return creatorLike; - } - - public String[] getDescription() { - return description; - } - - public int[] getPriority() { - return priority; - } - - public TaskState[] getStateIn() { - return stateIn; - } - - public String[] getOwnerIn() { - return ownerIn; - } - - public String[] getOwnerLike() { - return ownerLike; - } - - public Boolean getIsRead() { - return isRead; - } - - public Boolean getIsTransferred() { - return isTransferred; - } - - public String[] getPorCompanyIn() { - return porCompanyIn; - } - - public String[] getPorCompanyLike() { - return porCompanyLike; - } - - public String[] getPorSystemIn() { - return porSystemIn; - } - - public String[] getPorSystemLike() { - return porSystemLike; - } - - public String[] getPorSystemInstanceIn() { - return porSystemInstanceIn; - } - - public String[] getPorSystemInstanceLike() { - return porSystemInstanceLike; - } - - public String[] getPorTypeIn() { - return porTypeIn; - } - - public String[] getPorTypeLike() { - return porTypeLike; - } - - public String[] getPorValueIn() { - return porValueIn; - } - - public String[] getPorValueLike() { - return porValueLike; - } - - public List getOrderBy() { - return orderBy; - } - - public List getOrderColumns() { - return orderColumns; - } - - public TimeInterval[] getCreatedIn() { - return createdIn; - } - - public TaskServiceImpl getTaskService() { - return taskService; - } - - public String[] getNote() { - return note; - } - - public String[] getNoteLike() { - return noteLike; - } - - public String[] getParentBusinessProcessIdIn() { - return parentBusinessProcessIdIn; - } - - public String[] getParentBusinessProcessIdLike() { - return parentBusinessProcessIdLike; - } - - public String[] getBusinessProcessIdIn() { - return businessProcessIdIn; - } - - public String[] getBusinessProcessIdLike() { - return businessProcessIdLike; - } - - public String[] getCustom1In() { - return custom1In; - } - - public String[] getCustom1Like() { - return custom1Like; - } - - public String[] getCustom2In() { - return custom2In; - } - - public String[] getCustom2Like() { - return custom2Like; - } - - public String[] getCustom3In() { - return custom3In; - } - - public String[] getCustom3Like() { - return custom3Like; - } - - public String[] getCustom4In() { - return custom4In; - } - - public String[] getCustom4Like() { - return custom4Like; - } - - public String[] getCustom5In() { - return custom5In; - } - - public String[] getCustom5Like() { - return custom5Like; - } - - public String[] getCustom6In() { - return custom6In; - } - - public String[] getCustom6Like() { - return custom6Like; - } - - public String[] getCustom7In() { - return custom7In; - } - - public String[] getCustom7Like() { - return custom7Like; - } - - public String[] getCustom8In() { - return custom8In; - } - - public String[] getCustom8Like() { - return custom8Like; - } - - public String[] getCustom9In() { - return custom9In; - } - - public String[] getCustom9Like() { - return custom9Like; - } - - public String[] getCustom10In() { - return custom10In; - } - - public String[] getCustom10Like() { - return custom10Like; - } - - public String[] getCustom11In() { - return custom11In; - } - - public String[] getCustom11Like() { - return custom11Like; - } - - public String[] getCustom12In() { - return custom12In; - } - - public String[] getCustom12Like() { - return custom12Like; - } - - public String[] getCustom13In() { - return custom13In; - } - - public String[] getCustom13Like() { - return custom13Like; - } - - public String[] getCustom14In() { - return custom14In; - } - - public String[] getCustom14Like() { - return custom14Like; - } - - public String[] getCustom15In() { - return custom15In; - } - - public String[] getCustom15Like() { - return custom15Like; - } - - public String[] getCustom16In() { - return custom16In; - } - - public String[] getCustom16Like() { - return custom16Like; - } - - public String[] getClassificationCategoryIn() { - return classificationCategoryIn; - } - - public String[] getClassificationCategoryLike() { - return classificationCategoryLike; - } - - public TimeInterval[] getClaimedIn() { - return claimedIn; - } - - public TimeInterval[] getCompletedIn() { - return completedIn; - } - - public TimeInterval[] getModifiedIn() { - return modifiedIn; - } - - public TimeInterval[] getPlannedIn() { - return plannedIn; - } - - public TimeInterval[] getDueIn() { - return dueIn; - } - - public String[] getNameLike() { - return nameLike; - } - - public String[] getClassificationKeyIn() { - return classificationKeyIn; - } - - public String[] getClassificationKeyNotIn() { - return classificationKeyNotIn; - } - - public String[] getClassificationKeyLike() { - return classificationKeyLike; - } - - public String[] getClassificationIdIn() { - return classificationIdIn; - } - - public KeyDomain[] getWorkbasketKeyDomainIn() { - return workbasketKeyDomainIn; - } - - public String[] getWorkbasketIdIn() { - return workbasketIdIn; - } - - public TaskQueryColumnName getColumnName() { - return columnName; - } - - public String[] getAttachmentClassificationKeyIn() { - return attachmentClassificationKeyIn; - } - - public void setAttachmentClassificationKeyIn(String[] attachmentClassificationKeyIn) { - this.attachmentClassificationKeyIn = attachmentClassificationKeyIn; - } - - public String[] getAttachmentClassificationKeyLike() { - return attachmentClassificationKeyLike; - } - - public void setAttachmentClassificationKeyLike(String[] attachmentClassificationKeyLike) { - this.attachmentClassificationKeyLike = attachmentClassificationKeyLike; - } - - public String[] getAttachmentClassificationIdIn() { - return attachmentClassificationIdIn; - } - - public void setAttachmentClassificationIdIn(String[] attachmentClassificationIdIn) { - this.attachmentClassificationIdIn = attachmentClassificationIdIn; - } - - public String[] getAttachmentClassificationIdLike() { - return attachmentClassificationIdLike; - } - - public void setAttachmentClassificationIdLike(String[] attachmentclassificationIdLike) { - this.attachmentClassificationIdLike = attachmentclassificationIdLike; - } - - public String[] getAttachmentChannelIn() { - return attachmentChannelIn; - } - - public void setAttachmentChannelIn(String[] attachmentChannelIn) { - this.attachmentChannelIn = attachmentChannelIn; - } - - public String[] getAttachmentChannelLike() { - return attachmentChannelLike; - } - - public void setAttachmentChannelLike(String[] attachmentChannelLike) { - this.attachmentChannelLike = attachmentChannelLike; - } - - public String[] getAttachmentReferenceIn() { - return attachmentReferenceIn; - } - - public void setAttachmentReferenceIn(String[] attachmentReferenceIn) { - this.attachmentReferenceIn = attachmentReferenceIn; - } - - public String[] getAttachmentReferenceLike() { - return attachmentReferenceLike; - } - - public void setAttachmentReferenceLike(String[] attachmentReferenceLike) { - this.attachmentReferenceLike = attachmentReferenceLike; - } - - public TimeInterval[] getAttachmentReceivedIn() { - return attachmentReceivedIn; - } - - public void setAttachmentReceivedIn(TimeInterval[] attachmentReceivedIn) { - this.attachmentReceivedIn = attachmentReceivedIn; - } - - private TaskQuery addOrderCriteria(String columnName, SortDirection sortDirection) { - String orderByDirection = " " + (sortDirection == null ? SortDirection.ASCENDING : sortDirection); - orderBy.add(columnName + orderByDirection); - orderColumns.add(columnName.toString()); - return this; - } - - public String[] getClassificationNameIn() { - return classificationNameIn; - } - - public void setClassificationNameIn(String[] classificationNameIn) { - this.classificationNameIn = classificationNameIn; - } - - public String[] getClassificationNameLike() { - return classificationNameLike; - } - - public void setClassificationNameLike(String[] classificationNameLike) { - this.classificationNameLike = classificationNameLike; - } - - public String[] getAttachmentClassificationNameIn() { - return attachmentClassificationNameIn; - } - - public void setAttachmentClassificationNameIn(String[] attachmentClassificationNameIn) { - this.attachmentClassificationNameIn = attachmentClassificationNameIn; - } - - public String[] getAttachmentClassificationNameLike() { - return attachmentClassificationNameLike; - } - - public void setAttachmentClassificationNameLike(String[] attachmentClassificationNameLike) { - this.attachmentClassificationNameLike = attachmentClassificationNameLike; - } - - public boolean isAddClassificationNameToSelectClauseForOrdering() { - return addClassificationNameToSelectClauseForOrdering; - } - - public void setAddClassificationNameToSelectClauseForOrdering( - boolean addClassificationNameToSelectClauseForOrdering) { - this.addClassificationNameToSelectClauseForOrdering = addClassificationNameToSelectClauseForOrdering; - } - - public boolean isAddAttachmentClassificationNameToSelectClauseForOrdering() { - return addAttachmentClassificationNameToSelectClauseForOrdering; - } - - public void setAddAttachmentClassificationNameToSelectClauseForOrdering( - boolean addAttachmentClassificationNameToSelectClauseForOrdering) { - this.addAttachmentClassificationNameToSelectClauseForOrdering = addAttachmentClassificationNameToSelectClauseForOrdering; - } - - @Override - public String toString() { - return "TaskQueryImpl [columnName=" + columnName + ", nameIn=" + Arrays.toString(nameIn) + ", nameLike=" - + Arrays.toString(nameLike) + ", externalIdIn=" + Arrays.toString(externalIdIn) - + ", externalIdLike=" + Arrays.toString(externalIdLike) - + ", creatorIn=" + Arrays.toString(creatorIn) + ", creatorLike=" - + Arrays.toString(creatorLike) + ", taskIds=" + Arrays.toString(taskIds) + ", description=" - + Arrays.toString(description) + ", note=" + Arrays.toString(note) + ", noteLike=" - + Arrays.toString(noteLike) + ", priority=" + Arrays.toString(priority) + ", workbasketKeyDomainIn=" - + Arrays.toString(workbasketKeyDomainIn) + ", workbasketIdIn=" + Arrays.toString(workbasketIdIn) - + ", stateIn=" + Arrays.toString(stateIn) + ", classificationIdIn=" + Arrays.toString(classificationIdIn) - + ", classificationKeyIn=" + Arrays.toString(classificationKeyIn) + ", classificationKeyLike=" - + Arrays.toString(classificationKeyLike) + ", classificationKeyNotIn=" - + Arrays.toString(classificationKeyNotIn) + ", classificationCategoryIn=" - + Arrays.toString(classificationCategoryIn) + ", classificationCategoryLike=" - + Arrays.toString(classificationCategoryLike) + ", classificationNameIn=" - + Arrays.toString(classificationNameIn) + ", classificationNameLike=" - + Arrays.toString(classificationNameLike) + ", ownerIn=" + Arrays.toString(ownerIn) + ", ownerLike=" - + Arrays.toString(ownerLike) + ", isRead=" + isRead + ", isTransferred=" + isTransferred + ", porCompanyIn=" - + Arrays.toString(porCompanyIn) + ", porCompanyLike=" + Arrays.toString(porCompanyLike) + ", porSystemIn=" - + Arrays.toString(porSystemIn) + ", porSystemLike=" + Arrays.toString(porSystemLike) - + ", porSystemInstanceIn=" + Arrays.toString(porSystemInstanceIn) + ", porSystemInstanceLike=" - + Arrays.toString(porSystemInstanceLike) + ", porTypeIn=" + Arrays.toString(porTypeIn) + ", porTypeLike=" - + Arrays.toString(porTypeLike) + ", porValueIn=" + Arrays.toString(porValueIn) + ", porValueLike=" - + Arrays.toString(porValueLike) + ", parentBusinessProcessIdIn=" - + Arrays.toString(parentBusinessProcessIdIn) + ", parentBusinessProcessIdLike=" - + Arrays.toString(parentBusinessProcessIdLike) + ", businessProcessIdIn=" - + Arrays.toString(businessProcessIdIn) + ", businessProcessIdLike=" + Arrays.toString(businessProcessIdLike) - + ", custom1In=" + Arrays.toString(custom1In) + ", custom1Like=" + Arrays.toString(custom1Like) - + ", custom2In=" + Arrays.toString(custom2In) + ", custom2Like=" + Arrays.toString(custom2Like) - + ", custom3In=" + Arrays.toString(custom3In) + ", custom3Like=" + Arrays.toString(custom3Like) - + ", custom4In=" + Arrays.toString(custom4In) + ", custom4Like=" + Arrays.toString(custom4Like) - + ", custom5In=" + Arrays.toString(custom5In) + ", custom5Like=" + Arrays.toString(custom5Like) - + ", custom6In=" + Arrays.toString(custom6In) + ", custom6Like=" + Arrays.toString(custom6Like) - + ", custom7In=" + Arrays.toString(custom7In) + ", custom7Like=" + Arrays.toString(custom7Like) - + ", custom8In=" + Arrays.toString(custom8In) + ", custom8Like=" + Arrays.toString(custom8Like) - + ", custom9In=" + Arrays.toString(custom9In) + ", custom9Like=" + Arrays.toString(custom9Like) - + ", custom10In=" + Arrays.toString(custom10In) + ", custom10Like=" + Arrays.toString(custom10Like) - + ", custom11In=" + Arrays.toString(custom11In) + ", custom11Like=" + Arrays.toString(custom11Like) - + ", custom12In=" + Arrays.toString(custom12In) + ", custom12Like=" + Arrays.toString(custom12Like) - + ", custom13In=" + Arrays.toString(custom13In) + ", custom13Like=" + Arrays.toString(custom13Like) - + ", custom14In=" + Arrays.toString(custom14In) + ", custom14Like=" + Arrays.toString(custom14Like) - + ", custom15In=" + Arrays.toString(custom15In) + ", custom15Like=" + Arrays.toString(custom15Like) - + ", custom16In=" + Arrays.toString(custom16In) + ", custom16Like=" + Arrays.toString(custom16Like) - + ", attachmentClassificationKeyIn=" + Arrays.toString(attachmentClassificationKeyIn) - + ", attachmentClassificationKeyLike=" + Arrays.toString(attachmentClassificationKeyLike) - + ", attachmentClassificationIdIn=" + Arrays.toString(attachmentClassificationIdIn) - + ", attachmentClassificationIdLike=" + Arrays.toString(attachmentClassificationIdLike) - + ", attachmentClassificationNameIn=" + Arrays.toString(attachmentClassificationNameIn) - + ", attachmentClassificationNameLike=" + Arrays.toString(attachmentClassificationNameLike) - + ", attachmentChannelIn=" + Arrays.toString(attachmentChannelIn) + ", attachmentChannelLike=" - + Arrays.toString(attachmentChannelLike) + ", attachmentReferenceIn=" - + Arrays.toString(attachmentReferenceIn) + ", attachmentReferenceLike=" - + Arrays.toString(attachmentReferenceLike) + ", attachmentReceivedIn=" - + Arrays.toString(attachmentReceivedIn) + ", accessIdIn=" + Arrays.toString(accessIdIn) - + ", filterByAccessIdIn=" + filterByAccessIdIn + ", createdIn=" + Arrays.toString(createdIn) - + ", claimedIn=" + Arrays.toString(claimedIn) + ", completedIn=" + Arrays.toString(completedIn) - + ", modifiedIn=" + Arrays.toString(modifiedIn) + ", plannedIn=" + Arrays.toString(plannedIn) + ", dueIn=" - + Arrays.toString(dueIn) + ", orderBy=" + orderBy + ", orderColumns=" + orderColumns - + ", joinWithAttachments=" + joinWithAttachments + ", joinWithClassifications=" + joinWithClassifications - + ", joinWithAttachmentsClassifications=" + joinWithAttachmentClassifications - + ", addAttachmentColumnsToSelectClauseForOrdering=" + addAttachmentColumnsToSelectClauseForOrdering - + ", addClassificationNameToSelectClauseForOrdering=" + addClassificationNameToSelectClauseForOrdering - + ", addAttachmentClassificationNameToSelectClauseForOrdering=" - + addAttachmentClassificationNameToSelectClauseForOrdering + "]"; - } + } + } catch (NotAuthorizedException e) { + throw new NotAuthorizedToQueryWorkbasketException(e.getMessage(), e.getCause()); + } + } + + private void checkOpenAndReadPermissionById(String workbasketId) throws NotAuthorizedException { + try { + taskanaEngine + .getEngine() + .getWorkbasketService() + .checkAuthorization(workbasketId, WorkbasketPermission.OPEN, WorkbasketPermission.READ); + } catch (WorkbasketNotFoundException e) { + LOGGER.warn("The workbasket with the ID '" + workbasketId + "' does not exist.", e); + } + } + + private void checkOpenAndReadPermissionByKeyDomain(KeyDomain keyDomain) + throws NotAuthorizedException { + try { + taskanaEngine + .getEngine() + .getWorkbasketService() + .checkAuthorization( + keyDomain.getKey(), + keyDomain.getDomain(), + WorkbasketPermission.OPEN, + WorkbasketPermission.READ); + } catch (WorkbasketNotFoundException e) { + LOGGER.warn( + "The workbasket with the KEY '" + + keyDomain.getKey() + + "' and DOMAIN '" + + keyDomain.getDomain() + + "'does not exist.", + e); + } + } + + private TaskQuery addOrderCriteria(String columnName, SortDirection sortDirection) { + String orderByDirection = + " " + (sortDirection == null ? SortDirection.ASCENDING : sortDirection); + orderBy.add(columnName + orderByDirection); + orderColumns.add(columnName.toString()); + return this; + } + + @Override + public String toString() { + return "TaskQueryImpl [columnName=" + + columnName + + ", nameIn=" + + Arrays.toString(nameIn) + + ", nameLike=" + + Arrays.toString(nameLike) + + ", externalIdIn=" + + Arrays.toString(externalIdIn) + + ", externalIdLike=" + + Arrays.toString(externalIdLike) + + ", creatorIn=" + + Arrays.toString(creatorIn) + + ", creatorLike=" + + Arrays.toString(creatorLike) + + ", taskIds=" + + Arrays.toString(taskIds) + + ", description=" + + Arrays.toString(description) + + ", note=" + + Arrays.toString(note) + + ", noteLike=" + + Arrays.toString(noteLike) + + ", priority=" + + Arrays.toString(priority) + + ", workbasketKeyDomainIn=" + + Arrays.toString(workbasketKeyDomainIn) + + ", workbasketIdIn=" + + Arrays.toString(workbasketIdIn) + + ", stateIn=" + + Arrays.toString(stateIn) + + ", classificationIdIn=" + + Arrays.toString(classificationIdIn) + + ", classificationKeyIn=" + + Arrays.toString(classificationKeyIn) + + ", classificationKeyLike=" + + Arrays.toString(classificationKeyLike) + + ", classificationKeyNotIn=" + + Arrays.toString(classificationKeyNotIn) + + ", classificationCategoryIn=" + + Arrays.toString(classificationCategoryIn) + + ", classificationCategoryLike=" + + Arrays.toString(classificationCategoryLike) + + ", classificationNameIn=" + + Arrays.toString(classificationNameIn) + + ", classificationNameLike=" + + Arrays.toString(classificationNameLike) + + ", ownerIn=" + + Arrays.toString(ownerIn) + + ", ownerLike=" + + Arrays.toString(ownerLike) + + ", isRead=" + + isRead + + ", isTransferred=" + + isTransferred + + ", porCompanyIn=" + + Arrays.toString(porCompanyIn) + + ", porCompanyLike=" + + Arrays.toString(porCompanyLike) + + ", porSystemIn=" + + Arrays.toString(porSystemIn) + + ", porSystemLike=" + + Arrays.toString(porSystemLike) + + ", porSystemInstanceIn=" + + Arrays.toString(porSystemInstanceIn) + + ", porSystemInstanceLike=" + + Arrays.toString(porSystemInstanceLike) + + ", porTypeIn=" + + Arrays.toString(porTypeIn) + + ", porTypeLike=" + + Arrays.toString(porTypeLike) + + ", porValueIn=" + + Arrays.toString(porValueIn) + + ", porValueLike=" + + Arrays.toString(porValueLike) + + ", parentBusinessProcessIdIn=" + + Arrays.toString(parentBusinessProcessIdIn) + + ", parentBusinessProcessIdLike=" + + Arrays.toString(parentBusinessProcessIdLike) + + ", businessProcessIdIn=" + + Arrays.toString(businessProcessIdIn) + + ", businessProcessIdLike=" + + Arrays.toString(businessProcessIdLike) + + ", custom1In=" + + Arrays.toString(custom1In) + + ", custom1Like=" + + Arrays.toString(custom1Like) + + ", custom2In=" + + Arrays.toString(custom2In) + + ", custom2Like=" + + Arrays.toString(custom2Like) + + ", custom3In=" + + Arrays.toString(custom3In) + + ", custom3Like=" + + Arrays.toString(custom3Like) + + ", custom4In=" + + Arrays.toString(custom4In) + + ", custom4Like=" + + Arrays.toString(custom4Like) + + ", custom5In=" + + Arrays.toString(custom5In) + + ", custom5Like=" + + Arrays.toString(custom5Like) + + ", custom6In=" + + Arrays.toString(custom6In) + + ", custom6Like=" + + Arrays.toString(custom6Like) + + ", custom7In=" + + Arrays.toString(custom7In) + + ", custom7Like=" + + Arrays.toString(custom7Like) + + ", custom8In=" + + Arrays.toString(custom8In) + + ", custom8Like=" + + Arrays.toString(custom8Like) + + ", custom9In=" + + Arrays.toString(custom9In) + + ", custom9Like=" + + Arrays.toString(custom9Like) + + ", custom10In=" + + Arrays.toString(custom10In) + + ", custom10Like=" + + Arrays.toString(custom10Like) + + ", custom11In=" + + Arrays.toString(custom11In) + + ", custom11Like=" + + Arrays.toString(custom11Like) + + ", custom12In=" + + Arrays.toString(custom12In) + + ", custom12Like=" + + Arrays.toString(custom12Like) + + ", custom13In=" + + Arrays.toString(custom13In) + + ", custom13Like=" + + Arrays.toString(custom13Like) + + ", custom14In=" + + Arrays.toString(custom14In) + + ", custom14Like=" + + Arrays.toString(custom14Like) + + ", custom15In=" + + Arrays.toString(custom15In) + + ", custom15Like=" + + Arrays.toString(custom15Like) + + ", custom16In=" + + Arrays.toString(custom16In) + + ", custom16Like=" + + Arrays.toString(custom16Like) + + ", attachmentClassificationKeyIn=" + + Arrays.toString(attachmentClassificationKeyIn) + + ", attachmentClassificationKeyLike=" + + Arrays.toString(attachmentClassificationKeyLike) + + ", attachmentClassificationIdIn=" + + Arrays.toString(attachmentClassificationIdIn) + + ", attachmentClassificationIdLike=" + + Arrays.toString(attachmentClassificationIdLike) + + ", attachmentClassificationNameIn=" + + Arrays.toString(attachmentClassificationNameIn) + + ", attachmentClassificationNameLike=" + + Arrays.toString(attachmentClassificationNameLike) + + ", attachmentChannelIn=" + + Arrays.toString(attachmentChannelIn) + + ", attachmentChannelLike=" + + Arrays.toString(attachmentChannelLike) + + ", attachmentReferenceIn=" + + Arrays.toString(attachmentReferenceIn) + + ", attachmentReferenceLike=" + + Arrays.toString(attachmentReferenceLike) + + ", attachmentReceivedIn=" + + Arrays.toString(attachmentReceivedIn) + + ", accessIdIn=" + + Arrays.toString(accessIdIn) + + ", filterByAccessIdIn=" + + filterByAccessIdIn + + ", createdIn=" + + Arrays.toString(createdIn) + + ", claimedIn=" + + Arrays.toString(claimedIn) + + ", completedIn=" + + Arrays.toString(completedIn) + + ", modifiedIn=" + + Arrays.toString(modifiedIn) + + ", plannedIn=" + + Arrays.toString(plannedIn) + + ", dueIn=" + + Arrays.toString(dueIn) + + ", orderBy=" + + orderBy + + ", orderColumns=" + + orderColumns + + ", joinWithAttachments=" + + joinWithAttachments + + ", joinWithClassifications=" + + joinWithClassifications + + ", joinWithAttachmentsClassifications=" + + joinWithAttachmentClassifications + + ", addAttachmentColumnsToSelectClauseForOrdering=" + + addAttachmentColumnsToSelectClauseForOrdering + + ", addClassificationNameToSelectClauseForOrdering=" + + addClassificationNameToSelectClauseForOrdering + + ", addAttachmentClassificationNameToSelectClauseForOrdering=" + + addAttachmentClassificationNameToSelectClauseForOrdering + + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/TaskServiceImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/TaskServiceImpl.java index 7e025d09e..02958c82b 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/TaskServiceImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/TaskServiceImpl.java @@ -12,7 +12,6 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; - import org.apache.ibatis.exceptions.PersistenceException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -59,1768 +58,1946 @@ import pro.taskana.mappings.CustomPropertySelector; import pro.taskana.mappings.TaskMapper; import pro.taskana.security.CurrentUserContext; -/** - * This is the implementation of TaskService. - */ +/** This is the implementation of TaskService. */ public class TaskServiceImpl implements TaskService { - private static final String IS_ALREADY_CLAIMED_BY = " is already claimed by "; - private static final String IS_ALREADY_COMPLETED = " is already completed."; - private static final String WAS_NOT_FOUND2 = " was not found."; - private static final String WAS_NOT_FOUND = " was not found"; - private static final String TASK_WITH_ID = "Task with id "; - private static final String WAS_MARKED_FOR_DELETION = " was marked for deletion"; - private static final String THE_WORKBASKET = "The workbasket "; - private static final Logger LOGGER = LoggerFactory.getLogger(TaskServiceImpl.class); - private static final String ID_PREFIX_ATTACHMENT = "TAI"; - private static final String ID_PREFIX_TASK = "TKI"; - private static final String ID_PREFIX_EXT_TASK_ID = "ETI"; - private static final String ID_PREFIX_BUSINESS_PROCESS = "BPI"; - private static final String MUST_NOT_BE_EMPTY = " must not be empty"; - private static final Duration MAX_DURATION = Duration.ofSeconds(Long.MAX_VALUE, 999_999_999); - private static final Set ALLOWED_KEYS = - IntStream.rangeClosed(1, 16).mapToObj(String::valueOf).collect(Collectors.toSet()); - private DaysToWorkingDaysConverter converter; - private InternalTaskanaEngine taskanaEngine; - private WorkbasketService workbasketService; - private ClassificationService classificationService; - private TaskMapper taskMapper; - private AttachmentMapper attachmentMapper; - private HistoryEventProducer historyEventProducer; - private TaskTransferrer taskTransferrer; + private static final String IS_ALREADY_CLAIMED_BY = " is already claimed by "; + private static final String IS_ALREADY_COMPLETED = " is already completed."; + private static final String WAS_NOT_FOUND2 = " was not found."; + private static final String WAS_NOT_FOUND = " was not found"; + private static final String TASK_WITH_ID = "Task with id "; + private static final String WAS_MARKED_FOR_DELETION = " was marked for deletion"; + private static final String THE_WORKBASKET = "The workbasket "; + private static final Logger LOGGER = LoggerFactory.getLogger(TaskServiceImpl.class); + private static final String ID_PREFIX_ATTACHMENT = "TAI"; + private static final String ID_PREFIX_TASK = "TKI"; + private static final String ID_PREFIX_EXT_TASK_ID = "ETI"; + private static final String ID_PREFIX_BUSINESS_PROCESS = "BPI"; + private static final String MUST_NOT_BE_EMPTY = " must not be empty"; + private static final Duration MAX_DURATION = Duration.ofSeconds(Long.MAX_VALUE, 999_999_999); + private static final Set ALLOWED_KEYS = + IntStream.rangeClosed(1, 16).mapToObj(String::valueOf).collect(Collectors.toSet()); + private DaysToWorkingDaysConverter converter; + private InternalTaskanaEngine taskanaEngine; + private WorkbasketService workbasketService; + private ClassificationService classificationService; + private TaskMapper taskMapper; + private AttachmentMapper attachmentMapper; + private HistoryEventProducer historyEventProducer; + private TaskTransferrer taskTransferrer; - TaskServiceImpl(InternalTaskanaEngine taskanaEngine, TaskMapper taskMapper, - AttachmentMapper attachmentMapper) { - super(); - try { - this.converter = DaysToWorkingDaysConverter - .initialize(Collections.singletonList(new TimeIntervalColumnHeader(0)), Instant.now()); - } catch (InvalidArgumentException e) { - throw new SystemException("Internal error. Cannot initialize DaysToWorkingDaysConverter", e.getCause()); - } - this.taskanaEngine = taskanaEngine; - this.taskMapper = taskMapper; - this.workbasketService = taskanaEngine.getEngine().getWorkbasketService(); - this.attachmentMapper = attachmentMapper; - this.classificationService = taskanaEngine.getEngine().getClassificationService(); - this.historyEventProducer = taskanaEngine.getHistoryEventProducer(); - this.taskTransferrer = new TaskTransferrer(taskanaEngine, taskMapper, this); + TaskServiceImpl( + InternalTaskanaEngine taskanaEngine, + TaskMapper taskMapper, + AttachmentMapper attachmentMapper) { + super(); + try { + this.converter = + DaysToWorkingDaysConverter.initialize( + Collections.singletonList(new TimeIntervalColumnHeader(0)), Instant.now()); + } catch (InvalidArgumentException e) { + throw new SystemException( + "Internal error. Cannot initialize DaysToWorkingDaysConverter", e.getCause()); } + this.taskanaEngine = taskanaEngine; + this.taskMapper = taskMapper; + this.workbasketService = taskanaEngine.getEngine().getWorkbasketService(); + this.attachmentMapper = attachmentMapper; + this.classificationService = taskanaEngine.getEngine().getClassificationService(); + this.historyEventProducer = taskanaEngine.getHistoryEventProducer(); + this.taskTransferrer = new TaskTransferrer(taskanaEngine, taskMapper, this); + } - @Override - public Task claim(String taskId) - throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, NotAuthorizedException { - return claim(taskId, false); + @Override + public Task claim(String taskId) + throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, + NotAuthorizedException { + return claim(taskId, false); + } + + @Override + public Task forceClaim(String taskId) + throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, + NotAuthorizedException { + return claim(taskId, true); + } + + @Override + public Task cancelClaim(String taskId) + throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, + NotAuthorizedException { + return this.cancelClaim(taskId, false); + } + + @Override + public Task forceCancelClaim(String taskId) + throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, + NotAuthorizedException { + return this.cancelClaim(taskId, true); + } + + @Override + public Task completeTask(String taskId) + throws TaskNotFoundException, InvalidOwnerException, InvalidStateException, + NotAuthorizedException { + return completeTask(taskId, false); + } + + @Override + public Task forceCompleteTask(String taskId) + throws TaskNotFoundException, InvalidOwnerException, InvalidStateException, + NotAuthorizedException { + return completeTask(taskId, true); + } + + @Override + public BulkOperationResults completeTasks( + List taskIdsToBeCompleted) throws InvalidArgumentException { + try { + LOGGER.debug("entry to completeTasks(taskIds = {})", taskIdsToBeCompleted); + taskanaEngine.openConnection(); + + if (taskIdsToBeCompleted == null || taskIdsToBeCompleted.isEmpty()) { + throw new InvalidArgumentException("TaskIds can´t be used as NULL-Parameter."); + } + + BulkOperationResults bulkLog = new BulkOperationResults<>(); + List taskIds = new ArrayList<>(taskIdsToBeCompleted); + removeNonExistingTasksFromTaskIdList(taskIds, bulkLog); + + List taskSummaries = + this.createTaskQuery().idIn(taskIds.toArray(new String[0])).list(); + + checkIfTasksMatchCompleteCriteria(taskIds, taskSummaries, bulkLog); + + updateTasksToBeCompleted(taskIds, taskSummaries); + + return bulkLog; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from to completeTasks(taskIds = {})", taskIdsToBeCompleted); } + } - @Override - public Task forceClaim(String taskId) - throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, NotAuthorizedException { - return claim(taskId, true); - } + @Override + public Task createTask(Task taskToCreate) + throws NotAuthorizedException, WorkbasketNotFoundException, ClassificationNotFoundException, + TaskAlreadyExistException, InvalidArgumentException { + LOGGER.debug("entry to createTask(task = {})", taskToCreate); + TaskImpl task = (TaskImpl) taskToCreate; + try { + taskanaEngine.openConnection(); - @Override - public Task cancelClaim(String taskId) - throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, NotAuthorizedException { - return this.cancelClaim(taskId, false); - } + if (task.getId() != null && !task.getId().equals("")) { + throw new TaskAlreadyExistException(task.getId()); + } - @Override - public Task forceCancelClaim(String taskId) - throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, NotAuthorizedException { - return this.cancelClaim(taskId, true); - } + LOGGER.debug("Task {} cannot be found, so it can be created.", task.getId()); + Workbasket workbasket; - @Override - public Task completeTask(String taskId) - throws TaskNotFoundException, InvalidOwnerException, InvalidStateException, NotAuthorizedException { - return completeTask(taskId, false); - } - - @Override - public Task forceCompleteTask(String taskId) - throws TaskNotFoundException, InvalidOwnerException, InvalidStateException, NotAuthorizedException { - return completeTask(taskId, true); - } - - @Override - public BulkOperationResults completeTasks(List taskIdsToBeCompleted) - throws InvalidArgumentException { - try { - LOGGER.debug("entry to completeTasks(taskIds = {})", taskIdsToBeCompleted); - taskanaEngine.openConnection(); - - if (taskIdsToBeCompleted == null || taskIdsToBeCompleted.isEmpty()) { - throw new InvalidArgumentException( - "TaskIds can´t be used as NULL-Parameter."); - } - - BulkOperationResults bulkLog = new BulkOperationResults<>(); - List taskIds = new ArrayList<>(taskIdsToBeCompleted); - removeNonExistingTasksFromTaskIdList(taskIds, bulkLog); - - List taskSummaries = this.createTaskQuery().idIn(taskIds.toArray(new String[0])).list(); - - checkIfTasksMatchCompleteCriteria(taskIds, taskSummaries, bulkLog); - - updateTasksToBeCompleted(taskIds, taskSummaries); - - return bulkLog; - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from to completeTasks(taskIds = {})", taskIdsToBeCompleted); - } - } - - @Override - public Task createTask(Task taskToCreate) - throws NotAuthorizedException, WorkbasketNotFoundException, ClassificationNotFoundException, - TaskAlreadyExistException, InvalidArgumentException { - LOGGER.debug("entry to createTask(task = {})", taskToCreate); - TaskImpl task = (TaskImpl) taskToCreate; - try { - taskanaEngine.openConnection(); - - if (task.getId() != null && !task.getId().equals("")) { - throw new TaskAlreadyExistException(task.getId()); - } - - LOGGER.debug("Task {} cannot be found, so it can be created.", task.getId()); - Workbasket workbasket; - - if (task.getWorkbasketSummary().getId() != null) { - workbasket = workbasketService.getWorkbasket(task.getWorkbasketSummary().getId()); - } else if (task.getWorkbasketKey() != null) { - workbasket = workbasketService.getWorkbasket(task.getWorkbasketKey(), task.getDomain()); - } else { - String workbasketId = taskanaEngine.getTaskRoutingManager().determineWorkbasketId(task); - if (workbasketId != null) { - workbasket = workbasketService.getWorkbasket(workbasketId); - task.setWorkbasketSummary(workbasket.asSummary()); - } else { - throw new InvalidArgumentException("Cannot create a task outside a workbasket"); - } - } - - if (workbasket.isMarkedForDeletion()) { - throw new WorkbasketNotFoundException(workbasket.getId(), - THE_WORKBASKET + workbasket.getId() + WAS_MARKED_FOR_DELETION); - } - - task.setWorkbasketSummary(workbasket.asSummary()); - task.setDomain(workbasket.getDomain()); - - workbasketService.checkAuthorization(task.getWorkbasketSummary().getId(), - WorkbasketPermission.APPEND); - - // we do use the key and not the ID to make sure that we use the classification from the right domain. - // otherwise we would have to check the classification and its domain for validity. - String classificationKey = task.getClassificationKey(); - if (classificationKey == null || classificationKey.length() == 0) { - throw new InvalidArgumentException("classificationKey of task must not be empty"); - } - - Classification classification = this.classificationService.getClassification(classificationKey, - workbasket.getDomain()); - task.setClassificationSummary(classification.asSummary()); - validateObjectReference(task.getPrimaryObjRef(), "primary ObjectReference", "Task"); - PrioDurationHolder prioDurationFromAttachments = handleAttachments(task); - standardSettings(task, classification, prioDurationFromAttachments); - setCallbackStateOnTaskCreation(task); - try { - this.taskMapper.insert(task); - LOGGER.debug("Method createTask() created Task '{}'.", task.getId()); - if (HistoryEventProducer.isHistoryEnabled()) { - historyEventProducer.createEvent(new CreatedEvent(task)); - } - } catch (PersistenceException e) { - // Error messages: - // Postgres: ERROR: duplicate key value violates unique constraint "uc_external_id" - // DB/2: ### Error updating database. Cause: com.ibm.db2.jcc.am.SqlIntegrityConstraintViolationException: DB2 SQL Error: SQLCODE=-803, SQLSTATE=23505, SQLERRMC=2;TASKANA.TASK, DRIVER=4.22.29 - // ### The error may involve pro.taskana.mappings.TaskMapper.insert-Inline - // ### The error occurred while setting parameters - // ### SQL: INSERT INTO TASK(ID, EXTERNAL_ID, CREATED, CLAIMED, COMPLETED, MODIFIED, PLANNED, DUE, NAME, CREATOR, DESCRIPTION, NOTE, PRIORITY, STATE, CLASSIFICATION_CATEGORY, CLASSIFICATION_KEY, CLASSIFICATION_ID, WORKBASKET_ID, WORKBASKET_KEY, DOMAIN, BUSINESS_PROCESS_ID, PARENT_BUSINESS_PROCESS_ID, OWNER, POR_COMPANY, POR_SYSTEM, POR_INSTANCE, POR_TYPE, POR_VALUE, IS_READ, IS_TRANSFERRED, CALLBACK_INFO, CUSTOM_ATTRIBUTES, CUSTOM_1, CUSTOM_2, CUSTOM_3, CUSTOM_4, CUSTOM_5, CUSTOM_6, CUSTOM_7, CUSTOM_8, CUSTOM_9, CUSTOM_10, CUSTOM_11, CUSTOM_12, CUSTOM_13, CUSTOM_14, CUSTOM_15, CUSTOM_16 ) VALUES(?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - // ### Cause: com.ibm.db2.jcc.am.SqlIntegrityConstraintViolationException: DB2 SQL Error: SQLCODE=-803, SQLSTATE=23505, SQLERRMC=2;TASKANA.TASK, DRIVER=4.22.29 - // H2: ### Error updating database. Cause: org.h2.jdbc.JdbcSQLException: Unique index or primary key violation: "UC_EXTERNAL_ID_INDEX_2 ON TASKANA.TASK(EXTERNAL_ID) ... - String msg = e.getMessage() != null ? e.getMessage().toLowerCase() : null; - if (msg != null - && (msg.contains("violation") || msg.contains("violates")) - && msg.contains("external_id")) { - throw new TaskAlreadyExistException( - "Task with external id " + task.getExternalId() + " already exists"); - } else { - throw e; - } - } - return task; - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from createTask(task = {})", task); - } - } - - @Override - public Task getTask(String id) throws TaskNotFoundException, NotAuthorizedException { - LOGGER.debug("entry to getTaskById(id = {})", id); - TaskImpl resultTask = null; - try { - taskanaEngine.openConnection(); - - resultTask = taskMapper.findById(id); - if (resultTask != null) { - WorkbasketQueryImpl query = (WorkbasketQueryImpl) workbasketService.createWorkbasketQuery(); - query.setUsedToAugmentTasks(true); - String workbasketId = resultTask.getWorkbasketSummary().getId(); - List workbaskets = query - .idIn(workbasketId) - .list(); - if (workbaskets.isEmpty()) { - String currentUser = CurrentUserContext.getUserid(); - throw new NotAuthorizedException( - "The current user " + currentUser + " has no read permission for workbasket " + workbasketId, - CurrentUserContext.getUserid()); - } else { - resultTask.setWorkbasketSummary(workbaskets.get(0)); - } - - List attachmentImpls = attachmentMapper.findAttachmentsByTaskId(resultTask.getId()); - if (attachmentImpls == null) { - attachmentImpls = new ArrayList<>(); - } - - List classifications; - classifications = findClassificationForTaskImplAndAttachments(resultTask, attachmentImpls); - List attachments = addClassificationSummariesToAttachments(attachmentImpls, - classifications); - resultTask.setAttachments(attachments); - - String classificationId = resultTask.getClassificationSummary().getId(); - ClassificationSummary classification = classifications.stream() - .filter(c -> c.getId().equals(classificationId)) - .findFirst() - .orElse(null); - if (classification == null) { - throw new SystemException( - "Could not find a Classification for task " + resultTask.getId()); - } - - resultTask.setClassificationSummary(classification); - return resultTask; - } else { - throw new TaskNotFoundException(id, TASK_WITH_ID + id + WAS_NOT_FOUND); - } - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from getTaskById(). Returning result {} ", resultTask); - } - } - - @Override - public Task setTaskRead(String taskId, boolean isRead) - throws TaskNotFoundException, NotAuthorizedException { - LOGGER.debug("entry to setTaskRead(taskId = {}, isRead = {})", taskId, isRead); - TaskImpl task = null; - try { - taskanaEngine.openConnection(); - task = (TaskImpl) getTask(taskId); - task.setRead(isRead); - task.setModified(Instant.now()); - taskMapper.update(task); - LOGGER.debug("Method setTaskRead() set read property of Task '{}' to {} ", task, isRead); - return task; - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from setTaskRead(taskId, isRead). Returning result {} ", task); - } - } - - @Override - public Task transfer(String taskId, String destinationWorkbasketId) - throws TaskNotFoundException, WorkbasketNotFoundException, NotAuthorizedException, InvalidStateException { - return taskTransferrer.transfer(taskId, destinationWorkbasketId); - } - - @Override - public Task transfer(String taskId, String workbasketKey, String domain) - throws TaskNotFoundException, WorkbasketNotFoundException, NotAuthorizedException, InvalidStateException { - return taskTransferrer.transfer(taskId, workbasketKey, domain); - } - - @Override - public BulkOperationResults transferTasks(String destinationWorkbasketId, - List taskIds) throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException { - return taskTransferrer.transferTasks(destinationWorkbasketId, taskIds); - } - - @Override - public BulkOperationResults transferTasks(String destinationWorkbasketKey, - String destinationWorkbasketDomain, List taskIds) - throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException { - return taskTransferrer.transferTasks(destinationWorkbasketKey, destinationWorkbasketDomain, taskIds); - } - - @Override - public TaskQuery createTaskQuery() { - return new TaskQueryImpl(taskanaEngine); - } - - @Override - public Task newTask() { - return newTask(null); - } - - @Override - public Task newTask(String workbasketId) { - TaskImpl task = new TaskImpl(); - WorkbasketSummaryImpl wb = new WorkbasketSummaryImpl(); - wb.setId(workbasketId); - task.setWorkbasketSummary(wb); - task.setCallbackState(CallbackState.NONE); - return task; - } - - @Override - public Task newTask(String workbasketKey, String domain) { - LOGGER.debug("entry to newTask(workbasketKey = {}, domain = {})", workbasketKey, domain); - TaskImpl task = new TaskImpl(); - WorkbasketSummaryImpl wb = new WorkbasketSummaryImpl(); - wb.setKey(workbasketKey); - wb.setDomain(domain); - task.setWorkbasketSummary(wb); - LOGGER.debug("exit from newTask(), returning {}", task); - return task; - } - - @Override - public Attachment newAttachment() { - return new AttachmentImpl(); - } - - @Override - public void deleteTask(String taskId) - throws TaskNotFoundException, InvalidStateException, NotAuthorizedException { - deleteTask(taskId, false); - } - - @Override - public void forceDeleteTask(String taskId) - throws TaskNotFoundException, InvalidStateException, NotAuthorizedException { - deleteTask(taskId, true); - } - - @Override - public BulkOperationResults deleteTasks(List taskIds) - throws InvalidArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("entry to deleteTasks(tasks = {})", LoggerUtils.listToString(taskIds)); - } - try { - taskanaEngine.openConnection(); - if (taskIds == null) { - throw new InvalidArgumentException("List of TaskIds must not be null."); - } - - BulkOperationResults bulkLog = new BulkOperationResults<>(); - - if (taskIds.isEmpty()) { - return bulkLog; - } - - List taskSummaries = taskMapper.findExistingTasks(taskIds, null); - - Iterator taskIdIterator = taskIds.iterator(); - while (taskIdIterator.hasNext()) { - removeSingleTaskForTaskDeletionById(bulkLog, taskSummaries, taskIdIterator); - } - if (!taskIds.isEmpty()) { - taskMapper.deleteMultiple(taskIds); - } - return bulkLog; - } finally { - LOGGER.debug("exit from deleteTasks()"); - taskanaEngine.returnConnection(); - } - } - - @Override - public BulkOperationResults setCallbackStateForTasks(List externalIds, - CallbackState state) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("entry to setCallbackStateForTasks(externalIds = {})", LoggerUtils.listToString(externalIds)); - } - try { - taskanaEngine.openConnection(); - - BulkOperationResults bulkLog = new BulkOperationResults<>(); - - if (externalIds == null || externalIds.isEmpty()) { - return bulkLog; - } - - List taskSummaries = taskMapper.findExistingTasks(null, externalIds); - - Iterator taskIdIterator = externalIds.iterator(); - while (taskIdIterator.hasNext()) { - removeSingleTaskForCallbackStateByExternalId(bulkLog, taskSummaries, taskIdIterator, state); - } - if (!externalIds.isEmpty()) { - taskMapper.setCallbackStateMultiple(externalIds, state); - } - return bulkLog; - } finally { - LOGGER.debug("exit from setCallbckStateForTasks()"); - taskanaEngine.returnConnection(); - } - } - - private void removeSingleTaskForTaskDeletionById(BulkOperationResults bulkLog, - List taskSummaries, Iterator taskIdIterator) { - LOGGER.debug("entry to removeSingleTask()"); - String currentTaskId = taskIdIterator.next(); - if (currentTaskId == null || currentTaskId.equals("")) { - bulkLog.addError("", - new InvalidArgumentException("IDs with EMPTY or NULL value are not allowed.")); - taskIdIterator.remove(); + if (task.getWorkbasketSummary().getId() != null) { + workbasket = workbasketService.getWorkbasket(task.getWorkbasketSummary().getId()); + } else if (task.getWorkbasketKey() != null) { + workbasket = workbasketService.getWorkbasket(task.getWorkbasketKey(), task.getDomain()); + } else { + String workbasketId = taskanaEngine.getTaskRoutingManager().determineWorkbasketId(task); + if (workbasketId != null) { + workbasket = workbasketService.getWorkbasket(workbasketId); + task.setWorkbasketSummary(workbasket.asSummary()); } else { - MinimalTaskSummary foundSummary = taskSummaries.stream() - .filter(taskSummary -> currentTaskId.equals(taskSummary.getTaskId())) - .findFirst() - .orElse(null); - if (foundSummary == null) { - bulkLog.addError(currentTaskId, new TaskNotFoundException(currentTaskId, - TASK_WITH_ID + currentTaskId + WAS_NOT_FOUND2)); - taskIdIterator.remove(); - } else if (!TaskState.COMPLETED.equals(foundSummary.getTaskState())) { - bulkLog.addError(currentTaskId, new InvalidStateException(currentTaskId)); - taskIdIterator.remove(); - } else { - if (CallbackState.CALLBACK_PROCESSING_REQUIRED.equals(foundSummary.getCallbackState())) { - bulkLog.addError(currentTaskId, new InvalidStateException("Task " + currentTaskId - + " cannot be deleted before callback is processed")); - taskIdIterator.remove(); - } - } + throw new InvalidArgumentException("Cannot create a task outside a workbasket"); } - LOGGER.debug("exit from removeSingleTask()"); - } + } - private void removeSingleTaskForCallbackStateByExternalId(BulkOperationResults bulkLog, - List taskSummaries, Iterator externalIdIterator, CallbackState desiredCallbackState) { - LOGGER.debug("entry to removeSingleTask()"); - String currentExternalId = externalIdIterator.next(); - if (currentExternalId == null || currentExternalId.equals("")) { - bulkLog.addError("", - new InvalidArgumentException("IDs with EMPTY or NULL value are not allowed.")); - externalIdIterator.remove(); + if (workbasket.isMarkedForDeletion()) { + throw new WorkbasketNotFoundException( + workbasket.getId(), THE_WORKBASKET + workbasket.getId() + WAS_MARKED_FOR_DELETION); + } + + task.setWorkbasketSummary(workbasket.asSummary()); + task.setDomain(workbasket.getDomain()); + + workbasketService.checkAuthorization( + task.getWorkbasketSummary().getId(), WorkbasketPermission.APPEND); + + // we do use the key and not the ID to make sure that we use the classification from the right + // domain. + // otherwise we would have to check the classification and its domain for validity. + String classificationKey = task.getClassificationKey(); + if (classificationKey == null || classificationKey.length() == 0) { + throw new InvalidArgumentException("classificationKey of task must not be empty"); + } + + Classification classification = + this.classificationService.getClassification(classificationKey, workbasket.getDomain()); + task.setClassificationSummary(classification.asSummary()); + validateObjectReference(task.getPrimaryObjRef(), "primary ObjectReference", "Task"); + PrioDurationHolder prioDurationFromAttachments = handleAttachments(task); + standardSettings(task, classification, prioDurationFromAttachments); + setCallbackStateOnTaskCreation(task); + try { + this.taskMapper.insert(task); + LOGGER.debug("Method createTask() created Task '{}'.", task.getId()); + if (HistoryEventProducer.isHistoryEnabled()) { + historyEventProducer.createEvent(new CreatedEvent(task)); + } + } catch (PersistenceException e) { + // Error messages: + // Postgres: ERROR: duplicate key value violates unique constraint "uc_external_id" + // DB/2: ### Error updating database. Cause: + // com.ibm.db2.jcc.am.SqlIntegrityConstraintViolationException: DB2 SQL Error: SQLCODE=-803, + // SQLSTATE=23505, SQLERRMC=2;TASKANA.TASK, DRIVER=4.22.29 + // ### The error may involve pro.taskana.mappings.TaskMapper.insert-Inline + // ### The error occurred while setting parameters + // ### SQL: INSERT INTO TASK(ID, EXTERNAL_ID, CREATED, CLAIMED, COMPLETED, MODIFIED, + // PLANNED, DUE, NAME, CREATOR, DESCRIPTION, NOTE, PRIORITY, STATE, + // CLASSIFICATION_CATEGORY, CLASSIFICATION_KEY, CLASSIFICATION_ID, WORKBASKET_ID, + // WORKBASKET_KEY, DOMAIN, BUSINESS_PROCESS_ID, PARENT_BUSINESS_PROCESS_ID, OWNER, + // POR_COMPANY, POR_SYSTEM, POR_INSTANCE, POR_TYPE, POR_VALUE, IS_READ, IS_TRANSFERRED, + // CALLBACK_INFO, CUSTOM_ATTRIBUTES, CUSTOM_1, CUSTOM_2, CUSTOM_3, CUSTOM_4, CUSTOM_5, + // CUSTOM_6, CUSTOM_7, CUSTOM_8, CUSTOM_9, CUSTOM_10, CUSTOM_11, CUSTOM_12, CUSTOM_13, + // CUSTOM_14, CUSTOM_15, CUSTOM_16 ) VALUES(?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, + // ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, + // ?, ?) + // ### Cause: com.ibm.db2.jcc.am.SqlIntegrityConstraintViolationException: DB2 SQL + // Error: SQLCODE=-803, SQLSTATE=23505, SQLERRMC=2;TASKANA.TASK, DRIVER=4.22.29 + // H2: ### Error updating database. Cause: org.h2.jdbc.JdbcSQLException: Unique index or + // primary key violation: "UC_EXTERNAL_ID_INDEX_2 ON TASKANA.TASK(EXTERNAL_ID) ... + String msg = e.getMessage() != null ? e.getMessage().toLowerCase() : null; + if (msg != null + && (msg.contains("violation") || msg.contains("violates")) + && msg.contains("external_id")) { + throw new TaskAlreadyExistException( + "Task with external id " + task.getExternalId() + " already exists"); } else { - MinimalTaskSummary foundSummary = taskSummaries.stream() - .filter(taskSummary -> currentExternalId.equals(taskSummary.getExternalId())) - .findFirst() - .orElse(null); - if (foundSummary == null) { - bulkLog.addError(currentExternalId, new TaskNotFoundException(currentExternalId, - TASK_WITH_ID + currentExternalId + WAS_NOT_FOUND2)); - externalIdIterator.remove(); - } else if (!desiredCallbackStateCanBeSetForFoundSummary(foundSummary, desiredCallbackState)) { - bulkLog.addError(currentExternalId, new InvalidStateException(currentExternalId)); - externalIdIterator.remove(); - } - + throw e; } - LOGGER.debug("exit from removeSingleTask()"); + } + return task; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from createTask(task = {})", task); } + } - private boolean desiredCallbackStateCanBeSetForFoundSummary(MinimalTaskSummary foundSummary, CallbackState desiredCallbackState) { + @Override + public Task getTask(String id) throws TaskNotFoundException, NotAuthorizedException { + LOGGER.debug("entry to getTaskById(id = {})", id); + TaskImpl resultTask = null; + try { + taskanaEngine.openConnection(); - CallbackState currentTaskCallbackState = foundSummary.getCallbackState(); - TaskState currentTaskState = foundSummary.getTaskState(); - - switch (desiredCallbackState) { - - case CALLBACK_PROCESSING_COMPLETED: - if (!(currentTaskState.equals(TaskState.COMPLETED))) { - return false; - } - return true; - - case CLAIMED: - if (!currentTaskState.equals(TaskState.CLAIMED)) { - return false; - } else if (!currentTaskCallbackState.equals(CallbackState.CALLBACK_PROCESSING_REQUIRED)) { - return false; - } - return true; - - case CALLBACK_PROCESSING_REQUIRED: - if (currentTaskCallbackState.equals(CallbackState.CALLBACK_PROCESSING_COMPLETED)) { - return false; - } - return true; - case NONE: - return false; - - default: - return false; - } - - } - - @Override - public List updateTasks(ObjectReference selectionCriteria, - Map customFieldsToUpdate) throws InvalidArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("entry to updateTasks(selectionCriteria = {}, customFieldsToUpdate = {})", selectionCriteria, - customFieldsToUpdate); - } - validateObjectReference(selectionCriteria, "ObjectReference", "updateTasks call"); - validateCustomFields(customFieldsToUpdate); - CustomPropertySelector fieldSelector = new CustomPropertySelector(); - TaskImpl updated = initUpdatedTask(customFieldsToUpdate, fieldSelector); - - try { - taskanaEngine.openConnection(); - - // use query in order to find only those tasks that are visible to the current user - List taskSummaries = getTasksToChange(selectionCriteria); - - List changedTasks = new ArrayList<>(); - if (!taskSummaries.isEmpty()) { - changedTasks = taskSummaries.stream().map(TaskSummary::getTaskId).collect(Collectors.toList()); - taskMapper.updateTasks(changedTasks, updated, fieldSelector); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("updateTasks() updated the following tasks: {} ", - LoggerUtils.listToString(changedTasks)); - } - - } else { - LOGGER.debug("updateTasks() found no tasks for update "); - } - return changedTasks; - } finally { - LOGGER.debug("exit from updateTasks()."); - taskanaEngine.returnConnection(); - } - } - - @Override - public List updateTasks(List taskIds, Map customFieldsToUpdate) - throws InvalidArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("entry to updateTasks(taskIds = {}, customFieldsToUpdate = {})", taskIds, - customFieldsToUpdate); - } - - validateCustomFields(customFieldsToUpdate); - CustomPropertySelector fieldSelector = new CustomPropertySelector(); - TaskImpl updatedTask = initUpdatedTask(customFieldsToUpdate, fieldSelector); - - try { - taskanaEngine.openConnection(); - - // use query in order to find only those tasks that are visible to the current user - List taskSummaries = getTasksToChange(taskIds); - - List changedTasks = new ArrayList<>(); - if (!taskSummaries.isEmpty()) { - changedTasks = taskSummaries.stream().map(TaskSummary::getTaskId).collect(Collectors.toList()); - taskMapper.updateTasks(changedTasks, updatedTask, fieldSelector); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("updateTasks() updated the following tasks: {} ", - LoggerUtils.listToString(changedTasks)); - } - - } else { - LOGGER.debug("updateTasks() found no tasks for update "); - } - return changedTasks; - } finally { - LOGGER.debug("exit from updateTasks()."); - taskanaEngine.returnConnection(); - } - } - - @Override - public Task updateTask(Task task) - throws InvalidArgumentException, TaskNotFoundException, ConcurrencyException, - ClassificationNotFoundException, NotAuthorizedException, AttachmentPersistenceException { - String userId = CurrentUserContext.getUserid(); - LOGGER.debug("entry to updateTask(task = {}, userId = {})", task, userId); - TaskImpl newTaskImpl = (TaskImpl) task; - TaskImpl oldTaskImpl = null; - try { - taskanaEngine.openConnection(); - oldTaskImpl = (TaskImpl) getTask(newTaskImpl.getId()); - PrioDurationHolder prioDurationFromAttachments = handleAttachmentsOnTaskUpdate(oldTaskImpl, newTaskImpl); - standardUpdateActions(oldTaskImpl, newTaskImpl, prioDurationFromAttachments); - - taskMapper.update(newTaskImpl); - LOGGER.debug("Method updateTask() updated task '{}' for user '{}'.", task.getId(), userId); - - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from claim()"); - } - return task; - } - - private void standardSettings(TaskImpl task, Classification classification, - PrioDurationHolder prioDurationFromAttachments) throws InvalidArgumentException { - LOGGER.debug("entry to standardSettings()"); - Instant now = Instant.now(); - task.setId(IdGenerator.generateWithPrefix(ID_PREFIX_TASK)); - if (task.getExternalId() == null) { - task.setExternalId(IdGenerator.generateWithPrefix(ID_PREFIX_EXT_TASK_ID)); - } - task.setState(TaskState.READY); - task.setCreated(now); - task.setModified(now); - task.setRead(false); - task.setTransferred(false); - - String creator = CurrentUserContext.getUserid(); - if (taskanaEngine.getEngine().getConfiguration().isSecurityEnabled() && creator == null) { - throw new SystemException( - "TaskanaSecurity is enabled, but the current UserId is NULL while creating a Task."); - } - task.setCreator(creator); - - // if no business process id is provided, a unique id is created. - if (task.getBusinessProcessId() == null) { - task.setBusinessProcessId(IdGenerator.generateWithPrefix(ID_PREFIX_BUSINESS_PROCESS)); - } - - //null in case of manual tasks - if (classification == null) { - if (task.getPlanned() == null) { - task.setPlanned(now); - } + resultTask = taskMapper.findById(id); + if (resultTask != null) { + WorkbasketQueryImpl query = (WorkbasketQueryImpl) workbasketService.createWorkbasketQuery(); + query.setUsedToAugmentTasks(true); + String workbasketId = resultTask.getWorkbasketSummary().getId(); + List workbaskets = query.idIn(workbasketId).list(); + if (workbaskets.isEmpty()) { + String currentUser = CurrentUserContext.getUserid(); + throw new NotAuthorizedException( + "The current user " + + currentUser + + " has no read permission for workbasket " + + workbasketId, + CurrentUserContext.getUserid()); } else { - // do some Classification specific stuff (servicelevel). - // get duration in days from planned to due - PrioDurationHolder finalPrioDuration = getNewPrioDuration(prioDurationFromAttachments, - classification.getPriority(), classification.getServiceLevel()); - Duration finalDuration = finalPrioDuration.getDuration(); - if (finalDuration != null && !MAX_DURATION.equals(finalDuration)) { - // if we have a due date we need to go x days backwards, - // else we take the planned date (or now as fallback) and add x Days - if (task.getDue() != null) { - long days = converter.convertWorkingDaysToDays(task.getDue(), -finalDuration.toDays()); - //days < 0 -> so we ne need to add, not substract - Instant planned = task.getDue().plus(Duration.ofDays(days)); - if (task.getPlanned() != null && !task.getPlanned().equals(planned)) { - throw new InvalidArgumentException( - "Cannot create a task with given planned and due date not matching the service level"); - } - task.setPlanned(planned); - } else { - task.setPlanned(task.getPlanned() == null ? now : task.getPlanned()); - long days = converter.convertWorkingDaysToDays(task.getPlanned(), finalDuration.toDays()); - Instant due = task.getPlanned().plus(Duration.ofDays(days)); - task.setDue(due); - } - } - task.setPriority(finalPrioDuration.getPrio()); + resultTask.setWorkbasketSummary(workbaskets.get(0)); } - if (task.getName() == null && classification != null) { - task.setName(classification.getName()); + List attachmentImpls = + attachmentMapper.findAttachmentsByTaskId(resultTask.getId()); + if (attachmentImpls == null) { + attachmentImpls = new ArrayList<>(); } - if (task.getDescription() == null && classification != null) { - task.setDescription(classification.getDescription()); - } + List classifications; + classifications = findClassificationForTaskImplAndAttachments(resultTask, attachmentImpls); + List attachments = + addClassificationSummariesToAttachments(attachmentImpls, classifications); + resultTask.setAttachments(attachments); - // insert Attachments if needed - List attachments = task.getAttachments(); - if (attachments != null) { - for (Attachment attachment : attachments) { - AttachmentImpl attachmentImpl = (AttachmentImpl) attachment; - attachmentImpl.setId(IdGenerator.generateWithPrefix(ID_PREFIX_ATTACHMENT)); - attachmentImpl.setTaskId(task.getId()); - attachmentImpl.setCreated(now); - attachmentImpl.setModified(now); - attachmentMapper.insert(attachmentImpl); - } - } - LOGGER.debug("exit from standardSettings()"); - } - - private void setCallbackStateOnTaskCreation(TaskImpl task) throws InvalidArgumentException { - Map callbackInfo = task.getCallbackInfo(); - if (callbackInfo != null && callbackInfo.containsKey(Task.CALLBACK_STATE)) { - String value = callbackInfo.get(Task.CALLBACK_STATE); - if (value != null && !value.isEmpty()) { - try { - CallbackState state = CallbackState.valueOf(value); - task.setCallbackState(state); - } catch (Exception e) { - LOGGER.warn("Attempted to determine callback state from {} and caught {}", value, e); - throw new InvalidArgumentException("Attempted to set callback state for task " - + task.getId(), e); - } - } - } - } - - void removeNonExistingTasksFromTaskIdList(List taskIds, - BulkOperationResults bulkLog) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("entry to removeNonExistingTasksFromTaskIdList(targetWbId = {}, taskIds = {})", taskIds, - bulkLog); - } - - Iterator taskIdIterator = taskIds.iterator(); - while (taskIdIterator.hasNext()) { - String currentTaskId = taskIdIterator.next(); - if (currentTaskId == null || currentTaskId.equals("")) { - bulkLog.addError("", - new InvalidArgumentException("IDs with EMPTY or NULL value are not allowed.")); - taskIdIterator.remove(); - } - } - LOGGER.debug("exit from removeNonExistingTasksFromTaskIdList()"); - } - - private void checkIfTasksMatchCompleteCriteria(List taskIds, List taskSummaries, - BulkOperationResults bulkLog) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("entry to checkIfTasksMatchCompleteCriteria(taskIds = {}, taskSummaries = {}, bulkLog = {})", - LoggerUtils.listToString(taskIds), LoggerUtils.listToString(taskSummaries), bulkLog); - } - - Instant now = Instant.now(); - Iterator taskIdIterator = taskIds.iterator(); - while (taskIdIterator.hasNext()) { - String currentTaskId = taskIdIterator.next(); - TaskSummaryImpl taskSummary = (TaskSummaryImpl) taskSummaries.stream() - .filter(ts -> currentTaskId.equals(ts.getTaskId())) - .findFirst() - .orElse(null); - if (taskSummary == null) { - bulkLog.addError(currentTaskId, new TaskNotFoundException(currentTaskId, "task with id " - + currentTaskId + WAS_NOT_FOUND2)); - taskIdIterator.remove(); - } else if (taskSummary.getClaimed() == null || taskSummary.getState() != TaskState.CLAIMED) { - bulkLog.addError(currentTaskId, new InvalidStateException(currentTaskId)); - taskIdIterator.remove(); - } else if (!CurrentUserContext.getAccessIds().contains(taskSummary.getOwner())) { - bulkLog.addError(currentTaskId, new InvalidOwnerException( - "TaskOwner is" + taskSummary.getOwner() + ", but current User is " - + CurrentUserContext.getUserid())); - taskIdIterator.remove(); - } else { - taskSummary.setCompleted(now); - taskSummary.setModified(now); - taskSummary.setState(TaskState.COMPLETED); - } - } - LOGGER.debug("exit from checkIfTasksMatchCompleteCriteria()"); - } - - private void updateTasksToBeCompleted(List taskIds, - List taskSummaries) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("entry to updateTasksToBeCompleted(taskIds = {}, taskSummaries = {})", - LoggerUtils.listToString(taskIds), LoggerUtils.listToString(taskSummaries)); - } - - if (!taskIds.isEmpty() && !taskSummaries.isEmpty()) { - taskMapper.updateCompleted(taskIds, (TaskSummaryImpl) taskSummaries.get(0)); - if (HistoryEventProducer.isHistoryEnabled()) { - createTasksCompletedEvents(taskSummaries); - } - } - LOGGER.debug("exit from updateTasksToBeCompleted()"); - } - - private Task cancelClaim(String taskId, boolean forceUnclaim) - throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, NotAuthorizedException { - String userId = CurrentUserContext.getUserid(); - LOGGER.debug("entry to cancelClaim(taskId = {}), userId = {}, forceUnclaim = {})", taskId, userId, - forceUnclaim); - TaskImpl task = null; - try { - taskanaEngine.openConnection(); - task = (TaskImpl) getTask(taskId); - TaskState state = task.getState(); - if (state == TaskState.COMPLETED) { - throw new InvalidStateException(TASK_WITH_ID + taskId + IS_ALREADY_COMPLETED); - } - if (state == TaskState.CLAIMED && !forceUnclaim && !userId.equals(task.getOwner())) { - throw new InvalidOwnerException( - TASK_WITH_ID + taskId + IS_ALREADY_CLAIMED_BY + task.getOwner() + "."); - } - Instant now = Instant.now(); - task.setOwner(null); - task.setModified(now); - task.setClaimed(null); - task.setRead(true); - task.setState(TaskState.READY); - taskMapper.update(task); - LOGGER.debug("Task '{}' unclaimed by user '{}'.", taskId, userId); - if (HistoryEventProducer.isHistoryEnabled()) { - historyEventProducer.createEvent(new ClaimCancelledEvent(task)); - } - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from cancelClaim()"); - } - return task; - } - - private void addClassificationSummariesToTaskSummaries(List tasks, - List classifications) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("entry to addClassificationSummariesToTaskSummaries(tasks = {}, classifications = {})", - LoggerUtils.listToString(tasks), LoggerUtils.listToString(classifications)); - } - - if (tasks == null || tasks.isEmpty()) { - LOGGER.debug("exit from addClassificationSummariesToTaskSummaries()"); - return; - } - // assign query results to appropriate tasks. - for (TaskSummaryImpl task : tasks) { - String classificationId = task.getClassificationSummary().getId(); - ClassificationSummary aClassification = classifications.stream() + String classificationId = resultTask.getClassificationSummary().getId(); + ClassificationSummary classification = + classifications.stream() .filter(c -> c.getId().equals(classificationId)) .findFirst() .orElse(null); - if (aClassification == null) { - throw new SystemException( - "Did not find a Classification for task (Id=" + task.getTaskId() + ",classification=" - + task.getClassificationSummary().getId() + ")"); - } - // set the classification on the task object - task.setClassificationSummary(aClassification); + if (classification == null) { + throw new SystemException( + "Could not find a Classification for task " + resultTask.getId()); } - LOGGER.debug("exit from addClassificationSummariesToTaskSummaries()"); + + resultTask.setClassificationSummary(classification); + return resultTask; + } else { + throw new TaskNotFoundException(id, TASK_WITH_ID + id + WAS_NOT_FOUND); + } + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from getTaskById(). Returning result {} ", resultTask); } + } - private List findClassificationsForTasksAndAttachments( - List taskSummaries, List attachmentSummaries) { - LOGGER.debug("entry to findClassificationsForTasksAndAttachments()"); - if (taskSummaries == null || taskSummaries.isEmpty()) { - return new ArrayList<>(); - } - - Set classificationIdSet = taskSummaries.stream() - .map(t -> t.getClassificationSummary().getId()) - .collect( - Collectors.toSet()); - - if (attachmentSummaries != null && !attachmentSummaries.isEmpty()) { - for (AttachmentSummaryImpl att : attachmentSummaries) { - classificationIdSet.add(att.getClassificationSummary().getId()); - } - } - LOGGER.debug("exit from findClassificationsForTasksAndAttachments()"); - return queryClassificationsForTasksAndAttachments(classificationIdSet); + @Override + public Task setTaskRead(String taskId, boolean isRead) + throws TaskNotFoundException, NotAuthorizedException { + LOGGER.debug("entry to setTaskRead(taskId = {}, isRead = {})", taskId, isRead); + TaskImpl task = null; + try { + taskanaEngine.openConnection(); + task = (TaskImpl) getTask(taskId); + task.setRead(isRead); + task.setModified(Instant.now()); + taskMapper.update(task); + LOGGER.debug("Method setTaskRead() set read property of Task '{}' to {} ", task, isRead); + return task; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from setTaskRead(taskId, isRead). Returning result {} ", task); } + } - private List findClassificationForTaskImplAndAttachments(TaskImpl task, - List attachmentImpls) { - LOGGER.debug("entry to transferBulk()"); - Set classificationIdSet = new HashSet<>(Arrays.asList(task.getClassificationSummary().getId())); - if (attachmentImpls != null && !attachmentImpls.isEmpty()) { - for (AttachmentImpl att : attachmentImpls) { - classificationIdSet.add(att.getClassificationSummary().getId()); - } - } - LOGGER.debug("exit from findClassificationForTaskImplAndAttachments()"); - return queryClassificationsForTasksAndAttachments(classificationIdSet); + @Override + public Task transfer(String taskId, String destinationWorkbasketId) + throws TaskNotFoundException, WorkbasketNotFoundException, NotAuthorizedException, + InvalidStateException { + return taskTransferrer.transfer(taskId, destinationWorkbasketId); + } + + @Override + public Task transfer(String taskId, String workbasketKey, String domain) + throws TaskNotFoundException, WorkbasketNotFoundException, NotAuthorizedException, + InvalidStateException { + return taskTransferrer.transfer(taskId, workbasketKey, domain); + } + + @Override + public BulkOperationResults transferTasks( + String destinationWorkbasketId, List taskIds) + throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException { + return taskTransferrer.transferTasks(destinationWorkbasketId, taskIds); + } + + @Override + public BulkOperationResults transferTasks( + String destinationWorkbasketKey, String destinationWorkbasketDomain, List taskIds) + throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException { + return taskTransferrer.transferTasks( + destinationWorkbasketKey, destinationWorkbasketDomain, taskIds); + } + + @Override + public TaskQuery createTaskQuery() { + return new TaskQueryImpl(taskanaEngine); + } + + @Override + public Task newTask() { + return newTask(null); + } + + @Override + public Task newTask(String workbasketId) { + TaskImpl task = new TaskImpl(); + WorkbasketSummaryImpl wb = new WorkbasketSummaryImpl(); + wb.setId(workbasketId); + task.setWorkbasketSummary(wb); + task.setCallbackState(CallbackState.NONE); + return task; + } + + @Override + public Task newTask(String workbasketKey, String domain) { + LOGGER.debug("entry to newTask(workbasketKey = {}, domain = {})", workbasketKey, domain); + TaskImpl task = new TaskImpl(); + WorkbasketSummaryImpl wb = new WorkbasketSummaryImpl(); + wb.setKey(workbasketKey); + wb.setDomain(domain); + task.setWorkbasketSummary(wb); + LOGGER.debug("exit from newTask(), returning {}", task); + return task; + } + + @Override + public Attachment newAttachment() { + return new AttachmentImpl(); + } + + @Override + public void deleteTask(String taskId) + throws TaskNotFoundException, InvalidStateException, NotAuthorizedException { + deleteTask(taskId, false); + } + + @Override + public void forceDeleteTask(String taskId) + throws TaskNotFoundException, InvalidStateException, NotAuthorizedException { + deleteTask(taskId, true); + } + + @Override + public BulkOperationResults deleteTasks(List taskIds) + throws InvalidArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("entry to deleteTasks(tasks = {})", LoggerUtils.listToString(taskIds)); } + try { + taskanaEngine.openConnection(); + if (taskIds == null) { + throw new InvalidArgumentException("List of TaskIds must not be null."); + } - private List queryClassificationsForTasksAndAttachments(Set classificationIdSet) { + BulkOperationResults bulkLog = new BulkOperationResults<>(); - String[] classificationIdArray = classificationIdSet.toArray(new String[0]); + if (taskIds.isEmpty()) { + return bulkLog; + } - LOGGER.debug("getClassificationsForTasksAndAttachments() about to query classifications and exit"); - // perform classification query - return this.classificationService.createClassificationQuery() - .idIn(classificationIdArray) - .list(); + List taskSummaries = taskMapper.findExistingTasks(taskIds, null); + + Iterator taskIdIterator = taskIds.iterator(); + while (taskIdIterator.hasNext()) { + removeSingleTaskForTaskDeletionById(bulkLog, taskSummaries, taskIdIterator); + } + if (!taskIds.isEmpty()) { + taskMapper.deleteMultiple(taskIds); + } + return bulkLog; + } finally { + LOGGER.debug("exit from deleteTasks()"); + taskanaEngine.returnConnection(); } + } - private void addWorkbasketSummariesToTaskSummaries(List taskSummaries) { - LOGGER.debug("entry to addWorkbasketSummariesToTaskSummaries()"); - if (taskSummaries == null || taskSummaries.isEmpty()) { - return; - } - // calculate parameters for workbasket query: workbasket keys - Set workbasketIdSet = taskSummaries.stream() - .map(t -> t.getWorkbasketSummary().getId()) - .collect( - Collectors.toSet()); - String[] workbasketIdArray = workbasketIdSet.toArray(new String[0]); - LOGGER.debug("addWorkbasketSummariesToTaskSummaries() about to query workbaskets"); - WorkbasketQueryImpl query = (WorkbasketQueryImpl) workbasketService.createWorkbasketQuery(); - query.setUsedToAugmentTasks(true); - - List workbaskets = query - .idIn(workbasketIdArray) - .list(); - Iterator taskIterator = taskSummaries.iterator(); - while (taskIterator.hasNext()) { - TaskSummaryImpl task = taskIterator.next(); - String workbasketId = task.getWorkbasketSummaryImpl().getId(); - - WorkbasketSummary aWorkbasket = workbaskets.stream() - .filter(x -> workbasketId != null && workbasketId.equals(x.getId())) - .findFirst() - .orElse(null); - if (aWorkbasket == null) { - LOGGER.warn("Could not find a Workbasket for task {}.", task.getTaskId()); - taskIterator.remove(); - continue; - } - - task.setWorkbasketSummary(aWorkbasket); - } - LOGGER.debug("exit from addWorkbasketSummariesToTaskSummaries()"); + @Override + public BulkOperationResults setCallbackStateForTasks( + List externalIds, CallbackState state) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "entry to setCallbackStateForTasks(externalIds = {})", + LoggerUtils.listToString(externalIds)); } + try { + taskanaEngine.openConnection(); - private void addAttachmentSummariesToTaskSummaries(List taskSummaries, - List attachmentSummaries, List classifications) { + BulkOperationResults bulkLog = new BulkOperationResults<>(); + + if (externalIds == null || externalIds.isEmpty()) { + return bulkLog; + } + + List taskSummaries = taskMapper.findExistingTasks(null, externalIds); + + Iterator taskIdIterator = externalIds.iterator(); + while (taskIdIterator.hasNext()) { + removeSingleTaskForCallbackStateByExternalId(bulkLog, taskSummaries, taskIdIterator, state); + } + if (!externalIds.isEmpty()) { + taskMapper.setCallbackStateMultiple(externalIds, state); + } + return bulkLog; + } finally { + LOGGER.debug("exit from setCallbckStateForTasks()"); + taskanaEngine.returnConnection(); + } + } + + @Override + public List updateTasks( + ObjectReference selectionCriteria, Map customFieldsToUpdate) + throws InvalidArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "entry to updateTasks(selectionCriteria = {}, customFieldsToUpdate = {})", + selectionCriteria, + customFieldsToUpdate); + } + validateObjectReference(selectionCriteria, "ObjectReference", "updateTasks call"); + validateCustomFields(customFieldsToUpdate); + CustomPropertySelector fieldSelector = new CustomPropertySelector(); + TaskImpl updated = initUpdatedTask(customFieldsToUpdate, fieldSelector); + + try { + taskanaEngine.openConnection(); + + // use query in order to find only those tasks that are visible to the current user + List taskSummaries = getTasksToChange(selectionCriteria); + + List changedTasks = new ArrayList<>(); + if (!taskSummaries.isEmpty()) { + changedTasks = + taskSummaries.stream().map(TaskSummary::getTaskId).collect(Collectors.toList()); + taskMapper.updateTasks(changedTasks, updated, fieldSelector); if (LOGGER.isDebugEnabled()) { - LOGGER.debug( - "entry to addAttachmentSummariesToTaskSummaries(taskSummaries = {}, attachmentSummaries = {}, classifications = {})", - LoggerUtils.listToString(taskSummaries), LoggerUtils.listToString(attachmentSummaries), - LoggerUtils.listToString(classifications)); + LOGGER.debug( + "updateTasks() updated the following tasks: {} ", + LoggerUtils.listToString(changedTasks)); } - if (taskSummaries == null || taskSummaries.isEmpty()) { - return; - } + } else { + LOGGER.debug("updateTasks() found no tasks for update "); + } + return changedTasks; + } finally { + LOGGER.debug("exit from updateTasks()."); + taskanaEngine.returnConnection(); + } + } - // augment attachment summaries by classification summaries - // Note: - // the mapper sets for each Attachment summary the property classificationSummary.key from the - // CLASSIFICATION_KEY property in the DB - addClassificationSummariesToAttachmentSummaries(attachmentSummaries, taskSummaries, classifications); - // assign attachment summaries to task summaries - for (TaskSummaryImpl task : taskSummaries) { - for (AttachmentSummaryImpl attachment : attachmentSummaries) { - if (attachment.getTaskId() != null && attachment.getTaskId().equals(task.getTaskId())) { - task.addAttachmentSummary(attachment); - } - } - } - - LOGGER.debug("exit from addAttachmentSummariesToTaskSummaries()"); + @Override + public List updateTasks(List taskIds, Map customFieldsToUpdate) + throws InvalidArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "entry to updateTasks(taskIds = {}, customFieldsToUpdate = {})", + taskIds, + customFieldsToUpdate); } - private void addClassificationSummariesToAttachmentSummaries(List attachmentSummaries, - List taskSummaries, List classifications) { - LOGGER.debug("entry to addClassificationSummariesToAttachmentSummaries()"); - // prereq: in each attachmentSummary, the classificationSummary.key property is set. - if (attachmentSummaries == null || attachmentSummaries.isEmpty() || taskSummaries == null - || taskSummaries.isEmpty()) { - LOGGER.debug("exit from addClassificationSummariesToAttachmentSummaries()"); - return; - } - // iterate over all attachment summaries an add the appropriate classification summary to each - for (AttachmentSummaryImpl att : attachmentSummaries) { - String classificationId = att.getClassificationSummary().getId(); - ClassificationSummary aClassification = classifications.stream() - .filter(x -> classificationId != null && classificationId.equals(x.getId())) - .findFirst() - .orElse(null); - if (aClassification == null) { - throw new SystemException("Could not find a Classification for attachment " + att); - } - att.setClassificationSummary(aClassification); - } - LOGGER.debug("exit from addClassificationSummariesToAttachmentSummaries()"); - } + validateCustomFields(customFieldsToUpdate); + CustomPropertySelector fieldSelector = new CustomPropertySelector(); + TaskImpl updatedTask = initUpdatedTask(customFieldsToUpdate, fieldSelector); - private List addClassificationSummariesToAttachments(List attachmentImpls, - List classifications) { + try { + taskanaEngine.openConnection(); + + // use query in order to find only those tasks that are visible to the current user + List taskSummaries = getTasksToChange(taskIds); + + List changedTasks = new ArrayList<>(); + if (!taskSummaries.isEmpty()) { + changedTasks = + taskSummaries.stream().map(TaskSummary::getTaskId).collect(Collectors.toList()); + taskMapper.updateTasks(changedTasks, updatedTask, fieldSelector); if (LOGGER.isDebugEnabled()) { - LOGGER.debug("entry to addClassificationSummariesToAttachments(targetWbId = {}, taskIds = {})", - LoggerUtils.listToString(attachmentImpls), LoggerUtils.listToString(classifications)); + LOGGER.debug( + "updateTasks() updated the following tasks: {} ", + LoggerUtils.listToString(changedTasks)); } - if (attachmentImpls == null || attachmentImpls.isEmpty()) { - LOGGER.debug("exit from addClassificationSummariesToAttachments()"); - return new ArrayList<>(); - } - - List result = new ArrayList<>(); - for (AttachmentImpl att : attachmentImpls) { - // find the associated task to use the correct domain - ClassificationSummary aClassification = classifications.stream() - .filter(c -> c != null && c.getId().equals(att.getClassificationSummary().getId())) - .findFirst() - .orElse(null); - - if (aClassification == null) { - throw new SystemException("Could not find a Classification for attachment " + att); - } - att.setClassificationSummary(aClassification); - result.add(att); - } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("exit from addClassificationSummariesToAttachments(), returning {}", result); - } - - return result; + } else { + LOGGER.debug("updateTasks() found no tasks for update "); + } + return changedTasks; + } finally { + LOGGER.debug("exit from updateTasks()."); + taskanaEngine.returnConnection(); } + } - private TaskImpl initUpdatedTask(Map customFieldsToUpdate, CustomPropertySelector fieldSelector) - throws InvalidArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("entry to initUpdatedTask(customFieldsToUpdate = {}, fieldSelector = {})", - LoggerUtils.mapToString(customFieldsToUpdate), fieldSelector); - } + @Override + public Task updateTask(Task task) + throws InvalidArgumentException, TaskNotFoundException, ConcurrencyException, + ClassificationNotFoundException, NotAuthorizedException, AttachmentPersistenceException { + String userId = CurrentUserContext.getUserid(); + LOGGER.debug("entry to updateTask(task = {}, userId = {})", task, userId); + TaskImpl newTaskImpl = (TaskImpl) task; + TaskImpl oldTaskImpl = null; + try { + taskanaEngine.openConnection(); + oldTaskImpl = (TaskImpl) getTask(newTaskImpl.getId()); + PrioDurationHolder prioDurationFromAttachments = + handleAttachmentsOnTaskUpdate(oldTaskImpl, newTaskImpl); + standardUpdateActions(oldTaskImpl, newTaskImpl, prioDurationFromAttachments); - TaskImpl newTask = new TaskImpl(); - newTask.setModified(Instant.now()); + taskMapper.update(newTaskImpl); + LOGGER.debug("Method updateTask() updated task '{}' for user '{}'.", task.getId(), userId); - for (Map.Entry entry : customFieldsToUpdate.entrySet()) { - String key = entry.getKey(); - fieldSelector.setCustomProperty(key, true); - newTask.setCustomAttribute(key, entry.getValue()); - } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("exit from initUpdatedTask(), returning {}", newTask); - } - - return newTask; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from claim()"); } + return task; + } - private void validateCustomFields(Map customFieldsToUpdate) throws InvalidArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("entry to validateCustomFields(customFieldsToUpdate = {}, taskIds = {})", - LoggerUtils.mapToString(customFieldsToUpdate)); - } - - if (customFieldsToUpdate == null || customFieldsToUpdate.isEmpty()) { - throw new InvalidArgumentException("The customFieldsToUpdate argument to updateTasks must not be empty."); - } - - for (Map.Entry entry : customFieldsToUpdate.entrySet()) { - String key = entry.getKey(); - if (!ALLOWED_KEYS.contains(key)) { - throw new InvalidArgumentException( - "The customFieldsToUpdate argument to updateTasks contains invalid key " + key); - } - } - LOGGER.debug("exit from validateCustomFields()"); - } - - private List getTasksToChange(List taskIds) { - return createTaskQuery() - .idIn(taskIds.toArray(new String[taskIds.size()])) - .list(); - } - - private List getTasksToChange(ObjectReference selectionCriteria) { - return createTaskQuery() - .primaryObjectReferenceCompanyIn(selectionCriteria.getCompany()) - .primaryObjectReferenceSystemIn(selectionCriteria.getSystem()) - .primaryObjectReferenceSystemInstanceIn(selectionCriteria.getSystemInstance()) - .primaryObjectReferenceTypeIn(selectionCriteria.getType()) - .primaryObjectReferenceValueIn(selectionCriteria.getValue()) - .list(); - } - - private void validateObjectReference(ObjectReference objRef, String objRefType, String objName) - throws InvalidArgumentException { - LOGGER.debug("entry to validateObjectReference()"); - // check that all values in the ObjectReference are set correctly - if (objRef == null) { - throw new InvalidArgumentException(objRefType + " of " + objName + " must not be null"); - } else if (objRef.getCompany() == null || objRef.getCompany().length() == 0) { - throw new InvalidArgumentException( - "Company of " + objRefType + " of " + objName + MUST_NOT_BE_EMPTY); - } else if (objRef.getSystem() == null || objRef.getSystem().length() == 0) { - throw new InvalidArgumentException( - "System of " + objRefType + " of " + objName + MUST_NOT_BE_EMPTY); - } else if (objRef.getSystemInstance() == null || objRef.getSystemInstance().length() == 0) { - throw new InvalidArgumentException( - "SystemInstance of " + objRefType + " of " + objName + MUST_NOT_BE_EMPTY); - } else if (objRef.getType() == null || objRef.getType().length() == 0) { - throw new InvalidArgumentException("Type of " + objRefType + " of " + objName + MUST_NOT_BE_EMPTY); - } else if (objRef.getValue() == null || objRef.getValue().length() == 0) { - throw new InvalidArgumentException("Value of" + objRefType + " of " + objName + MUST_NOT_BE_EMPTY); - } - LOGGER.debug("exit from validateObjectReference()"); - } - - private PrioDurationHolder handleAttachments(TaskImpl task) throws InvalidArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("entry to handleAttachments(task = {})", task); - } - - List attachments = task.getAttachments(); - if (attachments == null || attachments.isEmpty()) { - return new PrioDurationHolder(null, Integer.MIN_VALUE); - } - - PrioDurationHolder actualPrioDuration = new PrioDurationHolder(MAX_DURATION, Integer.MIN_VALUE); - - Iterator i = attachments.iterator(); - while (i.hasNext()) { - Attachment attachment = i.next(); - if (attachment == null) { - i.remove(); - } else { - actualPrioDuration = handleNonNullAttachment(actualPrioDuration, attachment); - } - } - if (MAX_DURATION.equals(actualPrioDuration.getDuration())) { - actualPrioDuration.setDuration(null); - } - - LOGGER.debug("exit from handleAttachments(), returning {}", actualPrioDuration); - return actualPrioDuration; - } - - private PrioDurationHolder handleNonNullAttachment(PrioDurationHolder actualPrioDuration, Attachment attachment) - throws InvalidArgumentException { - ObjectReference objRef = attachment.getObjectReference(); - validateObjectReference(objRef, "ObjectReference", "Attachment"); - if (attachment.getClassificationSummary() == null) { - throw new InvalidArgumentException( - "Classification of attachment " + attachment + " must not be null"); - } else { - ClassificationSummary classificationSummary = attachment.getClassificationSummary(); - if (classificationSummary != null) { - actualPrioDuration = getNewPrioDuration(actualPrioDuration, - classificationSummary.getPriority(), classificationSummary.getServiceLevel()); - } - } - return actualPrioDuration; - } - - private void standardUpdateActions(TaskImpl oldTaskImpl, TaskImpl newTaskImpl, - PrioDurationHolder prioDurationFromAttachments) - throws InvalidArgumentException, ConcurrencyException, ClassificationNotFoundException { - validateObjectReference(newTaskImpl.getPrimaryObjRef(), "primary ObjectReference", "Task"); - //TODO: not safe to rely only on different timestamps. - // With fast execution below 1ms there will be no concurrencyException - if (oldTaskImpl.getModified() != null && !oldTaskImpl.getModified().equals(newTaskImpl.getModified()) - || oldTaskImpl.getClaimed() != null && !oldTaskImpl.getClaimed().equals(newTaskImpl.getClaimed()) - || oldTaskImpl.getState() != null && !oldTaskImpl.getState().equals(newTaskImpl.getState())) { - throw new ConcurrencyException("The task has already been updated by another user"); - } - - if (oldTaskImpl.getExternalId() == null || !(oldTaskImpl.getExternalId().equals(newTaskImpl.getExternalId()))) { - throw new InvalidArgumentException("A task's external Id cannot be changed via update of the task"); - } - - String newWorkbasketKey = newTaskImpl.getWorkbasketKey(); - if (newWorkbasketKey != null && !newWorkbasketKey.equals(oldTaskImpl.getWorkbasketKey())) { - throw new InvalidArgumentException("A task's Workbasket cannot be changed via update of the task"); - } - - if (newTaskImpl.getPlanned() == null) { - newTaskImpl.setPlanned(oldTaskImpl.getPlanned()); - } - - // if no business process id is provided, use the id of the old task. - if (newTaskImpl.getBusinessProcessId() == null) { - newTaskImpl.setBusinessProcessId(oldTaskImpl.getBusinessProcessId()); - } - - updateClassificationRelatedProperties(oldTaskImpl, newTaskImpl, prioDurationFromAttachments); - - newTaskImpl.setModified(Instant.now()); - } - - private void updateClassificationRelatedProperties(TaskImpl oldTaskImpl, TaskImpl newTaskImpl, - PrioDurationHolder prioDurationFromAttachments) - throws ClassificationNotFoundException { - LOGGER.debug("entry to updateClassificationRelatedProperties()"); - // insert Classification specifications if Classification is given. - ClassificationSummary oldClassificationSummary = oldTaskImpl.getClassificationSummary(); - ClassificationSummary newClassificationSummary = newTaskImpl.getClassificationSummary(); - if (newClassificationSummary == null) { - newClassificationSummary = oldClassificationSummary; - } - - if (newClassificationSummary == null) { // newClassification is null -> take prio and duration from attachments - updateTaskPrioDurationFromAttachments(newTaskImpl, prioDurationFromAttachments); - } else { - updateTaskPrioDurationFromClassification(newTaskImpl, prioDurationFromAttachments, oldClassificationSummary, - newClassificationSummary); - - } - - LOGGER.debug("exit from updateClassificationRelatedProperties()"); - } - - private void updateTaskPrioDurationFromClassification(TaskImpl newTaskImpl, - PrioDurationHolder prioDurationFromAttachments, ClassificationSummary oldClassificationSummary, - ClassificationSummary newClassificationSummary) throws ClassificationNotFoundException { - LOGGER.debug("entry to updateTaskPrioDurationFromClassification()"); - Classification newClassification = null; - if (!oldClassificationSummary.getKey().equals(newClassificationSummary.getKey())) { - newClassification = this.classificationService - .getClassification(newClassificationSummary.getKey(), - newTaskImpl.getWorkbasketSummary().getDomain()); - newClassificationSummary = newClassification.asSummary(); - newTaskImpl.setClassificationSummary(newClassificationSummary); - } - - Duration minDuration = calculateDuration(prioDurationFromAttachments, newClassificationSummary); - if (minDuration != null) { - - long days = converter.convertWorkingDaysToDays(newTaskImpl.getPlanned(), minDuration.toDays()); - Instant due = newTaskImpl.getPlanned().plus(Duration.ofDays(days)); - - newTaskImpl.setDue(due); - } - - if (newTaskImpl.getName() == null) { - newTaskImpl.setName(newClassificationSummary.getName()); - } - - if (newTaskImpl.getDescription() == null && newClassification != null) { - newTaskImpl.setDescription(newClassification.getDescription()); - } - - int newPriority = Math.max(newClassificationSummary.getPriority(), prioDurationFromAttachments.getPrio()); - newTaskImpl.setPriority(newPriority); - LOGGER.debug("exit from updateTaskPrioDurationFromClassification()"); - } - - Duration calculateDuration(PrioDurationHolder prioDurationFromAttachments, - ClassificationSummary newClassificationSummary) { - if (newClassificationSummary.getServiceLevel() == null) { - return null; - } - Duration minDuration = prioDurationFromAttachments.getDuration(); - Duration durationFromClassification = Duration.parse(newClassificationSummary.getServiceLevel()); - if (minDuration != null) { - if (minDuration.compareTo(durationFromClassification) > 0) { - minDuration = durationFromClassification; - } - } else { - minDuration = durationFromClassification; - } - return minDuration; - } - - private PrioDurationHolder handleAttachmentsOnTaskUpdate(TaskImpl oldTaskImpl, TaskImpl newTaskImpl) - throws AttachmentPersistenceException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("entry to handleAttachmentsOnTaskUpdate(oldTaskImpl = {}, newTaskImpl = {})", oldTaskImpl, - newTaskImpl); - } - - PrioDurationHolder prioDuration = new PrioDurationHolder(MAX_DURATION, Integer.MIN_VALUE); - - // Iterator for removing invalid current values directly. OldAttachments can be ignored. - Iterator i = newTaskImpl.getAttachments().iterator(); - while (i.hasNext()) { - Attachment attachment = i.next(); - if (attachment != null) { - prioDuration = handlePrioDurationOfOneAttachmentOnTaskUpdate(oldTaskImpl, newTaskImpl, prioDuration, - attachment); - } else { - i.remove(); - } - } - - // DELETE, when an Attachment was only represented before - deleteAttachmentOnTaskUpdate(oldTaskImpl, newTaskImpl); - if (MAX_DURATION.equals(prioDuration.getDuration())) { - prioDuration.setDuration(null); - } - - LOGGER.debug("exit from handleAttachmentsOnTaskUpdate()"); - return prioDuration; - } - - private void deleteAttachmentOnTaskUpdate(TaskImpl oldTaskImpl, TaskImpl newTaskImpl) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("entry to deleteAttachmentOnTaskUpdate(oldTaskImpl = {}, newTaskImpl = {})", oldTaskImpl, - newTaskImpl); - } - - for (Attachment oldAttachment : oldTaskImpl.getAttachments()) { - if (oldAttachment != null) { - boolean isRepresented = false; - for (Attachment newAttachment : newTaskImpl.getAttachments()) { - if (newAttachment != null && oldAttachment.getId().equals(newAttachment.getId())) { - isRepresented = true; - break; - } - } - if (!isRepresented) { - attachmentMapper.deleteAttachment(oldAttachment.getId()); - LOGGER.debug("TaskService.updateTask() for TaskId={} DELETED an Attachment={}.", - newTaskImpl.getId(), - oldAttachment); - } - } - } - LOGGER.debug("exit from deleteAttachmentOnTaskUpdate()"); - } - - private PrioDurationHolder handlePrioDurationOfOneAttachmentOnTaskUpdate(TaskImpl oldTaskImpl, TaskImpl newTaskImpl, - PrioDurationHolder prioDuration, Attachment attachment) throws AttachmentPersistenceException { - LOGGER.debug("entry to handlePrioDurationOfOneAttachmentOnTaskUpdate()"); - boolean wasAlreadyPresent = false; - if (attachment.getId() != null) { - for (Attachment oldAttachment : oldTaskImpl.getAttachments()) { - if (oldAttachment != null && attachment.getId().equals(oldAttachment.getId())) { - wasAlreadyPresent = true; - if (!attachment.equals(oldAttachment)) { - prioDuration = handlePrioDurationOfOneNewAttachmentOnTaskUpdate(newTaskImpl, prioDuration, - attachment); - break; - } - - } - } - } - - // ADD, when ID not set or not found in elements - if (!wasAlreadyPresent) { - prioDuration = handleNewAttachmentOnTaskUpdate(newTaskImpl, prioDuration, attachment); - - } - - LOGGER.debug("exit from handlePrioDurationOfOneAttachmentOnTaskUpdate(), returning {}", prioDuration); - return prioDuration; - } - - private PrioDurationHolder handlePrioDurationOfOneNewAttachmentOnTaskUpdate(TaskImpl newTaskImpl, - PrioDurationHolder prioDuration, Attachment attachment) { - LOGGER.debug("entry to handlePrioDurationOfOneNewAttachmentOnTaskUpdate()"); - AttachmentImpl temp = (AttachmentImpl) attachment; - - ClassificationSummary classification = attachment.getClassificationSummary(); - if (classification != null) { - prioDuration = getNewPrioDuration(prioDuration, - classification.getPriority(), classification.getServiceLevel()); - } - - temp.setModified(Instant.now()); - attachmentMapper.update(temp); - LOGGER.debug("TaskService.updateTask() for TaskId={} UPDATED an Attachment={}.", - newTaskImpl.getId(), - attachment); - LOGGER.debug("exit from handlePrioDurationOfOneNewAttachmentOnTaskUpdate(), returning {}", prioDuration); - return prioDuration; - } - - private PrioDurationHolder handleNewAttachmentOnTaskUpdate(TaskImpl newTaskImpl, PrioDurationHolder prioDuration, - Attachment attachment) throws AttachmentPersistenceException { - LOGGER.debug("entry to handleNewAttachmentOnTaskUpdate()"); - AttachmentImpl attachmentImpl = (AttachmentImpl) attachment; - initAttachment(attachmentImpl, newTaskImpl); - ClassificationSummary classification = attachment.getClassificationSummary(); - if (classification != null) { - prioDuration = getNewPrioDuration(prioDuration, - classification.getPriority(), classification.getServiceLevel()); - } - - try { - attachmentMapper.insert(attachmentImpl); - LOGGER.debug("TaskService.updateTask() for TaskId={} INSERTED an Attachment={}.", - newTaskImpl.getId(), - attachmentImpl); - } catch (PersistenceException e) { - throw new AttachmentPersistenceException( - "Cannot insert the Attachement " + attachmentImpl.getId() + " for Task " - + newTaskImpl.getId() + " because it already exists.", - e.getCause()); - } - LOGGER.debug("exit from handleNewAttachmentOnTaskUpdate(), returning {}", prioDuration); - return prioDuration; - } - - private PrioDurationHolder handleAttachmentsOnClassificationUpdate(Task task) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("entry to handleAttachmentsOnClassificationUpdate(task = {})", task); - } - - PrioDurationHolder prioDuration = new PrioDurationHolder(MAX_DURATION, Integer.MIN_VALUE); - - // Iterator for removing invalid current values directly. OldAttachments can be ignored. - for (Attachment attachment : task.getAttachments()) { - if (attachment != null) { - ClassificationSummary classification = attachment.getClassificationSummary(); - if (classification != null) { - prioDuration = getNewPrioDuration(prioDuration, - classification.getPriority(), classification.getServiceLevel()); - } - - } - } - if (MAX_DURATION.equals(prioDuration.getDuration())) { - prioDuration.setDuration(null); - } - - LOGGER.debug("exit from handleAttachmentsOnClassificationUpdate(), returning {}", prioDuration); - return prioDuration; - } - - private PrioDurationHolder getNewPrioDuration(PrioDurationHolder prioDurationHolder, int prioFromClassification, - String serviceLevelFromClassification) { - LOGGER.debug( - "entry to getNewPrioDuration(prioDurationHolder = {}, prioFromClassification = {}, serviceLevelFromClassification = {})", - prioDurationHolder, prioFromClassification, serviceLevelFromClassification); - Duration minDuration = prioDurationHolder.getDuration(); - int maxPrio = prioDurationHolder.getPrio(); - - if (serviceLevelFromClassification != null) { - Duration currentDuration = Duration.parse(serviceLevelFromClassification); - if (prioDurationHolder.getDuration() != null) { - if (prioDurationHolder.getDuration().compareTo(currentDuration) > 0) { - minDuration = currentDuration; - } - } else { - minDuration = currentDuration; - } - } - if (prioFromClassification > maxPrio) { - maxPrio = prioFromClassification; - } - - LOGGER.debug("exit from getNewPrioDuration(), returning {}", new PrioDurationHolder(minDuration, maxPrio)); - return new PrioDurationHolder(minDuration, maxPrio); - } - - private void initAttachment(AttachmentImpl attachment, Task newTask) { - LOGGER.debug("entry to initAttachment()"); - if (attachment.getId() == null) { - attachment.setId(IdGenerator.generateWithPrefix(ID_PREFIX_ATTACHMENT)); - } - if (attachment.getCreated() == null) { - attachment.setCreated(Instant.now()); - } - if (attachment.getModified() == null) { - attachment.setModified(attachment.getCreated()); - } - if (attachment.getTaskId() == null) { - attachment.setTaskId(newTask.getId()); - } - LOGGER.debug("exit from initAttachment()"); - } - - public Set findTasksIdsAffectedByClassificationChange(String classificationId) { - LOGGER.debug("entry to findTasksIdsAffectedByClassificationChange(classificationId = {})", classificationId); - // tasks directly affected - List tasks = createTaskQuery() + public Set findTasksIdsAffectedByClassificationChange(String classificationId) { + LOGGER.debug( + "entry to findTasksIdsAffectedByClassificationChange(classificationId = {})", + classificationId); + // tasks directly affected + List tasks = + createTaskQuery() .classificationIdIn(classificationId) .stateIn(TaskState.READY, TaskState.CLAIMED) .list(); - // tasks indirectly affected via attachments - List taskIdsFromAttachments = attachmentMapper.findTaskIdsAffectedByClassificationChange( - classificationId); + // tasks indirectly affected via attachments + List taskIdsFromAttachments = + attachmentMapper.findTaskIdsAffectedByClassificationChange(classificationId); - List filteredTaskIdsFromAttachments = taskIdsFromAttachments.isEmpty() ? new ArrayList<>() + List filteredTaskIdsFromAttachments = + taskIdsFromAttachments.isEmpty() + ? new ArrayList<>() : taskMapper.filterTaskIdsForNotCompleted(taskIdsFromAttachments); - Set affectedTaskIds = new HashSet<>(filteredTaskIdsFromAttachments); - for (TaskSummary task : tasks) { - affectedTaskIds.add(task.getTaskId()); - } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("the following tasks are affected by the update of classification {} : {}", classificationId, - LoggerUtils.setToString(affectedTaskIds)); - } - LOGGER.debug("exit from findTasksIdsAffectedByClassificationChange(). "); - return affectedTaskIds; + Set affectedTaskIds = new HashSet<>(filteredTaskIdsFromAttachments); + for (TaskSummary task : tasks) { + affectedTaskIds.add(task.getTaskId()); + } + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "the following tasks are affected by the update of classification {} : {}", + classificationId, + LoggerUtils.setToString(affectedTaskIds)); + } + LOGGER.debug("exit from findTasksIdsAffectedByClassificationChange(). "); + return affectedTaskIds; + } + + public void refreshPriorityAndDueDate(String taskId) throws ClassificationNotFoundException { + LOGGER.debug("entry to refreshPriorityAndDueDate(taskId = {})", taskId); + TaskImpl task = null; + BulkOperationResults bulkLog = new BulkOperationResults<>(); + try { + taskanaEngine.openConnection(); + if (taskId == null || taskId.isEmpty()) { + return; + } + + task = taskMapper.findById(taskId); + + List attachmentImpls = attachmentMapper.findAttachmentsByTaskId(task.getId()); + if (attachmentImpls == null) { + attachmentImpls = new ArrayList<>(); + } + List attachments = augmentAttachmentsByClassification(attachmentImpls, bulkLog); + task.setAttachments(attachments); + + Classification classification = + classificationService.getClassification(task.getClassificationSummary().getId()); + task.setClassificationSummary(classification.asSummary()); + PrioDurationHolder prioDurationFromAttachments = + handleAttachmentsOnClassificationUpdate(task); + + updatePrioDueDateOnClassificationUpdate(task, prioDurationFromAttachments); + + task.setModified(Instant.now()); + taskMapper.update(task); + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from refreshPriorityAndDueDate(). "); + } + } + + void removeNonExistingTasksFromTaskIdList( + List taskIds, BulkOperationResults bulkLog) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "entry to removeNonExistingTasksFromTaskIdList(targetWbId = {}, taskIds = {})", + taskIds, + bulkLog); } - public void refreshPriorityAndDueDate(String taskId) - throws ClassificationNotFoundException { - LOGGER.debug("entry to refreshPriorityAndDueDate(taskId = {})", taskId); - TaskImpl task = null; - BulkOperationResults bulkLog = new BulkOperationResults<>(); - try { - taskanaEngine.openConnection(); - if (taskId == null || taskId.isEmpty()) { - return; - } + Iterator taskIdIterator = taskIds.iterator(); + while (taskIdIterator.hasNext()) { + String currentTaskId = taskIdIterator.next(); + if (currentTaskId == null || currentTaskId.equals("")) { + bulkLog.addError( + "", new InvalidArgumentException("IDs with EMPTY or NULL value are not allowed.")); + taskIdIterator.remove(); + } + } + LOGGER.debug("exit from removeNonExistingTasksFromTaskIdList()"); + } - task = taskMapper.findById(taskId); - - List attachmentImpls = attachmentMapper.findAttachmentsByTaskId(task.getId()); - if (attachmentImpls == null) { - attachmentImpls = new ArrayList<>(); - } - List attachments = augmentAttachmentsByClassification(attachmentImpls, bulkLog); - task.setAttachments(attachments); - - Classification classification = classificationService - .getClassification(task.getClassificationSummary().getId()); - task.setClassificationSummary(classification.asSummary()); - PrioDurationHolder prioDurationFromAttachments = handleAttachmentsOnClassificationUpdate(task); - - updatePrioDueDateOnClassificationUpdate(task, prioDurationFromAttachments); - - task.setModified(Instant.now()); - taskMapper.update(task); - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from refreshPriorityAndDueDate(). "); - } + Duration calculateDuration( + PrioDurationHolder prioDurationFromAttachments, + ClassificationSummary newClassificationSummary) { + if (newClassificationSummary.getServiceLevel() == null) { + return null; + } + Duration minDuration = prioDurationFromAttachments.getDuration(); + Duration durationFromClassification = + Duration.parse(newClassificationSummary.getServiceLevel()); + if (minDuration != null) { + if (minDuration.compareTo(durationFromClassification) > 0) { + minDuration = durationFromClassification; + } + } else { + minDuration = durationFromClassification; + } + return minDuration; + } + List augmentTaskSummariesByContainedSummaries(List taskSummaries) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "entry to augmentTaskSummariesByContainedSummaries(taskSummaries= {})", + LoggerUtils.listToString(taskSummaries)); } - private void updatePrioDueDateOnClassificationUpdate(TaskImpl task, - PrioDurationHolder prioDurationFromAttachments) { - LOGGER.debug("entry to updatePrioDueDateOnClassificationUpdate()"); - ClassificationSummary classificationSummary = task.getClassificationSummary(); + List result = new ArrayList<>(); + if (taskSummaries == null || taskSummaries.isEmpty()) { + return result; + } - if (classificationSummary == null) { // classification is null -> take prio and duration from attachments - updateTaskPrioDurationFromAttachments(task, prioDurationFromAttachments); + Set taskIdSet = + taskSummaries.stream().map(TaskSummaryImpl::getTaskId).collect(Collectors.toSet()); + String[] taskIdArray = taskIdSet.toArray(new String[0]); + + LOGGER.debug( + "augmentTaskSummariesByContainedSummaries() about to query for attachmentSummaries "); + List attachmentSummaries = + attachmentMapper.findAttachmentSummariesByTaskIds(taskIdArray); + + List classifications = + findClassificationsForTasksAndAttachments(taskSummaries, attachmentSummaries); + + addClassificationSummariesToTaskSummaries(taskSummaries, classifications); + addWorkbasketSummariesToTaskSummaries(taskSummaries); + addAttachmentSummariesToTaskSummaries(taskSummaries, attachmentSummaries, classifications); + result.addAll(taskSummaries); + LOGGER.debug("exit from to augmentTaskSummariesByContainedSummaries()"); + return result; + } + + private void removeSingleTaskForTaskDeletionById( + BulkOperationResults bulkLog, + List taskSummaries, + Iterator taskIdIterator) { + LOGGER.debug("entry to removeSingleTask()"); + String currentTaskId = taskIdIterator.next(); + if (currentTaskId == null || currentTaskId.equals("")) { + bulkLog.addError( + "", new InvalidArgumentException("IDs with EMPTY or NULL value are not allowed.")); + taskIdIterator.remove(); + } else { + MinimalTaskSummary foundSummary = + taskSummaries.stream() + .filter(taskSummary -> currentTaskId.equals(taskSummary.getTaskId())) + .findFirst() + .orElse(null); + if (foundSummary == null) { + bulkLog.addError( + currentTaskId, + new TaskNotFoundException( + currentTaskId, TASK_WITH_ID + currentTaskId + WAS_NOT_FOUND2)); + taskIdIterator.remove(); + } else if (!TaskState.COMPLETED.equals(foundSummary.getTaskState())) { + bulkLog.addError(currentTaskId, new InvalidStateException(currentTaskId)); + taskIdIterator.remove(); + } else { + if (CallbackState.CALLBACK_PROCESSING_REQUIRED.equals(foundSummary.getCallbackState())) { + bulkLog.addError( + currentTaskId, + new InvalidStateException( + "Task " + currentTaskId + " cannot be deleted before callback is processed")); + taskIdIterator.remove(); + } + } + } + LOGGER.debug("exit from removeSingleTask()"); + } + + private void removeSingleTaskForCallbackStateByExternalId( + BulkOperationResults bulkLog, + List taskSummaries, + Iterator externalIdIterator, + CallbackState desiredCallbackState) { + LOGGER.debug("entry to removeSingleTask()"); + String currentExternalId = externalIdIterator.next(); + if (currentExternalId == null || currentExternalId.equals("")) { + bulkLog.addError( + "", new InvalidArgumentException("IDs with EMPTY or NULL value are not allowed.")); + externalIdIterator.remove(); + } else { + MinimalTaskSummary foundSummary = + taskSummaries.stream() + .filter(taskSummary -> currentExternalId.equals(taskSummary.getExternalId())) + .findFirst() + .orElse(null); + if (foundSummary == null) { + bulkLog.addError( + currentExternalId, + new TaskNotFoundException( + currentExternalId, TASK_WITH_ID + currentExternalId + WAS_NOT_FOUND2)); + externalIdIterator.remove(); + } else if (!desiredCallbackStateCanBeSetForFoundSummary(foundSummary, desiredCallbackState)) { + bulkLog.addError(currentExternalId, new InvalidStateException(currentExternalId)); + externalIdIterator.remove(); + } + } + LOGGER.debug("exit from removeSingleTask()"); + } + + private boolean desiredCallbackStateCanBeSetForFoundSummary( + MinimalTaskSummary foundSummary, CallbackState desiredCallbackState) { + + CallbackState currentTaskCallbackState = foundSummary.getCallbackState(); + TaskState currentTaskState = foundSummary.getTaskState(); + + switch (desiredCallbackState) { + case CALLBACK_PROCESSING_COMPLETED: + if (!(currentTaskState.equals(TaskState.COMPLETED))) { + return false; + } + return true; + + case CLAIMED: + if (!currentTaskState.equals(TaskState.CLAIMED)) { + return false; + } else if (!currentTaskCallbackState.equals(CallbackState.CALLBACK_PROCESSING_REQUIRED)) { + return false; + } + return true; + + case CALLBACK_PROCESSING_REQUIRED: + if (currentTaskCallbackState.equals(CallbackState.CALLBACK_PROCESSING_COMPLETED)) { + return false; + } + return true; + case NONE: + return false; + + default: + return false; + } + } + + private void standardSettings( + TaskImpl task, Classification classification, PrioDurationHolder prioDurationFromAttachments) + throws InvalidArgumentException { + LOGGER.debug("entry to standardSettings()"); + Instant now = Instant.now(); + task.setId(IdGenerator.generateWithPrefix(ID_PREFIX_TASK)); + if (task.getExternalId() == null) { + task.setExternalId(IdGenerator.generateWithPrefix(ID_PREFIX_EXT_TASK_ID)); + } + task.setState(TaskState.READY); + task.setCreated(now); + task.setModified(now); + task.setRead(false); + task.setTransferred(false); + + String creator = CurrentUserContext.getUserid(); + if (taskanaEngine.getEngine().getConfiguration().isSecurityEnabled() && creator == null) { + throw new SystemException( + "TaskanaSecurity is enabled, but the current UserId is NULL while creating a Task."); + } + task.setCreator(creator); + + // if no business process id is provided, a unique id is created. + if (task.getBusinessProcessId() == null) { + task.setBusinessProcessId(IdGenerator.generateWithPrefix(ID_PREFIX_BUSINESS_PROCESS)); + } + + // null in case of manual tasks + if (classification == null) { + if (task.getPlanned() == null) { + task.setPlanned(now); + } + } else { + // do some Classification specific stuff (servicelevel). + // get duration in days from planned to due + PrioDurationHolder finalPrioDuration = + getNewPrioDuration( + prioDurationFromAttachments, + classification.getPriority(), + classification.getServiceLevel()); + Duration finalDuration = finalPrioDuration.getDuration(); + if (finalDuration != null && !MAX_DURATION.equals(finalDuration)) { + // if we have a due date we need to go x days backwards, + // else we take the planned date (or now as fallback) and add x Days + if (task.getDue() != null) { + long days = converter.convertWorkingDaysToDays(task.getDue(), -finalDuration.toDays()); + // days < 0 -> so we ne need to add, not substract + Instant planned = task.getDue().plus(Duration.ofDays(days)); + if (task.getPlanned() != null && !task.getPlanned().equals(planned)) { + throw new InvalidArgumentException( + "Cannot create a task with given planned and due date not matching the service level"); + } + task.setPlanned(planned); } else { - updateTaskPrioDurationFromClassificationAndAttachments(task, prioDurationFromAttachments, - classificationSummary); + task.setPlanned(task.getPlanned() == null ? now : task.getPlanned()); + long days = converter.convertWorkingDaysToDays(task.getPlanned(), finalDuration.toDays()); + Instant due = task.getPlanned().plus(Duration.ofDays(days)); + task.setDue(due); } - - LOGGER.debug("exit from updatePrioDueDateOnClassificationUpdate()"); + } + task.setPriority(finalPrioDuration.getPrio()); } - private void updateTaskPrioDurationFromClassificationAndAttachments(TaskImpl task, - PrioDurationHolder prioDurationFromAttachments, ClassificationSummary classificationSummary) { - LOGGER.debug("entry to updateTaskPrioDurationFromClassificationAndAttachments()"); - - Duration minDuration = calculateDuration(prioDurationFromAttachments, classificationSummary); - if (minDuration != null) { - long days = converter.convertWorkingDaysToDays(task.getPlanned(), minDuration.toDays()); - Instant due = task.getPlanned().plus(Duration.ofDays(days)); - - task.setDue(due); - } - - int newPriority = Math.max(classificationSummary.getPriority(), prioDurationFromAttachments.getPrio()); - task.setPriority(newPriority); - LOGGER.debug("exit from updateTaskPrioDurationFromClassificationAndAttachments()"); + if (task.getName() == null && classification != null) { + task.setName(classification.getName()); } - private Task completeTask(String taskId, boolean isForced) - throws TaskNotFoundException, InvalidOwnerException, InvalidStateException, NotAuthorizedException { - String userId = CurrentUserContext.getUserid(); - LOGGER.debug("entry to completeTask(id = {}, userId = {}, isForced = {})", taskId, userId, isForced); - TaskImpl task = null; + if (task.getDescription() == null && classification != null) { + task.setDescription(classification.getDescription()); + } + + // insert Attachments if needed + List attachments = task.getAttachments(); + if (attachments != null) { + for (Attachment attachment : attachments) { + AttachmentImpl attachmentImpl = (AttachmentImpl) attachment; + attachmentImpl.setId(IdGenerator.generateWithPrefix(ID_PREFIX_ATTACHMENT)); + attachmentImpl.setTaskId(task.getId()); + attachmentImpl.setCreated(now); + attachmentImpl.setModified(now); + attachmentMapper.insert(attachmentImpl); + } + } + LOGGER.debug("exit from standardSettings()"); + } + + private void setCallbackStateOnTaskCreation(TaskImpl task) throws InvalidArgumentException { + Map callbackInfo = task.getCallbackInfo(); + if (callbackInfo != null && callbackInfo.containsKey(Task.CALLBACK_STATE)) { + String value = callbackInfo.get(Task.CALLBACK_STATE); + if (value != null && !value.isEmpty()) { try { - taskanaEngine.openConnection(); - task = (TaskImpl) this.getTask(taskId); - - if (task.getState() == TaskState.COMPLETED) { - return task; - } - - // check pre-conditions for non-forced invocation - if (!isForced) { - if (task.getClaimed() == null || task.getState() != TaskState.CLAIMED) { - throw new InvalidStateException(TASK_WITH_ID + taskId + " has to be claimed before."); - } else if (!CurrentUserContext.getAccessIds().contains(task.getOwner())) { - throw new InvalidOwnerException( - "Owner of task " + taskId + " is " + task.getOwner() + ", but current User is " + userId); - } - } else { - // CLAIM-forced, if task was not already claimed before. - if (task.getClaimed() == null || task.getState() != TaskState.CLAIMED) { - task = (TaskImpl) this.forceClaim(taskId); - } - } - Instant now = Instant.now(); - task.setCompleted(now); - task.setModified(now); - task.setState(TaskState.COMPLETED); - task.setOwner(userId); - taskMapper.update(task); - LOGGER.debug("Task '{}' completed by user '{}'.", taskId, userId); - if (HistoryEventProducer.isHistoryEnabled()) { - historyEventProducer.createEvent(new CompletedEvent(task)); - } - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from completeTask()"); + CallbackState state = CallbackState.valueOf(value); + task.setCallbackState(state); + } catch (Exception e) { + LOGGER.warn("Attempted to determine callback state from {} and caught {}", value, e); + throw new InvalidArgumentException( + "Attempted to set callback state for task " + task.getId(), e); } - return task; + } + } + } + + private void checkIfTasksMatchCompleteCriteria( + List taskIds, + List taskSummaries, + BulkOperationResults bulkLog) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "entry to checkIfTasksMatchCompleteCriteria(taskIds = {}, taskSummaries = {}, bulkLog = {})", + LoggerUtils.listToString(taskIds), + LoggerUtils.listToString(taskSummaries), + bulkLog); } - private Task claim(String taskId, boolean forceClaim) - throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, NotAuthorizedException { - String userId = CurrentUserContext.getUserid(); - LOGGER.debug("entry to claim(id = {}, userId = {}, forceClaim = {})", taskId, userId, forceClaim); - TaskImpl task = null; - try { - taskanaEngine.openConnection(); - task = (TaskImpl) getTask(taskId); - TaskState state = task.getState(); - if (state == TaskState.COMPLETED) { - throw new InvalidStateException(TASK_WITH_ID + taskId + IS_ALREADY_COMPLETED); - } - if (state == TaskState.CLAIMED && !forceClaim && !task.getOwner().equals(userId)) { - throw new InvalidOwnerException( - TASK_WITH_ID + taskId + IS_ALREADY_CLAIMED_BY + task.getOwner() + "."); - } - Instant now = Instant.now(); - task.setOwner(userId); - task.setModified(now); - task.setClaimed(now); - task.setRead(true); - task.setState(TaskState.CLAIMED); - taskMapper.update(task); - LOGGER.debug("Task '{}' claimed by user '{}'.", taskId, userId); - if (HistoryEventProducer.isHistoryEnabled()) { - historyEventProducer.createEvent(new ClaimedEvent(task)); - } - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from claim()"); - } - return task; + Instant now = Instant.now(); + Iterator taskIdIterator = taskIds.iterator(); + while (taskIdIterator.hasNext()) { + String currentTaskId = taskIdIterator.next(); + TaskSummaryImpl taskSummary = + (TaskSummaryImpl) + taskSummaries.stream() + .filter(ts -> currentTaskId.equals(ts.getTaskId())) + .findFirst() + .orElse(null); + if (taskSummary == null) { + bulkLog.addError( + currentTaskId, + new TaskNotFoundException( + currentTaskId, "task with id " + currentTaskId + WAS_NOT_FOUND2)); + taskIdIterator.remove(); + } else if (taskSummary.getClaimed() == null || taskSummary.getState() != TaskState.CLAIMED) { + bulkLog.addError(currentTaskId, new InvalidStateException(currentTaskId)); + taskIdIterator.remove(); + } else if (!CurrentUserContext.getAccessIds().contains(taskSummary.getOwner())) { + bulkLog.addError( + currentTaskId, + new InvalidOwnerException( + "TaskOwner is" + + taskSummary.getOwner() + + ", but current User is " + + CurrentUserContext.getUserid())); + taskIdIterator.remove(); + } else { + taskSummary.setCompleted(now); + taskSummary.setModified(now); + taskSummary.setState(TaskState.COMPLETED); + } + } + LOGGER.debug("exit from checkIfTasksMatchCompleteCriteria()"); + } + + private void updateTasksToBeCompleted(List taskIds, List taskSummaries) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "entry to updateTasksToBeCompleted(taskIds = {}, taskSummaries = {})", + LoggerUtils.listToString(taskIds), + LoggerUtils.listToString(taskSummaries)); } - private void updateTaskPrioDurationFromAttachments(TaskImpl task, PrioDurationHolder prioDurationFromAttachments) { - LOGGER.debug("entry to updateTaskPrioDurationFromAttachments()"); - if (prioDurationFromAttachments.getDuration() != null) { - long days = converter.convertWorkingDaysToDays(task.getPlanned(), - prioDurationFromAttachments.getDuration().toDays()); - Instant due = task.getPlanned().plus(Duration.ofDays(days)); - task.setDue(due); - } - if (prioDurationFromAttachments.getPrio() > Integer.MIN_VALUE) { - task.setPriority(prioDurationFromAttachments.getPrio()); - } - LOGGER.debug("exit from updateTaskPrioDurationFromAttachments()"); + if (!taskIds.isEmpty() && !taskSummaries.isEmpty()) { + taskMapper.updateCompleted(taskIds, (TaskSummaryImpl) taskSummaries.get(0)); + if (HistoryEventProducer.isHistoryEnabled()) { + createTasksCompletedEvents(taskSummaries); + } + } + LOGGER.debug("exit from updateTasksToBeCompleted()"); + } + + private Task cancelClaim(String taskId, boolean forceUnclaim) + throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, + NotAuthorizedException { + String userId = CurrentUserContext.getUserid(); + LOGGER.debug( + "entry to cancelClaim(taskId = {}), userId = {}, forceUnclaim = {})", + taskId, + userId, + forceUnclaim); + TaskImpl task = null; + try { + taskanaEngine.openConnection(); + task = (TaskImpl) getTask(taskId); + TaskState state = task.getState(); + if (state == TaskState.COMPLETED) { + throw new InvalidStateException(TASK_WITH_ID + taskId + IS_ALREADY_COMPLETED); + } + if (state == TaskState.CLAIMED && !forceUnclaim && !userId.equals(task.getOwner())) { + throw new InvalidOwnerException( + TASK_WITH_ID + taskId + IS_ALREADY_CLAIMED_BY + task.getOwner() + "."); + } + Instant now = Instant.now(); + task.setOwner(null); + task.setModified(now); + task.setClaimed(null); + task.setRead(true); + task.setState(TaskState.READY); + taskMapper.update(task); + LOGGER.debug("Task '{}' unclaimed by user '{}'.", taskId, userId); + if (HistoryEventProducer.isHistoryEnabled()) { + historyEventProducer.createEvent(new ClaimCancelledEvent(task)); + } + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from cancelClaim()"); + } + return task; + } + + private void addClassificationSummariesToTaskSummaries( + List tasks, List classifications) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "entry to addClassificationSummariesToTaskSummaries(tasks = {}, classifications = {})", + LoggerUtils.listToString(tasks), + LoggerUtils.listToString(classifications)); } - private List augmentAttachmentsByClassification(List attachmentImpls, - BulkOperationResults bulkLog) { - LOGGER.debug("entry to augmentAttachmentsByClassification()"); - List result = new ArrayList<>(); - if (attachmentImpls == null || attachmentImpls.isEmpty()) { - return result; - } - Set classificationIds = attachmentImpls.stream() + if (tasks == null || tasks.isEmpty()) { + LOGGER.debug("exit from addClassificationSummariesToTaskSummaries()"); + return; + } + // assign query results to appropriate tasks. + for (TaskSummaryImpl task : tasks) { + String classificationId = task.getClassificationSummary().getId(); + ClassificationSummary aClassification = + classifications.stream() + .filter(c -> c.getId().equals(classificationId)) + .findFirst() + .orElse(null); + if (aClassification == null) { + throw new SystemException( + "Did not find a Classification for task (Id=" + + task.getTaskId() + + ",classification=" + + task.getClassificationSummary().getId() + + ")"); + } + // set the classification on the task object + task.setClassificationSummary(aClassification); + } + LOGGER.debug("exit from addClassificationSummariesToTaskSummaries()"); + } + + private List findClassificationsForTasksAndAttachments( + List taskSummaries, List attachmentSummaries) { + LOGGER.debug("entry to findClassificationsForTasksAndAttachments()"); + if (taskSummaries == null || taskSummaries.isEmpty()) { + return new ArrayList<>(); + } + + Set classificationIdSet = + taskSummaries.stream() .map(t -> t.getClassificationSummary().getId()) - .collect( - Collectors.toSet()); - List classifications = classificationService.createClassificationQuery() + .collect(Collectors.toSet()); + + if (attachmentSummaries != null && !attachmentSummaries.isEmpty()) { + for (AttachmentSummaryImpl att : attachmentSummaries) { + classificationIdSet.add(att.getClassificationSummary().getId()); + } + } + LOGGER.debug("exit from findClassificationsForTasksAndAttachments()"); + return queryClassificationsForTasksAndAttachments(classificationIdSet); + } + + private List findClassificationForTaskImplAndAttachments( + TaskImpl task, List attachmentImpls) { + LOGGER.debug("entry to transferBulk()"); + Set classificationIdSet = + new HashSet<>(Arrays.asList(task.getClassificationSummary().getId())); + if (attachmentImpls != null && !attachmentImpls.isEmpty()) { + for (AttachmentImpl att : attachmentImpls) { + classificationIdSet.add(att.getClassificationSummary().getId()); + } + } + LOGGER.debug("exit from findClassificationForTaskImplAndAttachments()"); + return queryClassificationsForTasksAndAttachments(classificationIdSet); + } + + private List queryClassificationsForTasksAndAttachments( + Set classificationIdSet) { + + String[] classificationIdArray = classificationIdSet.toArray(new String[0]); + + LOGGER.debug( + "getClassificationsForTasksAndAttachments() about to query classifications and exit"); + // perform classification query + return this.classificationService + .createClassificationQuery() + .idIn(classificationIdArray) + .list(); + } + + private void addWorkbasketSummariesToTaskSummaries(List taskSummaries) { + LOGGER.debug("entry to addWorkbasketSummariesToTaskSummaries()"); + if (taskSummaries == null || taskSummaries.isEmpty()) { + return; + } + // calculate parameters for workbasket query: workbasket keys + Set workbasketIdSet = + taskSummaries.stream() + .map(t -> t.getWorkbasketSummary().getId()) + .collect(Collectors.toSet()); + String[] workbasketIdArray = workbasketIdSet.toArray(new String[0]); + LOGGER.debug("addWorkbasketSummariesToTaskSummaries() about to query workbaskets"); + WorkbasketQueryImpl query = (WorkbasketQueryImpl) workbasketService.createWorkbasketQuery(); + query.setUsedToAugmentTasks(true); + + List workbaskets = query.idIn(workbasketIdArray).list(); + Iterator taskIterator = taskSummaries.iterator(); + while (taskIterator.hasNext()) { + TaskSummaryImpl task = taskIterator.next(); + String workbasketId = task.getWorkbasketSummaryImpl().getId(); + + WorkbasketSummary aWorkbasket = + workbaskets.stream() + .filter(x -> workbasketId != null && workbasketId.equals(x.getId())) + .findFirst() + .orElse(null); + if (aWorkbasket == null) { + LOGGER.warn("Could not find a Workbasket for task {}.", task.getTaskId()); + taskIterator.remove(); + continue; + } + + task.setWorkbasketSummary(aWorkbasket); + } + LOGGER.debug("exit from addWorkbasketSummariesToTaskSummaries()"); + } + + private void addAttachmentSummariesToTaskSummaries( + List taskSummaries, + List attachmentSummaries, + List classifications) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "entry to addAttachmentSummariesToTaskSummaries(taskSummaries = {}, attachmentSummaries = {}, classifications = {})", + LoggerUtils.listToString(taskSummaries), + LoggerUtils.listToString(attachmentSummaries), + LoggerUtils.listToString(classifications)); + } + + if (taskSummaries == null || taskSummaries.isEmpty()) { + return; + } + + // augment attachment summaries by classification summaries + // Note: + // the mapper sets for each Attachment summary the property classificationSummary.key from the + // CLASSIFICATION_KEY property in the DB + addClassificationSummariesToAttachmentSummaries( + attachmentSummaries, taskSummaries, classifications); + // assign attachment summaries to task summaries + for (TaskSummaryImpl task : taskSummaries) { + for (AttachmentSummaryImpl attachment : attachmentSummaries) { + if (attachment.getTaskId() != null && attachment.getTaskId().equals(task.getTaskId())) { + task.addAttachmentSummary(attachment); + } + } + } + + LOGGER.debug("exit from addAttachmentSummariesToTaskSummaries()"); + } + + private void addClassificationSummariesToAttachmentSummaries( + List attachmentSummaries, + List taskSummaries, + List classifications) { + LOGGER.debug("entry to addClassificationSummariesToAttachmentSummaries()"); + // prereq: in each attachmentSummary, the classificationSummary.key property is set. + if (attachmentSummaries == null + || attachmentSummaries.isEmpty() + || taskSummaries == null + || taskSummaries.isEmpty()) { + LOGGER.debug("exit from addClassificationSummariesToAttachmentSummaries()"); + return; + } + // iterate over all attachment summaries an add the appropriate classification summary to each + for (AttachmentSummaryImpl att : attachmentSummaries) { + String classificationId = att.getClassificationSummary().getId(); + ClassificationSummary aClassification = + classifications.stream() + .filter(x -> classificationId != null && classificationId.equals(x.getId())) + .findFirst() + .orElse(null); + if (aClassification == null) { + throw new SystemException("Could not find a Classification for attachment " + att); + } + att.setClassificationSummary(aClassification); + } + LOGGER.debug("exit from addClassificationSummariesToAttachmentSummaries()"); + } + + private List addClassificationSummariesToAttachments( + List attachmentImpls, List classifications) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "entry to addClassificationSummariesToAttachments(targetWbId = {}, taskIds = {})", + LoggerUtils.listToString(attachmentImpls), + LoggerUtils.listToString(classifications)); + } + + if (attachmentImpls == null || attachmentImpls.isEmpty()) { + LOGGER.debug("exit from addClassificationSummariesToAttachments()"); + return new ArrayList<>(); + } + + List result = new ArrayList<>(); + for (AttachmentImpl att : attachmentImpls) { + // find the associated task to use the correct domain + ClassificationSummary aClassification = + classifications.stream() + .filter(c -> c != null && c.getId().equals(att.getClassificationSummary().getId())) + .findFirst() + .orElse(null); + + if (aClassification == null) { + throw new SystemException("Could not find a Classification for attachment " + att); + } + att.setClassificationSummary(aClassification); + result.add(att); + } + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("exit from addClassificationSummariesToAttachments(), returning {}", result); + } + + return result; + } + + private TaskImpl initUpdatedTask( + Map customFieldsToUpdate, CustomPropertySelector fieldSelector) + throws InvalidArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "entry to initUpdatedTask(customFieldsToUpdate = {}, fieldSelector = {})", + LoggerUtils.mapToString(customFieldsToUpdate), + fieldSelector); + } + + TaskImpl newTask = new TaskImpl(); + newTask.setModified(Instant.now()); + + for (Map.Entry entry : customFieldsToUpdate.entrySet()) { + String key = entry.getKey(); + fieldSelector.setCustomProperty(key, true); + newTask.setCustomAttribute(key, entry.getValue()); + } + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("exit from initUpdatedTask(), returning {}", newTask); + } + + return newTask; + } + + private void validateCustomFields(Map customFieldsToUpdate) + throws InvalidArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "entry to validateCustomFields(customFieldsToUpdate = {}, taskIds = {})", + LoggerUtils.mapToString(customFieldsToUpdate)); + } + + if (customFieldsToUpdate == null || customFieldsToUpdate.isEmpty()) { + throw new InvalidArgumentException( + "The customFieldsToUpdate argument to updateTasks must not be empty."); + } + + for (Map.Entry entry : customFieldsToUpdate.entrySet()) { + String key = entry.getKey(); + if (!ALLOWED_KEYS.contains(key)) { + throw new InvalidArgumentException( + "The customFieldsToUpdate argument to updateTasks contains invalid key " + key); + } + } + LOGGER.debug("exit from validateCustomFields()"); + } + + private List getTasksToChange(List taskIds) { + return createTaskQuery().idIn(taskIds.toArray(new String[taskIds.size()])).list(); + } + + private List getTasksToChange(ObjectReference selectionCriteria) { + return createTaskQuery() + .primaryObjectReferenceCompanyIn(selectionCriteria.getCompany()) + .primaryObjectReferenceSystemIn(selectionCriteria.getSystem()) + .primaryObjectReferenceSystemInstanceIn(selectionCriteria.getSystemInstance()) + .primaryObjectReferenceTypeIn(selectionCriteria.getType()) + .primaryObjectReferenceValueIn(selectionCriteria.getValue()) + .list(); + } + + private void validateObjectReference(ObjectReference objRef, String objRefType, String objName) + throws InvalidArgumentException { + LOGGER.debug("entry to validateObjectReference()"); + // check that all values in the ObjectReference are set correctly + if (objRef == null) { + throw new InvalidArgumentException(objRefType + " of " + objName + " must not be null"); + } else if (objRef.getCompany() == null || objRef.getCompany().length() == 0) { + throw new InvalidArgumentException( + "Company of " + objRefType + " of " + objName + MUST_NOT_BE_EMPTY); + } else if (objRef.getSystem() == null || objRef.getSystem().length() == 0) { + throw new InvalidArgumentException( + "System of " + objRefType + " of " + objName + MUST_NOT_BE_EMPTY); + } else if (objRef.getSystemInstance() == null || objRef.getSystemInstance().length() == 0) { + throw new InvalidArgumentException( + "SystemInstance of " + objRefType + " of " + objName + MUST_NOT_BE_EMPTY); + } else if (objRef.getType() == null || objRef.getType().length() == 0) { + throw new InvalidArgumentException( + "Type of " + objRefType + " of " + objName + MUST_NOT_BE_EMPTY); + } else if (objRef.getValue() == null || objRef.getValue().length() == 0) { + throw new InvalidArgumentException( + "Value of" + objRefType + " of " + objName + MUST_NOT_BE_EMPTY); + } + LOGGER.debug("exit from validateObjectReference()"); + } + + private PrioDurationHolder handleAttachments(TaskImpl task) throws InvalidArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("entry to handleAttachments(task = {})", task); + } + + List attachments = task.getAttachments(); + if (attachments == null || attachments.isEmpty()) { + return new PrioDurationHolder(null, Integer.MIN_VALUE); + } + + PrioDurationHolder actualPrioDuration = new PrioDurationHolder(MAX_DURATION, Integer.MIN_VALUE); + + Iterator i = attachments.iterator(); + while (i.hasNext()) { + Attachment attachment = i.next(); + if (attachment == null) { + i.remove(); + } else { + actualPrioDuration = handleNonNullAttachment(actualPrioDuration, attachment); + } + } + if (MAX_DURATION.equals(actualPrioDuration.getDuration())) { + actualPrioDuration.setDuration(null); + } + + LOGGER.debug("exit from handleAttachments(), returning {}", actualPrioDuration); + return actualPrioDuration; + } + + private PrioDurationHolder handleNonNullAttachment( + PrioDurationHolder actualPrioDuration, Attachment attachment) + throws InvalidArgumentException { + ObjectReference objRef = attachment.getObjectReference(); + validateObjectReference(objRef, "ObjectReference", "Attachment"); + if (attachment.getClassificationSummary() == null) { + throw new InvalidArgumentException( + "Classification of attachment " + attachment + " must not be null"); + } else { + ClassificationSummary classificationSummary = attachment.getClassificationSummary(); + if (classificationSummary != null) { + actualPrioDuration = + getNewPrioDuration( + actualPrioDuration, + classificationSummary.getPriority(), + classificationSummary.getServiceLevel()); + } + } + return actualPrioDuration; + } + + private void standardUpdateActions( + TaskImpl oldTaskImpl, TaskImpl newTaskImpl, PrioDurationHolder prioDurationFromAttachments) + throws InvalidArgumentException, ConcurrencyException, ClassificationNotFoundException { + validateObjectReference(newTaskImpl.getPrimaryObjRef(), "primary ObjectReference", "Task"); + // TODO: not safe to rely only on different timestamps. + // With fast execution below 1ms there will be no concurrencyException + if (oldTaskImpl.getModified() != null + && !oldTaskImpl.getModified().equals(newTaskImpl.getModified()) + || oldTaskImpl.getClaimed() != null + && !oldTaskImpl.getClaimed().equals(newTaskImpl.getClaimed()) + || oldTaskImpl.getState() != null + && !oldTaskImpl.getState().equals(newTaskImpl.getState())) { + throw new ConcurrencyException("The task has already been updated by another user"); + } + + if (oldTaskImpl.getExternalId() == null + || !(oldTaskImpl.getExternalId().equals(newTaskImpl.getExternalId()))) { + throw new InvalidArgumentException( + "A task's external Id cannot be changed via update of the task"); + } + + String newWorkbasketKey = newTaskImpl.getWorkbasketKey(); + if (newWorkbasketKey != null && !newWorkbasketKey.equals(oldTaskImpl.getWorkbasketKey())) { + throw new InvalidArgumentException( + "A task's Workbasket cannot be changed via update of the task"); + } + + if (newTaskImpl.getPlanned() == null) { + newTaskImpl.setPlanned(oldTaskImpl.getPlanned()); + } + + // if no business process id is provided, use the id of the old task. + if (newTaskImpl.getBusinessProcessId() == null) { + newTaskImpl.setBusinessProcessId(oldTaskImpl.getBusinessProcessId()); + } + + updateClassificationRelatedProperties(oldTaskImpl, newTaskImpl, prioDurationFromAttachments); + + newTaskImpl.setModified(Instant.now()); + } + + private void updateClassificationRelatedProperties( + TaskImpl oldTaskImpl, TaskImpl newTaskImpl, PrioDurationHolder prioDurationFromAttachments) + throws ClassificationNotFoundException { + LOGGER.debug("entry to updateClassificationRelatedProperties()"); + // insert Classification specifications if Classification is given. + ClassificationSummary oldClassificationSummary = oldTaskImpl.getClassificationSummary(); + ClassificationSummary newClassificationSummary = newTaskImpl.getClassificationSummary(); + if (newClassificationSummary == null) { + newClassificationSummary = oldClassificationSummary; + } + + if (newClassificationSummary + == null) { // newClassification is null -> take prio and duration from attachments + updateTaskPrioDurationFromAttachments(newTaskImpl, prioDurationFromAttachments); + } else { + updateTaskPrioDurationFromClassification( + newTaskImpl, + prioDurationFromAttachments, + oldClassificationSummary, + newClassificationSummary); + } + + LOGGER.debug("exit from updateClassificationRelatedProperties()"); + } + + private void updateTaskPrioDurationFromClassification( + TaskImpl newTaskImpl, + PrioDurationHolder prioDurationFromAttachments, + ClassificationSummary oldClassificationSummary, + ClassificationSummary newClassificationSummary) + throws ClassificationNotFoundException { + LOGGER.debug("entry to updateTaskPrioDurationFromClassification()"); + Classification newClassification = null; + if (!oldClassificationSummary.getKey().equals(newClassificationSummary.getKey())) { + newClassification = + this.classificationService.getClassification( + newClassificationSummary.getKey(), newTaskImpl.getWorkbasketSummary().getDomain()); + newClassificationSummary = newClassification.asSummary(); + newTaskImpl.setClassificationSummary(newClassificationSummary); + } + + Duration minDuration = calculateDuration(prioDurationFromAttachments, newClassificationSummary); + if (minDuration != null) { + + long days = + converter.convertWorkingDaysToDays(newTaskImpl.getPlanned(), minDuration.toDays()); + Instant due = newTaskImpl.getPlanned().plus(Duration.ofDays(days)); + + newTaskImpl.setDue(due); + } + + if (newTaskImpl.getName() == null) { + newTaskImpl.setName(newClassificationSummary.getName()); + } + + if (newTaskImpl.getDescription() == null && newClassification != null) { + newTaskImpl.setDescription(newClassification.getDescription()); + } + + int newPriority = + Math.max(newClassificationSummary.getPriority(), prioDurationFromAttachments.getPrio()); + newTaskImpl.setPriority(newPriority); + LOGGER.debug("exit from updateTaskPrioDurationFromClassification()"); + } + + private PrioDurationHolder handleAttachmentsOnTaskUpdate( + TaskImpl oldTaskImpl, TaskImpl newTaskImpl) throws AttachmentPersistenceException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "entry to handleAttachmentsOnTaskUpdate(oldTaskImpl = {}, newTaskImpl = {})", + oldTaskImpl, + newTaskImpl); + } + + PrioDurationHolder prioDuration = new PrioDurationHolder(MAX_DURATION, Integer.MIN_VALUE); + + // Iterator for removing invalid current values directly. OldAttachments can be ignored. + Iterator i = newTaskImpl.getAttachments().iterator(); + while (i.hasNext()) { + Attachment attachment = i.next(); + if (attachment != null) { + prioDuration = + handlePrioDurationOfOneAttachmentOnTaskUpdate( + oldTaskImpl, newTaskImpl, prioDuration, attachment); + } else { + i.remove(); + } + } + + // DELETE, when an Attachment was only represented before + deleteAttachmentOnTaskUpdate(oldTaskImpl, newTaskImpl); + if (MAX_DURATION.equals(prioDuration.getDuration())) { + prioDuration.setDuration(null); + } + + LOGGER.debug("exit from handleAttachmentsOnTaskUpdate()"); + return prioDuration; + } + + private void deleteAttachmentOnTaskUpdate(TaskImpl oldTaskImpl, TaskImpl newTaskImpl) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "entry to deleteAttachmentOnTaskUpdate(oldTaskImpl = {}, newTaskImpl = {})", + oldTaskImpl, + newTaskImpl); + } + + for (Attachment oldAttachment : oldTaskImpl.getAttachments()) { + if (oldAttachment != null) { + boolean isRepresented = false; + for (Attachment newAttachment : newTaskImpl.getAttachments()) { + if (newAttachment != null && oldAttachment.getId().equals(newAttachment.getId())) { + isRepresented = true; + break; + } + } + if (!isRepresented) { + attachmentMapper.deleteAttachment(oldAttachment.getId()); + LOGGER.debug( + "TaskService.updateTask() for TaskId={} DELETED an Attachment={}.", + newTaskImpl.getId(), + oldAttachment); + } + } + } + LOGGER.debug("exit from deleteAttachmentOnTaskUpdate()"); + } + + private PrioDurationHolder handlePrioDurationOfOneAttachmentOnTaskUpdate( + TaskImpl oldTaskImpl, + TaskImpl newTaskImpl, + PrioDurationHolder prioDuration, + Attachment attachment) + throws AttachmentPersistenceException { + LOGGER.debug("entry to handlePrioDurationOfOneAttachmentOnTaskUpdate()"); + boolean wasAlreadyPresent = false; + if (attachment.getId() != null) { + for (Attachment oldAttachment : oldTaskImpl.getAttachments()) { + if (oldAttachment != null && attachment.getId().equals(oldAttachment.getId())) { + wasAlreadyPresent = true; + if (!attachment.equals(oldAttachment)) { + prioDuration = + handlePrioDurationOfOneNewAttachmentOnTaskUpdate( + newTaskImpl, prioDuration, attachment); + break; + } + } + } + } + + // ADD, when ID not set or not found in elements + if (!wasAlreadyPresent) { + prioDuration = handleNewAttachmentOnTaskUpdate(newTaskImpl, prioDuration, attachment); + } + + LOGGER.debug( + "exit from handlePrioDurationOfOneAttachmentOnTaskUpdate(), returning {}", prioDuration); + return prioDuration; + } + + private PrioDurationHolder handlePrioDurationOfOneNewAttachmentOnTaskUpdate( + TaskImpl newTaskImpl, PrioDurationHolder prioDuration, Attachment attachment) { + LOGGER.debug("entry to handlePrioDurationOfOneNewAttachmentOnTaskUpdate()"); + AttachmentImpl temp = (AttachmentImpl) attachment; + + ClassificationSummary classification = attachment.getClassificationSummary(); + if (classification != null) { + prioDuration = + getNewPrioDuration( + prioDuration, classification.getPriority(), classification.getServiceLevel()); + } + + temp.setModified(Instant.now()); + attachmentMapper.update(temp); + LOGGER.debug( + "TaskService.updateTask() for TaskId={} UPDATED an Attachment={}.", + newTaskImpl.getId(), + attachment); + LOGGER.debug( + "exit from handlePrioDurationOfOneNewAttachmentOnTaskUpdate(), returning {}", prioDuration); + return prioDuration; + } + + private PrioDurationHolder handleNewAttachmentOnTaskUpdate( + TaskImpl newTaskImpl, PrioDurationHolder prioDuration, Attachment attachment) + throws AttachmentPersistenceException { + LOGGER.debug("entry to handleNewAttachmentOnTaskUpdate()"); + AttachmentImpl attachmentImpl = (AttachmentImpl) attachment; + initAttachment(attachmentImpl, newTaskImpl); + ClassificationSummary classification = attachment.getClassificationSummary(); + if (classification != null) { + prioDuration = + getNewPrioDuration( + prioDuration, classification.getPriority(), classification.getServiceLevel()); + } + + try { + attachmentMapper.insert(attachmentImpl); + LOGGER.debug( + "TaskService.updateTask() for TaskId={} INSERTED an Attachment={}.", + newTaskImpl.getId(), + attachmentImpl); + } catch (PersistenceException e) { + throw new AttachmentPersistenceException( + "Cannot insert the Attachement " + + attachmentImpl.getId() + + " for Task " + + newTaskImpl.getId() + + " because it already exists.", + e.getCause()); + } + LOGGER.debug("exit from handleNewAttachmentOnTaskUpdate(), returning {}", prioDuration); + return prioDuration; + } + + private PrioDurationHolder handleAttachmentsOnClassificationUpdate(Task task) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("entry to handleAttachmentsOnClassificationUpdate(task = {})", task); + } + + PrioDurationHolder prioDuration = new PrioDurationHolder(MAX_DURATION, Integer.MIN_VALUE); + + // Iterator for removing invalid current values directly. OldAttachments can be ignored. + for (Attachment attachment : task.getAttachments()) { + if (attachment != null) { + ClassificationSummary classification = attachment.getClassificationSummary(); + if (classification != null) { + prioDuration = + getNewPrioDuration( + prioDuration, classification.getPriority(), classification.getServiceLevel()); + } + } + } + if (MAX_DURATION.equals(prioDuration.getDuration())) { + prioDuration.setDuration(null); + } + + LOGGER.debug("exit from handleAttachmentsOnClassificationUpdate(), returning {}", prioDuration); + return prioDuration; + } + + private PrioDurationHolder getNewPrioDuration( + PrioDurationHolder prioDurationHolder, + int prioFromClassification, + String serviceLevelFromClassification) { + LOGGER.debug( + "entry to getNewPrioDuration(prioDurationHolder = {}, prioFromClassification = {}, serviceLevelFromClassification = {})", + prioDurationHolder, + prioFromClassification, + serviceLevelFromClassification); + Duration minDuration = prioDurationHolder.getDuration(); + int maxPrio = prioDurationHolder.getPrio(); + + if (serviceLevelFromClassification != null) { + Duration currentDuration = Duration.parse(serviceLevelFromClassification); + if (prioDurationHolder.getDuration() != null) { + if (prioDurationHolder.getDuration().compareTo(currentDuration) > 0) { + minDuration = currentDuration; + } + } else { + minDuration = currentDuration; + } + } + if (prioFromClassification > maxPrio) { + maxPrio = prioFromClassification; + } + + LOGGER.debug( + "exit from getNewPrioDuration(), returning {}", + new PrioDurationHolder(minDuration, maxPrio)); + return new PrioDurationHolder(minDuration, maxPrio); + } + + private void initAttachment(AttachmentImpl attachment, Task newTask) { + LOGGER.debug("entry to initAttachment()"); + if (attachment.getId() == null) { + attachment.setId(IdGenerator.generateWithPrefix(ID_PREFIX_ATTACHMENT)); + } + if (attachment.getCreated() == null) { + attachment.setCreated(Instant.now()); + } + if (attachment.getModified() == null) { + attachment.setModified(attachment.getCreated()); + } + if (attachment.getTaskId() == null) { + attachment.setTaskId(newTask.getId()); + } + LOGGER.debug("exit from initAttachment()"); + } + + private void updatePrioDueDateOnClassificationUpdate( + TaskImpl task, PrioDurationHolder prioDurationFromAttachments) { + LOGGER.debug("entry to updatePrioDueDateOnClassificationUpdate()"); + ClassificationSummary classificationSummary = task.getClassificationSummary(); + + if (classificationSummary + == null) { // classification is null -> take prio and duration from attachments + updateTaskPrioDurationFromAttachments(task, prioDurationFromAttachments); + } else { + updateTaskPrioDurationFromClassificationAndAttachments( + task, prioDurationFromAttachments, classificationSummary); + } + + LOGGER.debug("exit from updatePrioDueDateOnClassificationUpdate()"); + } + + private void updateTaskPrioDurationFromClassificationAndAttachments( + TaskImpl task, + PrioDurationHolder prioDurationFromAttachments, + ClassificationSummary classificationSummary) { + LOGGER.debug("entry to updateTaskPrioDurationFromClassificationAndAttachments()"); + + Duration minDuration = calculateDuration(prioDurationFromAttachments, classificationSummary); + if (minDuration != null) { + long days = converter.convertWorkingDaysToDays(task.getPlanned(), minDuration.toDays()); + Instant due = task.getPlanned().plus(Duration.ofDays(days)); + + task.setDue(due); + } + + int newPriority = + Math.max(classificationSummary.getPriority(), prioDurationFromAttachments.getPrio()); + task.setPriority(newPriority); + LOGGER.debug("exit from updateTaskPrioDurationFromClassificationAndAttachments()"); + } + + private Task completeTask(String taskId, boolean isForced) + throws TaskNotFoundException, InvalidOwnerException, InvalidStateException, + NotAuthorizedException { + String userId = CurrentUserContext.getUserid(); + LOGGER.debug( + "entry to completeTask(id = {}, userId = {}, isForced = {})", taskId, userId, isForced); + TaskImpl task = null; + try { + taskanaEngine.openConnection(); + task = (TaskImpl) this.getTask(taskId); + + if (task.getState() == TaskState.COMPLETED) { + return task; + } + + // check pre-conditions for non-forced invocation + if (!isForced) { + if (task.getClaimed() == null || task.getState() != TaskState.CLAIMED) { + throw new InvalidStateException(TASK_WITH_ID + taskId + " has to be claimed before."); + } else if (!CurrentUserContext.getAccessIds().contains(task.getOwner())) { + throw new InvalidOwnerException( + "Owner of task " + + taskId + + " is " + + task.getOwner() + + ", but current User is " + + userId); + } + } else { + // CLAIM-forced, if task was not already claimed before. + if (task.getClaimed() == null || task.getState() != TaskState.CLAIMED) { + task = (TaskImpl) this.forceClaim(taskId); + } + } + Instant now = Instant.now(); + task.setCompleted(now); + task.setModified(now); + task.setState(TaskState.COMPLETED); + task.setOwner(userId); + taskMapper.update(task); + LOGGER.debug("Task '{}' completed by user '{}'.", taskId, userId); + if (HistoryEventProducer.isHistoryEnabled()) { + historyEventProducer.createEvent(new CompletedEvent(task)); + } + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from completeTask()"); + } + return task; + } + + private Task claim(String taskId, boolean forceClaim) + throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, + NotAuthorizedException { + String userId = CurrentUserContext.getUserid(); + LOGGER.debug( + "entry to claim(id = {}, userId = {}, forceClaim = {})", taskId, userId, forceClaim); + TaskImpl task = null; + try { + taskanaEngine.openConnection(); + task = (TaskImpl) getTask(taskId); + TaskState state = task.getState(); + if (state == TaskState.COMPLETED) { + throw new InvalidStateException(TASK_WITH_ID + taskId + IS_ALREADY_COMPLETED); + } + if (state == TaskState.CLAIMED && !forceClaim && !task.getOwner().equals(userId)) { + throw new InvalidOwnerException( + TASK_WITH_ID + taskId + IS_ALREADY_CLAIMED_BY + task.getOwner() + "."); + } + Instant now = Instant.now(); + task.setOwner(userId); + task.setModified(now); + task.setClaimed(now); + task.setRead(true); + task.setState(TaskState.CLAIMED); + taskMapper.update(task); + LOGGER.debug("Task '{}' claimed by user '{}'.", taskId, userId); + if (HistoryEventProducer.isHistoryEnabled()) { + historyEventProducer.createEvent(new ClaimedEvent(task)); + } + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from claim()"); + } + return task; + } + + private void updateTaskPrioDurationFromAttachments( + TaskImpl task, PrioDurationHolder prioDurationFromAttachments) { + LOGGER.debug("entry to updateTaskPrioDurationFromAttachments()"); + if (prioDurationFromAttachments.getDuration() != null) { + long days = + converter.convertWorkingDaysToDays( + task.getPlanned(), prioDurationFromAttachments.getDuration().toDays()); + Instant due = task.getPlanned().plus(Duration.ofDays(days)); + task.setDue(due); + } + if (prioDurationFromAttachments.getPrio() > Integer.MIN_VALUE) { + task.setPriority(prioDurationFromAttachments.getPrio()); + } + LOGGER.debug("exit from updateTaskPrioDurationFromAttachments()"); + } + + private List augmentAttachmentsByClassification( + List attachmentImpls, BulkOperationResults bulkLog) { + LOGGER.debug("entry to augmentAttachmentsByClassification()"); + List result = new ArrayList<>(); + if (attachmentImpls == null || attachmentImpls.isEmpty()) { + return result; + } + Set classificationIds = + attachmentImpls.stream() + .map(t -> t.getClassificationSummary().getId()) + .collect(Collectors.toSet()); + List classifications = + classificationService + .createClassificationQuery() .idIn(classificationIds.toArray(new String[0])) .list(); - for (AttachmentImpl att : attachmentImpls) { - ClassificationSummary classificationSummary = classifications.stream() - .filter(cl -> cl.getId().equals(att.getClassificationSummary().getId())) - .findFirst() - .orElse(null); - if (classificationSummary == null) { - String id = att.getClassificationSummary().getId(); - bulkLog.addError(att.getClassificationSummary().getId(), new ClassificationNotFoundException(id, - "When processing task updates due to change of classification, the classification with id " + id - + WAS_NOT_FOUND2)); - } else { - att.setClassificationSummary(classificationSummary); - result.add(att); - } - } - - LOGGER.debug("exit from augmentAttachmentsByClassification()"); - return result; + for (AttachmentImpl att : attachmentImpls) { + ClassificationSummary classificationSummary = + classifications.stream() + .filter(cl -> cl.getId().equals(att.getClassificationSummary().getId())) + .findFirst() + .orElse(null); + if (classificationSummary == null) { + String id = att.getClassificationSummary().getId(); + bulkLog.addError( + att.getClassificationSummary().getId(), + new ClassificationNotFoundException( + id, + "When processing task updates due to change of classification, the classification with id " + + id + + WAS_NOT_FOUND2)); + } else { + att.setClassificationSummary(classificationSummary); + result.add(att); + } } - private void deleteTask(String taskId, boolean forceDelete) - throws TaskNotFoundException, InvalidStateException, NotAuthorizedException { - LOGGER.debug("entry to deleteTask(taskId = {} , forceDelete = {})", taskId, forceDelete); - taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.ADMIN); - TaskImpl task = null; - try { - taskanaEngine.openConnection(); - task = (TaskImpl) getTask(taskId); + LOGGER.debug("exit from augmentAttachmentsByClassification()"); + return result; + } - if (!TaskState.COMPLETED.equals(task.getState()) && !forceDelete) { - throw new InvalidStateException("Cannot delete Task " + taskId + " because it is not completed."); - } - if (CallbackState.CALLBACK_PROCESSING_REQUIRED.equals(task.getCallbackState())) { - throw new InvalidStateException( - "Task " + taskId + " cannot be deleted because its callback is not yet processed"); - } + private void deleteTask(String taskId, boolean forceDelete) + throws TaskNotFoundException, InvalidStateException, NotAuthorizedException { + LOGGER.debug("entry to deleteTask(taskId = {} , forceDelete = {})", taskId, forceDelete); + taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.ADMIN); + TaskImpl task = null; + try { + taskanaEngine.openConnection(); + task = (TaskImpl) getTask(taskId); - taskMapper.delete(taskId); - LOGGER.debug("Task {} deleted.", taskId); - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from deleteTask()."); - } + if (!TaskState.COMPLETED.equals(task.getState()) && !forceDelete) { + throw new InvalidStateException( + "Cannot delete Task " + taskId + " because it is not completed."); + } + if (CallbackState.CALLBACK_PROCESSING_REQUIRED.equals(task.getCallbackState())) { + throw new InvalidStateException( + "Task " + taskId + " cannot be deleted because its callback is not yet processed"); + } + + taskMapper.delete(taskId); + LOGGER.debug("Task {} deleted.", taskId); + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from deleteTask()."); + } + } + + private void createTasksCompletedEvents(List taskSummaries) { + taskSummaries.stream() + .forEach(task -> historyEventProducer.createEvent(new CompletedEvent(task))); + } + + /** + * hold a pair of priority and Duration. + * + * @author bbr + */ + static class PrioDurationHolder { + + private Duration duration; + + private int prio; + + PrioDurationHolder(Duration duration, int prio) { + super(); + this.duration = duration; + this.prio = prio; } - private void createTasksCompletedEvents(List taskSummaries) { - taskSummaries.stream().forEach(task -> historyEventProducer.createEvent(new CompletedEvent(task)) - ); + public Duration getDuration() { + return duration; } - List augmentTaskSummariesByContainedSummaries(List taskSummaries) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("entry to augmentTaskSummariesByContainedSummaries(taskSummaries= {})", - LoggerUtils.listToString(taskSummaries)); - } - - List result = new ArrayList<>(); - if (taskSummaries == null || taskSummaries.isEmpty()) { - return result; - } - - Set taskIdSet = taskSummaries.stream().map(TaskSummaryImpl::getTaskId).collect(Collectors.toSet()); - String[] taskIdArray = taskIdSet.toArray(new String[0]); - - LOGGER.debug("augmentTaskSummariesByContainedSummaries() about to query for attachmentSummaries "); - List attachmentSummaries = attachmentMapper - .findAttachmentSummariesByTaskIds(taskIdArray); - - List classifications = findClassificationsForTasksAndAttachments(taskSummaries, - attachmentSummaries); - - addClassificationSummariesToTaskSummaries(taskSummaries, classifications); - addWorkbasketSummariesToTaskSummaries(taskSummaries); - addAttachmentSummariesToTaskSummaries(taskSummaries, attachmentSummaries, classifications); - result.addAll(taskSummaries); - LOGGER.debug("exit from to augmentTaskSummariesByContainedSummaries()"); - return result; + public void setDuration(Duration duration) { + this.duration = duration; } - /** - * hold a pair of priority and Duration. - * - * @author bbr - */ - static class PrioDurationHolder { - - private Duration duration; - - private int prio; - - PrioDurationHolder(Duration duration, int prio) { - super(); - this.duration = duration; - this.prio = prio; - } - - public Duration getDuration() { - return duration; - } - - public void setDuration(Duration duration) { - this.duration = duration; - } - - public int getPrio() { - return prio; - } - - public void setPrio(int prio) { - this.prio = prio; - } - - @Override - public String toString() { - return "PrioDurationHolder [duration=" + duration + ", prio=" + prio + "]"; - } + public int getPrio() { + return prio; } + public void setPrio(int prio) { + this.prio = prio; + } + + @Override + public String toString() { + return "PrioDurationHolder [duration=" + duration + ", prio=" + prio + "]"; + } + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/TaskStatusReportBuilderImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/TaskStatusReportBuilderImpl.java index af0156295..f052d4beb 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/TaskStatusReportBuilderImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/TaskStatusReportBuilderImpl.java @@ -1,7 +1,6 @@ package pro.taskana.impl; import java.util.List; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -12,47 +11,47 @@ import pro.taskana.impl.report.item.TaskQueryItem; import pro.taskana.mappings.TaskMonitorMapper; import pro.taskana.report.TaskStatusReport; -/** - * The implementation of TaskStatusReportBuilder. - */ +/** The implementation of TaskStatusReportBuilder. */ public class TaskStatusReportBuilderImpl implements TaskStatusReport.Builder { - private static final Logger LOGGER = LoggerFactory.getLogger(TaskStatusReportBuilderImpl.class); - private InternalTaskanaEngine taskanaEngine; - private TaskMonitorMapper taskMonitorMapper; - private List domains; - private List states; + private static final Logger LOGGER = LoggerFactory.getLogger(TaskStatusReportBuilderImpl.class); + private InternalTaskanaEngine taskanaEngine; + private TaskMonitorMapper taskMonitorMapper; + private List domains; + private List states; - TaskStatusReportBuilderImpl(InternalTaskanaEngine taskanaEngine, TaskMonitorMapper taskMonitorMapper) { - this.taskanaEngine = taskanaEngine; - this.taskMonitorMapper = taskMonitorMapper; - } + TaskStatusReportBuilderImpl( + InternalTaskanaEngine taskanaEngine, TaskMonitorMapper taskMonitorMapper) { + this.taskanaEngine = taskanaEngine; + this.taskMonitorMapper = taskMonitorMapper; + } - @Override - public TaskStatusReportBuilderImpl stateIn(List states) { - this.states = states; - return this; - } + @Override + public TaskStatusReportBuilderImpl stateIn(List states) { + this.states = states; + return this; + } - @Override - public TaskStatusReportBuilderImpl domainIn(List domains) { - this.domains = domains; - return this; - } + @Override + public TaskStatusReportBuilderImpl domainIn(List domains) { + this.domains = domains; + return this; + } - @Override - public TaskStatusReport buildReport() throws NotAuthorizedException { - LOGGER.debug("entry to buildReport(), this = {}", this); - this.taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.MONITOR, TaskanaRole.ADMIN); - try { - this.taskanaEngine.openConnection(); - List tasks = this.taskMonitorMapper.getTasksCountByState(this.domains, this.states); - TaskStatusReport report = new TaskStatusReport(this.states); - report.addItems(tasks); - return report; - } finally { - this.taskanaEngine.returnConnection(); - LOGGER.debug("exit from buildReport()."); - } + @Override + public TaskStatusReport buildReport() throws NotAuthorizedException { + LOGGER.debug("entry to buildReport(), this = {}", this); + this.taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.MONITOR, TaskanaRole.ADMIN); + try { + this.taskanaEngine.openConnection(); + List tasks = + this.taskMonitorMapper.getTasksCountByState(this.domains, this.states); + TaskStatusReport report = new TaskStatusReport(this.states); + report.addItems(tasks); + return report; + } finally { + this.taskanaEngine.returnConnection(); + LOGGER.debug("exit from buildReport()."); } + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/TaskSummaryImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/TaskSummaryImpl.java index 78f476009..de8d23ae3 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/TaskSummaryImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/TaskSummaryImpl.java @@ -13,658 +13,817 @@ import pro.taskana.WorkbasketSummary; import pro.taskana.exceptions.InvalidArgumentException; import pro.taskana.exceptions.SystemException; -/** - * Entity which contains the most important informations about a Task. - */ +/** Entity which contains the most important informations about a Task. */ public class TaskSummaryImpl implements TaskSummary { - private String taskId; - private String externalId; - private Instant created; - private Instant claimed; - private Instant completed; - private Instant modified; - private Instant planned; - private Instant due; - private String name; - private String creator; - private String note; - private int priority; - private TaskState state; - private ClassificationSummary classificationSummary; - private WorkbasketSummary workbasketSummary; - private String businessProcessId; - private String parentBusinessProcessId; - private String owner; - private ObjectReference primaryObjRef; - private boolean isRead; - private boolean isTransferred; - // All objects have to be serializable - private List attachmentSummaries = new ArrayList<>(); - private String custom1; - private String custom2; - private String custom3; - private String custom4; - private String custom5; - private String custom6; - private String custom7; - private String custom8; - private String custom9; - private String custom10; - private String custom11; - private String custom12; - private String custom13; - private String custom14; - private String custom15; - private String custom16; - - - TaskSummaryImpl() { - } - - /* - * (non-Javadoc) - * @see pro.taskana.TaskSummary#getTaskId() - */ - @Override - public String getTaskId() { - return taskId; - } - - public void setTaskId(String id) { - this.taskId = id; - } - - /* - * (non-Javadoc) - * @see pro.taskana.TaskSummary#getExternalId() - */ - @Override - public String getExternalId() { - return externalId; - } - - public void setExternalId(String externalId) { - this.externalId = externalId; - } - - /* - * (non-Javadoc) - * @see pro.taskana.TaskSummary#getCreated() - */ - @Override - public Instant getCreated() { - return created; - } - - public void setCreated(Instant created) { - this.created = created; - } - - /* - * (non-Javadoc) - * @see pro.taskana.TaskSummary#getClaimed() - */ - @Override - public Instant getClaimed() { - return claimed; - } - - public void setClaimed(Instant claimed) { - this.claimed = claimed; - } - - /* - * (non-Javadoc) - * @see pro.taskana.TaskSummary#getCompleted() - */ - @Override - public Instant getCompleted() { - return completed; - } - - public void setCompleted(Instant completed) { - this.completed = completed; - } - - /* - * (non-Javadoc) - * @see pro.taskana.TaskSummary#getModified() - */ - @Override - public Instant getModified() { - return modified; - } - - public void setModified(Instant modified) { - this.modified = modified; - } - - /* - * (non-Javadoc) - * @see pro.taskana.TaskSummary#getPlanned() - */ - @Override - public Instant getPlanned() { - return planned; - } - - public void setPlanned(Instant planned) { - this.planned = planned; - } - - /* - * (non-Javadoc) - * @see pro.taskana.TaskSummary#getDue() - */ - @Override - public Instant getDue() { - return due; - } - - public void setDue(Instant due) { - this.due = due; - } - - /* - * (non-Javadoc) - * @see pro.taskana.TaskSummary#getName() - */ - @Override - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - /* - * (non-Javadoc) - * @see pro.taskana.TaskSummary#getCreator() - */ - @Override - public String getCreator() { - return creator; - } - - public void setCreator(String creator) { - this.creator = creator; - } - - /* - * (non-Javadoc) - * @see pro.taskana.TaskSummary#getNote() - */ - @Override - public String getNote() { - return note; - } - - public void setNote(String note) { - this.note = note; - } - - /* - * (non-Javadoc) - * @see pro.taskana.TaskSummary#getPriority() - */ - @Override - public int getPriority() { - return priority; - } - - public void setPriority(int priority) { - this.priority = priority; - } - - /* - * (non-Javadoc) - * @see pro.taskana.TaskSummary#getState() - */ - @Override - public TaskState getState() { - return state; - } - - public void setState(TaskState state) { - this.state = state; - } - - /* - * (non-Javadoc) - * @see pro.taskana.TaskSummary#getClassificationSummary() - */ - @Override - public ClassificationSummary getClassificationSummary() { - return classificationSummary; - } - - public void setClassificationSummary(ClassificationSummary classificationSummary) { - this.classificationSummary = classificationSummary; - } - - /* - * (non-Javadoc) - * @see pro.taskana.TaskSummary#getWorkbasketSummary() - */ - @Override - public WorkbasketSummary getWorkbasketSummary() { - return workbasketSummary; - } - - public void setWorkbasketSummary(WorkbasketSummary workbasketSummary) { - this.workbasketSummary = workbasketSummary; - } - - // utility method to allow mybatis access to workbasketSummary - public WorkbasketSummaryImpl getWorkbasketSummaryImpl() { - return (WorkbasketSummaryImpl) workbasketSummary; - } - - // utility method to allow mybatis access to workbasketSummary - public void setWorkbasketSummaryImpl(WorkbasketSummaryImpl workbasketSummary) { - setWorkbasketSummary(workbasketSummary); - } - - /* - * (non-Javadoc) - * @see pro.taskana.TaskSummary#getDomain() - */ - @Override - public String getDomain() { - return workbasketSummary == null ? null : workbasketSummary.getDomain(); - } - - public void setDomain(String domain) { - if (workbasketSummary == null) { - workbasketSummary = new WorkbasketSummaryImpl(); - } - ((WorkbasketSummaryImpl) this.workbasketSummary).setDomain(domain); - } - - /* - * (non-Javadoc) - * @see pro.taskana.TaskSummary#getBusinessProcessId() - */ - @Override - public String getBusinessProcessId() { - return businessProcessId; - } - - public void setBusinessProcessId(String businessProcessId) { - this.businessProcessId = businessProcessId; - } - - /* - * (non-Javadoc) - * @see pro.taskana.TaskSummary#getParentBusinessProcessId() - */ - @Override - public String getParentBusinessProcessId() { - return parentBusinessProcessId; - } - - public void setParentBusinessProcessId(String parentBusinessProcessId) { - this.parentBusinessProcessId = parentBusinessProcessId; - } - - /* - * (non-Javadoc) - * @see pro.taskana.TaskSummary#getOwner() - */ - @Override - public String getOwner() { - return owner; - } - - public void setOwner(String owner) { - this.owner = owner; - } - - /* - * (non-Javadoc) - * @see pro.taskana.TaskSummary#getPrimaryObjRef() - */ - @Override - public ObjectReference getPrimaryObjRef() { - return primaryObjRef; - } - - public void setPrimaryObjRef(ObjectReference primaryObjRef) { - this.primaryObjRef = primaryObjRef; - } - - /* - * (non-Javadoc) - * @see pro.taskana.TaskSummary#isRead() - */ - @Override - public boolean isRead() { - return isRead; - } - - public void setRead(boolean isRead) { - this.isRead = isRead; - } - - /* - * (non-Javadoc) - * @see pro.taskana.TaskSummary#isTransferred() - */ - @Override - public boolean isTransferred() { - return isTransferred; - } - - public void setTransferred(boolean isTransferred) { - this.isTransferred = isTransferred; - } - - @Override - public List getAttachmentSummaries() { - if (attachmentSummaries == null) { - attachmentSummaries = new ArrayList<>(); - } - return attachmentSummaries; - } - - public void setAttachmentSummaries(List attachmentSummaries) { - this.attachmentSummaries = attachmentSummaries; - } - - public void addAttachmentSummary(AttachmentSummary attachmentSummary) { - if (this.attachmentSummaries == null) { - this.attachmentSummaries = new ArrayList<>(); - } - this.attachmentSummaries.add(attachmentSummary); - } - - /* - * (non-Javadoc) - * @see pro.taskana.TaskSummary#getCustomAttribute(String number) - */ - @Override - public String getCustomAttribute(String number) throws InvalidArgumentException { - int num = 0; - try { - num = Integer.parseInt(number); - } catch (NumberFormatException e) { - throw new InvalidArgumentException( - "Argument '" + number + "' to getCustomAttribute cannot be converted to a number between 1 and 16", - e.getCause()); - } - - switch (num) { - case 1: - return custom1; - case 2: - return custom2; - case 3: - return custom3; - case 4: - return custom4; - case 5: - return custom5; - case 6: - return custom6; - case 7: - return custom7; - case 8: - return custom8; - case 9: - return custom9; - case 10: - return custom10; - case 11: - return custom11; - case 12: - return custom12; - case 13: - return custom13; - case 14: - return custom14; - case 15: - return custom15; - case 16: - return custom16; - default: - throw new InvalidArgumentException( - "Argument '" + number + "' to getCustomAttribute does not represent a number between 1 and 16"); - } - - } - - // auxiliary Method to enable Mybatis to access classificationSummary - public ClassificationSummaryImpl getClassificationSummaryImpl() { - return (ClassificationSummaryImpl) classificationSummary; - } - - // auxiliary Method to enable Mybatis to access classificationSummary - public void setClassificationSummaryImpl(ClassificationSummaryImpl classificationSummary) { - setClassificationSummary(classificationSummary); - } - - // auxiliary Method needed by Mybatis - public void setCustom1(String custom1) { - this.custom1 = custom1; - } - - // auxiliary Method needed by Mybatis - public void setCustom2(String custom2) { - this.custom2 = custom2; - } - - // auxiliary Method needed by Mybatis - public void setCustom3(String custom3) { - this.custom3 = custom3; - } - - // auxiliary Method needed by Mybatis - public void setCustom4(String custom4) { - this.custom4 = custom4; - } - - // auxiliary Method needed by Mybatis - public void setCustom5(String custom5) { - this.custom5 = custom5; - } - - // auxiliary Method needed by Mybatis - public void setCustom6(String custom6) { - this.custom6 = custom6; - } - - // auxiliary Method needed by Mybatis - public void setCustom7(String custom7) { - this.custom7 = custom7; - } - - // auxiliary Method needed by Mybatis - public void setCustom8(String custom8) { - this.custom8 = custom8; - } - - // auxiliary Method needed by Mybatis - public void setCustom9(String custom9) { - this.custom9 = custom9; - } - - // auxiliary Method needed by Mybatis - public void setCustom10(String custom10) { - this.custom10 = custom10; - } - - // auxiliary Method needed by Mybatis - public void setCustom11(String custom11) { - this.custom11 = custom11; - } - - // auxiliary Method needed by Mybatis - public void setCustom12(String custom12) { - this.custom12 = custom12; - } - - // auxiliary Method needed by Mybatis - public void setCustom13(String custom13) { - this.custom13 = custom13; - } - - // auxiliary Method needed by Mybatis - public void setCustom14(String custom14) { - this.custom14 = custom14; - } - - // auxiliary Method needed by Mybatis - public void setCustom15(String custom15) { - this.custom15 = custom15; - } - - // auxiliary Method needed by Mybatis - public void setCustom16(String custom16) { - this.custom16 = custom16; - } - - public String getCustom1() { + private String taskId; + private String externalId; + private Instant created; + private Instant claimed; + private Instant completed; + private Instant modified; + private Instant planned; + private Instant due; + private String name; + private String creator; + private String note; + private int priority; + private TaskState state; + private ClassificationSummary classificationSummary; + private WorkbasketSummary workbasketSummary; + private String businessProcessId; + private String parentBusinessProcessId; + private String owner; + private ObjectReference primaryObjRef; + private boolean isRead; + private boolean isTransferred; + // All objects have to be serializable + private List attachmentSummaries = new ArrayList<>(); + private String custom1; + private String custom2; + private String custom3; + private String custom4; + private String custom5; + private String custom6; + private String custom7; + private String custom8; + private String custom9; + private String custom10; + private String custom11; + private String custom12; + private String custom13; + private String custom14; + private String custom15; + private String custom16; + + TaskSummaryImpl() {} + + /* + * (non-Javadoc) + * @see pro.taskana.TaskSummary#getTaskId() + */ + @Override + public String getTaskId() { + return taskId; + } + + public void setTaskId(String id) { + this.taskId = id; + } + + /* + * (non-Javadoc) + * @see pro.taskana.TaskSummary#getExternalId() + */ + @Override + public String getExternalId() { + return externalId; + } + + public void setExternalId(String externalId) { + this.externalId = externalId; + } + + /* + * (non-Javadoc) + * @see pro.taskana.TaskSummary#getCreated() + */ + @Override + public Instant getCreated() { + return created; + } + + public void setCreated(Instant created) { + this.created = created; + } + + /* + * (non-Javadoc) + * @see pro.taskana.TaskSummary#getClaimed() + */ + @Override + public Instant getClaimed() { + return claimed; + } + + public void setClaimed(Instant claimed) { + this.claimed = claimed; + } + + /* + * (non-Javadoc) + * @see pro.taskana.TaskSummary#getCompleted() + */ + @Override + public Instant getCompleted() { + return completed; + } + + public void setCompleted(Instant completed) { + this.completed = completed; + } + + /* + * (non-Javadoc) + * @see pro.taskana.TaskSummary#getModified() + */ + @Override + public Instant getModified() { + return modified; + } + + public void setModified(Instant modified) { + this.modified = modified; + } + + /* + * (non-Javadoc) + * @see pro.taskana.TaskSummary#getPlanned() + */ + @Override + public Instant getPlanned() { + return planned; + } + + public void setPlanned(Instant planned) { + this.planned = planned; + } + + /* + * (non-Javadoc) + * @see pro.taskana.TaskSummary#getDue() + */ + @Override + public Instant getDue() { + return due; + } + + public void setDue(Instant due) { + this.due = due; + } + + /* + * (non-Javadoc) + * @see pro.taskana.TaskSummary#getName() + */ + @Override + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + /* + * (non-Javadoc) + * @see pro.taskana.TaskSummary#getCreator() + */ + @Override + public String getCreator() { + return creator; + } + + public void setCreator(String creator) { + this.creator = creator; + } + + /* + * (non-Javadoc) + * @see pro.taskana.TaskSummary#getNote() + */ + @Override + public String getNote() { + return note; + } + + public void setNote(String note) { + this.note = note; + } + + /* + * (non-Javadoc) + * @see pro.taskana.TaskSummary#getPriority() + */ + @Override + public int getPriority() { + return priority; + } + + public void setPriority(int priority) { + this.priority = priority; + } + + /* + * (non-Javadoc) + * @see pro.taskana.TaskSummary#getState() + */ + @Override + public TaskState getState() { + return state; + } + + public void setState(TaskState state) { + this.state = state; + } + + /* + * (non-Javadoc) + * @see pro.taskana.TaskSummary#getClassificationSummary() + */ + @Override + public ClassificationSummary getClassificationSummary() { + return classificationSummary; + } + + public void setClassificationSummary(ClassificationSummary classificationSummary) { + this.classificationSummary = classificationSummary; + } + + /* + * (non-Javadoc) + * @see pro.taskana.TaskSummary#getWorkbasketSummary() + */ + @Override + public WorkbasketSummary getWorkbasketSummary() { + return workbasketSummary; + } + + public void setWorkbasketSummary(WorkbasketSummary workbasketSummary) { + this.workbasketSummary = workbasketSummary; + } + + // utility method to allow mybatis access to workbasketSummary + public WorkbasketSummaryImpl getWorkbasketSummaryImpl() { + return (WorkbasketSummaryImpl) workbasketSummary; + } + + // utility method to allow mybatis access to workbasketSummary + public void setWorkbasketSummaryImpl(WorkbasketSummaryImpl workbasketSummary) { + setWorkbasketSummary(workbasketSummary); + } + + /* + * (non-Javadoc) + * @see pro.taskana.TaskSummary#getDomain() + */ + @Override + public String getDomain() { + return workbasketSummary == null ? null : workbasketSummary.getDomain(); + } + + public void setDomain(String domain) { + if (workbasketSummary == null) { + workbasketSummary = new WorkbasketSummaryImpl(); + } + ((WorkbasketSummaryImpl) this.workbasketSummary).setDomain(domain); + } + + /* + * (non-Javadoc) + * @see pro.taskana.TaskSummary#getBusinessProcessId() + */ + @Override + public String getBusinessProcessId() { + return businessProcessId; + } + + public void setBusinessProcessId(String businessProcessId) { + this.businessProcessId = businessProcessId; + } + + /* + * (non-Javadoc) + * @see pro.taskana.TaskSummary#getParentBusinessProcessId() + */ + @Override + public String getParentBusinessProcessId() { + return parentBusinessProcessId; + } + + public void setParentBusinessProcessId(String parentBusinessProcessId) { + this.parentBusinessProcessId = parentBusinessProcessId; + } + + /* + * (non-Javadoc) + * @see pro.taskana.TaskSummary#getOwner() + */ + @Override + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + + /* + * (non-Javadoc) + * @see pro.taskana.TaskSummary#getPrimaryObjRef() + */ + @Override + public ObjectReference getPrimaryObjRef() { + return primaryObjRef; + } + + public void setPrimaryObjRef(ObjectReference primaryObjRef) { + this.primaryObjRef = primaryObjRef; + } + + /* + * (non-Javadoc) + * @see pro.taskana.TaskSummary#isRead() + */ + @Override + public boolean isRead() { + return isRead; + } + + public void setRead(boolean isRead) { + this.isRead = isRead; + } + + /* + * (non-Javadoc) + * @see pro.taskana.TaskSummary#isTransferred() + */ + @Override + public boolean isTransferred() { + return isTransferred; + } + + public void setTransferred(boolean isTransferred) { + this.isTransferred = isTransferred; + } + + @Override + public List getAttachmentSummaries() { + if (attachmentSummaries == null) { + attachmentSummaries = new ArrayList<>(); + } + return attachmentSummaries; + } + + public void setAttachmentSummaries(List attachmentSummaries) { + this.attachmentSummaries = attachmentSummaries; + } + + public void addAttachmentSummary(AttachmentSummary attachmentSummary) { + if (this.attachmentSummaries == null) { + this.attachmentSummaries = new ArrayList<>(); + } + this.attachmentSummaries.add(attachmentSummary); + } + + /* + * (non-Javadoc) + * @see pro.taskana.TaskSummary#getCustomAttribute(String number) + */ + @Override + public String getCustomAttribute(String number) throws InvalidArgumentException { + int num = 0; + try { + num = Integer.parseInt(number); + } catch (NumberFormatException e) { + throw new InvalidArgumentException( + "Argument '" + + number + + "' to getCustomAttribute cannot be converted to a number between 1 and 16", + e.getCause()); + } + + switch (num) { + case 1: return custom1; - } - - public String getCustom2() { + case 2: return custom2; - } - - public String getCustom3() { + case 3: return custom3; - } - - public String getCustom4() { + case 4: return custom4; - } - - public String getCustom5() { + case 5: return custom5; - } - - public String getCustom6() { + case 6: return custom6; - } - - public String getCustom7() { + case 7: return custom7; - } - - public String getCustom8() { + case 8: return custom8; - } - - public String getCustom9() { + case 9: return custom9; - } - - public String getCustom10() { + case 10: return custom10; - } - - public String getCustom11() { + case 11: return custom11; - } - - public String getCustom12() { + case 12: return custom12; - } - - public String getCustom13() { + case 13: return custom13; - } - - public String getCustom14() { + case 14: return custom14; - } - - public String getCustom15() { + case 15: return custom15; - } - - public String getCustom16() { + case 16: return custom16; + default: + throw new InvalidArgumentException( + "Argument '" + + number + + "' to getCustomAttribute does not represent a number between 1 and 16"); + } + } + + // auxiliary Method to enable Mybatis to access classificationSummary + public ClassificationSummaryImpl getClassificationSummaryImpl() { + return (ClassificationSummaryImpl) classificationSummary; + } + + // auxiliary Method to enable Mybatis to access classificationSummary + public void setClassificationSummaryImpl(ClassificationSummaryImpl classificationSummary) { + setClassificationSummary(classificationSummary); + } + + public String getCustom1() { + return custom1; + } + + // auxiliary Method needed by Mybatis + public void setCustom1(String custom1) { + this.custom1 = custom1; + } + + public String getCustom2() { + return custom2; + } + + // auxiliary Method needed by Mybatis + public void setCustom2(String custom2) { + this.custom2 = custom2; + } + + public String getCustom3() { + return custom3; + } + + // auxiliary Method needed by Mybatis + public void setCustom3(String custom3) { + this.custom3 = custom3; + } + + public String getCustom4() { + return custom4; + } + + // auxiliary Method needed by Mybatis + public void setCustom4(String custom4) { + this.custom4 = custom4; + } + + public String getCustom5() { + return custom5; + } + + // auxiliary Method needed by Mybatis + public void setCustom5(String custom5) { + this.custom5 = custom5; + } + + public String getCustom6() { + return custom6; + } + + // auxiliary Method needed by Mybatis + public void setCustom6(String custom6) { + this.custom6 = custom6; + } + + public String getCustom7() { + return custom7; + } + + // auxiliary Method needed by Mybatis + public void setCustom7(String custom7) { + this.custom7 = custom7; + } + + public String getCustom8() { + return custom8; + } + + // auxiliary Method needed by Mybatis + public void setCustom8(String custom8) { + this.custom8 = custom8; + } + + public String getCustom9() { + return custom9; + } + + // auxiliary Method needed by Mybatis + public void setCustom9(String custom9) { + this.custom9 = custom9; + } + + public String getCustom10() { + return custom10; + } + + // auxiliary Method needed by Mybatis + public void setCustom10(String custom10) { + this.custom10 = custom10; + } + + public String getCustom11() { + return custom11; + } + + // auxiliary Method needed by Mybatis + public void setCustom11(String custom11) { + this.custom11 = custom11; + } + + public String getCustom12() { + return custom12; + } + + // auxiliary Method needed by Mybatis + public void setCustom12(String custom12) { + this.custom12 = custom12; + } + + public String getCustom13() { + return custom13; + } + + // auxiliary Method needed by Mybatis + public void setCustom13(String custom13) { + this.custom13 = custom13; + } + + public String getCustom14() { + return custom14; + } + + // auxiliary Method needed by Mybatis + public void setCustom14(String custom14) { + this.custom14 = custom14; + } + + public String getCustom15() { + return custom15; + } + + // auxiliary Method needed by Mybatis + public void setCustom15(String custom15) { + this.custom15 = custom15; + } + + public String getCustom16() { + return custom16; + } + + // auxiliary Method needed by Mybatis + public void setCustom16(String custom16) { + this.custom16 = custom16; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + Object[] myFields = { + externalId, + attachmentSummaries, + businessProcessId, + claimed, + classificationSummary, + completed, + created, + creator, + custom1, + custom10, + custom11, + custom12, + custom13, + custom14, + custom15, + custom16, + custom2, + custom3, + custom4, + custom5, + custom6, + custom7, + custom8, + custom9, + due, + modified, + name, + note, + owner, + parentBusinessProcessId, + planned, + primaryObjRef, + state, + taskId, + workbasketSummary + }; + + for (Object property : myFields) { + result = prime * result + (property == null ? 0 : property.hashCode()); + } + result = prime * result + (isRead ? 1231 : 1237); + result = prime * result + (isTransferred ? 1231 : 1237); + result = prime * result + priority; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!getClass().isAssignableFrom(obj.getClass())) { + return false; + } + TaskSummaryImpl other = (TaskSummaryImpl) obj; + Object[] myFields = { + externalId, + attachmentSummaries, + businessProcessId, + claimed, + classificationSummary, + completed, + created, + creator, + custom1, + custom10, + custom11, + custom12, + custom13, + custom14, + custom15, + custom16, + custom2, + custom3, + custom4, + custom5, + custom6, + custom7, + custom8, + custom9, + due, + modified, + name, + note, + owner, + parentBusinessProcessId, + planned, + primaryObjRef, + state, + taskId, + workbasketSummary + }; + + Object[] otherFields = { + other.externalId, + other.attachmentSummaries, + other.businessProcessId, + other.claimed, + other.classificationSummary, + other.completed, + other.created, + other.creator, + other.custom1, + other.custom10, + other.custom11, + other.custom12, + other.custom13, + other.custom14, + other.custom15, + other.custom16, + other.custom2, + other.custom3, + other.custom4, + other.custom5, + other.custom6, + other.custom7, + other.custom8, + other.custom9, + other.due, + other.modified, + other.name, + other.note, + other.owner, + other.parentBusinessProcessId, + other.planned, + other.primaryObjRef, + other.state, + other.taskId, + other.workbasketSummary + }; + + if (myFields.length != otherFields.length) { + throw new SystemException("TaskSummaryImpl: length mismatch between internal arrays"); + } + for (int i = 0; i < myFields.length; i++) { + if ((myFields[i] == null && otherFields[i] != null) + || (myFields[i] != null && !myFields[i].equals(otherFields[i]))) { + return false; + } + } + if (isRead != other.isRead) { + return false; + } + if (isTransferred != other.isTransferred) { + return false; } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - Object[] myFields = {externalId, attachmentSummaries, businessProcessId, claimed, classificationSummary, - completed, created, creator, custom1, custom10, custom11, custom12, custom13, custom14, - custom15, custom16, custom2, custom3, custom4, custom5, custom6, custom7, custom8, custom9, - due, modified, name, note, owner, parentBusinessProcessId, planned, primaryObjRef, - state, taskId, workbasketSummary}; - - for (Object property : myFields) { - result = prime * result + (property == null ? 0 : property.hashCode()); - } - result = prime * result + (isRead ? 1231 : 1237); - result = prime * result + (isTransferred ? 1231 : 1237); - result = prime * result + priority; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!getClass().isAssignableFrom(obj.getClass())) { - return false; - } - TaskSummaryImpl other = (TaskSummaryImpl) obj; - Object[] myFields = {externalId, attachmentSummaries, businessProcessId, claimed, classificationSummary, - completed, created, creator, custom1, custom10, custom11, custom12, custom13, custom14, - custom15, custom16, custom2, custom3, custom4, custom5, custom6, custom7, custom8, custom9, - due, modified, name, note, owner, parentBusinessProcessId, planned, primaryObjRef, - state, taskId, workbasketSummary}; - - Object[] otherFields = {other.externalId, other.attachmentSummaries, other.businessProcessId, other.claimed, other.classificationSummary, - other.completed, other.created, other.creator, other.custom1, other.custom10, other.custom11, other.custom12, - other.custom13, other.custom14, other.custom15, other.custom16, other.custom2, other.custom3, other.custom4, - other.custom5, other.custom6, other.custom7, other.custom8, other.custom9, other.due, other.modified, other.name, - other.note, other.owner, other.parentBusinessProcessId, other.planned, other.primaryObjRef, other.state, - other.taskId, other.workbasketSummary}; - - if (myFields.length != otherFields.length) { - throw new SystemException("TaskSummaryImpl: length mismatch between internal arrays"); - } - for (int i = 0; i < myFields.length; i++) { - if ((myFields[i] == null && otherFields[i] != null) - || (myFields[i] != null && !myFields[i].equals(otherFields[i]))) { - return false; - } - } - if (isRead != other.isRead) { - return false; - } - if (isTransferred != other.isTransferred) { - return false; - } - - return (priority == other.priority); - } - - @Override - public String toString() { - return "TaskSummaryImpl [taskId=" + taskId + ", externalId=" + externalId + ", created=" + created - + ", claimed=" + claimed + ", completed=" + completed + ", modified=" + modified + ", planned=" + planned - + ", due=" + due + ", name=" + name + ", creator=" + creator + ", note=" + note + ", priority=" + priority - + ", state=" + state + ", classificationSummary=" + classificationSummary + ", workbasketSummary=" - + workbasketSummary + ", businessProcessId=" + businessProcessId + ", parentBusinessProcessId=" - + parentBusinessProcessId + ", owner=" + owner + ", primaryObjRef=" + primaryObjRef + ", isRead=" + isRead - + ", isTransferred=" + isTransferred + ", attachmentSummaries=" + attachmentSummaries + ", custom1=" - + custom1 + ", custom2=" + custom2 + ", custom3=" + custom3 + ", custom4=" + custom4 + ", custom5=" - + custom5 + ", custom6=" + custom6 + ", custom7=" + custom7 + ", custom8=" + custom8 + ", custom9=" - + custom9 + ", custom10=" + custom10 + ", custom11=" + custom11 + ", custom12=" + custom12 + ", custom13=" - + custom13 + ", custom14=" + custom14 + ", custom15=" + custom15 + ", custom16=" + custom16 + "]"; - } + return (priority == other.priority); + } + @Override + public String toString() { + return "TaskSummaryImpl [taskId=" + + taskId + + ", externalId=" + + externalId + + ", created=" + + created + + ", claimed=" + + claimed + + ", completed=" + + completed + + ", modified=" + + modified + + ", planned=" + + planned + + ", due=" + + due + + ", name=" + + name + + ", creator=" + + creator + + ", note=" + + note + + ", priority=" + + priority + + ", state=" + + state + + ", classificationSummary=" + + classificationSummary + + ", workbasketSummary=" + + workbasketSummary + + ", businessProcessId=" + + businessProcessId + + ", parentBusinessProcessId=" + + parentBusinessProcessId + + ", owner=" + + owner + + ", primaryObjRef=" + + primaryObjRef + + ", isRead=" + + isRead + + ", isTransferred=" + + isTransferred + + ", attachmentSummaries=" + + attachmentSummaries + + ", custom1=" + + custom1 + + ", custom2=" + + custom2 + + ", custom3=" + + custom3 + + ", custom4=" + + custom4 + + ", custom5=" + + custom5 + + ", custom6=" + + custom6 + + ", custom7=" + + custom7 + + ", custom8=" + + custom8 + + ", custom9=" + + custom9 + + ", custom10=" + + custom10 + + ", custom11=" + + custom11 + + ", custom12=" + + custom12 + + ", custom13=" + + custom13 + + ", custom14=" + + custom14 + + ", custom15=" + + custom15 + + ", custom16=" + + custom16 + + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/TaskTransferrer.java b/lib/taskana-core/src/main/java/pro/taskana/impl/TaskTransferrer.java index 200289f22..0b62ee1e3 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/TaskTransferrer.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/TaskTransferrer.java @@ -7,7 +7,6 @@ import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.stream.Collectors; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -30,339 +29,389 @@ import pro.taskana.impl.util.LoggerUtils; import pro.taskana.mappings.TaskMapper; import pro.taskana.security.CurrentUserContext; -/** - * This class is responsible for the transfer of tasks. - */ +/** This class is responsible for the transfer of tasks. */ public class TaskTransferrer { - private static final String WAS_NOT_FOUND2 = " was not found."; - private static final String CANNOT_BE_TRANSFERRED = " cannot be transferred."; - private static final String COMPLETED_TASK_WITH_ID = "Completed task with id "; - private static final String TASK_WITH_ID = "Task with id "; - private static final String WAS_MARKED_FOR_DELETION = " was marked for deletion"; - private static final String THE_WORKBASKET = "The workbasket "; + private static final String WAS_NOT_FOUND2 = " was not found."; + private static final String CANNOT_BE_TRANSFERRED = " cannot be transferred."; + private static final String COMPLETED_TASK_WITH_ID = "Completed task with id "; + private static final String TASK_WITH_ID = "Task with id "; + private static final String WAS_MARKED_FOR_DELETION = " was marked for deletion"; + private static final String THE_WORKBASKET = "The workbasket "; + private static final Logger LOGGER = LoggerFactory.getLogger(TaskTransferrer.class); + private InternalTaskanaEngine taskanaEngine; + private WorkbasketService workbasketService; + private TaskServiceImpl taskService; + private TaskMapper taskMapper; + private HistoryEventProducer historyEventProducer; - private InternalTaskanaEngine taskanaEngine; - private WorkbasketService workbasketService; - private TaskServiceImpl taskService; - private TaskMapper taskMapper; - private HistoryEventProducer historyEventProducer; + TaskTransferrer( + InternalTaskanaEngine taskanaEngine, TaskMapper taskMapper, TaskServiceImpl taskService) { + super(); + this.taskanaEngine = taskanaEngine; + this.taskService = taskService; + this.taskMapper = taskMapper; + this.workbasketService = taskanaEngine.getEngine().getWorkbasketService(); + this.historyEventProducer = taskanaEngine.getHistoryEventProducer(); + } - private static final Logger LOGGER = LoggerFactory.getLogger(TaskTransferrer.class); + Task transfer(String taskId, String destinationWorkbasketKey, String domain) + throws TaskNotFoundException, WorkbasketNotFoundException, NotAuthorizedException, + InvalidStateException { + LOGGER.debug( + "entry to transfer(taskId = {}, destinationWorkbasketKey = {}, domain = {})", + taskId, + destinationWorkbasketKey, + domain); + TaskImpl task = null; + WorkbasketSummary oldWorkbasketSummary = null; + try { + taskanaEngine.openConnection(); + task = (TaskImpl) taskService.getTask(taskId); - TaskTransferrer(InternalTaskanaEngine taskanaEngine, TaskMapper taskMapper, TaskServiceImpl taskService) { - super(); - this.taskanaEngine = taskanaEngine; - this.taskService = taskService; - this.taskMapper = taskMapper; - this.workbasketService = taskanaEngine.getEngine().getWorkbasketService(); - this.historyEventProducer = taskanaEngine.getHistoryEventProducer(); + if (task.getState() == TaskState.COMPLETED) { + throw new InvalidStateException( + COMPLETED_TASK_WITH_ID + task.getId() + CANNOT_BE_TRANSFERRED); + } + + // Save previous workbasket id before transfer it. + oldWorkbasketSummary = task.getWorkbasketSummary(); + + // transfer requires TRANSFER in source and APPEND on destination workbasket + workbasketService.checkAuthorization( + destinationWorkbasketKey, domain, WorkbasketPermission.APPEND); + workbasketService.checkAuthorization( + task.getWorkbasketSummary().getId(), WorkbasketPermission.TRANSFER); + + Workbasket destinationWorkbasket = + workbasketService.getWorkbasket(destinationWorkbasketKey, domain); + + // reset read flag and set transferred flag + task.setRead(false); + task.setTransferred(true); + + // transfer task from source to destination workbasket + if (!destinationWorkbasket.isMarkedForDeletion()) { + task.setWorkbasketSummary(destinationWorkbasket.asSummary()); + } else { + throw new WorkbasketNotFoundException( + destinationWorkbasket.getId(), + THE_WORKBASKET + destinationWorkbasket.getId() + WAS_MARKED_FOR_DELETION); + } + + task.setModified(Instant.now()); + task.setState(TaskState.READY); + task.setOwner(null); + taskMapper.update(task); + LOGGER.debug( + "Method transfer() transferred Task '{}' to destination workbasket {}", + taskId, + destinationWorkbasket.getId()); + if (HistoryEventProducer.isHistoryEnabled()) { + createTaskTransferredEvent(task, oldWorkbasketSummary, destinationWorkbasket.asSummary()); + } + return task; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from transfer(). Returning result {} ", task); + } + } + + Task transfer(String taskId, String destinationWorkbasketId) + throws TaskNotFoundException, WorkbasketNotFoundException, NotAuthorizedException, + InvalidStateException { + LOGGER.debug( + "entry to transfer(taskId = {}, destinationWorkbasketId = {})", + taskId, + destinationWorkbasketId); + TaskImpl task = null; + WorkbasketSummary oldWorkbasketSummary = null; + try { + taskanaEngine.openConnection(); + task = (TaskImpl) taskService.getTask(taskId); + + if (task.getState() == TaskState.COMPLETED) { + throw new InvalidStateException( + COMPLETED_TASK_WITH_ID + task.getId() + CANNOT_BE_TRANSFERRED); + } + oldWorkbasketSummary = task.getWorkbasketSummary(); + + // transfer requires TRANSFER in source and APPEND on destination workbasket + workbasketService.checkAuthorization(destinationWorkbasketId, WorkbasketPermission.APPEND); + workbasketService.checkAuthorization( + task.getWorkbasketSummary().getId(), WorkbasketPermission.TRANSFER); + + Workbasket destinationWorkbasket = workbasketService.getWorkbasket(destinationWorkbasketId); + + // reset read flag and set transferred flag + task.setRead(false); + task.setTransferred(true); + + // transfer task from source to destination workbasket + if (!destinationWorkbasket.isMarkedForDeletion()) { + task.setWorkbasketSummary(destinationWorkbasket.asSummary()); + } else { + throw new WorkbasketNotFoundException( + destinationWorkbasket.getId(), + THE_WORKBASKET + destinationWorkbasket.getId() + WAS_MARKED_FOR_DELETION); + } + + task.setModified(Instant.now()); + task.setState(TaskState.READY); + task.setOwner(null); + taskMapper.update(task); + LOGGER.debug( + "Method transfer() transferred Task '{}' to destination workbasket {}", + taskId, + destinationWorkbasketId); + if (HistoryEventProducer.isHistoryEnabled()) { + createTaskTransferredEvent(task, oldWorkbasketSummary, destinationWorkbasket.asSummary()); + } + return task; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from transfer(). Returning result {} ", task); + } + } + + BulkOperationResults transferTasks( + String destinationWorkbasketKey, String destinationWorkbasketDomain, List taskIds) + throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException { + try { + taskanaEngine.openConnection(); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "entry to transferTasks(targetWbKey = {}, domain = {}, taskIds = {})", + destinationWorkbasketKey, + destinationWorkbasketDomain, + LoggerUtils.listToString(taskIds)); + } + + // Check pre-conditions with trowing Exceptions + if (destinationWorkbasketKey == null || destinationWorkbasketDomain == null) { + throw new InvalidArgumentException( + "DestinationWorkbasketKey or domain can´t be used as NULL-Parameter."); + } + Workbasket destinationWorkbasket = + workbasketService.getWorkbasket(destinationWorkbasketKey, destinationWorkbasketDomain); + + return transferTasks(taskIds, destinationWorkbasket); + } finally { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "exit from transferTasks(targetWbKey = {}, targetWbDomain = {}, destination taskIds = {})", + destinationWorkbasketKey, + destinationWorkbasketDomain, + LoggerUtils.listToString(taskIds)); + } + + taskanaEngine.returnConnection(); + } + } + + BulkOperationResults transferTasks( + String destinationWorkbasketId, List taskIds) + throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException { + try { + taskanaEngine.openConnection(); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "entry to transferTasks(targetWbId = {}, taskIds = {})", + destinationWorkbasketId, + LoggerUtils.listToString(taskIds)); + } + + // Check pre-conditions with trowing Exceptions + if (destinationWorkbasketId == null || destinationWorkbasketId.isEmpty()) { + throw new InvalidArgumentException("DestinationWorkbasketId must not be null or empty."); + } + Workbasket destinationWorkbasket = workbasketService.getWorkbasket(destinationWorkbasketId); + + return transferTasks(taskIds, destinationWorkbasket); + } finally { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "exit from transferTasks(targetWbKey = {}, taskIds = {})", + destinationWorkbasketId, + LoggerUtils.listToString(taskIds)); + } + + taskanaEngine.returnConnection(); + } + } + + private BulkOperationResults transferTasks( + List taskIdsToBeTransferred, Workbasket destinationWorkbasket) + throws InvalidArgumentException, WorkbasketNotFoundException, NotAuthorizedException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "entry to transferTasks(taskIdsToBeTransferred = {}, destinationWorkbasket = {})", + LoggerUtils.listToString(taskIdsToBeTransferred), + destinationWorkbasket); } - Task transfer(String taskId, String destinationWorkbasketKey, String domain) - throws TaskNotFoundException, WorkbasketNotFoundException, NotAuthorizedException, InvalidStateException { - LOGGER.debug("entry to transfer(taskId = {}, destinationWorkbasketKey = {}, domain = {})", taskId, - destinationWorkbasketKey, domain); - TaskImpl task = null; - WorkbasketSummary oldWorkbasketSummary = null; - try { - taskanaEngine.openConnection(); - task = (TaskImpl) taskService.getTask(taskId); + workbasketService.checkAuthorization( + destinationWorkbasket.getId(), WorkbasketPermission.APPEND); - if (task.getState() == TaskState.COMPLETED) { - throw new InvalidStateException(COMPLETED_TASK_WITH_ID + task.getId() + CANNOT_BE_TRANSFERRED); - } + if (taskIdsToBeTransferred == null) { + throw new InvalidArgumentException("TaskIds must not be null."); + } + BulkOperationResults bulkLog = new BulkOperationResults<>(); + List taskIds = new ArrayList<>(taskIdsToBeTransferred); + taskService.removeNonExistingTasksFromTaskIdList(taskIds, bulkLog); - // Save previous workbasket id before transfer it. - oldWorkbasketSummary = task.getWorkbasketSummary(); - - // transfer requires TRANSFER in source and APPEND on destination workbasket - workbasketService.checkAuthorization(destinationWorkbasketKey, domain, WorkbasketPermission.APPEND); - workbasketService.checkAuthorization(task.getWorkbasketSummary().getId(), - WorkbasketPermission.TRANSFER); - - Workbasket destinationWorkbasket = workbasketService.getWorkbasket(destinationWorkbasketKey, domain); - - // reset read flag and set transferred flag - task.setRead(false); - task.setTransferred(true); - - // transfer task from source to destination workbasket - if (!destinationWorkbasket.isMarkedForDeletion()) { - task.setWorkbasketSummary(destinationWorkbasket.asSummary()); - } else { - throw new WorkbasketNotFoundException(destinationWorkbasket.getId(), - THE_WORKBASKET + destinationWorkbasket.getId() + WAS_MARKED_FOR_DELETION); - } - - task.setModified(Instant.now()); - task.setState(TaskState.READY); - task.setOwner(null); - taskMapper.update(task); - LOGGER.debug("Method transfer() transferred Task '{}' to destination workbasket {}", taskId, - destinationWorkbasket.getId()); - if (HistoryEventProducer.isHistoryEnabled()) { - createTaskTransferredEvent(task, oldWorkbasketSummary, destinationWorkbasket.asSummary()); - } - return task; - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from transfer(). Returning result {} ", task); - } + if (taskIds.isEmpty()) { + throw new InvalidArgumentException("TaskIds must not contain only invalid arguments."); } - Task transfer(String taskId, String destinationWorkbasketId) - throws TaskNotFoundException, WorkbasketNotFoundException, NotAuthorizedException, InvalidStateException { - LOGGER.debug("entry to transfer(taskId = {}, destinationWorkbasketId = {})", taskId, destinationWorkbasketId); - TaskImpl task = null; - WorkbasketSummary oldWorkbasketSummary = null; - try { - taskanaEngine.openConnection(); - task = (TaskImpl) taskService.getTask(taskId); - - if (task.getState() == TaskState.COMPLETED) { - throw new InvalidStateException(COMPLETED_TASK_WITH_ID + task.getId() + CANNOT_BE_TRANSFERRED); - } - oldWorkbasketSummary = task.getWorkbasketSummary(); - - // transfer requires TRANSFER in source and APPEND on destination workbasket - workbasketService.checkAuthorization(destinationWorkbasketId, WorkbasketPermission.APPEND); - workbasketService.checkAuthorization(task.getWorkbasketSummary().getId(), - WorkbasketPermission.TRANSFER); - - Workbasket destinationWorkbasket = workbasketService.getWorkbasket(destinationWorkbasketId); - - // reset read flag and set transferred flag - task.setRead(false); - task.setTransferred(true); - - // transfer task from source to destination workbasket - if (!destinationWorkbasket.isMarkedForDeletion()) { - task.setWorkbasketSummary(destinationWorkbasket.asSummary()); - } else { - throw new WorkbasketNotFoundException(destinationWorkbasket.getId(), - THE_WORKBASKET + destinationWorkbasket.getId() + WAS_MARKED_FOR_DELETION); - } - - task.setModified(Instant.now()); - task.setState(TaskState.READY); - task.setOwner(null); - taskMapper.update(task); - LOGGER.debug("Method transfer() transferred Task '{}' to destination workbasket {}", taskId, - destinationWorkbasketId); - if (HistoryEventProducer.isHistoryEnabled()) { - createTaskTransferredEvent(task, oldWorkbasketSummary, destinationWorkbasket.asSummary()); - } - return task; - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from transfer(). Returning result {} ", task); - } + List taskSummaries; + if (taskIds.isEmpty()) { + taskSummaries = new ArrayList<>(); + } else { + taskSummaries = taskMapper.findExistingTasks(taskIds, null); + } + checkIfTransferConditionsAreFulfilled(taskIds, taskSummaries, bulkLog); + updateTasksToBeTransferred(taskIds, taskSummaries, destinationWorkbasket); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("exit from transferTasks(), returning {}", bulkLog); } - BulkOperationResults transferTasks(String destinationWorkbasketKey, - String destinationWorkbasketDomain, List taskIds) - throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException { - try { - taskanaEngine.openConnection(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("entry to transferTasks(targetWbKey = {}, domain = {}, taskIds = {})", - destinationWorkbasketKey, - destinationWorkbasketDomain, LoggerUtils.listToString(taskIds)); - } + return bulkLog; + } - // Check pre-conditions with trowing Exceptions - if (destinationWorkbasketKey == null || destinationWorkbasketDomain == null) { - throw new InvalidArgumentException( - "DestinationWorkbasketKey or domain can´t be used as NULL-Parameter."); - } - Workbasket destinationWorkbasket = workbasketService.getWorkbasket(destinationWorkbasketKey, - destinationWorkbasketDomain); - - return transferTasks(taskIds, destinationWorkbasket); - } finally { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("exit from transferTasks(targetWbKey = {}, targetWbDomain = {}, destination taskIds = {})", - destinationWorkbasketKey, - destinationWorkbasketDomain, LoggerUtils.listToString(taskIds)); - } - - taskanaEngine.returnConnection(); - } + private void checkIfTransferConditionsAreFulfilled( + List taskIds, + List taskSummaries, + BulkOperationResults bulkLog) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "entry to checkIfTransferConditionsAreFulfilled(taskIds = {}, taskSummaries = {}, bulkLog = {})", + LoggerUtils.listToString(taskIds), + LoggerUtils.listToString(taskSummaries), + bulkLog); } - BulkOperationResults transferTasks(String destinationWorkbasketId, - List taskIds) throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException { - try { - taskanaEngine.openConnection(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("entry to transferTasks(targetWbId = {}, taskIds = {})", destinationWorkbasketId, - LoggerUtils.listToString(taskIds)); - } + Set workbasketIds = new HashSet<>(); + taskSummaries.forEach(t -> workbasketIds.add(t.getWorkbasketId())); + WorkbasketQueryImpl query = (WorkbasketQueryImpl) workbasketService.createWorkbasketQuery(); + query.setUsedToAugmentTasks(true); + List sourceWorkbaskets; + if (taskSummaries.isEmpty()) { + sourceWorkbaskets = new ArrayList<>(); + } else { + sourceWorkbaskets = + query + .callerHasPermission(WorkbasketPermission.TRANSFER) + .idIn(workbasketIds.toArray(new String[0])) + .list(); + } + checkIfTasksMatchTransferCriteria(taskIds, taskSummaries, sourceWorkbaskets, bulkLog); + LOGGER.debug("exit from checkIfTransferConditionsAreFulfilled()"); + } - // Check pre-conditions with trowing Exceptions - if (destinationWorkbasketId == null || destinationWorkbasketId.isEmpty()) { - throw new InvalidArgumentException( - "DestinationWorkbasketId must not be null or empty."); - } - Workbasket destinationWorkbasket = workbasketService.getWorkbasket(destinationWorkbasketId); - - return transferTasks(taskIds, destinationWorkbasket); - } finally { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("exit from transferTasks(targetWbKey = {}, taskIds = {})", destinationWorkbasketId, - LoggerUtils.listToString(taskIds)); - } - - taskanaEngine.returnConnection(); - } + private void checkIfTasksMatchTransferCriteria( + List taskIds, + List taskSummaries, + List sourceWorkbaskets, + BulkOperationResults bulkLog) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "entry to checkIfTasksMatchTransferCriteria(taskIds = {}, taskSummaries = {}, sourceWorkbaskets = {}, bulkLog = {})", + LoggerUtils.listToString(taskIds), + LoggerUtils.listToString(taskSummaries), + LoggerUtils.listToString(sourceWorkbaskets), + bulkLog); } - private BulkOperationResults transferTasks(List taskIdsToBeTransferred, - Workbasket destinationWorkbasket) - throws InvalidArgumentException, WorkbasketNotFoundException, NotAuthorizedException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("entry to transferTasks(taskIdsToBeTransferred = {}, destinationWorkbasket = {})", - LoggerUtils.listToString(taskIdsToBeTransferred), destinationWorkbasket); - } + Iterator taskIdIterator = taskIds.iterator(); + while (taskIdIterator.hasNext()) { + String currentTaskId = taskIdIterator.next(); + MinimalTaskSummary taskSummary = + taskSummaries.stream() + .filter(t -> currentTaskId.equals(t.getTaskId())) + .findFirst() + .orElse(null); + if (taskSummary == null) { + bulkLog.addError( + currentTaskId, + new TaskNotFoundException( + currentTaskId, TASK_WITH_ID + currentTaskId + WAS_NOT_FOUND2)); + taskIdIterator.remove(); + } else if (taskSummary.getTaskState() == TaskState.COMPLETED) { + bulkLog.addError( + currentTaskId, + new InvalidStateException( + COMPLETED_TASK_WITH_ID + currentTaskId + CANNOT_BE_TRANSFERRED)); + taskIdIterator.remove(); + } else if (sourceWorkbaskets.stream() + .noneMatch(wb -> taskSummary.getWorkbasketId().equals(wb.getId()))) { + bulkLog.addError( + currentTaskId, + new NotAuthorizedException( + "The workbasket of this task got not TRANSFER permissions. TaskId=" + currentTaskId, + CurrentUserContext.getUserid())); + taskIdIterator.remove(); + } + } + LOGGER.debug("exit from checkIfTasksMatchTransferCriteria()"); + } - workbasketService.checkAuthorization(destinationWorkbasket.getId(), WorkbasketPermission.APPEND); + private void createTaskTransferredEvent( + Task task, WorkbasketSummary oldWorkbasketSummary, WorkbasketSummary newWorkbasketSummary) { + historyEventProducer.createEvent( + new TransferredEvent(task, oldWorkbasketSummary, newWorkbasketSummary)); + } - if (taskIdsToBeTransferred == null) { - throw new InvalidArgumentException("TaskIds must not be null."); - } - BulkOperationResults bulkLog = new BulkOperationResults<>(); - List taskIds = new ArrayList<>(taskIdsToBeTransferred); - taskService.removeNonExistingTasksFromTaskIdList(taskIds, bulkLog); - - if (taskIds.isEmpty()) { - throw new InvalidArgumentException("TaskIds must not contain only invalid arguments."); - } - - List taskSummaries; - if (taskIds.isEmpty()) { - taskSummaries = new ArrayList<>(); - } else { - taskSummaries = taskMapper.findExistingTasks(taskIds, null); - } - checkIfTransferConditionsAreFulfilled(taskIds, taskSummaries, bulkLog); - updateTasksToBeTransferred(taskIds, taskSummaries, destinationWorkbasket); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("exit from transferTasks(), returning {}", bulkLog); - } - - return bulkLog; + private void updateTasksToBeTransferred( + List taskIds, + List taskSummaries, + Workbasket destinationWorkbasket) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "entry to updateTasksToBeTransferred(taskIds = {}, taskSummaries = {})", + LoggerUtils.listToString(taskIds), + LoggerUtils.listToString(taskSummaries), + destinationWorkbasket); } - private void checkIfTransferConditionsAreFulfilled(List taskIds, List taskSummaries, - BulkOperationResults bulkLog) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug( - "entry to checkIfTransferConditionsAreFulfilled(taskIds = {}, taskSummaries = {}, bulkLog = {})", - LoggerUtils.listToString(taskIds), LoggerUtils.listToString(taskSummaries), bulkLog); - } - - Set workbasketIds = new HashSet<>(); - taskSummaries.forEach(t -> workbasketIds.add(t.getWorkbasketId())); - WorkbasketQueryImpl query = (WorkbasketQueryImpl) workbasketService.createWorkbasketQuery(); - query.setUsedToAugmentTasks(true); - List sourceWorkbaskets; - if (taskSummaries.isEmpty()) { - sourceWorkbaskets = new ArrayList<>(); - } else { - sourceWorkbaskets = query - .callerHasPermission(WorkbasketPermission.TRANSFER) - .idIn(workbasketIds.toArray(new String[0])) - .list(); - } - checkIfTasksMatchTransferCriteria(taskIds, taskSummaries, sourceWorkbaskets, bulkLog); - LOGGER.debug("exit from checkIfTransferConditionsAreFulfilled()"); - } - - private void checkIfTasksMatchTransferCriteria(List taskIds, List taskSummaries, - List sourceWorkbaskets, BulkOperationResults bulkLog) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug( - "entry to checkIfTasksMatchTransferCriteria(taskIds = {}, taskSummaries = {}, sourceWorkbaskets = {}, bulkLog = {})", - LoggerUtils.listToString(taskIds), LoggerUtils.listToString(taskSummaries), - LoggerUtils.listToString(sourceWorkbaskets), bulkLog); - } - - Iterator taskIdIterator = taskIds.iterator(); - while (taskIdIterator.hasNext()) { - String currentTaskId = taskIdIterator.next(); - MinimalTaskSummary taskSummary = taskSummaries.stream() - .filter(t -> currentTaskId.equals(t.getTaskId())) - .findFirst() - .orElse(null); - if (taskSummary == null) { - bulkLog.addError(currentTaskId, - new TaskNotFoundException(currentTaskId, TASK_WITH_ID + currentTaskId + WAS_NOT_FOUND2)); - taskIdIterator.remove(); - } else if (taskSummary.getTaskState() == TaskState.COMPLETED) { - bulkLog.addError(currentTaskId, - new InvalidStateException(COMPLETED_TASK_WITH_ID + currentTaskId + CANNOT_BE_TRANSFERRED)); - taskIdIterator.remove(); - } else if (sourceWorkbaskets.stream() - .noneMatch(wb -> taskSummary.getWorkbasketId().equals(wb.getId()))) { - bulkLog.addError(currentTaskId, - new NotAuthorizedException( - "The workbasket of this task got not TRANSFER permissions. TaskId=" + currentTaskId, - CurrentUserContext.getUserid())); - taskIdIterator.remove(); - } - } - LOGGER.debug("exit from checkIfTasksMatchTransferCriteria()"); - } - - private void createTaskTransferredEvent(Task task, WorkbasketSummary oldWorkbasketSummary, - WorkbasketSummary newWorkbasketSummary) { - historyEventProducer.createEvent(new TransferredEvent(task, oldWorkbasketSummary, newWorkbasketSummary)); - } - - private void updateTasksToBeTransferred(List taskIds, - List taskSummaries, Workbasket destinationWorkbasket) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("entry to updateTasksToBeTransferred(taskIds = {}, taskSummaries = {})", - LoggerUtils.listToString(taskIds), LoggerUtils.listToString(taskSummaries), destinationWorkbasket); - } - - taskSummaries = taskSummaries.stream() + taskSummaries = + taskSummaries.stream() .filter(ts -> taskIds.contains(ts.getTaskId())) - .collect( - Collectors.toList()); - if (!taskSummaries.isEmpty()) { - Instant now = Instant.now(); - TaskSummaryImpl updateObject = new TaskSummaryImpl(); - updateObject.setRead(false); - updateObject.setTransferred(true); - updateObject.setWorkbasketSummary(destinationWorkbasket.asSummary()); - updateObject.setDomain(destinationWorkbasket.getDomain()); - updateObject.setModified(now); - updateObject.setState(TaskState.READY); - updateObject.setOwner(null); - taskMapper.updateTransfered(taskIds, updateObject); - if (HistoryEventProducer.isHistoryEnabled()) { - createTasksTransferredEvents(taskSummaries, updateObject); - } - } - LOGGER.debug("exit from updateTasksToBeTransferred()"); - } - - private void createTasksTransferredEvents(List taskSummaries, TaskSummaryImpl updateObject) { - taskSummaries.stream().forEach(task -> { - TaskImpl newTask = (TaskImpl) taskService.newTask(task.getWorkbasketId()); - newTask.setWorkbasketSummary(updateObject.getWorkbasketSummary()); - newTask.setRead(updateObject.isRead()); - newTask.setTransferred(updateObject.isTransferred()); - newTask.setWorkbasketSummary(updateObject.getWorkbasketSummary()); - newTask.setDomain(updateObject.getDomain()); - newTask.setModified(updateObject.getModified()); - newTask.setState(updateObject.getState()); - newTask.setOwner(updateObject.getOwner()); - createTaskTransferredEvent(newTask, newTask.getWorkbasketSummary(), - updateObject.getWorkbasketSummary()); - }); + .collect(Collectors.toList()); + if (!taskSummaries.isEmpty()) { + Instant now = Instant.now(); + TaskSummaryImpl updateObject = new TaskSummaryImpl(); + updateObject.setRead(false); + updateObject.setTransferred(true); + updateObject.setWorkbasketSummary(destinationWorkbasket.asSummary()); + updateObject.setDomain(destinationWorkbasket.getDomain()); + updateObject.setModified(now); + updateObject.setState(TaskState.READY); + updateObject.setOwner(null); + taskMapper.updateTransfered(taskIds, updateObject); + if (HistoryEventProducer.isHistoryEnabled()) { + createTasksTransferredEvents(taskSummaries, updateObject); + } } + LOGGER.debug("exit from updateTasksToBeTransferred()"); + } + private void createTasksTransferredEvents( + List taskSummaries, TaskSummaryImpl updateObject) { + taskSummaries.stream() + .forEach( + task -> { + TaskImpl newTask = (TaskImpl) taskService.newTask(task.getWorkbasketId()); + newTask.setWorkbasketSummary(updateObject.getWorkbasketSummary()); + newTask.setRead(updateObject.isRead()); + newTask.setTransferred(updateObject.isTransferred()); + newTask.setWorkbasketSummary(updateObject.getWorkbasketSummary()); + newTask.setDomain(updateObject.getDomain()); + newTask.setModified(updateObject.getModified()); + newTask.setState(updateObject.getState()); + newTask.setOwner(updateObject.getOwner()); + createTaskTransferredEvent( + newTask, newTask.getWorkbasketSummary(), updateObject.getWorkbasketSummary()); + }); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/TaskanaEngineImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/TaskanaEngineImpl.java index 0590c52cc..d027d001f 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/TaskanaEngineImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/TaskanaEngineImpl.java @@ -9,7 +9,6 @@ import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.function.Supplier; - import org.apache.ibatis.mapping.Environment; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSession; @@ -51,336 +50,343 @@ import pro.taskana.mappings.WorkbasketMapper; import pro.taskana.security.CurrentUserContext; import pro.taskana.taskrouting.TaskRoutingManager; -/** - * This is the implementation of TaskanaEngine. - */ +/** This is the implementation of TaskanaEngine. */ public class TaskanaEngineImpl implements TaskanaEngine { - private static final String DEFAULT = "default"; - private static final Logger LOGGER = LoggerFactory.getLogger(TaskanaEngineImpl.class); - private static SessionStack sessionStack = new SessionStack(); - protected TaskanaEngineConfiguration taskanaEngineConfiguration; - protected TransactionFactory transactionFactory; - protected SqlSessionManager sessionManager; - protected ConnectionManagementMode mode = ConnectionManagementMode.PARTICIPATE; - protected java.sql.Connection connection = null; - private HistoryEventProducer historyEventProducer; - private TaskRoutingManager taskRoutingManager; - private InternalTaskanaEngineImpl internalTaskanaEngineImpl; + private static final String DEFAULT = "default"; + private static final Logger LOGGER = LoggerFactory.getLogger(TaskanaEngineImpl.class); + private static SessionStack sessionStack = new SessionStack(); + protected TaskanaEngineConfiguration taskanaEngineConfiguration; + protected TransactionFactory transactionFactory; + protected SqlSessionManager sessionManager; + protected ConnectionManagementMode mode = ConnectionManagementMode.PARTICIPATE; + protected java.sql.Connection connection = null; + private HistoryEventProducer historyEventProducer; + private TaskRoutingManager taskRoutingManager; + private InternalTaskanaEngineImpl internalTaskanaEngineImpl; - protected TaskanaEngineImpl(TaskanaEngineConfiguration taskanaEngineConfiguration) { - this.taskanaEngineConfiguration = taskanaEngineConfiguration; - createTransactionFactory(taskanaEngineConfiguration.getUseManagedTransactions()); - this.sessionManager = createSqlSessionManager(); - historyEventProducer = HistoryEventProducer.getInstance(taskanaEngineConfiguration); - taskRoutingManager = TaskRoutingManager.getInstance(this); - this.internalTaskanaEngineImpl = new InternalTaskanaEngineImpl(); + protected TaskanaEngineImpl(TaskanaEngineConfiguration taskanaEngineConfiguration) { + this.taskanaEngineConfiguration = taskanaEngineConfiguration; + createTransactionFactory(taskanaEngineConfiguration.getUseManagedTransactions()); + this.sessionManager = createSqlSessionManager(); + historyEventProducer = HistoryEventProducer.getInstance(taskanaEngineConfiguration); + taskRoutingManager = TaskRoutingManager.getInstance(this); + this.internalTaskanaEngineImpl = new InternalTaskanaEngineImpl(); + } + + public static TaskanaEngine createTaskanaEngine( + TaskanaEngineConfiguration taskanaEngineConfiguration) { + return new TaskanaEngineImpl(taskanaEngineConfiguration); + } + + @Override + public TaskService getTaskService() { + SqlSession session = this.sessionManager; + return new TaskServiceImpl( + internalTaskanaEngineImpl, + session.getMapper(TaskMapper.class), + session.getMapper(AttachmentMapper.class)); + } + + @Override + public TaskMonitorService getTaskMonitorService() { + SqlSession session = this.sessionManager; + return new TaskMonitorServiceImpl( + internalTaskanaEngineImpl, session.getMapper(TaskMonitorMapper.class)); + } + + @Override + public WorkbasketService getWorkbasketService() { + SqlSession session = this.sessionManager; + return new WorkbasketServiceImpl( + internalTaskanaEngineImpl, + session.getMapper(WorkbasketMapper.class), + session.getMapper(DistributionTargetMapper.class), + session.getMapper(WorkbasketAccessMapper.class)); + } + + @Override + public ClassificationService getClassificationService() { + SqlSession session = this.sessionManager; + return new ClassificationServiceImpl( + internalTaskanaEngineImpl, + session.getMapper(ClassificationMapper.class), + session.getMapper(TaskMapper.class)); + } + + @Override + public JobService getJobService() { + SqlSession session = this.sessionManager; + return new JobServiceImpl(internalTaskanaEngineImpl, session.getMapper(JobMapper.class)); + } + + @Override + public TaskanaEngineConfiguration getConfiguration() { + return this.taskanaEngineConfiguration; + } + + @Override + public boolean isHistoryEnabled() { + return HistoryEventProducer.isHistoryEnabled(); + } + + @Override + public void setConnectionManagementMode(ConnectionManagementMode mode) { + if (this.mode == ConnectionManagementMode.EXPLICIT + && connection != null + && mode != ConnectionManagementMode.EXPLICIT) { + if (sessionManager.isManagedSessionStarted()) { + sessionManager.close(); + } + connection = null; + } + this.mode = mode; + } + + @Override + public void setConnection(java.sql.Connection connection) throws SQLException { + if (connection != null) { + this.connection = connection; + // disabling auto commit for passed connection in order to gain full control over the + // connection management + connection.setAutoCommit(false); + connection.setSchema(taskanaEngineConfiguration.getSchemaName()); + mode = ConnectionManagementMode.EXPLICIT; + sessionManager.startManagedSession(connection); + } else if (this.connection != null) { + closeConnection(); + } + } + + @Override + public void closeConnection() { + if (this.mode == ConnectionManagementMode.EXPLICIT) { + this.connection = null; + if (sessionManager.isManagedSessionStarted()) { + sessionManager.close(); + } + mode = ConnectionManagementMode.PARTICIPATE; + } + } + + @Override + public void checkRoleMembership(TaskanaRole... roles) throws NotAuthorizedException { + if (!isUserInRole(roles)) { + if (LOGGER.isDebugEnabled()) { + String accessIds = LoggerUtils.listToString(CurrentUserContext.getAccessIds()); + String rolesAsString = Arrays.toString(roles); + LOGGER.debug( + "Throwing NotAuthorizedException because accessIds {} are not member of roles {}", + accessIds, + rolesAsString); + } + throw new NotAuthorizedException( + "current user is not member of role(s) " + Arrays.toString(roles), + CurrentUserContext.getUserid()); + } + } + + @Override + public boolean isUserInRole(TaskanaRole... roles) { + if (!getConfiguration().isSecurityEnabled()) { + return true; } - public static TaskanaEngine createTaskanaEngine(TaskanaEngineConfiguration taskanaEngineConfiguration) { - return new TaskanaEngineImpl(taskanaEngineConfiguration); + List accessIds = CurrentUserContext.getAccessIds(); + Set rolesMembers = new HashSet<>(); + for (TaskanaRole role : roles) { + rolesMembers.addAll(getConfiguration().getRoleMap().get(role)); + } + for (String accessId : accessIds) { + if (rolesMembers.contains(accessId)) { + return true; + } + } + + return false; + } + + /** + * This method creates the sqlSessionManager of myBatis. It integrates all the SQL mappers and + * sets the databaseId attribute. + * + * @return a {@link SqlSessionFactory} + */ + protected SqlSessionManager createSqlSessionManager() { + Environment environment = + new Environment( + DEFAULT, this.transactionFactory, taskanaEngineConfiguration.getDatasource()); + Configuration configuration = new Configuration(environment); + + // set databaseId + String databaseProductName; + try (Connection con = taskanaEngineConfiguration.getDatasource().getConnection()) { + databaseProductName = con.getMetaData().getDatabaseProductName(); + String databaseProductId = DB.getDatabaseProductId(databaseProductName); + configuration.setDatabaseId(databaseProductId); + + } catch (SQLException e) { + throw new SystemException( + "Method createSqlSessionManager() could not open a connection to the database. No databaseId has been set.", + e.getCause()); + } + + // add mappers + configuration.addMapper(TaskMapper.class); + configuration.addMapper(TaskMonitorMapper.class); + configuration.addMapper(WorkbasketMapper.class); + configuration.addMapper(DistributionTargetMapper.class); + configuration.addMapper(ClassificationMapper.class); + configuration.addMapper(WorkbasketAccessMapper.class); + configuration.addMapper(ObjectReferenceMapper.class); + configuration.addMapper(QueryMapper.class); + configuration.addMapper(AttachmentMapper.class); + configuration.addMapper(JobMapper.class); + configuration.getTypeHandlerRegistry().register(MapTypeHandler.class); + SqlSessionFactory localSessionFactory = new SqlSessionFactoryBuilder().build(configuration); + return SqlSessionManager.newInstance(localSessionFactory); + } + + /** + * creates the MyBatis transaction factory. + * + * @param useManagedTransactions true, if managed transations should be used. Otherwise false. + */ + private void createTransactionFactory(boolean useManagedTransactions) { + if (useManagedTransactions) { + this.transactionFactory = new ManagedTransactionFactory(); + } else { + this.transactionFactory = new JdbcTransactionFactory(); + } + } + + /** + * With sessionStack, we maintain a Stack of SqlSessionManager objects on a per thread basis. + * SqlSessionManager is the MyBatis object that wraps database connections. The purpose of this + * stack is to keep track of nested calls. Each external API call is wrapped into + * taskanaEngineImpl.openConnection(); ..... taskanaEngineImpl.returnConnection(); calls. In order + * to avoid duplicate opening / closing of connections, we use the sessionStack in the following + * way: Each time, an openConnection call is received, we push the current sessionManager onto the + * stack. On the first call to openConnection, we call sessionManager.startManagedSession() to + * open a database connection. On each call to returnConnection() we pop one instance of + * sessionManager from the stack. When the stack becomes empty, we close the database connection + * by calling sessionManager.close(). + */ + private static class SessionStack { + + private ThreadLocal> sessionStack = new ThreadLocal<>(); + + /** @return Stack of SqlSessionManager */ + private Deque getSessionStack() { + Deque stack = sessionStack.get(); + if (stack == null) { + stack = new ArrayDeque<>(); + sessionStack.set(stack); + } + return stack; + } + + private SqlSessionManager getSessionFromStack() { + Deque stack = getSessionStack(); + if (stack.isEmpty()) { + return null; + } + return stack.peek(); + } + + private void pushSessionToStack(SqlSessionManager session) { + getSessionStack().push(session); + } + + private void popSessionFromStack() { + Deque stack = getSessionStack(); + if (!stack.isEmpty()) { + stack.pop(); + } + } + } + + /** Internal Engine for internal operations. */ + private class InternalTaskanaEngineImpl implements InternalTaskanaEngine { + + @Override + public void openConnection() { + initSqlSession(); + try { + sessionManager.getConnection().setSchema(taskanaEngineConfiguration.getSchemaName()); + } catch (SQLException e) { + throw new SystemException( + "Method openConnection() could not open a connection to the database. No schema has been created.", + e.getCause()); + } + if (mode != ConnectionManagementMode.EXPLICIT) { + sessionStack.pushSessionToStack(sessionManager); + } } @Override - public TaskService getTaskService() { - SqlSession session = this.sessionManager; - return new TaskServiceImpl(internalTaskanaEngineImpl, session.getMapper(TaskMapper.class), - session.getMapper(AttachmentMapper.class)); + public void initSqlSession() { + if (mode == ConnectionManagementMode.EXPLICIT && connection == null) { + throw new ConnectionNotSetException(); + } else if (mode != ConnectionManagementMode.EXPLICIT + && !sessionManager.isManagedSessionStarted()) { + sessionManager.startManagedSession(); + } } @Override - public TaskMonitorService getTaskMonitorService() { - SqlSession session = this.sessionManager; - return new TaskMonitorServiceImpl(internalTaskanaEngineImpl, - session.getMapper(TaskMonitorMapper.class)); - } - - @Override - public WorkbasketService getWorkbasketService() { - SqlSession session = this.sessionManager; - return new WorkbasketServiceImpl(internalTaskanaEngineImpl, - session.getMapper(WorkbasketMapper.class), - session.getMapper(DistributionTargetMapper.class), - session.getMapper(WorkbasketAccessMapper.class)); - } - - @Override - public ClassificationService getClassificationService() { - SqlSession session = this.sessionManager; - return new ClassificationServiceImpl(internalTaskanaEngineImpl, session.getMapper(ClassificationMapper.class), - session.getMapper(TaskMapper.class)); - } - - @Override - public JobService getJobService() { - SqlSession session = this.sessionManager; - return new JobServiceImpl(internalTaskanaEngineImpl, session.getMapper(JobMapper.class)); - } - - @Override - public TaskanaEngineConfiguration getConfiguration() { - return this.taskanaEngineConfiguration; - } - - @Override - public boolean isHistoryEnabled() { - return HistoryEventProducer.isHistoryEnabled(); - } - - @Override - public void setConnectionManagementMode(ConnectionManagementMode mode) { - if (this.mode == ConnectionManagementMode.EXPLICIT && connection != null - && mode != ConnectionManagementMode.EXPLICIT) { - if (sessionManager.isManagedSessionStarted()) { - sessionManager.close(); - } - connection = null; - } - this.mode = mode; - } - - @Override - public void setConnection(java.sql.Connection connection) throws SQLException { - if (connection != null) { - this.connection = connection; - // disabling auto commit for passed connection in order to gain full control over the connection management - connection.setAutoCommit(false); - connection.setSchema(taskanaEngineConfiguration.getSchemaName()); - mode = ConnectionManagementMode.EXPLICIT; - sessionManager.startManagedSession(connection); - } else if (this.connection != null) { - closeConnection(); - } - } - - @Override - public void closeConnection() { - if (this.mode == ConnectionManagementMode.EXPLICIT) { - this.connection = null; - if (sessionManager.isManagedSessionStarted()) { - sessionManager.close(); - } - mode = ConnectionManagementMode.PARTICIPATE; - } - } - - @Override - public void checkRoleMembership(TaskanaRole... roles) throws NotAuthorizedException { - if (!isUserInRole(roles)) { - if (LOGGER.isDebugEnabled()) { - String accessIds = LoggerUtils.listToString(CurrentUserContext.getAccessIds()); - String rolesAsString = Arrays.toString(roles); - LOGGER.debug("Throwing NotAuthorizedException because accessIds {} are not member of roles {}", - accessIds, - rolesAsString); - } - throw new NotAuthorizedException("current user is not member of role(s) " + Arrays.toString(roles), - CurrentUserContext.getUserid()); - } - } - - @Override - public boolean isUserInRole(TaskanaRole... roles) { - if (!getConfiguration().isSecurityEnabled()) { - return true; - } - - List accessIds = CurrentUserContext.getAccessIds(); - Set rolesMembers = new HashSet<>(); - for (TaskanaRole role : roles) { - rolesMembers.addAll(getConfiguration().getRoleMap().get(role)); - } - for (String accessId : accessIds) { - if (rolesMembers.contains(accessId)) { - return true; - } - } - - return false; - } - - /** - * This method creates the sqlSessionManager of myBatis. It integrates all the SQL mappers and sets the databaseId - * attribute. - * - * @return a {@link SqlSessionFactory} - */ - protected SqlSessionManager createSqlSessionManager() { - Environment environment = new Environment(DEFAULT, this.transactionFactory, - taskanaEngineConfiguration.getDatasource()); - Configuration configuration = new Configuration(environment); - - // set databaseId - String databaseProductName; - try (Connection con = taskanaEngineConfiguration.getDatasource().getConnection()) { - databaseProductName = con.getMetaData().getDatabaseProductName(); - String databaseProductId = DB.getDatabaseProductId(databaseProductName); - configuration.setDatabaseId(databaseProductId); - - } catch (SQLException e) { - throw new SystemException( - "Method createSqlSessionManager() could not open a connection to the database. No databaseId has been set.", - e.getCause()); - } - - // add mappers - configuration.addMapper(TaskMapper.class); - configuration.addMapper(TaskMonitorMapper.class); - configuration.addMapper(WorkbasketMapper.class); - configuration.addMapper(DistributionTargetMapper.class); - configuration.addMapper(ClassificationMapper.class); - configuration.addMapper(WorkbasketAccessMapper.class); - configuration.addMapper(ObjectReferenceMapper.class); - configuration.addMapper(QueryMapper.class); - configuration.addMapper(AttachmentMapper.class); - configuration.addMapper(JobMapper.class); - configuration.getTypeHandlerRegistry().register(MapTypeHandler.class); - SqlSessionFactory localSessionFactory = new SqlSessionFactoryBuilder().build(configuration); - return SqlSessionManager.newInstance(localSessionFactory); - } - - /** - * creates the MyBatis transaction factory. - * - * @param useManagedTransactions true, if managed transations should be used. Otherwise false. - */ - private void createTransactionFactory(boolean useManagedTransactions) { - if (useManagedTransactions) { - this.transactionFactory = new ManagedTransactionFactory(); - } else { - this.transactionFactory = new JdbcTransactionFactory(); - } - } - - /** - * Internal Engine for internal operations. - */ - private class InternalTaskanaEngineImpl implements InternalTaskanaEngine { - - @Override - public void openConnection() { - initSqlSession(); + public void returnConnection() { + if (mode != ConnectionManagementMode.EXPLICIT) { + sessionStack.popSessionFromStack(); + if (sessionStack.getSessionStack().isEmpty() + && sessionManager != null + && sessionManager.isManagedSessionStarted()) { + if (mode == ConnectionManagementMode.AUTOCOMMIT) { try { - sessionManager.getConnection().setSchema(taskanaEngineConfiguration.getSchemaName()); - } catch (SQLException e) { - throw new SystemException( - "Method openConnection() could not open a connection to the database. No schema has been created.", - e.getCause()); - } - if (mode != ConnectionManagementMode.EXPLICIT) { - sessionStack.pushSessionToStack(sessionManager); + sessionManager.commit(); + } catch (Exception e) { + throw new AutocommitFailedException(e.getCause()); } + } + sessionManager.close(); } - - @Override - public void initSqlSession() { - if (mode == ConnectionManagementMode.EXPLICIT && connection == null) { - throw new ConnectionNotSetException(); - } else if (mode != ConnectionManagementMode.EXPLICIT && !sessionManager.isManagedSessionStarted()) { - sessionManager.startManagedSession(); - } - } - - @Override - public void returnConnection() { - if (mode != ConnectionManagementMode.EXPLICIT) { - sessionStack.popSessionFromStack(); - if (sessionStack.getSessionStack().isEmpty() - && sessionManager != null && sessionManager.isManagedSessionStarted()) { - if (mode == ConnectionManagementMode.AUTOCOMMIT) { - try { - sessionManager.commit(); - } catch (Exception e) { - throw new AutocommitFailedException(e.getCause()); - } - } - sessionManager.close(); - } - } - } - - @Override - public T openAndReturnConnection(Supplier supplier) { - try { - openConnection(); - return supplier.get(); - } finally { - // will be called before return & in case of exceptions - returnConnection(); - } - } - - @Override - public boolean domainExists(String domain) { - return getConfiguration().getDomains().contains(domain); - } - - @Override - public SqlSession getSqlSession() { - return sessionManager; - } - - @Override - public TaskanaEngine getEngine() { - return TaskanaEngineImpl.this; - } - - @Override - public HistoryEventProducer getHistoryEventProducer() { - return historyEventProducer; - } - - @Override - public TaskRoutingManager getTaskRoutingManager() { - return taskRoutingManager; - } - + } } - /** - * With sessionStack, we maintain a Stack of SqlSessionManager objects on a per thread basis. SqlSessionManager is - * the MyBatis object that wraps database connections. The purpose of this stack is to keep track of nested calls. - * Each external API call is wrapped into taskanaEngineImpl.openConnection(); ..... - * taskanaEngineImpl.returnConnection(); calls. In order to avoid duplicate opening / closing of connections, we use - * the sessionStack in the following way: Each time, an openConnection call is received, we push the current - * sessionManager onto the stack. On the first call to openConnection, we call sessionManager.startManagedSession() - * to open a database connection. On each call to returnConnection() we pop one instance of sessionManager from the - * stack. When the stack becomes empty, we close the database connection by calling sessionManager.close(). - */ - private static class SessionStack { - - private ThreadLocal> sessionStack = new ThreadLocal<>(); - - /** - * - * @return Stack of SqlSessionManager - */ - private Deque getSessionStack() { - Deque stack = sessionStack.get(); - if (stack == null) { - stack = new ArrayDeque<>(); - sessionStack.set(stack); - } - return stack; - } - - private SqlSessionManager getSessionFromStack() { - Deque stack = getSessionStack(); - if (stack.isEmpty()) { - return null; - } - return stack.peek(); - } - - private void pushSessionToStack(SqlSessionManager session) { - getSessionStack().push(session); - } - - private void popSessionFromStack() { - Deque stack = getSessionStack(); - if (!stack.isEmpty()) { - stack.pop(); - } - } + @Override + public T openAndReturnConnection(Supplier supplier) { + try { + openConnection(); + return supplier.get(); + } finally { + // will be called before return & in case of exceptions + returnConnection(); + } } + + @Override + public boolean domainExists(String domain) { + return getConfiguration().getDomains().contains(domain); + } + + @Override + public SqlSession getSqlSession() { + return sessionManager; + } + + @Override + public TaskanaEngine getEngine() { + return TaskanaEngineImpl.this; + } + + @Override + public HistoryEventProducer getHistoryEventProducer() { + return historyEventProducer; + } + + @Override + public TaskRoutingManager getTaskRoutingManager() { + return taskRoutingManager; + } + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/TimeIntervalReportBuilderImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/TimeIntervalReportBuilderImpl.java index 4e07545e5..efd41879a 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/TimeIntervalReportBuilderImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/TimeIntervalReportBuilderImpl.java @@ -5,7 +5,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -23,169 +22,190 @@ import pro.taskana.report.TimeIntervalReportBuilder; /** * Implementation of {@link TimeIntervalReportBuilder}. + * * @param the true Builder behind this Interface * @param the true AgeQueryItem inside the Report * @param the column header */ -abstract class TimeIntervalReportBuilderImpl, I extends AgeQueryItem, H extends TimeIntervalColumnHeader> +abstract class TimeIntervalReportBuilderImpl< + B extends TimeIntervalReportBuilder, + I extends AgeQueryItem, + H extends TimeIntervalColumnHeader> implements TimeIntervalReportBuilder { - private static final Logger LOGGER = LoggerFactory.getLogger(TimeIntervalReportBuilder.class); + private static final Logger LOGGER = LoggerFactory.getLogger(TimeIntervalReportBuilder.class); - protected InternalTaskanaEngine taskanaEngine; - protected TaskMonitorMapper taskMonitorMapper; - protected List columnHeaders; - protected boolean inWorkingDays; - protected List workbasketIds; - protected List states; - protected List categories; - protected List domains; - protected List classificationIds; - protected List excludedClassificationIds; - protected Map customAttributeFilter; + protected InternalTaskanaEngine taskanaEngine; + protected TaskMonitorMapper taskMonitorMapper; + protected List columnHeaders; + protected boolean inWorkingDays; + protected List workbasketIds; + protected List states; + protected List categories; + protected List domains; + protected List classificationIds; + protected List excludedClassificationIds; + protected Map customAttributeFilter; - TimeIntervalReportBuilderImpl(InternalTaskanaEngine taskanaEngine, TaskMonitorMapper taskMonitorMapper) { - this.taskanaEngine = taskanaEngine; - this.taskMonitorMapper = taskMonitorMapper; - this.columnHeaders = Collections.emptyList(); - configureDaysToWorkingDaysConverter(); + TimeIntervalReportBuilderImpl( + InternalTaskanaEngine taskanaEngine, TaskMonitorMapper taskMonitorMapper) { + this.taskanaEngine = taskanaEngine; + this.taskMonitorMapper = taskMonitorMapper; + this.columnHeaders = Collections.emptyList(); + configureDaysToWorkingDaysConverter(); + } + + @Override + public B withColumnHeaders(List columnHeaders) { + this.columnHeaders = columnHeaders; + return _this(); + } + + @Override + public B inWorkingDays() { + this.inWorkingDays = true; + return _this(); + } + + @Override + public B workbasketIdIn(List workbasketIds) { + this.workbasketIds = new ArrayList<>(workbasketIds); + return _this(); + } + + @Override + public B stateIn(List states) { + this.states = new ArrayList<>(states); + return _this(); + } + + @Override + public B categoryIn(List categories) { + this.categories = new ArrayList<>(categories); + return _this(); + } + + @Override + public B classificationIdIn(List classificationIds) { + this.classificationIds = new ArrayList<>(classificationIds); + return _this(); + } + + @Override + public B excludedClassificationIdIn(List excludedClassificationIds) { + this.excludedClassificationIds = new ArrayList<>(excludedClassificationIds); + return _this(); + } + + @Override + public B domainIn(List domains) { + this.domains = new ArrayList<>(domains); + return _this(); + } + + @Override + public B customAttributeFilterIn(Map customAttributeFilter) { + this.customAttributeFilter = new HashMap<>(customAttributeFilter); + return _this(); + } + + @Override + public List listCustomAttributeValuesForCustomAttributeName(CustomField customField) + throws NotAuthorizedException { + LOGGER.debug( + "entry to listCustomAttributeValuesForCustomAttributeName(customField = {}), this = {}", + customField, + this); + this.taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.MONITOR); + try { + this.taskanaEngine.openConnection(); + return taskMonitorMapper.getCustomAttributeValuesForReport( + this.workbasketIds, + this.states, + this.categories, + this.domains, + this.classificationIds, + this.excludedClassificationIds, + this.customAttributeFilter, + customField); + } finally { + this.taskanaEngine.returnConnection(); + LOGGER.debug("exit from listCustomAttributeValuesForCustomAttributeName()."); + } + } + + @Override + public List listTaskIdsForSelectedItems(List selectedItems) + throws NotAuthorizedException, InvalidArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "entry to listTaskIdsForSelectedItems(selectedItems = {}), this = {}", + LoggerUtils.listToString(selectedItems), + this); } - protected abstract B _this(); - - @Override - public B withColumnHeaders(List columnHeaders) { - this.columnHeaders = columnHeaders; - return _this(); + this.taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.MONITOR); + try { + this.taskanaEngine.openConnection(); + if (this.columnHeaders == null) { + throw new InvalidArgumentException("ColumnHeader must not be null."); + } + if (selectedItems == null || selectedItems.isEmpty()) { + throw new InvalidArgumentException("SelectedItems must not be null or empty."); + } + boolean joinWithAttachments = subKeyIsSet(selectedItems); + if (!(this instanceof ClassificationReport.Builder) && joinWithAttachments) { + throw new InvalidArgumentException("SubKeys are supported for ClassificationReport only."); + } + if (this.inWorkingDays) { + selectedItems = convertWorkingDaysToDays(selectedItems, this.columnHeaders); + } + return this.taskMonitorMapper.getTaskIdsForSelectedItems( + this.workbasketIds, + this.states, + this.categories, + this.domains, + this.classificationIds, + this.excludedClassificationIds, + this.customAttributeFilter, + determineGroupedBy(), + selectedItems, + joinWithAttachments); + } finally { + this.taskanaEngine.returnConnection(); + LOGGER.debug("exit from listTaskIdsForSelectedItems()."); } + } - @Override - public B inWorkingDays() { - this.inWorkingDays = true; - return _this(); + protected abstract B _this(); + + protected abstract String determineGroupedBy(); + + private void configureDaysToWorkingDaysConverter() { + DaysToWorkingDaysConverter.setCustomHolidays( + this.taskanaEngine.getEngine().getConfiguration().getCustomHolidays()); + DaysToWorkingDaysConverter.setGermanPublicHolidaysEnabled( + this.taskanaEngine.getEngine().getConfiguration().isGermanPublicHolidaysEnabled()); + } + + private List convertWorkingDaysToDays( + List selectedItems, List columnHeaders) throws InvalidArgumentException { + DaysToWorkingDaysConverter instance = DaysToWorkingDaysConverter.initialize(columnHeaders); + for (SelectedItem selectedItem : selectedItems) { + selectedItem.setLowerAgeLimit( + Collections.min(instance.convertWorkingDaysToDays(selectedItem.getLowerAgeLimit()))); + selectedItem.setUpperAgeLimit( + Collections.max(instance.convertWorkingDaysToDays(selectedItem.getUpperAgeLimit()))); } + return selectedItems; + } - @Override - public B workbasketIdIn(List workbasketIds) { - this.workbasketIds = new ArrayList<>(workbasketIds); - return _this(); + private boolean subKeyIsSet(List selectedItems) { + for (SelectedItem selectedItem : selectedItems) { + if (selectedItem.getSubKey() != null && !selectedItem.getSubKey().isEmpty()) { + return true; + } } - - @Override - public B stateIn(List states) { - this.states = new ArrayList<>(states); - return _this(); - } - - @Override - public B categoryIn(List categories) { - this.categories = new ArrayList<>(categories); - return _this(); - } - - @Override - public B classificationIdIn(List classificationIds) { - this.classificationIds = new ArrayList<>(classificationIds); - return _this(); - } - - @Override - public B excludedClassificationIdIn(List excludedClassificationIds) { - this.excludedClassificationIds = new ArrayList<>(excludedClassificationIds); - return _this(); - } - - @Override - public B domainIn(List domains) { - this.domains = new ArrayList<>(domains); - return _this(); - } - - @Override - public B customAttributeFilterIn(Map customAttributeFilter) { - this.customAttributeFilter = new HashMap<>(customAttributeFilter); - return _this(); - } - - @Override - public List listCustomAttributeValuesForCustomAttributeName(CustomField customField) - throws NotAuthorizedException { - LOGGER.debug("entry to listCustomAttributeValuesForCustomAttributeName(customField = {}), this = {}", - customField, this); - this.taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.MONITOR); - try { - this.taskanaEngine.openConnection(); - return taskMonitorMapper.getCustomAttributeValuesForReport(this.workbasketIds, - this.states, this.categories, this.domains, this.classificationIds, this.excludedClassificationIds, - this.customAttributeFilter, customField); - } finally { - this.taskanaEngine.returnConnection(); - LOGGER.debug("exit from listCustomAttributeValuesForCustomAttributeName()."); - } - } - - @Override - public List listTaskIdsForSelectedItems(List selectedItems) - throws NotAuthorizedException, InvalidArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("entry to listTaskIdsForSelectedItems(selectedItems = {}), this = {}", - LoggerUtils.listToString(selectedItems), this); - } - - this.taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.MONITOR); - try { - this.taskanaEngine.openConnection(); - if (this.columnHeaders == null) { - throw new InvalidArgumentException("ColumnHeader must not be null."); - } - if (selectedItems == null || selectedItems.isEmpty()) { - throw new InvalidArgumentException("SelectedItems must not be null or empty."); - } - boolean joinWithAttachments = subKeyIsSet(selectedItems); - if (!(this instanceof ClassificationReport.Builder) && joinWithAttachments) { - throw new InvalidArgumentException("SubKeys are supported for ClassificationReport only."); - } - if (this.inWorkingDays) { - selectedItems = convertWorkingDaysToDays(selectedItems, this.columnHeaders); - } - return this.taskMonitorMapper.getTaskIdsForSelectedItems(this.workbasketIds, - this.states, this.categories, this.domains, this.classificationIds, this.excludedClassificationIds, - this.customAttributeFilter, determineGroupedBy(), selectedItems, joinWithAttachments); - } finally { - this.taskanaEngine.returnConnection(); - LOGGER.debug("exit from listTaskIdsForSelectedItems()."); - } - } - - protected abstract String determineGroupedBy(); - - private void configureDaysToWorkingDaysConverter() { - DaysToWorkingDaysConverter.setCustomHolidays( - this.taskanaEngine.getEngine().getConfiguration().getCustomHolidays()); - DaysToWorkingDaysConverter.setGermanPublicHolidaysEnabled( - this.taskanaEngine.getEngine().getConfiguration().isGermanPublicHolidaysEnabled()); - } - - private List convertWorkingDaysToDays(List selectedItems, - List columnHeaders) throws InvalidArgumentException { - DaysToWorkingDaysConverter instance = DaysToWorkingDaysConverter.initialize(columnHeaders); - for (SelectedItem selectedItem : selectedItems) { - selectedItem - .setLowerAgeLimit(Collections.min(instance.convertWorkingDaysToDays(selectedItem.getLowerAgeLimit()))); - selectedItem - .setUpperAgeLimit(Collections.max(instance.convertWorkingDaysToDays(selectedItem.getUpperAgeLimit()))); - } - return selectedItems; - } - - private boolean subKeyIsSet(List selectedItems) { - for (SelectedItem selectedItem : selectedItems) { - if (selectedItem.getSubKey() != null && !selectedItem.getSubKey().isEmpty()) { - return true; - } - } - return false; - } - + return false; + } } - diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/TimestampReportBuilderImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/TimestampReportBuilderImpl.java index f3d75b9cb..b3c346ff0 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/TimestampReportBuilderImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/TimestampReportBuilderImpl.java @@ -5,7 +5,6 @@ import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -20,73 +19,81 @@ import pro.taskana.mappings.TaskMonitorMapper; import pro.taskana.report.Timestamp; import pro.taskana.report.TimestampReport; -/** - * The implementation of {@link TimestampReport.Builder}. - */ -public class TimestampReportBuilderImpl extends - TimeIntervalReportBuilderImpl +/** The implementation of {@link TimestampReport.Builder}. */ +public class TimestampReportBuilderImpl + extends TimeIntervalReportBuilderImpl< + TimestampReport.Builder, TimestampQueryItem, TimeIntervalColumnHeader> implements TimestampReport.Builder { - private static final Logger LOGGER = LoggerFactory.getLogger(TimestampReport.Builder.class); - private List status = Arrays.asList(Timestamp.CREATED, Timestamp.COMPLETED); + private static final Logger LOGGER = LoggerFactory.getLogger(TimestampReport.Builder.class); + private List status = Arrays.asList(Timestamp.CREATED, Timestamp.COMPLETED); - TimestampReportBuilderImpl(InternalTaskanaEngine taskanaEngine, TaskMonitorMapper taskMonitorMapper) { - super(taskanaEngine, taskMonitorMapper); + TimestampReportBuilderImpl( + InternalTaskanaEngine taskanaEngine, TaskMonitorMapper taskMonitorMapper) { + super(taskanaEngine, taskMonitorMapper); + } + + @Override + public TimestampReport.Builder stateIn(List states) { + throw new UnsupportedOperationException( + "The states have no influence regarding this report. Use withTimestamps instead"); + } + + @Override + public List listTaskIdsForSelectedItems(List selectedItems) { + throw new UnsupportedOperationException(); + } + + @Override + public TimestampReport.Builder withTimestamps(List statuses) { + this.status = new ArrayList<>(statuses); + return _this(); + } + + @Override + public TimestampReport buildReport() throws NotAuthorizedException, InvalidArgumentException { + LOGGER.debug("entry to buildDetailedReport(), this = {}", this); + this.taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.MONITOR, TaskanaRole.ADMIN); + try { + this.taskanaEngine.openConnection(); + TimestampReport report = new TimestampReport(this.columnHeaders); + List items = + status.stream() + // This can also be implemented into a single sql query which combines all statuses + // with the union + // operator. That would reduce the readability of the sql template. That's why "the + // loop" is done + // outside of mybatis. + .map(this::getTasksCountForStatusGroupedByOrgLevel) + .flatMap(Collection::stream) + .collect(Collectors.toList()); + + report.addItems( + items, new DaysToWorkingDaysPreProcessor<>(this.columnHeaders, this.inWorkingDays)); + return report; + } finally { + this.taskanaEngine.returnConnection(); + LOGGER.debug("exit from buildDetailedReport()."); } + } - @Override - public TimestampReport.Builder stateIn(List states) { - throw new UnsupportedOperationException( - "The states have no influence regarding this report. Use withTimestamps instead"); - } + @Override + protected TimestampReport.Builder _this() { + return this; + } - @Override - protected TimestampReport.Builder _this() { - return this; - } + @Override + protected String determineGroupedBy() { + throw new UnsupportedOperationException(); + } - @Override - public List listTaskIdsForSelectedItems(List selectedItems) { - throw new UnsupportedOperationException(); - } - - @Override - protected String determineGroupedBy() { - throw new UnsupportedOperationException(); - } - - @Override - public TimestampReport.Builder withTimestamps(List statuses) { - this.status = new ArrayList<>(statuses); - return _this(); - } - - @Override - public TimestampReport buildReport() throws NotAuthorizedException, InvalidArgumentException { - LOGGER.debug("entry to buildDetailedReport(), this = {}", this); - this.taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.MONITOR, TaskanaRole.ADMIN); - try { - this.taskanaEngine.openConnection(); - TimestampReport report = new TimestampReport(this.columnHeaders); - List items = status.stream() - // This can also be implemented into a single sql query which combines all statuses with the union - // operator. That would reduce the readability of the sql template. That's why "the loop" is done - // outside of mybatis. - .map(this::getTasksCountForStatusGroupedByOrgLevel) - .flatMap(Collection::stream) - .collect(Collectors.toList()); - - report.addItems(items, - new DaysToWorkingDaysPreProcessor<>(this.columnHeaders, this.inWorkingDays)); - return report; - } finally { - this.taskanaEngine.returnConnection(); - LOGGER.debug("exit from buildDetailedReport()."); - } - } - - private List getTasksCountForStatusGroupedByOrgLevel(Timestamp s) { - return taskMonitorMapper.getTasksCountForStatusGroupedByOrgLevel(s, categories, classificationIds, - excludedClassificationIds, domains, customAttributeFilter); - } + private List getTasksCountForStatusGroupedByOrgLevel(Timestamp s) { + return taskMonitorMapper.getTasksCountForStatusGroupedByOrgLevel( + s, + categories, + classificationIds, + excludedClassificationIds, + domains, + customAttributeFilter); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketAccessItemImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketAccessItemImpl.java index df262ae0e..ddf9f9d98 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketAccessItemImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketAccessItemImpl.java @@ -3,572 +3,590 @@ package pro.taskana.impl; import pro.taskana.WorkbasketAccessItem; import pro.taskana.configuration.TaskanaEngineConfiguration; -/** - * WorkbasketAccessItemImpl Entity. - */ +/** WorkbasketAccessItemImpl Entity. */ public class WorkbasketAccessItemImpl implements WorkbasketAccessItem { - private String id; - private String workbasketId; - private String workbasketKey; - private String accessId; - private String accessName; - private boolean permRead; - private boolean permOpen; - private boolean permAppend; - private boolean permTransfer; - private boolean permDistribute; - private boolean permCustom1; - private boolean permCustom2; - private boolean permCustom3; - private boolean permCustom4; - private boolean permCustom5; - private boolean permCustom6; - private boolean permCustom7; - private boolean permCustom8; - private boolean permCustom9; - private boolean permCustom10; - private boolean permCustom11; - private boolean permCustom12; + private String id; + private String workbasketId; + private String workbasketKey; + private String accessId; + private String accessName; + private boolean permRead; + private boolean permOpen; + private boolean permAppend; + private boolean permTransfer; + private boolean permDistribute; + private boolean permCustom1; + private boolean permCustom2; + private boolean permCustom3; + private boolean permCustom4; + private boolean permCustom5; + private boolean permCustom6; + private boolean permCustom7; + private boolean permCustom8; + private boolean permCustom9; + private boolean permCustom10; + private boolean permCustom11; + private boolean permCustom12; - WorkbasketAccessItemImpl() { - super(); + WorkbasketAccessItemImpl() { + super(); + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#getId() + */ + @Override + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#getWorkbasketId() + */ + @Override + public String getWorkbasketId() { + return workbasketId; + } + + public void setWorkbasketId(String workbasketId) { + this.workbasketId = workbasketId; + } + + @Override + public String getWorkbasketKey() { + return workbasketKey; + } + + public void setWorkbasketKey(String workbasketKey) { + this.workbasketKey = workbasketKey; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#getAccessId() + */ + @Override + public String getAccessId() { + return accessId; + } + + public void setAccessId(String accessId) { + this.accessId = accessId; + } + + public void setAccessIdWithSanitizing(String accessId) { + if (TaskanaEngineConfiguration.shouldUseLowerCaseForAccessIds()) { + setAccessId(accessId != null ? accessId.toLowerCase() : null); + } else { + setAccessId(accessId); } + } - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#getId() - */ - @Override - public String getId() { - return id; + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#getAccessName() + */ + @Override + public String getAccessName() { + return accessName; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#setAccessName() + */ + @Override + public void setAccessName(String accessName) { + this.accessName = accessName; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#isPermRead() + */ + @Override + public boolean isPermRead() { + return permRead; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#setPermRead(boolean) + */ + @Override + public void setPermRead(boolean permRead) { + this.permRead = permRead; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#isPermOpen() + */ + @Override + public boolean isPermOpen() { + return permOpen; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#setPermOpen(boolean) + */ + @Override + public void setPermOpen(boolean permOpen) { + this.permOpen = permOpen; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#isPermAppend() + */ + @Override + public boolean isPermAppend() { + return permAppend; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#setPermAppend(boolean) + */ + @Override + public void setPermAppend(boolean permAppend) { + this.permAppend = permAppend; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#isPermTransfer() + */ + @Override + public boolean isPermTransfer() { + return permTransfer; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#setPermTransfer(boolean) + */ + @Override + public void setPermTransfer(boolean permTransfer) { + this.permTransfer = permTransfer; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#isPermDistribute() + */ + @Override + public boolean isPermDistribute() { + return permDistribute; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#setPermDistribute(boolean) + */ + @Override + public void setPermDistribute(boolean permDistribute) { + this.permDistribute = permDistribute; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#isPermCustom1() + */ + @Override + public boolean isPermCustom1() { + return permCustom1; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#setPermCustom1(boolean) + */ + @Override + public void setPermCustom1(boolean permCustom1) { + this.permCustom1 = permCustom1; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#isPermCustom2() + */ + @Override + public boolean isPermCustom2() { + return permCustom2; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#setPermCustom2(boolean) + */ + @Override + public void setPermCustom2(boolean permCustom2) { + this.permCustom2 = permCustom2; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#isPermCustom3() + */ + @Override + public boolean isPermCustom3() { + return permCustom3; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#setPermCustom3(boolean) + */ + @Override + public void setPermCustom3(boolean permCustom3) { + this.permCustom3 = permCustom3; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#isPermCustom4() + */ + @Override + public boolean isPermCustom4() { + return permCustom4; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#setPermCustom4(boolean) + */ + @Override + public void setPermCustom4(boolean permCustom4) { + this.permCustom4 = permCustom4; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#isPermCustom5() + */ + @Override + public boolean isPermCustom5() { + return permCustom5; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#setPermCustom5(boolean) + */ + @Override + public void setPermCustom5(boolean permCustom5) { + this.permCustom5 = permCustom5; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#isPermCustom6() + */ + @Override + public boolean isPermCustom6() { + return permCustom6; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#setPermCustom6(boolean) + */ + @Override + public void setPermCustom6(boolean permCustom6) { + this.permCustom6 = permCustom6; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#isPermCustom7() + */ + @Override + public boolean isPermCustom7() { + return permCustom7; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#setPermCustom7(boolean) + */ + @Override + public void setPermCustom7(boolean permCustom7) { + this.permCustom7 = permCustom7; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#isPermCustom8() + */ + @Override + public boolean isPermCustom8() { + return permCustom8; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#setPermCustom8(boolean) + */ + @Override + public void setPermCustom8(boolean permCustom8) { + this.permCustom8 = permCustom8; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#isPermCustom9() + */ + @Override + public boolean isPermCustom9() { + return permCustom9; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#setPermCustom9(boolean) + */ + @Override + public void setPermCustom9(boolean permCustom9) { + this.permCustom9 = permCustom9; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#isPermCustom10() + */ + @Override + public boolean isPermCustom10() { + return permCustom10; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#setPermCustom10(boolean) + */ + @Override + public void setPermCustom10(boolean permCustom10) { + this.permCustom10 = permCustom10; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#isPermCustom11() + */ + @Override + public boolean isPermCustom11() { + return permCustom11; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#setPermCustom11(boolean) + */ + @Override + public void setPermCustom11(boolean permCustom11) { + this.permCustom11 = permCustom11; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#isPermCustom12() + */ + @Override + public boolean isPermCustom12() { + return permCustom12; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketAccessItem#setPermCustom12(boolean) + */ + @Override + public void setPermCustom12(boolean permCustom12) { + this.permCustom12 = permCustom12; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((accessId == null) ? 0 : accessId.hashCode()); + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + (permAppend ? 1231 : 1237); + result = prime * result + (permCustom1 ? 1231 : 1237); + result = prime * result + (permCustom10 ? 1231 : 1237); + result = prime * result + (permCustom11 ? 1231 : 1237); + result = prime * result + (permCustom12 ? 1231 : 1237); + result = prime * result + (permCustom2 ? 1231 : 1237); + result = prime * result + (permCustom3 ? 1231 : 1237); + result = prime * result + (permCustom4 ? 1231 : 1237); + result = prime * result + (permCustom5 ? 1231 : 1237); + result = prime * result + (permCustom6 ? 1231 : 1237); + result = prime * result + (permCustom7 ? 1231 : 1237); + result = prime * result + (permCustom8 ? 1231 : 1237); + result = prime * result + (permCustom9 ? 1231 : 1237); + result = prime * result + (permDistribute ? 1231 : 1237); + result = prime * result + (permOpen ? 1231 : 1237); + result = prime * result + (permRead ? 1231 : 1237); + result = prime * result + (permTransfer ? 1231 : 1237); + result = prime * result + ((workbasketId == null) ? 0 : workbasketId.hashCode()); + result = prime * result + ((workbasketKey == null) ? 0 : workbasketKey.hashCode()); + result = prime * result + ((accessName == null) ? 0 : accessName.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; } - - public void setId(String id) { - this.id = id; + if (obj == null) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#getWorkbasketId() - */ - @Override - public String getWorkbasketId() { - return workbasketId; + if (!getClass().isAssignableFrom(obj.getClass())) { + return false; } - - public void setWorkbasketId(String workbasketId) { - this.workbasketId = workbasketId; + WorkbasketAccessItemImpl other = (WorkbasketAccessItemImpl) obj; + if (accessId == null) { + if (other.accessId != null) { + return false; + } + } else if (!accessId.equals(other.accessId)) { + return false; } - - @Override - public String getWorkbasketKey() { - return workbasketKey; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; } - - public void setWorkbasketKey(String workbasketKey) { - this.workbasketKey = workbasketKey; + if (permAppend != other.permAppend) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#getAccessId() - */ - @Override - public String getAccessId() { - return accessId; + if (permCustom1 != other.permCustom1) { + return false; } - - public void setAccessIdWithSanitizing(String accessId) { - if (TaskanaEngineConfiguration.shouldUseLowerCaseForAccessIds()) { - setAccessId(accessId != null ? accessId.toLowerCase() : null); - } else { - setAccessId(accessId); - } + if (permCustom10 != other.permCustom10) { + return false; } - - public void setAccessId(String accessId) { - this.accessId = accessId; + if (permCustom11 != other.permCustom11) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#getAccessName() - */ - @Override - public String getAccessName() { - return accessName; + if (permCustom12 != other.permCustom12) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#setAccessName() - */ - @Override - public void setAccessName(String accessName) { - this.accessName = accessName; + if (permCustom2 != other.permCustom2) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#isPermRead() - */ - @Override - public boolean isPermRead() { - return permRead; + if (permCustom3 != other.permCustom3) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#setPermRead(boolean) - */ - @Override - public void setPermRead(boolean permRead) { - this.permRead = permRead; + if (permCustom4 != other.permCustom4) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#isPermOpen() - */ - @Override - public boolean isPermOpen() { - return permOpen; + if (permCustom5 != other.permCustom5) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#setPermOpen(boolean) - */ - @Override - public void setPermOpen(boolean permOpen) { - this.permOpen = permOpen; + if (permCustom6 != other.permCustom6) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#isPermAppend() - */ - @Override - public boolean isPermAppend() { - return permAppend; + if (permCustom7 != other.permCustom7) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#setPermAppend(boolean) - */ - @Override - public void setPermAppend(boolean permAppend) { - this.permAppend = permAppend; + if (permCustom8 != other.permCustom8) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#isPermTransfer() - */ - @Override - public boolean isPermTransfer() { - return permTransfer; + if (permCustom9 != other.permCustom9) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#setPermTransfer(boolean) - */ - @Override - public void setPermTransfer(boolean permTransfer) { - this.permTransfer = permTransfer; + if (permDistribute != other.permDistribute) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#isPermDistribute() - */ - @Override - public boolean isPermDistribute() { - return permDistribute; + if (permOpen != other.permOpen) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#setPermDistribute(boolean) - */ - @Override - public void setPermDistribute(boolean permDistribute) { - this.permDistribute = permDistribute; + if (permRead != other.permRead) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#isPermCustom1() - */ - @Override - public boolean isPermCustom1() { - return permCustom1; + if (permTransfer != other.permTransfer) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#setPermCustom1(boolean) - */ - @Override - public void setPermCustom1(boolean permCustom1) { - this.permCustom1 = permCustom1; + if (workbasketId == null) { + if (other.workbasketId != null) { + return false; + } + } else if (!workbasketId.equals(other.workbasketId)) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#isPermCustom2() - */ - @Override - public boolean isPermCustom2() { - return permCustom2; + if (workbasketKey == null) { + if (other.workbasketKey != null) { + return false; + } + } else if (!workbasketKey.equals(other.workbasketKey)) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#setPermCustom2(boolean) - */ - @Override - public void setPermCustom2(boolean permCustom2) { - this.permCustom2 = permCustom2; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#isPermCustom3() - */ - @Override - public boolean isPermCustom3() { - return permCustom3; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#setPermCustom3(boolean) - */ - @Override - public void setPermCustom3(boolean permCustom3) { - this.permCustom3 = permCustom3; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#isPermCustom4() - */ - @Override - public boolean isPermCustom4() { - return permCustom4; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#setPermCustom4(boolean) - */ - @Override - public void setPermCustom4(boolean permCustom4) { - this.permCustom4 = permCustom4; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#isPermCustom5() - */ - @Override - public boolean isPermCustom5() { - return permCustom5; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#setPermCustom5(boolean) - */ - @Override - public void setPermCustom5(boolean permCustom5) { - this.permCustom5 = permCustom5; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#isPermCustom6() - */ - @Override - public boolean isPermCustom6() { - return permCustom6; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#setPermCustom6(boolean) - */ - @Override - public void setPermCustom6(boolean permCustom6) { - this.permCustom6 = permCustom6; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#isPermCustom7() - */ - @Override - public boolean isPermCustom7() { - return permCustom7; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#setPermCustom7(boolean) - */ - @Override - public void setPermCustom7(boolean permCustom7) { - this.permCustom7 = permCustom7; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#isPermCustom8() - */ - @Override - public boolean isPermCustom8() { - return permCustom8; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#setPermCustom8(boolean) - */ - @Override - public void setPermCustom8(boolean permCustom8) { - this.permCustom8 = permCustom8; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#isPermCustom9() - */ - @Override - public boolean isPermCustom9() { - return permCustom9; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#setPermCustom9(boolean) - */ - @Override - public void setPermCustom9(boolean permCustom9) { - this.permCustom9 = permCustom9; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#isPermCustom10() - */ - @Override - public boolean isPermCustom10() { - return permCustom10; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#setPermCustom10(boolean) - */ - @Override - public void setPermCustom10(boolean permCustom10) { - this.permCustom10 = permCustom10; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#isPermCustom11() - */ - @Override - public boolean isPermCustom11() { - return permCustom11; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#setPermCustom11(boolean) - */ - @Override - public void setPermCustom11(boolean permCustom11) { - this.permCustom11 = permCustom11; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#isPermCustom12() - */ - @Override - public boolean isPermCustom12() { - return permCustom12; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketAccessItem#setPermCustom12(boolean) - */ - @Override - public void setPermCustom12(boolean permCustom12) { - this.permCustom12 = permCustom12; - } - - @Override - public String toString() { - return "WorkbasketAccessItem [id=" + this.id - + ", workbasketId=" + this.workbasketId - + ", workbasketKey=" + this.workbasketKey - + ", accessId=" + this.accessId - + ", permRead=" + this.permRead - + ", permOpen=" + this.permOpen - + ", permAppend=" + this.permAppend - + ", permTransfer=" + this.permTransfer - + ", permDistribute=" + this.permDistribute - + ", permCustom1=" + this.permCustom1 - + ", permCustom2=" + this.permCustom2 - + ", permCustom3=" + this.permCustom3 - + ", permCustom4=" + this.permCustom4 - + ", permCustom5=" + this.permCustom5 - + ", permCustom6=" + this.permCustom6 - + ", permCustom7=" + this.permCustom7 - + ", permCustom8=" + this.permCustom8 - + ", permCustom9=" + this.permCustom9 - + ", permCustom10=" + this.permCustom10 - + ", permCustom11=" + this.permCustom11 - + ", permCustom12=" + this.permCustom12 - + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((accessId == null) ? 0 : accessId.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + (permAppend ? 1231 : 1237); - result = prime * result + (permCustom1 ? 1231 : 1237); - result = prime * result + (permCustom10 ? 1231 : 1237); - result = prime * result + (permCustom11 ? 1231 : 1237); - result = prime * result + (permCustom12 ? 1231 : 1237); - result = prime * result + (permCustom2 ? 1231 : 1237); - result = prime * result + (permCustom3 ? 1231 : 1237); - result = prime * result + (permCustom4 ? 1231 : 1237); - result = prime * result + (permCustom5 ? 1231 : 1237); - result = prime * result + (permCustom6 ? 1231 : 1237); - result = prime * result + (permCustom7 ? 1231 : 1237); - result = prime * result + (permCustom8 ? 1231 : 1237); - result = prime * result + (permCustom9 ? 1231 : 1237); - result = prime * result + (permDistribute ? 1231 : 1237); - result = prime * result + (permOpen ? 1231 : 1237); - result = prime * result + (permRead ? 1231 : 1237); - result = prime * result + (permTransfer ? 1231 : 1237); - result = prime * result + ((workbasketId == null) ? 0 : workbasketId.hashCode()); - result = prime * result + ((workbasketKey == null) ? 0 : workbasketKey.hashCode()); - result = prime * result + ((accessName == null) ? 0 : accessName.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!getClass().isAssignableFrom(obj.getClass())) { - return false; - } - WorkbasketAccessItemImpl other = (WorkbasketAccessItemImpl) obj; - if (accessId == null) { - if (other.accessId != null) { - return false; - } - } else if (!accessId.equals(other.accessId)) { - return false; - } - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (permAppend != other.permAppend) { - return false; - } - if (permCustom1 != other.permCustom1) { - return false; - } - if (permCustom10 != other.permCustom10) { - return false; - } - if (permCustom11 != other.permCustom11) { - return false; - } - if (permCustom12 != other.permCustom12) { - return false; - } - if (permCustom2 != other.permCustom2) { - return false; - } - if (permCustom3 != other.permCustom3) { - return false; - } - if (permCustom4 != other.permCustom4) { - return false; - } - if (permCustom5 != other.permCustom5) { - return false; - } - if (permCustom6 != other.permCustom6) { - return false; - } - if (permCustom7 != other.permCustom7) { - return false; - } - if (permCustom8 != other.permCustom8) { - return false; - } - if (permCustom9 != other.permCustom9) { - return false; - } - if (permDistribute != other.permDistribute) { - return false; - } - if (permOpen != other.permOpen) { - return false; - } - if (permRead != other.permRead) { - return false; - } - if (permTransfer != other.permTransfer) { - return false; - } - if (workbasketId == null) { - if (other.workbasketId != null) { - return false; - } - } else if (!workbasketId.equals(other.workbasketId)) { - return false; - } - if (workbasketKey == null) { - if (other.workbasketKey != null) { - return false; - } - } else if (!workbasketKey.equals(other.workbasketKey)) { - return false; - } - if (accessName == null) { - if (other.accessName != null) { - return false; - } - } else if (!accessName.equals(other.accessName)) { - return false; - } - return true; + if (accessName == null) { + if (other.accessName != null) { + return false; + } + } else if (!accessName.equals(other.accessName)) { + return false; } + return true; + } + @Override + public String toString() { + return "WorkbasketAccessItem [id=" + + this.id + + ", workbasketId=" + + this.workbasketId + + ", workbasketKey=" + + this.workbasketKey + + ", accessId=" + + this.accessId + + ", permRead=" + + this.permRead + + ", permOpen=" + + this.permOpen + + ", permAppend=" + + this.permAppend + + ", permTransfer=" + + this.permTransfer + + ", permDistribute=" + + this.permDistribute + + ", permCustom1=" + + this.permCustom1 + + ", permCustom2=" + + this.permCustom2 + + ", permCustom3=" + + this.permCustom3 + + ", permCustom4=" + + this.permCustom4 + + ", permCustom5=" + + this.permCustom5 + + ", permCustom6=" + + this.permCustom6 + + ", permCustom7=" + + this.permCustom7 + + ", permCustom8=" + + this.permCustom8 + + ", permCustom9=" + + this.permCustom9 + + ", permCustom10=" + + this.permCustom10 + + ", permCustom11=" + + this.permCustom11 + + ", permCustom12=" + + this.permCustom12 + + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketAccessItemQueryImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketAccessItemQueryImpl.java index 6c3e95fb1..ffa430917 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketAccessItemQueryImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketAccessItemQueryImpl.java @@ -3,7 +3,6 @@ package pro.taskana.impl; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import org.apache.ibatis.exceptions.PersistenceException; import org.apache.ibatis.session.RowBounds; import org.slf4j.Logger; @@ -15,228 +14,247 @@ import pro.taskana.WorkbasketAccessItemQuery; import pro.taskana.exceptions.TaskanaRuntimeException; import pro.taskana.impl.util.LoggerUtils; -/** - * WorkbasketAccessItemQueryImpl for generating dynamic SQL. - */ +/** WorkbasketAccessItemQueryImpl for generating dynamic SQL. */ public class WorkbasketAccessItemQueryImpl implements WorkbasketAccessItemQuery { - private static final String LINK_TO_MAPPER = "pro.taskana.mappings.QueryMapper.queryWorkbasketAccessItems"; - private static final String LINK_TO_COUNTER = "pro.taskana.mappings.QueryMapper.countQueryWorkbasketAccessItems"; - private static final String LINK_TO_VALUEMAPPER = "pro.taskana.mappings.QueryMapper.queryWorkbasketAccessItemColumnValues"; - private static final Logger LOGGER = LoggerFactory.getLogger(WorkbasketQueryImpl.class); - private AccessItemQueryColumnName columnName; - private String[] accessIdIn; - private String[] accessIdLike; - private String[] workbasketIdIn; - private String[] workbasketKeyIn; - private String[] workbasketKeyLike; - private String[] idIn; + private static final String LINK_TO_MAPPER = + "pro.taskana.mappings.QueryMapper.queryWorkbasketAccessItems"; + private static final String LINK_TO_COUNTER = + "pro.taskana.mappings.QueryMapper.countQueryWorkbasketAccessItems"; + private static final String LINK_TO_VALUEMAPPER = + "pro.taskana.mappings.QueryMapper.queryWorkbasketAccessItemColumnValues"; + private static final Logger LOGGER = LoggerFactory.getLogger(WorkbasketQueryImpl.class); + private AccessItemQueryColumnName columnName; + private String[] accessIdIn; + private String[] accessIdLike; + private String[] workbasketIdIn; + private String[] workbasketKeyIn; + private String[] workbasketKeyLike; + private String[] idIn; - private InternalTaskanaEngine taskanaEngine; - private List orderBy; - private List orderColumns; + private InternalTaskanaEngine taskanaEngine; + private List orderBy; + private List orderColumns; - WorkbasketAccessItemQueryImpl(InternalTaskanaEngine taskanaEngine) { - this.taskanaEngine = taskanaEngine; - orderBy = new ArrayList<>(); - orderColumns = new ArrayList<>(); - } + WorkbasketAccessItemQueryImpl(InternalTaskanaEngine taskanaEngine) { + this.taskanaEngine = taskanaEngine; + orderBy = new ArrayList<>(); + orderColumns = new ArrayList<>(); + } - @Override - public WorkbasketAccessItemQuery idIn(String... ids) { - this.idIn = ids; - return this; - } + @Override + public WorkbasketAccessItemQuery idIn(String... ids) { + this.idIn = ids; + return this; + } - @Override - public WorkbasketAccessItemQuery workbasketIdIn(String... id) { - this.workbasketIdIn = id; - return this; - } + @Override + public WorkbasketAccessItemQuery workbasketIdIn(String... id) { + this.workbasketIdIn = id; + return this; + } - @Override - public WorkbasketAccessItemQuery workbasketKeyIn(String... keys) { - this.workbasketKeyIn = keys; - return this; - } + @Override + public WorkbasketAccessItemQuery workbasketKeyIn(String... keys) { + this.workbasketKeyIn = keys; + return this; + } - @Override - public WorkbasketAccessItemQuery workbasketKeyLike(String... key) { - this.workbasketKeyLike = toUpperCopy(key); - return this; - } + @Override + public WorkbasketAccessItemQuery workbasketKeyLike(String... key) { + this.workbasketKeyLike = toUpperCopy(key); + return this; + } - @Override - public WorkbasketAccessItemQuery accessIdIn(String... accessId) { - this.accessIdIn = accessId; - WorkbasketQueryImpl.lowercaseAccessIds(this.accessIdIn); - return this; - } + @Override + public WorkbasketAccessItemQuery accessIdIn(String... accessId) { + this.accessIdIn = accessId; + WorkbasketQueryImpl.lowercaseAccessIds(this.accessIdIn); + return this; + } - @Override - public WorkbasketAccessItemQuery accessIdLike(String... ids) { - this.accessIdLike = toUpperCopy(ids); - return this; - } + @Override + public WorkbasketAccessItemQuery accessIdLike(String... ids) { + this.accessIdLike = toUpperCopy(ids); + return this; + } - @Override - public WorkbasketAccessItemQuery orderById(SortDirection sortDirection) { - return addOrderCriteria("ID", sortDirection); - } + @Override + public WorkbasketAccessItemQuery orderById(SortDirection sortDirection) { + return addOrderCriteria("ID", sortDirection); + } - @Override - public WorkbasketAccessItemQuery orderByWorkbasketId(SortDirection sortDirection) { - return addOrderCriteria("WORKBASKET_ID", sortDirection); - } + @Override + public WorkbasketAccessItemQuery orderByWorkbasketId(SortDirection sortDirection) { + return addOrderCriteria("WORKBASKET_ID", sortDirection); + } - @Override - public WorkbasketAccessItemQuery orderByWorkbasketKey(SortDirection sortDirection) { - return addOrderCriteria("WB.KEY", sortDirection); - } + @Override + public WorkbasketAccessItemQuery orderByWorkbasketKey(SortDirection sortDirection) { + return addOrderCriteria("WB.KEY", sortDirection); + } - @Override - public WorkbasketAccessItemQuery orderByAccessId(SortDirection sortDirection) { - return addOrderCriteria("ACCESS_ID", sortDirection); - } + @Override + public WorkbasketAccessItemQuery orderByAccessId(SortDirection sortDirection) { + return addOrderCriteria("ACCESS_ID", sortDirection); + } - @Override - public List list() { - LOGGER.debug("entry to list(), this = {}", this); - List result = taskanaEngine.openAndReturnConnection( + @Override + public List list() { + LOGGER.debug("entry to list(), this = {}", this); + List result = + taskanaEngine.openAndReturnConnection( () -> new ArrayList<>(taskanaEngine.getSqlSession().selectList(LINK_TO_MAPPER, this))); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("exit from list(). Returning {} resulting Objects: {} ", result.size(), - LoggerUtils.listToString(result)); - } - return result; + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "exit from list(). Returning {} resulting Objects: {} ", + result.size(), + LoggerUtils.listToString(result)); } + return result; + } - @Override - public List listValues(AccessItemQueryColumnName columnName, SortDirection sortDirection) { - LOGGER.debug("Entry to listValues(dbColumnName={}) this = {}", columnName, this); - List result = null; - try { - taskanaEngine.openConnection(); - this.columnName = columnName; - this.orderBy.clear(); - this.addOrderCriteria(columnName.toString(), sortDirection); - result = taskanaEngine.getSqlSession().selectList(LINK_TO_VALUEMAPPER, this); - return result; - } finally { - taskanaEngine.returnConnection(); - if (LOGGER.isDebugEnabled()) { - int numberOfResultObjects = result == null ? 0 : result.size(); - LOGGER.debug("Exit from listValues. Returning {} resulting Objects: {} ", numberOfResultObjects, - LoggerUtils.listToString(result)); - } - } + @Override + public List listValues( + AccessItemQueryColumnName columnName, SortDirection sortDirection) { + LOGGER.debug("Entry to listValues(dbColumnName={}) this = {}", columnName, this); + List result = null; + try { + taskanaEngine.openConnection(); + this.columnName = columnName; + this.orderBy.clear(); + this.addOrderCriteria(columnName.toString(), sortDirection); + result = taskanaEngine.getSqlSession().selectList(LINK_TO_VALUEMAPPER, this); + return result; + } finally { + taskanaEngine.returnConnection(); + if (LOGGER.isDebugEnabled()) { + int numberOfResultObjects = result == null ? 0 : result.size(); + LOGGER.debug( + "Exit from listValues. Returning {} resulting Objects: {} ", + numberOfResultObjects, + LoggerUtils.listToString(result)); + } } + } - @Override - public List list(int offset, int limit) { - LOGGER.debug("entry to list(offset = {}, limit = {}), this = {}", offset, limit, this); - List result = new ArrayList<>(); - try { - taskanaEngine.openConnection(); - RowBounds rowBounds = new RowBounds(offset, limit); - List foundAccessItms = taskanaEngine.getSqlSession() - .selectList(LINK_TO_MAPPER, this, rowBounds); - result.addAll(foundAccessItms); - return result; - } catch (PersistenceException e) { - if (e.getMessage().contains("ERRORCODE=-4470")) { - TaskanaRuntimeException ex = new TaskanaRuntimeException( - "The offset beginning was set over the amount of result-rows.", e.getCause()); - ex.setStackTrace(e.getStackTrace()); - throw ex; - } - throw e; - } finally { - taskanaEngine.returnConnection(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("exit from list(offset,limit). Returning {} resulting Objects: {} ", result.size(), - LoggerUtils.listToString(result)); - } - } + @Override + public List list(int offset, int limit) { + LOGGER.debug("entry to list(offset = {}, limit = {}), this = {}", offset, limit, this); + List result = new ArrayList<>(); + try { + taskanaEngine.openConnection(); + RowBounds rowBounds = new RowBounds(offset, limit); + List foundAccessItms = + taskanaEngine.getSqlSession().selectList(LINK_TO_MAPPER, this, rowBounds); + result.addAll(foundAccessItms); + return result; + } catch (PersistenceException e) { + if (e.getMessage().contains("ERRORCODE=-4470")) { + TaskanaRuntimeException ex = + new TaskanaRuntimeException( + "The offset beginning was set over the amount of result-rows.", e.getCause()); + ex.setStackTrace(e.getStackTrace()); + throw ex; + } + throw e; + } finally { + taskanaEngine.returnConnection(); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "exit from list(offset,limit). Returning {} resulting Objects: {} ", + result.size(), + LoggerUtils.listToString(result)); + } } + } - @Override - public WorkbasketAccessItem single() { - LOGGER.debug("entry to single(), this = {}", this); - WorkbasketAccessItem accessItm = null; - try { - taskanaEngine.openConnection(); - accessItm = taskanaEngine.getSqlSession().selectOne(LINK_TO_MAPPER, this); - return accessItm; - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from single(). Returning result {} ", accessItm); - } + @Override + public WorkbasketAccessItem single() { + LOGGER.debug("entry to single(), this = {}", this); + WorkbasketAccessItem accessItm = null; + try { + taskanaEngine.openConnection(); + accessItm = taskanaEngine.getSqlSession().selectOne(LINK_TO_MAPPER, this); + return accessItm; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from single(). Returning result {} ", accessItm); } + } - @Override - public long count() { - LOGGER.debug("entry to count(), this = {}", this); - Long rowCount = null; - try { - taskanaEngine.openConnection(); - rowCount = taskanaEngine.getSqlSession().selectOne(LINK_TO_COUNTER, this); - return (rowCount == null) ? 0L : rowCount; - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from count(). Returning result {} ", rowCount); - } + @Override + public long count() { + LOGGER.debug("entry to count(), this = {}", this); + Long rowCount = null; + try { + taskanaEngine.openConnection(); + rowCount = taskanaEngine.getSqlSession().selectOne(LINK_TO_COUNTER, this); + return (rowCount == null) ? 0L : rowCount; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from count(). Returning result {} ", rowCount); } + } - private WorkbasketAccessItemQuery addOrderCriteria(String colName, SortDirection sortDirection) { - String orderByDirection = - " " + (sortDirection == null ? SortDirection.ASCENDING.toString() : sortDirection.toString()); - orderBy.add(colName + orderByDirection); - orderColumns.add(colName); - return this; - } + public String[] getIdIn() { + return this.idIn; + } - public String[] getIdIn() { - return this.idIn; - } + public String[] getAccessIdIn() { + return accessIdIn; + } - public String[] getAccessIdIn() { - return accessIdIn; - } + public String[] getAccessIdLike() { + return accessIdLike; + } - public String[] getAccessIdLike() { - return accessIdLike; - } + public String[] getWorkbasketIdIn() { + return workbasketIdIn; + } - public String[] getWorkbasketIdIn() { - return workbasketIdIn; - } + public List getOrderBy() { + return orderBy; + } - public List getOrderBy() { - return orderBy; - } + public List getOrderColumns() { + return orderColumns; + } - public List getOrderColumns() { - return orderColumns; - } + public AccessItemQueryColumnName getColumnName() { + return columnName; + } - public AccessItemQueryColumnName getColumnName() { - return columnName; - } + public String[] getWorkbasketKeyIn() { + return workbasketKeyIn; + } - public String[] getWorkbasketKeyIn() { - return workbasketKeyIn; - } + public String[] getWorkbasketKeyLike() { + return workbasketKeyLike; + } - public String[] getWorkbasketKeyLike() { - return workbasketKeyLike; - } - - @Override - public String toString() { - return "WorkbasketAccessItemQueryImpl [" + "idIn=" + Arrays.toString(this.idIn) + ", accessIdIn=" - + Arrays.toString(this.accessIdIn) + ", workbasketIdIn=" + Arrays.toString(this.workbasketIdIn) - + ", orderBy=" + this.orderBy + "]"; - } + private WorkbasketAccessItemQuery addOrderCriteria(String colName, SortDirection sortDirection) { + String orderByDirection = + " " + + (sortDirection == null + ? SortDirection.ASCENDING.toString() + : sortDirection.toString()); + orderBy.add(colName + orderByDirection); + orderColumns.add(colName); + return this; + } + @Override + public String toString() { + return "WorkbasketAccessItemQueryImpl [" + + "idIn=" + + Arrays.toString(this.idIn) + + ", accessIdIn=" + + Arrays.toString(this.accessIdIn) + + ", workbasketIdIn=" + + Arrays.toString(this.workbasketIdIn) + + ", orderBy=" + + this.orderBy + + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketImpl.java index 200be9422..ba521e6ad 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketImpl.java @@ -6,396 +6,424 @@ import pro.taskana.Workbasket; import pro.taskana.WorkbasketSummary; import pro.taskana.WorkbasketType; -/** - * Workbasket entity. - */ +/** Workbasket entity. */ public class WorkbasketImpl implements Workbasket { - private String id; - private String key; - private Instant created; - private Instant modified; - private String name; - private String description; - private String owner; - private String domain; - private WorkbasketType type; - private String custom1; - private String custom2; - private String custom3; - private String custom4; - private String orgLevel1; - private String orgLevel2; - private String orgLevel3; - private String orgLevel4; - private boolean markedForDeletion; + private String id; + private String key; + private Instant created; + private Instant modified; + private String name; + private String description; + private String owner; + private String domain; + private WorkbasketType type; + private String custom1; + private String custom2; + private String custom3; + private String custom4; + private String orgLevel1; + private String orgLevel2; + private String orgLevel3; + private String orgLevel4; + private boolean markedForDeletion; - WorkbasketImpl() { + WorkbasketImpl() {} + + @Override + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @Override + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + @Override + public Instant getCreated() { + return created; + } + + public void setCreated(Instant created) { + this.created = created; + } + + @Override + public Instant getModified() { + return modified; + } + + public void setModified(Instant modified) { + this.modified = modified; + } + + @Override + public String getName() { + return name; + } + + @Override + public void setName(String name) { + this.name = name; + } + + @Override + public String getDescription() { + return description; + } + + @Override + public void setDescription(String description) { + this.description = description; + } + + @Override + public String getOwner() { + return owner; + } + + @Override + public void setOwner(String owner) { + this.owner = owner; + } + + @Override + public String getDomain() { + return domain; + } + + public void setDomain(String domain) { + this.domain = domain; + } + + @Override + public WorkbasketType getType() { + return type; + } + + @Override + public void setType(WorkbasketType type) { + this.type = type; + } + + @Override + public String getCustom1() { + return custom1; + } + + @Override + public void setCustom1(String custom1) { + this.custom1 = custom1; + } + + @Override + public String getCustom2() { + return custom2; + } + + @Override + public void setCustom2(String custom2) { + this.custom2 = custom2; + } + + @Override + public String getCustom3() { + return custom3; + } + + @Override + public void setCustom3(String custom3) { + this.custom3 = custom3; + } + + @Override + public String getCustom4() { + return custom4; + } + + @Override + public void setCustom4(String custom4) { + this.custom4 = custom4; + } + + @Override + public String getOrgLevel1() { + return orgLevel1; + } + + @Override + public void setOrgLevel1(String orgLevel1) { + this.orgLevel1 = orgLevel1; + } + + @Override + public String getOrgLevel2() { + return orgLevel2; + } + + @Override + public void setOrgLevel2(String orgLevel2) { + this.orgLevel2 = orgLevel2; + } + + @Override + public String getOrgLevel3() { + return orgLevel3; + } + + @Override + public void setOrgLevel3(String orgLevel3) { + this.orgLevel3 = orgLevel3; + } + + @Override + public String getOrgLevel4() { + return orgLevel4; + } + + @Override + public void setOrgLevel4(String orgLevel4) { + this.orgLevel4 = orgLevel4; + } + + @Override + public boolean isMarkedForDeletion() { + return markedForDeletion; + } + + @Override + public void setMarkedForDeletion(boolean markedForDeletion) { + this.markedForDeletion = markedForDeletion; + } + + @Override + public WorkbasketSummary asSummary() { + WorkbasketSummaryImpl result = new WorkbasketSummaryImpl(); + result.setId(this.getId()); + result.setKey(this.getKey()); + result.setName(this.getName()); + result.setDescription(this.getDescription()); + result.setOwner(this.getOwner()); + result.setDomain(this.getDomain()); + result.setType(this.getType()); + result.setCustom1(this.getCustom1()); + result.setCustom2(this.getCustom2()); + result.setCustom3(this.getCustom3()); + result.setCustom4(this.getCustom4()); + result.setOrgLevel1(this.getOrgLevel1()); + result.setOrgLevel2(this.getOrgLevel2()); + result.setOrgLevel3(this.getOrgLevel3()); + result.setOrgLevel4(this.getOrgLevel4()); + result.setMarkedForDeletion(this.isMarkedForDeletion()); + return result; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((created == null) ? 0 : created.hashCode()); + result = prime * result + ((custom1 == null) ? 0 : custom1.hashCode()); + result = prime * result + ((custom2 == null) ? 0 : custom2.hashCode()); + result = prime * result + ((custom3 == null) ? 0 : custom3.hashCode()); + result = prime * result + ((custom4 == null) ? 0 : custom4.hashCode()); + result = prime * result + ((description == null) ? 0 : description.hashCode()); + result = prime * result + ((domain == null) ? 0 : domain.hashCode()); + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((key == null) ? 0 : key.hashCode()); + result = prime * result + (markedForDeletion ? 1231 : 1237); + result = prime * result + ((modified == null) ? 0 : modified.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((orgLevel1 == null) ? 0 : orgLevel1.hashCode()); + result = prime * result + ((orgLevel2 == null) ? 0 : orgLevel2.hashCode()); + result = prime * result + ((orgLevel3 == null) ? 0 : orgLevel3.hashCode()); + result = prime * result + ((orgLevel4 == null) ? 0 : orgLevel4.hashCode()); + result = prime * result + ((owner == null) ? 0 : owner.hashCode()); + result = prime * result + ((type == null) ? 0 : type.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; } - @Override - public String getId() { - return id; + if (!getClass().isAssignableFrom(obj.getClass())) { + return false; } - - public void setId(String id) { - this.id = id; + WorkbasketImpl other = (WorkbasketImpl) obj; + if (created == null) { + if (other.created != null) { + return false; + } + } else if (!created.equals(other.created)) { + return false; } - - @Override - public String getKey() { - return key; + if (custom1 == null) { + if (other.custom1 != null) { + return false; + } + } else if (!custom1.equals(other.custom1)) { + return false; } - - public void setKey(String key) { - this.key = key; + if (custom2 == null) { + if (other.custom2 != null) { + return false; + } + } else if (!custom2.equals(other.custom2)) { + return false; } - - @Override - public Instant getCreated() { - return created; + if (custom3 == null) { + if (other.custom3 != null) { + return false; + } + } else if (!custom3.equals(other.custom3)) { + return false; } - - public void setCreated(Instant created) { - this.created = created; + if (custom4 == null) { + if (other.custom4 != null) { + return false; + } + } else if (!custom4.equals(other.custom4)) { + return false; } - - @Override - public Instant getModified() { - return modified; + if (description == null) { + if (other.description != null) { + return false; + } + } else if (!description.equals(other.description)) { + return false; } - - public void setModified(Instant modified) { - this.modified = modified; + if (domain == null) { + if (other.domain != null) { + return false; + } + } else if (!domain.equals(other.domain)) { + return false; } - - @Override - public String getName() { - return name; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; } - - @Override - public void setName(String name) { - this.name = name; + if (key == null) { + if (other.key != null) { + return false; + } + } else if (!key.equals(other.key)) { + return false; } - - @Override - public String getDescription() { - return description; + if (markedForDeletion != other.markedForDeletion) { + return false; } - - @Override - public void setDescription(String description) { - this.description = description; + if (modified == null) { + if (other.modified != null) { + return false; + } + } else if (!modified.equals(other.modified)) { + return false; } - - @Override - public String getOwner() { - return owner; + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; } - - @Override - public void setOwner(String owner) { - this.owner = owner; + if (orgLevel1 == null) { + if (other.orgLevel1 != null) { + return false; + } + } else if (!orgLevel1.equals(other.orgLevel1)) { + return false; } - - @Override - public String getDomain() { - return domain; + if (orgLevel2 == null) { + if (other.orgLevel2 != null) { + return false; + } + } else if (!orgLevel2.equals(other.orgLevel2)) { + return false; } - - @Override - public WorkbasketType getType() { - return type; + if (orgLevel3 == null) { + if (other.orgLevel3 != null) { + return false; + } + } else if (!orgLevel3.equals(other.orgLevel3)) { + return false; } - - @Override - public void setType(WorkbasketType type) { - this.type = type; + if (orgLevel4 == null) { + if (other.orgLevel4 != null) { + return false; + } + } else if (!orgLevel4.equals(other.orgLevel4)) { + return false; } - - @Override - public String getCustom1() { - return custom1; + if (owner == null) { + if (other.owner != null) { + return false; + } + } else if (!owner.equals(other.owner)) { + return false; } - - @Override - public void setCustom1(String custom1) { - this.custom1 = custom1; - } - - @Override - public String getCustom2() { - return custom2; - } - - @Override - public void setCustom2(String custom2) { - this.custom2 = custom2; - } - - @Override - public String getCustom3() { - return custom3; - } - - @Override - public void setCustom3(String custom3) { - this.custom3 = custom3; - } - - @Override - public String getCustom4() { - return custom4; - } - - @Override - public void setCustom4(String custom4) { - this.custom4 = custom4; - } - - @Override - public String getOrgLevel1() { - return orgLevel1; - } - - @Override - public void setOrgLevel1(String orgLevel1) { - this.orgLevel1 = orgLevel1; - } - - @Override - public String getOrgLevel2() { - return orgLevel2; - } - - @Override - public void setOrgLevel2(String orgLevel2) { - this.orgLevel2 = orgLevel2; - } - - @Override - public String getOrgLevel3() { - return orgLevel3; - } - - @Override - public void setOrgLevel3(String orgLevel3) { - this.orgLevel3 = orgLevel3; - } - - @Override - public String getOrgLevel4() { - return orgLevel4; - } - - @Override - public void setOrgLevel4(String orgLevel4) { - this.orgLevel4 = orgLevel4; - } - - @Override - public boolean isMarkedForDeletion() { - return markedForDeletion; - } - - @Override - public void setMarkedForDeletion(boolean markedForDeletion) { - this.markedForDeletion = markedForDeletion; - } - - public void setDomain(String domain) { - this.domain = domain; - } - - @Override - public WorkbasketSummary asSummary() { - WorkbasketSummaryImpl result = new WorkbasketSummaryImpl(); - result.setId(this.getId()); - result.setKey(this.getKey()); - result.setName(this.getName()); - result.setDescription(this.getDescription()); - result.setOwner(this.getOwner()); - result.setDomain(this.getDomain()); - result.setType(this.getType()); - result.setCustom1(this.getCustom1()); - result.setCustom2(this.getCustom2()); - result.setCustom3(this.getCustom3()); - result.setCustom4(this.getCustom4()); - result.setOrgLevel1(this.getOrgLevel1()); - result.setOrgLevel2(this.getOrgLevel2()); - result.setOrgLevel3(this.getOrgLevel3()); - result.setOrgLevel4(this.getOrgLevel4()); - result.setMarkedForDeletion(this.isMarkedForDeletion()); - return result; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((created == null) ? 0 : created.hashCode()); - result = prime * result + ((custom1 == null) ? 0 : custom1.hashCode()); - result = prime * result + ((custom2 == null) ? 0 : custom2.hashCode()); - result = prime * result + ((custom3 == null) ? 0 : custom3.hashCode()); - result = prime * result + ((custom4 == null) ? 0 : custom4.hashCode()); - result = prime * result + ((description == null) ? 0 : description.hashCode()); - result = prime * result + ((domain == null) ? 0 : domain.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((key == null) ? 0 : key.hashCode()); - result = prime * result + (markedForDeletion ? 1231 : 1237); - result = prime * result + ((modified == null) ? 0 : modified.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((orgLevel1 == null) ? 0 : orgLevel1.hashCode()); - result = prime * result + ((orgLevel2 == null) ? 0 : orgLevel2.hashCode()); - result = prime * result + ((orgLevel3 == null) ? 0 : orgLevel3.hashCode()); - result = prime * result + ((orgLevel4 == null) ? 0 : orgLevel4.hashCode()); - result = prime * result + ((owner == null) ? 0 : owner.hashCode()); - result = prime * result + ((type == null) ? 0 : type.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - - if (!getClass().isAssignableFrom(obj.getClass())) { - return false; - } - WorkbasketImpl other = (WorkbasketImpl) obj; - if (created == null) { - if (other.created != null) { - return false; - } - } else if (!created.equals(other.created)) { - return false; - } - if (custom1 == null) { - if (other.custom1 != null) { - return false; - } - } else if (!custom1.equals(other.custom1)) { - return false; - } - if (custom2 == null) { - if (other.custom2 != null) { - return false; - } - } else if (!custom2.equals(other.custom2)) { - return false; - } - if (custom3 == null) { - if (other.custom3 != null) { - return false; - } - } else if (!custom3.equals(other.custom3)) { - return false; - } - if (custom4 == null) { - if (other.custom4 != null) { - return false; - } - } else if (!custom4.equals(other.custom4)) { - return false; - } - if (description == null) { - if (other.description != null) { - return false; - } - } else if (!description.equals(other.description)) { - return false; - } - if (domain == null) { - if (other.domain != null) { - return false; - } - } else if (!domain.equals(other.domain)) { - return false; - } - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (key == null) { - if (other.key != null) { - return false; - } - } else if (!key.equals(other.key)) { - return false; - } - if (markedForDeletion != other.markedForDeletion) { - return false; - } - if (modified == null) { - if (other.modified != null) { - return false; - } - } else if (!modified.equals(other.modified)) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - if (orgLevel1 == null) { - if (other.orgLevel1 != null) { - return false; - } - } else if (!orgLevel1.equals(other.orgLevel1)) { - return false; - } - if (orgLevel2 == null) { - if (other.orgLevel2 != null) { - return false; - } - } else if (!orgLevel2.equals(other.orgLevel2)) { - return false; - } - if (orgLevel3 == null) { - if (other.orgLevel3 != null) { - return false; - } - } else if (!orgLevel3.equals(other.orgLevel3)) { - return false; - } - if (orgLevel4 == null) { - if (other.orgLevel4 != null) { - return false; - } - } else if (!orgLevel4.equals(other.orgLevel4)) { - return false; - } - if (owner == null) { - if (other.owner != null) { - return false; - } - } else if (!owner.equals(other.owner)) { - return false; - } - if (type != other.type) { - return false; - } - return true; - } - - @Override - public String toString() { - return "WorkbasketImpl [id=" + id + ", key=" + key + ", created=" + created + ", modified=" + modified - + ", name=" + name + ", description=" + description + ", owner=" + owner + ", domain=" + domain + ", type=" - + type + ", custom1=" + custom1 + ", custom2=" + custom2 + ", custom3=" + custom3 + ", custom4=" + custom4 - + ", orgLevel1=" + orgLevel1 + ", orgLevel2=" + orgLevel2 + ", orgLevel3=" + orgLevel3 + ", orgLevel4=" - + orgLevel4 + ", markedForDeletion=" + markedForDeletion + "]"; + if (type != other.type) { + return false; } + return true; + } + @Override + public String toString() { + return "WorkbasketImpl [id=" + + id + + ", key=" + + key + + ", created=" + + created + + ", modified=" + + modified + + ", name=" + + name + + ", description=" + + description + + ", owner=" + + owner + + ", domain=" + + domain + + ", type=" + + type + + ", custom1=" + + custom1 + + ", custom2=" + + custom2 + + ", custom3=" + + custom3 + + ", custom4=" + + custom4 + + ", orgLevel1=" + + orgLevel1 + + ", orgLevel2=" + + orgLevel2 + + ", orgLevel3=" + + orgLevel3 + + ", orgLevel4=" + + orgLevel4 + + ", markedForDeletion=" + + markedForDeletion + + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketQueryImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketQueryImpl.java index 2641b5474..673c6f26e 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketQueryImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketQueryImpl.java @@ -3,7 +3,6 @@ package pro.taskana.impl; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import org.apache.ibatis.exceptions.PersistenceException; import org.apache.ibatis.session.RowBounds; import org.slf4j.Logger; @@ -30,685 +29,756 @@ import pro.taskana.security.CurrentUserContext; */ public class WorkbasketQueryImpl implements WorkbasketQuery { - private static final String LINK_TO_MAPPER = "pro.taskana.mappings.QueryMapper.queryWorkbasketSummaries"; - private static final String LINK_TO_COUNTER = "pro.taskana.mappings.QueryMapper.countQueryWorkbaskets"; - private static final String LINK_TO_VALUEMAPPER = "pro.taskana.mappings.QueryMapper.queryWorkbasketColumnValues"; - private static final Logger LOGGER = LoggerFactory.getLogger(WorkbasketQueryImpl.class); - private WorkbasketQueryColumnName columnName; - private String[] accessId; - private String[] idIn; - private WorkbasketPermission permission; - private String[] nameIn; - private String[] nameLike; - private String[] keyIn; - private String[] keyLike; - private String[] keyOrNameLike; - private String[] domainIn; - private String[] domainLike; - private WorkbasketType[] type; - private TimeInterval[] createdIn; - private TimeInterval[] modifiedIn; - private String[] descriptionLike; - private String[] ownerIn; - private String[] ownerLike; - private String[] custom1In; - private String[] custom1Like; - private String[] custom2In; - private String[] custom2Like; - private String[] custom3In; - private String[] custom3Like; - private String[] custom4In; - private String[] custom4Like; - private String[] orgLevel1In; - private String[] orgLevel1Like; - private String[] orgLevel2In; - private String[] orgLevel2Like; - private String[] orgLevel3In; - private String[] orgLevel3Like; - private String[] orgLevel4In; - private String[] orgLevel4Like; - private boolean markedForDeletion; + private static final String LINK_TO_MAPPER = + "pro.taskana.mappings.QueryMapper.queryWorkbasketSummaries"; + private static final String LINK_TO_COUNTER = + "pro.taskana.mappings.QueryMapper.countQueryWorkbaskets"; + private static final String LINK_TO_VALUEMAPPER = + "pro.taskana.mappings.QueryMapper.queryWorkbasketColumnValues"; + private static final Logger LOGGER = LoggerFactory.getLogger(WorkbasketQueryImpl.class); + private WorkbasketQueryColumnName columnName; + private String[] accessId; + private String[] idIn; + private WorkbasketPermission permission; + private String[] nameIn; + private String[] nameLike; + private String[] keyIn; + private String[] keyLike; + private String[] keyOrNameLike; + private String[] domainIn; + private String[] domainLike; + private WorkbasketType[] type; + private TimeInterval[] createdIn; + private TimeInterval[] modifiedIn; + private String[] descriptionLike; + private String[] ownerIn; + private String[] ownerLike; + private String[] custom1In; + private String[] custom1Like; + private String[] custom2In; + private String[] custom2Like; + private String[] custom3In; + private String[] custom3Like; + private String[] custom4In; + private String[] custom4Like; + private String[] orgLevel1In; + private String[] orgLevel1Like; + private String[] orgLevel2In; + private String[] orgLevel2Like; + private String[] orgLevel3In; + private String[] orgLevel3Like; + private String[] orgLevel4In; + private String[] orgLevel4Like; + private boolean markedForDeletion; - private InternalTaskanaEngine taskanaEngine; - private List orderBy; - private List orderColumns; - private boolean joinWithAccessList; - private boolean checkReadPermission; - private boolean usedToAugmentTasks; - private boolean callerRolesAndAccessIdsAlreadyHandled; + private InternalTaskanaEngine taskanaEngine; + private List orderBy; + private List orderColumns; + private boolean joinWithAccessList; + private boolean checkReadPermission; + private boolean usedToAugmentTasks; + private boolean callerRolesAndAccessIdsAlreadyHandled; - WorkbasketQueryImpl(InternalTaskanaEngine taskanaEngine) { - this.taskanaEngine = taskanaEngine; - this.orderBy = new ArrayList<>(); - this.orderColumns = new ArrayList<>(); - this.callerRolesAndAccessIdsAlreadyHandled = false; + WorkbasketQueryImpl(InternalTaskanaEngine taskanaEngine) { + this.taskanaEngine = taskanaEngine; + this.orderBy = new ArrayList<>(); + this.orderColumns = new ArrayList<>(); + this.callerRolesAndAccessIdsAlreadyHandled = false; + } + + @Override + public WorkbasketQuery idIn(String... id) { + this.idIn = id; + return this; + } + + @Override + public WorkbasketQuery keyIn(String... key) { + this.keyIn = toUpperCopy(key); + return this; + } + + @Override + public WorkbasketQuery keyLike(String... keys) { + this.keyLike = toUpperCopy(keys); + return this; + } + + @Override + public WorkbasketQuery nameIn(String... names) { + this.nameIn = toUpperCopy(names); + return this; + } + + @Override + public WorkbasketQuery nameLike(String... names) { + this.nameLike = toUpperCopy(names); + return this; + } + + @Override + public WorkbasketQuery keyOrNameLike(String... keysOrNames) { + this.keyOrNameLike = toUpperCopy(keysOrNames); + return this; + } + + @Override + public WorkbasketQuery domainIn(String... domain) { + this.domainIn = domain; + return this; + } + + @Override + public WorkbasketQuery domainLike(String... domain) { + this.domainLike = domain; + return this; + } + + @Override + public WorkbasketQuery typeIn(WorkbasketType... type) { + this.type = type; + return this; + } + + @Override + public WorkbasketQuery createdWithin(TimeInterval... intervals) { + this.createdIn = intervals; + for (TimeInterval ti : intervals) { + if (!ti.isValid()) { + throw new IllegalArgumentException("TimeInterval " + ti + " is invalid."); + } + } + return this; + } + + @Override + public WorkbasketQuery modifiedWithin(TimeInterval... intervals) { + this.modifiedIn = intervals; + for (TimeInterval ti : intervals) { + if (!ti.isValid()) { + throw new IllegalArgumentException("TimeInterval " + ti + " is invalid."); + } + } + return this; + } + + @Override + public WorkbasketQuery descriptionLike(String... description) { + this.descriptionLike = toUpperCopy(description); + return this; + } + + @Override + public WorkbasketQuery ownerIn(String... owners) { + this.ownerIn = owners; + return this; + } + + @Override + public WorkbasketQuery ownerLike(String... owners) { + this.ownerLike = toUpperCopy(owners); + return this; + } + + @Override + public WorkbasketQuery custom1In(String... custom1) { + this.custom1In = custom1; + return this; + } + + @Override + public WorkbasketQuery custom1Like(String... custom1) { + this.custom1Like = toUpperCopy(custom1); + return this; + } + + @Override + public WorkbasketQuery custom2In(String... custom2) { + this.custom2In = custom2; + return this; + } + + @Override + public WorkbasketQuery custom2Like(String... custom2) { + this.custom2Like = toUpperCopy(custom2); + return this; + } + + @Override + public WorkbasketQuery custom3In(String... custom3) { + this.custom3In = custom3; + return this; + } + + @Override + public WorkbasketQuery custom3Like(String... custom3) { + this.custom3Like = toUpperCopy(custom3); + return this; + } + + @Override + public WorkbasketQuery custom4In(String... custom4) { + this.custom4In = custom4; + return this; + } + + @Override + public WorkbasketQuery custom4Like(String... custom4) { + this.custom4Like = toUpperCopy(custom4); + return this; + } + + @Override + public WorkbasketQuery orgLevel1In(String... orgLevel1) { + this.orgLevel1In = orgLevel1; + return this; + } + + @Override + public WorkbasketQuery orgLevel1Like(String... orgLevel1) { + this.orgLevel1Like = toUpperCopy(orgLevel1); + return this; + } + + @Override + public WorkbasketQuery orgLevel2In(String... orgLevel2) { + this.orgLevel2In = orgLevel2; + return this; + } + + @Override + public WorkbasketQuery orgLevel2Like(String... orgLevel2) { + this.orgLevel2Like = toUpperCopy(orgLevel2); + return this; + } + + @Override + public WorkbasketQuery orgLevel3In(String... orgLevel3) { + this.orgLevel3In = orgLevel3; + return this; + } + + @Override + public WorkbasketQuery orgLevel3Like(String... orgLevel3) { + this.orgLevel3Like = toUpperCopy(orgLevel3); + return this; + } + + @Override + public WorkbasketQuery orgLevel4In(String... orgLevel4) { + this.orgLevel4In = orgLevel4; + return this; + } + + @Override + public WorkbasketQuery orgLevel4Like(String... orgLevel4) { + this.orgLevel4Like = toUpperCopy(orgLevel4); + return this; + } + + @Override + public WorkbasketQuery markedForDeletion(boolean markedForDeletion) { + this.markedForDeletion = markedForDeletion; + return this; + } + + @Override + public WorkbasketQuery orderByName(SortDirection sortDirection) { + return addOrderCriteria("NAME", sortDirection); + } + + @Override + public WorkbasketQuery orderByKey(SortDirection sortDirection) { + return addOrderCriteria("KEY", sortDirection); + } + + @Override + public WorkbasketQuery orderByDomain(SortDirection sortDirection) { + return addOrderCriteria("DOMAIN", sortDirection); + } + + @Override + public WorkbasketQuery orderByDescription(SortDirection sortDirection) { + return addOrderCriteria("DESCRIPTION", sortDirection); + } + + @Override + public WorkbasketQuery orderByOwner(SortDirection sortDirection) { + return addOrderCriteria("OWNER", sortDirection); + } + + @Override + public WorkbasketQuery orderByType(SortDirection sortDirection) { + return addOrderCriteria("TYPE", sortDirection); + } + + @Override + public WorkbasketQuery orderByCustom1(SortDirection sortDirection) { + return addOrderCriteria("CUSTOM_1", sortDirection); + } + + @Override + public WorkbasketQuery orderByCustom2(SortDirection sortDirection) { + return addOrderCriteria("CUSTOM_2", sortDirection); + } + + @Override + public WorkbasketQuery orderByCustom3(SortDirection sortDirection) { + return addOrderCriteria("CUSTOM_3", sortDirection); + } + + @Override + public WorkbasketQuery orderByCustom4(SortDirection sortDirection) { + return addOrderCriteria("CUSTOM_4", sortDirection); + } + + @Override + public WorkbasketQuery orderByOrgLevel1(SortDirection sortDirection) { + return addOrderCriteria("ORG_LEVEL_1", sortDirection); + } + + @Override + public WorkbasketQuery orderByOrgLevel2(SortDirection sortDirection) { + return addOrderCriteria("ORG_LEVEL_2", sortDirection); + } + + @Override + public WorkbasketQuery orderByOrgLevel3(SortDirection sortDirection) { + return addOrderCriteria("ORG_LEVEL_3", sortDirection); + } + + @Override + public WorkbasketQuery orderByOrgLevel4(SortDirection sortDirection) { + return addOrderCriteria("ORG_LEVEL_4", sortDirection); + } + + @Override + public WorkbasketQuery accessIdsHavePermission( + WorkbasketPermission permission, String... accessIds) + throws InvalidArgumentException, NotAuthorizedException { + taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.ADMIN, TaskanaRole.BUSINESS_ADMIN); + // Checking pre-conditions + if (permission == null) { + throw new InvalidArgumentException("Permission can´t be null."); + } + if (accessIds == null || accessIds.length == 0) { + throw new InvalidArgumentException("accessIds can´t be NULL or empty."); } - @Override - public WorkbasketQuery idIn(String... id) { - this.idIn = id; - return this; - } + // set up permissions and ids + this.permission = permission; + this.accessId = accessIds; + lowercaseAccessIds(this.accessId); - @Override - public WorkbasketQuery keyIn(String... key) { - this.keyIn = toUpperCopy(key); - return this; - } + return this; + } - @Override - public WorkbasketQuery keyLike(String... keys) { - this.keyLike = toUpperCopy(keys); - return this; - } + @Override + public WorkbasketQuery callerHasPermission(WorkbasketPermission permission) { + this.permission = permission; + return this; + } - @Override - public WorkbasketQuery nameIn(String... names) { - this.nameIn = toUpperCopy(names); - return this; + @Override + public List list() { + LOGGER.debug("entry to list(), this = {}", this); + List workbaskets = new ArrayList<>(); + try { + taskanaEngine.openConnection(); + handleCallerRolesAndAccessIds(); + workbaskets = taskanaEngine.getSqlSession().selectList(LINK_TO_MAPPER, this); + return workbaskets; + } finally { + taskanaEngine.returnConnection(); + if (LOGGER.isDebugEnabled()) { + int numberOfResultObjects = workbaskets == null ? 0 : workbaskets.size(); + LOGGER.debug( + "exit from list(). Returning {} resulting Objects: {} ", + numberOfResultObjects, + LoggerUtils.listToString(workbaskets)); + } } + } - @Override - public WorkbasketQuery nameLike(String... names) { - this.nameLike = toUpperCopy(names); - return this; + public List listValues( + WorkbasketQueryColumnName columnName, SortDirection sortDirection) { + LOGGER.debug("Entry to listValues(dbColumnName={}) this = {}", columnName, this); + List result = new ArrayList<>(); + try { + taskanaEngine.openConnection(); + this.columnName = columnName; + handleCallerRolesAndAccessIds(); + this.orderBy.clear(); + result = taskanaEngine.getSqlSession().selectList(LINK_TO_VALUEMAPPER, this); + return result; + } finally { + taskanaEngine.returnConnection(); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "Exit from listValues. Returning {} resulting Objects: {} ", + result.size(), + LoggerUtils.listToString(result)); + } } + } - @Override - public WorkbasketQuery keyOrNameLike(String... keysOrNames) { - this.keyOrNameLike = toUpperCopy(keysOrNames); - return this; + @Override + public List list(int offset, int limit) { + LOGGER.debug("entry to list(offset = {}, limit = {}), this = {}", offset, limit, this); + List workbaskets = new ArrayList<>(); + try { + taskanaEngine.openConnection(); + RowBounds rowBounds = new RowBounds(offset, limit); + handleCallerRolesAndAccessIds(); + workbaskets = taskanaEngine.getSqlSession().selectList(LINK_TO_MAPPER, this, rowBounds); + return workbaskets; + } catch (PersistenceException e) { + if (e.getMessage().contains("ERRORCODE=-4470")) { + TaskanaRuntimeException ex = + new TaskanaRuntimeException( + "The offset beginning was set over the amount of result-rows.", e.getCause()); + ex.setStackTrace(e.getStackTrace()); + throw ex; + } + throw e; + } finally { + taskanaEngine.returnConnection(); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "exit from list(offset,limit). Returning {} resulting Objects: {} ", + workbaskets.size(), + LoggerUtils.listToString(workbaskets)); + } } + } - @Override - public WorkbasketQuery domainIn(String... domain) { - this.domainIn = domain; - return this; + @Override + public WorkbasketSummary single() { + LOGGER.debug("entry to single(), this = {}", this); + WorkbasketSummary workbasket = null; + try { + taskanaEngine.openConnection(); + handleCallerRolesAndAccessIds(); + workbasket = taskanaEngine.getSqlSession().selectOne(LINK_TO_MAPPER, this); + return workbasket; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from single(). Returning result {} ", workbasket); } + } - @Override - public WorkbasketQuery domainLike(String... domain) { - this.domainLike = domain; - return this; + @Override + public long count() { + LOGGER.debug("entry to count(), this = {}", this); + Long rowCount = null; + try { + taskanaEngine.openConnection(); + handleCallerRolesAndAccessIds(); + rowCount = taskanaEngine.getSqlSession().selectOne(LINK_TO_COUNTER, this); + return (rowCount == null) ? 0L : rowCount; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from count(). Returning result {} ", rowCount); } + } - @Override - public WorkbasketQuery typeIn(WorkbasketType... type) { - this.type = type; - return this; - } + public String[] getAccessId() { + return accessId; + } - @Override - public WorkbasketQuery createdWithin(TimeInterval... intervals) { - this.createdIn = intervals; - for (TimeInterval ti : intervals) { - if (!ti.isValid()) { - throw new IllegalArgumentException("TimeInterval " + ti + " is invalid."); - } + public WorkbasketPermission getPermission() { + return permission; + } + + public String[] getNameIn() { + return nameIn; + } + + public String[] getNameLike() { + return nameLike; + } + + public String[] getKeyIn() { + return keyIn; + } + + public String[] getKeyLike() { + return keyLike; + } + + public String[] getKeyOrNameLike() { + return keyOrNameLike; + } + + public WorkbasketType[] getType() { + return type; + } + + public TimeInterval[] getCreatedIn() { + return createdIn; + } + + public TimeInterval[] getModifiedIn() { + return modifiedIn; + } + + public String[] getDescriptionLike() { + return descriptionLike; + } + + public String[] getOwnerIn() { + return ownerIn; + } + + public String[] getDomainIn() { + return domainIn; + } + + public String[] getDomainLike() { + return domainLike; + } + + public String[] getCustom1In() { + return custom1In; + } + + public String[] getCustom1Like() { + return custom1Like; + } + + public String[] getCustom2In() { + return custom2In; + } + + public String[] getCustom2Like() { + return custom2Like; + } + + public String[] getCustom3In() { + return custom3In; + } + + public String[] getCustom3Like() { + return custom3Like; + } + + public String[] getCustom4In() { + return custom4In; + } + + public String[] getCustom4Like() { + return custom4Like; + } + + public String[] getOrgLevel1In() { + return orgLevel1In; + } + + public String[] getOrgLevel1Like() { + return orgLevel1Like; + } + + public String[] getOrgLevel2In() { + return orgLevel2In; + } + + public String[] getOrgLevel2Like() { + return orgLevel2Like; + } + + public String[] getOrgLevel3In() { + return orgLevel3In; + } + + public String[] getOrgLevel3Like() { + return orgLevel3Like; + } + + public String[] getOrgLevel4In() { + return orgLevel4In; + } + + public String[] getOrgLevel4Like() { + return orgLevel4Like; + } + + public boolean isMarkedForDeletion() { + return markedForDeletion; + } + + public String[] getOwnerLike() { + return ownerLike; + } + + public String[] getIdIn() { + return idIn; + } + + public List getOrderBy() { + return orderBy; + } + + public List getOrderColumns() { + return orderColumns; + } + + public WorkbasketQueryColumnName getColumnName() { + return columnName; + } + + public boolean isJoinWithAccessList() { + return joinWithAccessList; + } + + public boolean isCheckReadPermission() { + return checkReadPermission; + } + + void setUsedToAugmentTasks(boolean usedToAugmentTasks) { + this.usedToAugmentTasks = usedToAugmentTasks; + } + + static void lowercaseAccessIds(String[] accessIdArray) { + if (TaskanaEngineConfiguration.shouldUseLowerCaseForAccessIds()) { + for (int i = 0; i < accessIdArray.length; i++) { + String id = accessIdArray[i]; + if (id != null) { + accessIdArray[i] = id.toLowerCase(); } - return this; + } } + } - @Override - public WorkbasketQuery modifiedWithin(TimeInterval... intervals) { - this.modifiedIn = intervals; - for (TimeInterval ti : intervals) { - if (!ti.isValid()) { - throw new IllegalArgumentException("TimeInterval " + ti + " is invalid."); - } + private void handleCallerRolesAndAccessIds() { + if (!callerRolesAndAccessIdsAlreadyHandled) { + callerRolesAndAccessIdsAlreadyHandled = true; + + // if user is admin or businessadmin, don't check read permission on workbasket. + // in addition, if user is admin or businessadmin and no accessIds were specified, don't join + // with access + // list + // if this query is used to augment task or a permission is given as filter criteria, + // a business admin should be treated like a normal user + // + // (joinWithAccessList,checkReadPermission) can assume the following combinations: + // (t,t) -> query performed by user + // (f,f) -> admin queries w/o access ids specified + // (t,f) -> admin queries with access ids specified or permissions given + // (f,t) -> cannot happen, cannot be matched to meaningful query + joinWithAccessList = true; + checkReadPermission = true; + if (taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN) && accessId == null) { + checkReadPermission = false; + joinWithAccessList = false; + } else if (taskanaEngine.getEngine().isUserInRole(TaskanaRole.BUSINESS_ADMIN) + && !usedToAugmentTasks) { + checkReadPermission = false; + if (accessId == null && permission == null) { + joinWithAccessList = false; } - return this; - } - - @Override - public WorkbasketQuery descriptionLike(String... description) { - this.descriptionLike = toUpperCopy(description); - return this; - } - - @Override - public WorkbasketQuery ownerIn(String... owners) { - this.ownerIn = owners; - return this; - } - - @Override - public WorkbasketQuery ownerLike(String... owners) { - this.ownerLike = toUpperCopy(owners); - return this; - } - - @Override - public WorkbasketQuery custom1In(String... custom1) { - this.custom1In = custom1; - return this; - } - - @Override - public WorkbasketQuery custom1Like(String... custom1) { - this.custom1Like = toUpperCopy(custom1); - return this; - } - - @Override - public WorkbasketQuery custom2In(String... custom2) { - this.custom2In = custom2; - return this; - } - - @Override - public WorkbasketQuery custom2Like(String... custom2) { - this.custom2Like = toUpperCopy(custom2); - return this; - } - - @Override - public WorkbasketQuery custom3In(String... custom3) { - this.custom3In = custom3; - return this; - } - - @Override - public WorkbasketQuery custom3Like(String... custom3) { - this.custom3Like = toUpperCopy(custom3); - return this; - } - - @Override - public WorkbasketQuery custom4In(String... custom4) { - this.custom4In = custom4; - return this; - } - - @Override - public WorkbasketQuery custom4Like(String... custom4) { - this.custom4Like = toUpperCopy(custom4); - return this; - } - - @Override - public WorkbasketQuery orgLevel1In(String... orgLevel1) { - this.orgLevel1In = orgLevel1; - return this; - } - - @Override - public WorkbasketQuery orgLevel1Like(String... orgLevel1) { - this.orgLevel1Like = toUpperCopy(orgLevel1); - return this; - } - - @Override - public WorkbasketQuery orgLevel2In(String... orgLevel2) { - this.orgLevel2In = orgLevel2; - return this; - } - - @Override - public WorkbasketQuery orgLevel2Like(String... orgLevel2) { - this.orgLevel2Like = toUpperCopy(orgLevel2); - return this; - } - - @Override - public WorkbasketQuery orgLevel3In(String... orgLevel3) { - this.orgLevel3In = orgLevel3; - return this; - } - - @Override - public WorkbasketQuery orgLevel3Like(String... orgLevel3) { - this.orgLevel3Like = toUpperCopy(orgLevel3); - return this; - } - - @Override - public WorkbasketQuery orgLevel4In(String... orgLevel4) { - this.orgLevel4In = orgLevel4; - return this; - } - - @Override - public WorkbasketQuery orgLevel4Like(String... orgLevel4) { - this.orgLevel4Like = toUpperCopy(orgLevel4); - return this; - } - - @Override - public WorkbasketQuery markedForDeletion(boolean markedForDeletion) { - this.markedForDeletion = markedForDeletion; - return this; - } - - @Override - public WorkbasketQuery orderByName(SortDirection sortDirection) { - return addOrderCriteria("NAME", sortDirection); - } - - @Override - public WorkbasketQuery orderByKey(SortDirection sortDirection) { - return addOrderCriteria("KEY", sortDirection); - } - - @Override - public WorkbasketQuery orderByDomain(SortDirection sortDirection) { - return addOrderCriteria("DOMAIN", sortDirection); - } - - @Override - public WorkbasketQuery orderByDescription(SortDirection sortDirection) { - return addOrderCriteria("DESCRIPTION", sortDirection); - } - - @Override - public WorkbasketQuery orderByOwner(SortDirection sortDirection) { - return addOrderCriteria("OWNER", sortDirection); - } - - @Override - public WorkbasketQuery orderByType(SortDirection sortDirection) { - return addOrderCriteria("TYPE", sortDirection); - } - - @Override - public WorkbasketQuery orderByCustom1(SortDirection sortDirection) { - return addOrderCriteria("CUSTOM_1", sortDirection); - } - - @Override - public WorkbasketQuery orderByCustom2(SortDirection sortDirection) { - return addOrderCriteria("CUSTOM_2", sortDirection); - } - - @Override - public WorkbasketQuery orderByCustom3(SortDirection sortDirection) { - return addOrderCriteria("CUSTOM_3", sortDirection); - } - - @Override - public WorkbasketQuery orderByCustom4(SortDirection sortDirection) { - return addOrderCriteria("CUSTOM_4", sortDirection); - } - - @Override - public WorkbasketQuery orderByOrgLevel1(SortDirection sortDirection) { - return addOrderCriteria("ORG_LEVEL_1", sortDirection); - } - - @Override - public WorkbasketQuery orderByOrgLevel2(SortDirection sortDirection) { - return addOrderCriteria("ORG_LEVEL_2", sortDirection); - } - - @Override - public WorkbasketQuery orderByOrgLevel3(SortDirection sortDirection) { - return addOrderCriteria("ORG_LEVEL_3", sortDirection); - } - - @Override - public WorkbasketQuery orderByOrgLevel4(SortDirection sortDirection) { - return addOrderCriteria("ORG_LEVEL_4", sortDirection); - } - - @Override - public WorkbasketQuery accessIdsHavePermission(WorkbasketPermission permission, String... accessIds) - throws InvalidArgumentException, NotAuthorizedException { - taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.ADMIN, TaskanaRole.BUSINESS_ADMIN); - // Checking pre-conditions - if (permission == null) { - throw new InvalidArgumentException("Permission can´t be null."); + } + // might already be set by accessIdsHavePermission + if (this.accessId == null) { + String[] accessIds = new String[0]; + List ucAccessIds = CurrentUserContext.getAccessIds(); + if (ucAccessIds != null && !ucAccessIds.isEmpty()) { + accessIds = new String[ucAccessIds.size()]; + accessIds = ucAccessIds.toArray(accessIds); } - if (accessIds == null || accessIds.length == 0) { - throw new InvalidArgumentException("accessIds can´t be NULL or empty."); - } - - // set up permissions and ids - this.permission = permission; this.accessId = accessIds; lowercaseAccessIds(this.accessId); - - return this; + } } + LOGGER.debug("exit from handleCallerRolesAndAccessIds, now this is {}", this); + } - @Override - public WorkbasketQuery callerHasPermission(WorkbasketPermission permission) { - this.permission = permission; - return this; - } - - @Override - public List list() { - LOGGER.debug("entry to list(), this = {}", this); - List workbaskets = new ArrayList<>(); - try { - taskanaEngine.openConnection(); - handleCallerRolesAndAccessIds(); - workbaskets = taskanaEngine.getSqlSession().selectList(LINK_TO_MAPPER, this); - return workbaskets; - } finally { - taskanaEngine.returnConnection(); - if (LOGGER.isDebugEnabled()) { - int numberOfResultObjects = workbaskets == null ? 0 : workbaskets.size(); - LOGGER.debug("exit from list(). Returning {} resulting Objects: {} ", numberOfResultObjects, - LoggerUtils.listToString(workbaskets)); - } - } - } - - public List listValues(WorkbasketQueryColumnName columnName, SortDirection sortDirection) { - LOGGER.debug("Entry to listValues(dbColumnName={}) this = {}", columnName, this); - List result = new ArrayList<>(); - try { - taskanaEngine.openConnection(); - this.columnName = columnName; - handleCallerRolesAndAccessIds(); - this.orderBy.clear(); - result = taskanaEngine.getSqlSession().selectList(LINK_TO_VALUEMAPPER, this); - return result; - } finally { - taskanaEngine.returnConnection(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from listValues. Returning {} resulting Objects: {} ", result.size(), - LoggerUtils.listToString(result)); - } - } - } - - @Override - public List list(int offset, int limit) { - LOGGER.debug("entry to list(offset = {}, limit = {}), this = {}", offset, limit, this); - List workbaskets = new ArrayList<>(); - try { - taskanaEngine.openConnection(); - RowBounds rowBounds = new RowBounds(offset, limit); - handleCallerRolesAndAccessIds(); - workbaskets = taskanaEngine.getSqlSession().selectList(LINK_TO_MAPPER, this, rowBounds); - return workbaskets; - } catch (PersistenceException e) { - if (e.getMessage().contains("ERRORCODE=-4470")) { - TaskanaRuntimeException ex = new TaskanaRuntimeException( - "The offset beginning was set over the amount of result-rows.", e.getCause()); - ex.setStackTrace(e.getStackTrace()); - throw ex; - } - throw e; - } finally { - taskanaEngine.returnConnection(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("exit from list(offset,limit). Returning {} resulting Objects: {} ", workbaskets.size(), - LoggerUtils.listToString(workbaskets)); - } - } - } - - @Override - public WorkbasketSummary single() { - LOGGER.debug("entry to single(), this = {}", this); - WorkbasketSummary workbasket = null; - try { - taskanaEngine.openConnection(); - handleCallerRolesAndAccessIds(); - workbasket = taskanaEngine.getSqlSession().selectOne(LINK_TO_MAPPER, this); - return workbasket; - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from single(). Returning result {} ", workbasket); - } - } - - @Override - public long count() { - LOGGER.debug("entry to count(), this = {}", this); - Long rowCount = null; - try { - taskanaEngine.openConnection(); - handleCallerRolesAndAccessIds(); - rowCount = taskanaEngine.getSqlSession().selectOne(LINK_TO_COUNTER, this); - return (rowCount == null) ? 0L : rowCount; - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from count(). Returning result {} ", rowCount); - } - } - - public String[] getAccessId() { - return accessId; - } - - public WorkbasketPermission getPermission() { - return permission; - } - - public String[] getNameIn() { - return nameIn; - } - - public String[] getNameLike() { - return nameLike; - } - - public String[] getKeyIn() { - return keyIn; - } - - public String[] getKeyLike() { - return keyLike; - } - - public String[] getKeyOrNameLike() { - return keyOrNameLike; - } - - public WorkbasketType[] getType() { - return type; - } - - public TimeInterval[] getCreatedIn() { - return createdIn; - } - - public TimeInterval[] getModifiedIn() { - return modifiedIn; - } - - public String[] getDescriptionLike() { - return descriptionLike; - } - - public String[] getOwnerIn() { - return ownerIn; - } - - public String[] getDomainIn() { - return domainIn; - } - - public String[] getDomainLike() { - return domainLike; - } - - public String[] getCustom1In() { - return custom1In; - } - - public String[] getCustom1Like() { - return custom1Like; - } - - public String[] getCustom2In() { - return custom2In; - } - - public String[] getCustom2Like() { - return custom2Like; - } - - public String[] getCustom3In() { - return custom3In; - } - - public String[] getCustom3Like() { - return custom3Like; - } - - public String[] getCustom4In() { - return custom4In; - } - - public String[] getCustom4Like() { - return custom4Like; - } - - public String[] getOrgLevel1In() { - return orgLevel1In; - } - - public String[] getOrgLevel1Like() { - return orgLevel1Like; - } - - public String[] getOrgLevel2In() { - return orgLevel2In; - } - - public String[] getOrgLevel2Like() { - return orgLevel2Like; - } - - public String[] getOrgLevel3In() { - return orgLevel3In; - } - - public String[] getOrgLevel3Like() { - return orgLevel3Like; - } - - public String[] getOrgLevel4In() { - return orgLevel4In; - } - - public String[] getOrgLevel4Like() { - return orgLevel4Like; - } - - public boolean isMarkedForDeletion() { - return markedForDeletion; - } - - public String[] getOwnerLike() { - return ownerLike; - } - - public String[] getIdIn() { - return idIn; - } - - public List getOrderBy() { - return orderBy; - } - - public List getOrderColumns() { - return orderColumns; - } - - public WorkbasketQueryColumnName getColumnName() { - return columnName; - } - - public boolean isJoinWithAccessList() { - return joinWithAccessList; - } - - public boolean isCheckReadPermission() { - return checkReadPermission; - } - - void setUsedToAugmentTasks(boolean usedToAugmentTasks) { - this.usedToAugmentTasks = usedToAugmentTasks; - } - - @Override - public String toString() { - return "WorkbasketQueryImpl [" + "columnName=" + this.columnName + ", accessId=" - + Arrays.toString(this.accessId) + ", idIn=" + Arrays.toString(this.idIn) + ", permission=" - + this.permission + ", nameIn=" + Arrays.toString(this.nameIn) + ", nameLike=" - + Arrays.toString(this.nameLike) + ", keyIn=" + Arrays.toString(this.keyIn) + ", keyLike=" - + Arrays.toString(this.keyLike) + ", keyOrNameLike=" + Arrays.toString(this.keyOrNameLike) + ", domainIn=" - + Arrays.toString(this.domainIn) + ", domainLike=" + Arrays.toString(this.domainLike) + ", type=" - + Arrays.toString(this.type) + ", createdIn=" + Arrays.toString(this.createdIn) + ", modifiedIn=" - + Arrays.toString(this.modifiedIn) + ", descriptionLike=" + Arrays.toString(this.descriptionLike) - + ", ownerIn=" + Arrays.toString(this.ownerIn) + ", ownerLike=" + Arrays.toString(this.ownerLike) - + ", custom1In=" + Arrays.toString(this.custom1In) + ", custom1Like=" + Arrays.toString(this.custom1Like) - + ", custom2In=" + Arrays.toString(this.custom2In) + ", custom2Like=" + Arrays.toString(this.custom2Like) - + ", custom3In=" + Arrays.toString(this.custom3In) + ", custom3Like=" + Arrays.toString(this.custom3Like) - + ", custom4In=" + Arrays.toString(this.custom4In) + ", custom4Like=" + Arrays.toString(this.custom4Like) - + ", orgLevel1In=" + Arrays.toString(this.orgLevel1In) + ", orgLevel1Like=" - + Arrays.toString(this.orgLevel1Like) + ", orgLevel2In=" + Arrays.toString(this.orgLevel2In) - + ", orgLevel2Like=" + Arrays.toString(this.orgLevel2Like) + ", orgLevel3In=" - + Arrays.toString(this.orgLevel3In) + ", orgLevel3Like=" + Arrays.toString(this.orgLevel3Like) - + ", orgLevel4In=" + Arrays.toString(this.orgLevel4In) + ", orgLevel4Like=" - + Arrays.toString(this.orgLevel4Like) + ", markedForDeletion=" + this.markedForDeletion + ", orderBy=" - + this.orderBy + ", joinWithAccessList=" + this.joinWithAccessList + ", checkReadPermission=" - + this.checkReadPermission + ", usedToAugmentTasks=" + this.usedToAugmentTasks + "]"; - } - - private void handleCallerRolesAndAccessIds() { - if (!callerRolesAndAccessIdsAlreadyHandled) { - callerRolesAndAccessIdsAlreadyHandled = true; - - // if user is admin or businessadmin, don't check read permission on workbasket. - // in addition, if user is admin or businessadmin and no accessIds were specified, don't join with access - // list - // if this query is used to augment task or a permission is given as filter criteria, - // a business admin should be treated like a normal user - // - // (joinWithAccessList,checkReadPermission) can assume the following combinations: - // (t,t) -> query performed by user - // (f,f) -> admin queries w/o access ids specified - // (t,f) -> admin queries with access ids specified or permissions given - // (f,t) -> cannot happen, cannot be matched to meaningful query - joinWithAccessList = true; - checkReadPermission = true; - if (taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN) && accessId == null) { - checkReadPermission = false; - joinWithAccessList = false; - } else if (taskanaEngine.getEngine().isUserInRole(TaskanaRole.BUSINESS_ADMIN) && !usedToAugmentTasks) { - checkReadPermission = false; - if (accessId == null && permission == null) { - joinWithAccessList = false; - } - } - // might already be set by accessIdsHavePermission - if (this.accessId == null) { - String[] accessIds = new String[0]; - List ucAccessIds = CurrentUserContext.getAccessIds(); - if (ucAccessIds != null && !ucAccessIds.isEmpty()) { - accessIds = new String[ucAccessIds.size()]; - accessIds = ucAccessIds.toArray(accessIds); - } - this.accessId = accessIds; - lowercaseAccessIds(this.accessId); - } - } - LOGGER.debug("exit from handleCallerRolesAndAccessIds, now this is {}", this); - } - - static void lowercaseAccessIds(String[] accessIdArray) { - if (TaskanaEngineConfiguration.shouldUseLowerCaseForAccessIds()) { - for (int i = 0; i < accessIdArray.length; i++) { - String id = accessIdArray[i]; - if (id != null) { - accessIdArray[i] = id.toLowerCase(); - } - } - } - } - - private WorkbasketQuery addOrderCriteria(String colName, SortDirection sortDirection) { - String orderByDirection = " " + (sortDirection == null ? SortDirection.ASCENDING : sortDirection); - orderBy.add(colName + orderByDirection); - orderColumns.add(colName); - return this; - } + private WorkbasketQuery addOrderCriteria(String colName, SortDirection sortDirection) { + String orderByDirection = + " " + (sortDirection == null ? SortDirection.ASCENDING : sortDirection); + orderBy.add(colName + orderByDirection); + orderColumns.add(colName); + return this; + } + @Override + public String toString() { + return "WorkbasketQueryImpl [" + + "columnName=" + + this.columnName + + ", accessId=" + + Arrays.toString(this.accessId) + + ", idIn=" + + Arrays.toString(this.idIn) + + ", permission=" + + this.permission + + ", nameIn=" + + Arrays.toString(this.nameIn) + + ", nameLike=" + + Arrays.toString(this.nameLike) + + ", keyIn=" + + Arrays.toString(this.keyIn) + + ", keyLike=" + + Arrays.toString(this.keyLike) + + ", keyOrNameLike=" + + Arrays.toString(this.keyOrNameLike) + + ", domainIn=" + + Arrays.toString(this.domainIn) + + ", domainLike=" + + Arrays.toString(this.domainLike) + + ", type=" + + Arrays.toString(this.type) + + ", createdIn=" + + Arrays.toString(this.createdIn) + + ", modifiedIn=" + + Arrays.toString(this.modifiedIn) + + ", descriptionLike=" + + Arrays.toString(this.descriptionLike) + + ", ownerIn=" + + Arrays.toString(this.ownerIn) + + ", ownerLike=" + + Arrays.toString(this.ownerLike) + + ", custom1In=" + + Arrays.toString(this.custom1In) + + ", custom1Like=" + + Arrays.toString(this.custom1Like) + + ", custom2In=" + + Arrays.toString(this.custom2In) + + ", custom2Like=" + + Arrays.toString(this.custom2Like) + + ", custom3In=" + + Arrays.toString(this.custom3In) + + ", custom3Like=" + + Arrays.toString(this.custom3Like) + + ", custom4In=" + + Arrays.toString(this.custom4In) + + ", custom4Like=" + + Arrays.toString(this.custom4Like) + + ", orgLevel1In=" + + Arrays.toString(this.orgLevel1In) + + ", orgLevel1Like=" + + Arrays.toString(this.orgLevel1Like) + + ", orgLevel2In=" + + Arrays.toString(this.orgLevel2In) + + ", orgLevel2Like=" + + Arrays.toString(this.orgLevel2Like) + + ", orgLevel3In=" + + Arrays.toString(this.orgLevel3In) + + ", orgLevel3Like=" + + Arrays.toString(this.orgLevel3Like) + + ", orgLevel4In=" + + Arrays.toString(this.orgLevel4In) + + ", orgLevel4Like=" + + Arrays.toString(this.orgLevel4Like) + + ", markedForDeletion=" + + this.markedForDeletion + + ", orderBy=" + + this.orderBy + + ", joinWithAccessList=" + + this.joinWithAccessList + + ", checkReadPermission=" + + this.checkReadPermission + + ", usedToAugmentTasks=" + + this.usedToAugmentTasks + + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketReportBuilderImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketReportBuilderImpl.java index b580716be..a9019f640 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketReportBuilderImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketReportBuilderImpl.java @@ -1,7 +1,6 @@ package pro.taskana.impl; import java.util.List; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -15,72 +14,89 @@ import pro.taskana.impl.report.preprocessor.DaysToWorkingDaysPreProcessor; import pro.taskana.mappings.TaskMonitorMapper; import pro.taskana.report.WorkbasketReport; -/** - * The implementation of WorkbasketReportBuilder. - */ +/** The implementation of WorkbasketReportBuilder. */ public class WorkbasketReportBuilderImpl - extends TimeIntervalReportBuilderImpl + extends TimeIntervalReportBuilderImpl< + WorkbasketReport.Builder, MonitorQueryItem, TimeIntervalColumnHeader> implements WorkbasketReport.Builder { - private static final Logger LOGGER = LoggerFactory.getLogger(WorkbasketReportBuilderImpl.class); - private List combinedClassificationFilter; + private static final Logger LOGGER = LoggerFactory.getLogger(WorkbasketReportBuilderImpl.class); + private List combinedClassificationFilter; - WorkbasketReportBuilderImpl(InternalTaskanaEngine taskanaEngine, TaskMonitorMapper taskMonitorMapper) { - super(taskanaEngine, taskMonitorMapper); - } + WorkbasketReportBuilderImpl( + InternalTaskanaEngine taskanaEngine, TaskMonitorMapper taskMonitorMapper) { + super(taskanaEngine, taskMonitorMapper); + } - @Override - protected WorkbasketReport.Builder _this() { - return this; + @Override + public WorkbasketReport buildReport() throws InvalidArgumentException, NotAuthorizedException { + LOGGER.debug("entry to buildReport(), this = {}", this); + this.taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.MONITOR, TaskanaRole.ADMIN); + try { + this.taskanaEngine.openConnection(); + WorkbasketReport report = new WorkbasketReport(this.columnHeaders); + List monitorQueryItems = + this.taskMonitorMapper.getTaskCountOfWorkbaskets( + this.workbasketIds, + this.states, + this.categories, + this.domains, + this.classificationIds, + this.excludedClassificationIds, + this.customAttributeFilter, + this.combinedClassificationFilter); + report.addItems( + monitorQueryItems, + new DaysToWorkingDaysPreProcessor<>(this.columnHeaders, this.inWorkingDays)); + return report; + } finally { + this.taskanaEngine.returnConnection(); + LOGGER.debug("exit from buildReport()."); } + } - @Override - protected String determineGroupedBy() { - return "WORKBASKET_KEY"; + @Override + public WorkbasketReport buildPlannedDateBasedReport() + throws NotAuthorizedException, InvalidArgumentException { + LOGGER.debug("entry to buildPlannedDateReport(), this = {}", this); + this.taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.MONITOR, TaskanaRole.ADMIN); + try { + this.taskanaEngine.openConnection(); + WorkbasketReport report = new WorkbasketReport(this.columnHeaders); + List monitorQueryItems = + this.taskMonitorMapper.getTaskCountOfWorkbasketsBasedOnPlannedDate( + this.workbasketIds, + this.states, + this.categories, + this.domains, + this.classificationIds, + this.excludedClassificationIds, + this.customAttributeFilter, + this.combinedClassificationFilter); + report.addItems( + monitorQueryItems, + new DaysToWorkingDaysPreProcessor<>(this.columnHeaders, this.inWorkingDays)); + return report; + } finally { + this.taskanaEngine.returnConnection(); + LOGGER.debug("exit from buildPlannedDateReport()."); } + } - @Override - public WorkbasketReport buildReport() throws InvalidArgumentException, NotAuthorizedException { - LOGGER.debug("entry to buildReport(), this = {}", this); - this.taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.MONITOR, TaskanaRole.ADMIN); - try { - this.taskanaEngine.openConnection(); - WorkbasketReport report = new WorkbasketReport(this.columnHeaders); - List monitorQueryItems = this.taskMonitorMapper.getTaskCountOfWorkbaskets( - this.workbasketIds, this.states, this.categories, this.domains, this.classificationIds, - this.excludedClassificationIds, this.customAttributeFilter, this.combinedClassificationFilter); - report.addItems(monitorQueryItems, - new DaysToWorkingDaysPreProcessor<>(this.columnHeaders, this.inWorkingDays)); - return report; - } finally { - this.taskanaEngine.returnConnection(); - LOGGER.debug("exit from buildReport()."); - } - } + @Override + public WorkbasketReport.Builder combinedClassificationFilterIn( + List combinedClassificationFilter) { + this.combinedClassificationFilter = combinedClassificationFilter; + return this; + } - @Override - public WorkbasketReport buildPlannedDateBasedReport() throws NotAuthorizedException, InvalidArgumentException { - LOGGER.debug("entry to buildPlannedDateReport(), this = {}", this); - this.taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.MONITOR, TaskanaRole.ADMIN); - try { - this.taskanaEngine.openConnection(); - WorkbasketReport report = new WorkbasketReport(this.columnHeaders); - List monitorQueryItems = this.taskMonitorMapper.getTaskCountOfWorkbasketsBasedOnPlannedDate( - this.workbasketIds, this.states, this.categories, this.domains, this.classificationIds, - this.excludedClassificationIds, this.customAttributeFilter, this.combinedClassificationFilter); - report.addItems(monitorQueryItems, - new DaysToWorkingDaysPreProcessor<>(this.columnHeaders, this.inWorkingDays)); - return report; - } finally { - this.taskanaEngine.returnConnection(); - LOGGER.debug("exit from buildPlannedDateReport()."); - } - } + @Override + protected WorkbasketReport.Builder _this() { + return this; + } - @Override - public WorkbasketReport.Builder combinedClassificationFilterIn( - List combinedClassificationFilter) { - this.combinedClassificationFilter = combinedClassificationFilter; - return this; - } + @Override + protected String determineGroupedBy() { + return "WORKBASKET_KEY"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketServiceImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketServiceImpl.java index b628e0c73..5ca8df378 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketServiceImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketServiceImpl.java @@ -5,7 +5,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -34,814 +33,905 @@ import pro.taskana.mappings.WorkbasketAccessMapper; import pro.taskana.mappings.WorkbasketMapper; import pro.taskana.security.CurrentUserContext; -/** - * This is the implementation of WorkbasketService. - */ +/** This is the implementation of WorkbasketService. */ public class WorkbasketServiceImpl implements WorkbasketService { - private static final Logger LOGGER = LoggerFactory.getLogger(WorkbasketServiceImpl.class); - private static final String ID_PREFIX_WORKBASKET = "WBI"; - private static final String ID_PREFIX_WORKBASKET_AUTHORIZATION = "WAI"; - private InternalTaskanaEngine taskanaEngine; - private WorkbasketMapper workbasketMapper; - private DistributionTargetMapper distributionTargetMapper; - private WorkbasketAccessMapper workbasketAccessMapper; + private static final Logger LOGGER = LoggerFactory.getLogger(WorkbasketServiceImpl.class); + private static final String ID_PREFIX_WORKBASKET = "WBI"; + private static final String ID_PREFIX_WORKBASKET_AUTHORIZATION = "WAI"; + private InternalTaskanaEngine taskanaEngine; + private WorkbasketMapper workbasketMapper; + private DistributionTargetMapper distributionTargetMapper; + private WorkbasketAccessMapper workbasketAccessMapper; - WorkbasketServiceImpl(InternalTaskanaEngine taskanaEngine, WorkbasketMapper workbasketMapper, - DistributionTargetMapper distributionTargetMapper, WorkbasketAccessMapper workbasketAccessMapper) { - this.taskanaEngine = taskanaEngine; - this.workbasketMapper = workbasketMapper; - this.distributionTargetMapper = distributionTargetMapper; - this.workbasketAccessMapper = workbasketAccessMapper; + WorkbasketServiceImpl( + InternalTaskanaEngine taskanaEngine, + WorkbasketMapper workbasketMapper, + DistributionTargetMapper distributionTargetMapper, + WorkbasketAccessMapper workbasketAccessMapper) { + this.taskanaEngine = taskanaEngine; + this.workbasketMapper = workbasketMapper; + this.distributionTargetMapper = distributionTargetMapper; + this.workbasketAccessMapper = workbasketAccessMapper; + } + + @Override + public Workbasket getWorkbasket(String workbasketId) + throws WorkbasketNotFoundException, NotAuthorizedException { + LOGGER.debug("entry to getWorkbasket(workbasketId = {})", workbasketId); + Workbasket result = null; + try { + taskanaEngine.openConnection(); + result = workbasketMapper.findById(workbasketId); + if (result == null) { + throw new WorkbasketNotFoundException( + workbasketId, "Workbasket with id " + workbasketId + " was not found."); + } + if (!taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.BUSINESS_ADMIN)) { + this.checkAuthorization(workbasketId, WorkbasketPermission.READ); + } + return result; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from getWorkbasket(workbasketId). Returning result {} ", result); } + } + + @Override + public Workbasket getWorkbasket(String workbasketKey, String domain) + throws WorkbasketNotFoundException, NotAuthorizedException { + LOGGER.debug("entry to getWorkbasketByKey(workbasketKey = {})", workbasketKey); + Workbasket result = null; + try { + taskanaEngine.openConnection(); + result = workbasketMapper.findByKeyAndDomain(workbasketKey, domain); + if (result == null) { + throw new WorkbasketNotFoundException( + workbasketKey, + domain, + "Workbasket with key " + workbasketKey + " and domain " + domain + " was not found."); + } + if (!taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.BUSINESS_ADMIN)) { + this.checkAuthorization(workbasketKey, domain, WorkbasketPermission.READ); + } + return result; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from getWorkbasket(workbasketId). Returning result {} ", result); + } + } + + @Override + public Workbasket createWorkbasket(Workbasket newWorkbasket) + throws InvalidWorkbasketException, NotAuthorizedException, WorkbasketAlreadyExistException, + DomainNotFoundException { + LOGGER.debug("entry to createtWorkbasket(workbasket)", newWorkbasket); + taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); + + WorkbasketImpl workbasket = (WorkbasketImpl) newWorkbasket; + try { + taskanaEngine.openConnection(); + Instant now = Instant.now(); + workbasket.setCreated(now); + workbasket.setModified(now); + Workbasket existingWorkbasket = + workbasketMapper.findByKeyAndDomain(newWorkbasket.getKey(), newWorkbasket.getDomain()); + if (existingWorkbasket != null) { + throw new WorkbasketAlreadyExistException(existingWorkbasket); + } + + if (workbasket.getId() == null || workbasket.getId().isEmpty()) { + workbasket.setId(IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET)); + } + validateWorkbasket(workbasket); + + workbasketMapper.insert(workbasket); + LOGGER.debug("Method createWorkbasket() created Workbasket '{}'", workbasket); + return workbasket; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from createWorkbasket(workbasket). Returning result {} ", workbasket); + } + } + + @Override + public Workbasket updateWorkbasket(Workbasket workbasketToUpdate) throws NotAuthorizedException { + LOGGER.debug("entry to updateWorkbasket(workbasket)", workbasketToUpdate); + taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); + + WorkbasketImpl workbasket = (WorkbasketImpl) workbasketToUpdate; + try { + taskanaEngine.openConnection(); + workbasket.setModified(Instant.now()); + if (workbasket.getId() == null || workbasket.getId().isEmpty()) { + workbasketMapper.updateByKeyAndDomain(workbasket); + } else { + workbasketMapper.update(workbasket); + } + LOGGER.debug("Method updateWorkbasket() updated workbasket '{}'", workbasket.getId()); + return workbasket; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from updateWorkbasket(). Returning result {} ", workbasket); + } + } + + @Override + public WorkbasketAccessItem newWorkbasketAccessItem(String workbasketId, String accessId) { + WorkbasketAccessItemImpl accessItem = new WorkbasketAccessItemImpl(); + accessItem.setWorkbasketId(workbasketId); + accessItem.setAccessIdWithSanitizing(accessId); + return accessItem; + } + + @Override + public WorkbasketAccessItem createWorkbasketAccessItem(WorkbasketAccessItem workbasketAccessItem) + throws InvalidArgumentException, NotAuthorizedException, WorkbasketNotFoundException { + LOGGER.debug( + "entry to createWorkbasketAccessItemn(workbasketAccessItem = {})", workbasketAccessItem); + taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); + WorkbasketAccessItemImpl accessItem = (WorkbasketAccessItemImpl) workbasketAccessItem; + try { + taskanaEngine.openConnection(); + accessItem.setId(IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_AUTHORIZATION)); + if (workbasketAccessItem.getId() == null + || workbasketAccessItem.getAccessId() == null + || workbasketAccessItem.getWorkbasketId() == null) { + throw new InvalidArgumentException( + "Checking the preconditions of the current WorkbasketAccessItem failed. WorkbasketAccessItem=" + + workbasketAccessItem.toString()); + } + WorkbasketImpl wb = workbasketMapper.findById(workbasketAccessItem.getWorkbasketId()); + if (wb == null) { + throw new WorkbasketNotFoundException( + workbasketAccessItem.getWorkbasketId(), + "WorkbasketAccessItem " + + workbasketAccessItem + + " refers to a not existing workbasket"); + } + workbasketAccessMapper.insert(accessItem); + LOGGER.debug( + "Method createWorkbasketAccessItem() created workbaskteAccessItem {}", accessItem); + return accessItem; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug( + "exit from createWorkbasketAccessItem(workbasketAccessItem). Returning result {}", + accessItem); + } + } + + @Override + public void setWorkbasketAccessItems( + String workbasketId, List wbAccessItems) + throws InvalidArgumentException, NotAuthorizedException { + LOGGER.debug( + "entry to setWorkbasketAccessItems(workbasketAccessItems = {})", wbAccessItems.toString()); + taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); + List newItems = new ArrayList<>(); + try { + taskanaEngine.openConnection(); + // Check pre-conditions and set ID + if (!wbAccessItems.isEmpty()) { + for (WorkbasketAccessItem workbasketAccessItem : wbAccessItems) { + WorkbasketAccessItemImpl wbAccessItemImpl = + (WorkbasketAccessItemImpl) workbasketAccessItem; + if (wbAccessItemImpl.getWorkbasketId() == null) { + throw new InvalidArgumentException( + "Checking the preconditions of the current WorkbasketAccessItem failed - WBID is NULL. WorkbasketAccessItem=" + + workbasketAccessItem.toString()); + } else if (!wbAccessItemImpl.getWorkbasketId().equals(workbasketId)) { + throw new InvalidArgumentException( + "Checking the preconditions of the current WorkbasketAccessItem failed - the WBID does not match. Target-WBID='" + + workbasketId + + "' WorkbasketAccessItem=" + + workbasketAccessItem.toString()); + } + if (wbAccessItemImpl.getId() == null || wbAccessItemImpl.getId().isEmpty()) { + wbAccessItemImpl.setId( + IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_AUTHORIZATION)); + } + newItems.add(wbAccessItemImpl); + } + } + + // delete all current ones + workbasketAccessMapper.deleteAllAccessItemsForWorkbasketId(workbasketId); + + // add all + if (!newItems.isEmpty()) { + newItems.forEach(item -> workbasketAccessMapper.insert(item)); + } + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug( + "exit from setWorkbasketAccessItems(workbasketAccessItems = {})", + wbAccessItems.toString()); + } + } + + @Override + public void deleteWorkbasketAccessItem(String accessItemId) throws NotAuthorizedException { + LOGGER.debug("entry to deleteWorkbasketAccessItem(id = {})", accessItemId); + taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); + try { + taskanaEngine.openConnection(); + workbasketAccessMapper.delete(accessItemId); + LOGGER.debug( + "Method deleteWorkbasketAccessItem() deleted workbasketAccessItem wit Id {}", + accessItemId); + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from deleteWorkbasketAccessItem(id)."); + } + } + + @Override + public void deleteWorkbasketAccessItemsForAccessId(String accessId) + throws NotAuthorizedException { + LOGGER.debug("entry to deleteWorkbasketAccessItemsForAccessId(accessId = {})", accessId); + taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); + try { + taskanaEngine.openConnection(); + workbasketAccessMapper.deleteAccessItemsForAccessId(accessId); + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from deleteWorkbasketAccessItemsForAccessId(accessId={}).", accessId); + } + } + + @Override + public void checkAuthorization(String workbasketId, WorkbasketPermission... requestedPermissions) + throws NotAuthorizedException, WorkbasketNotFoundException { + boolean isAuthorized = true; + try { + taskanaEngine.openConnection(); + + if (workbasketMapper.findById(workbasketId) == null) { + throw new WorkbasketNotFoundException( + workbasketId, "Workbasket with id " + workbasketId + " was not found."); + } + + if (skipAuthorizationCheck()) { + return; + } + + List accessIds = CurrentUserContext.getAccessIds(); + WorkbasketAccessItem wbAcc = + workbasketAccessMapper.findByWorkbasketAndAccessId(workbasketId, accessIds); + if (wbAcc == null) { + throw new NotAuthorizedException( + "Not authorized. Permission '" + + Arrays.toString(requestedPermissions) + + "' on workbasket '" + + workbasketId + + "' is needed.", + CurrentUserContext.getUserid()); + } + + List grantedPermissions = + this.getPermissionsFromWorkbasketAccessItem(wbAcc); + + for (WorkbasketPermission perm : requestedPermissions) { + if (!grantedPermissions.contains(perm)) { + isAuthorized = false; + throw new NotAuthorizedException( + "Not authorized. Permission '" + + perm.name() + + "' on workbasket '" + + workbasketId + + "' is needed.", + CurrentUserContext.getUserid()); + } + } + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from checkAuthorization(). User is authorized = {}.", isAuthorized); + } + } + + @Override + public void checkAuthorization( + String workbasketKey, String domain, WorkbasketPermission... requestedPermissions) + throws NotAuthorizedException, WorkbasketNotFoundException { + boolean isAuthorized = true; + try { + taskanaEngine.openConnection(); + + if (workbasketMapper.findByKeyAndDomain(workbasketKey, domain) == null) { + throw new WorkbasketNotFoundException( + workbasketKey, + domain, + "Workbasket with key " + workbasketKey + " and domain " + domain + " was not found"); + } + if (skipAuthorizationCheck()) { + return; + } + List accessIds = CurrentUserContext.getAccessIds(); + WorkbasketAccessItem wbAcc = + workbasketAccessMapper.findByWorkbasketKeyDomainAndAccessId( + workbasketKey, domain, accessIds); + if (wbAcc == null) { + throw new NotAuthorizedException( + "Not authorized. Permission '" + + Arrays.toString(requestedPermissions) + + "' on workbasket with key '" + + workbasketKey + + "' and domain '" + + domain + + "' is needed.", + CurrentUserContext.getUserid()); + } + List grantedPermissions = + this.getPermissionsFromWorkbasketAccessItem(wbAcc); + + for (WorkbasketPermission perm : requestedPermissions) { + if (!grantedPermissions.contains(perm)) { + isAuthorized = false; + throw new NotAuthorizedException( + "Not authorized. Permission '" + + perm.name() + + "' on workbasket with key '" + + workbasketKey + + "' and domain '" + + domain + + "' is needed.", + CurrentUserContext.getUserid()); + } + } + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from checkAuthorization(). User is authorized = {}.", isAuthorized); + } + } + + @Override + public WorkbasketAccessItem updateWorkbasketAccessItem(WorkbasketAccessItem workbasketAccessItem) + throws InvalidArgumentException, NotAuthorizedException { + LOGGER.debug( + "entry to updateWorkbasketAccessItem(workbasketAccessItem = {}", workbasketAccessItem); + taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); + WorkbasketAccessItemImpl accessItem = (WorkbasketAccessItemImpl) workbasketAccessItem; + try { + taskanaEngine.openConnection(); + WorkbasketAccessItem originalItem = workbasketAccessMapper.findById(accessItem.getId()); + + if ((originalItem.getAccessId() != null + && !originalItem.getAccessId().equals(accessItem.getAccessId())) + || (originalItem.getWorkbasketId() != null + && !originalItem.getWorkbasketId().equals(accessItem.getWorkbasketId()))) { + throw new InvalidArgumentException( + "AccessId and WorkbasketId must not be changed in updateWorkbasketAccessItem calls"); + } + + workbasketAccessMapper.update(accessItem); + LOGGER.debug( + "Method updateWorkbasketAccessItem() updated workbasketAccessItem {}", accessItem); + return accessItem; + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug( + "exit from updateWorkbasketAccessItem(workbasketAccessItem). Returning {}", accessItem); + } + } + + @Override + public List getWorkbasketAccessItems(String workbasketId) + throws NotAuthorizedException { + LOGGER.debug("entry to getWorkbasketAccessItems(workbasketId = {})", workbasketId); + taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); + List result = new ArrayList<>(); + try { + taskanaEngine.openConnection(); + List queryResult = + workbasketAccessMapper.findByWorkbasketId(workbasketId); + result.addAll(queryResult); + return result; + } finally { + taskanaEngine.returnConnection(); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "exit from getWorkbasketAccessItems(workbasketId). Returning {} resulting Objects: {} ", + result.size(), + LoggerUtils.listToString(result)); + } + } + } + + @Override + public List getPermissionsForWorkbasket(String workbasketId) { + WorkbasketAccessItem wbAcc = + workbasketAccessMapper.findByWorkbasketAndAccessId( + workbasketId, CurrentUserContext.getAccessIds()); + return this.getPermissionsFromWorkbasketAccessItem(wbAcc); + } + + @Override + public WorkbasketQuery createWorkbasketQuery() { + return new WorkbasketQueryImpl(taskanaEngine); + } + + @Override + public Workbasket newWorkbasket(String key, String domain) { + WorkbasketImpl wb = new WorkbasketImpl(); + wb.setDomain(domain); + wb.setKey(key); + return wb; + } + + @Override + public List getDistributionTargets(String workbasketId) + throws NotAuthorizedException, WorkbasketNotFoundException { + LOGGER.debug("entry to getDistributionTargets(workbasketId = {})", workbasketId); + List result = new ArrayList<>(); + try { + taskanaEngine.openConnection(); + // check that source workbasket exists + getWorkbasket(workbasketId); + if (!taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.BUSINESS_ADMIN)) { + checkAuthorization(workbasketId, WorkbasketPermission.READ); + } + List distributionTargets = + workbasketMapper.findDistributionTargets(workbasketId); + result.addAll(distributionTargets); + return result; + } finally { + taskanaEngine.returnConnection(); + if (LOGGER.isDebugEnabled()) { + int numberOfResultObjects = result.size(); + LOGGER.debug( + "exit from getDistributionTargets(workbasketId). Returning {} resulting Objects: {} ", + numberOfResultObjects, + LoggerUtils.listToString(result)); + } + } + } + + @Override + public List getDistributionTargets(String workbasketKey, String domain) + throws NotAuthorizedException, WorkbasketNotFoundException { + LOGGER.debug( + "entry to getDistributionTargets(workbasketKey = {}, domain = {})", workbasketKey, domain); + List result = new ArrayList<>(); + try { + taskanaEngine.openConnection(); + // check that source workbasket exists + Workbasket workbasket = getWorkbasket(workbasketKey, domain); + if (!taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.BUSINESS_ADMIN)) { + checkAuthorization(workbasket.getId(), WorkbasketPermission.READ); + } + List distributionTargets = + workbasketMapper.findDistributionTargets(workbasket.getId()); + result.addAll(distributionTargets); + return result; + } finally { + taskanaEngine.returnConnection(); + if (LOGGER.isDebugEnabled()) { + int numberOfResultObjects = result.size(); + LOGGER.debug( + "exit from getDistributionTargets(workbasketId). Returning {} resulting Objects: {} ", + numberOfResultObjects, + LoggerUtils.listToString(result)); + } + } + } + + @Override + public List getDistributionSources(String workbasketId) + throws NotAuthorizedException, WorkbasketNotFoundException { + LOGGER.debug("entry to getDistributionSources(workbasketId = {})", workbasketId); + List result = new ArrayList<>(); + try { + taskanaEngine.openConnection(); + // check that source workbasket exists + getWorkbasket(workbasketId); + if (!taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.BUSINESS_ADMIN)) { + checkAuthorization(workbasketId, WorkbasketPermission.READ); + } + List distributionSources = + workbasketMapper.findDistributionSources(workbasketId); + result.addAll(distributionSources); + return result; + } finally { + taskanaEngine.returnConnection(); + if (LOGGER.isDebugEnabled()) { + int numberOfResultObjects = result.size(); + LOGGER.debug( + "exit from getDistributionSources(workbasketId). Returning {} resulting Objects: {} ", + numberOfResultObjects, + LoggerUtils.listToString(result)); + } + } + } + + @Override + public List getDistributionSources(String workbasketKey, String domain) + throws NotAuthorizedException, WorkbasketNotFoundException { + LOGGER.debug( + "entry to getDistributionSources(workbasketKey = {}, domain = {})", workbasketKey, domain); + List result = new ArrayList<>(); + try { + taskanaEngine.openConnection(); + // check that source workbasket exists + Workbasket workbasket = getWorkbasket(workbasketKey, domain); + if (!taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.BUSINESS_ADMIN)) { + checkAuthorization(workbasket.getId(), WorkbasketPermission.READ); + } + List distributionSources = + workbasketMapper.findDistributionSources(workbasket.getId()); + result.addAll(distributionSources); + return result; + } finally { + taskanaEngine.returnConnection(); + if (LOGGER.isDebugEnabled()) { + int numberOfResultObjects = result.size(); + LOGGER.debug( + "exit from getDistributionSources(workbasketId). Returning {} resulting Objects: {} ", + numberOfResultObjects, + LoggerUtils.listToString(result)); + } + } + } + + @Override + public void setDistributionTargets(String sourceWorkbasketId, List targetWorkbasketIds) + throws WorkbasketNotFoundException, NotAuthorizedException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "entry to setDistributionTargets(sourceWorkbasketId = {}, targetWorkazketIds = {})", + sourceWorkbasketId, + LoggerUtils.listToString(targetWorkbasketIds)); + } + taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); + try { + taskanaEngine.openConnection(); + // check existence of source workbasket + WorkbasketImpl sourceWorkbasket = (WorkbasketImpl) getWorkbasket(sourceWorkbasketId); + distributionTargetMapper.deleteAllDistributionTargetsBySourceId(sourceWorkbasketId); + + sourceWorkbasket.setModified(Instant.now()); + workbasketMapper.update(sourceWorkbasket); + + if (targetWorkbasketIds != null) { + for (String targetId : targetWorkbasketIds) { + // check for existence of target workbasket + getWorkbasket(targetId); + distributionTargetMapper.insert(sourceWorkbasketId, targetId); + LOGGER.debug( + "Method setDistributionTargets() created distributiontarget for source '{}' and target {}", + sourceWorkbasketId, + targetId); + } + } + } finally { + taskanaEngine.returnConnection(); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "setDistributionTargets set {} distribution targets to source workbasket {} ", + targetWorkbasketIds == null ? 0 : targetWorkbasketIds.size(), + sourceWorkbasketId); + } + } + } + + @Override + public void addDistributionTarget(String sourceWorkbasketId, String targetWorkbasketId) + throws NotAuthorizedException, WorkbasketNotFoundException { + LOGGER.debug( + "entry to addDistributionTarget(sourceWorkbasketId = {}, targetWorkbasketId = {})", + sourceWorkbasketId, + targetWorkbasketId); + taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); + try { + taskanaEngine.openConnection(); + // check existence of source workbasket + WorkbasketImpl sourceWorkbasket = (WorkbasketImpl) getWorkbasket(sourceWorkbasketId); + // check existence of target workbasket + getWorkbasket(targetWorkbasketId); + // check whether the target is already set as target + int numOfDistTargets = + distributionTargetMapper.getNumberOfDistributionTargets( + sourceWorkbasketId, targetWorkbasketId); + if (numOfDistTargets > 0) { + LOGGER.debug( + "addDistributionTarget detected that the specified distribution target exists already. Doing nothing..."); + } else { + distributionTargetMapper.insert(sourceWorkbasketId, targetWorkbasketId); + LOGGER.debug( + "addDistributionTarget inserted distribution target sourceId = {}, targetId = {}", + sourceWorkbasketId, + targetWorkbasketId); + sourceWorkbasket.setModified(Instant.now()); + workbasketMapper.update(sourceWorkbasket); + } + + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from addDistributionTarget"); + } + } + + @Override + public void removeDistributionTarget(String sourceWorkbasketId, String targetWorkbasketId) + throws NotAuthorizedException { + LOGGER.debug( + "entry to removeDistributionTarget(sourceWorkbasketId = {}, targetWorkbasketId = {})", + sourceWorkbasketId, + targetWorkbasketId); + taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); + try { + taskanaEngine.openConnection(); + // don't check existence of source / target workbasket to enable cleanup even if the db is + // corrupted + // check whether the target is set as target + int numberOfDistTargets = + distributionTargetMapper.getNumberOfDistributionTargets( + sourceWorkbasketId, targetWorkbasketId); + if (numberOfDistTargets > 0) { + distributionTargetMapper.delete(sourceWorkbasketId, targetWorkbasketId); + LOGGER.debug( + "removeDistributionTarget deleted distribution target sourceId = {}, targetId = {}", + sourceWorkbasketId, + targetWorkbasketId); - @Override - public Workbasket getWorkbasket(String workbasketId) - throws WorkbasketNotFoundException, NotAuthorizedException { - LOGGER.debug("entry to getWorkbasket(workbasketId = {})", workbasketId); - Workbasket result = null; try { - taskanaEngine.openConnection(); - result = workbasketMapper.findById(workbasketId); - if (result == null) { - throw new WorkbasketNotFoundException(workbasketId, - "Workbasket with id " + workbasketId + " was not found."); - } - if (!taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.BUSINESS_ADMIN)) { - this.checkAuthorization(workbasketId, WorkbasketPermission.READ); - } - return result; - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from getWorkbasket(workbasketId). Returning result {} ", result); + WorkbasketImpl sourceWorkbasket = (WorkbasketImpl) getWorkbasket(sourceWorkbasketId); + sourceWorkbasket.setModified(Instant.now()); + workbasketMapper.update(sourceWorkbasket); + } catch (WorkbasketNotFoundException e) { + LOGGER.debug( + "removeDistributionTarget found that the source workbasket {} doesn't exist. Ignoring the request... ", + sourceWorkbasketId); } + + } else { + LOGGER.debug( + "removeDistributionTarget detected that the specified distribution target doesn't exist. Doing nothing..."); + } + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from addDistributionTarget"); } + } - @Override - public Workbasket getWorkbasket(String workbasketKey, String domain) - throws WorkbasketNotFoundException, NotAuthorizedException { - LOGGER.debug("entry to getWorkbasketByKey(workbasketKey = {})", workbasketKey); - Workbasket result = null; - try { - taskanaEngine.openConnection(); - result = workbasketMapper.findByKeyAndDomain(workbasketKey, domain); - if (result == null) { - throw new WorkbasketNotFoundException(workbasketKey, domain, - "Workbasket with key " + workbasketKey + " and domain " + domain + " was not found."); - } - if (!taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.BUSINESS_ADMIN)) { - this.checkAuthorization(workbasketKey, domain, WorkbasketPermission.READ); - } - return result; - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from getWorkbasket(workbasketId). Returning result {} ", result); - } - } + @Override + public boolean deleteWorkbasket(String workbasketId) + throws NotAuthorizedException, WorkbasketNotFoundException, WorkbasketInUseException, + InvalidArgumentException { + LOGGER.debug("entry to deleteWorkbasket(workbasketId = {})", workbasketId); + taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); - @Override - public Workbasket createWorkbasket(Workbasket newWorkbasket) - throws InvalidWorkbasketException, NotAuthorizedException, WorkbasketAlreadyExistException, - DomainNotFoundException { - LOGGER.debug("entry to createtWorkbasket(workbasket)", newWorkbasket); - taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); + try { + taskanaEngine.openConnection(); + if (workbasketId == null || workbasketId.isEmpty()) { + throw new InvalidArgumentException( + "The WorkbasketId can´t be NULL or EMPTY for deleteWorkbasket()"); + } - WorkbasketImpl workbasket = (WorkbasketImpl) newWorkbasket; - try { - taskanaEngine.openConnection(); - Instant now = Instant.now(); - workbasket.setCreated(now); - workbasket.setModified(now); - Workbasket existingWorkbasket = workbasketMapper.findByKeyAndDomain(newWorkbasket.getKey(), - newWorkbasket.getDomain()); - if (existingWorkbasket != null) { - throw new WorkbasketAlreadyExistException(existingWorkbasket); - } + // check if the workbasket does exist and is empty (Task) + this.getWorkbasket(workbasketId); - if (workbasket.getId() == null || workbasket.getId().isEmpty()) { - workbasket.setId(IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET)); - } - validateWorkbasket(workbasket); + long numTasksNotCompletedInWorkbasket = + taskanaEngine + .getEngine() + .getTaskService() + .createTaskQuery() + .workbasketIdIn(workbasketId) + .stateNotIn(TaskState.COMPLETED) + .count(); - workbasketMapper.insert(workbasket); - LOGGER.debug("Method createWorkbasket() created Workbasket '{}'", workbasket); - return workbasket; - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from createWorkbasket(workbasket). Returning result {} ", workbasket); - } - } + if (numTasksNotCompletedInWorkbasket > 0) { + throw new WorkbasketInUseException( + "Workbasket " + + workbasketId + + " contains non-completed tasks and can´t be marked for deletion."); + } - @Override - public Workbasket updateWorkbasket(Workbasket workbasketToUpdate) - throws NotAuthorizedException { - LOGGER.debug("entry to updateWorkbasket(workbasket)", workbasketToUpdate); - taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); - - WorkbasketImpl workbasket = (WorkbasketImpl) workbasketToUpdate; - try { - taskanaEngine.openConnection(); - workbasket.setModified(Instant.now()); - if (workbasket.getId() == null || workbasket.getId().isEmpty()) { - workbasketMapper.updateByKeyAndDomain(workbasket); - } else { - workbasketMapper.update(workbasket); - } - LOGGER.debug("Method updateWorkbasket() updated workbasket '{}'", workbasket.getId()); - return workbasket; - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from updateWorkbasket(). Returning result {} ", workbasket); - } - } - - @Override - public WorkbasketAccessItem newWorkbasketAccessItem(String workbasketId, String accessId) { - WorkbasketAccessItemImpl accessItem = new WorkbasketAccessItemImpl(); - accessItem.setWorkbasketId(workbasketId); - accessItem.setAccessIdWithSanitizing(accessId); - return accessItem; - } - - @Override - public WorkbasketAccessItem createWorkbasketAccessItem(WorkbasketAccessItem workbasketAccessItem) - throws InvalidArgumentException, NotAuthorizedException, WorkbasketNotFoundException { - LOGGER.debug("entry to createWorkbasketAccessItemn(workbasketAccessItem = {})", workbasketAccessItem); - taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); - WorkbasketAccessItemImpl accessItem = (WorkbasketAccessItemImpl) workbasketAccessItem; - try { - taskanaEngine.openConnection(); - accessItem.setId(IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_AUTHORIZATION)); - if (workbasketAccessItem.getId() == null || workbasketAccessItem.getAccessId() == null - || workbasketAccessItem.getWorkbasketId() == null) { - throw new InvalidArgumentException( - "Checking the preconditions of the current WorkbasketAccessItem failed. WorkbasketAccessItem=" - + workbasketAccessItem.toString()); - } - WorkbasketImpl wb = workbasketMapper.findById(workbasketAccessItem.getWorkbasketId()); - if (wb == null) { - throw new WorkbasketNotFoundException(workbasketAccessItem.getWorkbasketId(), - "WorkbasketAccessItem " + workbasketAccessItem + " refers to a not existing workbasket"); - } - workbasketAccessMapper.insert(accessItem); - LOGGER.debug("Method createWorkbasketAccessItem() created workbaskteAccessItem {}", - accessItem); - return accessItem; - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from createWorkbasketAccessItem(workbasketAccessItem). Returning result {}", - accessItem); - } - } - - @Override - public void setWorkbasketAccessItems(String workbasketId, List wbAccessItems) - throws InvalidArgumentException, NotAuthorizedException { - LOGGER.debug("entry to setWorkbasketAccessItems(workbasketAccessItems = {})", wbAccessItems.toString()); - taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); - List newItems = new ArrayList<>(); - try { - taskanaEngine.openConnection(); - // Check pre-conditions and set ID - if (!wbAccessItems.isEmpty()) { - for (WorkbasketAccessItem workbasketAccessItem : wbAccessItems) { - WorkbasketAccessItemImpl wbAccessItemImpl = (WorkbasketAccessItemImpl) workbasketAccessItem; - if (wbAccessItemImpl.getWorkbasketId() == null) { - throw new InvalidArgumentException( - "Checking the preconditions of the current WorkbasketAccessItem failed - WBID is NULL. WorkbasketAccessItem=" - + workbasketAccessItem.toString()); - } else if (!wbAccessItemImpl.getWorkbasketId().equals(workbasketId)) { - throw new InvalidArgumentException( - "Checking the preconditions of the current WorkbasketAccessItem failed - the WBID does not match. Target-WBID='" - + workbasketId + "' WorkbasketAccessItem=" - + workbasketAccessItem.toString()); - } - if (wbAccessItemImpl.getId() == null || wbAccessItemImpl.getId().isEmpty()) { - wbAccessItemImpl.setId(IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_AUTHORIZATION)); - } - newItems.add(wbAccessItemImpl); - } - } - - // delete all current ones - workbasketAccessMapper.deleteAllAccessItemsForWorkbasketId(workbasketId); - - // add all - if (!newItems.isEmpty()) { - newItems.forEach(item -> workbasketAccessMapper.insert(item)); - } - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from setWorkbasketAccessItems(workbasketAccessItems = {})", wbAccessItems.toString()); - } - } - - @Override - public void deleteWorkbasketAccessItem(String accessItemId) throws NotAuthorizedException { - LOGGER.debug("entry to deleteWorkbasketAccessItem(id = {})", accessItemId); - taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); - try { - taskanaEngine.openConnection(); - workbasketAccessMapper.delete(accessItemId); - LOGGER.debug("Method deleteWorkbasketAccessItem() deleted workbasketAccessItem wit Id {}", accessItemId); - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from deleteWorkbasketAccessItem(id)."); - } - } - - @Override - public void deleteWorkbasketAccessItemsForAccessId(String accessId) throws NotAuthorizedException { - LOGGER.debug("entry to deleteWorkbasketAccessItemsForAccessId(accessId = {})", accessId); - taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); - try { - taskanaEngine.openConnection(); - workbasketAccessMapper.deleteAccessItemsForAccessId(accessId); - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from deleteWorkbasketAccessItemsForAccessId(accessId={}).", accessId); - } - } - - @Override - public void checkAuthorization(String workbasketId, - WorkbasketPermission... requestedPermissions) throws NotAuthorizedException, WorkbasketNotFoundException { - boolean isAuthorized = true; - try { - taskanaEngine.openConnection(); - - if (workbasketMapper.findById(workbasketId) == null) { - throw new WorkbasketNotFoundException(workbasketId, - "Workbasket with id " + workbasketId + " was not found."); - } - - if (skipAuthorizationCheck()) { - return; - } - - List accessIds = CurrentUserContext.getAccessIds(); - WorkbasketAccessItem wbAcc = workbasketAccessMapper.findByWorkbasketAndAccessId(workbasketId, - accessIds); - if (wbAcc == null) { - throw new NotAuthorizedException( - "Not authorized. Permission '" + Arrays.toString(requestedPermissions) + "' on workbasket '" - + workbasketId - + "' is needed.", CurrentUserContext.getUserid()); - } - - List grantedPermissions = this.getPermissionsFromWorkbasketAccessItem(wbAcc); - - for (WorkbasketPermission perm : requestedPermissions) { - if (!grantedPermissions.contains(perm)) { - isAuthorized = false; - throw new NotAuthorizedException( - "Not authorized. Permission '" + perm.name() + "' on workbasket '" + workbasketId - + "' is needed.", CurrentUserContext.getUserid()); - } - } - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from checkAuthorization(). User is authorized = {}.", isAuthorized); - } - } - - @Override - public void checkAuthorization(String workbasketKey, String domain, - WorkbasketPermission... requestedPermissions) - throws NotAuthorizedException, WorkbasketNotFoundException { - boolean isAuthorized = true; - try { - taskanaEngine.openConnection(); - - if (workbasketMapper.findByKeyAndDomain(workbasketKey, domain) == null) { - throw new WorkbasketNotFoundException(workbasketKey, domain, - "Workbasket with key " + workbasketKey + " and domain " + domain + " was not found"); - } - if (skipAuthorizationCheck()) { - return; - } - List accessIds = CurrentUserContext.getAccessIds(); - WorkbasketAccessItem wbAcc = workbasketAccessMapper.findByWorkbasketKeyDomainAndAccessId( - workbasketKey, domain, accessIds); - if (wbAcc == null) { - throw new NotAuthorizedException( - "Not authorized. Permission '" + Arrays.toString(requestedPermissions) - + "' on workbasket with key '" - + workbasketKey - + "' and domain '" + domain + "' is needed.", CurrentUserContext.getUserid()); - } - List grantedPermissions = this.getPermissionsFromWorkbasketAccessItem(wbAcc); - - for (WorkbasketPermission perm : requestedPermissions) { - if (!grantedPermissions.contains(perm)) { - isAuthorized = false; - throw new NotAuthorizedException( - "Not authorized. Permission '" + perm.name() + "' on workbasket with key '" + workbasketKey - + "' and domain '" + domain + "' is needed.", CurrentUserContext.getUserid()); - } - } - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from checkAuthorization(). User is authorized = {}.", isAuthorized); - } - } - - private boolean skipAuthorizationCheck() { - - // Skip permission check is security is not enabled - if (!taskanaEngine.getEngine().getConfiguration().isSecurityEnabled()) { - LOGGER.debug("Skipping permissions check since security is disabled."); - return true; - } - - if (taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN)) { - LOGGER.debug("Skipping permissions check since user is in role ADMIN."); - return true; - } + long numTasksInWorkbasket = + taskanaEngine + .getEngine() + .getTaskService() + .createTaskQuery() + .workbasketIdIn(workbasketId) + .count(); + if (numTasksInWorkbasket == 0) { + workbasketMapper.delete(workbasketId); + deleteReferencesToWorkbasket(workbasketId); + return true; + } else { + markWorkbasketForDeletion(workbasketId); return false; + } + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from deleteWorkbasket(workbasketId = {})", workbasketId); + } + } + + public BulkOperationResults deleteWorkbaskets( + List workbasketsIds) throws NotAuthorizedException, InvalidArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "entry to deleteWorkbaskets(workbasketId = {})", + LoggerUtils.listToString(workbasketsIds)); } - @Override - public WorkbasketAccessItem updateWorkbasketAccessItem(WorkbasketAccessItem workbasketAccessItem) - throws InvalidArgumentException, NotAuthorizedException { - LOGGER.debug("entry to updateWorkbasketAccessItem(workbasketAccessItem = {}", workbasketAccessItem); - taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); - WorkbasketAccessItemImpl accessItem = (WorkbasketAccessItemImpl) workbasketAccessItem; + taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); + + try { + taskanaEngine.openConnection(); + if (workbasketsIds == null || workbasketsIds.isEmpty()) { + throw new InvalidArgumentException("List of WorkbasketIds must not be null."); + } + BulkOperationResults bulkLog = new BulkOperationResults<>(); + + Iterator iterator = workbasketsIds.iterator(); + String workbasketIdForDeleting = null; + while (iterator.hasNext()) { try { - taskanaEngine.openConnection(); - WorkbasketAccessItem originalItem = workbasketAccessMapper.findById(accessItem.getId()); - - if ((originalItem.getAccessId() != null && !originalItem.getAccessId().equals(accessItem.getAccessId())) - || (originalItem.getWorkbasketId() != null - && !originalItem.getWorkbasketId().equals(accessItem.getWorkbasketId()))) { - throw new InvalidArgumentException( - "AccessId and WorkbasketId must not be changed in updateWorkbasketAccessItem calls"); - } - - workbasketAccessMapper.update(accessItem); - LOGGER.debug("Method updateWorkbasketAccessItem() updated workbasketAccessItem {}", - accessItem); - return accessItem; - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from updateWorkbasketAccessItem(workbasketAccessItem). Returning {}", - accessItem); + workbasketIdForDeleting = iterator.next(); + if (!deleteWorkbasket(workbasketIdForDeleting)) { + bulkLog.addError( + workbasketIdForDeleting, + new WorkbasketInUseException( + "Workbasket with id " + + workbasketIdForDeleting + + " contains completed tasks not deleted and will not be deleted.")); + } + } catch (WorkbasketInUseException ex) { + bulkLog.addError( + workbasketIdForDeleting, + new WorkbasketInUseException( + "Workbasket with id " + + workbasketIdForDeleting + + " is in use and will not be deleted.")); + } catch (TaskanaException ex) { + bulkLog.addError( + workbasketIdForDeleting, + new TaskanaException( + "Workbasket with id " + + workbasketIdForDeleting + + " Throw an exception and couldn't be deleted.")); } + } + return bulkLog; + } finally { + LOGGER.debug("exit from deleteWorkbaskets()"); + taskanaEngine.returnConnection(); + } + } + + @Override + public WorkbasketAccessItemQuery createWorkbasketAccessItemQuery() throws NotAuthorizedException { + taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.ADMIN, TaskanaRole.BUSINESS_ADMIN); + return new WorkbasketAccessItemQueryImpl(this.taskanaEngine); + } + + private boolean skipAuthorizationCheck() { + + // Skip permission check is security is not enabled + if (!taskanaEngine.getEngine().getConfiguration().isSecurityEnabled()) { + LOGGER.debug("Skipping permissions check since security is disabled."); + return true; } - @Override - public List getWorkbasketAccessItems(String workbasketId) throws NotAuthorizedException { - LOGGER.debug("entry to getWorkbasketAccessItems(workbasketId = {})", workbasketId); - taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); - List result = new ArrayList<>(); - try { - taskanaEngine.openConnection(); - List queryResult = workbasketAccessMapper.findByWorkbasketId(workbasketId); - result.addAll(queryResult); - return result; - } finally { - taskanaEngine.returnConnection(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("exit from getWorkbasketAccessItems(workbasketId). Returning {} resulting Objects: {} ", - result.size(), LoggerUtils.listToString(result)); - } - } + if (taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN)) { + LOGGER.debug("Skipping permissions check since user is in role ADMIN."); + return true; } - @Override - public List getPermissionsForWorkbasket(String workbasketId) { - WorkbasketAccessItem wbAcc = workbasketAccessMapper.findByWorkbasketAndAccessId(workbasketId, - CurrentUserContext.getAccessIds()); - return this.getPermissionsFromWorkbasketAccessItem(wbAcc); + return false; + } + + private void validateWorkbasket(Workbasket workbasket) + throws InvalidWorkbasketException, DomainNotFoundException { + // check that required properties (database not null) are set + if (workbasket.getId() == null || workbasket.getId().length() == 0) { + throw new InvalidWorkbasketException("Id must not be null for " + workbasket); + } else if (workbasket.getKey() == null || workbasket.getKey().length() == 0) { + throw new InvalidWorkbasketException("Key must not be null for " + workbasket); } - - @Override - public WorkbasketQuery createWorkbasketQuery() { - return new WorkbasketQueryImpl(taskanaEngine); + if (workbasket.getName() == null || workbasket.getName().length() == 0) { + throw new InvalidWorkbasketException("Name must not be null for " + workbasket); } - - private void validateWorkbasket(Workbasket workbasket) throws InvalidWorkbasketException, DomainNotFoundException { - // check that required properties (database not null) are set - if (workbasket.getId() == null || workbasket.getId().length() == 0) { - throw new InvalidWorkbasketException("Id must not be null for " + workbasket); - } else if (workbasket.getKey() == null || workbasket.getKey().length() == 0) { - throw new InvalidWorkbasketException("Key must not be null for " + workbasket); - } - if (workbasket.getName() == null || workbasket.getName().length() == 0) { - throw new InvalidWorkbasketException("Name must not be null for " + workbasket); - } - if (workbasket.getDomain() == null) { - throw new InvalidWorkbasketException("Domain must not be null for " + workbasket); - } - if (workbasket.getType() == null) { - throw new InvalidWorkbasketException("Type must not be null for " + workbasket); - } - if (!taskanaEngine.domainExists(workbasket.getDomain())) { - throw new DomainNotFoundException(workbasket.getDomain(), - "Domain " + workbasket.getDomain() + " does not exist in the configuration."); - } + if (workbasket.getDomain() == null) { + throw new InvalidWorkbasketException("Domain must not be null for " + workbasket); } - - private List getPermissionsFromWorkbasketAccessItem( - WorkbasketAccessItem workbasketAccessItem) { - List permissions = new ArrayList<>(); - if (workbasketAccessItem == null) { - return permissions; - } - if (workbasketAccessItem.isPermOpen()) { - permissions.add(WorkbasketPermission.OPEN); - } - if (workbasketAccessItem.isPermRead()) { - permissions.add(WorkbasketPermission.READ); - } - if (workbasketAccessItem.isPermAppend()) { - permissions.add(WorkbasketPermission.APPEND); - } - if (workbasketAccessItem.isPermTransfer()) { - permissions.add(WorkbasketPermission.TRANSFER); - } - if (workbasketAccessItem.isPermDistribute()) { - permissions.add(WorkbasketPermission.DISTRIBUTE); - } - if (workbasketAccessItem.isPermCustom1()) { - permissions.add(WorkbasketPermission.CUSTOM_1); - } - if (workbasketAccessItem.isPermCustom2()) { - permissions.add(WorkbasketPermission.CUSTOM_2); - } - if (workbasketAccessItem.isPermCustom3()) { - permissions.add(WorkbasketPermission.CUSTOM_3); - } - if (workbasketAccessItem.isPermCustom4()) { - permissions.add(WorkbasketPermission.CUSTOM_4); - } - if (workbasketAccessItem.isPermCustom5()) { - permissions.add(WorkbasketPermission.CUSTOM_5); - } - if (workbasketAccessItem.isPermCustom6()) { - permissions.add(WorkbasketPermission.CUSTOM_6); - } - if (workbasketAccessItem.isPermCustom7()) { - permissions.add(WorkbasketPermission.CUSTOM_7); - } - if (workbasketAccessItem.isPermCustom8()) { - permissions.add(WorkbasketPermission.CUSTOM_8); - } - if (workbasketAccessItem.isPermCustom9()) { - permissions.add(WorkbasketPermission.CUSTOM_9); - } - if (workbasketAccessItem.isPermCustom10()) { - permissions.add(WorkbasketPermission.CUSTOM_10); - } - if (workbasketAccessItem.isPermCustom11()) { - permissions.add(WorkbasketPermission.CUSTOM_11); - } - if (workbasketAccessItem.isPermCustom12()) { - permissions.add(WorkbasketPermission.CUSTOM_12); - } - return permissions; + if (workbasket.getType() == null) { + throw new InvalidWorkbasketException("Type must not be null for " + workbasket); } - - @Override - public Workbasket newWorkbasket(String key, String domain) { - WorkbasketImpl wb = new WorkbasketImpl(); - wb.setDomain(domain); - wb.setKey(key); - return wb; + if (!taskanaEngine.domainExists(workbasket.getDomain())) { + throw new DomainNotFoundException( + workbasket.getDomain(), + "Domain " + workbasket.getDomain() + " does not exist in the configuration."); } + } - @Override - public List getDistributionTargets(String workbasketId) - throws NotAuthorizedException, WorkbasketNotFoundException { - LOGGER.debug("entry to getDistributionTargets(workbasketId = {})", workbasketId); - List result = new ArrayList<>(); - try { - taskanaEngine.openConnection(); - // check that source workbasket exists - getWorkbasket(workbasketId); - if (!taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.BUSINESS_ADMIN)) { - checkAuthorization(workbasketId, WorkbasketPermission.READ); - } - List distributionTargets = workbasketMapper - .findDistributionTargets(workbasketId); - result.addAll(distributionTargets); - return result; - } finally { - taskanaEngine.returnConnection(); - if (LOGGER.isDebugEnabled()) { - int numberOfResultObjects = result.size(); - LOGGER.debug("exit from getDistributionTargets(workbasketId). Returning {} resulting Objects: {} ", - numberOfResultObjects, LoggerUtils.listToString(result)); - } - } + private List getPermissionsFromWorkbasketAccessItem( + WorkbasketAccessItem workbasketAccessItem) { + List permissions = new ArrayList<>(); + if (workbasketAccessItem == null) { + return permissions; } - - @Override - public List getDistributionTargets(String workbasketKey, String domain) - throws NotAuthorizedException, WorkbasketNotFoundException { - LOGGER.debug("entry to getDistributionTargets(workbasketKey = {}, domain = {})", workbasketKey, domain); - List result = new ArrayList<>(); - try { - taskanaEngine.openConnection(); - // check that source workbasket exists - Workbasket workbasket = getWorkbasket(workbasketKey, domain); - if (!taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.BUSINESS_ADMIN)) { - checkAuthorization(workbasket.getId(), WorkbasketPermission.READ); - } - List distributionTargets = workbasketMapper - .findDistributionTargets(workbasket.getId()); - result.addAll(distributionTargets); - return result; - } finally { - taskanaEngine.returnConnection(); - if (LOGGER.isDebugEnabled()) { - int numberOfResultObjects = result.size(); - LOGGER.debug("exit from getDistributionTargets(workbasketId). Returning {} resulting Objects: {} ", - numberOfResultObjects, LoggerUtils.listToString(result)); - } - } - + if (workbasketAccessItem.isPermOpen()) { + permissions.add(WorkbasketPermission.OPEN); } - - @Override - public List getDistributionSources(String workbasketId) - throws NotAuthorizedException, WorkbasketNotFoundException { - LOGGER.debug("entry to getDistributionSources(workbasketId = {})", workbasketId); - List result = new ArrayList<>(); - try { - taskanaEngine.openConnection(); - // check that source workbasket exists - getWorkbasket(workbasketId); - if (!taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.BUSINESS_ADMIN)) { - checkAuthorization(workbasketId, WorkbasketPermission.READ); - } - List distributionSources = workbasketMapper - .findDistributionSources(workbasketId); - result.addAll(distributionSources); - return result; - } finally { - taskanaEngine.returnConnection(); - if (LOGGER.isDebugEnabled()) { - int numberOfResultObjects = result.size(); - LOGGER.debug("exit from getDistributionSources(workbasketId). Returning {} resulting Objects: {} ", - numberOfResultObjects, LoggerUtils.listToString(result)); - } - } + if (workbasketAccessItem.isPermRead()) { + permissions.add(WorkbasketPermission.READ); } - - @Override - public List getDistributionSources(String workbasketKey, String domain) - throws NotAuthorizedException, WorkbasketNotFoundException { - LOGGER.debug("entry to getDistributionSources(workbasketKey = {}, domain = {})", workbasketKey, domain); - List result = new ArrayList<>(); - try { - taskanaEngine.openConnection(); - // check that source workbasket exists - Workbasket workbasket = getWorkbasket(workbasketKey, domain); - if (!taskanaEngine.getEngine().isUserInRole(TaskanaRole.ADMIN, TaskanaRole.BUSINESS_ADMIN)) { - checkAuthorization(workbasket.getId(), WorkbasketPermission.READ); - } - List distributionSources = workbasketMapper - .findDistributionSources(workbasket.getId()); - result.addAll(distributionSources); - return result; - } finally { - taskanaEngine.returnConnection(); - if (LOGGER.isDebugEnabled()) { - int numberOfResultObjects = result.size(); - LOGGER.debug("exit from getDistributionSources(workbasketId). Returning {} resulting Objects: {} ", - numberOfResultObjects, LoggerUtils.listToString(result)); - } - } + if (workbasketAccessItem.isPermAppend()) { + permissions.add(WorkbasketPermission.APPEND); } - - @Override - public void setDistributionTargets(String sourceWorkbasketId, List targetWorkbasketIds) - throws WorkbasketNotFoundException, NotAuthorizedException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("entry to setDistributionTargets(sourceWorkbasketId = {}, targetWorkazketIds = {})", - sourceWorkbasketId, - LoggerUtils.listToString(targetWorkbasketIds)); - } - taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); - try { - taskanaEngine.openConnection(); - // check existence of source workbasket - WorkbasketImpl sourceWorkbasket = (WorkbasketImpl) getWorkbasket(sourceWorkbasketId); - distributionTargetMapper.deleteAllDistributionTargetsBySourceId(sourceWorkbasketId); - - sourceWorkbasket.setModified(Instant.now()); - workbasketMapper.update(sourceWorkbasket); - - if (targetWorkbasketIds != null) { - for (String targetId : targetWorkbasketIds) { - // check for existence of target workbasket - getWorkbasket(targetId); - distributionTargetMapper.insert(sourceWorkbasketId, targetId); - LOGGER.debug( - "Method setDistributionTargets() created distributiontarget for source '{}' and target {}", - sourceWorkbasketId, targetId); - } - } - } finally { - taskanaEngine.returnConnection(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("setDistributionTargets set {} distribution targets to source workbasket {} ", - targetWorkbasketIds == null ? 0 : targetWorkbasketIds.size(), sourceWorkbasketId); - } - } - + if (workbasketAccessItem.isPermTransfer()) { + permissions.add(WorkbasketPermission.TRANSFER); } - - @Override - public void addDistributionTarget(String sourceWorkbasketId, String targetWorkbasketId) - throws NotAuthorizedException, WorkbasketNotFoundException { - LOGGER.debug("entry to addDistributionTarget(sourceWorkbasketId = {}, targetWorkbasketId = {})", - sourceWorkbasketId, targetWorkbasketId); - taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); - try { - taskanaEngine.openConnection(); - // check existence of source workbasket - WorkbasketImpl sourceWorkbasket = (WorkbasketImpl) getWorkbasket(sourceWorkbasketId); - // check existence of target workbasket - getWorkbasket(targetWorkbasketId); - // check whether the target is already set as target - int numOfDistTargets = distributionTargetMapper.getNumberOfDistributionTargets(sourceWorkbasketId, - targetWorkbasketId); - if (numOfDistTargets > 0) { - LOGGER.debug( - "addDistributionTarget detected that the specified distribution target exists already. Doing nothing..."); - } else { - distributionTargetMapper.insert(sourceWorkbasketId, targetWorkbasketId); - LOGGER.debug("addDistributionTarget inserted distribution target sourceId = {}, targetId = {}", - sourceWorkbasketId, targetWorkbasketId); - sourceWorkbasket.setModified(Instant.now()); - workbasketMapper.update(sourceWorkbasket); - } - - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from addDistributionTarget"); - } - + if (workbasketAccessItem.isPermDistribute()) { + permissions.add(WorkbasketPermission.DISTRIBUTE); } - - @Override - public void removeDistributionTarget(String sourceWorkbasketId, String targetWorkbasketId) - throws NotAuthorizedException { - LOGGER.debug("entry to removeDistributionTarget(sourceWorkbasketId = {}, targetWorkbasketId = {})", - sourceWorkbasketId, targetWorkbasketId); - taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); - try { - taskanaEngine.openConnection(); - // don't check existence of source / target workbasket to enable cleanup even if the db is corrupted - // check whether the target is set as target - int numberOfDistTargets = distributionTargetMapper.getNumberOfDistributionTargets(sourceWorkbasketId, - targetWorkbasketId); - if (numberOfDistTargets > 0) { - distributionTargetMapper.delete(sourceWorkbasketId, targetWorkbasketId); - LOGGER.debug("removeDistributionTarget deleted distribution target sourceId = {}, targetId = {}", - sourceWorkbasketId, targetWorkbasketId); - - try { - WorkbasketImpl sourceWorkbasket = (WorkbasketImpl) getWorkbasket(sourceWorkbasketId); - sourceWorkbasket.setModified(Instant.now()); - workbasketMapper.update(sourceWorkbasket); - } catch (WorkbasketNotFoundException e) { - LOGGER.debug( - "removeDistributionTarget found that the source workbasket {} doesn't exist. Ignoring the request... ", - sourceWorkbasketId); - } - - } else { - LOGGER.debug( - "removeDistributionTarget detected that the specified distribution target doesn't exist. Doing nothing..."); - } - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from addDistributionTarget"); - } + if (workbasketAccessItem.isPermCustom1()) { + permissions.add(WorkbasketPermission.CUSTOM_1); } - - @Override - public boolean deleteWorkbasket(String workbasketId) - throws NotAuthorizedException, WorkbasketNotFoundException, WorkbasketInUseException, InvalidArgumentException { - LOGGER.debug("entry to deleteWorkbasket(workbasketId = {})", workbasketId); - taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); - - try { - taskanaEngine.openConnection(); - if (workbasketId == null || workbasketId.isEmpty()) { - throw new InvalidArgumentException("The WorkbasketId can´t be NULL or EMPTY for deleteWorkbasket()"); - } - - // check if the workbasket does exist and is empty (Task) - this.getWorkbasket(workbasketId); - - long numTasksNotCompletedInWorkbasket = taskanaEngine.getEngine().getTaskService() - .createTaskQuery() - .workbasketIdIn(workbasketId) - .stateNotIn( - TaskState.COMPLETED) - .count(); - - if (numTasksNotCompletedInWorkbasket > 0) { - throw new WorkbasketInUseException( - "Workbasket " + workbasketId + " contains non-completed tasks and can´t be marked for deletion."); - } - - long numTasksInWorkbasket = taskanaEngine.getEngine().getTaskService() - .createTaskQuery() - .workbasketIdIn(workbasketId) - .count(); - - if (numTasksInWorkbasket == 0) { - workbasketMapper.delete(workbasketId); - deleteReferencesToWorkbasket(workbasketId); - return true; - } else { - markWorkbasketForDeletion(workbasketId); - return false; - } - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from deleteWorkbasket(workbasketId = {})", workbasketId); - } + if (workbasketAccessItem.isPermCustom2()) { + permissions.add(WorkbasketPermission.CUSTOM_2); } - - private void markWorkbasketForDeletion(String workbasketId) - throws NotAuthorizedException, InvalidArgumentException { - LOGGER.debug("entry to markWorkbasketForDeletion(workbasketId = {})", workbasketId); - taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); - try { - taskanaEngine.openConnection(); - - if (workbasketId == null || workbasketId.isEmpty()) { - throw new InvalidArgumentException( - "The WorkbasketId can´t be NULL or EMPTY for markWorkbasketForDeletion()"); - } - WorkbasketImpl workbasket = workbasketMapper.findById(workbasketId); - workbasket.setMarkedForDeletion(true); - workbasketMapper.update(workbasket); - } finally { - taskanaEngine.returnConnection(); - LOGGER.debug("exit from markWorkbasketForDeletion(workbasketId = {}).", workbasketId); - } + if (workbasketAccessItem.isPermCustom3()) { + permissions.add(WorkbasketPermission.CUSTOM_3); } - - public BulkOperationResults deleteWorkbaskets(List workbasketsIds) - throws NotAuthorizedException, InvalidArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("entry to deleteWorkbaskets(workbasketId = {})", LoggerUtils.listToString(workbasketsIds)); - } - - taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); - - try { - taskanaEngine.openConnection(); - if (workbasketsIds == null || workbasketsIds.isEmpty()) { - throw new InvalidArgumentException("List of WorkbasketIds must not be null."); - } - BulkOperationResults bulkLog = new BulkOperationResults<>(); - - Iterator iterator = workbasketsIds.iterator(); - String workbasketIdForDeleting = null; - while (iterator.hasNext()) { - try { - workbasketIdForDeleting = iterator.next(); - if (!deleteWorkbasket(workbasketIdForDeleting)) { - bulkLog.addError(workbasketIdForDeleting, new WorkbasketInUseException( - "Workbasket with id " + workbasketIdForDeleting - + " contains completed tasks not deleted and will not be deleted.")); - } - } catch (WorkbasketInUseException ex) { - bulkLog.addError(workbasketIdForDeleting, new WorkbasketInUseException( - "Workbasket with id " + workbasketIdForDeleting + " is in use and will not be deleted.")); - } catch (TaskanaException ex) { - bulkLog.addError(workbasketIdForDeleting, new TaskanaException( - "Workbasket with id " + workbasketIdForDeleting - + " Throw an exception and couldn't be deleted.")); - } - } - return bulkLog; - } finally { - LOGGER.debug("exit from deleteWorkbaskets()"); - taskanaEngine.returnConnection(); - } + if (workbasketAccessItem.isPermCustom4()) { + permissions.add(WorkbasketPermission.CUSTOM_4); } - - @Override - public WorkbasketAccessItemQuery createWorkbasketAccessItemQuery() throws NotAuthorizedException { - taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.ADMIN, TaskanaRole.BUSINESS_ADMIN); - return new WorkbasketAccessItemQueryImpl(this.taskanaEngine); + if (workbasketAccessItem.isPermCustom5()) { + permissions.add(WorkbasketPermission.CUSTOM_5); } - - private void deleteReferencesToWorkbasket(String workbasketId) { - // deletes sub-tables workbasket references - distributionTargetMapper.deleteAllDistributionTargetsBySourceId(workbasketId); - distributionTargetMapper.deleteAllDistributionTargetsByTargetId(workbasketId); - workbasketAccessMapper.deleteAllAccessItemsForWorkbasketId(workbasketId); + if (workbasketAccessItem.isPermCustom6()) { + permissions.add(WorkbasketPermission.CUSTOM_6); } + if (workbasketAccessItem.isPermCustom7()) { + permissions.add(WorkbasketPermission.CUSTOM_7); + } + if (workbasketAccessItem.isPermCustom8()) { + permissions.add(WorkbasketPermission.CUSTOM_8); + } + if (workbasketAccessItem.isPermCustom9()) { + permissions.add(WorkbasketPermission.CUSTOM_9); + } + if (workbasketAccessItem.isPermCustom10()) { + permissions.add(WorkbasketPermission.CUSTOM_10); + } + if (workbasketAccessItem.isPermCustom11()) { + permissions.add(WorkbasketPermission.CUSTOM_11); + } + if (workbasketAccessItem.isPermCustom12()) { + permissions.add(WorkbasketPermission.CUSTOM_12); + } + return permissions; + } + private void markWorkbasketForDeletion(String workbasketId) + throws NotAuthorizedException, InvalidArgumentException { + LOGGER.debug("entry to markWorkbasketForDeletion(workbasketId = {})", workbasketId); + taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.BUSINESS_ADMIN, TaskanaRole.ADMIN); + try { + taskanaEngine.openConnection(); + + if (workbasketId == null || workbasketId.isEmpty()) { + throw new InvalidArgumentException( + "The WorkbasketId can´t be NULL or EMPTY for markWorkbasketForDeletion()"); + } + WorkbasketImpl workbasket = workbasketMapper.findById(workbasketId); + workbasket.setMarkedForDeletion(true); + workbasketMapper.update(workbasket); + } finally { + taskanaEngine.returnConnection(); + LOGGER.debug("exit from markWorkbasketForDeletion(workbasketId = {}).", workbasketId); + } + } + + private void deleteReferencesToWorkbasket(String workbasketId) { + // deletes sub-tables workbasket references + distributionTargetMapper.deleteAllDistributionTargetsBySourceId(workbasketId); + distributionTargetMapper.deleteAllDistributionTargetsByTargetId(workbasketId); + workbasketAccessMapper.deleteAllAccessItemsForWorkbasketId(workbasketId); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketSummaryImpl.java b/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketSummaryImpl.java index 3d140a9b0..9e4aa1ec0 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketSummaryImpl.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/WorkbasketSummaryImpl.java @@ -3,384 +3,408 @@ package pro.taskana.impl; import pro.taskana.WorkbasketSummary; import pro.taskana.WorkbasketType; -/** - * This entity contains the most important information about a workbasket. - */ +/** This entity contains the most important information about a workbasket. */ public class WorkbasketSummaryImpl implements WorkbasketSummary { - private String id; - private String key; - private String name; - private String description; - private String owner; - private String domain; - private WorkbasketType type; - private String custom1; - private String custom2; - private String custom3; - private String custom4; - private String orgLevel1; - private String orgLevel2; - private String orgLevel3; - private String orgLevel4; - private boolean markedForDeletion; + private String id; + private String key; + private String name; + private String description; + private String owner; + private String domain; + private WorkbasketType type; + private String custom1; + private String custom2; + private String custom3; + private String custom4; + private String orgLevel1; + private String orgLevel2; + private String orgLevel3; + private String orgLevel4; + private boolean markedForDeletion; - WorkbasketSummaryImpl() { + WorkbasketSummaryImpl() {} + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketSummary#getId() + */ + @Override + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketSummary#getKey() + */ + @Override + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketSummary#getName() + */ + @Override + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketSummary#getDescription() + */ + @Override + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketSummary#getOwner() + */ + @Override + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketSummary#getDomain() + */ + @Override + public String getDomain() { + return domain; + } + + public void setDomain(String domain) { + this.domain = domain; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketSummary#getType() + */ + @Override + public WorkbasketType getType() { + return type; + } + + public void setType(WorkbasketType type) { + this.type = type; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketSummary#getCustom1() + */ + @Override + public String getCustom1() { + return custom1; + } + + public void setCustom1(String custom1) { + this.custom1 = custom1; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketSummary#getCustom2() + */ + @Override + public String getCustom2() { + return custom2; + } + + public void setCustom2(String custom2) { + this.custom2 = custom2; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketSummary#getCustom3() + */ + @Override + public String getCustom3() { + return custom3; + } + + public void setCustom3(String custom3) { + this.custom3 = custom3; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketSummary#getCustom4() + */ + @Override + public String getCustom4() { + return custom4; + } + + public void setCustom4(String custom4) { + this.custom4 = custom4; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketSummary#getOrgLevel1() + */ + @Override + public String getOrgLevel1() { + return orgLevel1; + } + + public void setOrgLevel1(String orgLevel1) { + this.orgLevel1 = orgLevel1; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketSummary#getOrgLevel2() + */ + @Override + public String getOrgLevel2() { + return orgLevel2; + } + + public void setOrgLevel2(String orgLevel2) { + this.orgLevel2 = orgLevel2; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketSummary#getOrgLevel3() + */ + @Override + public String getOrgLevel3() { + return orgLevel3; + } + + public void setOrgLevel3(String orgLevel3) { + this.orgLevel3 = orgLevel3; + } + + /* + * (non-Javadoc) + * @see pro.taskana.impl.WorkbasketSummary#getOrgLevel4() + */ + @Override + public String getOrgLevel4() { + return orgLevel4; + } + + public void setOrgLevel4(String orgLevel4) { + this.orgLevel4 = orgLevel4; + } + + @Override + public boolean isMarkedForDeletion() { + return markedForDeletion; + } + + public void setMarkedForDeletion(boolean markedForDeletion) { + this.markedForDeletion = markedForDeletion; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((custom1 == null) ? 0 : custom1.hashCode()); + result = prime * result + ((custom2 == null) ? 0 : custom2.hashCode()); + result = prime * result + ((custom3 == null) ? 0 : custom3.hashCode()); + result = prime * result + ((custom4 == null) ? 0 : custom4.hashCode()); + result = prime * result + ((description == null) ? 0 : description.hashCode()); + result = prime * result + ((domain == null) ? 0 : domain.hashCode()); + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((key == null) ? 0 : key.hashCode()); + result = prime * result + (markedForDeletion ? 1231 : 1237); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((orgLevel1 == null) ? 0 : orgLevel1.hashCode()); + result = prime * result + ((orgLevel2 == null) ? 0 : orgLevel2.hashCode()); + result = prime * result + ((orgLevel3 == null) ? 0 : orgLevel3.hashCode()); + result = prime * result + ((orgLevel4 == null) ? 0 : orgLevel4.hashCode()); + result = prime * result + ((owner == null) ? 0 : owner.hashCode()); + result = prime * result + ((type == null) ? 0 : type.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketSummary#getId() - */ - @Override - public String getId() { - return id; + if (obj == null) { + return false; } - - public void setId(String id) { - this.id = id; + if (!getClass().isAssignableFrom(obj.getClass())) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketSummary#getKey() - */ - @Override - public String getKey() { - return key; + WorkbasketSummaryImpl other = (WorkbasketSummaryImpl) obj; + if (custom1 == null) { + if (other.custom1 != null) { + return false; + } + } else if (!custom1.equals(other.custom1)) { + return false; } - - public void setKey(String key) { - this.key = key; + if (custom2 == null) { + if (other.custom2 != null) { + return false; + } + } else if (!custom2.equals(other.custom2)) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketSummary#getName() - */ - @Override - public String getName() { - return name; + if (custom3 == null) { + if (other.custom3 != null) { + return false; + } + } else if (!custom3.equals(other.custom3)) { + return false; } - - public void setName(String name) { - this.name = name; + if (custom4 == null) { + if (other.custom4 != null) { + return false; + } + } else if (!custom4.equals(other.custom4)) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketSummary#getDescription() - */ - @Override - public String getDescription() { - return description; + if (description == null) { + if (other.description != null) { + return false; + } + } else if (!description.equals(other.description)) { + return false; } - - public void setDescription(String description) { - this.description = description; + if (domain == null) { + if (other.domain != null) { + return false; + } + } else if (!domain.equals(other.domain)) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketSummary#getOwner() - */ - @Override - public String getOwner() { - return owner; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; } - - public void setOwner(String owner) { - this.owner = owner; + if (key == null) { + if (other.key != null) { + return false; + } + } else if (!key.equals(other.key)) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketSummary#getDomain() - */ - @Override - public String getDomain() { - return domain; + if (markedForDeletion != other.markedForDeletion) { + return false; } - - public void setDomain(String domain) { - this.domain = domain; + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketSummary#getType() - */ - @Override - public WorkbasketType getType() { - return type; + if (orgLevel1 == null) { + if (other.orgLevel1 != null) { + return false; + } + } else if (!orgLevel1.equals(other.orgLevel1)) { + return false; } - - public void setType(WorkbasketType type) { - this.type = type; + if (orgLevel2 == null) { + if (other.orgLevel2 != null) { + return false; + } + } else if (!orgLevel2.equals(other.orgLevel2)) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketSummary#getCustom1() - */ - @Override - public String getCustom1() { - return custom1; + if (orgLevel3 == null) { + if (other.orgLevel3 != null) { + return false; + } + } else if (!orgLevel3.equals(other.orgLevel3)) { + return false; } - - public void setCustom1(String custom1) { - this.custom1 = custom1; + if (orgLevel4 == null) { + if (other.orgLevel4 != null) { + return false; + } + } else if (!orgLevel4.equals(other.orgLevel4)) { + return false; } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketSummary#getCustom2() - */ - @Override - public String getCustom2() { - return custom2; + if (owner == null) { + if (other.owner != null) { + return false; + } + } else if (!owner.equals(other.owner)) { + return false; } - - public void setCustom2(String custom2) { - this.custom2 = custom2; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketSummary#getCustom3() - */ - @Override - public String getCustom3() { - return custom3; - } - - public void setCustom3(String custom3) { - this.custom3 = custom3; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketSummary#getCustom4() - */ - @Override - public String getCustom4() { - return custom4; - } - - public void setCustom4(String custom4) { - this.custom4 = custom4; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketSummary#getOrgLevel1() - */ - @Override - public String getOrgLevel1() { - return orgLevel1; - } - - public void setOrgLevel1(String orgLevel1) { - this.orgLevel1 = orgLevel1; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketSummary#getOrgLevel2() - */ - @Override - public String getOrgLevel2() { - return orgLevel2; - } - - public void setOrgLevel2(String orgLevel2) { - this.orgLevel2 = orgLevel2; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketSummary#getOrgLevel3() - */ - @Override - public String getOrgLevel3() { - return orgLevel3; - } - - public void setOrgLevel3(String orgLevel3) { - this.orgLevel3 = orgLevel3; - } - - /* - * (non-Javadoc) - * @see pro.taskana.impl.WorkbasketSummary#getOrgLevel4() - */ - @Override - public String getOrgLevel4() { - return orgLevel4; - } - - public void setOrgLevel4(String orgLevel4) { - this.orgLevel4 = orgLevel4; - } - - @Override - public boolean isMarkedForDeletion() { - return markedForDeletion; - } - - public void setMarkedForDeletion(boolean markedForDeletion) { - this.markedForDeletion = markedForDeletion; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((custom1 == null) ? 0 : custom1.hashCode()); - result = prime * result + ((custom2 == null) ? 0 : custom2.hashCode()); - result = prime * result + ((custom3 == null) ? 0 : custom3.hashCode()); - result = prime * result + ((custom4 == null) ? 0 : custom4.hashCode()); - result = prime * result + ((description == null) ? 0 : description.hashCode()); - result = prime * result + ((domain == null) ? 0 : domain.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((key == null) ? 0 : key.hashCode()); - result = prime * result + (markedForDeletion ? 1231 : 1237); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((orgLevel1 == null) ? 0 : orgLevel1.hashCode()); - result = prime * result + ((orgLevel2 == null) ? 0 : orgLevel2.hashCode()); - result = prime * result + ((orgLevel3 == null) ? 0 : orgLevel3.hashCode()); - result = prime * result + ((orgLevel4 == null) ? 0 : orgLevel4.hashCode()); - result = prime * result + ((owner == null) ? 0 : owner.hashCode()); - result = prime * result + ((type == null) ? 0 : type.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!getClass().isAssignableFrom(obj.getClass())) { - return false; - } - WorkbasketSummaryImpl other = (WorkbasketSummaryImpl) obj; - if (custom1 == null) { - if (other.custom1 != null) { - return false; - } - } else if (!custom1.equals(other.custom1)) { - return false; - } - if (custom2 == null) { - if (other.custom2 != null) { - return false; - } - } else if (!custom2.equals(other.custom2)) { - return false; - } - if (custom3 == null) { - if (other.custom3 != null) { - return false; - } - } else if (!custom3.equals(other.custom3)) { - return false; - } - if (custom4 == null) { - if (other.custom4 != null) { - return false; - } - } else if (!custom4.equals(other.custom4)) { - return false; - } - if (description == null) { - if (other.description != null) { - return false; - } - } else if (!description.equals(other.description)) { - return false; - } - if (domain == null) { - if (other.domain != null) { - return false; - } - } else if (!domain.equals(other.domain)) { - return false; - } - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (key == null) { - if (other.key != null) { - return false; - } - } else if (!key.equals(other.key)) { - return false; - } - if (markedForDeletion != other.markedForDeletion) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - if (orgLevel1 == null) { - if (other.orgLevel1 != null) { - return false; - } - } else if (!orgLevel1.equals(other.orgLevel1)) { - return false; - } - if (orgLevel2 == null) { - if (other.orgLevel2 != null) { - return false; - } - } else if (!orgLevel2.equals(other.orgLevel2)) { - return false; - } - if (orgLevel3 == null) { - if (other.orgLevel3 != null) { - return false; - } - } else if (!orgLevel3.equals(other.orgLevel3)) { - return false; - } - if (orgLevel4 == null) { - if (other.orgLevel4 != null) { - return false; - } - } else if (!orgLevel4.equals(other.orgLevel4)) { - return false; - } - if (owner == null) { - if (other.owner != null) { - return false; - } - } else if (!owner.equals(other.owner)) { - return false; - } - if (type != other.type) { - return false; - } - return true; - } - - @Override - public String toString() { - return "WorkbasketSummaryImpl [id=" + id + ", key=" + key + ", name=" + name + ", description=" + description - + ", owner=" + owner + ", domain=" + domain + ", type=" + type + ", custom1=" + custom1 + ", custom2=" - + custom2 + ", custom3=" + custom3 + ", custom4=" + custom4 + ", orgLevel1=" + orgLevel1 + ", orgLevel2=" - + orgLevel2 + ", orgLevel3=" + orgLevel3 + ", orgLevel4=" + orgLevel4 + ", markedForDeletion=" - + markedForDeletion + "]"; + if (type != other.type) { + return false; } + return true; + } + @Override + public String toString() { + return "WorkbasketSummaryImpl [id=" + + id + + ", key=" + + key + + ", name=" + + name + + ", description=" + + description + + ", owner=" + + owner + + ", domain=" + + domain + + ", type=" + + type + + ", custom1=" + + custom1 + + ", custom2=" + + custom2 + + ", custom3=" + + custom3 + + ", custom4=" + + custom4 + + ", orgLevel1=" + + orgLevel1 + + ", orgLevel2=" + + orgLevel2 + + ", orgLevel3=" + + orgLevel3 + + ", orgLevel4=" + + orgLevel4 + + ", markedForDeletion=" + + markedForDeletion + + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/persistence/MapTypeHandler.java b/lib/taskana-core/src/main/java/pro/taskana/impl/persistence/MapTypeHandler.java index c4ee3f71b..7c4d0bea9 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/persistence/MapTypeHandler.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/persistence/MapTypeHandler.java @@ -6,7 +6,6 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.Map; - import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.JdbcType; import org.json.JSONObject; @@ -21,50 +20,50 @@ import org.slf4j.LoggerFactory; @SuppressWarnings("rawtypes") public class MapTypeHandler extends BaseTypeHandler { - private static final Logger LOGGER = LoggerFactory.getLogger(MapTypeHandler.class); + private static final Logger LOGGER = LoggerFactory.getLogger(MapTypeHandler.class); - @Override - public void setNonNullParameter(PreparedStatement ps, int i, Map parameter, JdbcType jdbcType) throws SQLException { - if (parameter != null && parameter.size() > 0) { - LOGGER.debug("Input-Map before serializing: ", parameter); - // Convert Map to JSON string - JSONObject jsonObj = new JSONObject(parameter); - ps.setString(i, jsonObj.toString()); - } else { - ps.setNull(i, Types.BLOB); - } + @Override + public void setNonNullParameter(PreparedStatement ps, int i, Map parameter, JdbcType jdbcType) + throws SQLException { + if (parameter != null && parameter.size() > 0) { + LOGGER.debug("Input-Map before serializing: ", parameter); + // Convert Map to JSON string + JSONObject jsonObj = new JSONObject(parameter); + ps.setString(i, jsonObj.toString()); + } else { + ps.setNull(i, Types.BLOB); } + } - @Override - public Map getNullableResult(ResultSet rs, String columnName) throws SQLException { - String fieldValue = rs.getString(columnName); - if (fieldValue != null) { - return convertToMap(fieldValue); - } - return null; + @Override + public Map getNullableResult(ResultSet rs, String columnName) throws SQLException { + String fieldValue = rs.getString(columnName); + if (fieldValue != null) { + return convertToMap(fieldValue); } + return null; + } - @Override - public Map getNullableResult(ResultSet rs, int columnIndex) throws SQLException { - String fieldValue = rs.getString(columnIndex); - if (fieldValue != null) { - return convertToMap(fieldValue); - } - return null; + @Override + public Map getNullableResult(ResultSet rs, int columnIndex) throws SQLException { + String fieldValue = rs.getString(columnIndex); + if (fieldValue != null) { + return convertToMap(fieldValue); } + return null; + } - @Override - public Map getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { - String fieldValue = cs.getString(columnIndex); - if (fieldValue != null) { - return convertToMap(fieldValue); - } - return null; - } - - private Map convertToMap(String fieldValue) { - JSONObject jsonObj = new JSONObject(fieldValue); - return jsonObj.toMap(); + @Override + public Map getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { + String fieldValue = cs.getString(columnIndex); + if (fieldValue != null) { + return convertToMap(fieldValue); } + return null; + } + private Map convertToMap(String fieldValue) { + JSONObject jsonObj = new JSONObject(fieldValue); + return jsonObj.toMap(); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/report/CombinedClassificationFilter.java b/lib/taskana-core/src/main/java/pro/taskana/impl/report/CombinedClassificationFilter.java index d7fc4c98e..c2251af59 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/report/CombinedClassificationFilter.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/report/CombinedClassificationFilter.java @@ -1,44 +1,48 @@ package pro.taskana.impl.report; /** - * The CombinedClassificationFilter is a pair of a classificationId for a task and a classificationId for the - * corresponding attachment that is used to filter the {@link pro.taskana.report.WorkbasketReport} by the classification of the attachment. - * To filter by the classification of the task, the classificationId of the attachment should be null. + * The CombinedClassificationFilter is a pair of a classificationId for a task and a + * classificationId for the corresponding attachment that is used to filter the {@link + * pro.taskana.report.WorkbasketReport} by the classification of the attachment. To filter by the + * classification of the task, the classificationId of the attachment should be null. */ public class CombinedClassificationFilter { - private String taskClassificationId; - private String attachmentClassificationId; + private String taskClassificationId; + private String attachmentClassificationId; - public CombinedClassificationFilter(String taskClassificationId) { - this.taskClassificationId = taskClassificationId; - } + public CombinedClassificationFilter(String taskClassificationId) { + this.taskClassificationId = taskClassificationId; + } - public CombinedClassificationFilter(String taskClassificationId, String attachmentClassificationId) { - this.taskClassificationId = taskClassificationId; - this.attachmentClassificationId = attachmentClassificationId; - } + public CombinedClassificationFilter( + String taskClassificationId, String attachmentClassificationId) { + this.taskClassificationId = taskClassificationId; + this.attachmentClassificationId = attachmentClassificationId; + } - public String getTaskClassificationId() { - return this.taskClassificationId; - } + public String getTaskClassificationId() { + return this.taskClassificationId; + } - public void setTaskClassificationId(String taskClassificationId) { - this.taskClassificationId = taskClassificationId; - } + public void setTaskClassificationId(String taskClassificationId) { + this.taskClassificationId = taskClassificationId; + } - public String getAttachmentClassificationId() { - return this.attachmentClassificationId; - } + public String getAttachmentClassificationId() { + return this.attachmentClassificationId; + } - public void setAttachmentClassificationId(String attachmentClassificationId) { - this.attachmentClassificationId = attachmentClassificationId; - } - - @Override - public String toString() { - return "CombinedClassificationFilter [taskClassificationId=" + taskClassificationId - + ", attachmentClassificationId=" + attachmentClassificationId + "]"; - } + public void setAttachmentClassificationId(String attachmentClassificationId) { + this.attachmentClassificationId = attachmentClassificationId; + } + @Override + public String toString() { + return "CombinedClassificationFilter [taskClassificationId=" + + taskClassificationId + + ", attachmentClassificationId=" + + attachmentClassificationId + + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/report/header/TaskStatusColumnHeader.java b/lib/taskana-core/src/main/java/pro/taskana/impl/report/header/TaskStatusColumnHeader.java index 4afa88c1c..e2d7b398c 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/report/header/TaskStatusColumnHeader.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/report/header/TaskStatusColumnHeader.java @@ -4,29 +4,27 @@ import pro.taskana.TaskState; import pro.taskana.impl.report.item.TaskQueryItem; import pro.taskana.impl.report.structure.ColumnHeader; -/** - * The TaskStatusColumnHeader represents a column for each {@link TaskState}. - */ +/** The TaskStatusColumnHeader represents a column for each {@link TaskState}. */ public class TaskStatusColumnHeader implements ColumnHeader { - private TaskState state; + private TaskState state; - public TaskStatusColumnHeader(TaskState state) { - this.state = state; - } + public TaskStatusColumnHeader(TaskState state) { + this.state = state; + } - @Override - public String getDisplayName() { - return this.state.name(); - } + @Override + public String getDisplayName() { + return this.state.name(); + } - @Override - public boolean fits(TaskQueryItem item) { - return item.getState() == this.state; - } + @Override + public boolean fits(TaskQueryItem item) { + return item.getState() == this.state; + } - @Override - public String toString() { - return getDisplayName(); - } + @Override + public String toString() { + return getDisplayName(); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/report/header/TimeIntervalColumnHeader.java b/lib/taskana-core/src/main/java/pro/taskana/impl/report/header/TimeIntervalColumnHeader.java index e424130f9..22003297c 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/report/header/TimeIntervalColumnHeader.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/report/header/TimeIntervalColumnHeader.java @@ -9,117 +9,114 @@ import pro.taskana.impl.report.item.AgeQueryItem; import pro.taskana.impl.report.structure.ColumnHeader; /** - * A TimeIntervalColumnHeader has a lower and an upper age limit which subdivide the count of tasks into different - * sections. Days in past are represented as negative values and days in the future are represented as positive values. - * To avoid tasks are counted multiple times or not be listed in the report, these TimeIntervalColumnHeaders should not - * overlap and should not have gaps. If the TimeIntervalColumnHeader should represent a single day, lowerAgeLimit and - * upperAgeLimit have to be equal. The outer cluster of a report should have open ends. These open ends are represented + * A TimeIntervalColumnHeader has a lower and an upper age limit which subdivide the count of tasks + * into different sections. Days in past are represented as negative values and days in the future + * are represented as positive values. To avoid tasks are counted multiple times or not be listed in + * the report, these TimeIntervalColumnHeaders should not overlap and should not have gaps. If the + * TimeIntervalColumnHeader should represent a single day, lowerAgeLimit and upperAgeLimit have to + * be equal. The outer cluster of a report should have open ends. These open ends are represented * with Integer.MIN_VALUE and Integer.MAX_VALUE. */ public class TimeIntervalColumnHeader implements ColumnHeader { - private final int lowerAgeLimit; - private final int upperAgeLimit; + private final int lowerAgeLimit; + private final int upperAgeLimit; - public TimeIntervalColumnHeader(int ageInDays) { - this.lowerAgeLimit = ageInDays; - this.upperAgeLimit = ageInDays; + public TimeIntervalColumnHeader(int ageInDays) { + this.lowerAgeLimit = ageInDays; + this.upperAgeLimit = ageInDays; + } + + public TimeIntervalColumnHeader(int lowerAgeLimit, int upperAgeLimit) { + this.lowerAgeLimit = lowerAgeLimit; + this.upperAgeLimit = upperAgeLimit; + } + + public static int getSmallestUpperLimit(List columnHeaders) { + return columnHeaders.stream() + .mapToInt(TimeIntervalColumnHeader::getUpperAgeLimit) + .filter(i -> i < 0) + .min() + .orElse(0); + } + + public static int getLargestLowerLimit(List columnHeaders) { + int greatestLowerLimit = 0; + for (TimeIntervalColumnHeader columnHeader : columnHeaders) { + if (columnHeader.getUpperAgeLimit() > greatestLowerLimit) { + greatestLowerLimit = columnHeader.getLowerAgeLimit(); + } } + return greatestLowerLimit; + } - public TimeIntervalColumnHeader(int lowerAgeLimit, int upperAgeLimit) { - this.lowerAgeLimit = lowerAgeLimit; - this.upperAgeLimit = upperAgeLimit; - } + public int getLowerAgeLimit() { + return lowerAgeLimit; + } - public static int getSmallestUpperLimit(List columnHeaders) { - return columnHeaders.stream() - .mapToInt(TimeIntervalColumnHeader::getUpperAgeLimit) - .filter(i -> i < 0) - .min() - .orElse(0); - } + public int getUpperAgeLimit() { + return upperAgeLimit; + } - public static int getLargestLowerLimit(List columnHeaders) { - int greatestLowerLimit = 0; - for (TimeIntervalColumnHeader columnHeader : columnHeaders) { - if (columnHeader.getUpperAgeLimit() > greatestLowerLimit) { - greatestLowerLimit = columnHeader.getLowerAgeLimit(); - } - } - return greatestLowerLimit; - } + @Override + public String getDisplayName() { + return "(" + this.lowerAgeLimit + "," + this.upperAgeLimit + ")"; + } - public int getLowerAgeLimit() { - return lowerAgeLimit; - } + @Override + public boolean fits(AgeQueryItem item) { + return lowerAgeLimit <= item.getAgeInDays() && upperAgeLimit >= item.getAgeInDays(); + } - public int getUpperAgeLimit() { - return upperAgeLimit; - } + @Override + public String toString() { + return getDisplayName(); + } - @Override - public String toString() { - return getDisplayName(); + /** for Date representation. */ + public static class Date extends TimeIntervalColumnHeader { + + public Date(int ageInDays) { + super(ageInDays); } @Override public String getDisplayName() { - return "(" + this.lowerAgeLimit + "," + this.upperAgeLimit + ")"; + LocalDateTime ldt = LocalDateTime.now().plusDays(getLowerAgeLimit()); + DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH); + return dateFormat.format(ldt); + } + } + + /** For representation of Range. */ + public static class Range extends TimeIntervalColumnHeader { + + public Range(int ageInDays) { + super(ageInDays); + } + + public Range(int lowerAgeLimit, int upperAgeLimit) { + super(lowerAgeLimit, upperAgeLimit); } @Override - public boolean fits(AgeQueryItem item) { - return lowerAgeLimit <= item.getAgeInDays() && upperAgeLimit >= item.getAgeInDays(); - } - - /** - * for Date representation. - */ - public static class Date extends TimeIntervalColumnHeader { - - public Date(int ageInDays) { - super(ageInDays); - } - - @Override - public String getDisplayName() { - LocalDateTime ldt = LocalDateTime.now().plusDays(getLowerAgeLimit()); - DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH); - return dateFormat.format(ldt); - } - } - - /** - * For representation of Range. - */ - public static class Range extends TimeIntervalColumnHeader { - - public Range(int ageInDays) { - super(ageInDays); - } - - public Range(int lowerAgeLimit, int upperAgeLimit) { - super(lowerAgeLimit, upperAgeLimit); - } - - @Override - public String getDisplayName() { - if (this.getLowerAgeLimit() == Integer.MIN_VALUE) { - return "<" + this.getUpperAgeLimit(); - } else if (this.getUpperAgeLimit() == Integer.MAX_VALUE) { - return ">" + this.getLowerAgeLimit(); - } else if (this.getLowerAgeLimit() == -1) { - return "-1 day"; - } else if (this.getLowerAgeLimit() == 1) { - return "+1 day"; - } else if (this.getLowerAgeLimit() == 0) { - return "today"; - } else if (this.getLowerAgeLimit() == this.getUpperAgeLimit()) { - return this.getUpperAgeLimit() + ""; - } else if (this.getLowerAgeLimit() != this.getUpperAgeLimit()) { - return "[" + this.getLowerAgeLimit() + " ... " + this.getUpperAgeLimit() + "]"; - } - return super.getDisplayName(); - } + public String getDisplayName() { + if (this.getLowerAgeLimit() == Integer.MIN_VALUE) { + return "<" + this.getUpperAgeLimit(); + } else if (this.getUpperAgeLimit() == Integer.MAX_VALUE) { + return ">" + this.getLowerAgeLimit(); + } else if (this.getLowerAgeLimit() == -1) { + return "-1 day"; + } else if (this.getLowerAgeLimit() == 1) { + return "+1 day"; + } else if (this.getLowerAgeLimit() == 0) { + return "today"; + } else if (this.getLowerAgeLimit() == this.getUpperAgeLimit()) { + return this.getUpperAgeLimit() + ""; + } else if (this.getLowerAgeLimit() != this.getUpperAgeLimit()) { + return "[" + this.getLowerAgeLimit() + " ... " + this.getUpperAgeLimit() + "]"; + } + return super.getDisplayName(); } + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/report/item/AgeQueryItem.java b/lib/taskana-core/src/main/java/pro/taskana/impl/report/item/AgeQueryItem.java index 390b398a5..24a0b85f1 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/report/item/AgeQueryItem.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/report/item/AgeQueryItem.java @@ -3,12 +3,12 @@ package pro.taskana.impl.report.item; import pro.taskana.impl.report.structure.QueryItem; /** - * The MonitorQueryItem entity contains the number of tasks for a key (e.g. workbasketKey) and age in days. + * The MonitorQueryItem entity contains the number of tasks for a key (e.g. workbasketKey) and age + * in days. */ public interface AgeQueryItem extends QueryItem { - int getAgeInDays(); - - void setAgeInDays(int ageInDays); + int getAgeInDays(); + void setAgeInDays(int ageInDays); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/report/item/DetailedMonitorQueryItem.java b/lib/taskana-core/src/main/java/pro/taskana/impl/report/item/DetailedMonitorQueryItem.java index aa5affb18..cf7360abb 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/report/item/DetailedMonitorQueryItem.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/report/item/DetailedMonitorQueryItem.java @@ -1,24 +1,23 @@ package pro.taskana.impl.report.item; /** - * The DetailedMonitorQueryItem extends the {@link MonitorQueryItem}. - * The additional attachment key is used for the detailed classification report. + * The DetailedMonitorQueryItem extends the {@link MonitorQueryItem}. The additional attachment key + * is used for the detailed classification report. */ public class DetailedMonitorQueryItem extends MonitorQueryItem { - private String attachmentKey; + private String attachmentKey; - public String getAttachmentKey() { - return attachmentKey; - } + public String getAttachmentKey() { + return attachmentKey; + } - public void setAttachmentKey(String attachmentKey) { - this.attachmentKey = attachmentKey; - } - - @Override - public String toString() { - return "DetailedMonitorQueryItem [" + "attachmentKey= " + this.attachmentKey + "]"; - } + public void setAttachmentKey(String attachmentKey) { + this.attachmentKey = attachmentKey; + } + @Override + public String toString() { + return "DetailedMonitorQueryItem [" + "attachmentKey= " + this.attachmentKey + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/report/item/MonitorQueryItem.java b/lib/taskana-core/src/main/java/pro/taskana/impl/report/item/MonitorQueryItem.java index 53f2176e2..58bc82e75 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/report/item/MonitorQueryItem.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/report/item/MonitorQueryItem.java @@ -1,45 +1,47 @@ package pro.taskana.impl.report.item; /** - * The MonitorQueryItem entity contains the number of tasks for a key (e.g. workbasketKey) and age in days. + * The MonitorQueryItem entity contains the number of tasks for a key (e.g. workbasketKey) and age + * in days. */ public class MonitorQueryItem implements AgeQueryItem { - private String key; - private int ageInDays; - private int numberOfTasks; + private String key; + private int ageInDays; + private int numberOfTasks; - @Override - public String getKey() { - return key; - } + @Override + public String getKey() { + return key; + } - public void setKey(String key) { - this.key = key; - } + public void setKey(String key) { + this.key = key; + } - @Override - public int getAgeInDays() { - return ageInDays; - } + @Override + public int getAgeInDays() { + return ageInDays; + } - @Override - public void setAgeInDays(int ageInDays) { - this.ageInDays = ageInDays; - } + @Override + public void setAgeInDays(int ageInDays) { + this.ageInDays = ageInDays; + } - @Override - public int getValue() { - return numberOfTasks; - } + @Override + public int getValue() { + return numberOfTasks; + } - public void setNumberOfTasks(int numberOfTasks) { - this.numberOfTasks = numberOfTasks; - } + public void setNumberOfTasks(int numberOfTasks) { + this.numberOfTasks = numberOfTasks; + } - @Override - public String toString() { - return String.format("MonitorQueryItem [key= %s, ageInDays= %d, numberOfTasks= %d]", - key, ageInDays, numberOfTasks); - } + @Override + public String toString() { + return String.format( + "MonitorQueryItem [key= %s, ageInDays= %d, numberOfTasks= %d]", + key, ageInDays, numberOfTasks); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/report/item/TaskQueryItem.java b/lib/taskana-core/src/main/java/pro/taskana/impl/report/item/TaskQueryItem.java index ed68d7def..37d634f7f 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/report/item/TaskQueryItem.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/report/item/TaskQueryItem.java @@ -8,39 +8,45 @@ import pro.taskana.impl.report.structure.QueryItem; */ public class TaskQueryItem implements QueryItem { - private String domain; - private TaskState state; - private int count; + private String domain; + private TaskState state; + private int count; - public void setDomain(String domain) { - this.domain = domain; - } + public void setDomain(String domain) { + this.domain = domain; + } - public void setCount(int count) { - this.count = count; - } + public void setCount(int count) { + this.count = count; + } - public TaskState getState() { - return state; - } + public TaskState getState() { + return state; + } - public void setState(TaskState state) { - this.state = state; - } + public void setState(TaskState state) { + this.state = state; + } - @Override - public String getKey() { - return domain; - } + @Override + public String getKey() { + return domain; + } - @Override - public int getValue() { - return count; - } + @Override + public int getValue() { + return count; + } - @Override - public String toString() { - return "TaskQueryItem [" + "domain= " + this.domain + ", state= " + this.state.name() - + ", count= " + this.count + "]"; - } + @Override + public String toString() { + return "TaskQueryItem [" + + "domain= " + + this.domain + + ", state= " + + this.state.name() + + ", count= " + + this.count + + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/report/item/TimestampQueryItem.java b/lib/taskana-core/src/main/java/pro/taskana/impl/report/item/TimestampQueryItem.java index 94b162d17..c2282b0e2 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/report/item/TimestampQueryItem.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/report/item/TimestampQueryItem.java @@ -3,52 +3,53 @@ package pro.taskana.impl.report.item; import pro.taskana.report.Timestamp; /** - * The TimestampQueryItem contains the necessary information for the {@link pro.taskana.report.TimestampReport}. + * The TimestampQueryItem contains the necessary information for the {@link + * pro.taskana.report.TimestampReport}. */ public class TimestampQueryItem implements AgeQueryItem { - private static final String N_A = "N/A"; - private int count; - private Timestamp status; - private int ageInDays; - private String orgLevel1; - private String orgLevel2; - private String orgLevel3; - private String orgLevel4; + private static final String N_A = "N/A"; + private int count; + private Timestamp status; + private int ageInDays; + private String orgLevel1; + private String orgLevel2; + private String orgLevel3; + private String orgLevel4; - @Override - public String getKey() { - return status.name(); - } + @Override + public String getKey() { + return status.name(); + } - @Override - public int getValue() { - return count; - } + @Override + public int getValue() { + return count; + } - @Override - public int getAgeInDays() { - return ageInDays; - } + @Override + public int getAgeInDays() { + return ageInDays; + } - @Override - public void setAgeInDays(int ageInDays) { - this.ageInDays = ageInDays; - } + @Override + public void setAgeInDays(int ageInDays) { + this.ageInDays = ageInDays; + } - public String getOrgLevel1() { - return orgLevel1 == null || orgLevel1.isEmpty() ? N_A : orgLevel1; - } + public String getOrgLevel1() { + return orgLevel1 == null || orgLevel1.isEmpty() ? N_A : orgLevel1; + } - public String getOrgLevel2() { - return orgLevel2 == null || orgLevel2.isEmpty() ? N_A : orgLevel2; - } + public String getOrgLevel2() { + return orgLevel2 == null || orgLevel2.isEmpty() ? N_A : orgLevel2; + } - public String getOrgLevel3() { - return orgLevel3 == null || orgLevel3.isEmpty() ? N_A : orgLevel3; - } + public String getOrgLevel3() { + return orgLevel3 == null || orgLevel3.isEmpty() ? N_A : orgLevel3; + } - public String getOrgLevel4() { - return orgLevel4 == null || orgLevel4.isEmpty() ? N_A : orgLevel4; - } + public String getOrgLevel4() { + return orgLevel4 == null || orgLevel4.isEmpty() ? N_A : orgLevel4; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/report/preprocessor/DaysToWorkingDaysPreProcessor.java b/lib/taskana-core/src/main/java/pro/taskana/impl/report/preprocessor/DaysToWorkingDaysPreProcessor.java index 190d48677..830889296 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/report/preprocessor/DaysToWorkingDaysPreProcessor.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/report/preprocessor/DaysToWorkingDaysPreProcessor.java @@ -10,24 +10,27 @@ import pro.taskana.impl.report.structure.QueryItemPreprocessor; /** * Uses {@link DaysToWorkingDaysConverter} to convert an <I>s age to working days. + * * @param QueryItem which is being processed */ -public class DaysToWorkingDaysPreProcessor implements QueryItemPreprocessor { +public class DaysToWorkingDaysPreProcessor + implements QueryItemPreprocessor { - private DaysToWorkingDaysConverter instance; + private DaysToWorkingDaysConverter instance; - public DaysToWorkingDaysPreProcessor(List columnHeaders, boolean activate) - throws InvalidArgumentException { - if (activate) { - instance = DaysToWorkingDaysConverter.initialize(columnHeaders); - } + public DaysToWorkingDaysPreProcessor( + List columnHeaders, boolean activate) + throws InvalidArgumentException { + if (activate) { + instance = DaysToWorkingDaysConverter.initialize(columnHeaders); } + } - @Override - public I apply(I item) { - if (instance != null) { - item.setAgeInDays(instance.convertDaysToWorkingDays(item.getAgeInDays())); - } - return item; + @Override + public I apply(I item) { + if (instance != null) { + item.setAgeInDays(instance.convertDaysToWorkingDays(item.getAgeInDays())); } + return item; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/report/row/DetailedClassificationRow.java b/lib/taskana-core/src/main/java/pro/taskana/impl/report/row/DetailedClassificationRow.java index 93f478245..818cddfa3 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/report/row/DetailedClassificationRow.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/report/row/DetailedClassificationRow.java @@ -4,22 +4,23 @@ import pro.taskana.impl.report.item.DetailedMonitorQueryItem; import pro.taskana.impl.report.structure.Row; /** - * Represents a single Row inside {@link pro.taskana.report.ClassificationReport.DetailedClassificationReport}. - * The collapsing criteria is the attachement key of each {@link DetailedMonitorQueryItem}. + * Represents a single Row inside {@link + * pro.taskana.report.ClassificationReport.DetailedClassificationReport}. The collapsing criteria is + * the attachement key of each {@link DetailedMonitorQueryItem}. */ public class DetailedClassificationRow extends FoldableRow { - public DetailedClassificationRow(int columnSize) { - super(columnSize, (item) -> item.getAttachmentKey() != null ? item.getAttachmentKey() : "N/A"); - } + public DetailedClassificationRow(int columnSize) { + super(columnSize, (item) -> item.getAttachmentKey() != null ? item.getAttachmentKey() : "N/A"); + } - @Override - Row buildRow(int columnSize) { - return new SingleRow<>(columnSize); - } + @Override + public SingleRow getFoldableRow(String key) { + return (SingleRow) super.getFoldableRow(key); + } - @Override - public SingleRow getFoldableRow(String key) { - return (SingleRow) super.getFoldableRow(key); - } + @Override + Row buildRow(int columnSize) { + return new SingleRow<>(columnSize); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/report/row/FoldableRow.java b/lib/taskana-core/src/main/java/pro/taskana/impl/report/row/FoldableRow.java index 99666e596..803b045cc 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/report/row/FoldableRow.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/report/row/FoldableRow.java @@ -5,62 +5,64 @@ import java.util.Map; import java.util.Set; import java.util.function.Function; -import pro.taskana.impl.util.LoggerUtils; import pro.taskana.impl.report.structure.QueryItem; import pro.taskana.impl.report.structure.Row; +import pro.taskana.impl.util.LoggerUtils; /** - * The FoldableRow extends the {@link SingleRow}. - * In contrast to the {@link SingleRow} the FoldableRow contains rows which can be collapsed or expanded. - * The FoldableRow itself displays the sum of all foldable rows. + * The FoldableRow extends the {@link SingleRow}. In contrast to the {@link SingleRow} the + * FoldableRow contains rows which can be collapsed or expanded. The FoldableRow itself displays the + * sum of all foldable rows. * - * @param the {@link QueryItem} on which the {@link pro.taskana.impl.report.structure.Report} is based on. + * @param the {@link QueryItem} on which the {@link pro.taskana.impl.report.structure.Report} is + * based on. */ public abstract class FoldableRow extends SingleRow { - private Map> foldableRows = new LinkedHashMap<>(); - private Function calcFoldableRowKey; - private int columnSize; + private Map> foldableRows = new LinkedHashMap<>(); + private Function calcFoldableRowKey; + private int columnSize; - protected FoldableRow(int columnSize, Function calcFoldableRowKey) { - super(columnSize); - this.columnSize = columnSize; - this.calcFoldableRowKey = calcFoldableRowKey; - } + protected FoldableRow(int columnSize, Function calcFoldableRowKey) { + super(columnSize); + this.columnSize = columnSize; + this.calcFoldableRowKey = calcFoldableRowKey; + } - public final int getFoldableRowCount() { - return foldableRows.size(); - } + public final int getFoldableRowCount() { + return foldableRows.size(); + } - public final Set getFoldableRowKeySet() { - return foldableRows.keySet(); - } + public final Set getFoldableRowKeySet() { + return foldableRows.keySet(); + } - @Override - public void updateTotalValue(I item) { - super.updateTotalValue(item); - foldableRows - .computeIfAbsent(calcFoldableRowKey.apply(item), (s) -> buildRow(columnSize)) - .updateTotalValue(item); - } + @Override + public void updateTotalValue(I item) { + super.updateTotalValue(item); + foldableRows + .computeIfAbsent(calcFoldableRowKey.apply(item), (s) -> buildRow(columnSize)) + .updateTotalValue(item); + } - @Override - public void addItem(I item, int index) throws IndexOutOfBoundsException { - super.addItem(item, index); - foldableRows - .computeIfAbsent(calcFoldableRowKey.apply(item), (s) -> buildRow(columnSize)) - .addItem(item, index); - } + @Override + public void addItem(I item, int index) throws IndexOutOfBoundsException { + super.addItem(item, index); + foldableRows + .computeIfAbsent(calcFoldableRowKey.apply(item), (s) -> buildRow(columnSize)) + .addItem(item, index); + } - public Row getFoldableRow(String key) { - return foldableRows.get(key); - } + public Row getFoldableRow(String key) { + return foldableRows.get(key); + } - abstract Row buildRow(int columnSize); + abstract Row buildRow(int columnSize); - @Override - public String toString() { - return String.format("FoldableRow [detailRows= %s, columnSize= %d]", - LoggerUtils.mapToString(this.foldableRows), columnSize); - } + @Override + public String toString() { + return String.format( + "FoldableRow [detailRows= %s, columnSize= %d]", + LoggerUtils.mapToString(this.foldableRows), columnSize); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/report/row/SingleRow.java b/lib/taskana-core/src/main/java/pro/taskana/impl/report/row/SingleRow.java index 766603d2e..5478e8ddc 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/report/row/SingleRow.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/report/row/SingleRow.java @@ -4,38 +4,41 @@ import pro.taskana.impl.report.structure.QueryItem; import pro.taskana.impl.report.structure.Row; /** - * A SingleRow represents a single row in a {@link pro.taskana.impl.report.structure.Report}. - * It contains an array of cells whose index corresponds to the {@link pro.taskana.impl.report.structure.ColumnHeader} index in the {@link pro.taskana.impl.report.structure.Report}. + * A SingleRow represents a single row in a {@link pro.taskana.impl.report.structure.Report}. It + * contains an array of cells whose index corresponds to the {@link + * pro.taskana.impl.report.structure.ColumnHeader} index in the {@link + * pro.taskana.impl.report.structure.Report}. * - * @param {@link QueryItem} on which the {@link pro.taskana.impl.report.structure.Report} is based on. + * @param {@link QueryItem} on which the {@link pro.taskana.impl.report.structure.Report} is + * based on. */ public class SingleRow implements Row { - private final int[] cells; - private int total = 0; + private final int[] cells; + private int total = 0; - public SingleRow(int columnCount) { - cells = new int[columnCount]; - } + public SingleRow(int columnCount) { + cells = new int[columnCount]; + } - @Override - public void addItem(I item, int index) throws IndexOutOfBoundsException { - total += item.getValue(); - cells[index] += item.getValue(); - } + @Override + public void addItem(I item, int index) throws IndexOutOfBoundsException { + total += item.getValue(); + cells[index] += item.getValue(); + } - @Override - public void updateTotalValue(I item) { - total += item.getValue(); - } + @Override + public void updateTotalValue(I item) { + total += item.getValue(); + } - @Override - public final int getTotalValue() { - return total; - } + @Override + public final int getTotalValue() { + return total; + } - @Override - public final int[] getCells() { - return cells.clone(); - } + @Override + public final int[] getCells() { + return cells.clone(); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/report/row/TimestampRow.java b/lib/taskana-core/src/main/java/pro/taskana/impl/report/row/TimestampRow.java index ca22d8d37..febd88685 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/report/row/TimestampRow.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/report/row/TimestampRow.java @@ -4,86 +4,85 @@ import pro.taskana.impl.report.item.TimestampQueryItem; import pro.taskana.impl.report.structure.Row; /** - * A single Row inside the {@link pro.taskana.report.TimestampReport}. - * It contains 4 sub-rows for each org level respectively. + * A single Row inside the {@link pro.taskana.report.TimestampReport}. It contains 4 sub-rows for + * each org level respectively. */ public class TimestampRow extends FoldableRow { - public TimestampRow(int columnSize) { - super(columnSize, TimestampQueryItem::getOrgLevel1); + public TimestampRow(int columnSize) { + super(columnSize, TimestampQueryItem::getOrgLevel1); + } + + @Override + public OrgLevel1Row getFoldableRow(String key) { + return (OrgLevel1Row) super.getFoldableRow(key); + } + + @Override + OrgLevel1Row buildRow(int columnSize) { + return new OrgLevel1Row(columnSize); + } + + /** + * Row inside the {@link pro.taskana.report.TimestampReport} containing the information regarding + * a specific org level 1. + */ + public static final class OrgLevel1Row extends FoldableRow { + + private OrgLevel1Row(int columnSize) { + super(columnSize, TimestampQueryItem::getOrgLevel2); } @Override - OrgLevel1Row buildRow(int columnSize) { - return new OrgLevel1Row(columnSize); + public OrgLevel2Row getFoldableRow(String key) { + return (OrgLevel2Row) super.getFoldableRow(key); } @Override - public OrgLevel1Row getFoldableRow(String key) { - return (OrgLevel1Row) super.getFoldableRow(key); + OrgLevel2Row buildRow(int columnSize) { + return new OrgLevel2Row(columnSize); + } + } + + /** + * Row inside the {@link pro.taskana.report.TimestampReport} containing the information regarding + * a specific org level 2. + */ + public static final class OrgLevel2Row extends FoldableRow { + + private OrgLevel2Row(int columnSize) { + super(columnSize, TimestampQueryItem::getOrgLevel3); } - /** - * Row inside the {@link pro.taskana.report.TimestampReport} containing - * the information regarding a specific org level 1. - */ - public static final class OrgLevel1Row extends FoldableRow { - - private OrgLevel1Row(int columnSize) { - super(columnSize, TimestampQueryItem::getOrgLevel2); - } - - @Override - OrgLevel2Row buildRow(int columnSize) { - return new OrgLevel2Row(columnSize); - } - - @Override - public OrgLevel2Row getFoldableRow(String key) { - return (OrgLevel2Row) super.getFoldableRow(key); - } + @Override + public OrgLevel3Row getFoldableRow(String key) { + return (OrgLevel3Row) super.getFoldableRow(key); } - /** - * Row inside the {@link pro.taskana.report.TimestampReport} containing - * the information regarding a specific org level 2. - */ - public static final class OrgLevel2Row extends FoldableRow { + @Override + OrgLevel3Row buildRow(int columnSize) { + return new OrgLevel3Row(columnSize); + } + } - private OrgLevel2Row(int columnSize) { - super(columnSize, TimestampQueryItem::getOrgLevel3); - } + /** + * Row inside the {@link pro.taskana.report.TimestampReport} containing the information regarding + * a specific org level 3. + */ + public static final class OrgLevel3Row extends FoldableRow { - @Override - OrgLevel3Row buildRow(int columnSize) { - return new OrgLevel3Row(columnSize); - } - - @Override - public OrgLevel3Row getFoldableRow(String key) { - return (OrgLevel3Row) super.getFoldableRow(key); - } + private OrgLevel3Row(int columnSize) { + super(columnSize, TimestampQueryItem::getOrgLevel4); } - /** - * Row inside the {@link pro.taskana.report.TimestampReport} containing - * the information regarding a specific org level 3. - */ - public static final class OrgLevel3Row extends FoldableRow { - - private OrgLevel3Row(int columnSize) { - super(columnSize, TimestampQueryItem::getOrgLevel4); - } - - @Override - Row buildRow(int columnSize) { - return new SingleRow<>(columnSize); - } - - @Override - public SingleRow getFoldableRow(String key) { - return (SingleRow) super.getFoldableRow(key); - } + @Override + public SingleRow getFoldableRow(String key) { + return (SingleRow) super.getFoldableRow(key); } + @Override + Row buildRow(int columnSize) { + return new SingleRow<>(columnSize); + } + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/report/structure/ColumnHeader.java b/lib/taskana-core/src/main/java/pro/taskana/impl/report/structure/ColumnHeader.java index 033be2b97..7567a49b5 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/report/structure/ColumnHeader.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/report/structure/ColumnHeader.java @@ -1,27 +1,26 @@ package pro.taskana.impl.report.structure; /** - * A ColumnHeader is an element of a {@link Report}. - * It determines weather a given <Item> belongs into the representing column. + * A ColumnHeader is an element of a {@link Report}. It determines weather a given <Item> + * belongs into the representing column. * * @param {@link QueryItem} on which the {@link Report} is based on. */ public interface ColumnHeader { - /** - * The display name is the string representation of this column. - * Used to give this column a name during presentation. - * @return String representation of this column. - */ - String getDisplayName(); - - /** - * Determines if a specific item is meant part of this column. - * - * @param item the given item to check. - * - * @return True, if the item is supposed to be part of this column. Otherwise false. - */ - boolean fits(I item); + /** + * The display name is the string representation of this column. Used to give this column a name + * during presentation. + * + * @return String representation of this column. + */ + String getDisplayName(); + /** + * Determines if a specific item is meant part of this column. + * + * @param item the given item to check. + * @return True, if the item is supposed to be part of this column. Otherwise false. + */ + boolean fits(I item); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/report/structure/QueryItem.java b/lib/taskana-core/src/main/java/pro/taskana/impl/report/structure/QueryItem.java index 6ba38e329..c038321b0 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/report/structure/QueryItem.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/report/structure/QueryItem.java @@ -1,18 +1,18 @@ package pro.taskana.impl.report.structure; /** - * A QueryItem is en entity on which a {@link Report} is based on. - * Its value will be added to the existing cell value during the insertion into a report. - * Its key will determine in which {@link Row} the item will be inserted. + * A QueryItem is en entity on which a {@link Report} is based on. Its value will be added to the + * existing cell value during the insertion into a report. Its key will determine in which {@link + * Row} the item will be inserted. */ public interface QueryItem { - /** - * The key of a QueryItem determines its row within a {@link Report}. - * @return the key of this query item. - */ - String getKey(); - - int getValue(); + /** + * The key of a QueryItem determines its row within a {@link Report}. + * + * @return the key of this query item. + */ + String getKey(); + int getValue(); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/report/structure/QueryItemPreprocessor.java b/lib/taskana-core/src/main/java/pro/taskana/impl/report/structure/QueryItemPreprocessor.java index b723d8566..a4857fa33 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/report/structure/QueryItemPreprocessor.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/report/structure/QueryItemPreprocessor.java @@ -1,13 +1,14 @@ package pro.taskana.impl.report.structure; /** - * The QueryItemPreprocessor is used when adding {@link QueryItem}s into a {@link Report}. It defines a processing - * step which is executed on each {@link QueryItem} before inserting it into the {@link Report}. + * The QueryItemPreprocessor is used when adding {@link QueryItem}s into a {@link Report}. It + * defines a processing step which is executed on each {@link QueryItem} before inserting it into + * the {@link Report}. + * * @param Item class which is being pre processed. */ @FunctionalInterface public interface QueryItemPreprocessor { - I apply(I item); - + I apply(I item); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/report/structure/Report.java b/lib/taskana-core/src/main/java/pro/taskana/impl/report/structure/Report.java index 9bcc12d34..9518b516b 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/report/structure/Report.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/report/structure/Report.java @@ -11,99 +11,101 @@ import pro.taskana.exceptions.NotAuthorizedException; import pro.taskana.impl.report.row.SingleRow; /** - * A Report represents a an abstract table that consists of {@link Row}s and a list of <ColumnHeader>s. - * Since a report does not specify <Item> and <ColumnHeader> it does not contain functional logic. - * Due to readability implicit definition of functional logic is prevented and thus prevent - * initialization of an abstract Report. In order to create a specific Report a subclass has to be created. + * A Report represents a an abstract table that consists of {@link Row}s and a list of + * <ColumnHeader>s. Since a report does not specify <Item> and <ColumnHeader> it + * does not contain functional logic. Due to readability implicit definition of functional logic is + * prevented and thus prevent initialization of an abstract Report. In order to create a specific + * Report a subclass has to be created. * * @param {@link QueryItem} whose value is relevant for this report. - * @param {@link ColumnHeader} which can determine if an <Item> belongs into that column or not. + * @param {@link ColumnHeader} which can determine if an <Item> belongs into that column + * or not. */ public abstract class Report> { - protected List columnHeaders; - private Map> reportRows = new LinkedHashMap<>(); - private Row sumRow; - private String[] rowDesc; + protected List columnHeaders; + private Map> reportRows = new LinkedHashMap<>(); + private Row sumRow; + private String[] rowDesc; - protected Report(List columnHeaders, String[] rowDesc) { - this.rowDesc = rowDesc; - sumRow = createRow(columnHeaders.size()); - this.columnHeaders = new ArrayList<>(columnHeaders); - } + protected Report(List columnHeaders, String[] rowDesc) { + this.rowDesc = rowDesc; + sumRow = createRow(columnHeaders.size()); + this.columnHeaders = new ArrayList<>(columnHeaders); + } - public final Map> getRows() { - return reportRows; - } + public final Map> getRows() { + return reportRows; + } - public final Row getSumRow() { - return sumRow; - } + public final Row getSumRow() { + return sumRow; + } - public final List getColumnHeaders() { - return columnHeaders; - } + public final List getColumnHeaders() { + return columnHeaders; + } - public final String[] getRowDesc() { - return rowDesc; - } + public final String[] getRowDesc() { + return rowDesc; + } - public Row getRow(String key) { - return reportRows.get(key); - } + public Row getRow(String key) { + return reportRows.get(key); + } - public final Set rowTitles() { - return reportRows.keySet(); - } + public final Set rowTitles() { + return reportRows.keySet(); + } - public final int rowSize() { - return reportRows.size(); - } + public final int rowSize() { + return reportRows.size(); + } - public final void addItem(I item) { - Row row = null; - if (columnHeaders.isEmpty()) { + public final void addItem(I item) { + Row row = null; + if (columnHeaders.isEmpty()) { + row = reportRows.computeIfAbsent(item.getKey(), (s) -> createRow(columnHeaders.size())); + row.updateTotalValue(item); + sumRow.updateTotalValue(item); + } else { + for (int i = 0; i < columnHeaders.size(); i++) { + if (columnHeaders.get(i).fits(item)) { + if (row == null) { row = reportRows.computeIfAbsent(item.getKey(), (s) -> createRow(columnHeaders.size())); - row.updateTotalValue(item); - sumRow.updateTotalValue(item); - } else { - for (int i = 0; i < columnHeaders.size(); i++) { - if (columnHeaders.get(i).fits(item)) { - if (row == null) { - row = reportRows.computeIfAbsent(item.getKey(), (s) -> createRow(columnHeaders.size())); - } - row.addItem(item, i); - sumRow.addItem(item, i); - } - } + } + row.addItem(item, i); + sumRow.addItem(item, i); } + } } + } - public final void addItem(I item, QueryItemPreprocessor preprocessor) { - addItem(preprocessor.apply(item)); - } + public final void addItem(I item, QueryItemPreprocessor preprocessor) { + addItem(preprocessor.apply(item)); + } - public final void addItems(List items, QueryItemPreprocessor preprocessor) { - items.stream() - .map(preprocessor::apply) - .forEach(this::addItem); - } + public final void addItems(List items, QueryItemPreprocessor preprocessor) { + items.stream().map(preprocessor::apply).forEach(this::addItem); + } - public final void addItems(List items) { - items.forEach(this::addItem); - } + public final void addItems(List items) { + items.forEach(this::addItem); + } - protected Row createRow(int columnSize) { - return new SingleRow<>(columnSize); - } + protected Row createRow(int columnSize) { + return new SingleRow<>(columnSize); + } - /** - * Builder for {@link Report}. - * @param {@link QueryItem} whose value is relevant for this report. - * @param {@link ColumnHeader} which can determine if an <Item> belongs into that column or not. - */ - public interface Builder> { + /** + * Builder for {@link Report}. + * + * @param {@link QueryItem} whose value is relevant for this report. + * @param {@link ColumnHeader} which can determine if an <Item> belongs into that column + * or not. + */ + public interface Builder> { - Report buildReport() throws NotAuthorizedException, InvalidArgumentException; - } + Report buildReport() throws NotAuthorizedException, InvalidArgumentException; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/report/structure/Row.java b/lib/taskana-core/src/main/java/pro/taskana/impl/report/structure/Row.java index b64190144..e79873068 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/report/structure/Row.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/report/structure/Row.java @@ -1,29 +1,30 @@ package pro.taskana.impl.report.structure; /** - * Representation of a row in a {@link Report}. - * It contains an array of cells whose index corresponds to the {@link ColumnHeader} index in the {@link Report}. + * Representation of a row in a {@link Report}. It contains an array of cells whose index + * corresponds to the {@link ColumnHeader} index in the {@link Report}. * * @param {@link QueryItem} on which the {@link Report} is based on. */ public interface Row { - /** - * Appends a specific item value at a specific index. - * @param item the item which will be appended - * @param index the index at which the item will be appended at. - * @throws IndexOutOfBoundsException if the given index is invalid. - */ - void addItem(I item, int index) throws IndexOutOfBoundsException; + /** + * Appends a specific item value at a specific index. + * + * @param item the item which will be appended + * @param index the index at which the item will be appended at. + * @throws IndexOutOfBoundsException if the given index is invalid. + */ + void addItem(I item, int index) throws IndexOutOfBoundsException; - /** - * updates the total value of the row without changing any cell value. - * @param item the item whose value will be added to the total value of this row. - */ - void updateTotalValue(I item); + /** + * updates the total value of the row without changing any cell value. + * + * @param item the item whose value will be added to the total value of this row. + */ + void updateTotalValue(I item); - int getTotalValue(); - - int[] getCells(); + int getTotalValue(); + int[] getCells(); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/util/IdGenerator.java b/lib/taskana-core/src/main/java/pro/taskana/impl/util/IdGenerator.java index 805cb367a..b71916536 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/util/IdGenerator.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/util/IdGenerator.java @@ -2,27 +2,24 @@ package pro.taskana.impl.util; import java.util.UUID; -/** - * This class contains util methods for generating ids. - */ +/** This class contains util methods for generating ids. */ public final class IdGenerator { - private static final String SEPERATOR = ":"; + private static final String SEPERATOR = ":"; - /** - * This method create an id with an specific prefix. - * - * @param prefix - * only 3 characters! - * @return a String with a length of 40 characters - */ - public static String generateWithPrefix(String prefix) { - return new StringBuilder().append(prefix) - .append(SEPERATOR) - .append(UUID.randomUUID().toString()) - .toString(); - } + private IdGenerator() {} - private IdGenerator() { - } + /** + * This method create an id with an specific prefix. + * + * @param prefix only 3 characters! + * @return a String with a length of 40 characters + */ + public static String generateWithPrefix(String prefix) { + return new StringBuilder() + .append(prefix) + .append(SEPERATOR) + .append(UUID.randomUUID().toString()) + .toString(); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/impl/util/LoggerUtils.java b/lib/taskana-core/src/main/java/pro/taskana/impl/util/LoggerUtils.java index c10302f41..611fe2341 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/impl/util/LoggerUtils.java +++ b/lib/taskana-core/src/main/java/pro/taskana/impl/util/LoggerUtils.java @@ -12,74 +12,68 @@ import java.util.Set; */ public final class LoggerUtils { - private LoggerUtils() { + private LoggerUtils() {} + + /** + * Creating an appended log-string of a list with generic type T. The logging does append + * informations using toString() on the entries. + * + * @param list the input list to be stringified + * @param the type of the objects in the input list + * @return A String representation of the list. + */ + public static String listToString(List list) { + if (list == null || list.isEmpty()) { + return "[]"; + } else { + StringBuilder builder = new StringBuilder(); + builder.append("["); + for (T t : list) { + builder.append(String.valueOf(t)); + builder.append(";\n"); + } + builder.append("]"); + return builder.toString(); + } + } + + /** + * Creating an appended log-string of a map with generic types K/V. The logging does append + * informations using toString() on the entries. + * + * @param map the map to be stringified + * @param the type of the keys in the map + * @param the type of the values in the map + * @return A String representation of the map. + */ + public static String mapToString(Map map) { + if (map == null || map.isEmpty()) { + return "[]"; + } else { + StringBuilder builder = new StringBuilder(); + builder.append("["); + Set> entrySet = map.entrySet(); + for (Entry entry : entrySet) { + builder.append("("); + builder.append(entry.getKey()); + builder.append(" , "); + builder.append(entry.getValue()); + builder.append(")"); + builder.append(" , "); + } + builder.append("]"); + return builder.toString(); + } + } + + public static String setToString(Set set) { + if (set == null || set.isEmpty()) { + return "[]"; } - /** - * Creating an appended log-string of a list with generic type T. The logging does append informations using - * toString() on the entries. - * - * @param list - * the input list to be stringified - * @param - * the type of the objects in the input list - * @return A String representation of the list. - */ - public static String listToString(List list) { - if (list == null || list.isEmpty()) { - return "[]"; - } else { - StringBuilder builder = new StringBuilder(); - builder.append("["); - for (T t : list) { - builder.append(String.valueOf(t)); - builder.append(";\n"); - } - builder.append("]"); - return builder.toString(); - } - } - - /** - * Creating an appended log-string of a map with generic types K/V. The logging does append informations using - * toString() on the entries. - * - * @param map - * the map to be stringified - * @param - * the type of the keys in the map - * @param - * the type of the values in the map - * @return A String representation of the map. - */ - public static String mapToString(Map map) { - if (map == null || map.isEmpty()) { - return "[]"; - } else { - StringBuilder builder = new StringBuilder(); - builder.append("["); - Set> entrySet = map.entrySet(); - for (Entry entry : entrySet) { - builder.append("("); - builder.append(entry.getKey()); - builder.append(" , "); - builder.append(entry.getValue()); - builder.append(")"); - builder.append(" , "); - } - builder.append("]"); - return builder.toString(); - } - } - - public static String setToString(Set set) { - if (set == null || set.isEmpty()) { - return "[]"; - } - - StringBuilder result = new StringBuilder("["); - set.forEach(e -> result.append("(").append(e).append(") ,")); - result.append("]"); - return result.toString(); - } + StringBuilder result = new StringBuilder("["); + set.forEach(e -> result.append("(").append(e).append(") ,")); + result.append("]"); + return result.toString(); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/jobs/AbstractTaskanaJob.java b/lib/taskana-core/src/main/java/pro/taskana/jobs/AbstractTaskanaJob.java index 2fab25250..0cd4dc92a 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/jobs/AbstractTaskanaJob.java +++ b/lib/taskana-core/src/main/java/pro/taskana/jobs/AbstractTaskanaJob.java @@ -9,53 +9,57 @@ import pro.taskana.exceptions.TaskanaException; import pro.taskana.impl.TaskanaEngineImpl; import pro.taskana.transaction.TaskanaTransactionProvider; -/** - * Abstract base for all background jobs of TASKANA. - */ +/** Abstract base for all background jobs of TASKANA. */ public abstract class AbstractTaskanaJob implements TaskanaJob { - protected TaskanaEngineImpl taskanaEngineImpl; - protected TaskanaTransactionProvider txProvider; - protected ScheduledJob scheduledJob; + protected TaskanaEngineImpl taskanaEngineImpl; + protected TaskanaTransactionProvider txProvider; + protected ScheduledJob scheduledJob; - public AbstractTaskanaJob(TaskanaEngine taskanaEngine, TaskanaTransactionProvider txProvider, - ScheduledJob job) { - this.taskanaEngineImpl = (TaskanaEngineImpl) taskanaEngine; - this.txProvider = txProvider; - this.scheduledJob = job; + public AbstractTaskanaJob( + TaskanaEngine taskanaEngine, + TaskanaTransactionProvider txProvider, + ScheduledJob job) { + this.taskanaEngineImpl = (TaskanaEngineImpl) taskanaEngine; + this.txProvider = txProvider; + this.scheduledJob = job; + } + + public static TaskanaJob createFromScheduledJob( + TaskanaEngine engine, TaskanaTransactionProvider txProvider, ScheduledJob job) + throws TaskanaException { + switch (job.getType()) { + case CLASSIFICATIONCHANGEDJOB: + return new ClassificationChangedJob(engine, txProvider, job); + case UPDATETASKSJOB: + return new TaskRefreshJob(engine, txProvider, job); + case TASKCLEANUPJOB: + return new TaskCleanupJob(engine, txProvider, job); + case WORKBASKETCLEANUPJOB: + return new WorkbasketCleanupJob(engine, txProvider, job); + default: + throw new TaskanaException( + "No matching job found for " + + job.getType() + + " of ScheduledJob " + + job.getJobId() + + "."); } + } - public static TaskanaJob createFromScheduledJob(TaskanaEngine engine, TaskanaTransactionProvider txProvider, - ScheduledJob job) throws TaskanaException { - switch (job.getType()) { - case CLASSIFICATIONCHANGEDJOB: - return new ClassificationChangedJob(engine, txProvider, job); - case UPDATETASKSJOB: - return new TaskRefreshJob(engine, txProvider, job); - case TASKCLEANUPJOB: - return new TaskCleanupJob(engine, txProvider, job); - case WORKBASKETCLEANUPJOB: - return new WorkbasketCleanupJob(engine, txProvider, job); - default: - throw new TaskanaException( - "No matching job found for " + job.getType() + " of ScheduledJob " + job.getJobId() + "."); - } + List> partition(Collection members, int maxSize) { + List> result = new ArrayList<>(); + List internal = new ArrayList<>(); + for (T member : members) { + internal.add(member); + if (internal.size() == maxSize) { + result.add(internal); + internal = new ArrayList<>(); + } } - - List> partition(Collection members, int maxSize) { - List> result = new ArrayList<>(); - List internal = new ArrayList<>(); - for (T member : members) { - internal.add(member); - if (internal.size() == maxSize) { - result.add(internal); - internal = new ArrayList<>(); - } - } - if (!internal.isEmpty()) { - result.add(internal); - } - return result; + if (!internal.isEmpty()) { + result.add(internal); } - + return result; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/jobs/ClassificationChangedJob.java b/lib/taskana-core/src/main/java/pro/taskana/jobs/ClassificationChangedJob.java index 3ae3e2e17..9df815078 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/jobs/ClassificationChangedJob.java +++ b/lib/taskana-core/src/main/java/pro/taskana/jobs/ClassificationChangedJob.java @@ -4,11 +4,9 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import pro.taskana.TaskanaEngine; import pro.taskana.exceptions.TaskanaException; import pro.taskana.impl.TaskServiceImpl; @@ -19,59 +17,60 @@ import pro.taskana.transaction.TaskanaTransactionProvider; * * @author bbr */ - public class ClassificationChangedJob extends AbstractTaskanaJob { - private static final Logger LOGGER = LoggerFactory.getLogger(ClassificationChangedJob.class); + public static final String TASK_IDS = "taskIds"; + public static final String CLASSIFICATION_ID = "classificationId"; + public static final String PRIORITY_CHANGED = "priorityChanged"; + public static final String SERVICE_LEVEL_CHANGED = "serviceLevelChanged"; + private static final Logger LOGGER = LoggerFactory.getLogger(ClassificationChangedJob.class); + private String classificationId; + private boolean priorityChanged; + private boolean serviceLevelChanged; - public static final String TASK_IDS = "taskIds"; - public static final String CLASSIFICATION_ID = "classificationId"; - public static final String PRIORITY_CHANGED = "priorityChanged"; - public static final String SERVICE_LEVEL_CHANGED = "serviceLevelChanged"; + public ClassificationChangedJob( + TaskanaEngine engine, TaskanaTransactionProvider txProvider, ScheduledJob job) { + super(engine, txProvider, job); + Map args = job.getArguments(); + classificationId = args.get(CLASSIFICATION_ID); + priorityChanged = Boolean.parseBoolean(args.get(PRIORITY_CHANGED)); + serviceLevelChanged = Boolean.parseBoolean(args.get(SERVICE_LEVEL_CHANGED)); + } - private String classificationId; - private boolean priorityChanged; - private boolean serviceLevelChanged; - - public ClassificationChangedJob(TaskanaEngine engine, TaskanaTransactionProvider txProvider, - ScheduledJob job) { - super(engine, txProvider, job); - Map args = job.getArguments(); - classificationId = args.get(CLASSIFICATION_ID); - priorityChanged = Boolean.parseBoolean(args.get(PRIORITY_CHANGED)); - serviceLevelChanged = Boolean.parseBoolean(args.get(SERVICE_LEVEL_CHANGED)); + @Override + public void run() throws TaskanaException { + LOGGER.info("Running ClassificationChangedJob for classification ({})", classificationId); + try { + TaskServiceImpl taskService = (TaskServiceImpl) taskanaEngineImpl.getTaskService(); + Set affectedTaskIds = + taskService.findTasksIdsAffectedByClassificationChange(classificationId); + scheduleTaskRefreshJobs(affectedTaskIds); + LOGGER.info("ClassificationChangedJob ended successfully."); + } catch (Exception e) { + throw new TaskanaException("Error while processing ClassificationChangedJob.", e); } + } - @Override - public void run() throws TaskanaException { - LOGGER.info("Running ClassificationChangedJob for classification ({})", classificationId); - try { - TaskServiceImpl taskService = (TaskServiceImpl) taskanaEngineImpl.getTaskService(); - Set affectedTaskIds = taskService.findTasksIdsAffectedByClassificationChange(classificationId); - scheduleTaskRefreshJobs(affectedTaskIds); - LOGGER.info("ClassificationChangedJob ended successfully."); - } catch (Exception e) { - throw new TaskanaException("Error while processing ClassificationChangedJob.", e); - } - } - - private void scheduleTaskRefreshJobs(Set affectedTaskIds) { - int batchSize = taskanaEngineImpl.getConfiguration().getMaxNumberOfUpdatesPerTransaction(); - List> affectedTaskBatches = partition(affectedTaskIds, batchSize); - LOGGER.debug("Creating {} TaskRefreshJobs out of {} affected tasks with a maximum number of {} tasks each. ", - affectedTaskBatches.size(), affectedTaskIds.size(), batchSize); - for (List taskIdBatch : affectedTaskBatches) { - Map args = new HashMap<>(); - if (!taskIdBatch.isEmpty()) { - String taskIds = String.join(",", affectedTaskIds); - args.put(TASK_IDS, taskIds); - args.put(PRIORITY_CHANGED, Boolean.valueOf(priorityChanged).toString()); - args.put(SERVICE_LEVEL_CHANGED, Boolean.valueOf(serviceLevelChanged).toString()); - ScheduledJob job = new ScheduledJob(); - job.setType(ScheduledJob.Type.UPDATETASKSJOB); - job.setArguments(args); - taskanaEngineImpl.getJobService().createJob(job); - } - } + private void scheduleTaskRefreshJobs(Set affectedTaskIds) { + int batchSize = taskanaEngineImpl.getConfiguration().getMaxNumberOfUpdatesPerTransaction(); + List> affectedTaskBatches = partition(affectedTaskIds, batchSize); + LOGGER.debug( + "Creating {} TaskRefreshJobs out of {} affected tasks with a maximum number of {} tasks each. ", + affectedTaskBatches.size(), + affectedTaskIds.size(), + batchSize); + for (List taskIdBatch : affectedTaskBatches) { + Map args = new HashMap<>(); + if (!taskIdBatch.isEmpty()) { + String taskIds = String.join(",", affectedTaskIds); + args.put(TASK_IDS, taskIds); + args.put(PRIORITY_CHANGED, Boolean.valueOf(priorityChanged).toString()); + args.put(SERVICE_LEVEL_CHANGED, Boolean.valueOf(serviceLevelChanged).toString()); + ScheduledJob job = new ScheduledJob(); + job.setType(ScheduledJob.Type.UPDATETASKSJOB); + job.setArguments(args); + taskanaEngineImpl.getJobService().createJob(job); + } } + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/jobs/JobRunner.java b/lib/taskana-core/src/main/java/pro/taskana/jobs/JobRunner.java index 4defb1fba..d8ac7cda9 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/jobs/JobRunner.java +++ b/lib/taskana-core/src/main/java/pro/taskana/jobs/JobRunner.java @@ -4,7 +4,6 @@ import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -15,105 +14,104 @@ import pro.taskana.impl.TaskServiceImpl; import pro.taskana.impl.TaskanaEngineImpl; import pro.taskana.transaction.TaskanaTransactionProvider; -/** - * This is the runner for Tasks jobs. - */ +/** This is the runner for Tasks jobs. */ public class JobRunner { - private static final Logger LOGGER = LoggerFactory.getLogger(TaskServiceImpl.class); - private TaskanaEngineImpl taskanaEngine; - private JobServiceImpl jobService; - private TaskanaTransactionProvider txProvider; + private static final Logger LOGGER = LoggerFactory.getLogger(TaskServiceImpl.class); + private TaskanaEngineImpl taskanaEngine; + private JobServiceImpl jobService; + private TaskanaTransactionProvider txProvider; - public JobRunner(TaskanaEngine taskanaEngine) { - this.taskanaEngine = (TaskanaEngineImpl) taskanaEngine; - jobService = (JobServiceImpl) taskanaEngine.getJobService(); + public JobRunner(TaskanaEngine taskanaEngine) { + this.taskanaEngine = (TaskanaEngineImpl) taskanaEngine; + jobService = (JobServiceImpl) taskanaEngine.getJobService(); + } + + public void registerTransactionProvider(TaskanaTransactionProvider txProvider) { + this.txProvider = txProvider; + } + + public void runJobs() { + LOGGER.info("entry to runJobs()"); + try { + List jobsToRun = findAndLockJobsToRun(); + for (ScheduledJob scheduledJob : jobsToRun) { + runJobTransactionally(scheduledJob); + } + } catch (Exception e) { + LOGGER.error("Error occurred while running jobs: ", e); + } finally { + LOGGER.info("exit from runJobs()."); } + } - public void registerTransactionProvider( - TaskanaTransactionProvider txProvider) { - this.txProvider = txProvider; + private List findAndLockJobsToRun() { + List availableJobs = jobService.findJobsToRun(); + List lockedJobs = new ArrayList(); + for (ScheduledJob job : availableJobs) { + lockedJobs.add(lockJobTransactionally(job)); } + return lockedJobs; + } - public void runJobs() { - LOGGER.info("entry to runJobs()"); - try { - List jobsToRun = findAndLockJobsToRun(); - for (ScheduledJob scheduledJob : jobsToRun) { - runJobTransactionally(scheduledJob); - } - } catch (Exception e) { - LOGGER.error("Error occurred while running jobs: ", e); - } finally { - LOGGER.info("exit from runJobs()."); - } - + private ScheduledJob lockJobTransactionally(ScheduledJob job) { + ScheduledJob lockedJob; + if (txProvider != null) { + lockedJob = (ScheduledJob) txProvider.executeInTransaction(() -> lockJob(job)); + } else { + lockedJob = lockJob(job); } + LOGGER.debug("Locked job: {}", lockedJob); + return lockedJob; + } - private List findAndLockJobsToRun() { - List availableJobs = jobService.findJobsToRun(); - List lockedJobs = new ArrayList(); - for (ScheduledJob job : availableJobs) { - lockedJobs.add(lockJobTransactionally(job)); - } - return lockedJobs; + private ScheduledJob lockJob(ScheduledJob job) { + String hostAddress = "UNKNOWN_ADDRESS"; + try { + hostAddress = InetAddress.getLocalHost().getHostAddress(); + } catch (UnknownHostException e) { } + job.setLockedBy(hostAddress + " - " + Thread.currentThread().getName()); + String owner = hostAddress + " - " + Thread.currentThread().getName(); + ScheduledJob lockedJob = jobService.lockJob(job, owner); + return lockedJob; + } - private ScheduledJob lockJobTransactionally(ScheduledJob job) { - ScheduledJob lockedJob; - if (txProvider != null) { - lockedJob = (ScheduledJob) txProvider.executeInTransaction(() -> lockJob(job)); - } else { - lockedJob = lockJob(job); - } - LOGGER.debug("Locked job: {}", lockedJob); - return lockedJob; + private void runJobTransactionally(ScheduledJob scheduledJob) { + try { + if (txProvider != null) { + txProvider.executeInTransaction( + () -> { + runScheduledJob(scheduledJob); + return null; + }); + } else { + runScheduledJob(scheduledJob); + } + jobService.deleteJob(scheduledJob); + } catch (Exception e) { + LOGGER.error( + "Processing of job {} failed. Trying to split it up into two pieces...", + scheduledJob.getJobId(), + e); } + } - private ScheduledJob lockJob(ScheduledJob job) { - String hostAddress = "UNKNOWN_ADDRESS"; - try { - hostAddress = InetAddress.getLocalHost().getHostAddress(); - } catch (UnknownHostException e) { - } - job.setLockedBy( - hostAddress + " - " + Thread.currentThread().getName()); - String owner = hostAddress + " - " + Thread.currentThread().getName(); - ScheduledJob lockedJob = jobService.lockJob(job, owner); - return lockedJob; + private void runScheduledJob(ScheduledJob scheduledJob) { + LOGGER.debug("entry to runScheduledJob(job = {})", scheduledJob); + try { + TaskanaJob job = + AbstractTaskanaJob.createFromScheduledJob(taskanaEngine, txProvider, scheduledJob); + job.run(); + } catch (Exception e) { + LOGGER.error("Error running job: {} ", scheduledJob.getType(), e); + throw new SystemException( + "When attempting to load class " + + scheduledJob.getType() + + " caught Exception " + + e.getMessage(), + e); } - - private void runJobTransactionally(ScheduledJob scheduledJob) { - try { - if (txProvider != null) { - txProvider.executeInTransaction(() -> { - runScheduledJob(scheduledJob); - return null; - }); - } else { - runScheduledJob(scheduledJob); - } - jobService.deleteJob(scheduledJob); - } catch (Exception e) { - LOGGER.error( - "Processing of job {} failed. Trying to split it up into two pieces...", - scheduledJob.getJobId(), - e); - } - } - - private void runScheduledJob(ScheduledJob scheduledJob) { - LOGGER.debug("entry to runScheduledJob(job = {})", scheduledJob); - try { - TaskanaJob job = AbstractTaskanaJob.createFromScheduledJob(taskanaEngine, txProvider, scheduledJob); - job.run(); - } catch (Exception e) { - LOGGER.error("Error running job: {} ", scheduledJob.getType(), e); - throw new SystemException( - "When attempting to load class " + scheduledJob.getType() + " caught Exception " + e.getMessage(), - e); - } - LOGGER.debug("exit from runScheduledJob"); - } - + LOGGER.debug("exit from runScheduledJob"); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/jobs/ScheduledJob.java b/lib/taskana-core/src/main/java/pro/taskana/jobs/ScheduledJob.java index 3ab67a473..d28e18bed 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/jobs/ScheduledJob.java +++ b/lib/taskana-core/src/main/java/pro/taskana/jobs/ScheduledJob.java @@ -10,127 +10,143 @@ import java.util.Map; */ public class ScheduledJob { - private Integer jobId; - private Integer priority; - private Instant created; - private Instant due; - private State state; - private String lockedBy; - private Instant lockExpires; - private Type type; - private int retryCount; - Map arguments; + Map arguments; + private Integer jobId; + private Integer priority; + private Instant created; + private Instant due; + private State state; + private String lockedBy; + private Instant lockExpires; + private Type type; + private int retryCount; - public ScheduledJob() { - created = Instant.now(); - state = State.READY; - retryCount = 0; - } + public ScheduledJob() { + created = Instant.now(); + state = State.READY; + retryCount = 0; + } - public Integer getJobId() { - return jobId; - } + public Integer getJobId() { + return jobId; + } - public void setJobId(Integer jobId) { - this.jobId = jobId; - } + public void setJobId(Integer jobId) { + this.jobId = jobId; + } - public Integer getPriority() { - return priority; - } + public Integer getPriority() { + return priority; + } - public void setPriority(Integer priority) { - this.priority = priority; - } + public void setPriority(Integer priority) { + this.priority = priority; + } - public Instant getCreated() { - return created; - } + public Instant getCreated() { + return created; + } - public void setCreated(Instant created) { - this.created = created; - } + public void setCreated(Instant created) { + this.created = created; + } - public Instant getDue() { - return due; - } + public Instant getDue() { + return due; + } - public void setDue(Instant due) { - this.due = due; - } + public void setDue(Instant due) { + this.due = due; + } - public State getState() { - return state; - } + public State getState() { + return state; + } - public void setState(State state) { - this.state = state; - } + public void setState(State state) { + this.state = state; + } - public String getLockedBy() { - return lockedBy; - } + public String getLockedBy() { + return lockedBy; + } - public void setLockedBy(String lockedBy) { - this.lockedBy = lockedBy; - } + public void setLockedBy(String lockedBy) { + this.lockedBy = lockedBy; + } - public Instant getLockExpires() { - return lockExpires; - } + public Instant getLockExpires() { + return lockExpires; + } - public void setLockExpires(Instant lockExpires) { - this.lockExpires = lockExpires; - } + public void setLockExpires(Instant lockExpires) { + this.lockExpires = lockExpires; + } - public Map getArguments() { - return arguments; - } + public Map getArguments() { + return arguments; + } - public void setArguments(Map arguments) { - this.arguments = arguments; - } + public void setArguments(Map arguments) { + this.arguments = arguments; + } - public Type getType() { - return type; - } + public Type getType() { + return type; + } - public void setType(Type type) { - this.type = type; - } + public void setType(Type type) { + this.type = type; + } - public int getRetryCount() { - return retryCount; - } + public int getRetryCount() { + return retryCount; + } - public void setRetryCount(int retryCount) { - this.retryCount = retryCount; - } + public void setRetryCount(int retryCount) { + this.retryCount = retryCount; + } - @Override - public String toString() { - return "ScheduledJob [jobId=" + jobId + ", priority=" + priority + ", created=" + created + ", due=" + due - + ", state=" + state + ", lockedBy=" + lockedBy + ", lockExpires=" + lockExpires + ", type=" + type - + ", retryCount=" + retryCount + ", arguments=" + arguments + "]"; - } + @Override + public String toString() { + return "ScheduledJob [jobId=" + + jobId + + ", priority=" + + priority + + ", created=" + + created + + ", due=" + + due + + ", state=" + + state + + ", lockedBy=" + + lockedBy + + ", lockExpires=" + + lockExpires + + ", type=" + + type + + ", retryCount=" + + retryCount + + ", arguments=" + + arguments + + "]"; + } - /** - * This enum tracks the state of a job. - * - * @author bbr - */ - public enum State { - READY, - FAILED - } + /** + * This enum tracks the state of a job. + * + * @author bbr + */ + public enum State { + READY, + FAILED + } - /** - * This enum controls the type of a job. - */ - public enum Type { - CLASSIFICATIONCHANGEDJOB, - UPDATETASKSJOB, - TASKCLEANUPJOB, - WORKBASKETCLEANUPJOB; - } + /** This enum controls the type of a job. */ + public enum Type { + CLASSIFICATIONCHANGEDJOB, + UPDATETASKSJOB, + TASKCLEANUPJOB, + WORKBASKETCLEANUPJOB; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/jobs/TaskCleanupJob.java b/lib/taskana-core/src/main/java/pro/taskana/jobs/TaskCleanupJob.java index ecca82d18..cc12bd67e 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/jobs/TaskCleanupJob.java +++ b/lib/taskana-core/src/main/java/pro/taskana/jobs/TaskCleanupJob.java @@ -7,7 +7,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -21,176 +20,194 @@ import pro.taskana.exceptions.TaskanaException; import pro.taskana.impl.util.LoggerUtils; import pro.taskana.transaction.TaskanaTransactionProvider; -/** - * Job to cleanup completed tasks after a period of time. - */ +/** Job to cleanup completed tasks after a period of time. */ public class TaskCleanupJob extends AbstractTaskanaJob { - private static final Logger LOGGER = LoggerFactory.getLogger(TaskCleanupJob.class); + private static final Logger LOGGER = LoggerFactory.getLogger(TaskCleanupJob.class); - private static BaseQuery.SortDirection asc = BaseQuery.SortDirection.ASCENDING; + private static BaseQuery.SortDirection asc = BaseQuery.SortDirection.ASCENDING; - // Parameter - private Instant firstRun; - private Duration runEvery; - private Duration minimumAge; - private int batchSize; - private boolean allCompletedSameParentBusiness; + // Parameter + private Instant firstRun; + private Duration runEvery; + private Duration minimumAge; + private int batchSize; + private boolean allCompletedSameParentBusiness; - public TaskCleanupJob(TaskanaEngine taskanaEngine, TaskanaTransactionProvider txProvider, - ScheduledJob scheduledJob) { - super(taskanaEngine, txProvider, scheduledJob); - firstRun = taskanaEngine.getConfiguration().getCleanupJobFirstRun(); - runEvery = taskanaEngine.getConfiguration().getCleanupJobRunEvery(); - minimumAge = taskanaEngine.getConfiguration().getCleanupJobMinimumAge(); - batchSize = taskanaEngine.getConfiguration().getMaxNumberOfUpdatesPerTransaction(); - allCompletedSameParentBusiness = taskanaEngine.getConfiguration() - .isTaskCleanupJobAllCompletedSameParentBusiness(); - } + public TaskCleanupJob( + TaskanaEngine taskanaEngine, + TaskanaTransactionProvider txProvider, + ScheduledJob scheduledJob) { + super(taskanaEngine, txProvider, scheduledJob); + firstRun = taskanaEngine.getConfiguration().getCleanupJobFirstRun(); + runEvery = taskanaEngine.getConfiguration().getCleanupJobRunEvery(); + minimumAge = taskanaEngine.getConfiguration().getCleanupJobMinimumAge(); + batchSize = taskanaEngine.getConfiguration().getMaxNumberOfUpdatesPerTransaction(); + allCompletedSameParentBusiness = + taskanaEngine.getConfiguration().isTaskCleanupJobAllCompletedSameParentBusiness(); + } - @Override - public void run() throws TaskanaException { - Instant completedBefore = Instant.now().minus(minimumAge); - LOGGER.info("Running job to delete all tasks completed before ({})", completedBefore.toString()); - try { - List tasksCompletedBefore = getTasksCompletedBefore(completedBefore); - int totalNumberOfTasksCompleted = 0; - while (tasksCompletedBefore.size() > 0) { - int upperLimit = batchSize; - if (upperLimit > tasksCompletedBefore.size()) { - upperLimit = tasksCompletedBefore.size(); - } - totalNumberOfTasksCompleted += deleteTasksTransactionally(tasksCompletedBefore.subList(0, upperLimit)); - tasksCompletedBefore.subList(0, upperLimit).clear(); - } - LOGGER.info("Job ended successfully. {} tasks deleted.", totalNumberOfTasksCompleted); - } catch (Exception e) { - throw new TaskanaException("Error while processing TaskCleanupJob.", e); - } finally { - scheduleNextCleanupJob(); + @Override + public void run() throws TaskanaException { + Instant completedBefore = Instant.now().minus(minimumAge); + LOGGER.info( + "Running job to delete all tasks completed before ({})", completedBefore.toString()); + try { + List tasksCompletedBefore = getTasksCompletedBefore(completedBefore); + int totalNumberOfTasksCompleted = 0; + while (tasksCompletedBefore.size() > 0) { + int upperLimit = batchSize; + if (upperLimit > tasksCompletedBefore.size()) { + upperLimit = tasksCompletedBefore.size(); } + totalNumberOfTasksCompleted += + deleteTasksTransactionally(tasksCompletedBefore.subList(0, upperLimit)); + tasksCompletedBefore.subList(0, upperLimit).clear(); + } + LOGGER.info("Job ended successfully. {} tasks deleted.", totalNumberOfTasksCompleted); + } catch (Exception e) { + throw new TaskanaException("Error while processing TaskCleanupJob.", e); + } finally { + scheduleNextCleanupJob(); } + } - private List getTasksCompletedBefore(Instant untilDate) { - LOGGER.debug("entry to getTasksCompletedBefore(untilDate = {})", untilDate); - List taskList = taskanaEngineImpl.getTaskService() + /** + * Initializes the TaskCleanupJob schedule.
+ * All scheduled cleanup jobs are cancelled/deleted and a new one is scheduled. + * + * @param taskanaEngine the TASKANA engine. + */ + public static void initializeSchedule(TaskanaEngine taskanaEngine) { + TaskCleanupJob job = new TaskCleanupJob(taskanaEngine, null, null); + job.scheduleNextCleanupJob(); + } + + private List getTasksCompletedBefore(Instant untilDate) { + LOGGER.debug("entry to getTasksCompletedBefore(untilDate = {})", untilDate); + List taskList = + taskanaEngineImpl + .getTaskService() .createTaskQuery() .completedWithin(new TimeInterval(null, untilDate)) .orderByBusinessProcessId(asc) .list(); - if (allCompletedSameParentBusiness) { - Map numberParentTasksShouldHave = new HashMap<>(); - Map countParentTask = new HashMap<>(); - for (TaskSummary task : taskList) { - numberParentTasksShouldHave.put(task.getParentBusinessProcessId(), taskanaEngineImpl.getTaskService() - .createTaskQuery() - .parentBusinessProcessIdIn(task.getParentBusinessProcessId()) - .count()); - countParentTask.merge(task.getParentBusinessProcessId(), 1L, Long::sum); - } - - List idsList = new ArrayList<>(); - numberParentTasksShouldHave.forEach((k, v) -> { - if (v.compareTo(countParentTask.get(k)) == 0) { - idsList.add(k); - } - }); - - if (idsList.isEmpty()) { - LOGGER.debug("exit from getTasksCompletedBefore(), returning {}", new ArrayList<>()); - return new ArrayList<>(); - } - - String[] ids = new String[idsList.size()]; - ids = idsList.toArray(ids); - taskList = taskanaEngineImpl.getTaskService() + if (allCompletedSameParentBusiness) { + Map numberParentTasksShouldHave = new HashMap<>(); + Map countParentTask = new HashMap<>(); + for (TaskSummary task : taskList) { + numberParentTasksShouldHave.put( + task.getParentBusinessProcessId(), + taskanaEngineImpl + .getTaskService() .createTaskQuery() - .parentBusinessProcessIdIn(ids) - .list(); - } + .parentBusinessProcessIdIn(task.getParentBusinessProcessId()) + .count()); + countParentTask.merge(task.getParentBusinessProcessId(), 1L, Long::sum); + } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("exit from getTasksCompletedBefore(), returning {}", LoggerUtils.listToString(taskList)); - } - - return taskList; - } - - private int deleteTasksTransactionally(List tasksToBeDeleted) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("entry to deleteTasksTransactionally(tasksToBeDeleted = {})", LoggerUtils.listToString(tasksToBeDeleted)); - } - - int deletedTaskCount = 0; - if (txProvider != null) { - int count = (Integer) txProvider.executeInTransaction(() -> { - try { - return deleteTasks(tasksToBeDeleted); - } catch (Exception e) { - LOGGER.warn("Could not delete tasks.", e); - return 0; - } - }); - LOGGER.debug("exit from deleteTasksTransactionally(), returning {}", count); - return count; - } else { - try { - deletedTaskCount = deleteTasks(tasksToBeDeleted); - } catch (Exception e) { - LOGGER.warn("Could not delete tasks.", e); + List idsList = new ArrayList<>(); + numberParentTasksShouldHave.forEach( + (k, v) -> { + if (v.compareTo(countParentTask.get(k)) == 0) { + idsList.add(k); } - } - LOGGER.debug("exit from deleteTasksTransactionally(), returning {}", deletedTaskCount); - return deletedTaskCount; + }); + + if (idsList.isEmpty()) { + LOGGER.debug("exit from getTasksCompletedBefore(), returning {}", new ArrayList<>()); + return new ArrayList<>(); + } + + String[] ids = new String[idsList.size()]; + ids = idsList.toArray(ids); + taskList = + taskanaEngineImpl + .getTaskService() + .createTaskQuery() + .parentBusinessProcessIdIn(ids) + .list(); } - private int deleteTasks(List tasksToBeDeleted) throws InvalidArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("entry to deleteTasks(tasksToBeDeleted = {})", tasksToBeDeleted); - } - - List tasksIdsToBeDeleted = tasksToBeDeleted.stream() - .map(task -> task.getTaskId()) - .collect(Collectors.toList()); - BulkOperationResults results = taskanaEngineImpl.getTaskService() - .deleteTasks(tasksIdsToBeDeleted); - LOGGER.debug("{} tasks deleted.", tasksIdsToBeDeleted.size() - results.getFailedIds().size()); - for (String failedId : results.getFailedIds()) { - LOGGER.warn("Task with id {} could not be deleted. Reason: {}", failedId, results.getErrorForId(failedId)); - } - LOGGER.debug("exit from deleteTasks(), returning {}", tasksIdsToBeDeleted.size() - results.getFailedIds().size()); - return tasksIdsToBeDeleted.size() - results.getFailedIds().size(); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "exit from getTasksCompletedBefore(), returning {}", LoggerUtils.listToString(taskList)); } - private void scheduleNextCleanupJob() { - LOGGER.debug("Entry to scheduleNextCleanupJob."); - ScheduledJob job = new ScheduledJob(); - job.setType(ScheduledJob.Type.TASKCLEANUPJOB); - job.setDue(getNextDueForTaskCleanupJob()); - taskanaEngineImpl.getJobService().createJob(job); - LOGGER.debug("Exit from scheduleNextCleanupJob."); + return taskList; + } + + private int deleteTasksTransactionally(List tasksToBeDeleted) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "entry to deleteTasksTransactionally(tasksToBeDeleted = {})", + LoggerUtils.listToString(tasksToBeDeleted)); } - private Instant getNextDueForTaskCleanupJob() { - Instant nextRunAt = firstRun; - while (nextRunAt.isBefore(Instant.now())) { - nextRunAt = nextRunAt.plus(runEvery); - } - LOGGER.info("Scheduling next run of the TaskCleanupJob for {}", nextRunAt); - return nextRunAt; + int deletedTaskCount = 0; + if (txProvider != null) { + int count = + (Integer) + txProvider.executeInTransaction( + () -> { + try { + return deleteTasks(tasksToBeDeleted); + } catch (Exception e) { + LOGGER.warn("Could not delete tasks.", e); + return 0; + } + }); + LOGGER.debug("exit from deleteTasksTransactionally(), returning {}", count); + return count; + } else { + try { + deletedTaskCount = deleteTasks(tasksToBeDeleted); + } catch (Exception e) { + LOGGER.warn("Could not delete tasks.", e); + } + } + LOGGER.debug("exit from deleteTasksTransactionally(), returning {}", deletedTaskCount); + return deletedTaskCount; + } + + private int deleteTasks(List tasksToBeDeleted) throws InvalidArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("entry to deleteTasks(tasksToBeDeleted = {})", tasksToBeDeleted); } - /** - * Initializes the TaskCleanupJob schedule.
- * All scheduled cleanup jobs are cancelled/deleted and a new one is scheduled. - * - * @param taskanaEngine - * the TASKANA engine. - */ - public static void initializeSchedule(TaskanaEngine taskanaEngine) { - TaskCleanupJob job = new TaskCleanupJob(taskanaEngine, null, null); - job.scheduleNextCleanupJob(); + List tasksIdsToBeDeleted = + tasksToBeDeleted.stream().map(task -> task.getTaskId()).collect(Collectors.toList()); + BulkOperationResults results = + taskanaEngineImpl.getTaskService().deleteTasks(tasksIdsToBeDeleted); + LOGGER.debug("{} tasks deleted.", tasksIdsToBeDeleted.size() - results.getFailedIds().size()); + for (String failedId : results.getFailedIds()) { + LOGGER.warn( + "Task with id {} could not be deleted. Reason: {}", + failedId, + results.getErrorForId(failedId)); } + LOGGER.debug( + "exit from deleteTasks(), returning {}", + tasksIdsToBeDeleted.size() - results.getFailedIds().size()); + return tasksIdsToBeDeleted.size() - results.getFailedIds().size(); + } + private void scheduleNextCleanupJob() { + LOGGER.debug("Entry to scheduleNextCleanupJob."); + ScheduledJob job = new ScheduledJob(); + job.setType(ScheduledJob.Type.TASKCLEANUPJOB); + job.setDue(getNextDueForTaskCleanupJob()); + taskanaEngineImpl.getJobService().createJob(job); + LOGGER.debug("Exit from scheduleNextCleanupJob."); + } + + private Instant getNextDueForTaskCleanupJob() { + Instant nextRunAt = firstRun; + while (nextRunAt.isBefore(Instant.now())) { + nextRunAt = nextRunAt.plus(runEvery); + } + LOGGER.info("Scheduling next run of the TaskCleanupJob for {}", nextRunAt); + return nextRunAt; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/jobs/TaskRefreshJob.java b/lib/taskana-core/src/main/java/pro/taskana/jobs/TaskRefreshJob.java index b581dbae2..f4dee8979 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/jobs/TaskRefreshJob.java +++ b/lib/taskana-core/src/main/java/pro/taskana/jobs/TaskRefreshJob.java @@ -3,7 +3,6 @@ package pro.taskana.jobs; import java.util.Arrays; import java.util.List; import java.util.Map; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -18,43 +17,41 @@ import pro.taskana.transaction.TaskanaTransactionProvider; * * @author bbr */ - public class TaskRefreshJob extends AbstractTaskanaJob { - private static final Logger LOGGER = LoggerFactory.getLogger(TaskRefreshJob.class); + public static final String ARG_TASK_IDS = "taskIds"; + private static final Logger LOGGER = LoggerFactory.getLogger(TaskRefreshJob.class); + private List affectedTaskIds; - public static final String ARG_TASK_IDS = "taskIds"; + public TaskRefreshJob( + TaskanaEngine engine, TaskanaTransactionProvider txProvider, ScheduledJob job) { + super(engine, txProvider, job); + Map args = job.getArguments(); + String taskIdsString = args.get(ARG_TASK_IDS); + affectedTaskIds = Arrays.asList(taskIdsString.split(",")); + } - private List affectedTaskIds; - - public TaskRefreshJob(TaskanaEngine engine, TaskanaTransactionProvider txProvider, ScheduledJob job) { - super(engine, txProvider, job); - Map args = job.getArguments(); - String taskIdsString = args.get(ARG_TASK_IDS); - affectedTaskIds = Arrays.asList(taskIdsString.split(",")); - } - - @Override - public void run() throws TaskanaException { - LOGGER.info("Running TaskRefreshJob for {} tasks", affectedTaskIds.size()); + @Override + public void run() throws TaskanaException { + LOGGER.info("Running TaskRefreshJob for {} tasks", affectedTaskIds.size()); + try { + TaskServiceImpl taskService = (TaskServiceImpl) taskanaEngineImpl.getTaskService(); + for (String taskId : affectedTaskIds) { try { - TaskServiceImpl taskService = (TaskServiceImpl) taskanaEngineImpl.getTaskService(); - for (String taskId : affectedTaskIds) { - try { - taskService.refreshPriorityAndDueDate(taskId); - } catch (Exception e) { - LOGGER.warn("Task {} could not be refreshed because of exception: {}", taskId, e.getMessage()); - } - } - LOGGER.info("TaskRefreshJob ended successfully."); + taskService.refreshPriorityAndDueDate(taskId); } catch (Exception e) { - throw new TaskanaException("Error while processing TaskRefreshJob.", e); + LOGGER.warn( + "Task {} could not be refreshed because of exception: {}", taskId, e.getMessage()); } + } + LOGGER.info("TaskRefreshJob ended successfully."); + } catch (Exception e) { + throw new TaskanaException("Error while processing TaskRefreshJob.", e); } + } - @Override - public String toString() { - return "TaskRefreshJob [affectedTaskIds= " + LoggerUtils.listToString(affectedTaskIds) + "]"; - } - + @Override + public String toString() { + return "TaskRefreshJob [affectedTaskIds= " + LoggerUtils.listToString(affectedTaskIds) + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/jobs/TaskanaJob.java b/lib/taskana-core/src/main/java/pro/taskana/jobs/TaskanaJob.java index 99f5c9fb8..bf6939108 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/jobs/TaskanaJob.java +++ b/lib/taskana-core/src/main/java/pro/taskana/jobs/TaskanaJob.java @@ -2,17 +2,13 @@ package pro.taskana.jobs; import pro.taskana.exceptions.TaskanaException; -/** - * Interface for all background TASKANA jobs. - */ +/** Interface for all background TASKANA jobs. */ public interface TaskanaJob { - /** - * Runs the TaskanaJob. - * - * @throws TaskanaException - * if an exception occured during the run. - */ - void run() throws TaskanaException; - + /** + * Runs the TaskanaJob. + * + * @throws TaskanaException if an exception occured during the run. + */ + void run() throws TaskanaException; } diff --git a/lib/taskana-core/src/main/java/pro/taskana/jobs/WorkbasketCleanupJob.java b/lib/taskana-core/src/main/java/pro/taskana/jobs/WorkbasketCleanupJob.java index a19f69708..1cfdf492a 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/jobs/WorkbasketCleanupJob.java +++ b/lib/taskana-core/src/main/java/pro/taskana/jobs/WorkbasketCleanupJob.java @@ -3,7 +3,6 @@ package pro.taskana.jobs; import java.time.Duration; import java.time.Instant; import java.util.List; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -19,118 +18,131 @@ import pro.taskana.exceptions.WorkbasketNotFoundException; import pro.taskana.transaction.TaskanaTransactionProvider; /** - * Job to cleanup completed workbaskets after a period of time if there are no pending tasks associated to the workbasket. + * Job to cleanup completed workbaskets after a period of time if there are no pending tasks + * associated to the workbasket. */ public class WorkbasketCleanupJob extends AbstractTaskanaJob { - private static final Logger LOGGER = LoggerFactory.getLogger(WorkbasketCleanupJob.class); + private static final Logger LOGGER = LoggerFactory.getLogger(WorkbasketCleanupJob.class); - // Parameter - private Instant firstRun; - private Duration runEvery; - private int batchSize; + // Parameter + private Instant firstRun; + private Duration runEvery; + private int batchSize; - public WorkbasketCleanupJob(TaskanaEngine taskanaEngine, - TaskanaTransactionProvider txProvider, ScheduledJob job) { - super(taskanaEngine, txProvider, job); - firstRun = taskanaEngine.getConfiguration().getCleanupJobFirstRun(); - runEvery = taskanaEngine.getConfiguration().getCleanupJobRunEvery(); - batchSize = taskanaEngine.getConfiguration().getMaxNumberOfUpdatesPerTransaction(); - } + public WorkbasketCleanupJob( + TaskanaEngine taskanaEngine, + TaskanaTransactionProvider txProvider, + ScheduledJob job) { + super(taskanaEngine, txProvider, job); + firstRun = taskanaEngine.getConfiguration().getCleanupJobFirstRun(); + runEvery = taskanaEngine.getConfiguration().getCleanupJobRunEvery(); + batchSize = taskanaEngine.getConfiguration().getMaxNumberOfUpdatesPerTransaction(); + } - @Override - public void run() throws TaskanaException { - LOGGER.info("Running job to delete all workbaskets marked for deletion"); - try { - List workbasketsMarkedForDeletion = getWorkbasketsMarkedForDeletion(); - int totalNumberOfWorkbasketDeleted = 0; - while (workbasketsMarkedForDeletion.size() > 0) { - int upperLimit = batchSize; - if (upperLimit > workbasketsMarkedForDeletion.size()) { - upperLimit = workbasketsMarkedForDeletion.size(); - } - totalNumberOfWorkbasketDeleted += deleteWorkbasketsTransactionally( - workbasketsMarkedForDeletion.subList(0, upperLimit)); - workbasketsMarkedForDeletion.subList(0, upperLimit).clear(); - } - LOGGER.info("Job ended successfully. {} workbaskets deleted.", totalNumberOfWorkbasketDeleted); - } catch (Exception e) { - throw new TaskanaException("Error while processing WorkbasketCleanupJob.", e); - } finally { - scheduleNextCleanupJob(); + @Override + public void run() throws TaskanaException { + LOGGER.info("Running job to delete all workbaskets marked for deletion"); + try { + List workbasketsMarkedForDeletion = getWorkbasketsMarkedForDeletion(); + int totalNumberOfWorkbasketDeleted = 0; + while (workbasketsMarkedForDeletion.size() > 0) { + int upperLimit = batchSize; + if (upperLimit > workbasketsMarkedForDeletion.size()) { + upperLimit = workbasketsMarkedForDeletion.size(); } + totalNumberOfWorkbasketDeleted += + deleteWorkbasketsTransactionally(workbasketsMarkedForDeletion.subList(0, upperLimit)); + workbasketsMarkedForDeletion.subList(0, upperLimit).clear(); + } + LOGGER.info( + "Job ended successfully. {} workbaskets deleted.", totalNumberOfWorkbasketDeleted); + } catch (Exception e) { + throw new TaskanaException("Error while processing WorkbasketCleanupJob.", e); + } finally { + scheduleNextCleanupJob(); } + } - private List getWorkbasketsMarkedForDeletion() { - List workbasketList = taskanaEngineImpl.getWorkbasketService() + /** + * Initializes the WorkbasketCleanupJob schedule.
+ * All scheduled cleanup jobs are cancelled/deleted and a new one is scheduled. + * + * @param taskanaEngine the taskana engine + */ + public static void initializeSchedule(TaskanaEngine taskanaEngine) { + WorkbasketCleanupJob job = new WorkbasketCleanupJob(taskanaEngine, null, null); + job.scheduleNextCleanupJob(); + } + + private List getWorkbasketsMarkedForDeletion() { + List workbasketList = + taskanaEngineImpl + .getWorkbasketService() .createWorkbasketQuery() .markedForDeletion(true) .listValues(WorkbasketQueryColumnName.ID, BaseQuery.SortDirection.ASCENDING); - return workbasketList; - } + return workbasketList; + } - private int deleteWorkbasketsTransactionally(List workbasketsToBeDeleted) { - int deletedWorkbasketsCount = 0; - if (txProvider != null) { - int count = (Integer) txProvider.executeInTransaction(() -> { - try { - return deleteWorkbaskets(workbasketsToBeDeleted); - } catch (Exception e) { - LOGGER.warn("Could not delete workbaskets.", e); - return 0; - } - }); - return count; - } else { - try { - deletedWorkbasketsCount = deleteWorkbaskets(workbasketsToBeDeleted); - } catch (Exception e) { - LOGGER.warn("Could not delete workbaskets.", e); - } - } - return deletedWorkbasketsCount; + private int deleteWorkbasketsTransactionally(List workbasketsToBeDeleted) { + int deletedWorkbasketsCount = 0; + if (txProvider != null) { + int count = + (Integer) + txProvider.executeInTransaction( + () -> { + try { + return deleteWorkbaskets(workbasketsToBeDeleted); + } catch (Exception e) { + LOGGER.warn("Could not delete workbaskets.", e); + return 0; + } + }); + return count; + } else { + try { + deletedWorkbasketsCount = deleteWorkbaskets(workbasketsToBeDeleted); + } catch (Exception e) { + LOGGER.warn("Could not delete workbaskets.", e); + } } + return deletedWorkbasketsCount; + } - private int deleteWorkbaskets(List workbasketsToBeDeleted) - throws InvalidArgumentException, NotAuthorizedException, WorkbasketNotFoundException, WorkbasketInUseException { + private int deleteWorkbaskets(List workbasketsToBeDeleted) + throws InvalidArgumentException, NotAuthorizedException, WorkbasketNotFoundException, + WorkbasketInUseException { - BulkOperationResults results = taskanaEngineImpl.getWorkbasketService() - .deleteWorkbaskets(workbasketsToBeDeleted); - LOGGER.debug("{} workbasket deleted.", workbasketsToBeDeleted.size() - results.getFailedIds().size()); - for (String failedId : results.getFailedIds()) { - LOGGER.warn("Workbasket with id {} could not be deleted. Reason: {}", failedId, - results.getErrorForId(failedId)); - } - return workbasketsToBeDeleted.size() - results.getFailedIds().size(); + BulkOperationResults results = + taskanaEngineImpl.getWorkbasketService().deleteWorkbaskets(workbasketsToBeDeleted); + LOGGER.debug( + "{} workbasket deleted.", workbasketsToBeDeleted.size() - results.getFailedIds().size()); + for (String failedId : results.getFailedIds()) { + LOGGER.warn( + "Workbasket with id {} could not be deleted. Reason: {}", + failedId, + results.getErrorForId(failedId)); } + return workbasketsToBeDeleted.size() - results.getFailedIds().size(); + } - private void scheduleNextCleanupJob() { - LOGGER.debug("Entry to scheduleNextCleanupJob."); - ScheduledJob job = new ScheduledJob(); - job.setType(ScheduledJob.Type.WORKBASKETCLEANUPJOB); - job.setDue(getNextDueForWorkbasketCleanupJob()); - taskanaEngineImpl.getJobService().createJob(job); - LOGGER.debug("Exit from scheduleNextCleanupJob."); - } + private void scheduleNextCleanupJob() { + LOGGER.debug("Entry to scheduleNextCleanupJob."); + ScheduledJob job = new ScheduledJob(); + job.setType(ScheduledJob.Type.WORKBASKETCLEANUPJOB); + job.setDue(getNextDueForWorkbasketCleanupJob()); + taskanaEngineImpl.getJobService().createJob(job); + LOGGER.debug("Exit from scheduleNextCleanupJob."); + } - private Instant getNextDueForWorkbasketCleanupJob() { - Instant nextRunAt = firstRun; - while (nextRunAt.isBefore(Instant.now())) { - nextRunAt = nextRunAt.plus(runEvery); - } - LOGGER.info("Scheduling next run of the WorkbasketCleanupJob for {}", nextRunAt); - return nextRunAt; - } - - /** - * Initializes the WorkbasketCleanupJob schedule.
- * All scheduled cleanup jobs are cancelled/deleted and a new one is scheduled. - * - * @param taskanaEngine the taskana engine - */ - public static void initializeSchedule(TaskanaEngine taskanaEngine) { - WorkbasketCleanupJob job = new WorkbasketCleanupJob(taskanaEngine, null, null); - job.scheduleNextCleanupJob(); + private Instant getNextDueForWorkbasketCleanupJob() { + Instant nextRunAt = firstRun; + while (nextRunAt.isBefore(Instant.now())) { + nextRunAt = nextRunAt.plus(runEvery); } + LOGGER.info("Scheduling next run of the WorkbasketCleanupJob for {}", nextRunAt); + return nextRunAt; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/mappings/AttachmentMapper.java b/lib/taskana-core/src/main/java/pro/taskana/mappings/AttachmentMapper.java index 182e65fd6..9545e342e 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/mappings/AttachmentMapper.java +++ b/lib/taskana-core/src/main/java/pro/taskana/mappings/AttachmentMapper.java @@ -2,7 +2,6 @@ package pro.taskana.mappings; import java.util.List; import java.util.Map; - import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; @@ -16,22 +15,23 @@ import pro.taskana.impl.AttachmentImpl; import pro.taskana.impl.AttachmentSummaryImpl; import pro.taskana.impl.persistence.MapTypeHandler; -/** - * This class is the mybatis mapping of Attachment. - */ +/** This class is the mybatis mapping of Attachment. */ public interface AttachmentMapper { - @Insert("INSERT INTO ATTACHMENT (ID, TASK_ID, CREATED, MODIFIED, CLASSIFICATION_KEY, CLASSIFICATION_ID, REF_COMPANY, REF_SYSTEM, REF_INSTANCE, REF_TYPE, REF_VALUE, CHANNEL, RECEIVED, CUSTOM_ATTRIBUTES) " - + "VALUES (#{att.id}, #{att.taskId}, #{att.created}, #{att.modified}, #{att.classificationSummary.key}, #{att.classificationSummary.id}, #{att.objectReference.company}, #{att.objectReference.system}, #{att.objectReference.systemInstance}, " - + " #{att.objectReference.type}, #{att.objectReference.value}, #{att.channel}, #{att.received}, #{att.customAttributes,jdbcType=CLOB,javaType=java.util.Map,typeHandler=pro.taskana.impl.persistence.MapTypeHandler} )") - void insert(@Param("att") AttachmentImpl att); + @Insert( + "INSERT INTO ATTACHMENT (ID, TASK_ID, CREATED, MODIFIED, CLASSIFICATION_KEY, CLASSIFICATION_ID, REF_COMPANY, REF_SYSTEM, REF_INSTANCE, REF_TYPE, REF_VALUE, CHANNEL, RECEIVED, CUSTOM_ATTRIBUTES) " + + "VALUES (#{att.id}, #{att.taskId}, #{att.created}, #{att.modified}, #{att.classificationSummary.key}, #{att.classificationSummary.id}, #{att.objectReference.company}, #{att.objectReference.system}, #{att.objectReference.systemInstance}, " + + " #{att.objectReference.type}, #{att.objectReference.value}, #{att.channel}, #{att.received}, #{att.customAttributes,jdbcType=CLOB,javaType=java.util.Map,typeHandler=pro.taskana.impl.persistence.MapTypeHandler} )") + void insert(@Param("att") AttachmentImpl att); - @Select("") - @Results(value = { + @Select( + "") + @Results( + value = { @Result(property = "id", column = "ID"), @Result(property = "taskId", column = "TASK_ID"), @Result(property = "created", column = "CREATED"), @@ -45,17 +45,22 @@ public interface AttachmentMapper { @Result(property = "objectReference.value", column = "REF_VALUE"), @Result(property = "channel", column = "CHANNEL"), @Result(property = "received", column = "RECEIVED"), - @Result(property = "customAttributes", column = "CUSTOM_ATTRIBUTES", - javaType = Map.class, typeHandler = MapTypeHandler.class) - }) - List findAttachmentsByTaskId(@Param("taskId") String taskId); + @Result( + property = "customAttributes", + column = "CUSTOM_ATTRIBUTES", + javaType = Map.class, + typeHandler = MapTypeHandler.class) + }) + List findAttachmentsByTaskId(@Param("taskId") String taskId); - @Select("") - @Results(value = { + @Select( + "") + @Results( + value = { @Result(property = "id", column = "ID"), @Result(property = "taskId", column = "TASK_ID"), @Result(property = "created", column = "CREATED"), @@ -69,19 +74,24 @@ public interface AttachmentMapper { @Result(property = "objectReference.value", column = "REF_VALUE"), @Result(property = "channel", column = "CHANNEL"), @Result(property = "received", column = "RECEIVED"), - @Result(property = "customAttributes", column = "CUSTOM_ATTRIBUTES", - javaType = Map.class, typeHandler = MapTypeHandler.class) - }) - AttachmentImpl getAttachment(@Param("attachmentId") String attachmentId); + @Result( + property = "customAttributes", + column = "CUSTOM_ATTRIBUTES", + javaType = Map.class, + typeHandler = MapTypeHandler.class) + }) + AttachmentImpl getAttachment(@Param("attachmentId") String attachmentId); - @Select("") - @Results(value = { + @Select( + "") + @Results( + value = { @Result(property = "id", column = "ID"), @Result(property = "taskId", column = "TASK_ID"), @Result(property = "created", column = "CREATED"), @@ -95,33 +105,39 @@ public interface AttachmentMapper { @Result(property = "objectReference.value", column = "REF_VALUE"), @Result(property = "channel", column = "CHANNEL"), @Result(property = "received", column = "RECEIVED") - }) - List findAttachmentSummariesByTaskIds(@Param("taskIds") String[] taskIds); + }) + List findAttachmentSummariesByTaskIds(@Param("taskIds") String[] taskIds); - @Delete("DELETE FROM ATTACHMENT WHERE ID=#{attachmentId}") - void deleteAttachment(@Param("attachmentId") String attachmentId); + @Delete("DELETE FROM ATTACHMENT WHERE ID=#{attachmentId}") + void deleteAttachment(@Param("attachmentId") String attachmentId); - @Update("UPDATE ATTACHMENT SET TASK_ID = #{taskId}, CREATED = #{created}, MODIFIED = #{modified}," - + " CLASSIFICATION_KEY = #{classificationSummary.key}, CLASSIFICATION_ID = #{classificationSummary.id}, REF_COMPANY = #{objectReference.company}, REF_SYSTEM = #{objectReference.system}," - + " REF_INSTANCE = #{objectReference.systemInstance}, REF_TYPE = #{objectReference.type}, REF_VALUE = #{objectReference.value}," - + " CHANNEL = #{channel}, RECEIVED = #{received}, CUSTOM_ATTRIBUTES = #{customAttributes,jdbcType=CLOB,javaType=java.util.Map,typeHandler=pro.taskana.impl.persistence.MapTypeHandler}" - + " WHERE ID = #{id}") - void update(AttachmentImpl attachment); + @Update( + "UPDATE ATTACHMENT SET TASK_ID = #{taskId}, CREATED = #{created}, MODIFIED = #{modified}," + + " CLASSIFICATION_KEY = #{classificationSummary.key}, CLASSIFICATION_ID = #{classificationSummary.id}, REF_COMPANY = #{objectReference.company}, REF_SYSTEM = #{objectReference.system}," + + " REF_INSTANCE = #{objectReference.systemInstance}, REF_TYPE = #{objectReference.type}, REF_VALUE = #{objectReference.value}," + + " CHANNEL = #{channel}, RECEIVED = #{received}, CUSTOM_ATTRIBUTES = #{customAttributes,jdbcType=CLOB,javaType=java.util.Map,typeHandler=pro.taskana.impl.persistence.MapTypeHandler}" + + " WHERE ID = #{id}") + void update(AttachmentImpl attachment); - @Select("") - @Results(value = { - @Result(property = "customAttributes", column = "CUSTOM_ATTRIBUTES", - javaType = String.class, typeHandler = ClobTypeHandler.class) - }) - String getCustomAttributesAsString(@Param("attachmentId") String attachmentId); - - @Select("") - @Results(value = { - @Result(property = "taskId", column = "TASK_ID")}) - List findTaskIdsAffectedByClassificationChange(@Param("classificationId") String classificationId); + @Select( + "") + @Results( + value = { + @Result( + property = "customAttributes", + column = "CUSTOM_ATTRIBUTES", + javaType = String.class, + typeHandler = ClobTypeHandler.class) + }) + String getCustomAttributesAsString(@Param("attachmentId") String attachmentId); + @Select( + "") + @Results(value = {@Result(property = "taskId", column = "TASK_ID")}) + List findTaskIdsAffectedByClassificationChange( + @Param("classificationId") String classificationId); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/mappings/ClassificationMapper.java b/lib/taskana-core/src/main/java/pro/taskana/mappings/ClassificationMapper.java index 74b9ea9c2..18796dead 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/mappings/ClassificationMapper.java +++ b/lib/taskana-core/src/main/java/pro/taskana/mappings/ClassificationMapper.java @@ -10,81 +10,85 @@ import org.apache.ibatis.annotations.Update; import pro.taskana.impl.ClassificationImpl; -/** - * This class is the mybatis mapping of classifications. - */ +/** This class is the mybatis mapping of classifications. */ public interface ClassificationMapper { - @Select("") - @Results({@Result(property = "id", column = "ID"), - @Result(property = "key", column = "KEY"), - @Result(property = "parentId", column = "PARENT_ID"), - @Result(property = "parentKey", column = "PARENT_KEY"), - @Result(property = "category", column = "CATEGORY"), - @Result(property = "type", column = "TYPE"), - @Result(property = "domain", column = "DOMAIN"), - @Result(property = "isValidInDomain", column = "VALID_IN_DOMAIN"), - @Result(property = "created", column = "CREATED"), - @Result(property = "modified", column = "MODIFIED"), - @Result(property = "name", column = "NAME"), - @Result(property = "description", column = "DESCRIPTION"), - @Result(property = "priority", column = "PRIORITY"), - @Result(property = "serviceLevel", column = "SERVICE_LEVEL"), - @Result(property = "applicationEntryPoint", column = "APPLICATION_ENTRY_POINT"), - @Result(property = "custom1", column = "CUSTOM_1"), - @Result(property = "custom2", column = "CUSTOM_2"), - @Result(property = "custom3", column = "CUSTOM_3"), - @Result(property = "custom4", column = "CUSTOM_4"), - @Result(property = "custom5", column = "CUSTOM_5"), - @Result(property = "custom6", column = "CUSTOM_6"), - @Result(property = "custom7", column = "CUSTOM_7"), - @Result(property = "custom8", column = "CUSTOM_8")}) - ClassificationImpl findByKeyAndDomain(@Param("key") String key, @Param("domain") String domain); + @Select( + "") + @Results({ + @Result(property = "id", column = "ID"), + @Result(property = "key", column = "KEY"), + @Result(property = "parentId", column = "PARENT_ID"), + @Result(property = "parentKey", column = "PARENT_KEY"), + @Result(property = "category", column = "CATEGORY"), + @Result(property = "type", column = "TYPE"), + @Result(property = "domain", column = "DOMAIN"), + @Result(property = "isValidInDomain", column = "VALID_IN_DOMAIN"), + @Result(property = "created", column = "CREATED"), + @Result(property = "modified", column = "MODIFIED"), + @Result(property = "name", column = "NAME"), + @Result(property = "description", column = "DESCRIPTION"), + @Result(property = "priority", column = "PRIORITY"), + @Result(property = "serviceLevel", column = "SERVICE_LEVEL"), + @Result(property = "applicationEntryPoint", column = "APPLICATION_ENTRY_POINT"), + @Result(property = "custom1", column = "CUSTOM_1"), + @Result(property = "custom2", column = "CUSTOM_2"), + @Result(property = "custom3", column = "CUSTOM_3"), + @Result(property = "custom4", column = "CUSTOM_4"), + @Result(property = "custom5", column = "CUSTOM_5"), + @Result(property = "custom6", column = "CUSTOM_6"), + @Result(property = "custom7", column = "CUSTOM_7"), + @Result(property = "custom8", column = "CUSTOM_8") + }) + ClassificationImpl findByKeyAndDomain(@Param("key") String key, @Param("domain") String domain); - @Select("") - @Results({@Result(property = "id", column = "ID"), - @Result(property = "key", column = "KEY"), - @Result(property = "parentId", column = "PARENT_ID"), - @Result(property = "parentKey", column = "PARENT_KEY"), - @Result(property = "category", column = "CATEGORY"), - @Result(property = "type", column = "TYPE"), - @Result(property = "domain", column = "DOMAIN"), - @Result(property = "isValidInDomain", column = "VALID_IN_DOMAIN"), - @Result(property = "created", column = "CREATED"), - @Result(property = "modified", column = "MODIFIED"), - @Result(property = "name", column = "NAME"), - @Result(property = "description", column = "DESCRIPTION"), - @Result(property = "priority", column = "PRIORITY"), - @Result(property = "serviceLevel", column = "SERVICE_LEVEL"), - @Result(property = "applicationEntryPoint", column = "APPLICATION_ENTRY_POINT"), - @Result(property = "custom1", column = "CUSTOM_1"), - @Result(property = "custom2", column = "CUSTOM_2"), - @Result(property = "custom3", column = "CUSTOM_3"), - @Result(property = "custom4", column = "CUSTOM_4"), - @Result(property = "custom5", column = "CUSTOM_5"), - @Result(property = "custom6", column = "CUSTOM_6"), - @Result(property = "custom7", column = "CUSTOM_7"), - @Result(property = "custom8", column = "CUSTOM_8")}) - ClassificationImpl findById(@Param("id") String id); + @Select( + "") + @Results({ + @Result(property = "id", column = "ID"), + @Result(property = "key", column = "KEY"), + @Result(property = "parentId", column = "PARENT_ID"), + @Result(property = "parentKey", column = "PARENT_KEY"), + @Result(property = "category", column = "CATEGORY"), + @Result(property = "type", column = "TYPE"), + @Result(property = "domain", column = "DOMAIN"), + @Result(property = "isValidInDomain", column = "VALID_IN_DOMAIN"), + @Result(property = "created", column = "CREATED"), + @Result(property = "modified", column = "MODIFIED"), + @Result(property = "name", column = "NAME"), + @Result(property = "description", column = "DESCRIPTION"), + @Result(property = "priority", column = "PRIORITY"), + @Result(property = "serviceLevel", column = "SERVICE_LEVEL"), + @Result(property = "applicationEntryPoint", column = "APPLICATION_ENTRY_POINT"), + @Result(property = "custom1", column = "CUSTOM_1"), + @Result(property = "custom2", column = "CUSTOM_2"), + @Result(property = "custom3", column = "CUSTOM_3"), + @Result(property = "custom4", column = "CUSTOM_4"), + @Result(property = "custom5", column = "CUSTOM_5"), + @Result(property = "custom6", column = "CUSTOM_6"), + @Result(property = "custom7", column = "CUSTOM_7"), + @Result(property = "custom8", column = "CUSTOM_8") + }) + ClassificationImpl findById(@Param("id") String id); - @Insert("INSERT INTO CLASSIFICATION (ID, KEY, PARENT_ID, PARENT_KEY, CATEGORY, TYPE, DOMAIN, VALID_IN_DOMAIN, CREATED, MODIFIED, NAME, DESCRIPTION, PRIORITY, SERVICE_LEVEL, APPLICATION_ENTRY_POINT, CUSTOM_1, CUSTOM_2, CUSTOM_3, CUSTOM_4, CUSTOM_5, CUSTOM_6, CUSTOM_7, CUSTOM_8) VALUES (#{classification.id}, #{classification.key}, #{classification.parentId}, #{classification.parentKey}, #{classification.category}, #{classification.type}, #{classification.domain}, #{classification.isValidInDomain}, #{classification.created}, #{classification.modified}, #{classification.name}, #{classification.description}, #{classification.priority}, #{classification.serviceLevel}, #{classification.applicationEntryPoint}, #{classification.custom1}, #{classification.custom2}, #{classification.custom3}, #{classification.custom4}, #{classification.custom5}, #{classification.custom6}, #{classification.custom7}, #{classification.custom8})") - void insert(@Param("classification") ClassificationImpl classification); + @Insert( + "INSERT INTO CLASSIFICATION (ID, KEY, PARENT_ID, PARENT_KEY, CATEGORY, TYPE, DOMAIN, VALID_IN_DOMAIN, CREATED, MODIFIED, NAME, DESCRIPTION, PRIORITY, SERVICE_LEVEL, APPLICATION_ENTRY_POINT, CUSTOM_1, CUSTOM_2, CUSTOM_3, CUSTOM_4, CUSTOM_5, CUSTOM_6, CUSTOM_7, CUSTOM_8) VALUES (#{classification.id}, #{classification.key}, #{classification.parentId}, #{classification.parentKey}, #{classification.category}, #{classification.type}, #{classification.domain}, #{classification.isValidInDomain}, #{classification.created}, #{classification.modified}, #{classification.name}, #{classification.description}, #{classification.priority}, #{classification.serviceLevel}, #{classification.applicationEntryPoint}, #{classification.custom1}, #{classification.custom2}, #{classification.custom3}, #{classification.custom4}, #{classification.custom5}, #{classification.custom6}, #{classification.custom7}, #{classification.custom8})") + void insert(@Param("classification") ClassificationImpl classification); - @Update( - value = "UPDATE CLASSIFICATION SET KEY = #{classification.key}, PARENT_ID = #{classification.parentId}, PARENT_KEY = #{classification.parentKey}, CATEGORY = #{classification.category}, TYPE = #{classification.type}, MODIFIED = #{classification.modified}, NAME = #{classification.name}, DESCRIPTION = #{classification.description}, PRIORITY = #{classification.priority}, SERVICE_LEVEL = #{classification.serviceLevel}, DOMAIN = #{classification.domain}, VALID_IN_DOMAIN = #{classification.isValidInDomain}, APPLICATION_ENTRY_POINT = #{classification.applicationEntryPoint}, CUSTOM_1 = #{classification.custom1}, CUSTOM_2 = #{classification.custom2}, CUSTOM_3 = #{classification.custom3}, CUSTOM_4 = #{classification.custom4}, CUSTOM_5 = #{classification.custom5}, CUSTOM_6 = #{classification.custom6}, CUSTOM_7 = #{classification.custom7}, CUSTOM_8 = #{classification.custom8} WHERE ID = #{classification.id}") - void update(@Param("classification") ClassificationImpl classification); - - @Delete("DELETE FROM CLASSIFICATION " - + "WHERE ID = #{classificationId}") - void deleteClassification(@Param("classificationId") String classificationId); + @Update( + value = + "UPDATE CLASSIFICATION SET KEY = #{classification.key}, PARENT_ID = #{classification.parentId}, PARENT_KEY = #{classification.parentKey}, CATEGORY = #{classification.category}, TYPE = #{classification.type}, MODIFIED = #{classification.modified}, NAME = #{classification.name}, DESCRIPTION = #{classification.description}, PRIORITY = #{classification.priority}, SERVICE_LEVEL = #{classification.serviceLevel}, DOMAIN = #{classification.domain}, VALID_IN_DOMAIN = #{classification.isValidInDomain}, APPLICATION_ENTRY_POINT = #{classification.applicationEntryPoint}, CUSTOM_1 = #{classification.custom1}, CUSTOM_2 = #{classification.custom2}, CUSTOM_3 = #{classification.custom3}, CUSTOM_4 = #{classification.custom4}, CUSTOM_5 = #{classification.custom5}, CUSTOM_6 = #{classification.custom6}, CUSTOM_7 = #{classification.custom7}, CUSTOM_8 = #{classification.custom8} WHERE ID = #{classification.id}") + void update(@Param("classification") ClassificationImpl classification); + @Delete("DELETE FROM CLASSIFICATION " + "WHERE ID = #{classificationId}") + void deleteClassification(@Param("classificationId") String classificationId); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/mappings/CustomPropertySelector.java b/lib/taskana-core/src/main/java/pro/taskana/mappings/CustomPropertySelector.java index cd5afbe86..cfbf618ac 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/mappings/CustomPropertySelector.java +++ b/lib/taskana-core/src/main/java/pro/taskana/mappings/CustomPropertySelector.java @@ -9,223 +9,252 @@ import pro.taskana.exceptions.InvalidArgumentException; */ public class CustomPropertySelector { - boolean custom1 = false; - boolean custom2 = false; - boolean custom3 = false; - boolean custom4 = false; - boolean custom5 = false; - boolean custom6 = false; - boolean custom7 = false; - boolean custom8 = false; - boolean custom9 = false; - boolean custom10 = false; - boolean custom11 = false; - boolean custom12 = false; - boolean custom13 = false; - boolean custom14 = false; - boolean custom15 = false; - boolean custom16 = false; + boolean custom1 = false; + boolean custom2 = false; + boolean custom3 = false; + boolean custom4 = false; + boolean custom5 = false; + boolean custom6 = false; + boolean custom7 = false; + boolean custom8 = false; + boolean custom9 = false; + boolean custom10 = false; + boolean custom11 = false; + boolean custom12 = false; + boolean custom13 = false; + boolean custom14 = false; + boolean custom15 = false; + boolean custom16 = false; - public void setCustomProperty(String propertyNumber, boolean value) - throws InvalidArgumentException { - int num = 0; - try { - num = Integer.parseInt(propertyNumber); - } catch (NumberFormatException e) { - throw new InvalidArgumentException( - "propertyNumber '" + propertyNumber + "' cannot be converted to a number between 1 and 16"); - } - - switch (num) { - case 1: - this.setCustom1(value); - break; - case 2: - this.setCustom2(value); - break; - case 3: - this.setCustom3(value); - break; - case 4: - this.setCustom4(value); - break; - case 5: - this.setCustom5(value); - break; - case 6: - this.setCustom6(value); - break; - case 7: - this.setCustom7(value); - break; - case 8: - this.setCustom8(value); - break; - case 9: - this.setCustom9(value); - break; - case 10: - this.setCustom10(value); - break; - case 11: - this.setCustom11(value); - break; - case 12: - this.setCustom12(value); - break; - case 13: - this.setCustom13(value); - break; - case 14: - this.setCustom14(value); - break; - case 15: - this.setCustom15(value); - break; - case 16: - this.setCustom16(value); - break; - default: - throw new InvalidArgumentException( - "propertyNumber '" + propertyNumber + "' does not represent a number between 1 and 16"); - } + public void setCustomProperty(String propertyNumber, boolean value) + throws InvalidArgumentException { + int num = 0; + try { + num = Integer.parseInt(propertyNumber); + } catch (NumberFormatException e) { + throw new InvalidArgumentException( + "propertyNumber '" + + propertyNumber + + "' cannot be converted to a number between 1 and 16"); } - public boolean isCustom1() { - return custom1; + switch (num) { + case 1: + this.setCustom1(value); + break; + case 2: + this.setCustom2(value); + break; + case 3: + this.setCustom3(value); + break; + case 4: + this.setCustom4(value); + break; + case 5: + this.setCustom5(value); + break; + case 6: + this.setCustom6(value); + break; + case 7: + this.setCustom7(value); + break; + case 8: + this.setCustom8(value); + break; + case 9: + this.setCustom9(value); + break; + case 10: + this.setCustom10(value); + break; + case 11: + this.setCustom11(value); + break; + case 12: + this.setCustom12(value); + break; + case 13: + this.setCustom13(value); + break; + case 14: + this.setCustom14(value); + break; + case 15: + this.setCustom15(value); + break; + case 16: + this.setCustom16(value); + break; + default: + throw new InvalidArgumentException( + "propertyNumber '" + propertyNumber + "' does not represent a number between 1 and 16"); } + } - public void setCustom1(boolean custom1) { - this.custom1 = custom1; - } + public boolean isCustom1() { + return custom1; + } - public boolean isCustom2() { - return custom2; - } + public void setCustom1(boolean custom1) { + this.custom1 = custom1; + } - public void setCustom2(boolean custom2) { - this.custom2 = custom2; - } + public boolean isCustom2() { + return custom2; + } - public boolean isCustom3() { - return custom3; - } + public void setCustom2(boolean custom2) { + this.custom2 = custom2; + } - public void setCustom3(boolean custom3) { - this.custom3 = custom3; - } + public boolean isCustom3() { + return custom3; + } - public boolean isCustom4() { - return custom4; - } + public void setCustom3(boolean custom3) { + this.custom3 = custom3; + } - public void setCustom4(boolean custom4) { - this.custom4 = custom4; - } + public boolean isCustom4() { + return custom4; + } - public boolean isCustom5() { - return custom5; - } + public void setCustom4(boolean custom4) { + this.custom4 = custom4; + } - public void setCustom5(boolean custom5) { - this.custom5 = custom5; - } + public boolean isCustom5() { + return custom5; + } - public boolean isCustom6() { - return custom6; - } + public void setCustom5(boolean custom5) { + this.custom5 = custom5; + } - public void setCustom6(boolean custom6) { - this.custom6 = custom6; - } + public boolean isCustom6() { + return custom6; + } - public boolean isCustom7() { - return custom7; - } + public void setCustom6(boolean custom6) { + this.custom6 = custom6; + } - public void setCustom7(boolean custom7) { - this.custom7 = custom7; - } + public boolean isCustom7() { + return custom7; + } - public boolean isCustom8() { - return custom8; - } + public void setCustom7(boolean custom7) { + this.custom7 = custom7; + } - public void setCustom8(boolean custom8) { - this.custom8 = custom8; - } + public boolean isCustom8() { + return custom8; + } - public boolean isCustom9() { - return custom9; - } + public void setCustom8(boolean custom8) { + this.custom8 = custom8; + } - public void setCustom9(boolean custom9) { - this.custom9 = custom9; - } + public boolean isCustom9() { + return custom9; + } - public boolean isCustom10() { - return custom10; - } + public void setCustom9(boolean custom9) { + this.custom9 = custom9; + } - public void setCustom10(boolean custom10) { - this.custom10 = custom10; - } + public boolean isCustom10() { + return custom10; + } - public boolean isCustom11() { - return custom11; - } + public void setCustom10(boolean custom10) { + this.custom10 = custom10; + } - public void setCustom11(boolean custom11) { - this.custom11 = custom11; - } + public boolean isCustom11() { + return custom11; + } - public boolean isCustom12() { - return custom12; - } + public void setCustom11(boolean custom11) { + this.custom11 = custom11; + } - public void setCustom12(boolean custom12) { - this.custom12 = custom12; - } + public boolean isCustom12() { + return custom12; + } - public boolean isCustom13() { - return custom13; - } + public void setCustom12(boolean custom12) { + this.custom12 = custom12; + } - public void setCustom13(boolean custom13) { - this.custom13 = custom13; - } + public boolean isCustom13() { + return custom13; + } - public boolean isCustom14() { - return custom14; - } + public void setCustom13(boolean custom13) { + this.custom13 = custom13; + } - public void setCustom14(boolean custom14) { - this.custom14 = custom14; - } + public boolean isCustom14() { + return custom14; + } - public boolean isCustom15() { - return custom15; - } + public void setCustom14(boolean custom14) { + this.custom14 = custom14; + } - public void setCustom15(boolean custom15) { - this.custom15 = custom15; - } + public boolean isCustom15() { + return custom15; + } - public boolean isCustom16() { - return custom16; - } + public void setCustom15(boolean custom15) { + this.custom15 = custom15; + } - public void setCustom16(boolean custom16) { - this.custom16 = custom16; - } + public boolean isCustom16() { + return custom16; + } - @Override - public String toString() { - return "CustomPropertySelector [custom1=" + custom1 + ", custom2=" + custom2 + ", custom3=" + custom3 - + ", custom4=" + custom4 + ", custom5=" + custom5 + ", custom6=" + custom6 + ", custom7=" + custom7 - + ", custom8=" + custom8 + ", custom9=" + custom9 + ", custom10=" + custom10 + ", custom11=" + custom11 - + ", custom12=" + custom12 + ", custom13=" + custom13 + ", custom14=" + custom14 + ", custom15=" + custom15 - + ", custom16=" + custom16 + "]"; - } + public void setCustom16(boolean custom16) { + this.custom16 = custom16; + } + @Override + public String toString() { + return "CustomPropertySelector [custom1=" + + custom1 + + ", custom2=" + + custom2 + + ", custom3=" + + custom3 + + ", custom4=" + + custom4 + + ", custom5=" + + custom5 + + ", custom6=" + + custom6 + + ", custom7=" + + custom7 + + ", custom8=" + + custom8 + + ", custom9=" + + custom9 + + ", custom10=" + + custom10 + + ", custom11=" + + custom11 + + ", custom12=" + + custom12 + + ", custom13=" + + custom13 + + ", custom14=" + + custom14 + + ", custom15=" + + custom15 + + ", custom16=" + + custom16 + + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/mappings/DistributionTargetMapper.java b/lib/taskana-core/src/main/java/pro/taskana/mappings/DistributionTargetMapper.java index f6a7562b5..43a630acb 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/mappings/DistributionTargetMapper.java +++ b/lib/taskana-core/src/main/java/pro/taskana/mappings/DistributionTargetMapper.java @@ -1,39 +1,43 @@ package pro.taskana.mappings; import java.util.List; - import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; -/** - * This class is the mybatis mapping of distribution targets. - */ +/** This class is the mybatis mapping of distribution targets. */ public interface DistributionTargetMapper { - @Insert("INSERT INTO DISTRIBUTION_TARGETS (SOURCE_ID, TARGET_ID) VALUES (#{sourceId}, #{targetId})") - void insert(@Param("sourceId") String sourceId, @Param("targetId") String targetId); + @Insert( + "INSERT INTO DISTRIBUTION_TARGETS (SOURCE_ID, TARGET_ID) VALUES (#{sourceId}, #{targetId})") + void insert(@Param("sourceId") String sourceId, @Param("targetId") String targetId); - @Delete("DELETE FROM DISTRIBUTION_TARGETS WHERE SOURCE_ID = #{sourceId} AND TARGET_ID = #{targetId}") - void delete(@Param("sourceId") String sourceId, @Param("targetId") String targetId); + @Delete( + "DELETE FROM DISTRIBUTION_TARGETS WHERE SOURCE_ID = #{sourceId} AND TARGET_ID = #{targetId}") + void delete(@Param("sourceId") String sourceId, @Param("targetId") String targetId); - @Select("") - List findBySourceId(@Param("sourceId") String sourceId); + @Select( + "") + List findBySourceId(@Param("sourceId") String sourceId); - @Select("") - int getNumberOfDistributionTargets(@Param("sourceId") String sourceId, @Param("targetId") String targetId); + @Select( + "") + int getNumberOfDistributionTargets( + @Param("sourceId") String sourceId, @Param("targetId") String targetId); - @Delete("") - void deleteMultipleBySourceId(@Param("sourceId") String sourceId, @Param("targetId") List targetId); + @Delete( + "") + void deleteMultipleBySourceId( + @Param("sourceId") String sourceId, @Param("targetId") List targetId); - @Delete("DELETE FROM DISTRIBUTION_TARGETS WHERE SOURCE_ID = #{sourceId}") - void deleteAllDistributionTargetsBySourceId(@Param("sourceId") String sourceId); + @Delete("DELETE FROM DISTRIBUTION_TARGETS WHERE SOURCE_ID = #{sourceId}") + void deleteAllDistributionTargetsBySourceId(@Param("sourceId") String sourceId); - @Delete("DELETE FROM DISTRIBUTION_TARGETS WHERE TARGET_ID = #{targetId}") - void deleteAllDistributionTargetsByTargetId(@Param("targetId") String targetId); + @Delete("DELETE FROM DISTRIBUTION_TARGETS WHERE TARGET_ID = #{targetId}") + void deleteAllDistributionTargetsByTargetId(@Param("targetId") String targetId); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/mappings/JobMapper.java b/lib/taskana-core/src/main/java/pro/taskana/mappings/JobMapper.java index b41233445..7944e0c91 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/mappings/JobMapper.java +++ b/lib/taskana-core/src/main/java/pro/taskana/mappings/JobMapper.java @@ -2,7 +2,6 @@ package pro.taskana.mappings; import java.util.List; import java.util.Map; - import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; @@ -14,34 +13,34 @@ import org.apache.ibatis.annotations.Update; import pro.taskana.impl.persistence.MapTypeHandler; import pro.taskana.jobs.ScheduledJob; -/** - * This class is the mybatis mapping of the JOB table. - */ +/** This class is the mybatis mapping of the JOB table. */ public interface JobMapper { - @Insert("") - void insertJob(@Param("job") ScheduledJob job); + @Insert( + "") + void insertJob(@Param("job") ScheduledJob job); - @Select("") - - @Results(value = { + @Select( + "") + @Results( + value = { @Result(property = "jobId", column = "JOB_ID"), @Result(property = "priority", column = "PRIORITY"), @Result(property = "created", column = "CREATED"), @@ -51,19 +50,22 @@ public interface JobMapper { @Result(property = "lockExpires", column = "LOCK_EXPIRES"), @Result(property = "type", column = "TYPE"), @Result(property = "retryCount", column = "RETRY_COUNT"), - @Result(property = "arguments", column = "ARGUMENTS", - javaType = Map.class, typeHandler = MapTypeHandler.class) - }) - List findJobsToRun(); + @Result( + property = "arguments", + column = "ARGUMENTS", + javaType = Map.class, + typeHandler = MapTypeHandler.class) + }) + List findJobsToRun(); - @Update( - value = "UPDATE SCHEDULED_JOB SET CREATED = #{created}, PRIORITY = #{priority}, DUE = #{due}, STATE = #{state}, " - + "LOCKED_BY = #{lockedBy}, LOCK_EXPIRES = #{lockExpires}, TYPE = #{type}, RETRY_COUNT = #{retryCount}, " - + "ARGUMENTS = #{arguments,jdbcType=CLOB ,javaType=java.util.Map,typeHandler=pro.taskana.impl.persistence.MapTypeHandler} " - + "where JOB_ID = #{jobId}") - void update(ScheduledJob job); + @Update( + value = + "UPDATE SCHEDULED_JOB SET CREATED = #{created}, PRIORITY = #{priority}, DUE = #{due}, STATE = #{state}, " + + "LOCKED_BY = #{lockedBy}, LOCK_EXPIRES = #{lockExpires}, TYPE = #{type}, RETRY_COUNT = #{retryCount}, " + + "ARGUMENTS = #{arguments,jdbcType=CLOB ,javaType=java.util.Map,typeHandler=pro.taskana.impl.persistence.MapTypeHandler} " + + "where JOB_ID = #{jobId}") + void update(ScheduledJob job); - @Delete( - value = "DELETE FROM SCHEDULED_JOB WHERE JOB_ID = #{jobId}") - void delete(ScheduledJob job); + @Delete(value = "DELETE FROM SCHEDULED_JOB WHERE JOB_ID = #{jobId}") + void delete(ScheduledJob job); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/mappings/ObjectReferenceMapper.java b/lib/taskana-core/src/main/java/pro/taskana/mappings/ObjectReferenceMapper.java index 8e0d225f4..be9233d94 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/mappings/ObjectReferenceMapper.java +++ b/lib/taskana-core/src/main/java/pro/taskana/mappings/ObjectReferenceMapper.java @@ -9,49 +9,54 @@ import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import pro.taskana.ObjectReference; -/** - * This class is the mybatis mapping of ObjectReference. - */ +/** This class is the mybatis mapping of ObjectReference. */ public interface ObjectReferenceMapper { - @Select("") - @Results({ - @Result(property = "id", column = "ID"), - @Result(property = "company", column = "COMPANY"), - @Result(property = "system", column = "SYSTEM"), - @Result(property = "systemInstance", column = "SYSTEM_INSTANCE"), - @Result(property = "type", column = "TYPE"), - @Result(property = "value", column = "VALUE") }) - ObjectReference findById(@Param("id") String id); + @Select( + "") + @Results({ + @Result(property = "id", column = "ID"), + @Result(property = "company", column = "COMPANY"), + @Result(property = "system", column = "SYSTEM"), + @Result(property = "systemInstance", column = "SYSTEM_INSTANCE"), + @Result(property = "type", column = "TYPE"), + @Result(property = "value", column = "VALUE") + }) + ObjectReference findById(@Param("id") String id); - @Select("") - @Results({ - @Result(property = "id", column = "ID"), - @Result(property = "company", column = "COMPANY"), - @Result(property = "system", column = "SYSTEM"), - @Result(property = "systemInstance", column = "SYSTEM_INSTANCE"), - @Result(property = "type", column = "TYPE"), - @Result(property = "value", column = "VALUE") }) - ObjectReference findByObjectReference(@Param("objectReference") ObjectReference objectReference); + @Select( + "") + @Results({ + @Result(property = "id", column = "ID"), + @Result(property = "company", column = "COMPANY"), + @Result(property = "system", column = "SYSTEM"), + @Result(property = "systemInstance", column = "SYSTEM_INSTANCE"), + @Result(property = "type", column = "TYPE"), + @Result(property = "value", column = "VALUE") + }) + ObjectReference findByObjectReference(@Param("objectReference") ObjectReference objectReference); - @Insert("INSERT INTO OBJECT_REFERENCE (ID, COMPANY, SYSTEM, SYSTEM_INSTANCE, TYPE, VALUE) VALUES (#{ref.id}, #{ref.company}, #{ref.system}, #{ref.systemInstance}, #{ref.type}, #{ref.value})") - void insert(@Param("ref") ObjectReference ref); + @Insert( + "INSERT INTO OBJECT_REFERENCE (ID, COMPANY, SYSTEM, SYSTEM_INSTANCE, TYPE, VALUE) VALUES (#{ref.id}, #{ref.company}, #{ref.system}, #{ref.systemInstance}, #{ref.type}, #{ref.value})") + void insert(@Param("ref") ObjectReference ref); - @Update(value = "UPDATE OBJECT_REFERENCE SET COMPANY = #{ref.company}, SYSTEM = #{ref.system}, SYSTEM_INSTANCE = #{ref.systemInstance}, TYPE = #{ref.type}, VALUE = #{ref.value} WHERE ID = #{ref.id}") - void update(@Param("ref") ObjectReference ref); + @Update( + value = + "UPDATE OBJECT_REFERENCE SET COMPANY = #{ref.company}, SYSTEM = #{ref.system}, SYSTEM_INSTANCE = #{ref.systemInstance}, TYPE = #{ref.type}, VALUE = #{ref.value} WHERE ID = #{ref.id}") + void update(@Param("ref") ObjectReference ref); - @Delete("DELETE FROM OBJECT_REFERENCE WHERE ID = #{id}") - void delete(String id); + @Delete("DELETE FROM OBJECT_REFERENCE WHERE ID = #{id}") + void delete(String id); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/mappings/QueryMapper.java b/lib/taskana-core/src/main/java/pro/taskana/mappings/QueryMapper.java index e577deda6..0cb4fd61c 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/mappings/QueryMapper.java +++ b/lib/taskana-core/src/main/java/pro/taskana/mappings/QueryMapper.java @@ -1,7 +1,6 @@ package pro.taskana.mappings; import java.util.List; - import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; @@ -17,140 +16,142 @@ import pro.taskana.impl.WorkbasketAccessItemImpl; import pro.taskana.impl.WorkbasketQueryImpl; import pro.taskana.impl.WorkbasketSummaryImpl; -/** - * This class provides a mapper for all queries. - */ +/** This class provides a mapper for all queries. */ public interface QueryMapper { - String OBJECTREFERENCEMAPPER_FINDBYID = "pro.taskana.mappings.ObjectReferenceMapper.findById"; - String CLASSIFICATION_FINDBYKEYANDDOMAIN = "pro.taskana.mappings.ClassificationMapper.findByKeyAndDomain"; - String CLASSIFICATION_FINDBYID = "pro.taskana.mappings.ClassificationMapper.findById"; - String WORKBASKET_FINDSUMMARYBYKEY = "pro.taskana.mappings.WorkbasketMapper.findSummaryByKey"; + String OBJECTREFERENCEMAPPER_FINDBYID = "pro.taskana.mappings.ObjectReferenceMapper.findById"; + String CLASSIFICATION_FINDBYKEYANDDOMAIN = + "pro.taskana.mappings.ClassificationMapper.findByKeyAndDomain"; + String CLASSIFICATION_FINDBYID = "pro.taskana.mappings.ClassificationMapper.findById"; + String WORKBASKET_FINDSUMMARYBYKEY = "pro.taskana.mappings.WorkbasketMapper.findSummaryByKey"; - @Select("") - @Results(value = {@Result(property = "taskId", column = "ID"), + @Select( + "") + @Results( + value = { + @Result(property = "taskId", column = "ID"), @Result(property = "externalId", column = "EXTERNAL_ID"), @Result(property = "created", column = "CREATED"), @Result(property = "claimed", column = "CLAIMED"), @@ -169,7 +170,9 @@ public interface QueryMapper { @Result(property = "classificationSummaryImpl.key", column = "CLASSIFICATION_KEY"), @Result(property = "classificationSummaryImpl.id", column = "CLASSIFICATION_ID"), @Result(property = "classificationSummaryImpl.domain", column = "DOMAIN"), - @Result(property = "classificationSummaryImpl.category", column = "CLASSIFICATION_CATEGORY"), + @Result( + property = "classificationSummaryImpl.category", + column = "CLASSIFICATION_CATEGORY"), @Result(property = "businessProcessId", column = "BUSINESS_PROCESS_ID"), @Result(property = "parentBusinessProcessId", column = "PARENT_BUSINESS_PROCESS_ID"), @Result(property = "owner", column = "OWNER"), @@ -195,195 +198,199 @@ public interface QueryMapper { @Result(property = "custom13", column = "CUSTOM_13"), @Result(property = "custom14", column = "CUSTOM_14"), @Result(property = "custom15", column = "CUSTOM_15"), - @Result(property = "custom16", column = "CUSTOM_16")}) - List queryTaskSummaries(TaskQueryImpl taskQuery); + @Result(property = "custom16", column = "CUSTOM_16") + }) + List queryTaskSummaries(TaskQueryImpl taskQuery); - @Select("") - @Results(value = {@Result(property = "taskId", column = "ID"), + @Select( + "") + @Results( + value = { + @Result(property = "taskId", column = "ID"), @Result(property = "externalId", column = "EXTERNAL_ID"), @Result(property = "created", column = "CREATED"), @Result(property = "claimed", column = "CLAIMED"), @@ -402,7 +409,9 @@ public interface QueryMapper { @Result(property = "classificationSummaryImpl.key", column = "CLASSIFICATION_KEY"), @Result(property = "classificationSummaryImpl.id", column = "CLASSIFICATION_ID"), @Result(property = "classificationSummaryImpl.domain", column = "DOMAIN"), - @Result(property = "classificationSummaryImpl.category", column = "CLASSIFICATION_CATEGORY"), + @Result( + property = "classificationSummaryImpl.category", + column = "CLASSIFICATION_CATEGORY"), @Result(property = "businessProcessId", column = "BUSINESS_PROCESS_ID"), @Result(property = "parentBusinessProcessId", column = "PARENT_BUSINESS_PROCESS_ID"), @Result(property = "owner", column = "OWNER"), @@ -428,915 +437,936 @@ public interface QueryMapper { @Result(property = "custom13", column = "CUSTOM_13"), @Result(property = "custom14", column = "CUSTOM_14"), @Result(property = "custom15", column = "CUSTOM_15"), - @Result(property = "custom16", column = "CUSTOM_16")}) - List queryTaskSummariesDb2(TaskQueryImpl taskQuery); + @Result(property = "custom16", column = "CUSTOM_16") + }) + List queryTaskSummariesDb2(TaskQueryImpl taskQuery); - @Select( - "") - @Results({@Result(property = "id", column = "ID"), - @Result(property = "key", column = "KEY"), - @Result(property = "category", column = "CATEGORY"), - @Result(property = "type", column = "TYPE"), - @Result(property = "domain", column = "DOMAIN"), - @Result(property = "name", column = "NAME"), - @Result(property = "priority", column = "PRIORITY"), - @Result(property = "serviceLevel", column = "SERVICE_LEVEL"), - @Result(property = "parentId", column = "PARENT_ID"), - @Result(property = "parentKey", column = "PARENT_KEY"), - @Result(property = "custom1", column = "CUSTOM_1"), - @Result(property = "custom2", column = "CUSTOM_2"), - @Result(property = "custom3", column = "CUSTOM_3"), - @Result(property = "custom4", column = "CUSTOM_4"), - @Result(property = "custom5", column = "CUSTOM_5"), - @Result(property = "custom6", column = "CUSTOM_6"), - @Result(property = "custom7", column = "CUSTOM_7"), - @Result(property = "custom8", column = "CUSTOM_8")}) - List queryClassificationSummaries(ClassificationQueryImpl classificationQuery); + @Select( + "") + @Results({ + @Result(property = "id", column = "ID"), + @Result(property = "key", column = "KEY"), + @Result(property = "category", column = "CATEGORY"), + @Result(property = "type", column = "TYPE"), + @Result(property = "domain", column = "DOMAIN"), + @Result(property = "name", column = "NAME"), + @Result(property = "priority", column = "PRIORITY"), + @Result(property = "serviceLevel", column = "SERVICE_LEVEL"), + @Result(property = "parentId", column = "PARENT_ID"), + @Result(property = "parentKey", column = "PARENT_KEY"), + @Result(property = "custom1", column = "CUSTOM_1"), + @Result(property = "custom2", column = "CUSTOM_2"), + @Result(property = "custom3", column = "CUSTOM_3"), + @Result(property = "custom4", column = "CUSTOM_4"), + @Result(property = "custom5", column = "CUSTOM_5"), + @Result(property = "custom6", column = "CUSTOM_6"), + @Result(property = "custom7", column = "CUSTOM_7"), + @Result(property = "custom8", column = "CUSTOM_8") + }) + List queryClassificationSummaries( + ClassificationQueryImpl classificationQuery); - @Select("") - @Results({ - @Result(property = "id", column = "ID"), - @Result(property = "company", column = "COMPANY"), - @Result(property = "system", column = "SYSTEM"), - @Result(property = "systemInstance", column = "SYSTEM_INSTANCE"), - @Result(property = "type", column = "TYPE"), - @Result(property = "value", column = "VALUE")}) - List queryObjectReferences(ObjectReferenceQueryImpl objectReference); + @Select( + "") + @Results({ + @Result(property = "id", column = "ID"), + @Result(property = "company", column = "COMPANY"), + @Result(property = "system", column = "SYSTEM"), + @Result(property = "systemInstance", column = "SYSTEM_INSTANCE"), + @Result(property = "type", column = "TYPE"), + @Result(property = "value", column = "VALUE") + }) + List queryObjectReferences(ObjectReferenceQueryImpl objectReference); - @Select("") - @Results({ - @Result(property = "id", column = "ID"), - @Result(property = "key", column = "KEY"), - @Result(property = "name", column = "NAME"), - @Result(property = "description", column = "DESCRIPTION"), - @Result(property = "owner", column = "OWNER"), - @Result(property = "domain", column = "DOMAIN"), - @Result(property = "type", column = "TYPE"), - @Result(property = "custom1", column = "CUSTOM_1"), - @Result(property = "custom2", column = "CUSTOM_2"), - @Result(property = "custom3", column = "CUSTOM_3"), - @Result(property = "custom4", column = "CUSTOM_4"), - @Result(property = "orgLevel1", column = "ORG_LEVEL_1"), - @Result(property = "orgLevel2", column = "ORG_LEVEL_2"), - @Result(property = "orgLevel3", column = "ORG_LEVEL_3"), - @Result(property = "orgLevel4", column = "ORG_LEVEL_4"), - @Result(property = "markedForDeletion", column = "MARKED_FOR_DELETION")}) - List queryWorkbasketSummaries(WorkbasketQueryImpl workbasketQuery); + @Select( + "") + @Results({ + @Result(property = "id", column = "ID"), + @Result(property = "key", column = "KEY"), + @Result(property = "name", column = "NAME"), + @Result(property = "description", column = "DESCRIPTION"), + @Result(property = "owner", column = "OWNER"), + @Result(property = "domain", column = "DOMAIN"), + @Result(property = "type", column = "TYPE"), + @Result(property = "custom1", column = "CUSTOM_1"), + @Result(property = "custom2", column = "CUSTOM_2"), + @Result(property = "custom3", column = "CUSTOM_3"), + @Result(property = "custom4", column = "CUSTOM_4"), + @Result(property = "orgLevel1", column = "ORG_LEVEL_1"), + @Result(property = "orgLevel2", column = "ORG_LEVEL_2"), + @Result(property = "orgLevel3", column = "ORG_LEVEL_3"), + @Result(property = "orgLevel4", column = "ORG_LEVEL_4"), + @Result(property = "markedForDeletion", column = "MARKED_FOR_DELETION") + }) + List queryWorkbasketSummaries(WorkbasketQueryImpl workbasketQuery); - @Select("") - @Results({ - @Result(property = "id", column = "ID"), - @Result(property = "workbasketId", column = "WORKBASKET_ID"), - @Result(property = "workbasketKey", column = "KEY"), - @Result(property = "accessId", column = "ACCESS_ID"), - @Result(property = "accessName", column = "ACCESS_NAME"), - @Result(property = "permRead", column = "PERM_READ"), - @Result(property = "permOpen", column = "PERM_OPEN"), - @Result(property = "permAppend", column = "PERM_APPEND"), - @Result(property = "permTransfer", column = "PERM_TRANSFER"), - @Result(property = "permDistribute", column = "PERM_DISTRIBUTE"), - @Result(property = "permCustom1", column = "PERM_CUSTOM_1"), - @Result(property = "permCustom2", column = "PERM_CUSTOM_2"), - @Result(property = "permCustom3", column = "PERM_CUSTOM_3"), - @Result(property = "permCustom4", column = "PERM_CUSTOM_4"), - @Result(property = "permCustom5", column = "PERM_CUSTOM_5"), - @Result(property = "permCustom6", column = "PERM_CUSTOM_6"), - @Result(property = "permCustom7", column = "PERM_CUSTOM_7"), - @Result(property = "permCustom8", column = "PERM_CUSTOM_8"), - @Result(property = "permCustom9", column = "PERM_CUSTOM_9"), - @Result(property = "permCustom10", column = "PERM_CUSTOM_10"), - @Result(property = "permCustom11", column = "PERM_CUSTOM_11"), - @Result(property = "permCustom12", column = "PERM_CUSTOM_12")}) - List queryWorkbasketAccessItems(WorkbasketAccessItemQuery accessItemQuery); + @Select( + "") + @Results({ + @Result(property = "id", column = "ID"), + @Result(property = "workbasketId", column = "WORKBASKET_ID"), + @Result(property = "workbasketKey", column = "KEY"), + @Result(property = "accessId", column = "ACCESS_ID"), + @Result(property = "accessName", column = "ACCESS_NAME"), + @Result(property = "permRead", column = "PERM_READ"), + @Result(property = "permOpen", column = "PERM_OPEN"), + @Result(property = "permAppend", column = "PERM_APPEND"), + @Result(property = "permTransfer", column = "PERM_TRANSFER"), + @Result(property = "permDistribute", column = "PERM_DISTRIBUTE"), + @Result(property = "permCustom1", column = "PERM_CUSTOM_1"), + @Result(property = "permCustom2", column = "PERM_CUSTOM_2"), + @Result(property = "permCustom3", column = "PERM_CUSTOM_3"), + @Result(property = "permCustom4", column = "PERM_CUSTOM_4"), + @Result(property = "permCustom5", column = "PERM_CUSTOM_5"), + @Result(property = "permCustom6", column = "PERM_CUSTOM_6"), + @Result(property = "permCustom7", column = "PERM_CUSTOM_7"), + @Result(property = "permCustom8", column = "PERM_CUSTOM_8"), + @Result(property = "permCustom9", column = "PERM_CUSTOM_9"), + @Result(property = "permCustom10", column = "PERM_CUSTOM_10"), + @Result(property = "permCustom11", column = "PERM_CUSTOM_11"), + @Result(property = "permCustom12", column = "PERM_CUSTOM_12") + }) + List queryWorkbasketAccessItems( + WorkbasketAccessItemQuery accessItemQuery); - @Select("") - Long countQueryTasks(TaskQueryImpl taskQuery); + @Select( + "") + Long countQueryTasks(TaskQueryImpl taskQuery); - @Select("") - Long countQueryTasksDb2(TaskQueryImpl taskQuery); + @Select( + "") + Long countQueryTasksDb2(TaskQueryImpl taskQuery); - @Select("") - Long countQueryClassifications(ClassificationQueryImpl classificationQuery); + @Select( + "") + Long countQueryClassifications(ClassificationQueryImpl classificationQuery); - @Select("") - Long countQueryObjectReferences(ObjectReferenceQueryImpl objectReference); + @Select( + "") + Long countQueryObjectReferences(ObjectReferenceQueryImpl objectReference); - @Select("") - Long countQueryWorkbaskets(WorkbasketQueryImpl workbasketQuery); + @Select( + "") + Long countQueryWorkbaskets(WorkbasketQueryImpl workbasketQuery); - @Select("") - Long countQueryWorkbasketAccessItems(WorkbasketAccessItemQuery accessItem); + @Select( + "") + Long countQueryWorkbasketAccessItems(WorkbasketAccessItemQuery accessItem); - @Select("") - List queryTaskColumnValues(TaskQueryImpl taskQuery); + @Select( + "") + List queryTaskColumnValues(TaskQueryImpl taskQuery); - @Select("") - List queryClassificationColumnValues(ClassificationQueryImpl classificationQuery); + @Select( + "") + List queryClassificationColumnValues(ClassificationQueryImpl classificationQuery); - @Select("") - List queryObjectReferenceColumnValues(ObjectReferenceQueryImpl objectReference); + @Select( + "") + List queryObjectReferenceColumnValues(ObjectReferenceQueryImpl objectReference); - @Select("") - List queryWorkbasketColumnValues(WorkbasketQueryImpl workbasketQuery); - - @Select("") - List queryWorkbasketAccessItemColumnValues(WorkbasketAccessItemQuery accessItemQuery); + @Select( + "") + List queryWorkbasketColumnValues(WorkbasketQueryImpl workbasketQuery); + @Select( + "") + List queryWorkbasketAccessItemColumnValues(WorkbasketAccessItemQuery accessItemQuery); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/mappings/TaskMapper.java b/lib/taskana-core/src/main/java/pro/taskana/mappings/TaskMapper.java index a967815ea..ad5aec1c8 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/mappings/TaskMapper.java +++ b/lib/taskana-core/src/main/java/pro/taskana/mappings/TaskMapper.java @@ -2,7 +2,6 @@ package pro.taskana.mappings; import java.util.List; import java.util.Map; - import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Options; @@ -18,18 +17,18 @@ import pro.taskana.impl.TaskImpl; import pro.taskana.impl.TaskSummaryImpl; import pro.taskana.impl.persistence.MapTypeHandler; -/** - * This class is the mybatis mapping of task. - */ +/** This class is the mybatis mapping of task. */ public interface TaskMapper { - @Select("") - @Results(value = { + @Select( + "") + @Results( + value = { @Result(property = "id", column = "ID"), @Result(property = "externalId", column = "EXTERNAL_ID"), @Result(property = "created", column = "CREATED"), @@ -46,7 +45,9 @@ public interface TaskMapper { @Result(property = "state", column = "STATE"), @Result(property = "workbasketSummaryImpl.id", column = "WORKBASKET_ID"), @Result(property = "workbasketSummaryImpl.key", column = "WORKBASKET_KEY"), - @Result(property = "classificationSummaryImpl.category", column = "CLASSIFICATION_CATEGORY"), + @Result( + property = "classificationSummaryImpl.category", + column = "CLASSIFICATION_CATEGORY"), @Result(property = "classificationSummaryImpl.id", column = "CLASSIFICATION_ID"), @Result(property = "classificationSummaryImpl.key", column = "CLASSIFICATION_KEY"), @Result(property = "domain", column = "DOMAIN"), @@ -60,11 +61,17 @@ public interface TaskMapper { @Result(property = "primaryObjRef.value", column = "POR_VALUE"), @Result(property = "isRead", column = "IS_READ"), @Result(property = "isTransferred", column = "IS_TRANSFERRED"), - @Result(property = "callbackInfo", column = "CALLBACK_INFO", - javaType = Map.class, typeHandler = MapTypeHandler.class), + @Result( + property = "callbackInfo", + column = "CALLBACK_INFO", + javaType = Map.class, + typeHandler = MapTypeHandler.class), @Result(property = "callbackState", column = "CALLBACK_STATE"), - @Result(property = "customAttributes", column = "CUSTOM_ATTRIBUTES", - javaType = Map.class, typeHandler = MapTypeHandler.class), + @Result( + property = "customAttributes", + column = "CUSTOM_ATTRIBUTES", + javaType = Map.class, + typeHandler = MapTypeHandler.class), @Result(property = "custom1", column = "CUSTOM_1"), @Result(property = "custom2", column = "CUSTOM_2"), @Result(property = "custom3", column = "CUSTOM_3"), @@ -81,51 +88,58 @@ public interface TaskMapper { @Result(property = "custom14", column = "CUSTOM_14"), @Result(property = "custom15", column = "CUSTOM_15"), @Result(property = "custom16", column = "CUSTOM_16") - }) - TaskImpl findById(@Param("id") String id); + }) + TaskImpl findById(@Param("id") String id); - @Insert("INSERT INTO TASK(ID, EXTERNAL_ID, CREATED, CLAIMED, COMPLETED, MODIFIED, PLANNED, DUE, NAME, CREATOR, DESCRIPTION, NOTE, PRIORITY, STATE, CLASSIFICATION_CATEGORY, CLASSIFICATION_KEY, CLASSIFICATION_ID, WORKBASKET_ID, WORKBASKET_KEY, DOMAIN, BUSINESS_PROCESS_ID, PARENT_BUSINESS_PROCESS_ID, OWNER, POR_COMPANY, " - + "POR_SYSTEM, POR_INSTANCE, POR_TYPE, POR_VALUE, IS_READ, IS_TRANSFERRED, CALLBACK_INFO, CALLBACK_STATE, CUSTOM_ATTRIBUTES, CUSTOM_1, CUSTOM_2, CUSTOM_3, CUSTOM_4, CUSTOM_5, CUSTOM_6, CUSTOM_7, CUSTOM_8, " - + "CUSTOM_9, CUSTOM_10, CUSTOM_11, CUSTOM_12, CUSTOM_13, CUSTOM_14, CUSTOM_15, CUSTOM_16 ) " - + "VALUES(#{id},#{externalId}, #{created}, #{claimed}, #{completed}, #{modified}, #{planned}, #{due}, #{name}, #{creator}, #{description}, #{note}, #{priority}, #{state}, #{classificationSummary.category}, " - + "#{classificationSummary.key}, #{classificationSummary.id}, #{workbasketSummary.id}, #{workbasketSummary.key}, #{workbasketSummary.domain}, #{businessProcessId}, " - + "#{parentBusinessProcessId}, #{owner}, #{primaryObjRef.company}, #{primaryObjRef.system}, #{primaryObjRef.systemInstance}, #{primaryObjRef.type}, #{primaryObjRef.value}, " - + "#{isRead}, #{isTransferred}, #{callbackInfo,jdbcType=CLOB,javaType=java.util.Map,typeHandler=pro.taskana.impl.persistence.MapTypeHandler}, #{callbackState}, " - + "#{customAttributes,jdbcType=CLOB,javaType=java.util.Map,typeHandler=pro.taskana.impl.persistence.MapTypeHandler}, " - + "#{custom1}, #{custom2}, #{custom3}, #{custom4}, #{custom5}, #{custom6}, #{custom7}, #{custom8}, #{custom9}, #{custom10}, " - + "#{custom11}, #{custom12}, #{custom13}, #{custom14}, #{custom15}, #{custom16})") - @Options(keyProperty = "id", keyColumn = "ID") - void insert(TaskImpl task); + @Insert( + "INSERT INTO TASK(ID, EXTERNAL_ID, CREATED, CLAIMED, COMPLETED, MODIFIED, PLANNED, DUE, NAME, CREATOR, DESCRIPTION, NOTE, PRIORITY, STATE, CLASSIFICATION_CATEGORY, CLASSIFICATION_KEY, CLASSIFICATION_ID, WORKBASKET_ID, WORKBASKET_KEY, DOMAIN, BUSINESS_PROCESS_ID, PARENT_BUSINESS_PROCESS_ID, OWNER, POR_COMPANY, " + + "POR_SYSTEM, POR_INSTANCE, POR_TYPE, POR_VALUE, IS_READ, IS_TRANSFERRED, CALLBACK_INFO, CALLBACK_STATE, CUSTOM_ATTRIBUTES, CUSTOM_1, CUSTOM_2, CUSTOM_3, CUSTOM_4, CUSTOM_5, CUSTOM_6, CUSTOM_7, CUSTOM_8, " + + "CUSTOM_9, CUSTOM_10, CUSTOM_11, CUSTOM_12, CUSTOM_13, CUSTOM_14, CUSTOM_15, CUSTOM_16 ) " + + "VALUES(#{id},#{externalId}, #{created}, #{claimed}, #{completed}, #{modified}, #{planned}, #{due}, #{name}, #{creator}, #{description}, #{note}, #{priority}, #{state}, #{classificationSummary.category}, " + + "#{classificationSummary.key}, #{classificationSummary.id}, #{workbasketSummary.id}, #{workbasketSummary.key}, #{workbasketSummary.domain}, #{businessProcessId}, " + + "#{parentBusinessProcessId}, #{owner}, #{primaryObjRef.company}, #{primaryObjRef.system}, #{primaryObjRef.systemInstance}, #{primaryObjRef.type}, #{primaryObjRef.value}, " + + "#{isRead}, #{isTransferred}, #{callbackInfo,jdbcType=CLOB,javaType=java.util.Map,typeHandler=pro.taskana.impl.persistence.MapTypeHandler}, #{callbackState}, " + + "#{customAttributes,jdbcType=CLOB,javaType=java.util.Map,typeHandler=pro.taskana.impl.persistence.MapTypeHandler}, " + + "#{custom1}, #{custom2}, #{custom3}, #{custom4}, #{custom5}, #{custom6}, #{custom7}, #{custom8}, #{custom9}, #{custom10}, " + + "#{custom11}, #{custom12}, #{custom13}, #{custom14}, #{custom15}, #{custom16})") + @Options(keyProperty = "id", keyColumn = "ID") + void insert(TaskImpl task); - @Update("UPDATE TASK SET CLAIMED = #{claimed}, COMPLETED = #{completed}, MODIFIED = #{modified}, PLANNED = #{planned}, DUE = #{due}, NAME = #{name}, DESCRIPTION = #{description}, NOTE = #{note}, " - + " PRIORITY = #{priority}, STATE = #{state}, CLASSIFICATION_CATEGORY = #{classificationSummary.category}, CLASSIFICATION_KEY = #{classificationSummary.key}, CLASSIFICATION_ID = #{classificationSummary.id}, " - + "WORKBASKET_ID = #{workbasketSummary.id}, WORKBASKET_KEY = #{workbasketSummary.key}, DOMAIN = #{workbasketSummary.domain}, " - + "BUSINESS_PROCESS_ID = #{businessProcessId}, PARENT_BUSINESS_PROCESS_ID = #{parentBusinessProcessId}, OWNER = #{owner}, POR_COMPANY = #{primaryObjRef.company}, POR_SYSTEM = #{primaryObjRef.system}, " - + "POR_INSTANCE = #{primaryObjRef.systemInstance}, POR_TYPE = #{primaryObjRef.type}, POR_VALUE = #{primaryObjRef.value}, IS_READ = #{isRead}, IS_TRANSFERRED = #{isTransferred}, " - + "CALLBACK_INFO = #{callbackInfo,jdbcType=CLOB,javaType=java.util.Map,typeHandler=pro.taskana.impl.persistence.MapTypeHandler}, " - + "CUSTOM_ATTRIBUTES = #{customAttributes,jdbcType=CLOB,javaType=java.util.Map,typeHandler=pro.taskana.impl.persistence.MapTypeHandler}, CUSTOM_1 = #{custom1}, CUSTOM_2 = #{custom2}, " - + "CUSTOM_3 = #{custom3}, CUSTOM_4 = #{custom4}, CUSTOM_5 = #{custom5}, CUSTOM_6 = #{custom6}, CUSTOM_7 = #{custom7}, CUSTOM_8 = #{custom8}, " - + "CUSTOM_9 = #{custom9}, CUSTOM_10 = #{custom10}, CUSTOM_11 = #{custom11}, CUSTOM_12 = #{custom12}, CUSTOM_13 = #{custom13}, CUSTOM_14 = #{custom14}, CUSTOM_15 = #{custom15}, CUSTOM_16 = #{custom16} " - + "WHERE ID = #{id}") - void update(TaskImpl task); + @Update( + "UPDATE TASK SET CLAIMED = #{claimed}, COMPLETED = #{completed}, MODIFIED = #{modified}, PLANNED = #{planned}, DUE = #{due}, NAME = #{name}, DESCRIPTION = #{description}, NOTE = #{note}, " + + " PRIORITY = #{priority}, STATE = #{state}, CLASSIFICATION_CATEGORY = #{classificationSummary.category}, CLASSIFICATION_KEY = #{classificationSummary.key}, CLASSIFICATION_ID = #{classificationSummary.id}, " + + "WORKBASKET_ID = #{workbasketSummary.id}, WORKBASKET_KEY = #{workbasketSummary.key}, DOMAIN = #{workbasketSummary.domain}, " + + "BUSINESS_PROCESS_ID = #{businessProcessId}, PARENT_BUSINESS_PROCESS_ID = #{parentBusinessProcessId}, OWNER = #{owner}, POR_COMPANY = #{primaryObjRef.company}, POR_SYSTEM = #{primaryObjRef.system}, " + + "POR_INSTANCE = #{primaryObjRef.systemInstance}, POR_TYPE = #{primaryObjRef.type}, POR_VALUE = #{primaryObjRef.value}, IS_READ = #{isRead}, IS_TRANSFERRED = #{isTransferred}, " + + "CALLBACK_INFO = #{callbackInfo,jdbcType=CLOB,javaType=java.util.Map,typeHandler=pro.taskana.impl.persistence.MapTypeHandler}, " + + "CUSTOM_ATTRIBUTES = #{customAttributes,jdbcType=CLOB,javaType=java.util.Map,typeHandler=pro.taskana.impl.persistence.MapTypeHandler}, CUSTOM_1 = #{custom1}, CUSTOM_2 = #{custom2}, " + + "CUSTOM_3 = #{custom3}, CUSTOM_4 = #{custom4}, CUSTOM_5 = #{custom5}, CUSTOM_6 = #{custom6}, CUSTOM_7 = #{custom7}, CUSTOM_8 = #{custom8}, " + + "CUSTOM_9 = #{custom9}, CUSTOM_10 = #{custom10}, CUSTOM_11 = #{custom11}, CUSTOM_12 = #{custom12}, CUSTOM_13 = #{custom13}, CUSTOM_14 = #{custom14}, CUSTOM_15 = #{custom15}, CUSTOM_16 = #{custom16} " + + "WHERE ID = #{id}") + void update(TaskImpl task); - @Delete("DELETE FROM TASK WHERE ID = #{id}") - void delete(String id); + @Delete("DELETE FROM TASK WHERE ID = #{id}") + void delete(String id); - @Delete("") - void deleteMultiple(@Param("ids") List ids); + @Delete( + "") + void deleteMultiple(@Param("ids") List ids); - @Update("") - void setCallbackStateMultiple(@Param("externalIds") List externalIds, @Param("state") CallbackState state); + @Update( + "") + void setCallbackStateMultiple( + @Param("externalIds") List externalIds, @Param("state") CallbackState state); - @Select("") - @Results(value = { + @Select( + "") + @Results( + value = { @Result(property = "taskId", column = "ID"), @Result(property = "externalId", column = "EXTERNAL_ID"), @Result(property = "created", column = "CREATED"), @@ -139,7 +153,9 @@ public interface TaskMapper { @Result(property = "note", column = "NOTE"), @Result(property = "priority", column = "PRIORITY"), @Result(property = "state", column = "STATE"), - @Result(property = "classificationSummaryImpl.category", column = "CLASSIFICATION_CATEGORY"), + @Result( + property = "classificationSummaryImpl.category", + column = "CLASSIFICATION_CATEGORY"), @Result(property = "classificationSummaryImpl.key", column = "CLASSIFICATION_KEY"), @Result(property = "classificationSummaryImpl.id", column = "CLASSIFICATION_ID"), @Result(property = "workbasketSummaryImpl.id", column = "WORKBASKET_ID"), @@ -171,77 +187,89 @@ public interface TaskMapper { @Result(property = "custom13", column = "CUSTOM_13"), @Result(property = "custom14", column = "CUSTOM_14"), @Result(property = "custom15", column = "CUSTOM_15"), - @Result(property = "custom16", column = "CUSTOM_16")}) - List findTasksAffectedByClassificationChange(@Param("classificationId") String classificationId); + @Result(property = "custom16", column = "CUSTOM_16") + }) + List findTasksAffectedByClassificationChange( + @Param("classificationId") String classificationId); - @Update("") - void updateTransfered(@Param("taskIds") List taskIds, - @Param("referencetask") TaskSummaryImpl referencetask); + @Update( + "") + void updateTransfered( + @Param("taskIds") List taskIds, + @Param("referencetask") TaskSummaryImpl referencetask); - @Update("") - void updateCompleted(@Param("taskIds") List taskIds, - @Param("referencetask") TaskSummaryImpl referencetask); + @Update( + "") + void updateCompleted( + @Param("taskIds") List taskIds, + @Param("referencetask") TaskSummaryImpl referencetask); - @Select("") - @Results(value = { + @Select( + "") + @Results( + value = { @Result(property = "taskId", column = "ID"), @Result(property = "externalId", column = "EXTERNAL_ID"), @Result(property = "workbasketId", column = "WORKBASKET_ID"), @Result(property = "taskState", column = "STATE"), - @Result(property = "callbackState", column = "CALLBACK_STATE")}) - List findExistingTasks(@Param("taskIds") List taskIds, - @Param("externalIds") List externalIds); + @Result(property = "callbackState", column = "CALLBACK_STATE") + }) + List findExistingTasks( + @Param("taskIds") List taskIds, @Param("externalIds") List externalIds); - @Update("") - void updateClassificationCategoryOnChange(@Param("taskIds") List taskIds, - @Param("newCategory") String newCategory); + @Update( + "") + void updateClassificationCategoryOnChange( + @Param("taskIds") List taskIds, @Param("newCategory") String newCategory); - @Update("") - void updateTasks(@Param("taskIds") List taskIds, @Param("task") TaskImpl task, - @Param("fields") CustomPropertySelector fields); - - @Select("") - @Results(value = { - @Result(property = "taskId", column = "ID")}) - List filterTaskIdsForNotCompleted(@Param("taskIds") List taskIds); + @Update( + "") + void updateTasks( + @Param("taskIds") List taskIds, + @Param("task") TaskImpl task, + @Param("fields") CustomPropertySelector fields); + @Select( + "") + @Results(value = {@Result(property = "taskId", column = "ID")}) + List filterTaskIdsForNotCompleted(@Param("taskIds") List taskIds); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/mappings/TaskMonitorMapper.java b/lib/taskana-core/src/main/java/pro/taskana/mappings/TaskMonitorMapper.java index 4006643c8..a997b4398 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/mappings/TaskMonitorMapper.java +++ b/lib/taskana-core/src/main/java/pro/taskana/mappings/TaskMonitorMapper.java @@ -2,7 +2,6 @@ package pro.taskana.mappings; import java.util.List; import java.util.Map; - import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; @@ -18,468 +17,494 @@ import pro.taskana.impl.report.item.TaskQueryItem; import pro.taskana.impl.report.item.TimestampQueryItem; import pro.taskana.report.Timestamp; -/** - * This class is the mybatis mapping of task monitoring. - */ +/** This class is the mybatis mapping of task monitoring. */ public interface TaskMonitorMapper { - @Select("") - @Results({ - @Result(column = "WORKBASKET_KEY", property = "key"), - @Result(column = "AGE_IN_DAYS", property = "ageInDays"), - @Result(column = "NUMBER_OF_TASKS", property = "numberOfTasks")}) - List getTaskCountOfWorkbaskets(@Param("workbasketIds") List workbasketIds, - @Param("states") List states, - @Param("categories") List categories, - @Param("domains") List domains, - @Param("classificationIds") List classificationIds, - @Param("excludedClassificationIds") List excludedClassificationIds, - @Param("customAttributeFilter") Map customAttributeFilter, - @Param("combinedClassificationFilter") List combinedClassificationFilter); + @Select( + "") + @Results({ + @Result(column = "WORKBASKET_KEY", property = "key"), + @Result(column = "AGE_IN_DAYS", property = "ageInDays"), + @Result(column = "NUMBER_OF_TASKS", property = "numberOfTasks") + }) + List getTaskCountOfWorkbaskets( + @Param("workbasketIds") List workbasketIds, + @Param("states") List states, + @Param("categories") List categories, + @Param("domains") List domains, + @Param("classificationIds") List classificationIds, + @Param("excludedClassificationIds") List excludedClassificationIds, + @Param("customAttributeFilter") Map customAttributeFilter, + @Param("combinedClassificationFilter") + List combinedClassificationFilter); - @Select("") - @Results({ - @Result(column = "WORKBASKET_KEY", property = "key"), - @Result(column = "AGE_IN_DAYS", property = "ageInDays"), - @Result(column = "NUMBER_OF_TASKS", property = "numberOfTasks")}) - List getTaskCountOfWorkbasketsBasedOnPlannedDate( - @Param("workbasketIds") List workbasketIds, - @Param("states") List states, - @Param("categories") List categories, - @Param("domains") List domains, - @Param("classificationIds") List classificationIds, - @Param("excludedClassificationIds") List excludedClassificationIds, - @Param("customAttributeFilter") Map customAttributeFilter, - @Param("combinedClassificationFilter") List combinedClassificationFilter); + @Select( + "") + @Results({ + @Result(column = "WORKBASKET_KEY", property = "key"), + @Result(column = "AGE_IN_DAYS", property = "ageInDays"), + @Result(column = "NUMBER_OF_TASKS", property = "numberOfTasks") + }) + List getTaskCountOfWorkbasketsBasedOnPlannedDate( + @Param("workbasketIds") List workbasketIds, + @Param("states") List states, + @Param("categories") List categories, + @Param("domains") List domains, + @Param("classificationIds") List classificationIds, + @Param("excludedClassificationIds") List excludedClassificationIds, + @Param("customAttributeFilter") Map customAttributeFilter, + @Param("combinedClassificationFilter") + List combinedClassificationFilter); - @Select("") - @Results({ - @Result(column = "CLASSIFICATION_CATEGORY", property = "key"), - @Result(column = "AGE_IN_DAYS", property = "ageInDays"), - @Result(column = "NUMBER_OF_TASKS", property = "numberOfTasks")}) - List getTaskCountOfCategories(@Param("workbasketIds") List workbasketIds, - @Param("states") List states, - @Param("categories") List categories, - @Param("domains") List domains, - @Param("classificationIds") List classificationIds, - @Param("excludedClassificationIds") List excludedClassificationIds, - @Param("customAttributeFilter") Map customAttributeFilter); + @Select( + "") + @Results({ + @Result(column = "CLASSIFICATION_CATEGORY", property = "key"), + @Result(column = "AGE_IN_DAYS", property = "ageInDays"), + @Result(column = "NUMBER_OF_TASKS", property = "numberOfTasks") + }) + List getTaskCountOfCategories( + @Param("workbasketIds") List workbasketIds, + @Param("states") List states, + @Param("categories") List categories, + @Param("domains") List domains, + @Param("classificationIds") List classificationIds, + @Param("excludedClassificationIds") List excludedClassificationIds, + @Param("customAttributeFilter") Map customAttributeFilter); - @Select("") - @Results({ - @Result(column = "CLASSIFICATION_KEY", property = "key"), - @Result(column = "AGE_IN_DAYS", property = "ageInDays"), - @Result(column = "NUMBER_OF_TASKS", property = "numberOfTasks")}) - List getTaskCountOfClassifications(@Param("workbasketIds") List workbasketIds, - @Param("states") List states, - @Param("categories") List categories, - @Param("domains") List domains, - @Param("classificationIds") List classificationIds, - @Param("excludedClassificationIds") List excludedClassificationIds, - @Param("customAttributeFilter") Map customAttributeFilter); + @Select( + "") + @Results({ + @Result(column = "CLASSIFICATION_KEY", property = "key"), + @Result(column = "AGE_IN_DAYS", property = "ageInDays"), + @Result(column = "NUMBER_OF_TASKS", property = "numberOfTasks") + }) + List getTaskCountOfClassifications( + @Param("workbasketIds") List workbasketIds, + @Param("states") List states, + @Param("categories") List categories, + @Param("domains") List domains, + @Param("classificationIds") List classificationIds, + @Param("excludedClassificationIds") List excludedClassificationIds, + @Param("customAttributeFilter") Map customAttributeFilter); - @Select("") - @Results({ - @Result(column = "TASK_CLASSIFICATION_KEY", property = "key"), - @Result(column = "ATTACHMENT_CLASSIFICATION_KEY", property = "attachmentKey"), - @Result(column = "AGE_IN_DAYS", property = "ageInDays"), - @Result(column = "NUMBER_OF_TASKS", property = "numberOfTasks")}) - List getTaskCountOfDetailedClassifications( - @Param("workbasketIds") List workbasketIds, - @Param("states") List states, - @Param("categories") List categories, - @Param("domains") List domains, - @Param("classificationIds") List classificationIds, - @Param("excludedClassificationIds") List excludedClassificationIds, - @Param("customAttributeFilter") Map customAttributeFilter); + @Select( + "") + @Results({ + @Result(column = "TASK_CLASSIFICATION_KEY", property = "key"), + @Result(column = "ATTACHMENT_CLASSIFICATION_KEY", property = "attachmentKey"), + @Result(column = "AGE_IN_DAYS", property = "ageInDays"), + @Result(column = "NUMBER_OF_TASKS", property = "numberOfTasks") + }) + List getTaskCountOfDetailedClassifications( + @Param("workbasketIds") List workbasketIds, + @Param("states") List states, + @Param("categories") List categories, + @Param("domains") List domains, + @Param("classificationIds") List classificationIds, + @Param("excludedClassificationIds") List excludedClassificationIds, + @Param("customAttributeFilter") Map customAttributeFilter); - @Select("") - @Results({ - @Result(column = "CUSTOM_FIELD", property = "key"), - @Result(column = "AGE_IN_DAYS", property = "ageInDays"), - @Result(column = "NUMBER_OF_TASKS", property = "numberOfTasks")}) - List getTaskCountOfCustomFieldValues( - @Param("customField") CustomField customField, - @Param("workbasketIds") List workbasketIds, - @Param("states") List states, - @Param("categories") List categories, - @Param("domains") List domains, - @Param("classificationIds") List classificationIds, - @Param("excludedClassificationIds") List excludedClassificationIds, - @Param("customAttributeFilter") Map customAttributeFilter); + @Select( + "") + @Results({ + @Result(column = "CUSTOM_FIELD", property = "key"), + @Result(column = "AGE_IN_DAYS", property = "ageInDays"), + @Result(column = "NUMBER_OF_TASKS", property = "numberOfTasks") + }) + List getTaskCountOfCustomFieldValues( + @Param("customField") CustomField customField, + @Param("workbasketIds") List workbasketIds, + @Param("states") List states, + @Param("categories") List categories, + @Param("domains") List domains, + @Param("classificationIds") List classificationIds, + @Param("excludedClassificationIds") List excludedClassificationIds, + @Param("customAttributeFilter") Map customAttributeFilter); - @Select("") - List getTaskIdsForSelectedItems(@Param("workbasketIds") List workbasketIds, - @Param("states") List states, - @Param("categories") List categories, - @Param("domains") List domains, - @Param("classificationIds") List classificationIds, - @Param("excludedClassificationIds") List excludedClassificationIds, - @Param("customAttributeFilter") Map customAttributeFilter, - @Param("groupedBy") String groupedBy, @Param("selectedItems") List selectedItems, - @Param("joinWithAttachments") boolean joinWithAttachments); + @Select( + "") + List getTaskIdsForSelectedItems( + @Param("workbasketIds") List workbasketIds, + @Param("states") List states, + @Param("categories") List categories, + @Param("domains") List domains, + @Param("classificationIds") List classificationIds, + @Param("excludedClassificationIds") List excludedClassificationIds, + @Param("customAttributeFilter") Map customAttributeFilter, + @Param("groupedBy") String groupedBy, + @Param("selectedItems") List selectedItems, + @Param("joinWithAttachments") boolean joinWithAttachments); - @Select("") - @Results({ - @Result(column = "DOMAIN", property = "domain"), - @Result(column = "STATE", property = "state"), - @Result(column = "COUNT", property = "count"), - }) - List getTasksCountByState(@Param("domains") List domains, - @Param("states") List states); + @Select( + "") + @Results({ + @Result(column = "DOMAIN", property = "domain"), + @Result(column = "STATE", property = "state"), + @Result(column = "COUNT", property = "count"), + }) + List getTasksCountByState( + @Param("domains") List domains, @Param("states") List states); - @Select("") - List getCustomAttributeValuesForReport(@Param("workbasketIds") List workbasketIds, - @Param("states") List states, - @Param("categories") List categories, @Param("domains") List domains, - @Param("classificationIds") List classificationIds, - @Param("excludedClassificationIds") List excludedClassificationIds, - @Param("customAttributeFilter") Map customAttributeFilter, - @Param("customField") CustomField customField); - - @Select("") - @Results({ - @Result(column = "STATUS", property = "status"), - @Result(column = "AGE_IN_DAYS", property = "ageInDays"), - @Result(column = "COUNT", property = "count"), - @Result(column = "ORG_LEVEL_1", property = "orgLevel1"), - @Result(column = "ORG_LEVEL_2", property = "orgLevel2"), - @Result(column = "ORG_LEVEL_3", property = "orgLevel3"), - @Result(column = "ORG_LEVEL_4", property = "orgLevel4") - }) - List getTasksCountForStatusGroupedByOrgLevel(@Param("status") Timestamp status, - @Param("categories") List categories, @Param("classificationIds") List classificationIds, - @Param("excludedClassificationIds") List excludedClassificationIds, - @Param("domains") List domains, - @Param("customAttributeFilter") Map customAttributeFilter); + @Select( + "") + List getCustomAttributeValuesForReport( + @Param("workbasketIds") List workbasketIds, + @Param("states") List states, + @Param("categories") List categories, + @Param("domains") List domains, + @Param("classificationIds") List classificationIds, + @Param("excludedClassificationIds") List excludedClassificationIds, + @Param("customAttributeFilter") Map customAttributeFilter, + @Param("customField") CustomField customField); + @Select( + "") + @Results({ + @Result(column = "STATUS", property = "status"), + @Result(column = "AGE_IN_DAYS", property = "ageInDays"), + @Result(column = "COUNT", property = "count"), + @Result(column = "ORG_LEVEL_1", property = "orgLevel1"), + @Result(column = "ORG_LEVEL_2", property = "orgLevel2"), + @Result(column = "ORG_LEVEL_3", property = "orgLevel3"), + @Result(column = "ORG_LEVEL_4", property = "orgLevel4") + }) + List getTasksCountForStatusGroupedByOrgLevel( + @Param("status") Timestamp status, + @Param("categories") List categories, + @Param("classificationIds") List classificationIds, + @Param("excludedClassificationIds") List excludedClassificationIds, + @Param("domains") List domains, + @Param("customAttributeFilter") Map customAttributeFilter); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/mappings/WorkbasketAccessMapper.java b/lib/taskana-core/src/main/java/pro/taskana/mappings/WorkbasketAccessMapper.java index 1e740b75d..8ed636c79 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/mappings/WorkbasketAccessMapper.java +++ b/lib/taskana-core/src/main/java/pro/taskana/mappings/WorkbasketAccessMapper.java @@ -1,7 +1,6 @@ package pro.taskana.mappings; import java.util.List; - import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Options; @@ -13,16 +12,16 @@ import org.apache.ibatis.annotations.Update; import pro.taskana.impl.WorkbasketAccessItemImpl; -/** - * This class is the mybatis mapping of workbasket access items. - */ +/** This class is the mybatis mapping of workbasket access items. */ public interface WorkbasketAccessMapper { - @Select("") - @Results(value = { + @Select( + "") + @Results( + value = { @Result(property = "id", column = "ID"), @Result(property = "workbasketId", column = "WORKBASKET_ID"), @Result(property = "accessId", column = "ACCESS_ID"), @@ -43,14 +42,17 @@ public interface WorkbasketAccessMapper { @Result(property = "permCustom9", column = "PERM_CUSTOM_9"), @Result(property = "permCustom10", column = "PERM_CUSTOM_10"), @Result(property = "permCustom11", column = "PERM_CUSTOM_11"), - @Result(property = "permCustom12", column = "PERM_CUSTOM_12")}) - WorkbasketAccessItemImpl findById(@Param("id") String id); + @Result(property = "permCustom12", column = "PERM_CUSTOM_12") + }) + WorkbasketAccessItemImpl findById(@Param("id") String id); - @Select("") - @Results(value = { + @Select( + "") + @Results( + value = { @Result(property = "id", column = "ID"), @Result(property = "workbasketId", column = "WORKBASKET_ID"), @Result(property = "workbasketKey", column = "KEY"), @@ -72,42 +74,47 @@ public interface WorkbasketAccessMapper { @Result(property = "permCustom9", column = "PERM_CUSTOM_9"), @Result(property = "permCustom10", column = "PERM_CUSTOM_10"), @Result(property = "permCustom11", column = "PERM_CUSTOM_11"), - @Result(property = "permCustom12", column = "PERM_CUSTOM_12")}) - List findByWorkbasketId(@Param("id") String id); + @Result(property = "permCustom12", column = "PERM_CUSTOM_12") + }) + List findByWorkbasketId(@Param("id") String id); - @Insert("INSERT INTO WORKBASKET_ACCESS_LIST (ID, WORKBASKET_ID, ACCESS_ID, ACCESS_NAME, PERM_READ, PERM_OPEN, PERM_APPEND, PERM_TRANSFER, PERM_DISTRIBUTE, PERM_CUSTOM_1, PERM_CUSTOM_2, PERM_CUSTOM_3, PERM_CUSTOM_4, PERM_CUSTOM_5, PERM_CUSTOM_6, PERM_CUSTOM_7, PERM_CUSTOM_8, PERM_CUSTOM_9, PERM_CUSTOM_10, PERM_CUSTOM_11, PERM_CUSTOM_12) " - + "VALUES (#{workbasketAccessItem.id}, #{workbasketAccessItem.workbasketId}, #{workbasketAccessItem.accessId}, #{workbasketAccessItem.accessName}, #{workbasketAccessItem.permRead}, #{workbasketAccessItem.permOpen}, #{workbasketAccessItem.permAppend}, #{workbasketAccessItem.permTransfer}, #{workbasketAccessItem.permDistribute}, #{workbasketAccessItem.permCustom1}, #{workbasketAccessItem.permCustom2}, #{workbasketAccessItem.permCustom3}, #{workbasketAccessItem.permCustom4}, #{workbasketAccessItem.permCustom5}, #{workbasketAccessItem.permCustom6}, #{workbasketAccessItem.permCustom7}, #{workbasketAccessItem.permCustom8}, #{workbasketAccessItem.permCustom9}, #{workbasketAccessItem.permCustom10}, #{workbasketAccessItem.permCustom11}, #{workbasketAccessItem.permCustom12})") - @Options(keyProperty = "id", keyColumn = "ID") - void insert(@Param("workbasketAccessItem") WorkbasketAccessItemImpl workbasketAccessItem); + @Insert( + "INSERT INTO WORKBASKET_ACCESS_LIST (ID, WORKBASKET_ID, ACCESS_ID, ACCESS_NAME, PERM_READ, PERM_OPEN, PERM_APPEND, PERM_TRANSFER, PERM_DISTRIBUTE, PERM_CUSTOM_1, PERM_CUSTOM_2, PERM_CUSTOM_3, PERM_CUSTOM_4, PERM_CUSTOM_5, PERM_CUSTOM_6, PERM_CUSTOM_7, PERM_CUSTOM_8, PERM_CUSTOM_9, PERM_CUSTOM_10, PERM_CUSTOM_11, PERM_CUSTOM_12) " + + "VALUES (#{workbasketAccessItem.id}, #{workbasketAccessItem.workbasketId}, #{workbasketAccessItem.accessId}, #{workbasketAccessItem.accessName}, #{workbasketAccessItem.permRead}, #{workbasketAccessItem.permOpen}, #{workbasketAccessItem.permAppend}, #{workbasketAccessItem.permTransfer}, #{workbasketAccessItem.permDistribute}, #{workbasketAccessItem.permCustom1}, #{workbasketAccessItem.permCustom2}, #{workbasketAccessItem.permCustom3}, #{workbasketAccessItem.permCustom4}, #{workbasketAccessItem.permCustom5}, #{workbasketAccessItem.permCustom6}, #{workbasketAccessItem.permCustom7}, #{workbasketAccessItem.permCustom8}, #{workbasketAccessItem.permCustom9}, #{workbasketAccessItem.permCustom10}, #{workbasketAccessItem.permCustom11}, #{workbasketAccessItem.permCustom12})") + @Options(keyProperty = "id", keyColumn = "ID") + void insert(@Param("workbasketAccessItem") WorkbasketAccessItemImpl workbasketAccessItem); - @Update("UPDATE WORKBASKET_ACCESS_LIST SET WORKBASKET_ID = #{workbasketAccessItem.workbasketId}, ACCESS_ID = #{workbasketAccessItem.accessId}, ACCESS_NAME = #{workbasketAccessItem.accessName}, PERM_READ = #{workbasketAccessItem.permRead}, PERM_OPEN = #{workbasketAccessItem.permOpen}, PERM_APPEND = #{workbasketAccessItem.permAppend}, PERM_TRANSFER = #{workbasketAccessItem.permTransfer}, PERM_DISTRIBUTE = #{workbasketAccessItem.permDistribute}, PERM_CUSTOM_1 = #{workbasketAccessItem.permCustom1}, PERM_CUSTOM_2 = #{workbasketAccessItem.permCustom2}, PERM_CUSTOM_3 = #{workbasketAccessItem.permCustom3}, PERM_CUSTOM_4 = #{workbasketAccessItem.permCustom4}, PERM_CUSTOM_5 = #{workbasketAccessItem.permCustom5}, PERM_CUSTOM_6 = #{workbasketAccessItem.permCustom6}, PERM_CUSTOM_7 = #{workbasketAccessItem.permCustom7}, PERM_CUSTOM_8 = #{workbasketAccessItem.permCustom8}, PERM_CUSTOM_9 = #{workbasketAccessItem.permCustom9}, PERM_CUSTOM_10 = #{workbasketAccessItem.permCustom10}, PERM_CUSTOM_11 = #{workbasketAccessItem.permCustom11}, PERM_CUSTOM_12 = #{workbasketAccessItem.permCustom12} " - + "WHERE id = #{workbasketAccessItem.id}") - void update(@Param("workbasketAccessItem") WorkbasketAccessItemImpl workbasketAccessItem); + @Update( + "UPDATE WORKBASKET_ACCESS_LIST SET WORKBASKET_ID = #{workbasketAccessItem.workbasketId}, ACCESS_ID = #{workbasketAccessItem.accessId}, ACCESS_NAME = #{workbasketAccessItem.accessName}, PERM_READ = #{workbasketAccessItem.permRead}, PERM_OPEN = #{workbasketAccessItem.permOpen}, PERM_APPEND = #{workbasketAccessItem.permAppend}, PERM_TRANSFER = #{workbasketAccessItem.permTransfer}, PERM_DISTRIBUTE = #{workbasketAccessItem.permDistribute}, PERM_CUSTOM_1 = #{workbasketAccessItem.permCustom1}, PERM_CUSTOM_2 = #{workbasketAccessItem.permCustom2}, PERM_CUSTOM_3 = #{workbasketAccessItem.permCustom3}, PERM_CUSTOM_4 = #{workbasketAccessItem.permCustom4}, PERM_CUSTOM_5 = #{workbasketAccessItem.permCustom5}, PERM_CUSTOM_6 = #{workbasketAccessItem.permCustom6}, PERM_CUSTOM_7 = #{workbasketAccessItem.permCustom7}, PERM_CUSTOM_8 = #{workbasketAccessItem.permCustom8}, PERM_CUSTOM_9 = #{workbasketAccessItem.permCustom9}, PERM_CUSTOM_10 = #{workbasketAccessItem.permCustom10}, PERM_CUSTOM_11 = #{workbasketAccessItem.permCustom11}, PERM_CUSTOM_12 = #{workbasketAccessItem.permCustom12} " + + "WHERE id = #{workbasketAccessItem.id}") + void update(@Param("workbasketAccessItem") WorkbasketAccessItemImpl workbasketAccessItem); - @Delete("DELETE FROM WORKBASKET_ACCESS_LIST WHERE ID = #{id}") - void delete(@Param("id") String id); + @Delete("DELETE FROM WORKBASKET_ACCESS_LIST WHERE ID = #{id}") + void delete(@Param("id") String id); - @Delete("DELETE FROM WORKBASKET_ACCESS_LIST WHERE WORKBASKET_ID = #{workbasketId}") - void deleteAllAccessItemsForWorkbasketId(@Param("workbasketId") String workbasketId); + @Delete("DELETE FROM WORKBASKET_ACCESS_LIST WHERE WORKBASKET_ID = #{workbasketId}") + void deleteAllAccessItemsForWorkbasketId(@Param("workbasketId") String workbasketId); - @Delete("DELETE FROM WORKBASKET_ACCESS_LIST where ACCESS_ID = #{accessId}") - void deleteAccessItemsForAccessId(@Param("accessId") String accessId); + @Delete("DELETE FROM WORKBASKET_ACCESS_LIST where ACCESS_ID = #{accessId}") + void deleteAccessItemsForAccessId(@Param("accessId") String accessId); - @Select("") - @Results(value = { + @Select( + "") + @Results( + value = { @Result(property = "id", column = "ID"), @Result(property = "workbasketId", column = "WORKBASKET_ID"), @Result(property = "accessId", column = "ACCESS_ID"), @@ -128,25 +135,28 @@ public interface WorkbasketAccessMapper { @Result(property = "permCustom9", column = "P_CUSTOM_9"), @Result(property = "permCustom10", column = "P_CUSTOM_10"), @Result(property = "permCustom11", column = "P_CUSTOM_11"), - @Result(property = "permCustom12", column = "P_CUSTOM_12")}) - WorkbasketAccessItemImpl findByWorkbasketAndAccessId( - @Param("workbasketId") String workbasketId, @Param("accessIds") List accessIds); + @Result(property = "permCustom12", column = "P_CUSTOM_12") + }) + WorkbasketAccessItemImpl findByWorkbasketAndAccessId( + @Param("workbasketId") String workbasketId, @Param("accessIds") List accessIds); - @Select("") - @Results(value = { + @Select( + "") + @Results( + value = { @Result(property = "workbasketId", column = "WORKBASKET_ID"), @Result(property = "accessId", column = "ACCESS_ID"), @Result(property = "accessName", column = "ACCESS_NAME"), @@ -166,9 +176,10 @@ public interface WorkbasketAccessMapper { @Result(property = "permCustom9", column = "P_CUSTOM_9"), @Result(property = "permCustom10", column = "P_CUSTOM_10"), @Result(property = "permCustom11", column = "P_CUSTOM_11"), - @Result(property = "permCustom12", column = "P_CUSTOM_12")}) - WorkbasketAccessItemImpl findByWorkbasketKeyDomainAndAccessId( - @Param("workbasketKey") String workbasketKey, @Param("domain") String domain, - @Param("accessIds") List accessIds); - + @Result(property = "permCustom12", column = "P_CUSTOM_12") + }) + WorkbasketAccessItemImpl findByWorkbasketKeyDomainAndAccessId( + @Param("workbasketKey") String workbasketKey, + @Param("domain") String domain, + @Param("accessIds") List accessIds); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/mappings/WorkbasketMapper.java b/lib/taskana-core/src/main/java/pro/taskana/mappings/WorkbasketMapper.java index e708f42c4..fea7c004b 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/mappings/WorkbasketMapper.java +++ b/lib/taskana-core/src/main/java/pro/taskana/mappings/WorkbasketMapper.java @@ -1,7 +1,6 @@ package pro.taskana.mappings; import java.util.List; - import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Options; @@ -14,15 +13,16 @@ import org.apache.ibatis.annotations.Update; import pro.taskana.impl.WorkbasketImpl; import pro.taskana.impl.WorkbasketSummaryImpl; -/** - * This class is the mybatis mapping of workbaskets. - */ +/** This class is the mybatis mapping of workbaskets. */ public interface WorkbasketMapper { - @Select("") - @Results(value = {@Result(property = "id", column = "ID"), + @Select( + "") + @Results( + value = { + @Result(property = "id", column = "ID"), @Result(property = "key", column = "KEY"), @Result(property = "created", column = "CREATED"), @Result(property = "modified", column = "MODIFIED"), @@ -39,13 +39,17 @@ public interface WorkbasketMapper { @Result(property = "orgLevel2", column = "ORG_LEVEL_2"), @Result(property = "orgLevel3", column = "ORG_LEVEL_3"), @Result(property = "orgLevel4", column = "ORG_LEVEL_4"), - @Result(property = "markedForDeletion", column = "MARKED_FOR_DELETION")}) - WorkbasketImpl findById(@Param("id") String id); + @Result(property = "markedForDeletion", column = "MARKED_FOR_DELETION") + }) + WorkbasketImpl findById(@Param("id") String id); - @Select("") - @Results(value = {@Result(property = "id", column = "ID"), + @Select( + "") + @Results( + value = { + @Result(property = "id", column = "ID"), @Result(property = "key", column = "KEY"), @Result(property = "created", column = "CREATED"), @Result(property = "modified", column = "MODIFIED"), @@ -62,14 +66,16 @@ public interface WorkbasketMapper { @Result(property = "orgLevel2", column = "ORG_LEVEL_2"), @Result(property = "orgLevel3", column = "ORG_LEVEL_3"), @Result(property = "orgLevel4", column = "ORG_LEVEL_4"), - @Result(property = "markedForDeletion", column = "MARKED_FOR_DELETION")}) - WorkbasketImpl findByKeyAndDomain(@Param("key") String key, @Param("domain") String domain); + @Result(property = "markedForDeletion", column = "MARKED_FOR_DELETION") + }) + WorkbasketImpl findByKeyAndDomain(@Param("key") String key, @Param("domain") String domain); - @Select( - "") - @Results(value = { + @Select( + "") + @Results( + value = { @Result(property = "id", column = "ID"), @Result(property = "key", column = "KEY"), @Result(property = "name", column = "NAME"), @@ -84,15 +90,17 @@ public interface WorkbasketMapper { @Result(property = "orgLevel1", column = "ORG_LEVEL_1"), @Result(property = "orgLevel2", column = "ORG_LEVEL_2"), @Result(property = "orgLevel3", column = "ORG_LEVEL_3"), - @Result(property = "orgLevel4", column = "ORG_LEVEL_4")}) - List findDistributionTargets(@Param("id") String id); + @Result(property = "orgLevel4", column = "ORG_LEVEL_4") + }) + List findDistributionTargets(@Param("id") String id); - @Select( - "") - @Results(value = { + @Select( + "") + @Results( + value = { @Result(property = "id", column = "ID"), @Result(property = "key", column = "KEY"), @Result(property = "name", column = "NAME"), @@ -107,13 +115,16 @@ public interface WorkbasketMapper { @Result(property = "orgLevel1", column = "ORG_LEVEL_1"), @Result(property = "orgLevel2", column = "ORG_LEVEL_2"), @Result(property = "orgLevel3", column = "ORG_LEVEL_3"), - @Result(property = "orgLevel4", column = "ORG_LEVEL_4")}) - List findDistributionSources(@Param("id") String id); + @Result(property = "orgLevel4", column = "ORG_LEVEL_4") + }) + List findDistributionSources(@Param("id") String id); - @Select("") - @Results(value = { + @Select( + "") + @Results( + value = { @Result(property = "id", column = "ID"), @Result(property = "key", column = "KEY"), @Result(property = "name", column = "NAME"), @@ -128,13 +139,16 @@ public interface WorkbasketMapper { @Result(property = "orgLevel1", column = "ORG_LEVEL_1"), @Result(property = "orgLevel2", column = "ORG_LEVEL_2"), @Result(property = "orgLevel3", column = "ORG_LEVEL_3"), - @Result(property = "orgLevel4", column = "ORG_LEVEL_4")}) - List findSummaryById(@Param("key") String id); + @Result(property = "orgLevel4", column = "ORG_LEVEL_4") + }) + List findSummaryById(@Param("key") String id); - @Select("") - @Results(value = { + @Select( + "") + @Results( + value = { @Result(property = "id", column = "ID"), @Result(property = "key", column = "KEY"), @Result(property = "name", column = "NAME"), @@ -149,20 +163,24 @@ public interface WorkbasketMapper { @Result(property = "orgLevel1", column = "ORG_LEVEL_1"), @Result(property = "orgLevel2", column = "ORG_LEVEL_2"), @Result(property = "orgLevel3", column = "ORG_LEVEL_3"), - @Result(property = "orgLevel4", column = "ORG_LEVEL_4")}) - List findAll(); + @Result(property = "orgLevel4", column = "ORG_LEVEL_4") + }) + List findAll(); - @Insert("") - @Options(keyProperty = "id", keyColumn = "ID") - void insert(@Param("workbasket") WorkbasketImpl workbasket); + @Insert( + "") + @Options(keyProperty = "id", keyColumn = "ID") + void insert(@Param("workbasket") WorkbasketImpl workbasket); - @Update("UPDATE WORKBASKET SET MODIFIED = #{workbasket.modified}, KEY = #{workbasket.key}, NAME = #{workbasket.name}, DOMAIN = #{workbasket.domain}, TYPE = #{workbasket.type}, DESCRIPTION = #{workbasket.description}, OWNER = #{workbasket.owner}, CUSTOM_1 = #{workbasket.custom1}, CUSTOM_2 = #{workbasket.custom2}, CUSTOM_3 = #{workbasket.custom3}, CUSTOM_4 = #{workbasket.custom4}, ORG_LEVEL_1 = #{workbasket.orgLevel1}, ORG_LEVEL_2 = #{workbasket.orgLevel2}, ORG_LEVEL_3 = #{workbasket.orgLevel3}, ORG_LEVEL_4 = #{workbasket.orgLevel4}, MARKED_FOR_DELETION = #{workbasket.markedForDeletion} WHERE id = #{workbasket.id}") - void update(@Param("workbasket") WorkbasketImpl workbasket); + @Update( + "UPDATE WORKBASKET SET MODIFIED = #{workbasket.modified}, KEY = #{workbasket.key}, NAME = #{workbasket.name}, DOMAIN = #{workbasket.domain}, TYPE = #{workbasket.type}, DESCRIPTION = #{workbasket.description}, OWNER = #{workbasket.owner}, CUSTOM_1 = #{workbasket.custom1}, CUSTOM_2 = #{workbasket.custom2}, CUSTOM_3 = #{workbasket.custom3}, CUSTOM_4 = #{workbasket.custom4}, ORG_LEVEL_1 = #{workbasket.orgLevel1}, ORG_LEVEL_2 = #{workbasket.orgLevel2}, ORG_LEVEL_3 = #{workbasket.orgLevel3}, ORG_LEVEL_4 = #{workbasket.orgLevel4}, MARKED_FOR_DELETION = #{workbasket.markedForDeletion} WHERE id = #{workbasket.id}") + void update(@Param("workbasket") WorkbasketImpl workbasket); - @Update("UPDATE WORKBASKET SET MODIFIED = #{workbasket.modified}, NAME = #{workbasket.name}, TYPE = #{workbasket.type}, DESCRIPTION = #{workbasket.description}, OWNER = #{workbasket.owner}, CUSTOM_1 = #{workbasket.custom1}, CUSTOM_2 = #{workbasket.custom2}, CUSTOM_3 = #{workbasket.custom3}, CUSTOM_4 = #{workbasket.custom4}, ORG_LEVEL_1 = #{workbasket.orgLevel1}, ORG_LEVEL_2 = #{workbasket.orgLevel2}, ORG_LEVEL_3 = #{workbasket.orgLevel3}, ORG_LEVEL_4 = #{workbasket.orgLevel4}, MARKED_FOR_DELETION = #{workbasket.markedForDeletion} WHERE KEY = #{workbasket.key} AND DOMAIN = #{workbasket.domain}") - void updateByKeyAndDomain(@Param("workbasket") WorkbasketImpl workbasket); + @Update( + "UPDATE WORKBASKET SET MODIFIED = #{workbasket.modified}, NAME = #{workbasket.name}, TYPE = #{workbasket.type}, DESCRIPTION = #{workbasket.description}, OWNER = #{workbasket.owner}, CUSTOM_1 = #{workbasket.custom1}, CUSTOM_2 = #{workbasket.custom2}, CUSTOM_3 = #{workbasket.custom3}, CUSTOM_4 = #{workbasket.custom4}, ORG_LEVEL_1 = #{workbasket.orgLevel1}, ORG_LEVEL_2 = #{workbasket.orgLevel2}, ORG_LEVEL_3 = #{workbasket.orgLevel3}, ORG_LEVEL_4 = #{workbasket.orgLevel4}, MARKED_FOR_DELETION = #{workbasket.markedForDeletion} WHERE KEY = #{workbasket.key} AND DOMAIN = #{workbasket.domain}") + void updateByKeyAndDomain(@Param("workbasket") WorkbasketImpl workbasket); - @Delete("DELETE FROM WORKBASKET where id = #{id}") - void delete(@Param("id") String id); + @Delete("DELETE FROM WORKBASKET where id = #{id}") + void delete(@Param("id") String id); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/report/CategoryReport.java b/lib/taskana-core/src/main/java/pro/taskana/report/CategoryReport.java index 68a008211..83a56424b 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/report/CategoryReport.java +++ b/lib/taskana-core/src/main/java/pro/taskana/report/CategoryReport.java @@ -9,25 +9,24 @@ import pro.taskana.impl.report.item.MonitorQueryItem; import pro.taskana.impl.report.structure.Report; /** - * A CategoryReport contains the total numbers of tasks of the respective category as well as the total number of - * all tasks. The tasks of the report can be filtered by workbaskets, states, categories, domains, classifications - * and values of a custom field. Classifications can also be excluded from the report. - * If the {@link TimeIntervalColumnHeader}s are set, the report contains also the number of tasks of the - * respective cluster. The age of the tasks can be counted in days or in working days. Tasks with Timestamp DUE = null - * are not considered. + * A CategoryReport contains the total numbers of tasks of the respective category as well as the + * total number of all tasks. The tasks of the report can be filtered by workbaskets, states, + * categories, domains, classifications and values of a custom field. Classifications can also be + * excluded from the report. If the {@link TimeIntervalColumnHeader}s are set, the report contains + * also the number of tasks of the respective cluster. The age of the tasks can be counted in days + * or in working days. Tasks with Timestamp DUE = null are not considered. */ public class CategoryReport extends Report { - public CategoryReport(List timeIntervalColumnHeaders) { - super(timeIntervalColumnHeaders, new String[] {"CLASSIFICATION CATEGORIES"}); - } + public CategoryReport(List timeIntervalColumnHeaders) { + super(timeIntervalColumnHeaders, new String[] {"CLASSIFICATION CATEGORIES"}); + } - /** - * Builder for {@link CategoryReport}. - */ - public interface Builder extends TimeIntervalReportBuilder { + /** Builder for {@link CategoryReport}. */ + public interface Builder + extends TimeIntervalReportBuilder { - @Override - CategoryReport buildReport() throws NotAuthorizedException, InvalidArgumentException; - } + @Override + CategoryReport buildReport() throws NotAuthorizedException, InvalidArgumentException; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/report/ClassificationReport.java b/lib/taskana-core/src/main/java/pro/taskana/report/ClassificationReport.java index d5d0426ee..3e734ea18 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/report/ClassificationReport.java +++ b/lib/taskana-core/src/main/java/pro/taskana/report/ClassificationReport.java @@ -11,59 +11,61 @@ import pro.taskana.impl.report.row.DetailedClassificationRow; import pro.taskana.impl.report.structure.Report; /** - * The ClassificationReport extends the Report. The {@link pro.taskana.impl.report.structure.Row}s of the ClassificationReport are grouped by - * classifications. + * The ClassificationReport extends the Report. The {@link pro.taskana.impl.report.structure.Row}s + * of the ClassificationReport are grouped by classifications. */ public class ClassificationReport extends Report { - public ClassificationReport(List timeIntervalColumnHeaders) { - super(timeIntervalColumnHeaders, new String[] {"CLASSIFICATION KEYS"}); - } + public ClassificationReport(List timeIntervalColumnHeaders) { + super(timeIntervalColumnHeaders, new String[] {"CLASSIFICATION KEYS"}); + } + + /** Builder for {@link ClassificationReport}. */ + public interface Builder + extends TimeIntervalReportBuilder { + + @Override + ClassificationReport buildReport() throws NotAuthorizedException, InvalidArgumentException; /** - * Builder for {@link ClassificationReport}. + * Returns a {@link DetailedClassificationReport} containing all tasks after applying the + * filters. If the column headers are set the report is subdivided into clusters. Its {@link + * pro.taskana.impl.report.row.FoldableRow}s contain an additional list of {@link + * pro.taskana.impl.report.structure.Row}s for the classifications of the attachments of the + * tasks. + * + * @throws InvalidArgumentException if the column headers are not initialized + * @throws NotAuthorizedException if the user has no rights to access the monitor + * @return the DetailedClassificationReport */ - public interface Builder extends TimeIntervalReportBuilder { + DetailedClassificationReport buildDetailedReport() + throws InvalidArgumentException, NotAuthorizedException; + } - @Override - ClassificationReport buildReport() throws NotAuthorizedException, InvalidArgumentException; + /** + * The DetailedClassificationReport is a functional extension of the {@link ClassificationReport}. + * Its {@link pro.taskana.impl.report.row.FoldableRow}s contain an additional list of {@link + * pro.taskana.impl.report.structure.Row}s for the classifications of the attachments of the + * tasks. + */ + public static class DetailedClassificationReport + extends Report { - /** - * Returns a {@link DetailedClassificationReport} containing all tasks after applying the filters. If the column - * headers are set the report is subdivided into clusters. Its - * {@link pro.taskana.impl.report.row.FoldableRow}s contain an additional list of - * {@link pro.taskana.impl.report.structure.Row}s for the classifications of the attachments of the tasks. - * - * @throws InvalidArgumentException - * if the column headers are not initialized - * @throws NotAuthorizedException - * if the user has no rights to access the monitor - * @return the DetailedClassificationReport - */ - DetailedClassificationReport buildDetailedReport() throws InvalidArgumentException, NotAuthorizedException; + public DetailedClassificationReport( + List workbasketLevelReportColumnHeaders) { + super( + workbasketLevelReportColumnHeaders, + new String[] {"TASK CLASSIFICATION KEYS", "ATTACHMENT"}); } - /** - * The DetailedClassificationReport is a functional extension of the {@link ClassificationReport}. - * Its {@link pro.taskana.impl.report.row.FoldableRow}s contain an additional list of {@link pro.taskana.impl.report.structure.Row}s - * for the classifications of the attachments of the tasks. - */ - public static class DetailedClassificationReport - extends Report { - - public DetailedClassificationReport(List workbasketLevelReportColumnHeaders) { - super(workbasketLevelReportColumnHeaders, new String[] {"TASK CLASSIFICATION KEYS", "ATTACHMENT"}); - } - - @Override - protected DetailedClassificationRow createRow(int columnSize) { - return new DetailedClassificationRow(columnSize); - } - - @Override - public DetailedClassificationRow getRow(String key) { - return (DetailedClassificationRow) super.getRow(key); - } - + @Override + public DetailedClassificationRow getRow(String key) { + return (DetailedClassificationRow) super.getRow(key); } + + @Override + protected DetailedClassificationRow createRow(int columnSize) { + return new DetailedClassificationRow(columnSize); + } + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/report/CustomFieldValueReport.java b/lib/taskana-core/src/main/java/pro/taskana/report/CustomFieldValueReport.java index e590480a9..6a898cffc 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/report/CustomFieldValueReport.java +++ b/lib/taskana-core/src/main/java/pro/taskana/report/CustomFieldValueReport.java @@ -1,4 +1,3 @@ - package pro.taskana.report; import java.util.List; @@ -10,25 +9,24 @@ import pro.taskana.impl.report.item.MonitorQueryItem; import pro.taskana.impl.report.structure.Report; /** - * A CustomFieldValueReport contains the total numbers of tasks of the respective custom field as well as - * the total number of all tasks. The tasks of the report can be filtered by workbaskets, states, categories, domains, - * classifications and values of a custom field. Classifications can also be excluded from the report. If the - * {@link TimeIntervalColumnHeader}s are set, the report contains also the number of tasks of the respective cluster. - * The age of the tasks can be counted in days or in working days. Tasks with Timestamp DUE = null are not considered. + * A CustomFieldValueReport contains the total numbers of tasks of the respective custom field as + * well as the total number of all tasks. The tasks of the report can be filtered by workbaskets, + * states, categories, domains, classifications and values of a custom field. Classifications can + * also be excluded from the report. If the {@link TimeIntervalColumnHeader}s are set, the report + * contains also the number of tasks of the respective cluster. The age of the tasks can be counted + * in days or in working days. Tasks with Timestamp DUE = null are not considered. */ public class CustomFieldValueReport extends Report { - public CustomFieldValueReport(List timeIntervalColumnHeaders) { - super(timeIntervalColumnHeaders, new String[] {"CUSTOM FIELDS"}); - } + public CustomFieldValueReport(List timeIntervalColumnHeaders) { + super(timeIntervalColumnHeaders, new String[] {"CUSTOM FIELDS"}); + } - /** - * Builder for {@link CustomFieldValueReport}. - */ - public interface Builder extends TimeIntervalReportBuilder { + /** Builder for {@link CustomFieldValueReport}. */ + public interface Builder + extends TimeIntervalReportBuilder { - @Override - CustomFieldValueReport buildReport() throws NotAuthorizedException, InvalidArgumentException; - } + @Override + CustomFieldValueReport buildReport() throws NotAuthorizedException, InvalidArgumentException; + } } - diff --git a/lib/taskana-core/src/main/java/pro/taskana/report/TaskStatusReport.java b/lib/taskana-core/src/main/java/pro/taskana/report/TaskStatusReport.java index 6295b9ab6..82916d732 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/report/TaskStatusReport.java +++ b/lib/taskana-core/src/main/java/pro/taskana/report/TaskStatusReport.java @@ -12,42 +12,42 @@ import pro.taskana.impl.report.item.TaskQueryItem; import pro.taskana.impl.report.structure.Report; /** - * A TaskStatusReport contains the total number of tasks, clustered in their task status. - * Furthermore the report contains a sum line that contains the total numbers - * of the different clusters and the total number of all tasks. + * A TaskStatusReport contains the total number of tasks, clustered in their task status. + * Furthermore the report contains a sum line that contains the total numbers of the different + * clusters and the total number of all tasks. */ public class TaskStatusReport extends Report { - public TaskStatusReport(List filter) { - super((filter != null ? filter.stream() : Stream.of(TaskState.values())) + public TaskStatusReport(List filter) { + super( + (filter != null ? filter.stream() : Stream.of(TaskState.values())) .map(TaskStatusColumnHeader::new) - .collect(Collectors.toList()), new String[] {"DOMAINS"}); - } + .collect(Collectors.toList()), + new String[] {"DOMAINS"}); + } + + /** Builder for {@link TaskStatusReport}. */ + public interface Builder extends Report.Builder { + + @Override + TaskStatusReport buildReport() throws NotAuthorizedException, InvalidArgumentException; /** - * Builder for {@link TaskStatusReport}. + * Adds a list of states to the builder. The created report contains only tasks with a state in + * this list. + * + * @param states a list of states + * @return the Builder */ - public interface Builder extends Report.Builder { + Builder stateIn(List states); - @Override - TaskStatusReport buildReport() throws NotAuthorizedException, InvalidArgumentException; - - /** - * Adds a list of states to the builder. The created report contains only tasks with a state in this list. - * - * @param states - * a list of states - * @return the Builder - */ - Builder stateIn(List states); - - /** - * Adds a list of domains to the builder. The created report contains only tasks with a domain in this list. - * - * @param domains - * a list of domains - * @return the Builder - */ - Builder domainIn(List domains); - } + /** + * Adds a list of domains to the builder. The created report contains only tasks with a domain + * in this list. + * + * @param domains a list of domains + * @return the Builder + */ + Builder domainIn(List domains); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/report/TimeIntervalReportBuilder.java b/lib/taskana-core/src/main/java/pro/taskana/report/TimeIntervalReportBuilder.java index 7c3deec7c..ce7c675fa 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/report/TimeIntervalReportBuilder.java +++ b/lib/taskana-core/src/main/java/pro/taskana/report/TimeIntervalReportBuilder.java @@ -14,120 +14,114 @@ import pro.taskana.impl.report.structure.Report; /** * "Super" Interface for all TimeIntervalReportBuilders. + * * @param the true Builder behind this Interface. * @param the AgeQueryItem which will be inserted into the Report. * @param the column Header */ -public interface TimeIntervalReportBuilder, I extends AgeQueryItem, H extends TimeIntervalColumnHeader> +public interface TimeIntervalReportBuilder< + B extends TimeIntervalReportBuilder, + I extends AgeQueryItem, + H extends TimeIntervalColumnHeader> extends Report.Builder { - /** - * Adds a list {@link TimeIntervalColumnHeader}s to the builder to subdivide the report into clusters. - * - * @param columnHeaders - * the column headers the report should consist of. - * @return the TimeIntervalReportBuilder - */ - B withColumnHeaders(List columnHeaders); + /** + * Adds a list {@link TimeIntervalColumnHeader}s to the builder to subdivide the report into + * clusters. + * + * @param columnHeaders the column headers the report should consist of. + * @return the TimeIntervalReportBuilder + */ + B withColumnHeaders(List columnHeaders); - /** - * If this filter is used, the days of the report are counted in working days. - * - * @return the TimeIntervalReportBuilder - */ - B inWorkingDays(); + /** + * If this filter is used, the days of the report are counted in working days. + * + * @return the TimeIntervalReportBuilder + */ + B inWorkingDays(); - /** - * Adds a list of workbasket ids to the builder. The created report contains only tasks with a workbasket id in this - * list. - * - * @param workbasketIds - * a list of workbasket ids - * @return the TimeIntervalReportBuilder - */ - B workbasketIdIn(List workbasketIds); + /** + * Adds a list of workbasket ids to the builder. The created report contains only tasks with a + * workbasket id in this list. + * + * @param workbasketIds a list of workbasket ids + * @return the TimeIntervalReportBuilder + */ + B workbasketIdIn(List workbasketIds); - /** - * Adds a list of states to the builder. The created report contains only tasks with a state in this list. - * - * @param states - * a list of states - * @return the TimeIntervalReportBuilder - */ - B stateIn(List states); + /** + * Adds a list of states to the builder. The created report contains only tasks with a state in + * this list. + * + * @param states a list of states + * @return the TimeIntervalReportBuilder + */ + B stateIn(List states); - /** - * Adds a list of categories to the builder. The created report contains only tasks with a category in this list. - * - * @param categories - * a list of categories - * @return the TimeIntervalReportBuilder - */ - B categoryIn(List categories); + /** + * Adds a list of categories to the builder. The created report contains only tasks with a + * category in this list. + * + * @param categories a list of categories + * @return the TimeIntervalReportBuilder + */ + B categoryIn(List categories); - /** - * Adds a list of classificationIds to the builder. The created report contains only tasks with a classificationId - * in this list. - * - * @param classificationIds - * a list of classificationIds - * @return the TimeIntervalReportBuilder - */ - B classificationIdIn(List classificationIds); + /** + * Adds a list of classificationIds to the builder. The created report contains only tasks with a + * classificationId in this list. + * + * @param classificationIds a list of classificationIds + * @return the TimeIntervalReportBuilder + */ + B classificationIdIn(List classificationIds); - /** - * Adds a list of excludedClassificationIds to the builder. The created report contains only tasks with a - * classificationId NOT in this list. - * - * @param excludedClassificationIds - * a list of excludedClassificationIds - * @return the TimeIntervalReportBuilder - */ - B excludedClassificationIdIn(List excludedClassificationIds); + /** + * Adds a list of excludedClassificationIds to the builder. The created report contains only tasks + * with a classificationId NOT in this list. + * + * @param excludedClassificationIds a list of excludedClassificationIds + * @return the TimeIntervalReportBuilder + */ + B excludedClassificationIdIn(List excludedClassificationIds); - /** - * Adds a list of domains to the builder. The created report contains only tasks with a domain in this list. - * - * @param domains - * a list of domains - * @return the TimeIntervalReportBuilder - */ - B domainIn(List domains); + /** + * Adds a list of domains to the builder. The created report contains only tasks with a domain in + * this list. + * + * @param domains a list of domains + * @return the TimeIntervalReportBuilder + */ + B domainIn(List domains); - /** - * Adds a map of custom attributes and custom attribute values to the builder. The created report contains only - * tasks with a custom attribute value in this list. - * - * @param customAttributeFilter - * a map of custom attributes and custom attribute value - * @return the TimeIntervalReportBuilder - */ - B customAttributeFilterIn(Map customAttributeFilter); + /** + * Adds a map of custom attributes and custom attribute values to the builder. The created report + * contains only tasks with a custom attribute value in this list. + * + * @param customAttributeFilter a map of custom attributes and custom attribute value + * @return the TimeIntervalReportBuilder + */ + B customAttributeFilterIn(Map customAttributeFilter); - /** - * Returns a list of all taskIds of the report that are in the list of selected items. - * - * @param selectedItems - * a list of selectedItems - * @throws InvalidArgumentException - * if the column headers are not initialized - * @throws NotAuthorizedException - * if the user has no rights to access the monitor - * @return the list of all taskIds - */ - List listTaskIdsForSelectedItems(List selectedItems) - throws NotAuthorizedException, InvalidArgumentException; - - /** - * Returns a list of all values of an entered custom field that are in the report. - * - * @param customField - * the customField whose values should appear in the list - * @throws NotAuthorizedException - * if the user has no rights to access the monitor - * @return the list of all custom attribute values - */ - List listCustomAttributeValuesForCustomAttributeName(CustomField customField) - throws NotAuthorizedException; + /** + * Returns a list of all taskIds of the report that are in the list of selected items. + * + * @param selectedItems a list of selectedItems + * @throws InvalidArgumentException if the column headers are not initialized + * @throws NotAuthorizedException if the user has no rights to access the monitor + * @return the list of all taskIds + */ + List listTaskIdsForSelectedItems(List selectedItems) + throws NotAuthorizedException, InvalidArgumentException; + /** + * Returns a list of all values of an entered custom field that are in the report. + * + * @param customField the customField whose values should appear in the list + * @throws NotAuthorizedException if the user has no rights to access the monitor + * @return the list of all custom attribute values + */ + List listCustomAttributeValuesForCustomAttributeName(CustomField customField) + throws NotAuthorizedException; } diff --git a/lib/taskana-core/src/main/java/pro/taskana/report/Timestamp.java b/lib/taskana-core/src/main/java/pro/taskana/report/Timestamp.java index 1bd49e458..6ae9fd214 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/report/Timestamp.java +++ b/lib/taskana-core/src/main/java/pro/taskana/report/Timestamp.java @@ -1,8 +1,11 @@ package pro.taskana.report; -/** - * This enum contains all timestamps saved in the database table for a {@link pro.taskana.Task}. - */ +/** This enum contains all timestamps saved in the database table for a {@link pro.taskana.Task}. */ public enum Timestamp { - CREATED, CLAIMED, COMPLETED, MODIFIED, PLANNED, DUE + CREATED, + CLAIMED, + COMPLETED, + MODIFIED, + PLANNED, + DUE } diff --git a/lib/taskana-core/src/main/java/pro/taskana/report/TimestampReport.java b/lib/taskana-core/src/main/java/pro/taskana/report/TimestampReport.java index 521fdb809..ee11310d7 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/report/TimestampReport.java +++ b/lib/taskana-core/src/main/java/pro/taskana/report/TimestampReport.java @@ -9,34 +9,32 @@ import pro.taskana.impl.report.item.TimestampQueryItem; import pro.taskana.impl.report.row.TimestampRow; import pro.taskana.impl.report.structure.Report; -/** - * A {@link TimestampReport} displays created and competed tasks for a specific dates. - */ +/** A {@link TimestampReport} displays created and competed tasks for a specific dates. */ public class TimestampReport extends Report { - public TimestampReport(List dates) { - super(dates, new String[] {"STATES", "ORG LEVEL 1", "ORG LEVEL 2", "ORG LEVEL 3", "ORG LEVEL 4"}); - } + public TimestampReport(List dates) { + super( + dates, new String[] {"STATES", "ORG LEVEL 1", "ORG LEVEL 2", "ORG LEVEL 3", "ORG LEVEL 4"}); + } + + @Override + public TimestampRow getRow(String key) { + return (TimestampRow) super.getRow(key); + } + + @Override + protected TimestampRow createRow(int columnSize) { + return new TimestampRow(columnSize); + } + + /** Builder for {@link TimestampReport}. */ + public interface Builder + extends TimeIntervalReportBuilder< + TimestampReport.Builder, TimestampQueryItem, TimeIntervalColumnHeader> { @Override - protected TimestampRow createRow(int columnSize) { - return new TimestampRow(columnSize); - } + TimestampReport buildReport() throws NotAuthorizedException, InvalidArgumentException; - @Override - public TimestampRow getRow(String key) { - return (TimestampRow) super.getRow(key); - } - - /** - * Builder for {@link TimestampReport}. - */ - public interface Builder extends - TimeIntervalReportBuilder { - - @Override - TimestampReport buildReport() throws NotAuthorizedException, InvalidArgumentException; - - Builder withTimestamps(List statuses); - } + Builder withTimestamps(List statuses); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/report/WorkbasketReport.java b/lib/taskana-core/src/main/java/pro/taskana/report/WorkbasketReport.java index b64fdd647..e1eb8eb89 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/report/WorkbasketReport.java +++ b/lib/taskana-core/src/main/java/pro/taskana/report/WorkbasketReport.java @@ -10,49 +10,46 @@ import pro.taskana.impl.report.item.MonitorQueryItem; import pro.taskana.impl.report.structure.Report; /** - * A WorkbasketReport contains the total numbers of tasks of the respective workbasket as well as the - * total number of all tasks. The tasks of the report can be filtered by workbaskets, states, - * categories, domains, classifications and values of a custom field. Classifications can also be excluded from the - * report. It is also possible to filter by the classifications of the attachments by using the - * {@link CombinedClassificationFilter}. If the {@link TimeIntervalColumnHeader}s are set, the report contains also the - * number of tasks of the respective cluster. The age of the tasks can be counted in days or in working days. Tasks with - * Timestamp DUE = null are not considered. + * A WorkbasketReport contains the total numbers of tasks of the respective workbasket as well as + * the total number of all tasks. The tasks of the report can be filtered by workbaskets, states, + * categories, domains, classifications and values of a custom field. Classifications can also be + * excluded from the report. It is also possible to filter by the classifications of the attachments + * by using the {@link CombinedClassificationFilter}. If the {@link TimeIntervalColumnHeader}s are + * set, the report contains also the number of tasks of the respective cluster. The age of the tasks + * can be counted in days or in working days. Tasks with Timestamp DUE = null are not considered. */ - public class WorkbasketReport extends Report { - public WorkbasketReport(List timeIntervalColumnHeaders) { - super(timeIntervalColumnHeaders, new String[] {"WORKBASKET KEYS"}); - } + public WorkbasketReport(List timeIntervalColumnHeaders) { + super(timeIntervalColumnHeaders, new String[] {"WORKBASKET KEYS"}); + } + + /** Builder for {@link WorkbasketReport}. */ + public interface Builder + extends TimeIntervalReportBuilder { + + @Override + WorkbasketReport buildReport() throws NotAuthorizedException, InvalidArgumentException; /** - * Builder for {@link WorkbasketReport}. + * buildPlannedDateBasedReport is querying grouping by plannedDate instead of due date. + * + * @return the built workbasketReport + * @throws NotAuthorizedException when the current user is not authorized to perform this action + * @throws InvalidArgumentException when the arguments given to the builder do not match */ - public interface Builder extends TimeIntervalReportBuilder { + WorkbasketReport buildPlannedDateBasedReport() + throws NotAuthorizedException, InvalidArgumentException; - @Override - WorkbasketReport buildReport() throws NotAuthorizedException, InvalidArgumentException; - - /** - * buildPlannedDateBasedReport is querying grouping by plannedDate instead of due date. - * - * @return the built workbasketReport - * - * @throws NotAuthorizedException when the current user is not authorized to perform this action - * - * @throws InvalidArgumentException when the arguments given to the builder do not match - */ - WorkbasketReport buildPlannedDateBasedReport() throws NotAuthorizedException, InvalidArgumentException; - - /** - * Adds a list of {@link CombinedClassificationFilter} to the builder. The created report contains only tasks with a - * pair of a classificationId for a task and a classificationId for the corresponding attachment in this list. - * - * @param combinedClassificationFilter - * a list of combinedClassificationFilter - * @return the WorkbasketReportBuilder - */ - WorkbasketReport.Builder combinedClassificationFilterIn( - List combinedClassificationFilter); - } + /** + * Adds a list of {@link CombinedClassificationFilter} to the builder. The created report + * contains only tasks with a pair of a classificationId for a task and a classificationId for + * the corresponding attachment in this list. + * + * @param combinedClassificationFilter a list of combinedClassificationFilter + * @return the WorkbasketReportBuilder + */ + WorkbasketReport.Builder combinedClassificationFilterIn( + List combinedClassificationFilter); + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/security/CurrentUserContext.java b/lib/taskana-core/src/main/java/pro/taskana/security/CurrentUserContext.java index acb82b23c..036584d2b 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/security/CurrentUserContext.java +++ b/lib/taskana-core/src/main/java/pro/taskana/security/CurrentUserContext.java @@ -7,148 +7,151 @@ import java.security.acl.Group; import java.util.ArrayList; import java.util.List; import java.util.Set; - import javax.security.auth.Subject; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pro.taskana.configuration.TaskanaEngineConfiguration; /** - * Provides the context information about the current (calling) user. The context is gathered from the JAAS subject. + * Provides the context information about the current (calling) user. The context is gathered from + * the JAAS subject. * * @author Holger Hagen */ public final class CurrentUserContext { - private static final String GET_UNIQUE_SECURITY_NAME_METHOD = "getUniqueSecurityName"; - private static final String GET_CALLER_SUBJECT_METHOD = "getCallerSubject"; - private static final String WSSUBJECT_CLASSNAME = "com.ibm.websphere.security.auth.WSSubject"; + private static final String GET_UNIQUE_SECURITY_NAME_METHOD = "getUniqueSecurityName"; + private static final String GET_CALLER_SUBJECT_METHOD = "getCallerSubject"; + private static final String WSSUBJECT_CLASSNAME = "com.ibm.websphere.security.auth.WSSubject"; - private static final Logger LOGGER = LoggerFactory.getLogger(CurrentUserContext.class); + private static final Logger LOGGER = LoggerFactory.getLogger(CurrentUserContext.class); - private static Boolean runningOnWebSphere = null; + private static Boolean runningOnWebSphere = null; - private CurrentUserContext() { + private CurrentUserContext() {} + + /** + * Returns the userid of the current user. + * + * @return String the userid. null if there is no JAAS subject. + */ + public static String getUserid() { + if (runningOnWebSphere()) { + return getUseridFromWSSubject(); + } else { + return getUseridFromJAASSubject(); } + } - /** - * Returns the userid of the current user. - * - * @return String the userid. null if there is no JAAS subject. - */ - public static String getUserid() { - if (runningOnWebSphere()) { - return getUseridFromWSSubject(); - } else { - return getUseridFromJAASSubject(); + public static List getGroupIds() { + Subject subject = Subject.getSubject(AccessController.getContext()); + LOGGER.trace("Subject of caller: {}", subject); + List groupIds = new ArrayList<>(); + if (subject != null) { + Set groups = subject.getPrincipals(Group.class); + LOGGER.trace("Public groups of caller: {}", groups); + for (Principal group : groups) { + String groupNameFound = group.getName(); + String groupNameReturned = groupNameFound; + if (TaskanaEngineConfiguration.shouldUseLowerCaseForAccessIds() && groupNameFound != null) { + groupNameReturned = groupNameFound.toLowerCase(); } + LOGGER.trace( + "Found group id {}. Returning group Id: {}", groupNameFound, groupNameReturned); + groupIds.add(groupNameReturned); + } + return groupIds; } + LOGGER.trace("No groupids found in subject!"); + return groupIds; + } - /** - * Returns the unique security name of the first public credentials found in the WSSubject as userid. - * - * @return the userid of the caller. If the userid could not be obtained, null is returned. - */ - private static String getUseridFromWSSubject() { - try { - Class wsSubjectClass = Class.forName(WSSUBJECT_CLASSNAME); - Method getCallerSubjectMethod = wsSubjectClass.getMethod(GET_CALLER_SUBJECT_METHOD, (Class[]) null); - Subject callerSubject = (Subject) getCallerSubjectMethod.invoke(null, (Object[]) null); - LOGGER.debug("Subject of caller: {}", callerSubject); - if (callerSubject != null) { - Set publicCredentials = callerSubject.getPublicCredentials(); - LOGGER.debug("Public credentials of caller: {}", publicCredentials); - for (Object pC : publicCredentials) { - Object o = pC.getClass().getMethod(GET_UNIQUE_SECURITY_NAME_METHOD, (Class[]) null).invoke(pC, - (Object[]) null); - LOGGER.debug("Returning the unique security name of first public credential: {}", o); - String userIdFound = o.toString(); - String userIdUsed = userIdFound; - if (TaskanaEngineConfiguration.shouldUseLowerCaseForAccessIds() && userIdFound != null) { - userIdUsed = userIdFound.toLowerCase(); - } - LOGGER.trace("Found User id {}. Returning User id {} ", userIdFound, userIdUsed); - return userIdUsed; - } - } - } catch (Exception e) { - LOGGER.warn("Could not get user from WSSubject. Going ahead unauthorized."); - } - return null; + public static List getAccessIds() { + List accessIds = new ArrayList<>(); + List groupIds = getGroupIds(); + accessIds.add(getUserid()); + if (!groupIds.isEmpty()) { + accessIds.addAll(groupIds); } + return accessIds; + } - /** - * Checks, whether Taskana is running on IBM WebSphere. - * - * @return true, if it is running on IBM WebSphere - */ - private static boolean runningOnWebSphere() { - if (runningOnWebSphere == null) { - try { - Class.forName(WSSUBJECT_CLASSNAME); - LOGGER.debug("WSSubject detected. Assuming that Taskana runs on IBM WebSphere."); - runningOnWebSphere = Boolean.TRUE; - } catch (ClassNotFoundException e) { - LOGGER.debug("No WSSubject detected. Using JAAS subject further on."); - runningOnWebSphere = Boolean.FALSE; - } + /** + * Returns the unique security name of the first public credentials found in the WSSubject as + * userid. + * + * @return the userid of the caller. If the userid could not be obtained, null is returned. + */ + private static String getUseridFromWSSubject() { + try { + Class wsSubjectClass = Class.forName(WSSUBJECT_CLASSNAME); + Method getCallerSubjectMethod = + wsSubjectClass.getMethod(GET_CALLER_SUBJECT_METHOD, (Class[]) null); + Subject callerSubject = (Subject) getCallerSubjectMethod.invoke(null, (Object[]) null); + LOGGER.debug("Subject of caller: {}", callerSubject); + if (callerSubject != null) { + Set publicCredentials = callerSubject.getPublicCredentials(); + LOGGER.debug("Public credentials of caller: {}", publicCredentials); + for (Object pC : publicCredentials) { + Object o = + pC.getClass() + .getMethod(GET_UNIQUE_SECURITY_NAME_METHOD, (Class[]) null) + .invoke(pC, (Object[]) null); + LOGGER.debug("Returning the unique security name of first public credential: {}", o); + String userIdFound = o.toString(); + String userIdUsed = userIdFound; + if (TaskanaEngineConfiguration.shouldUseLowerCaseForAccessIds() && userIdFound != null) { + userIdUsed = userIdFound.toLowerCase(); + } + LOGGER.trace("Found User id {}. Returning User id {} ", userIdFound, userIdUsed); + return userIdUsed; } - return runningOnWebSphere; + } + } catch (Exception e) { + LOGGER.warn("Could not get user from WSSubject. Going ahead unauthorized."); } + return null; + } - private static String getUseridFromJAASSubject() { - Subject subject = Subject.getSubject(AccessController.getContext()); - LOGGER.trace("Subject of caller: {}", subject); - if (subject != null) { - Set principals = subject.getPrincipals(); - LOGGER.trace("Public principals of caller: {}", principals); - for (Principal pC : principals) { - if (!(pC instanceof Group)) { - String userIdFound = pC.getName(); - String userIdUsed = userIdFound; - if (TaskanaEngineConfiguration.shouldUseLowerCaseForAccessIds() && userIdFound != null) { - userIdUsed = userIdFound.toLowerCase(); - } - LOGGER.trace("Found User id {}. Returning User id {} ", userIdFound, userIdUsed); - return userIdUsed; - } - } - } - LOGGER.trace("No userid found in subject!"); - return null; + /** + * Checks, whether Taskana is running on IBM WebSphere. + * + * @return true, if it is running on IBM WebSphere + */ + private static boolean runningOnWebSphere() { + if (runningOnWebSphere == null) { + try { + Class.forName(WSSUBJECT_CLASSNAME); + LOGGER.debug("WSSubject detected. Assuming that Taskana runs on IBM WebSphere."); + runningOnWebSphere = Boolean.TRUE; + } catch (ClassNotFoundException e) { + LOGGER.debug("No WSSubject detected. Using JAAS subject further on."); + runningOnWebSphere = Boolean.FALSE; + } } + return runningOnWebSphere; + } - public static List getGroupIds() { - Subject subject = Subject.getSubject(AccessController.getContext()); - LOGGER.trace("Subject of caller: {}", subject); - List groupIds = new ArrayList<>(); - if (subject != null) { - Set groups = subject.getPrincipals(Group.class); - LOGGER.trace("Public groups of caller: {}", groups); - for (Principal group : groups) { - String groupNameFound = group.getName(); - String groupNameReturned = groupNameFound; - if (TaskanaEngineConfiguration.shouldUseLowerCaseForAccessIds() && groupNameFound != null) { - groupNameReturned = groupNameFound.toLowerCase(); - } - LOGGER.trace("Found group id {}. Returning group Id: {}", groupNameFound, groupNameReturned); - groupIds.add(groupNameReturned); - } - return groupIds; + private static String getUseridFromJAASSubject() { + Subject subject = Subject.getSubject(AccessController.getContext()); + LOGGER.trace("Subject of caller: {}", subject); + if (subject != null) { + Set principals = subject.getPrincipals(); + LOGGER.trace("Public principals of caller: {}", principals); + for (Principal pC : principals) { + if (!(pC instanceof Group)) { + String userIdFound = pC.getName(); + String userIdUsed = userIdFound; + if (TaskanaEngineConfiguration.shouldUseLowerCaseForAccessIds() && userIdFound != null) { + userIdUsed = userIdFound.toLowerCase(); + } + LOGGER.trace("Found User id {}. Returning User id {} ", userIdFound, userIdUsed); + return userIdUsed; } - LOGGER.trace("No groupids found in subject!"); - return groupIds; - } - - public static List getAccessIds() { - List accessIds = new ArrayList<>(); - List groupIds = getGroupIds(); - accessIds.add(getUserid()); - if (!groupIds.isEmpty()) { - accessIds.addAll(groupIds); - } - return accessIds; + } } + LOGGER.trace("No userid found in subject!"); + return null; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/security/GroupPrincipal.java b/lib/taskana-core/src/main/java/pro/taskana/security/GroupPrincipal.java index 8cf7c8b63..785c4844a 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/security/GroupPrincipal.java +++ b/lib/taskana-core/src/main/java/pro/taskana/security/GroupPrincipal.java @@ -9,47 +9,48 @@ import java.util.Set; import pro.taskana.impl.util.LoggerUtils; -/** - * Represents a group with a name and a set of members. - */ +/** Represents a group with a name and a set of members. */ public class GroupPrincipal implements Group { - private String name; - private Set members; + private String name; + private Set members; - public GroupPrincipal(String name) { - this.name = name; - this.members = new HashSet(); - } + public GroupPrincipal(String name) { + this.name = name; + this.members = new HashSet(); + } - @Override - public String getName() { - return this.name; - } + @Override + public String getName() { + return this.name; + } - @Override - public boolean addMember(Principal user) { - return this.members.add(user); - } + @Override + public boolean addMember(Principal user) { + return this.members.add(user); + } - @Override - public boolean removeMember(Principal user) { - return this.members.remove(user); - } + @Override + public boolean removeMember(Principal user) { + return this.members.remove(user); + } - @Override - public boolean isMember(Principal member) { - return this.members.contains(member); - } + @Override + public boolean isMember(Principal member) { + return this.members.contains(member); + } - @Override - public Enumeration members() { - return Collections.enumeration(this.members); - } - - @Override - public String toString() { - return "GroupPrincipal [name=" + name + ", members=" + LoggerUtils.setToString(this.members) + "]"; - } + @Override + public Enumeration members() { + return Collections.enumeration(this.members); + } + @Override + public String toString() { + return "GroupPrincipal [name=" + + name + + ", members=" + + LoggerUtils.setToString(this.members) + + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/security/UserPrincipal.java b/lib/taskana-core/src/main/java/pro/taskana/security/UserPrincipal.java index 0755847fb..8dbe54d55 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/security/UserPrincipal.java +++ b/lib/taskana-core/src/main/java/pro/taskana/security/UserPrincipal.java @@ -2,24 +2,22 @@ package pro.taskana.security; import java.security.Principal; -/** - * Represents a user principal with a name. - */ +/** Represents a user principal with a name. */ public class UserPrincipal implements Principal { - private String name; + private String name; - public UserPrincipal(String name) { - this.name = name; - } + public UserPrincipal(String name) { + this.name = name; + } - @Override - public String getName() { - return this.name; - } + @Override + public String getName() { + return this.name; + } - @Override - public String toString() { - return "UserPrincipal [name= " + this.getName() + "]"; - } + @Override + public String toString() { + return "UserPrincipal [name= " + this.getName() + "]"; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/taskrouting/TaskRoutingManager.java b/lib/taskana-core/src/main/java/pro/taskana/taskrouting/TaskRoutingManager.java index 60600f27d..6d496647e 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/taskrouting/TaskRoutingManager.java +++ b/lib/taskana-core/src/main/java/pro/taskana/taskrouting/TaskRoutingManager.java @@ -6,7 +6,6 @@ import java.util.Objects; import java.util.ServiceLoader; import java.util.Set; import java.util.stream.Collectors; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -15,70 +14,75 @@ import pro.taskana.TaskanaEngine; import pro.taskana.taskrouting.api.TaskRoutingProvider; /** - * Loads TaskRoutingProvider SPI implementation(s) and passes requests to determine workbasketids to them. + * Loads TaskRoutingProvider SPI implementation(s) and passes requests to determine workbasketids to + * them. */ public final class TaskRoutingManager { - private static final Logger LOGGER = LoggerFactory.getLogger(TaskRoutingManager.class); - private static TaskRoutingManager singleton; - private static boolean enabled = false; - private ServiceLoader serviceLoader; - private static List theTaskRoutingProviders = new ArrayList<>(); + private static final Logger LOGGER = LoggerFactory.getLogger(TaskRoutingManager.class); + private static TaskRoutingManager singleton; + private static boolean enabled = false; + private static List theTaskRoutingProviders = new ArrayList<>(); + private ServiceLoader serviceLoader; - private TaskRoutingManager(TaskanaEngine taskanaEngine) { - serviceLoader = ServiceLoader.load(TaskRoutingProvider.class); - for (TaskRoutingProvider router : serviceLoader) { - router.initialize(taskanaEngine); - theTaskRoutingProviders.add(router); - LOGGER.info("Registered TaskRouter provider: {}", router.getClass().getName()); - } - - if (theTaskRoutingProviders.isEmpty()) { - LOGGER.info("No TaskRouter provider found. Running without Task Routing."); - } else { - enabled = true; - } + private TaskRoutingManager(TaskanaEngine taskanaEngine) { + serviceLoader = ServiceLoader.load(TaskRoutingProvider.class); + for (TaskRoutingProvider router : serviceLoader) { + router.initialize(taskanaEngine); + theTaskRoutingProviders.add(router); + LOGGER.info("Registered TaskRouter provider: {}", router.getClass().getName()); } - public static synchronized TaskRoutingManager getInstance(TaskanaEngine taskanaEngine) { - if (singleton == null) { - singleton = new TaskRoutingManager(taskanaEngine); - } - return singleton; + if (theTaskRoutingProviders.isEmpty()) { + LOGGER.info("No TaskRouter provider found. Running without Task Routing."); + } else { + enabled = true; } + } - public static boolean isTaskRoutingEnabled() { - return enabled; + public static synchronized TaskRoutingManager getInstance(TaskanaEngine taskanaEngine) { + if (singleton == null) { + singleton = new TaskRoutingManager(taskanaEngine); } + return singleton; + } - /** - * Determines a workbasket id for a given task. - * Algorithm: The task that needs a workbasket id is passed to all registered TaskRoutingProviders. - * If they return no or more than one workbasketId, null is returned, otherwise we return - * the workbasketId that was returned from the TaskRoutingProviders. - * - * @param task the task for which a workbasketId is to be determined. - * @return the id of the workbasket in which the task is to be created. - */ - public String determineWorkbasketId(Task task) { - LOGGER.debug("entry to routeToWorkbasket. TaskRouterr is enabled {}, task = {}", isTaskRoutingEnabled(), task); - String workbasketId = null; - if (isTaskRoutingEnabled()) { - // route to all TaskRoutingProviders - // collect in a set to see whether different workbasket ids are returned - Set workbasketIds = theTaskRoutingProviders.stream() - .map(rtr -> rtr.determineWorkbasketId(task)) - .filter(Objects::nonNull) - .collect(Collectors.toSet()); - if (workbasketIds.isEmpty()) { - LOGGER.error("No TaskRouter determined a workbasket for task {}.", task); - } else if (workbasketIds.size() > 1) { - LOGGER.error("The TaskRouters determined more than one workbasket for task {}", task); - } else { - workbasketId = workbasketIds.stream().findFirst().orElse(null); - } - } - LOGGER.debug("exit from routeToWorkbasketId. Destination WorkbasketId = {}", workbasketId); - return workbasketId; - } + public static boolean isTaskRoutingEnabled() { + return enabled; + } + + /** + * Determines a workbasket id for a given task. Algorithm: The task that needs a workbasket id is + * passed to all registered TaskRoutingProviders. If they return no or more than one workbasketId, + * null is returned, otherwise we return the workbasketId that was returned from the + * TaskRoutingProviders. + * + * @param task the task for which a workbasketId is to be determined. + * @return the id of the workbasket in which the task is to be created. + */ + public String determineWorkbasketId(Task task) { + LOGGER.debug( + "entry to routeToWorkbasket. TaskRouterr is enabled {}, task = {}", + isTaskRoutingEnabled(), + task); + String workbasketId = null; + if (isTaskRoutingEnabled()) { + // route to all TaskRoutingProviders + // collect in a set to see whether different workbasket ids are returned + Set workbasketIds = + theTaskRoutingProviders.stream() + .map(rtr -> rtr.determineWorkbasketId(task)) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); + if (workbasketIds.isEmpty()) { + LOGGER.error("No TaskRouter determined a workbasket for task {}.", task); + } else if (workbasketIds.size() > 1) { + LOGGER.error("The TaskRouters determined more than one workbasket for task {}", task); + } else { + workbasketId = workbasketIds.stream().findFirst().orElse(null); + } + } + LOGGER.debug("exit from routeToWorkbasketId. Destination WorkbasketId = {}", workbasketId); + return workbasketId; + } } diff --git a/lib/taskana-core/src/main/java/pro/taskana/taskrouting/api/TaskRoutingProvider.java b/lib/taskana-core/src/main/java/pro/taskana/taskrouting/api/TaskRoutingProvider.java index 745f93db5..a44f967fa 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/taskrouting/api/TaskRoutingProvider.java +++ b/lib/taskana-core/src/main/java/pro/taskana/taskrouting/api/TaskRoutingProvider.java @@ -3,26 +3,21 @@ package pro.taskana.taskrouting.api; import pro.taskana.Task; import pro.taskana.TaskanaEngine; -/** - * Interface for TASKANA TaskRoutingProvider SPI. - */ +/** Interface for TASKANA TaskRoutingProvider SPI. */ public interface TaskRoutingProvider { - /** - * Initialize TaskRoutingProvider service. - * - * @param taskanaEngine - * {@link TaskanaEngine} The Taskana engine needed for initialization. - */ - void initialize(TaskanaEngine taskanaEngine); - - /** - * Determines a WorkbasketId for a given task. - * - * @param task - * {@link Task} The task for which a workbasket must be determined. - * @return the id of the workbasket in which the task is to be created. - */ - String determineWorkbasketId(Task task); + /** + * Initialize TaskRoutingProvider service. + * + * @param taskanaEngine {@link TaskanaEngine} The Taskana engine needed for initialization. + */ + void initialize(TaskanaEngine taskanaEngine); + /** + * Determines a WorkbasketId for a given task. + * + * @param task {@link Task} The task for which a workbasket must be determined. + * @return the id of the workbasket in which the task is to be created. + */ + String determineWorkbasketId(Task task); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/transaction/TaskanaCallable.java b/lib/taskana-core/src/main/java/pro/taskana/transaction/TaskanaCallable.java index db2df099d..76269c52c 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/transaction/TaskanaCallable.java +++ b/lib/taskana-core/src/main/java/pro/taskana/transaction/TaskanaCallable.java @@ -3,12 +3,11 @@ package pro.taskana.transaction; /** * represents a callable Object. * - * @param - * the type of the returned objects. + * @param the type of the returned objects. * @author bbr */ @FunctionalInterface public interface TaskanaCallable { - T call(); + T call(); } diff --git a/lib/taskana-core/src/main/java/pro/taskana/transaction/TaskanaTransactionProvider.java b/lib/taskana-core/src/main/java/pro/taskana/transaction/TaskanaTransactionProvider.java index 32c1e5ba7..19fedfd21 100644 --- a/lib/taskana-core/src/main/java/pro/taskana/transaction/TaskanaTransactionProvider.java +++ b/lib/taskana-core/src/main/java/pro/taskana/transaction/TaskanaTransactionProvider.java @@ -3,12 +3,10 @@ package pro.taskana.transaction; /** * This class provides support for transactions. * - * @param - * the type of the returned objects. + * @param the type of the returned objects. */ @FunctionalInterface public interface TaskanaTransactionProvider { - T executeInTransaction(TaskanaCallable action); - + T executeInTransaction(TaskanaCallable action); } diff --git a/lib/taskana-core/src/test/java/acceptance/AbstractAccTest.java b/lib/taskana-core/src/test/java/acceptance/AbstractAccTest.java index f0057778e..563b6b8c8 100644 --- a/lib/taskana-core/src/test/java/acceptance/AbstractAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/AbstractAccTest.java @@ -9,9 +9,7 @@ import java.time.ZoneId; import java.time.ZoneOffset; import java.util.HashMap; import java.util.Map; - import javax.sql.DataSource; - import org.junit.jupiter.api.BeforeAll; import pro.taskana.Attachment; @@ -24,86 +22,92 @@ import pro.taskana.exceptions.ClassificationNotFoundException; import pro.taskana.impl.configuration.TaskanaEngineTestConfiguration; import pro.taskana.sampledata.SampleDataGenerator; -/** - * Base class for all acceptance tests. - */ +/** Base class for all acceptance tests. */ public abstract class AbstractAccTest { - protected static TaskanaEngineConfiguration taskanaEngineConfiguration; - protected static TaskanaEngine taskanaEngine; + protected static TaskanaEngineConfiguration taskanaEngineConfiguration; + protected static TaskanaEngine taskanaEngine; - @BeforeAll - public static void setupTest() throws Exception { - resetDb(false); + @BeforeAll + public static void setupTest() throws Exception { + resetDb(false); + } + + public static void resetDb(boolean dropTables) throws SQLException { + DataSource dataSource = TaskanaEngineTestConfiguration.getDataSource(); + String schemaName = TaskanaEngineTestConfiguration.getSchemaName(); + SampleDataGenerator sampleDataGenerator = new SampleDataGenerator(dataSource, schemaName); + if (dropTables) { + sampleDataGenerator.dropDb(); + } + dataSource = TaskanaEngineTestConfiguration.getDataSource(); + taskanaEngineConfiguration = new TaskanaEngineConfiguration(dataSource, false, schemaName); + taskanaEngine = taskanaEngineConfiguration.buildTaskanaEngine(); + taskanaEngine.setConnectionManagementMode(ConnectionManagementMode.AUTOCOMMIT); + sampleDataGenerator.clearDb(); + sampleDataGenerator.generateTestData(); + } + + protected ObjectReference createObjectReference( + String company, String system, String systemInstance, String type, String value) { + ObjectReference objectReference = new ObjectReference(); + objectReference.setCompany(company); + objectReference.setSystem(system); + objectReference.setSystemInstance(systemInstance); + objectReference.setType(type); + objectReference.setValue(value); + return objectReference; + } + + protected Map createSimpleCustomProperties(int propertiesCount) { + HashMap properties = new HashMap<>(); + for (int i = 1; i <= propertiesCount; i++) { + properties.put("Property_" + i, "Property Value of Property_" + i); + } + return properties; + } + + protected Attachment createAttachment( + String classificationKey, + ObjectReference objRef, + String channel, + String receivedDate, + Map customAttributes) + throws ClassificationNotFoundException { + Attachment attachment = taskanaEngine.getTaskService().newAttachment(); + + attachment.setClassificationSummary( + taskanaEngine + .getClassificationService() + .getClassification(classificationKey, "DOMAIN_A") + .asSummary()); + attachment.setObjectReference(objRef); + attachment.setChannel(channel); + Instant receivedTimestamp = null; + if (receivedDate != null && receivedDate.length() < 11) { + // contains only the date, not the time + LocalDate date = LocalDate.parse(receivedDate); + receivedTimestamp = date.atStartOfDay().toInstant(ZoneOffset.UTC); + } else { + receivedTimestamp = Instant.parse(receivedDate); + } + attachment.setReceived(receivedTimestamp); + if (customAttributes != null) { + attachment.setCustomAttributes(customAttributes); } - public static void resetDb(boolean dropTables) throws SQLException { - DataSource dataSource = TaskanaEngineTestConfiguration.getDataSource(); - String schemaName = TaskanaEngineTestConfiguration.getSchemaName(); - SampleDataGenerator sampleDataGenerator = new SampleDataGenerator(dataSource, schemaName); - if (dropTables) { - sampleDataGenerator.dropDb(); - } - dataSource = TaskanaEngineTestConfiguration.getDataSource(); - taskanaEngineConfiguration = new TaskanaEngineConfiguration(dataSource, false, - schemaName); - taskanaEngine = taskanaEngineConfiguration.buildTaskanaEngine(); - taskanaEngine.setConnectionManagementMode(ConnectionManagementMode.AUTOCOMMIT); - sampleDataGenerator.clearDb(); - sampleDataGenerator.generateTestData(); - } + return attachment; + } - protected ObjectReference createObjectReference(String company, String system, String systemInstance, String type, - String value) { - ObjectReference objectReference = new ObjectReference(); - objectReference.setCompany(company); - objectReference.setSystem(system); - objectReference.setSystemInstance(systemInstance); - objectReference.setType(type); - objectReference.setValue(value); - return objectReference; - } + protected TimeInterval todaysInterval() { + Instant begin = + LocalDateTime.of(LocalDate.now(), LocalTime.MIN).atZone(ZoneId.systemDefault()).toInstant(); + Instant end = + LocalDateTime.of(LocalDate.now(), LocalTime.MAX).atZone(ZoneId.systemDefault()).toInstant(); + return new TimeInterval(begin, end); + } - protected Map createSimpleCustomProperties(int propertiesCount) { - HashMap properties = new HashMap<>(); - for (int i = 1; i <= propertiesCount; i++) { - properties.put("Property_" + i, "Property Value of Property_" + i); - } - return properties; - } - - protected Attachment createAttachment(String classificationKey, ObjectReference objRef, - String channel, String receivedDate, Map customAttributes) - throws ClassificationNotFoundException { - Attachment attachment = taskanaEngine.getTaskService().newAttachment(); - - attachment.setClassificationSummary( - taskanaEngine.getClassificationService().getClassification(classificationKey, "DOMAIN_A").asSummary()); - attachment.setObjectReference(objRef); - attachment.setChannel(channel); - Instant receivedTimestamp = null; - if (receivedDate != null && receivedDate.length() < 11) { - // contains only the date, not the time - LocalDate date = LocalDate.parse(receivedDate); - receivedTimestamp = date.atStartOfDay().toInstant(ZoneOffset.UTC); - } else { - receivedTimestamp = Instant.parse(receivedDate); - } - attachment.setReceived(receivedTimestamp); - if (customAttributes != null) { - attachment.setCustomAttributes(customAttributes); - } - - return attachment; - } - - protected TimeInterval todaysInterval() { - Instant begin = LocalDateTime.of(LocalDate.now(), LocalTime.MIN).atZone(ZoneId.systemDefault()).toInstant(); - Instant end = LocalDateTime.of(LocalDate.now(), LocalTime.MAX).atZone(ZoneId.systemDefault()).toInstant(); - return new TimeInterval(begin, end); - } - - protected Instant getInstant(String datetime) { - return LocalDateTime.parse(datetime).atZone(ZoneId.systemDefault()).toInstant(); - } + protected Instant getInstant(String datetime) { + return LocalDateTime.parse(datetime).atZone(ZoneId.systemDefault()).toInstant(); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/classification/CreateClassificationAccTest.java b/lib/taskana-core/src/test/java/acceptance/classification/CreateClassificationAccTest.java index 316d30160..e32b24d13 100644 --- a/lib/taskana-core/src/test/java/acceptance/classification/CreateClassificationAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/classification/CreateClassificationAccTest.java @@ -6,11 +6,11 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import acceptance.AbstractAccTest; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.Classification; import pro.taskana.ClassificationService; import pro.taskana.exceptions.ClassificationAlreadyExistException; @@ -23,228 +23,241 @@ import pro.taskana.impl.ClassificationImpl; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "create classification" scenarios. - */ +/** Acceptance test for all "create classification" scenarios. */ @ExtendWith(JAASExtension.class) class CreateClassificationAccTest extends AbstractAccTest { - private static final String ID_PREFIX_CLASSIFICATION = "CLI"; + private static final String ID_PREFIX_CLASSIFICATION = "CLI"; - private ClassificationService classificationService; + private ClassificationService classificationService; - CreateClassificationAccTest() { - super(); - classificationService = taskanaEngine.getClassificationService(); - } + CreateClassificationAccTest() { + super(); + classificationService = taskanaEngine.getClassificationService(); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "businessadmin"}) - @Test - void testCreateMasterClassification() - throws ClassificationAlreadyExistException, ClassificationNotFoundException, NotAuthorizedException, - DomainNotFoundException, InvalidArgumentException { - long amountOfClassificationsBefore = classificationService.createClassificationQuery().count(); - Classification classification = classificationService.newClassification("Key0", "", "TASK"); - classification.setIsValidInDomain(true); - classification = classificationService.createClassification(classification); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "businessadmin"}) + @Test + void testCreateMasterClassification() + throws ClassificationAlreadyExistException, ClassificationNotFoundException, + NotAuthorizedException, DomainNotFoundException, InvalidArgumentException { + long amountOfClassificationsBefore = classificationService.createClassificationQuery().count(); + Classification classification = classificationService.newClassification("Key0", "", "TASK"); + classification.setIsValidInDomain(true); + classification = classificationService.createClassification(classification); - // check only 1 created - long amountOfClassificationsAfter = classificationService.createClassificationQuery().count(); - assertThat(amountOfClassificationsAfter, equalTo(amountOfClassificationsBefore + 1)); + // check only 1 created + long amountOfClassificationsAfter = classificationService.createClassificationQuery().count(); + assertThat(amountOfClassificationsAfter, equalTo(amountOfClassificationsBefore + 1)); - classification = classificationService.getClassification(classification.getId()); - assertNotNull(classification); - assertNotNull(classification.getCreated()); - assertNotNull(classification.getModified()); - assertNotNull(classification.getId()); - assertThat(classification.getIsValidInDomain(), equalTo(false)); - assertTrue(classification.getId().startsWith(ID_PREFIX_CLASSIFICATION)); - } + classification = classificationService.getClassification(classification.getId()); + assertNotNull(classification); + assertNotNull(classification.getCreated()); + assertNotNull(classification.getModified()); + assertNotNull(classification.getId()); + assertThat(classification.getIsValidInDomain(), equalTo(false)); + assertTrue(classification.getId().startsWith(ID_PREFIX_CLASSIFICATION)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "businessadmin"}) - @Test - void testCreateClassificationWithMasterCopy() - throws ClassificationAlreadyExistException, ClassificationNotFoundException, NotAuthorizedException, - DomainNotFoundException, InvalidArgumentException { - long amountOfClassificationsBefore = classificationService.createClassificationQuery().count(); - Classification classification = classificationService.newClassification("Key1", "DOMAIN_A", "TASK"); - classification.setIsValidInDomain(true); - classification = classificationService.createClassification(classification); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "businessadmin"}) + @Test + void testCreateClassificationWithMasterCopy() + throws ClassificationAlreadyExistException, ClassificationNotFoundException, + NotAuthorizedException, DomainNotFoundException, InvalidArgumentException { + long amountOfClassificationsBefore = classificationService.createClassificationQuery().count(); + Classification classification = + classificationService.newClassification("Key1", "DOMAIN_A", "TASK"); + classification.setIsValidInDomain(true); + classification = classificationService.createClassification(classification); - // Check returning one is the "original" - Classification createdClassification = classificationService.getClassification(classification.getId()); - assertNotNull(createdClassification.getId()); - assertNotNull(createdClassification.getCreated()); - assertNotNull(createdClassification.getModified()); - assertThat(createdClassification.getIsValidInDomain(), equalTo(true)); - assertThat(createdClassification.getDomain(), equalTo("DOMAIN_A")); - assertEquals(createdClassification.getKey(), "Key1"); + // Check returning one is the "original" + Classification createdClassification = + classificationService.getClassification(classification.getId()); + assertNotNull(createdClassification.getId()); + assertNotNull(createdClassification.getCreated()); + assertNotNull(createdClassification.getModified()); + assertThat(createdClassification.getIsValidInDomain(), equalTo(true)); + assertThat(createdClassification.getDomain(), equalTo("DOMAIN_A")); + assertEquals(createdClassification.getKey(), "Key1"); - // Check 2 new created - long amountOfClassificationsAfter = classificationService.createClassificationQuery().count(); - assertThat(amountOfClassificationsAfter, equalTo(amountOfClassificationsBefore + 2)); + // Check 2 new created + long amountOfClassificationsAfter = classificationService.createClassificationQuery().count(); + assertThat(amountOfClassificationsAfter, equalTo(amountOfClassificationsBefore + 2)); - // Check main - classification = classificationService.getClassification(classification.getId()); - assertNotNull(classification); - assertNotNull(classification.getCreated()); - assertNotNull(classification.getModified()); - assertNotNull(classification.getId()); - assertThat(classification.getIsValidInDomain(), equalTo(true)); - assertTrue(classification.getId().startsWith(ID_PREFIX_CLASSIFICATION)); + // Check main + classification = classificationService.getClassification(classification.getId()); + assertNotNull(classification); + assertNotNull(classification.getCreated()); + assertNotNull(classification.getModified()); + assertNotNull(classification.getId()); + assertThat(classification.getIsValidInDomain(), equalTo(true)); + assertTrue(classification.getId().startsWith(ID_PREFIX_CLASSIFICATION)); - // Check master-copy - classification = classificationService.getClassification(classification.getKey(), ""); - assertNotNull(classification); - assertNotNull(classification.getCreated()); - assertNotNull(classification.getModified()); - assertNotNull(classification.getId()); - assertThat(classification.getIsValidInDomain(), equalTo(false)); - assertTrue(classification.getId().startsWith(ID_PREFIX_CLASSIFICATION)); - } + // Check master-copy + classification = classificationService.getClassification(classification.getKey(), ""); + assertNotNull(classification); + assertNotNull(classification.getCreated()); + assertNotNull(classification.getModified()); + assertNotNull(classification.getId()); + assertThat(classification.getIsValidInDomain(), equalTo(false)); + assertTrue(classification.getId().startsWith(ID_PREFIX_CLASSIFICATION)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "businessadmin"}) - @Test - void testCreateClassificationWithExistingMaster() - throws DomainNotFoundException, ClassificationAlreadyExistException, - NotAuthorizedException, InvalidArgumentException { + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "businessadmin"}) + @Test + void testCreateClassificationWithExistingMaster() + throws DomainNotFoundException, ClassificationAlreadyExistException, NotAuthorizedException, + InvalidArgumentException { - classificationService.createClassification( - classificationService.newClassification("Key0815", "", "TASK")); + classificationService.createClassification( + classificationService.newClassification("Key0815", "", "TASK")); - long amountOfClassificationsBefore = classificationService.createClassificationQuery().count(); - Classification expected = classificationService.newClassification("Key0815", "DOMAIN_B", "TASK"); - Classification actual = classificationService.createClassification(expected); - long amountOfClassificationsAfter = classificationService.createClassificationQuery().count(); + long amountOfClassificationsBefore = classificationService.createClassificationQuery().count(); + Classification expected = + classificationService.newClassification("Key0815", "DOMAIN_B", "TASK"); + Classification actual = classificationService.createClassification(expected); + long amountOfClassificationsAfter = classificationService.createClassificationQuery().count(); - assertEquals(amountOfClassificationsBefore + 1, amountOfClassificationsAfter); - assertNotNull(actual); - assertEquals(actual, expected); - assertTrue(actual.getIsValidInDomain()); - } + assertEquals(amountOfClassificationsBefore + 1, amountOfClassificationsAfter); + assertNotNull(actual); + assertEquals(actual, expected); + assertTrue(actual.getIsValidInDomain()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "businessadmin"}) - @Test - void testCreateChildInDomainAndCopyInMaster() - throws TaskanaException { - Classification parent = classificationService.newClassification("Key0816", "DOMAIN_A", "TASK"); - Classification actualParent = classificationService.createClassification(parent); - assertNotNull(actualParent); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "businessadmin"}) + @Test + void testCreateChildInDomainAndCopyInMaster() throws TaskanaException { + Classification parent = classificationService.newClassification("Key0816", "DOMAIN_A", "TASK"); + Classification actualParent = classificationService.createClassification(parent); + assertNotNull(actualParent); - long amountOfClassificationsBefore = classificationService.createClassificationQuery().count(); - Classification child = classificationService.newClassification("Key0817", "DOMAIN_A", "TASK"); - child.setParentId(actualParent.getId()); - child.setParentKey(actualParent.getKey()); - Classification actualChild = classificationService.createClassification(child); - long amountOfClassificationsAfter = classificationService.createClassificationQuery().count(); + long amountOfClassificationsBefore = classificationService.createClassificationQuery().count(); + Classification child = classificationService.newClassification("Key0817", "DOMAIN_A", "TASK"); + child.setParentId(actualParent.getId()); + child.setParentKey(actualParent.getKey()); + Classification actualChild = classificationService.createClassification(child); + long amountOfClassificationsAfter = classificationService.createClassificationQuery().count(); - assertEquals(amountOfClassificationsBefore + 2, amountOfClassificationsAfter); - assertNotNull(actualChild); - } + assertEquals(amountOfClassificationsBefore + 2, amountOfClassificationsAfter); + assertNotNull(actualChild); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "businessadmin"}) - @Test - void testCreateClassificationWithInvalidValues() { - classificationService.createClassificationQuery().count(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "businessadmin"}) + @Test + void testCreateClassificationWithInvalidValues() { + classificationService.createClassificationQuery().count(); - // Check key NULL - Classification classification = classificationService.newClassification(null, "DOMAIN_A", "TASK"); - Assertions.assertThrows(InvalidArgumentException.class, () -> - classificationService.createClassification(classification)); + // Check key NULL + Classification classification = + classificationService.newClassification(null, "DOMAIN_A", "TASK"); + Assertions.assertThrows( + InvalidArgumentException.class, + () -> classificationService.createClassification(classification)); - // Check invalid ServiceLevel + // Check invalid ServiceLevel - Classification classification2 = classificationService.newClassification("Key2", "DOMAIN_B", "TASK"); - classification2.setServiceLevel("abc"); - Assertions.assertThrows(InvalidArgumentException.class, - () -> classificationService.createClassification(classification2)); - } + Classification classification2 = + classificationService.newClassification("Key2", "DOMAIN_B", "TASK"); + classification2.setServiceLevel("abc"); + Assertions.assertThrows( + InvalidArgumentException.class, + () -> classificationService.createClassification(classification2)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "businessadmin"}) - @Test - void testCreateClassificationAlreadyExisting() - throws TaskanaException { - Classification classification = classificationService.newClassification("Key3", "", "TASK"); - Classification classificationCreated = classificationService.createClassification(classification); - Assertions.assertThrows(ClassificationAlreadyExistException.class, - () -> classificationService.createClassification(classificationCreated)); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "businessadmin"}) + @Test + void testCreateClassificationAlreadyExisting() throws TaskanaException { + Classification classification = classificationService.newClassification("Key3", "", "TASK"); + Classification classificationCreated = + classificationService.createClassification(classification); + Assertions.assertThrows( + ClassificationAlreadyExistException.class, + () -> classificationService.createClassification(classificationCreated)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "businessadmin"}) - @Test - void testCreateClassificationInUnknownDomain() { - Classification classification = classificationService.newClassification("Key3", "UNKNOWN_DOMAIN", "TASK"); - Assertions.assertThrows(DomainNotFoundException.class, - () -> classificationService.createClassification(classification)); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "businessadmin"}) + @Test + void testCreateClassificationInUnknownDomain() { + Classification classification = + classificationService.newClassification("Key3", "UNKNOWN_DOMAIN", "TASK"); + Assertions.assertThrows( + DomainNotFoundException.class, + () -> classificationService.createClassification(classification)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "businessadmin"}) - @Test - void testCreateClassificationOfUnknownType() { - Classification classification = classificationService.newClassification("Key3", "DOMAIN_A", "UNKNOWN_TYPE"); - Assertions.assertThrows(InvalidArgumentException.class, - () -> classificationService.createClassification(classification)); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "businessadmin"}) + @Test + void testCreateClassificationOfUnknownType() { + Classification classification = + classificationService.newClassification("Key3", "DOMAIN_A", "UNKNOWN_TYPE"); + Assertions.assertThrows( + InvalidArgumentException.class, + () -> classificationService.createClassification(classification)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "businessadmin"}) - @Test - void testCreateClassificationOfUnknownCategory() { - Classification classification = classificationService.newClassification("Key4", "DOMAIN_A", "TASK"); - classification.setCategory("UNKNOWN_CATEGORY"); - Assertions.assertThrows(InvalidArgumentException.class, - () -> classificationService.createClassification(classification)); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "businessadmin"}) + @Test + void testCreateClassificationOfUnknownCategory() { + Classification classification = + classificationService.newClassification("Key4", "DOMAIN_A", "TASK"); + classification.setCategory("UNKNOWN_CATEGORY"); + Assertions.assertThrows( + InvalidArgumentException.class, + () -> classificationService.createClassification(classification)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "businessadmin"}) - @Test - void testCreateClassificationWithInvalidParentId() { - Classification classification = classificationService.newClassification("Key5", "", "TASK"); - classification.setParentId("ID WHICH CANT BE FOUND"); - Assertions.assertThrows(InvalidArgumentException.class, - () -> classificationService.createClassification(classification)); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "businessadmin"}) + @Test + void testCreateClassificationWithInvalidParentId() { + Classification classification = classificationService.newClassification("Key5", "", "TASK"); + classification.setParentId("ID WHICH CANT BE FOUND"); + Assertions.assertThrows( + InvalidArgumentException.class, + () -> classificationService.createClassification(classification)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "businessadmin"}) - @Test - void testCreateClassificationWithInvalidParentKey() { - Classification classification = classificationService.newClassification("Key5", "", "TASK"); - classification.setParentKey("KEY WHICH CANT BE FOUND"); - Assertions.assertThrows(InvalidArgumentException.class, - () -> classificationService.createClassification(classification)); - } - - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "businessadmin"}) - @Test - void testCreateClassificationWithExplicitId() { - ClassificationImpl classification = (ClassificationImpl) classificationService - .newClassification("Key0818", "", "TASK"); - classification.setId("EXPLICIT ID"); - Assertions.assertThrows(InvalidArgumentException.class, - () -> classificationService.createClassification(classification)); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "businessadmin"}) + @Test + void testCreateClassificationWithInvalidParentKey() { + Classification classification = classificationService.newClassification("Key5", "", "TASK"); + classification.setParentKey("KEY WHICH CANT BE FOUND"); + Assertions.assertThrows( + InvalidArgumentException.class, + () -> classificationService.createClassification(classification)); + } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "businessadmin"}) + @Test + void testCreateClassificationWithExplicitId() { + ClassificationImpl classification = + (ClassificationImpl) classificationService.newClassification("Key0818", "", "TASK"); + classification.setId("EXPLICIT ID"); + Assertions.assertThrows( + InvalidArgumentException.class, + () -> classificationService.createClassification(classification)); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/classification/DeleteClassificationAccTest.java b/lib/taskana-core/src/test/java/acceptance/classification/DeleteClassificationAccTest.java index 464763e35..c10845955 100644 --- a/lib/taskana-core/src/test/java/acceptance/classification/DeleteClassificationAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/classification/DeleteClassificationAccTest.java @@ -4,11 +4,11 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import acceptance.AbstractAccTest; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.Classification; import pro.taskana.ClassificationService; import pro.taskana.exceptions.ClassificationInUseException; @@ -17,119 +17,124 @@ import pro.taskana.exceptions.NotAuthorizedException; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "delete classification" scenarios. - */ +/** Acceptance test for all "delete classification" scenarios. */ @ExtendWith(JAASExtension.class) class DeleteClassificationAccTest extends AbstractAccTest { - private ClassificationService classificationService; + private ClassificationService classificationService; - DeleteClassificationAccTest() { - super(); - classificationService = taskanaEngine.getClassificationService(); - } + DeleteClassificationAccTest() { + super(); + classificationService = taskanaEngine.getClassificationService(); + } - @WithAccessId( - userName = "dummy", - groupNames = {"businessadmin"}) - @Test - void testDeleteClassificationInDomain() - throws ClassificationNotFoundException, NotAuthorizedException, ClassificationInUseException { - classificationService.deleteClassification("L140101", "DOMAIN_A"); + @WithAccessId( + userName = "dummy", + groupNames = {"businessadmin"}) + @Test + void testDeleteClassificationInDomain() + throws ClassificationNotFoundException, NotAuthorizedException, ClassificationInUseException { + classificationService.deleteClassification("L140101", "DOMAIN_A"); - Classification classification = classificationService.getClassification("L140101", "DOMAIN_A"); - assertNotNull(classification); - assertEquals("", classification.getDomain()); - } + Classification classification = classificationService.getClassification("L140101", "DOMAIN_A"); + assertNotNull(classification); + assertEquals("", classification.getDomain()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "group_2"}) - @Test - void testDeleteClassificationInDomainUserIsNotAuthorized() { - Assertions.assertThrows(NotAuthorizedException.class, () -> - classificationService.deleteClassification("L140101", "DOMAIN_A")); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "group_2"}) + @Test + void testDeleteClassificationInDomainUserIsNotAuthorized() { + Assertions.assertThrows( + NotAuthorizedException.class, + () -> classificationService.deleteClassification("L140101", "DOMAIN_A")); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "businessadmin"}) - @Test - void testThrowExeptionIfDeleteClassificationWithExistingTasks() { - Assertions.assertThrows(ClassificationInUseException.class, () -> - classificationService.deleteClassification("L1050", "DOMAIN_A")); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "businessadmin"}) + @Test + void testThrowExeptionIfDeleteClassificationWithExistingTasks() { + Assertions.assertThrows( + ClassificationInUseException.class, + () -> classificationService.deleteClassification("L1050", "DOMAIN_A")); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "businessadmin"}) - @Test - void testThrowExeptionIfDeleteMasterClassificationWithExistingTasks() { - Assertions.assertThrows(ClassificationInUseException.class, () -> - classificationService.deleteClassification("L1050", "")); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "businessadmin"}) + @Test + void testThrowExeptionIfDeleteMasterClassificationWithExistingTasks() { + Assertions.assertThrows( + ClassificationInUseException.class, + () -> classificationService.deleteClassification("L1050", "")); + } - @WithAccessId( - userName = "dummy", - groupNames = {"businessadmin"}) - @Test - void testDeleteMasterClassification() - throws ClassificationNotFoundException, NotAuthorizedException, ClassificationInUseException { + @WithAccessId( + userName = "dummy", + groupNames = {"businessadmin"}) + @Test + void testDeleteMasterClassification() + throws ClassificationNotFoundException, NotAuthorizedException, ClassificationInUseException { - classificationService.deleteClassification("L3060", ""); - Assertions.assertThrows(ClassificationNotFoundException.class, () -> - classificationService.getClassification("L3060", "DOMAIN_A") - ); - } + classificationService.deleteClassification("L3060", ""); + Assertions.assertThrows( + ClassificationNotFoundException.class, + () -> classificationService.getClassification("L3060", "DOMAIN_A")); + } - @WithAccessId( - userName = "dummy", - groupNames = {"businessadmin"}) - @Test - void testDeleteMasterClassificationWithExistingAttachment() { - Assertions.assertThrows(ClassificationInUseException.class, () -> - classificationService.deleteClassification("L12010", "")); - } + @WithAccessId( + userName = "dummy", + groupNames = {"businessadmin"}) + @Test + void testDeleteMasterClassificationWithExistingAttachment() { + Assertions.assertThrows( + ClassificationInUseException.class, + () -> classificationService.deleteClassification("L12010", "")); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "businessadmin"}) - @Test - void testThrowExceptionWhenChildClassificationIsInUseAndRollback() - throws ClassificationNotFoundException { + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "businessadmin"}) + @Test + void testThrowExceptionWhenChildClassificationIsInUseAndRollback() + throws ClassificationNotFoundException { - Assertions.assertThrows(ClassificationInUseException.class, () -> - classificationService.deleteClassification("L11010", "DOMAIN_A")); + Assertions.assertThrows( + ClassificationInUseException.class, + () -> classificationService.deleteClassification("L11010", "DOMAIN_A")); - Classification rollback = classificationService.getClassification("L11010", "DOMAIN_A"); - assertEquals("DOMAIN_A", rollback.getDomain()); + Classification rollback = classificationService.getClassification("L11010", "DOMAIN_A"); + assertEquals("DOMAIN_A", rollback.getDomain()); - Assertions.assertThrows(ClassificationInUseException.class, () -> - classificationService.deleteClassification("L11010", "")); + Assertions.assertThrows( + ClassificationInUseException.class, + () -> classificationService.deleteClassification("L11010", "")); - Classification rollbackMaster = classificationService.getClassification("L11010", ""); - Classification rollbackA = classificationService.getClassification("L11010", "DOMAIN_A"); - assertEquals(rollbackMaster.getKey(), rollbackA.getKey()); - assertNotEquals(rollbackMaster.getDomain(), rollbackA.getDomain()); - } + Classification rollbackMaster = classificationService.getClassification("L11010", ""); + Classification rollbackA = classificationService.getClassification("L11010", "DOMAIN_A"); + assertEquals(rollbackMaster.getKey(), rollbackA.getKey()); + assertNotEquals(rollbackMaster.getDomain(), rollbackA.getDomain()); + } - @WithAccessId( - userName = "dummy", - groupNames = {"businessadmin"}) - @Test - void testThrowClassificationNotFoundIfClassificationNotExists() { - Assertions.assertThrows(ClassificationNotFoundException.class, () -> - classificationService.deleteClassification("not existing classification key", "")); - } - - @WithAccessId( - userName = "dummy", - groupNames = {"businessadmin"}) - @Test - void testThrowClassificationNotFoundIfClassificationNotExistsInDomain() { - Assertions.assertThrows(ClassificationNotFoundException.class, () -> - classificationService.deleteClassification("L10000", "DOMAIN_B")); - } + @WithAccessId( + userName = "dummy", + groupNames = {"businessadmin"}) + @Test + void testThrowClassificationNotFoundIfClassificationNotExists() { + Assertions.assertThrows( + ClassificationNotFoundException.class, + () -> classificationService.deleteClassification("not existing classification key", "")); + } + @WithAccessId( + userName = "dummy", + groupNames = {"businessadmin"}) + @Test + void testThrowClassificationNotFoundIfClassificationNotExistsInDomain() { + Assertions.assertThrows( + ClassificationNotFoundException.class, + () -> classificationService.deleteClassification("L10000", "DOMAIN_B")); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/classification/GetClassificationAccTest.java b/lib/taskana-core/src/test/java/acceptance/classification/GetClassificationAccTest.java index d4db899c7..e3b1fbaf7 100644 --- a/lib/taskana-core/src/test/java/acceptance/classification/GetClassificationAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/classification/GetClassificationAccTest.java @@ -3,140 +3,143 @@ package acceptance.classification; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import acceptance.AbstractAccTest; import java.util.List; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import acceptance.AbstractAccTest; import pro.taskana.Classification; import pro.taskana.ClassificationService; import pro.taskana.ClassificationSummary; import pro.taskana.exceptions.ClassificationNotFoundException; -/** - * Acceptance test for all "get classification" scenarios. - */ +/** Acceptance test for all "get classification" scenarios. */ class GetClassificationAccTest extends AbstractAccTest { - private ClassificationService classificationService; + private ClassificationService classificationService; - GetClassificationAccTest() { - super(); - classificationService = taskanaEngine.getClassificationService(); - } + GetClassificationAccTest() { + super(); + classificationService = taskanaEngine.getClassificationService(); + } - @Test - void testFindAllClassifications() { - List classificationSummaryList = classificationService.createClassificationQuery() - .list(); - assertNotNull(classificationSummaryList); - } + @Test + void testFindAllClassifications() { + List classificationSummaryList = + classificationService.createClassificationQuery().list(); + assertNotNull(classificationSummaryList); + } - @Test - void testGetOneClassificationByKeyAndDomain() throws ClassificationNotFoundException { - Classification classification = classificationService.getClassification("T6310", "DOMAIN_A"); - assertNotNull(classification); - assertEquals("CLI:100000000000000000000000000000000011", classification.getId()); - assertEquals("", classification.getParentId()); - assertEquals("AUTOMATIC", classification.getCategory()); - assertEquals("TASK", classification.getType()); - assertEquals(true, classification.getIsValidInDomain()); - assertEquals("T-GUK Honorarrechnung erstellen", classification.getName()); - assertEquals(2, classification.getPriority()); - assertEquals("P2D", classification.getServiceLevel()); - assertEquals("point0815", classification.getApplicationEntryPoint()); - assertEquals("VNR", classification.getCustom1()); - assertEquals("custom2", classification.getCustom2()); - assertEquals("custom3", classification.getCustom3()); - assertEquals("custom4", classification.getCustom4()); - assertEquals("custom5", classification.getCustom5()); - assertEquals("custom6", classification.getCustom6()); - assertEquals("custom7", classification.getCustom7()); - assertEquals("custom8", classification.getCustom8()); - } + @Test + void testGetOneClassificationByKeyAndDomain() throws ClassificationNotFoundException { + Classification classification = classificationService.getClassification("T6310", "DOMAIN_A"); + assertNotNull(classification); + assertEquals("CLI:100000000000000000000000000000000011", classification.getId()); + assertEquals("", classification.getParentId()); + assertEquals("AUTOMATIC", classification.getCategory()); + assertEquals("TASK", classification.getType()); + assertEquals(true, classification.getIsValidInDomain()); + assertEquals("T-GUK Honorarrechnung erstellen", classification.getName()); + assertEquals(2, classification.getPriority()); + assertEquals("P2D", classification.getServiceLevel()); + assertEquals("point0815", classification.getApplicationEntryPoint()); + assertEquals("VNR", classification.getCustom1()); + assertEquals("custom2", classification.getCustom2()); + assertEquals("custom3", classification.getCustom3()); + assertEquals("custom4", classification.getCustom4()); + assertEquals("custom5", classification.getCustom5()); + assertEquals("custom6", classification.getCustom6()); + assertEquals("custom7", classification.getCustom7()); + assertEquals("custom8", classification.getCustom8()); + } - @Test - void testGetOneClassificationById() throws ClassificationNotFoundException { - Classification classification = classificationService - .getClassification("CLI:100000000000000000000000000000000011"); - assertNotNull(classification); - assertEquals("T6310", classification.getKey()); - assertEquals("", classification.getParentId()); - assertEquals("AUTOMATIC", classification.getCategory()); - assertEquals("TASK", classification.getType()); - assertEquals("DOMAIN_A", classification.getDomain()); - assertEquals(true, classification.getIsValidInDomain()); - assertEquals("T-GUK Honorarrechnung erstellen", classification.getName()); - assertEquals(2, classification.getPriority()); - assertEquals("P2D", classification.getServiceLevel()); - assertEquals("point0815", classification.getApplicationEntryPoint()); - assertEquals("VNR", classification.getCustom1()); - assertEquals("custom2", classification.getCustom2()); - assertEquals("custom3", classification.getCustom3()); - assertEquals("custom4", classification.getCustom4()); - assertEquals("custom5", classification.getCustom5()); - assertEquals("custom6", classification.getCustom6()); - assertEquals("custom7", classification.getCustom7()); - assertEquals("custom8", classification.getCustom8()); - } + @Test + void testGetOneClassificationById() throws ClassificationNotFoundException { + Classification classification = + classificationService.getClassification("CLI:100000000000000000000000000000000011"); + assertNotNull(classification); + assertEquals("T6310", classification.getKey()); + assertEquals("", classification.getParentId()); + assertEquals("AUTOMATIC", classification.getCategory()); + assertEquals("TASK", classification.getType()); + assertEquals("DOMAIN_A", classification.getDomain()); + assertEquals(true, classification.getIsValidInDomain()); + assertEquals("T-GUK Honorarrechnung erstellen", classification.getName()); + assertEquals(2, classification.getPriority()); + assertEquals("P2D", classification.getServiceLevel()); + assertEquals("point0815", classification.getApplicationEntryPoint()); + assertEquals("VNR", classification.getCustom1()); + assertEquals("custom2", classification.getCustom2()); + assertEquals("custom3", classification.getCustom3()); + assertEquals("custom4", classification.getCustom4()); + assertEquals("custom5", classification.getCustom5()); + assertEquals("custom6", classification.getCustom6()); + assertEquals("custom7", classification.getCustom7()); + assertEquals("custom8", classification.getCustom8()); + } - @Test - void testGetClassificationWithSpecialCharacter() throws ClassificationNotFoundException { - Classification classification = classificationService.getClassification( - "CLI:100000000000000000000000000000000009"); - assertEquals("Zustimmungserklärung", classification.getName()); - } + @Test + void testGetClassificationWithSpecialCharacter() throws ClassificationNotFoundException { + Classification classification = + classificationService.getClassification("CLI:100000000000000000000000000000000009"); + assertEquals("Zustimmungserklärung", classification.getName()); + } - @Test - void testGetClassificationAsSummary() throws ClassificationNotFoundException { - ClassificationSummary classification = classificationService - .getClassification("CLI:100000000000000000000000000000000011").asSummary(); - assertNotNull(classification); - assertEquals("T6310", classification.getKey()); - assertEquals("", classification.getParentId()); - assertEquals("AUTOMATIC", classification.getCategory()); - assertEquals("TASK", classification.getType()); - assertEquals("DOMAIN_A", classification.getDomain()); - assertEquals("T-GUK Honorarrechnung erstellen", classification.getName()); - //assertEquals("Generali Unterstützungskasse Honorar wird fällig", classification.getDescription()); - assertEquals(2, classification.getPriority()); - assertEquals("P2D", classification.getServiceLevel()); - } + @Test + void testGetClassificationAsSummary() throws ClassificationNotFoundException { + ClassificationSummary classification = + classificationService + .getClassification("CLI:100000000000000000000000000000000011") + .asSummary(); + assertNotNull(classification); + assertEquals("T6310", classification.getKey()); + assertEquals("", classification.getParentId()); + assertEquals("AUTOMATIC", classification.getCategory()); + assertEquals("TASK", classification.getType()); + assertEquals("DOMAIN_A", classification.getDomain()); + assertEquals("T-GUK Honorarrechnung erstellen", classification.getName()); + // assertEquals("Generali Unterstützungskasse Honorar wird fällig", + // classification.getDescription()); + assertEquals(2, classification.getPriority()); + assertEquals("P2D", classification.getServiceLevel()); + } - @Test - void testGetOneClassificationByIdFails() { + @Test + void testGetOneClassificationByIdFails() { - Assertions.assertThrows(ClassificationNotFoundException.class, () -> - classificationService.getClassification("CLI:100000000470000000000000000000000011")); - } + Assertions.assertThrows( + ClassificationNotFoundException.class, + () -> classificationService.getClassification("CLI:100000000470000000000000000000000011")); + } - @Test - void testGetClassificationByNullKeyFails() { - Assertions.assertThrows(ClassificationNotFoundException.class, () -> - classificationService.getClassification(null, "")); - } + @Test + void testGetClassificationByNullKeyFails() { + Assertions.assertThrows( + ClassificationNotFoundException.class, + () -> classificationService.getClassification(null, "")); + } - @Test - void testGetClassificationByInvalidKeyAndDomain() { - Assertions.assertThrows(ClassificationNotFoundException.class, () -> - classificationService.getClassification("Key0815", "NOT_EXISTING")); - } + @Test + void testGetClassificationByInvalidKeyAndDomain() { + Assertions.assertThrows( + ClassificationNotFoundException.class, + () -> classificationService.getClassification("Key0815", "NOT_EXISTING")); + } - @Test - void testGetOneClassificationForDomainAndGetClassificationFromMasterDomain() - throws ClassificationNotFoundException { - Classification classification = classificationService.getClassification("L10000", "DOMAIN_B"); - assertNotNull(classification); - assertEquals("", classification.getDomain()); - assertEquals(999L, classification.getPriority()); - } + @Test + void testGetOneClassificationForDomainAndGetClassificationFromMasterDomain() + throws ClassificationNotFoundException { + Classification classification = classificationService.getClassification("L10000", "DOMAIN_B"); + assertNotNull(classification); + assertEquals("", classification.getDomain()); + assertEquals(999L, classification.getPriority()); + } - @Test - void testGetOneClassificationForMasterDomain() throws ClassificationNotFoundException { - Classification classification = classificationService.getClassification("L10000", ""); - assertNotNull(classification); - assertEquals("", classification.getDomain()); - assertEquals(999L, classification.getPriority()); - } + @Test + void testGetOneClassificationForMasterDomain() throws ClassificationNotFoundException { + Classification classification = classificationService.getClassification("L10000", ""); + assertNotNull(classification); + assertEquals("", classification.getDomain()); + assertEquals(999L, classification.getPriority()); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/classification/QueryClassificationAccTest.java b/lib/taskana-core/src/test/java/acceptance/classification/QueryClassificationAccTest.java index a8f9632d6..fc6d7e28d 100644 --- a/lib/taskana-core/src/test/java/acceptance/classification/QueryClassificationAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/classification/QueryClassificationAccTest.java @@ -7,14 +7,13 @@ import static pro.taskana.ClassificationQueryColumnName.NAME; import static pro.taskana.ClassificationQueryColumnName.TYPE; import static pro.taskana.ClassificationQueryColumnName.VALID_IN_DOMAIN; +import acceptance.AbstractAccTest; import java.time.Instant; import java.util.List; import java.util.stream.Collectors; - import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.BaseQuery.SortDirection; import pro.taskana.ClassificationService; import pro.taskana.ClassificationSummary; @@ -26,614 +25,662 @@ import pro.taskana.exceptions.NotAuthorizedException; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "get classification" scenarios. - */ +/** Acceptance test for all "get classification" scenarios. */ @ExtendWith(JAASExtension.class) class QueryClassificationAccTest extends AbstractAccTest { - private static SortDirection asc = SortDirection.ASCENDING; - private static SortDirection desc = SortDirection.DESCENDING; + private static SortDirection asc = SortDirection.ASCENDING; + private static SortDirection desc = SortDirection.DESCENDING; - QueryClassificationAccTest() { - super(); - } + QueryClassificationAccTest() { + super(); + } - @Test - void testQueryClassificationValuesForColumnName() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List columnValueList = classificationService.createClassificationQuery() - .listValues(NAME, null); - assertNotNull(columnValueList); - assertEquals(16, columnValueList.size()); + @Test + void testQueryClassificationValuesForColumnName() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List columnValueList = + classificationService.createClassificationQuery().listValues(NAME, null); + assertNotNull(columnValueList); + assertEquals(16, columnValueList.size()); - columnValueList = classificationService.createClassificationQuery() - .listValues(TYPE, null); - assertNotNull(columnValueList); - assertEquals(2, columnValueList.size()); + columnValueList = classificationService.createClassificationQuery().listValues(TYPE, null); + assertNotNull(columnValueList); + assertEquals(2, columnValueList.size()); - columnValueList = classificationService.createClassificationQuery() - .domainIn("") - .listValues(TYPE, null); - assertNotNull(columnValueList); - assertEquals(2, columnValueList.size()); + columnValueList = + classificationService.createClassificationQuery().domainIn("").listValues(TYPE, null); + assertNotNull(columnValueList); + assertEquals(2, columnValueList.size()); - columnValueList = classificationService.createClassificationQuery() - .domainIn("") - .listValues(CREATED, null); - assertNotNull(columnValueList); + columnValueList = + classificationService.createClassificationQuery().domainIn("").listValues(CREATED, null); + assertNotNull(columnValueList); - columnValueList = classificationService.createClassificationQuery() + columnValueList = + classificationService + .createClassificationQuery() .domainIn("") .validInDomainEquals(false) .listValues(VALID_IN_DOMAIN, null); - assertNotNull(columnValueList); - assertEquals(1, columnValueList.size()); // all are false in "" - } + assertNotNull(columnValueList); + assertEquals(1, columnValueList.size()); // all are false in "" + } - @Test - void testFindClassificationsByCategoryAndDomain() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List classificationSummaryList = classificationService.createClassificationQuery() + @Test + void testFindClassificationsByCategoryAndDomain() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List classificationSummaryList = + classificationService + .createClassificationQuery() .categoryIn("MANUAL") .domainIn("DOMAIN_A") .list(); - assertNotNull(classificationSummaryList); - assertEquals(2, classificationSummaryList.size()); - } + assertNotNull(classificationSummaryList); + assertEquals(2, classificationSummaryList.size()); + } - @Test - void testGetOneClassificationForMultipleDomains() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List classifications = classificationService.createClassificationQuery() + @Test + void testGetOneClassificationForMultipleDomains() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List classifications = + classificationService + .createClassificationQuery() .keyIn("L10000") .domainIn("DOMAIN_A", "DOMAIN_B", "") .list(); - assertNotNull(classifications); - assertEquals(2, classifications.size()); - } + assertNotNull(classifications); + assertEquals(2, classifications.size()); + } - @Test - void testGetClassificationsForTypeAndParent() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List classifications = classificationService.createClassificationQuery() + @Test + void testGetClassificationsForTypeAndParent() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List classifications = + classificationService + .createClassificationQuery() .typeIn("TASK", "DOCUMENT") .parentIdIn("") .list(); - assertNotNull(classifications); - assertEquals(28, classifications.size()); + assertNotNull(classifications); + assertEquals(28, classifications.size()); - List documentTypes = classifications.stream() + List documentTypes = + classifications.stream() .filter(c -> c.getType().equals("DOCUMENT")) - .collect( - Collectors.toList()); - assertEquals(2, documentTypes.size()); + .collect(Collectors.toList()); + assertEquals(2, documentTypes.size()); - List taskTypes = classifications.stream() + List taskTypes = + classifications.stream() .filter(c -> c.getType().equals("TASK")) - .collect( - Collectors.toList()); - assertEquals(26, taskTypes.size()); - } + .collect(Collectors.toList()); + assertEquals(26, taskTypes.size()); + } - @Test - void testGetClassificationsForKeyAndCategories() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List classifications = classificationService.createClassificationQuery() + @Test + void testGetClassificationsForKeyAndCategories() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List classifications = + classificationService + .createClassificationQuery() .keyIn("T2100", "L10000") .categoryIn("EXTERNAL", "MANUAL") .list(); - assertNotNull(classifications); - assertEquals(5, classifications.size()); + assertNotNull(classifications); + assertEquals(5, classifications.size()); - List externCategory = classifications.stream() + List externCategory = + classifications.stream() .filter(c -> c.getCategory().equals("EXTERNAL")) - .collect( - Collectors.toList()); - assertEquals(2, externCategory.size()); + .collect(Collectors.toList()); + assertEquals(2, externCategory.size()); - List manualCategory = classifications.stream() + List manualCategory = + classifications.stream() .filter(c -> c.getCategory().equals("MANUAL")) - .collect( - Collectors.toList()); - assertEquals(3, manualCategory.size()); - } + .collect(Collectors.toList()); + assertEquals(3, manualCategory.size()); + } - @Test - void testGetClassificationsWithParentId() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List classifications = classificationService.createClassificationQuery() + @Test + void testGetClassificationsWithParentId() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List classifications = + classificationService + .createClassificationQuery() .keyIn("A12", "A13") .categoryIn("EXTERNAL", "MANUAL") .parentIdIn("CLI:100000000000000000000000000000000014") .list(); - assertNotNull(classifications); - assertEquals(1, classifications.size()); + assertNotNull(classifications); + assertEquals(1, classifications.size()); - classifications = classificationService.createClassificationQuery() + classifications = + classificationService + .createClassificationQuery() .keyIn("A12", "A13") .categoryIn("EXTERNAL", "MANUAL", "AUTOMATIC") - .parentIdIn("CLI:100000000000000000000000000000000014", "CLI:100000000000000000000000000000000010", + .parentIdIn( + "CLI:100000000000000000000000000000000014", + "CLI:100000000000000000000000000000000010", "CLI:100000000000000000000000000000000011") .domainIn("DOMAIN_A") .list(); - assertNotNull(classifications); - assertEquals(2, classifications.size()); - } + assertNotNull(classifications); + assertEquals(2, classifications.size()); + } - @Test - void testGetClassificationsWithParentKey() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List classifications = classificationService.createClassificationQuery() + @Test + void testGetClassificationsWithParentKey() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List classifications = + classificationService + .createClassificationQuery() .keyIn("A12", "A13") .categoryIn("EXTERNAL", "MANUAL") .parentKeyIn("L10000") .list(); - assertNotNull(classifications); - assertEquals(2, classifications.size()); + assertNotNull(classifications); + assertEquals(2, classifications.size()); - classifications = classificationService.createClassificationQuery() + classifications = + classificationService + .createClassificationQuery() .keyIn("A12", "A13") .categoryIn("EXTERNAL", "MANUAL", "AUTOMATIC") .parentKeyIn("L10000", "T2100", "T6310") .domainIn("DOMAIN_A") .list(); - assertNotNull(classifications); - assertEquals(2, classifications.size()); - } + assertNotNull(classifications); + assertEquals(2, classifications.size()); + } - @Test - void testGetClassificationsWithCustom1() throws InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List classifications = classificationService.createClassificationQuery() + @Test + void testGetClassificationsWithCustom1() throws InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List classifications = + classificationService + .createClassificationQuery() .customAttributeIn("1", "VNR,RVNR,KOLVNR", "VNR") .domainIn("DOMAIN_A") .list(); - assertNotNull(classifications); - assertEquals(14, classifications.size()); - } + assertNotNull(classifications); + assertEquals(14, classifications.size()); + } - @Test - void testGetClassificationsWithCustom1Like() throws InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List classifications = classificationService.createClassificationQuery() + @Test + void testGetClassificationsWithCustom1Like() throws InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List classifications = + classificationService + .createClassificationQuery() .customAttributeLike("1", "%RVNR%") .domainIn("DOMAIN_A") .typeIn("TASK") .list(); - assertNotNull(classifications); - assertEquals(13, classifications.size()); - } + assertNotNull(classifications); + assertEquals(13, classifications.size()); + } - @Test - void testGetClassificationsWithParentAndCustom2() throws InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List classifications = classificationService.createClassificationQuery() + @Test + void testGetClassificationsWithParentAndCustom2() throws InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List classifications = + classificationService + .createClassificationQuery() .parentIdIn("CLI:100000000000000000000000000000000004") .customAttributeIn("2", "TEXT_1", "TEXT_2") .list(); - // zwei tests - assertNotNull(classifications); - assertEquals(3, classifications.size()); - } + // zwei tests + assertNotNull(classifications); + assertEquals(3, classifications.size()); + } - @Test - void testFindClassificationsByCreatedTimestamp() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List classificationSummaryList = classificationService.createClassificationQuery() + @Test + void testFindClassificationsByCreatedTimestamp() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List classificationSummaryList = + classificationService + .createClassificationQuery() .domainIn("DOMAIN_A") .createdWithin(todaysInterval()) .list(); - assertNotNull(classificationSummaryList); - assertEquals(17, classificationSummaryList.size()); - } + assertNotNull(classificationSummaryList); + assertEquals(17, classificationSummaryList.size()); + } - @Test - void testFindClassificationsByPriorityAndValidInDomain() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List list = classificationService.createClassificationQuery() + @Test + void testFindClassificationsByPriorityAndValidInDomain() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List list = + classificationService + .createClassificationQuery() .validInDomainEquals(Boolean.TRUE) .priorityIn(1, 2, 3) .list(); - assertEquals(15, list.size()); + assertEquals(15, list.size()); + } - } - - @WithAccessId( - userName = "businessadmin") - @Test - void testFindClassificationByModifiedWithin() - throws ClassificationNotFoundException, NotAuthorizedException, ConcurrencyException, InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - String clId = "CLI:200000000000000000000000000000000015"; - classificationService.updateClassification(classificationService.getClassification(clId)); - List list = classificationService.createClassificationQuery() - .modifiedWithin(new TimeInterval( - classificationService.getClassification(clId).getModified(), - Instant.now())) + @WithAccessId(userName = "businessadmin") + @Test + void testFindClassificationByModifiedWithin() + throws ClassificationNotFoundException, NotAuthorizedException, ConcurrencyException, + InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + String clId = "CLI:200000000000000000000000000000000015"; + classificationService.updateClassification(classificationService.getClassification(clId)); + List list = + classificationService + .createClassificationQuery() + .modifiedWithin( + new TimeInterval( + classificationService.getClassification(clId).getModified(), Instant.now())) .list(); - assertEquals(1, list.size()); - assertEquals(clId, list.get(0).getId()); - } + assertEquals(1, list.size()); + assertEquals(clId, list.get(0).getId()); + } - @Test - void testQueryForNameLike() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() - .nameLike("Dynamik%") - .list(); - assertEquals(8, results.size()); - } + @Test + void testQueryForNameLike() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService.createClassificationQuery().nameLike("Dynamik%").list(); + assertEquals(8, results.size()); + } - @Test - void testQueryForNameIn() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() + @Test + void testQueryForNameIn() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService + .createClassificationQuery() .nameIn("Widerruf", "OLD-Leistungsfall") .list(); - assertEquals(6, results.size()); - } + assertEquals(6, results.size()); + } - @Test - void testQueryForDescriptionLike() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() - .descriptionLike("Widerruf%") - .list(); - assertEquals(9, results.size()); - } + @Test + void testQueryForDescriptionLike() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService.createClassificationQuery().descriptionLike("Widerruf%").list(); + assertEquals(9, results.size()); + } - @Test - void testQueryForServiceLevelIn() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() - .serviceLevelIn("P2D") - .list(); - assertEquals(5, results.size()); - } + @Test + void testQueryForServiceLevelIn() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService.createClassificationQuery().serviceLevelIn("P2D").list(); + assertEquals(5, results.size()); + } - @Test - void testQueryForServiceLevelLike() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() - .serviceLevelLike("PT%") - .list(); - assertEquals(0, results.size()); - } + @Test + void testQueryForServiceLevelLike() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService.createClassificationQuery().serviceLevelLike("PT%").list(); + assertEquals(0, results.size()); + } - @Test - void testQueryForApplicationEntryPointIn() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() + @Test + void testQueryForApplicationEntryPointIn() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService + .createClassificationQuery() .applicationEntryPointIn("specialPoint", "point0815") .list(); - assertEquals(3, results.size()); - } + assertEquals(3, results.size()); + } - @Test - void testQueryForApplicationEntryPointLike() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() + @Test + void testQueryForApplicationEntryPointLike() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService + .createClassificationQuery() .applicationEntryPointLike("point%") .list(); - assertEquals(3, results.size()); - } + assertEquals(3, results.size()); + } - @Test - void testQueryForCustom1In() throws InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() + @Test + void testQueryForCustom1In() throws InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService + .createClassificationQuery() .customAttributeIn("1", "VNR,RVNR,KOLVNR, ANR", "VNR") .list(); - assertEquals(17, results.size()); - } + assertEquals(17, results.size()); + } - @Test - void testQueryForCustom2In() throws InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() + @Test + void testQueryForCustom2In() throws InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService + .createClassificationQuery() .customAttributeIn("2", "CUSTOM2", "custom2") .list(); - assertEquals(3, results.size()); - } + assertEquals(3, results.size()); + } - @Test - void testQueryForCustom3In() throws InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() + @Test + void testQueryForCustom3In() throws InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService + .createClassificationQuery() .customAttributeIn("3", "Custom3", "custom3") .list(); - assertEquals(3, results.size()); - } + assertEquals(3, results.size()); + } - @Test - void testQueryForCustom4In() throws InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() - .customAttributeIn("4", "custom4") - .list(); - assertEquals(3, results.size()); - } + @Test + void testQueryForCustom4In() throws InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService.createClassificationQuery().customAttributeIn("4", "custom4").list(); + assertEquals(3, results.size()); + } - @Test - void testQueryForCustom5In() throws InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() - .customAttributeIn("5", "custom5") - .list(); - assertEquals(3, results.size()); - } + @Test + void testQueryForCustom5In() throws InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService.createClassificationQuery().customAttributeIn("5", "custom5").list(); + assertEquals(3, results.size()); + } - @Test - void testQueryForCustom6In() throws InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() - .customAttributeIn("6", "custom6") - .list(); - assertEquals(3, results.size()); - } + @Test + void testQueryForCustom6In() throws InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService.createClassificationQuery().customAttributeIn("6", "custom6").list(); + assertEquals(3, results.size()); + } - @Test - void testQueryForCustom7In() throws InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() + @Test + void testQueryForCustom7In() throws InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService + .createClassificationQuery() .customAttributeIn("7", "custom7", "custom_7") .list(); - assertEquals(3, results.size()); - } + assertEquals(3, results.size()); + } - @Test - void testQueryForCustom8In() throws InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() + @Test + void testQueryForCustom8In() throws InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService + .createClassificationQuery() .customAttributeIn("8", "custom_8", "custom8") .list(); - assertEquals(3, results.size()); - } + assertEquals(3, results.size()); + } - @Test - void testQueryForCustom2Like() throws InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() - .customAttributeLike("2", "cus%") - .list(); - assertEquals(4, results.size()); - } + @Test + void testQueryForCustom2Like() throws InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService.createClassificationQuery().customAttributeLike("2", "cus%").list(); + assertEquals(4, results.size()); + } - @Test - void testQueryForCustom3Like() throws InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() - .customAttributeLike("3", "cus%") - .list(); - assertEquals(4, results.size()); - } + @Test + void testQueryForCustom3Like() throws InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService.createClassificationQuery().customAttributeLike("3", "cus%").list(); + assertEquals(4, results.size()); + } - @Test - void testQueryForCustom4Like() throws InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() - .customAttributeLike("4", "cus%") - .list(); - assertEquals(4, results.size()); - } + @Test + void testQueryForCustom4Like() throws InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService.createClassificationQuery().customAttributeLike("4", "cus%").list(); + assertEquals(4, results.size()); + } - @Test - void testQueryForCustom5Like() throws InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() - .customAttributeLike("5", "cus%") - .list(); - assertEquals(4, results.size()); - } + @Test + void testQueryForCustom5Like() throws InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService.createClassificationQuery().customAttributeLike("5", "cus%").list(); + assertEquals(4, results.size()); + } - @Test - void testQueryForCustom6Like() throws InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() - .customAttributeLike("6", "cus%") - .list(); - assertEquals(4, results.size()); - } + @Test + void testQueryForCustom6Like() throws InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService.createClassificationQuery().customAttributeLike("6", "cus%").list(); + assertEquals(4, results.size()); + } - @Test - void testQueryForCustom7Like() throws InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() - .customAttributeLike("7", "cus%") - .list(); - assertEquals(4, results.size()); - } + @Test + void testQueryForCustom7Like() throws InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService.createClassificationQuery().customAttributeLike("7", "cus%").list(); + assertEquals(4, results.size()); + } - @Test - void testQueryForCustom8Like() throws InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() - .customAttributeLike("8", "cus%") - .list(); - assertEquals(4, results.size()); - } + @Test + void testQueryForCustom8Like() throws InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService.createClassificationQuery().customAttributeLike("8", "cus%").list(); + assertEquals(4, results.size()); + } - @Test - void testQueryForOrderByKeyAsc() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() - .orderByKey(asc) - .list(); - assertEquals("A12", results.get(0).getKey()); - } + @Test + void testQueryForOrderByKeyAsc() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService.createClassificationQuery().orderByKey(asc).list(); + assertEquals("A12", results.get(0).getKey()); + } - @Test - void testQueryForOrderByParentIdDesc() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() + @Test + void testQueryForOrderByParentIdDesc() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService + .createClassificationQuery() .orderByDomain(asc) .orderByParentId(desc) .list(); - assertEquals("CLI:000000000000000000000000000000000020", results.get(0).getParentId()); - } + assertEquals("CLI:000000000000000000000000000000000020", results.get(0).getParentId()); + } - @Test - void testQueryForOrderByParentKeyDesc() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() - .orderByParentKey(desc) - .list(); - assertEquals("T6310", results.get(0).getParentKey()); - } + @Test + void testQueryForOrderByParentKeyDesc() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService.createClassificationQuery().orderByParentKey(desc).list(); + assertEquals("T6310", results.get(0).getParentKey()); + } - @Test - void testQueryForOrderByCategoryDesc() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() - .orderByCategory(desc) - .list(); - assertEquals("MANUAL", results.get(0).getCategory()); - } + @Test + void testQueryForOrderByCategoryDesc() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService.createClassificationQuery().orderByCategory(desc).list(); + assertEquals("MANUAL", results.get(0).getCategory()); + } - @Test - void testQueryForOrderByDomainAsc() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() - .orderByDomain(asc) - .list(); - assertEquals("", results.get(0).getDomain()); - } + @Test + void testQueryForOrderByDomainAsc() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService.createClassificationQuery().orderByDomain(asc).list(); + assertEquals("", results.get(0).getDomain()); + } - @Test - void testQueryForOrderByPriorityDesc() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() - .orderByPriority(desc) - .list(); - assertEquals(999, results.get(0).getPriority()); - } + @Test + void testQueryForOrderByPriorityDesc() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService.createClassificationQuery().orderByPriority(desc).list(); + assertEquals(999, results.get(0).getPriority()); + } - @Test - void testQueryForOrderByNameAsc() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() - .orderByName(asc) - .list(); - assertEquals("Beratungsprotokoll", results.get(0).getName()); - } + @Test + void testQueryForOrderByNameAsc() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService.createClassificationQuery().orderByName(asc).list(); + assertEquals("Beratungsprotokoll", results.get(0).getName()); + } - @Test - void testQueryForOrderByServiceLevelDesc() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() - .orderByServiceLevel(desc) - .list(); - assertEquals("P8D", results.get(0).getServiceLevel()); - } + @Test + void testQueryForOrderByServiceLevelDesc() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService.createClassificationQuery().orderByServiceLevel(desc).list(); + assertEquals("P8D", results.get(0).getServiceLevel()); + } - @Test - void testQueryForOrderByApplicationEntryPointAsc() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() + @Test + void testQueryForOrderByApplicationEntryPointAsc() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService + .createClassificationQuery() .orderByApplicationEntryPoint(asc) .orderByName(asc) .list(); - assertEquals("CLI:100000000000000000000000000000000007", results.get(results.size() - 6).getId()); - } + assertEquals( + "CLI:100000000000000000000000000000000007", results.get(results.size() - 6).getId()); + } - @Test - void testQueryForOrderByParentKeyAsc() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() + @Test + void testQueryForOrderByParentKeyAsc() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService + .createClassificationQuery() .orderByParentKey(asc) .orderByDomain(asc) .list(); - assertEquals("CLI:000000000000000000000000000000000019", results.get(results.size() - 5).getId()); - } + assertEquals( + "CLI:000000000000000000000000000000000019", results.get(results.size() - 5).getId()); + } - @Test - void testQueryForOrderByCustom1Desc() throws InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() + @Test + void testQueryForOrderByCustom1Desc() throws InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService + .createClassificationQuery() .orderByCustomAttribute("1", desc) .orderByDomain(asc) .orderByServiceLevel(desc) .list(); - assertEquals("CLI:000000000000000000000000000000000002", results.get(0).getId()); - } + assertEquals("CLI:000000000000000000000000000000000002", results.get(0).getId()); + } - @Test - void testQueryForOrderByCustom2Asc() throws InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() + @Test + void testQueryForOrderByCustom2Asc() throws InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService + .createClassificationQuery() .orderByCustomAttribute("2", asc) .orderByName(asc) .orderByParentKey(asc) .orderByDomain(asc) .list(); - assertEquals("CLI:000000000000000000000000000000000002", results.get(0).getId()); - } + assertEquals("CLI:000000000000000000000000000000000002", results.get(0).getId()); + } - @Test - void testQueryForOrderByCustom3Desc() throws InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() + @Test + void testQueryForOrderByCustom3Desc() throws InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService + .createClassificationQuery() .orderByCustomAttribute("3", desc) .orderByName(asc) .list(); - assertEquals("CLI:100000000000000000000000000000000014", results.get(0).getId()); - } + assertEquals("CLI:100000000000000000000000000000000014", results.get(0).getId()); + } - @Test - void testQueryForOrderByCustom4Asc() throws InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() + @Test + void testQueryForOrderByCustom4Asc() throws InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService + .createClassificationQuery() .orderByCustomAttribute("4", asc) .orderByName(asc) .list(); - assertEquals("CLI:100000000000000000000000000000000010", results.get(results.size() - 5).getId()); - } + assertEquals( + "CLI:100000000000000000000000000000000010", results.get(results.size() - 5).getId()); + } - @Test - void testQueryForOrderByCustom5Desc() throws InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() + @Test + void testQueryForOrderByCustom5Desc() throws InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService + .createClassificationQuery() .orderByCustomAttribute("5", desc) .orderByName(asc) .list(); - assertEquals("CLI:100000000000000000000000000000000011", results.get(0).getId()); - } + assertEquals("CLI:100000000000000000000000000000000011", results.get(0).getId()); + } - @Test - void testQueryForOrderByCustom6Asc() throws InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() + @Test + void testQueryForOrderByCustom6Asc() throws InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService + .createClassificationQuery() .orderByCustomAttribute("6", asc) .orderByName(asc) .list(); - assertEquals("CLI:100000000000000000000000000000000010", results.get(results.size() - 4).getId()); - } + assertEquals( + "CLI:100000000000000000000000000000000010", results.get(results.size() - 4).getId()); + } - @Test - void testQueryForOrderByCustom7Desc() throws InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() + @Test + void testQueryForOrderByCustom7Desc() throws InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService + .createClassificationQuery() .orderByCustomAttribute("7", desc) .orderByName(asc) .list(); - assertEquals("CLI:100000000000000000000000000000000011", results.get(0).getId()); - } + assertEquals("CLI:100000000000000000000000000000000011", results.get(0).getId()); + } - @Test - void testQueryForOrderByCustom8Asc() throws InvalidArgumentException { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() + @Test + void testQueryForOrderByCustom8Asc() throws InvalidArgumentException { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService + .createClassificationQuery() .orderByCustomAttribute("8", asc) .orderByName(asc) .list(); - assertEquals("CLI:100000000000000000000000000000000010", results.get(results.size() - 4).getId()); - } + assertEquals( + "CLI:100000000000000000000000000000000010", results.get(results.size() - 4).getId()); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/classification/QueryClassificationWithPaginationAccTest.java b/lib/taskana-core/src/test/java/acceptance/classification/QueryClassificationWithPaginationAccTest.java index 918012873..eaa129ffb 100644 --- a/lib/taskana-core/src/test/java/acceptance/classification/QueryClassificationWithPaginationAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/classification/QueryClassificationWithPaginationAccTest.java @@ -3,162 +3,167 @@ package acceptance.classification; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; +import acceptance.AbstractAccTest; import java.util.List; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.ClassificationService; import pro.taskana.ClassificationSummary; import pro.taskana.exceptions.TaskanaRuntimeException; import pro.taskana.security.JAASExtension; -/** - * Acceptance test for all "query classifications with pagination" scenarios. - */ +/** Acceptance test for all "query classifications with pagination" scenarios. */ @ExtendWith(JAASExtension.class) class QueryClassificationWithPaginationAccTest extends AbstractAccTest { - QueryClassificationWithPaginationAccTest() { - super(); - } + QueryClassificationWithPaginationAccTest() { + super(); + } - @Test - void testGetFirstPageOfClassificationQueryWithOffset() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() - .domainIn("DOMAIN_A") - .list(0, 5); - assertThat(results.size(), equalTo(5)); - } + @Test + void testGetFirstPageOfClassificationQueryWithOffset() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService.createClassificationQuery().domainIn("DOMAIN_A").list(0, 5); + assertThat(results.size(), equalTo(5)); + } - @Test - void testGetSecondPageOfClassificationQueryWithOffset() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List results = classificationService.createClassificationQuery() - .domainIn("DOMAIN_A") - .list(5, 5); - assertThat(results.size(), equalTo(5)); - } + @Test + void testGetSecondPageOfClassificationQueryWithOffset() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List results = + classificationService.createClassificationQuery().domainIn("DOMAIN_A").list(5, 5); + assertThat(results.size(), equalTo(5)); + } - @Test - void testListOffsetAndLimitOutOfBounds() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); + @Test + void testListOffsetAndLimitOutOfBounds() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); - // both will be 0, working - List results = classificationService.createClassificationQuery() - .domainIn("DOMAIN_A") - .list(-1, -3); - assertThat(results.size(), equalTo(0)); + // both will be 0, working + List results = + classificationService.createClassificationQuery().domainIn("DOMAIN_A").list(-1, -3); + assertThat(results.size(), equalTo(0)); - // limit will be 0 - results = classificationService.createClassificationQuery() - .domainIn("DOMAIN_A") - .list(1, -3); - assertThat(results.size(), equalTo(0)); + // limit will be 0 + results = classificationService.createClassificationQuery().domainIn("DOMAIN_A").list(1, -3); + assertThat(results.size(), equalTo(0)); - // offset will be 0 - results = classificationService.createClassificationQuery() - .domainIn("DOMAIN_A") - .list(-1, 3); - assertThat(results.size(), equalTo(3)); - } + // offset will be 0 + results = classificationService.createClassificationQuery().domainIn("DOMAIN_A").list(-1, 3); + assertThat(results.size(), equalTo(3)); + } - @Test - void testPaginationWithPages() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); + @Test + void testPaginationWithPages() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); - // Getting full page - int pageNumber = 1; - int pageSize = 4; - List results = classificationService.createClassificationQuery() + // Getting full page + int pageNumber = 1; + int pageSize = 4; + List results = + classificationService + .createClassificationQuery() .domainIn("DOMAIN_A") .listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(4)); + assertThat(results.size(), equalTo(4)); - // Getting full page - pageNumber = 3; - pageSize = 4; - results = classificationService.createClassificationQuery() + // Getting full page + pageNumber = 3; + pageSize = 4; + results = + classificationService + .createClassificationQuery() .domainIn("DOMAIN_A") .listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(4)); + assertThat(results.size(), equalTo(4)); - // Getting last results on 1 big page - pageNumber = 1; - pageSize = 100; - results = classificationService.createClassificationQuery() + // Getting last results on 1 big page + pageNumber = 1; + pageSize = 100; + results = + classificationService + .createClassificationQuery() .domainIn("DOMAIN_A") .listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(17)); + assertThat(results.size(), equalTo(17)); - // Getting last results on multiple pages - pageNumber = 2; - pageSize = 10; - results = classificationService.createClassificationQuery() + // Getting last results on multiple pages + pageNumber = 2; + pageSize = 10; + results = + classificationService + .createClassificationQuery() .domainIn("DOMAIN_A") .listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(7)); - } + assertThat(results.size(), equalTo(7)); + } - @Test - void testPaginationNullAndNegativeLimitsIgnoring() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); + @Test + void testPaginationNullAndNegativeLimitsIgnoring() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); - // 0 limit/size = 0 results - int pageNumber = 1; - int pageSize = 0; - List results = classificationService.createClassificationQuery() + // 0 limit/size = 0 results + int pageNumber = 1; + int pageSize = 0; + List results = + classificationService + .createClassificationQuery() .domainIn("DOMAIN_A") .listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(0)); + assertThat(results.size(), equalTo(0)); - // Negative will be 0 = all results - pageNumber = 1; - pageSize = -1; - results = classificationService.createClassificationQuery() + // Negative will be 0 = all results + pageNumber = 1; + pageSize = -1; + results = + classificationService + .createClassificationQuery() .domainIn("DOMAIN_A") .listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(0)); + assertThat(results.size(), equalTo(0)); - // Negative page = first page - pageNumber = -1; - pageSize = 10; - results = classificationService.createClassificationQuery() + // Negative page = first page + pageNumber = -1; + pageSize = 10; + results = + classificationService + .createClassificationQuery() .domainIn("DOMAIN_A") .listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(10)); - } + assertThat(results.size(), equalTo(10)); + } - /** - * Testcase only for DB2 users, because H2 doesn´t throw a Exception when the offset is set to high.
- * Using DB2 should throw a unchecked RuntimeException for a offset which is out of bounds. - */ - @Disabled - @Test - void testPaginationThrowingExceptionWhenPageOutOfBounds() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); + /** + * Testcase only for DB2 users, because H2 doesn´t throw a Exception when the offset is set to + * high.
+ * Using DB2 should throw a unchecked RuntimeException for a offset which is out of bounds. + */ + @Disabled + @Test + void testPaginationThrowingExceptionWhenPageOutOfBounds() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); - // entrypoint set outside result amount - int pageNumber = 5; - int pageSize = 10; + // entrypoint set outside result amount + int pageNumber = 5; + int pageSize = 10; - Assertions.assertThrows(TaskanaRuntimeException.class, () -> - classificationService.createClassificationQuery() + Assertions.assertThrows( + TaskanaRuntimeException.class, + () -> + classificationService + .createClassificationQuery() .domainIn("DOMAIN_A") .listPage(pageNumber, pageSize)); - } - - @Test - void testCountOfClassificationsQuery() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - long count = classificationService.createClassificationQuery() - .domainIn("DOMAIN_A") - .count(); - assertThat(count, equalTo(17L)); - } + } + @Test + void testCountOfClassificationsQuery() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + long count = classificationService.createClassificationQuery().domainIn("DOMAIN_A").count(); + assertThat(count, equalTo(17L)); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/classification/UpdateClassificationAccTest.java b/lib/taskana-core/src/test/java/acceptance/classification/UpdateClassificationAccTest.java index 220d2f850..ea1237fee 100644 --- a/lib/taskana-core/src/test/java/acceptance/classification/UpdateClassificationAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/classification/UpdateClassificationAccTest.java @@ -7,18 +7,17 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import acceptance.AbstractAccTest; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.Classification; import pro.taskana.ClassificationService; import pro.taskana.Task; @@ -37,293 +36,330 @@ import pro.taskana.jobs.JobRunner; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "update classification" scenarios. - */ +/** Acceptance test for all "update classification" scenarios. */ @ExtendWith(JAASExtension.class) public class UpdateClassificationAccTest extends AbstractAccTest { - private ClassificationService classificationService; + private ClassificationService classificationService; - public UpdateClassificationAccTest() { - super(); - classificationService = taskanaEngine.getClassificationService(); - } + public UpdateClassificationAccTest() { + super(); + classificationService = taskanaEngine.getClassificationService(); + } - @WithAccessId( - userName = "dummy", - groupNames = {"businessadmin"}) - @Test - public void testUpdateClassification() - throws ClassificationNotFoundException, NotAuthorizedException, ConcurrencyException, - InvalidArgumentException { - String newName = "updated Name"; - String newEntryPoint = "updated EntryPoint"; - Classification classification = classificationService.getClassification("T2100", "DOMAIN_A"); - Instant createdBefore = classification.getCreated(); - Instant modifiedBefore = classification.getModified(); + @WithAccessId( + userName = "dummy", + groupNames = {"businessadmin"}) + @Test + public void testUpdateClassification() + throws ClassificationNotFoundException, NotAuthorizedException, ConcurrencyException, + InvalidArgumentException { + String newName = "updated Name"; + String newEntryPoint = "updated EntryPoint"; + Classification classification = classificationService.getClassification("T2100", "DOMAIN_A"); + Instant createdBefore = classification.getCreated(); + Instant modifiedBefore = classification.getModified(); - classification.setApplicationEntryPoint(newEntryPoint); - classification.setCategory("PROCESS"); - classification.setCustom1("newCustom1"); - classification.setCustom2("newCustom2"); - classification.setCustom3("newCustom3"); - classification.setCustom4("newCustom4"); - classification.setCustom5("newCustom5"); - classification.setCustom6("newCustom6"); - classification.setCustom7("newCustom7"); - classification.setCustom8("newCustom8"); - classification.setDescription("newDescription"); - classification.setIsValidInDomain(false); - classification.setName(newName); - classification.setParentId("CLI:100000000000000000000000000000000004"); - classification.setParentKey("L11010"); - classification.setPriority(1000); - classification.setServiceLevel("P3D"); + classification.setApplicationEntryPoint(newEntryPoint); + classification.setCategory("PROCESS"); + classification.setCustom1("newCustom1"); + classification.setCustom2("newCustom2"); + classification.setCustom3("newCustom3"); + classification.setCustom4("newCustom4"); + classification.setCustom5("newCustom5"); + classification.setCustom6("newCustom6"); + classification.setCustom7("newCustom7"); + classification.setCustom8("newCustom8"); + classification.setDescription("newDescription"); + classification.setIsValidInDomain(false); + classification.setName(newName); + classification.setParentId("CLI:100000000000000000000000000000000004"); + classification.setParentKey("L11010"); + classification.setPriority(1000); + classification.setServiceLevel("P3D"); - classificationService.updateClassification(classification); + classificationService.updateClassification(classification); - // Get and check the new value - Classification updatedClassification = classificationService.getClassification("T2100", "DOMAIN_A"); - assertNotNull(updatedClassification); - assertThat(updatedClassification.getName(), equalTo(newName)); - assertThat(updatedClassification.getApplicationEntryPoint(), equalTo(newEntryPoint)); - assertThat(updatedClassification.getCreated(), equalTo(createdBefore)); - assertTrue(modifiedBefore.isBefore(updatedClassification.getModified())); - } + // Get and check the new value + Classification updatedClassification = + classificationService.getClassification("T2100", "DOMAIN_A"); + assertNotNull(updatedClassification); + assertThat(updatedClassification.getName(), equalTo(newName)); + assertThat(updatedClassification.getApplicationEntryPoint(), equalTo(newEntryPoint)); + assertThat(updatedClassification.getCreated(), equalTo(createdBefore)); + assertTrue(modifiedBefore.isBefore(updatedClassification.getModified())); + } - @Test - public void testUpdateClassificationFails() - throws ClassificationNotFoundException, ConcurrencyException, - InvalidArgumentException { - String newName = "updated Name"; - String newEntryPoint = "updated EntryPoint"; - Classification classification = classificationService.getClassification("T2100", "DOMAIN_A"); + @Test + public void testUpdateClassificationFails() + throws ClassificationNotFoundException, ConcurrencyException, InvalidArgumentException { + String newName = "updated Name"; + String newEntryPoint = "updated EntryPoint"; + Classification classification = classificationService.getClassification("T2100", "DOMAIN_A"); - classification.setApplicationEntryPoint(newEntryPoint); - classification.setCategory("PROCESS"); - classification.setCustom1("newCustom1"); - classification.setCustom2("newCustom2"); - classification.setCustom3("newCustom3"); - classification.setCustom4("newCustom4"); - classification.setCustom5("newCustom5"); - classification.setCustom6("newCustom6"); - classification.setCustom7("newCustom7"); - classification.setCustom8("newCustom8"); - classification.setDescription("newDescription"); - classification.setIsValidInDomain(false); - classification.setName(newName); - classification.setParentId("T2000"); - classification.setPriority(1000); - classification.setServiceLevel("P2DT3H4M"); + classification.setApplicationEntryPoint(newEntryPoint); + classification.setCategory("PROCESS"); + classification.setCustom1("newCustom1"); + classification.setCustom2("newCustom2"); + classification.setCustom3("newCustom3"); + classification.setCustom4("newCustom4"); + classification.setCustom5("newCustom5"); + classification.setCustom6("newCustom6"); + classification.setCustom7("newCustom7"); + classification.setCustom8("newCustom8"); + classification.setDescription("newDescription"); + classification.setIsValidInDomain(false); + classification.setName(newName); + classification.setParentId("T2000"); + classification.setPriority(1000); + classification.setServiceLevel("P2DT3H4M"); - Assertions.assertThrows(NotAuthorizedException.class, () -> - classificationService.updateClassification(classification)); - } + Assertions.assertThrows( + NotAuthorizedException.class, + () -> classificationService.updateClassification(classification)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "businessadmin"}) - @Test - public void testUpdateTaskOnClassificationKeyCategoryChange() - throws Exception { - setupTest(); - TaskImpl beforeTask = (TaskImpl) taskanaEngine.getTaskService() - .getTask("TKI:000000000000000000000000000000000000"); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "businessadmin"}) + @Test + public void testUpdateTaskOnClassificationKeyCategoryChange() throws Exception { + setupTest(); + TaskImpl beforeTask = + (TaskImpl) + taskanaEngine.getTaskService().getTask("TKI:000000000000000000000000000000000000"); - Classification classification = classificationService - .getClassification(beforeTask.getClassificationSummary().getKey(), beforeTask.getDomain()); - classification.setCategory("PROCESS"); - Instant createdBefore = classification.getCreated(); - Instant modifiedBefore = classification.getModified(); - classification = taskanaEngine.getClassificationService().updateClassification(classification); + Classification classification = + classificationService.getClassification( + beforeTask.getClassificationSummary().getKey(), beforeTask.getDomain()); + classification.setCategory("PROCESS"); + Instant createdBefore = classification.getCreated(); + Instant modifiedBefore = classification.getModified(); + classification = taskanaEngine.getClassificationService().updateClassification(classification); - TaskImpl updatedTask = (TaskImpl) taskanaEngine.getTaskService() - .getTask("TKI:000000000000000000000000000000000000"); - assertThat(updatedTask.getClassificationCategory(), not(equalTo(beforeTask.getClassificationCategory()))); - assertThat(updatedTask.getClassificationSummary().getCategory(), - not(equalTo(beforeTask.getClassificationSummary().getCategory()))); - assertThat(updatedTask.getClassificationCategory(), equalTo("PROCESS")); - assertThat(updatedTask.getClassificationSummary().getCategory(), - equalTo("PROCESS")); + TaskImpl updatedTask = + (TaskImpl) + taskanaEngine.getTaskService().getTask("TKI:000000000000000000000000000000000000"); + assertThat( + updatedTask.getClassificationCategory(), + not(equalTo(beforeTask.getClassificationCategory()))); + assertThat( + updatedTask.getClassificationSummary().getCategory(), + not(equalTo(beforeTask.getClassificationSummary().getCategory()))); + assertThat(updatedTask.getClassificationCategory(), equalTo("PROCESS")); + assertThat(updatedTask.getClassificationSummary().getCategory(), equalTo("PROCESS")); - assertThat(classification.getCreated(), equalTo(createdBefore)); - //isBeforeOrEquals in case of too fast execution - assertTrue(modifiedBefore.isBefore(classification.getModified()) || modifiedBefore.equals( - classification.getModified())); - } + assertThat(classification.getCreated(), equalTo(createdBefore)); + // isBeforeOrEquals in case of too fast execution + assertTrue( + modifiedBefore.isBefore(classification.getModified()) + || modifiedBefore.equals(classification.getModified())); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "businessadmin"}) - @Test - public void testUpdateClassificationNotLatestAnymore() - throws ClassificationNotFoundException, NotAuthorizedException, ConcurrencyException, InterruptedException, - InvalidArgumentException { - Classification base = classificationService.getClassification("T2100", "DOMAIN_A"); - Classification classification = classificationService.getClassification("T2100", "DOMAIN_A"); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "businessadmin"}) + @Test + public void testUpdateClassificationNotLatestAnymore() + throws ClassificationNotFoundException, NotAuthorizedException, ConcurrencyException, + InterruptedException, InvalidArgumentException { + Classification base = classificationService.getClassification("T2100", "DOMAIN_A"); + Classification classification = classificationService.getClassification("T2100", "DOMAIN_A"); - // UPDATE BASE - base.setApplicationEntryPoint("SOME CHANGED POINT"); - base.setDescription("AN OTHER DESCRIPTION"); - base.setName("I AM UPDATED"); - Thread.sleep(20); // to avoid identity of modified timestamps between classification and base - classificationService.updateClassification(base); + // UPDATE BASE + base.setApplicationEntryPoint("SOME CHANGED POINT"); + base.setDescription("AN OTHER DESCRIPTION"); + base.setName("I AM UPDATED"); + Thread.sleep(20); // to avoid identity of modified timestamps between classification and base + classificationService.updateClassification(base); - classification.setName("NOW IT´S MY TURN"); - classification.setDescription("IT SHOULD BE TO LATE..."); - Assertions.assertThrows(ConcurrencyException.class, () -> - classificationService.updateClassification(classification), - "The Classification should not be updated, because it was modified while editing."); - } + classification.setName("NOW IT´S MY TURN"); + classification.setDescription("IT SHOULD BE TO LATE..."); + Assertions.assertThrows( + ConcurrencyException.class, + () -> classificationService.updateClassification(classification), + "The Classification should not be updated, because it was modified while editing."); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "businessadmin"}) - @Test - public void testUpdateClassificationParentIdToInvalid() - throws NotAuthorizedException, ClassificationNotFoundException, - ConcurrencyException, InvalidArgumentException { - Classification classification = classificationService.getClassification("T2100", "DOMAIN_A"); - classification.setParentId("ID WHICH CANT BE FOUND"); - Assertions.assertThrows(ClassificationNotFoundException.class, () -> - classificationService.updateClassification(classification)); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "businessadmin"}) + @Test + public void testUpdateClassificationParentIdToInvalid() + throws NotAuthorizedException, ClassificationNotFoundException, ConcurrencyException, + InvalidArgumentException { + Classification classification = classificationService.getClassification("T2100", "DOMAIN_A"); + classification.setParentId("ID WHICH CANT BE FOUND"); + Assertions.assertThrows( + ClassificationNotFoundException.class, + () -> classificationService.updateClassification(classification)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "businessadmin"}) - @Test - public void testUpdateClassificationParentKeyToInvalid() - throws NotAuthorizedException, ClassificationNotFoundException, - ConcurrencyException, InvalidArgumentException { - Classification classification = classificationService.getClassification("T2100", "DOMAIN_A"); - classification.setParentKey("KEY WHICH CANT BE FOUND"); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "businessadmin"}) + @Test + public void testUpdateClassificationParentKeyToInvalid() + throws NotAuthorizedException, ClassificationNotFoundException, ConcurrencyException, + InvalidArgumentException { + Classification classification = classificationService.getClassification("T2100", "DOMAIN_A"); + classification.setParentKey("KEY WHICH CANT BE FOUND"); - Assertions.assertThrows(ClassificationNotFoundException.class, () -> - classificationService.updateClassification(classification)); - } + Assertions.assertThrows( + ClassificationNotFoundException.class, + () -> classificationService.updateClassification(classification)); + } - @WithAccessId( - userName = "dummy", - groupNames = {"admin"}) - @Test - public void testUpdateClassificationPrioServiceLevel() - throws ClassificationNotFoundException, NotAuthorizedException, ConcurrencyException, - InterruptedException, TaskNotFoundException, InvalidArgumentException { - String newEntryPoint = "updated EntryPoint"; - Instant before = Instant.now(); - Classification classification = classificationService - .getClassification("CLI:100000000000000000000000000000000003"); - Instant createdBefore = classification.getCreated(); - Instant modifiedBefore = classification.getModified(); - classification.setPriority(1000); - classification.setServiceLevel("P15D"); + @WithAccessId( + userName = "dummy", + groupNames = {"admin"}) + @Test + public void testUpdateClassificationPrioServiceLevel() + throws ClassificationNotFoundException, NotAuthorizedException, ConcurrencyException, + InterruptedException, TaskNotFoundException, InvalidArgumentException { + String newEntryPoint = "updated EntryPoint"; + Instant before = Instant.now(); + Classification classification = + classificationService.getClassification("CLI:100000000000000000000000000000000003"); + Instant createdBefore = classification.getCreated(); + Instant modifiedBefore = classification.getModified(); + classification.setPriority(1000); + classification.setServiceLevel("P15D"); - classificationService.updateClassification(classification); - Thread.sleep(10); - JobRunner runner = new JobRunner(taskanaEngine); - // need to run jobs twice, since the first job creates a second one. - runner.runJobs(); - Thread.sleep(10); // otherwise the next runJobs call intermittently doesn't find the Job created - // by the previous step (it searches with DueDate < CurrentTime) - runner.runJobs(); - // Get and check the new value - Classification updatedClassification = classificationService - .getClassification("CLI:100000000000000000000000000000000003"); - assertNotNull(updatedClassification); + classificationService.updateClassification(classification); + Thread.sleep(10); + JobRunner runner = new JobRunner(taskanaEngine); + // need to run jobs twice, since the first job creates a second one. + runner.runJobs(); + Thread.sleep(10); // otherwise the next runJobs call intermittently doesn't find the Job created + // by the previous step (it searches with DueDate < CurrentTime) + runner.runJobs(); + // Get and check the new value + Classification updatedClassification = + classificationService.getClassification("CLI:100000000000000000000000000000000003"); + assertNotNull(updatedClassification); - assertTrue(!modifiedBefore.isAfter(updatedClassification.getModified())); - // TODO - resume old behaviour after attachment query is possible. - TaskService taskService = taskanaEngine.getTaskService(); + assertTrue(!modifiedBefore.isAfter(updatedClassification.getModified())); + // TODO - resume old behaviour after attachment query is possible. + TaskService taskService = taskanaEngine.getTaskService(); - DaysToWorkingDaysConverter converter = DaysToWorkingDaysConverter - .initialize(Collections.singletonList(new TimeIntervalColumnHeader(0)), Instant.now()); + DaysToWorkingDaysConverter converter = + DaysToWorkingDaysConverter.initialize( + Collections.singletonList(new TimeIntervalColumnHeader(0)), Instant.now()); - List tasksWithP1D = new ArrayList<>(Arrays.asList( - "TKI:000000000000000000000000000000000054", - "TKI:000000000000000000000000000000000055", - "TKI:000000000000000000000000000000000000", - "TKI:000000000000000000000000000000000011", - "TKI:000000000000000000000000000000000053" - )); - validateNewTaskProperties(before, tasksWithP1D, taskService, converter, 1); + List tasksWithP1D = + new ArrayList<>( + Arrays.asList( + "TKI:000000000000000000000000000000000054", + "TKI:000000000000000000000000000000000055", + "TKI:000000000000000000000000000000000000", + "TKI:000000000000000000000000000000000011", + "TKI:000000000000000000000000000000000053")); + validateNewTaskProperties(before, tasksWithP1D, taskService, converter, 1); - List tasksWithP8D = new ArrayList<>(Arrays.asList( - "TKI:000000000000000000000000000000000008" - )); - validateNewTaskProperties(before, tasksWithP8D, taskService, converter, 8); + List tasksWithP8D = + new ArrayList<>(Arrays.asList("TKI:000000000000000000000000000000000008")); + validateNewTaskProperties(before, tasksWithP8D, taskService, converter, 8); - List tasksWithP14D = new ArrayList<>(Arrays.asList( - "TKI:000000000000000000000000000000000010" - )); - validateNewTaskProperties(before, tasksWithP14D, taskService, converter, 14); + List tasksWithP14D = + new ArrayList<>(Arrays.asList("TKI:000000000000000000000000000000000010")); + validateNewTaskProperties(before, tasksWithP14D, taskService, converter, 14); - List tasksWithP15D = new ArrayList<>( - Arrays.asList("TKI:000000000000000000000000000000000003", "TKI:000000000000000000000000000000000004", - "TKI:000000000000000000000000000000000005", "TKI:000000000000000000000000000000000006", + List tasksWithP15D = + new ArrayList<>( + Arrays.asList( + "TKI:000000000000000000000000000000000003", + "TKI:000000000000000000000000000000000004", + "TKI:000000000000000000000000000000000005", + "TKI:000000000000000000000000000000000006", "TKI:000000000000000000000000000000000007", - "TKI:000000000000000000000000000000000009", "TKI:000000000000000000000000000000000012", - "TKI:000000000000000000000000000000000013", "TKI:000000000000000000000000000000000014", - "TKI:000000000000000000000000000000000015", "TKI:000000000000000000000000000000000016", - "TKI:000000000000000000000000000000000017", "TKI:000000000000000000000000000000000018", - "TKI:000000000000000000000000000000000019", "TKI:000000000000000000000000000000000020", - "TKI:000000000000000000000000000000000021", "TKI:000000000000000000000000000000000022", - "TKI:000000000000000000000000000000000023", "TKI:000000000000000000000000000000000024", - "TKI:000000000000000000000000000000000025", "TKI:000000000000000000000000000000000026", - "TKI:000000000000000000000000000000000027", "TKI:000000000000000000000000000000000028", - "TKI:000000000000000000000000000000000029", "TKI:000000000000000000000000000000000030", - "TKI:000000000000000000000000000000000031", "TKI:000000000000000000000000000000000032", - "TKI:000000000000000000000000000000000033", "TKI:000000000000000000000000000000000034", - "TKI:000000000000000000000000000000000035", "TKI:000000000000000000000000000000000100", - "TKI:000000000000000000000000000000000101", "TKI:000000000000000000000000000000000102", - "TKI:000000000000000000000000000000000103" - )); - validateNewTaskProperties(before, tasksWithP15D, taskService, converter, 15); + "TKI:000000000000000000000000000000000009", + "TKI:000000000000000000000000000000000012", + "TKI:000000000000000000000000000000000013", + "TKI:000000000000000000000000000000000014", + "TKI:000000000000000000000000000000000015", + "TKI:000000000000000000000000000000000016", + "TKI:000000000000000000000000000000000017", + "TKI:000000000000000000000000000000000018", + "TKI:000000000000000000000000000000000019", + "TKI:000000000000000000000000000000000020", + "TKI:000000000000000000000000000000000021", + "TKI:000000000000000000000000000000000022", + "TKI:000000000000000000000000000000000023", + "TKI:000000000000000000000000000000000024", + "TKI:000000000000000000000000000000000025", + "TKI:000000000000000000000000000000000026", + "TKI:000000000000000000000000000000000027", + "TKI:000000000000000000000000000000000028", + "TKI:000000000000000000000000000000000029", + "TKI:000000000000000000000000000000000030", + "TKI:000000000000000000000000000000000031", + "TKI:000000000000000000000000000000000032", + "TKI:000000000000000000000000000000000033", + "TKI:000000000000000000000000000000000034", + "TKI:000000000000000000000000000000000035", + "TKI:000000000000000000000000000000000100", + "TKI:000000000000000000000000000000000101", + "TKI:000000000000000000000000000000000102", + "TKI:000000000000000000000000000000000103")); + validateNewTaskProperties(before, tasksWithP15D, taskService, converter, 15); + } + @WithAccessId( + userName = "dummy", + groupNames = {"businessadmin"}) + @Test + public void testUpdateClassificationWithSameKeyAndParentKey() + throws ClassificationNotFoundException, NotAuthorizedException, ConcurrencyException, + InvalidArgumentException { + + Classification classification = classificationService.getClassification("T2100", "DOMAIN_A"); + + classification.setParentKey(classification.getKey()); + Assertions.assertThrows( + InvalidArgumentException.class, + () -> classificationService.updateClassification(classification)); + } + + @WithAccessId( + userName = "dummy", + groupNames = {"businessadmin"}) + @Test + public void testUpdateClassificationWithEmptyServiceLevel() + throws DomainNotFoundException, ClassificationAlreadyExistException, NotAuthorizedException, + InvalidArgumentException, ClassificationNotFoundException, ConcurrencyException { + + Classification classification = + classificationService.newClassification("Key=0818", "DOMAIN_A", "TASK"); + Classification created = classificationService.createClassification(classification); + created.setServiceLevel(""); + classificationService.updateClassification(created); + } + + private void validateNewTaskProperties( + Instant before, + List tasksWithP15D, + TaskService taskService, + DaysToWorkingDaysConverter converter, + int serviceLevel) + throws TaskNotFoundException, NotAuthorizedException { + for (String taskId : tasksWithP15D) { + Task task = taskService.getTask(taskId); + assertTrue( + task.getModified().isAfter(before), "Task " + task.getId() + " has not been refreshed."); + assertEquals(1000, task.getPriority()); + long calendarDays = converter.convertWorkingDaysToDays(task.getPlanned(), serviceLevel); + + String msg = + "Task: " + + taskId + + ": Due Date " + + task.getDue() + + " does not match planned " + + task.getPlanned() + + " + calendar days " + + calendarDays; + assertEquals(task.getDue(), task.getPlanned().plus(Duration.ofDays(calendarDays)), msg); } - - @WithAccessId( - userName = "dummy", - groupNames = {"businessadmin"}) - @Test - public void testUpdateClassificationWithSameKeyAndParentKey() - throws ClassificationNotFoundException, NotAuthorizedException, ConcurrencyException, InvalidArgumentException { - - Classification classification = classificationService.getClassification("T2100", "DOMAIN_A"); - - classification.setParentKey(classification.getKey()); - Assertions.assertThrows(InvalidArgumentException.class, () -> - classificationService.updateClassification(classification)); - } - - @WithAccessId( - userName = "dummy", - groupNames = {"businessadmin"}) - @Test - public void testUpdateClassificationWithEmptyServiceLevel() - throws DomainNotFoundException, ClassificationAlreadyExistException, NotAuthorizedException, - InvalidArgumentException, ClassificationNotFoundException, ConcurrencyException { - - Classification classification = classificationService.newClassification("Key=0818", "DOMAIN_A", "TASK"); - Classification created = classificationService.createClassification(classification); - created.setServiceLevel(""); - classificationService.updateClassification(created); - } - - private void validateNewTaskProperties(Instant before, List tasksWithP15D, TaskService taskService, - DaysToWorkingDaysConverter converter, int serviceLevel) throws TaskNotFoundException, NotAuthorizedException { - for (String taskId : tasksWithP15D) { - Task task = taskService.getTask(taskId); - assertTrue(task.getModified().isAfter(before), "Task " + task.getId() + " has not been refreshed."); - assertEquals(1000, task.getPriority()); - long calendarDays = converter.convertWorkingDaysToDays(task.getPlanned(), serviceLevel); - - String msg = - "Task: " + taskId + ": Due Date " + task.getDue() + " does not match planned " + task.getPlanned() - + " + calendar days " + calendarDays; - assertEquals(task.getDue(), task.getPlanned().plus(Duration.ofDays(calendarDays)), msg); - } - } - + } } diff --git a/lib/taskana-core/src/test/java/acceptance/config/TaskanaConfigAccTest.java b/lib/taskana-core/src/test/java/acceptance/config/TaskanaConfigAccTest.java index 49d8f28e2..f1e3ef9d9 100644 --- a/lib/taskana-core/src/test/java/acceptance/config/TaskanaConfigAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/config/TaskanaConfigAccTest.java @@ -11,7 +11,6 @@ import java.io.PrintWriter; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; - import org.h2.store.fs.FileUtils; import org.junit.jupiter.api.Test; @@ -26,115 +25,129 @@ import pro.taskana.impl.configuration.TaskanaEngineTestConfiguration; */ class TaskanaConfigAccTest extends TaskanaEngineImpl { - TaskanaConfigAccTest() throws SQLException { - super(new TaskanaEngineConfiguration(TaskanaEngineTestConfiguration.getDataSource(), + TaskanaConfigAccTest() throws SQLException { + super( + new TaskanaEngineConfiguration( + TaskanaEngineTestConfiguration.getDataSource(), true, TaskanaEngineTestConfiguration.getSchemaName())); - } + } - @Test - void testDomains() { - assertEquals(2, getConfiguration().getDomains().size()); - assertTrue(getConfiguration().getDomains().contains("DOMAIN_A")); - assertTrue(getConfiguration().getDomains().contains("DOMAIN_B")); - assertFalse(getConfiguration().getDomains().contains("Domain_A")); - } + @Test + void testDomains() { + assertEquals(2, getConfiguration().getDomains().size()); + assertTrue(getConfiguration().getDomains().contains("DOMAIN_A")); + assertTrue(getConfiguration().getDomains().contains("DOMAIN_B")); + assertFalse(getConfiguration().getDomains().contains("Domain_A")); + } - @Test - void testClassificationTypes() { - assertEquals(2, getConfiguration().getClassificationTypes().size()); - assertTrue(getConfiguration().getClassificationTypes().contains("TASK")); - assertTrue(getConfiguration().getClassificationTypes().contains("DOCUMENT")); - assertFalse(getConfiguration().getClassificationTypes().contains("document")); - } + @Test + void testClassificationTypes() { + assertEquals(2, getConfiguration().getClassificationTypes().size()); + assertTrue(getConfiguration().getClassificationTypes().contains("TASK")); + assertTrue(getConfiguration().getClassificationTypes().contains("DOCUMENT")); + assertFalse(getConfiguration().getClassificationTypes().contains("document")); + } - @Test - void testClassificationCategories() { - assertEquals(4, getConfiguration().getClassificationCategoriesByType("TASK").size()); - assertTrue(getConfiguration().getClassificationCategoriesByType("TASK").contains("EXTERNAL")); - assertTrue(getConfiguration().getClassificationCategoriesByType("TASK").contains("MANUAL")); - assertTrue(getConfiguration().getClassificationCategoriesByType("TASK").contains("AUTOMATIC")); - assertTrue(getConfiguration().getClassificationCategoriesByType("TASK").contains("PROCESS")); - assertFalse(getConfiguration().getClassificationCategoriesByType("TASK").contains("manual")); - } + @Test + void testClassificationCategories() { + assertEquals(4, getConfiguration().getClassificationCategoriesByType("TASK").size()); + assertTrue(getConfiguration().getClassificationCategoriesByType("TASK").contains("EXTERNAL")); + assertTrue(getConfiguration().getClassificationCategoriesByType("TASK").contains("MANUAL")); + assertTrue(getConfiguration().getClassificationCategoriesByType("TASK").contains("AUTOMATIC")); + assertTrue(getConfiguration().getClassificationCategoriesByType("TASK").contains("PROCESS")); + assertFalse(getConfiguration().getClassificationCategoriesByType("TASK").contains("manual")); + } - @Test - void testDoesNotExistPropertyClassificationTypeOrItIsEmpty() throws IOException { - taskanaEngineConfiguration.setClassificationTypes(new ArrayList<>()); - String propertiesFileName = createNewConfigFile("/dummyTestConfig.properties", false, true); - String delimiter = ";"; - try { - getConfiguration().initTaskanaProperties(propertiesFileName, delimiter); - } finally { - deleteFile(propertiesFileName); - } - assertTrue(taskanaEngineConfiguration.getClassificationTypes().isEmpty()); + @Test + void testDoesNotExistPropertyClassificationTypeOrItIsEmpty() throws IOException { + taskanaEngineConfiguration.setClassificationTypes(new ArrayList<>()); + String propertiesFileName = createNewConfigFile("/dummyTestConfig.properties", false, true); + String delimiter = ";"; + try { + getConfiguration().initTaskanaProperties(propertiesFileName, delimiter); + } finally { + deleteFile(propertiesFileName); } + assertTrue(taskanaEngineConfiguration.getClassificationTypes().isEmpty()); + } - @Test - void testDoesNotExistPropertyClassificatioCategoryOrItIsEmpty() throws IOException { - taskanaEngineConfiguration.setClassificationTypes(new ArrayList<>()); - taskanaEngineConfiguration.setClassificationCategoriesByType(new HashMap<>()); - String propertiesFileName = createNewConfigFile("/dummyTestConfig.properties", true, false); - String delimiter = ";"; - try { - getConfiguration().initTaskanaProperties(propertiesFileName, delimiter); - } finally { - deleteFile(propertiesFileName); - } - assertNull(taskanaEngineConfiguration.getClassificationCategoriesByType( + @Test + void testDoesNotExistPropertyClassificatioCategoryOrItIsEmpty() throws IOException { + taskanaEngineConfiguration.setClassificationTypes(new ArrayList<>()); + taskanaEngineConfiguration.setClassificationCategoriesByType(new HashMap<>()); + String propertiesFileName = createNewConfigFile("/dummyTestConfig.properties", true, false); + String delimiter = ";"; + try { + getConfiguration().initTaskanaProperties(propertiesFileName, delimiter); + } finally { + deleteFile(propertiesFileName); + } + assertNull( + taskanaEngineConfiguration.getClassificationCategoriesByType( taskanaEngineConfiguration.getClassificationTypes().get(0))); - } + } - @Test - void testWithCategoriesAndClassificationFilled() throws IOException { - taskanaEngineConfiguration.setClassificationTypes(new ArrayList<>()); - taskanaEngineConfiguration.setClassificationCategoriesByType(new HashMap<>()); - String propertiesFileName = createNewConfigFile("/dummyTestConfig.properties", true, true); - String delimiter = ";"; - try { - getConfiguration().initTaskanaProperties(propertiesFileName, delimiter); - } finally { - deleteFile(propertiesFileName); + @Test + void testWithCategoriesAndClassificationFilled() throws IOException { + taskanaEngineConfiguration.setClassificationTypes(new ArrayList<>()); + taskanaEngineConfiguration.setClassificationCategoriesByType(new HashMap<>()); + String propertiesFileName = createNewConfigFile("/dummyTestConfig.properties", true, true); + String delimiter = ";"; + try { + getConfiguration().initTaskanaProperties(propertiesFileName, delimiter); + } finally { + deleteFile(propertiesFileName); + } + assertFalse(taskanaEngineConfiguration.getClassificationTypes().isEmpty()); + assertFalse( + taskanaEngineConfiguration + .getClassificationCategoriesByType( + taskanaEngineConfiguration.getClassificationTypes().get(0)) + .isEmpty()); + assertEquals(taskanaEngineConfiguration.getClassificationTypes().size(), 2); + assertEquals( + taskanaEngineConfiguration + .getClassificationCategoriesByType( + taskanaEngineConfiguration.getClassificationTypes().get(0)) + .size(), + 4); + assertEquals( + taskanaEngineConfiguration + .getClassificationCategoriesByType( + taskanaEngineConfiguration.getClassificationTypes().get(1)) + .size(), + 1); + } + + private String createNewConfigFile( + String filename, boolean addingTypes, boolean addingClassification) throws IOException { + String userHomeDirectroy = System.getProperty("user.home"); + String propertiesFileName = userHomeDirectroy + filename; + File f = new File(propertiesFileName); + if (!f.exists()) { + try (PrintWriter writer = new PrintWriter(propertiesFileName, "UTF-8")) { + writer.println("taskana.roles.Admin =Holger|Stefan"); + writer.println("taskana.roles.businessadmin = ebe | konstantin "); + writer.println("taskana.roles.user = nobody"); + if (addingTypes) { + writer.println("taskana.classification.types= TASK , document"); } - assertFalse(taskanaEngineConfiguration.getClassificationTypes().isEmpty()); - assertFalse(taskanaEngineConfiguration.getClassificationCategoriesByType( - taskanaEngineConfiguration.getClassificationTypes().get(0)).isEmpty()); - assertEquals(taskanaEngineConfiguration.getClassificationTypes().size(), 2); - assertEquals(taskanaEngineConfiguration.getClassificationCategoriesByType( - taskanaEngineConfiguration.getClassificationTypes().get(0)).size(), 4); - assertEquals(taskanaEngineConfiguration.getClassificationCategoriesByType( - taskanaEngineConfiguration.getClassificationTypes().get(1)).size(), 1); - } - - private String createNewConfigFile(String filename, boolean addingTypes, boolean addingClassification) - throws IOException { - String userHomeDirectroy = System.getProperty("user.home"); - String propertiesFileName = userHomeDirectroy + filename; - File f = new File(propertiesFileName); - if (!f.exists()) { - try (PrintWriter writer = new PrintWriter(propertiesFileName, "UTF-8")) { - writer.println("taskana.roles.Admin =Holger|Stefan"); - writer.println("taskana.roles.businessadmin = ebe | konstantin "); - writer.println("taskana.roles.user = nobody"); - if (addingTypes) { - writer.println("taskana.classification.types= TASK , document"); - } - if (addingClassification) { - writer.println("taskana.classification.categories.task= EXTERNAL, manual, autoMAtic, Process"); - writer.println("taskana.classification.categories.document= EXTERNAL"); - } - } + if (addingClassification) { + writer.println( + "taskana.classification.categories.task= EXTERNAL, manual, autoMAtic, Process"); + writer.println("taskana.classification.categories.document= EXTERNAL"); } - return propertiesFileName; + } } + return propertiesFileName; + } - private void deleteFile(String propertiesFileName) { - System.out.println("about to delete " + propertiesFileName); - File f = new File(propertiesFileName); - if (f.exists() && !f.isDirectory()) { - FileUtils.delete(propertiesFileName); - } + private void deleteFile(String propertiesFileName) { + System.out.println("about to delete " + propertiesFileName); + File f = new File(propertiesFileName); + if (f.exists() && !f.isDirectory()) { + FileUtils.delete(propertiesFileName); } - + } } diff --git a/lib/taskana-core/src/test/java/acceptance/config/TaskanaRoleConfigAccTest.java b/lib/taskana-core/src/test/java/acceptance/config/TaskanaRoleConfigAccTest.java index 344a5a0e5..e1b265128 100644 --- a/lib/taskana-core/src/test/java/acceptance/config/TaskanaRoleConfigAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/config/TaskanaRoleConfigAccTest.java @@ -7,7 +7,6 @@ import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import java.util.Set; - import org.h2.store.fs.FileUtils; import org.junit.jupiter.api.Test; @@ -23,127 +22,129 @@ import pro.taskana.impl.configuration.TaskanaEngineTestConfiguration; */ class TaskanaRoleConfigAccTest extends TaskanaEngineImpl { - TaskanaRoleConfigAccTest() throws SQLException { - super(new TaskanaEngineConfiguration(TaskanaEngineTestConfiguration.getDataSource(), + TaskanaRoleConfigAccTest() throws SQLException { + super( + new TaskanaEngineConfiguration( + TaskanaEngineTestConfiguration.getDataSource(), true, TaskanaEngineTestConfiguration.getSchemaName())); + } + + @Test + void testStandardConfig() { + Set rolesConfigured = getConfiguration().getRoleMap().keySet(); + assertTrue(rolesConfigured.contains(TaskanaRole.ADMIN)); + assertTrue(rolesConfigured.contains(TaskanaRole.BUSINESS_ADMIN)); + assertTrue(rolesConfigured.contains(TaskanaRole.USER)); + + Set users = getConfiguration().getRoleMap().get(TaskanaRole.USER); + assertTrue(users.contains("user_1_1")); + assertTrue(users.contains("user_1_2")); + + Set admins = getConfiguration().getRoleMap().get(TaskanaRole.ADMIN); + assertTrue(admins.contains("name=konrad,organisation=novatec")); + assertTrue(admins.contains("admin")); + + Set businessAdmins = getConfiguration().getRoleMap().get(TaskanaRole.BUSINESS_ADMIN); + assertTrue(businessAdmins.contains("max")); + assertTrue(businessAdmins.contains("moritz")); + + Set monitorAccessIds = getConfiguration().getRoleMap().get(TaskanaRole.MONITOR); + assertTrue(monitorAccessIds.contains("john")); + assertTrue(monitorAccessIds.contains("teamlead_2")); + assertTrue(monitorAccessIds.contains("monitor")); + } + + @Test + void testOtherConfigFileSameDelimiter() throws IOException { + String propertiesFileName = createNewConfigFileWithSameDelimiter("/dummyTestConfig.properties"); + try { + getConfiguration().initTaskanaProperties(propertiesFileName, "|"); + + Set rolesConfigured = getConfiguration().getRoleMap().keySet(); + assertTrue(rolesConfigured.contains(TaskanaRole.ADMIN)); + assertTrue(rolesConfigured.contains(TaskanaRole.BUSINESS_ADMIN)); + assertTrue(rolesConfigured.contains(TaskanaRole.USER)); + + Set users = getConfiguration().getRoleMap().get(TaskanaRole.USER); + assertTrue(users.contains("nobody")); + + Set admins = getConfiguration().getRoleMap().get(TaskanaRole.ADMIN); + assertTrue(admins.contains("holger")); + assertTrue(admins.contains("stefan")); + + Set businessAdmins = getConfiguration().getRoleMap().get(TaskanaRole.BUSINESS_ADMIN); + assertTrue(businessAdmins.contains("ebe")); + assertTrue(businessAdmins.contains("konstantin")); + } finally { + deleteFile(propertiesFileName); } + } - @Test - void testStandardConfig() { - Set rolesConfigured = getConfiguration().getRoleMap().keySet(); - assertTrue(rolesConfigured.contains(TaskanaRole.ADMIN)); - assertTrue(rolesConfigured.contains(TaskanaRole.BUSINESS_ADMIN)); - assertTrue(rolesConfigured.contains(TaskanaRole.USER)); + @Test + void testOtherConfigFileDifferentDelimiter() throws IOException { + String delimiter = ";"; + String propertiesFileName = + createNewConfigFileWithDifferentDelimiter("/dummyTestConfig.properties", delimiter); + try { + getConfiguration().initTaskanaProperties(propertiesFileName, delimiter); - Set users = getConfiguration().getRoleMap().get(TaskanaRole.USER); - assertTrue(users.contains("user_1_1")); - assertTrue(users.contains("user_1_2")); + Set rolesConfigured = getConfiguration().getRoleMap().keySet(); + assertTrue(rolesConfigured.contains(TaskanaRole.ADMIN)); + assertTrue(rolesConfigured.contains(TaskanaRole.BUSINESS_ADMIN)); + assertTrue(rolesConfigured.contains(TaskanaRole.USER)); - Set admins = getConfiguration().getRoleMap().get(TaskanaRole.ADMIN); - assertTrue(admins.contains("name=konrad,organisation=novatec")); - assertTrue(admins.contains("admin")); + Set users = getConfiguration().getRoleMap().get(TaskanaRole.USER); + assertTrue(users.isEmpty()); - Set businessAdmins = getConfiguration().getRoleMap().get(TaskanaRole.BUSINESS_ADMIN); - assertTrue(businessAdmins.contains("max")); - assertTrue(businessAdmins.contains("moritz")); - - Set monitorAccessIds = getConfiguration().getRoleMap().get(TaskanaRole.MONITOR); - assertTrue(monitorAccessIds.contains("john")); - assertTrue(monitorAccessIds.contains("teamlead_2")); - assertTrue(monitorAccessIds.contains("monitor")); + Set admins = getConfiguration().getRoleMap().get(TaskanaRole.ADMIN); + assertTrue(admins.contains("holger")); + assertTrue(admins.contains("name=stefan,organisation=novatec")); + Set businessAdmins = getConfiguration().getRoleMap().get(TaskanaRole.BUSINESS_ADMIN); + assertTrue(businessAdmins.contains("name=ebe, ou = bpm")); + assertTrue(businessAdmins.contains("konstantin")); + } finally { + deleteFile(propertiesFileName); } + } - @Test - void testOtherConfigFileSameDelimiter() throws IOException { - String propertiesFileName = createNewConfigFileWithSameDelimiter("/dummyTestConfig.properties"); - try { - getConfiguration().initTaskanaProperties(propertiesFileName, "|"); - - Set rolesConfigured = getConfiguration().getRoleMap().keySet(); - assertTrue(rolesConfigured.contains(TaskanaRole.ADMIN)); - assertTrue(rolesConfigured.contains(TaskanaRole.BUSINESS_ADMIN)); - assertTrue(rolesConfigured.contains(TaskanaRole.USER)); - - Set users = getConfiguration().getRoleMap().get(TaskanaRole.USER); - assertTrue(users.contains("nobody")); - - Set admins = getConfiguration().getRoleMap().get(TaskanaRole.ADMIN); - assertTrue(admins.contains("holger")); - assertTrue(admins.contains("stefan")); - - Set businessAdmins = getConfiguration().getRoleMap().get(TaskanaRole.BUSINESS_ADMIN); - assertTrue(businessAdmins.contains("ebe")); - assertTrue(businessAdmins.contains("konstantin")); - } finally { - deleteFile(propertiesFileName); - } - + private String createNewConfigFileWithDifferentDelimiter(String filename, String delimiter) + throws IOException { + String userHomeDirectroy = System.getProperty("user.home"); + String propertiesFileName = userHomeDirectroy + filename; + File f = new File(propertiesFileName); + if (!f.exists()) { + try (PrintWriter writer = new PrintWriter(propertiesFileName, "UTF-8")) { + writer.println( + "taskana.roles.Admin =hOlGeR " + delimiter + "name=Stefan,Organisation=novatec"); + writer.println( + " taskana.roles.businessadmin = name=ebe, ou = bpm " + delimiter + " konstantin "); + writer.println(" taskana.roles.user = "); + } } + return propertiesFileName; + } - @Test - void testOtherConfigFileDifferentDelimiter() throws IOException { - String delimiter = ";"; - String propertiesFileName = createNewConfigFileWithDifferentDelimiter("/dummyTestConfig.properties", delimiter); - try { - getConfiguration().initTaskanaProperties(propertiesFileName, delimiter); - - Set rolesConfigured = getConfiguration().getRoleMap().keySet(); - assertTrue(rolesConfigured.contains(TaskanaRole.ADMIN)); - assertTrue(rolesConfigured.contains(TaskanaRole.BUSINESS_ADMIN)); - assertTrue(rolesConfigured.contains(TaskanaRole.USER)); - - Set users = getConfiguration().getRoleMap().get(TaskanaRole.USER); - assertTrue(users.isEmpty()); - - Set admins = getConfiguration().getRoleMap().get(TaskanaRole.ADMIN); - assertTrue(admins.contains("holger")); - assertTrue(admins.contains("name=stefan,organisation=novatec")); - - Set businessAdmins = getConfiguration().getRoleMap().get(TaskanaRole.BUSINESS_ADMIN); - assertTrue(businessAdmins.contains("name=ebe, ou = bpm")); - assertTrue(businessAdmins.contains("konstantin")); - } finally { - deleteFile(propertiesFileName); - } - + private void deleteFile(String propertiesFileName) { + System.out.println("about to delete " + propertiesFileName); + File f = new File(propertiesFileName); + if (f.exists() && !f.isDirectory()) { + FileUtils.delete(propertiesFileName); } + } - private String createNewConfigFileWithDifferentDelimiter(String filename, String delimiter) throws IOException { - String userHomeDirectroy = System.getProperty("user.home"); - String propertiesFileName = userHomeDirectroy + filename; - File f = new File(propertiesFileName); - if (!f.exists()) { - try (PrintWriter writer = new PrintWriter(propertiesFileName, "UTF-8")) { - writer.println("taskana.roles.Admin =hOlGeR " + delimiter + "name=Stefan,Organisation=novatec"); - writer.println(" taskana.roles.businessadmin = name=ebe, ou = bpm " + delimiter + " konstantin "); - writer.println(" taskana.roles.user = "); - } - } - return propertiesFileName; + private String createNewConfigFileWithSameDelimiter(String filename) throws IOException { + String userHomeDirectroy = System.getProperty("user.home"); + String propertiesFileName = userHomeDirectroy + filename; + File f = new File(propertiesFileName); + if (!f.exists()) { + try (PrintWriter writer = new PrintWriter(propertiesFileName, "UTF-8")) { + writer.println("taskana.roles.Admin =hOlGeR|Stefan"); + writer.println(" taskana.roles.businessadmin = ebe | konstantin "); + writer.println(" taskana.roles.user = nobody"); + } } - - private void deleteFile(String propertiesFileName) { - System.out.println("about to delete " + propertiesFileName); - File f = new File(propertiesFileName); - if (f.exists() && !f.isDirectory()) { - FileUtils.delete(propertiesFileName); - } - } - - private String createNewConfigFileWithSameDelimiter(String filename) throws IOException { - String userHomeDirectroy = System.getProperty("user.home"); - String propertiesFileName = userHomeDirectroy + filename; - File f = new File(propertiesFileName); - if (!f.exists()) { - try (PrintWriter writer = new PrintWriter(propertiesFileName, "UTF-8")) { - writer.println("taskana.roles.Admin =hOlGeR|Stefan"); - writer.println(" taskana.roles.businessadmin = ebe | konstantin "); - writer.println(" taskana.roles.user = nobody"); - } - } - return propertiesFileName; - } - + return propertiesFileName; + } } diff --git a/lib/taskana-core/src/test/java/acceptance/history/TaskEventProducerTest.java b/lib/taskana-core/src/test/java/acceptance/history/TaskEventProducerTest.java index 000b6ccf3..a901ea59d 100644 --- a/lib/taskana-core/src/test/java/acceptance/history/TaskEventProducerTest.java +++ b/lib/taskana-core/src/test/java/acceptance/history/TaskEventProducerTest.java @@ -2,17 +2,14 @@ package acceptance.history; import static org.junit.jupiter.api.Assertions.assertFalse; +import acceptance.AbstractAccTest; import org.junit.jupiter.api.Test; -import acceptance.AbstractAccTest; - -/** - * Acceptance test for historyEventProducer class. - */ +/** Acceptance test for historyEventProducer class. */ class TaskEventProducerTest extends AbstractAccTest { - @Test - void testHistoryEventProducerIsNotEnabled() { - assertFalse(taskanaEngine.isHistoryEnabled()); - } + @Test + void testHistoryEventProducerIsNotEnabled() { + assertFalse(taskanaEngine.isHistoryEnabled()); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/jobs/TaskCleanupJobAccTest.java b/lib/taskana-core/src/test/java/acceptance/jobs/TaskCleanupJobAccTest.java index 278646067..8ba648c36 100644 --- a/lib/taskana-core/src/test/java/acceptance/jobs/TaskCleanupJobAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/jobs/TaskCleanupJobAccTest.java @@ -3,15 +3,14 @@ package acceptance.jobs; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import acceptance.AbstractAccTest; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.Task; import pro.taskana.TaskService; import pro.taskana.TaskSummary; @@ -27,87 +26,86 @@ import pro.taskana.jobs.TaskCleanupJob; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "jobs tasks runner" scenarios. - */ +/** Acceptance test for all "jobs tasks runner" scenarios. */ @ExtendWith(JAASExtension.class) class TaskCleanupJobAccTest extends AbstractAccTest { - TaskService taskService; + TaskService taskService; - @BeforeEach - void before() throws SQLException { - //required if single tests modify database - //TODO split test class into readOnly & modifying tests to improve performance - resetDb(false); - taskService = taskanaEngine.getTaskService(); - } + @BeforeEach + void before() throws SQLException { + // required if single tests modify database + // TODO split test class into readOnly & modifying tests to improve performance + resetDb(false); + taskService = taskanaEngine.getTaskService(); + } - @WithAccessId(userName = "admin") - @Test - void shouldCleanCompletedTasksUntilDate() throws Exception { + @WithAccessId(userName = "admin") + @Test + void shouldCleanCompletedTasksUntilDate() throws Exception { - createAndCompleteTask(); - long totalTasksCount = taskService.createTaskQuery().count(); - assertEquals(74, totalTasksCount); + createAndCompleteTask(); + long totalTasksCount = taskService.createTaskQuery().count(); + assertEquals(74, totalTasksCount); - taskanaEngine.getConfiguration().setTaskCleanupJobAllCompletedSameParentBusiness(false); + taskanaEngine.getConfiguration().setTaskCleanupJobAllCompletedSameParentBusiness(false); - TaskCleanupJob job = new TaskCleanupJob(taskanaEngine, null, null); - job.run(); + TaskCleanupJob job = new TaskCleanupJob(taskanaEngine, null, null); + job.run(); - totalTasksCount = taskService.createTaskQuery().count(); - assertEquals(68, totalTasksCount); - } + totalTasksCount = taskService.createTaskQuery().count(); + assertEquals(68, totalTasksCount); + } - @WithAccessId(userName = "admin") - @Test - void shouldCleanCompletedTasksUntilDateWithSameParentBussiness() throws Exception { - long totalTasksCount = taskService.createTaskQuery().count(); - assertEquals(73, totalTasksCount); + @WithAccessId(userName = "admin") + @Test + void shouldCleanCompletedTasksUntilDateWithSameParentBussiness() throws Exception { + long totalTasksCount = taskService.createTaskQuery().count(); + assertEquals(73, totalTasksCount); - taskanaEngine.getConfiguration().setTaskCleanupJobAllCompletedSameParentBusiness(true); + taskanaEngine.getConfiguration().setTaskCleanupJobAllCompletedSameParentBusiness(true); - List tasks = taskService.createTaskQuery() - .parentBusinessProcessIdIn("DOC_0000000000000000006") - .list(); - List ids = new ArrayList<>(); - tasks.forEach(item -> { - if (item.getCompleted() == null) { - ids.add(item.getTaskId()); - } + List tasks = + taskService.createTaskQuery().parentBusinessProcessIdIn("DOC_0000000000000000006").list(); + List ids = new ArrayList<>(); + tasks.forEach( + item -> { + if (item.getCompleted() == null) { + ids.add(item.getTaskId()); + } }); - taskService.deleteTasks(ids); + taskService.deleteTasks(ids); - TaskCleanupJob job = new TaskCleanupJob(taskanaEngine, null, null); - job.run(); + TaskCleanupJob job = new TaskCleanupJob(taskanaEngine, null, null); + job.run(); - totalTasksCount = taskService.createTaskQuery().count(); - assertEquals(66, totalTasksCount); - } + totalTasksCount = taskService.createTaskQuery().count(); + assertEquals(66, totalTasksCount); + } - @WithAccessId(userName = "admin") - @Test - void shouldNotCleanCompleteTasksAfterDefinedDay() throws Exception { - Task createdTask = createAndCompleteTask(); + @WithAccessId(userName = "admin") + @Test + void shouldNotCleanCompleteTasksAfterDefinedDay() throws Exception { + Task createdTask = createAndCompleteTask(); - TaskCleanupJob job = new TaskCleanupJob(taskanaEngine, null, null); - job.run(); + TaskCleanupJob job = new TaskCleanupJob(taskanaEngine, null, null); + job.run(); - Task completedCreatedTask = taskService.getTask(createdTask.getId()); - assertNotNull(completedCreatedTask); - } - - private Task createAndCompleteTask() throws NotAuthorizedException, WorkbasketNotFoundException, - ClassificationNotFoundException, TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException, - InvalidStateException, InvalidOwnerException { - Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); - newTask.setClassificationKey("T2100"); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - Task createdTask = taskService.createTask(newTask); - taskService.claim(createdTask.getId()); - taskService.completeTask(createdTask.getId()); - return createdTask; - } + Task completedCreatedTask = taskService.getTask(createdTask.getId()); + assertNotNull(completedCreatedTask); + } + private Task createAndCompleteTask() + throws NotAuthorizedException, WorkbasketNotFoundException, ClassificationNotFoundException, + TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException, + InvalidStateException, InvalidOwnerException { + Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); + newTask.setClassificationKey("T2100"); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + Task createdTask = taskService.createTask(newTask); + taskService.claim(createdTask.getId()); + taskService.completeTask(createdTask.getId()); + return createdTask; + } } diff --git a/lib/taskana-core/src/test/java/acceptance/jobs/WorkbasketCleanupJobAccTest.java b/lib/taskana-core/src/test/java/acceptance/jobs/WorkbasketCleanupJobAccTest.java index 6df6e07e8..ff7beff6e 100644 --- a/lib/taskana-core/src/test/java/acceptance/jobs/WorkbasketCleanupJobAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/jobs/WorkbasketCleanupJobAccTest.java @@ -3,14 +3,13 @@ package acceptance.jobs; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import acceptance.AbstractAccTest; import java.util.List; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.BaseQuery; import pro.taskana.TaskService; import pro.taskana.TaskState; @@ -22,94 +21,92 @@ import pro.taskana.jobs.WorkbasketCleanupJob; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "jobs workbasket runner" scenarios. - */ +/** Acceptance test for all "jobs workbasket runner" scenarios. */ @ExtendWith(JAASExtension.class) class WorkbasketCleanupJobAccTest extends AbstractAccTest { - WorkbasketService workbasketService; - TaskService taskService; + WorkbasketService workbasketService; + TaskService taskService; - @BeforeEach - void before() { - workbasketService = taskanaEngine.getWorkbasketService(); - taskService = taskanaEngine.getTaskService(); - } + @BeforeEach + void before() { + workbasketService = taskanaEngine.getWorkbasketService(); + taskService = taskanaEngine.getTaskService(); + } - @AfterEach - void after() throws Exception { - resetDb(true); - } + @AfterEach + void after() throws Exception { + resetDb(true); + } - @WithAccessId(userName = "admin") - @Test - void shouldCleanWorkbasketMarkedForDeletionWithoutTasks() throws TaskanaException { - long totalWorkbasketCount = workbasketService.createWorkbasketQuery().count(); - assertEquals(25, totalWorkbasketCount); - List workbaskets = workbasketService.createWorkbasketQuery() + @WithAccessId(userName = "admin") + @Test + void shouldCleanWorkbasketMarkedForDeletionWithoutTasks() throws TaskanaException { + long totalWorkbasketCount = workbasketService.createWorkbasketQuery().count(); + assertEquals(25, totalWorkbasketCount); + List workbaskets = + workbasketService + .createWorkbasketQuery() .keyIn("TEAMLEAD_1") - .orderByKey( - BaseQuery.SortDirection.ASCENDING) + .orderByKey(BaseQuery.SortDirection.ASCENDING) .list(); - assertEquals(getNumberTaskNotCompleted(workbaskets.get(0).getId()), 0); - assertEquals(getNumberTaskCompleted(workbaskets.get(0).getId()), 1); + assertEquals(getNumberTaskNotCompleted(workbaskets.get(0).getId()), 0); + assertEquals(getNumberTaskCompleted(workbaskets.get(0).getId()), 1); - // Workbasket with completed task will be marked for deletion. - workbasketService.deleteWorkbasket(workbaskets.get(0).getId()); + // Workbasket with completed task will be marked for deletion. + workbasketService.deleteWorkbasket(workbaskets.get(0).getId()); - // Run taskCleanupJob for deleting completing tasks before running workbasketCleanupJob - TaskCleanupJob taskCleanupJob = new TaskCleanupJob(taskanaEngine, null, null); - taskCleanupJob.run(); + // Run taskCleanupJob for deleting completing tasks before running workbasketCleanupJob + TaskCleanupJob taskCleanupJob = new TaskCleanupJob(taskanaEngine, null, null); + taskCleanupJob.run(); - assertEquals(getNumberTaskCompleted(workbaskets.get(0).getId()), 0); + assertEquals(getNumberTaskCompleted(workbaskets.get(0).getId()), 0); - WorkbasketCleanupJob workbasketCleanupJob = new WorkbasketCleanupJob(taskanaEngine, null, null); - workbasketCleanupJob.run(); + WorkbasketCleanupJob workbasketCleanupJob = new WorkbasketCleanupJob(taskanaEngine, null, null); + workbasketCleanupJob.run(); - totalWorkbasketCount = workbasketService.createWorkbasketQuery().count(); - assertEquals(24, totalWorkbasketCount); - } + totalWorkbasketCount = workbasketService.createWorkbasketQuery().count(); + assertEquals(24, totalWorkbasketCount); + } - @WithAccessId(userName = "admin") - @Test - void shouldNotCleanWorkbasketMarkedForDeletionIfWorkbasketHasTasks() throws Exception { - long totalWorkbasketCount = workbasketService.createWorkbasketQuery().count(); - assertEquals(25, totalWorkbasketCount); - List workbaskets = workbasketService.createWorkbasketQuery() + @WithAccessId(userName = "admin") + @Test + void shouldNotCleanWorkbasketMarkedForDeletionIfWorkbasketHasTasks() throws Exception { + long totalWorkbasketCount = workbasketService.createWorkbasketQuery().count(); + assertEquals(25, totalWorkbasketCount); + List workbaskets = + workbasketService + .createWorkbasketQuery() .keyIn("TEAMLEAD_1") - .orderByKey( - BaseQuery.SortDirection.ASCENDING) + .orderByKey(BaseQuery.SortDirection.ASCENDING) .list(); - assertNotEquals(getNumberTaskCompleted(workbaskets.get(0).getId()), 0); + assertNotEquals(getNumberTaskCompleted(workbaskets.get(0).getId()), 0); - // Workbasket with completed task will be marked for deletion. - workbasketService.deleteWorkbasket(workbaskets.get(0).getId()); + // Workbasket with completed task will be marked for deletion. + workbasketService.deleteWorkbasket(workbaskets.get(0).getId()); - WorkbasketCleanupJob job = new WorkbasketCleanupJob(taskanaEngine, null, null); - job.run(); + WorkbasketCleanupJob job = new WorkbasketCleanupJob(taskanaEngine, null, null); + job.run(); - totalWorkbasketCount = workbasketService.createWorkbasketQuery().count(); - assertEquals(25, totalWorkbasketCount); - } + totalWorkbasketCount = workbasketService.createWorkbasketQuery().count(); + assertEquals(25, totalWorkbasketCount); + } - private long getNumberTaskNotCompleted(String workbasketId) { - return taskService - .createTaskQuery() - .workbasketIdIn(workbasketId) - .stateNotIn( - TaskState.COMPLETED) - .count(); - } + private long getNumberTaskNotCompleted(String workbasketId) { + return taskService + .createTaskQuery() + .workbasketIdIn(workbasketId) + .stateNotIn(TaskState.COMPLETED) + .count(); + } - private long getNumberTaskCompleted(String workbasketId) { - return taskService - .createTaskQuery() - .workbasketIdIn(workbasketId) - .stateIn( - TaskState.COMPLETED) - .count(); - } + private long getNumberTaskCompleted(String workbasketId) { + return taskService + .createTaskQuery() + .workbasketIdIn(workbasketId) + .stateIn(TaskState.COMPLETED) + .count(); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/objectreference/QueryObjectReferenceAccTest.java b/lib/taskana-core/src/test/java/acceptance/objectreference/QueryObjectReferenceAccTest.java index a895bf3c0..a40bc22af 100644 --- a/lib/taskana-core/src/test/java/acceptance/objectreference/QueryObjectReferenceAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/objectreference/QueryObjectReferenceAccTest.java @@ -5,100 +5,94 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static pro.taskana.ObjectReferenceQueryColumnName.COMPANY; import static pro.taskana.ObjectReferenceQueryColumnName.SYSTEM; +import acceptance.AbstractAccTest; import java.util.List; - import org.junit.jupiter.api.Test; -import acceptance.AbstractAccTest; import pro.taskana.ObjectReference; import pro.taskana.TaskQuery; -/** - * Acceptance test for all "get classification" scenarios. - */ +/** Acceptance test for all "get classification" scenarios. */ class QueryObjectReferenceAccTest extends AbstractAccTest { - QueryObjectReferenceAccTest() { - super(); - } + QueryObjectReferenceAccTest() { + super(); + } - @Test - void testQueryObjectReferenceValuesForColumnName() { - TaskQuery taskQuery = taskanaEngine.getTaskService().createTaskQuery(); - List columnValues = taskQuery.createObjectReferenceQuery() - .listValues(COMPANY, null); - assertEquals(3, columnValues.size()); + @Test + void testQueryObjectReferenceValuesForColumnName() { + TaskQuery taskQuery = taskanaEngine.getTaskService().createTaskQuery(); + List columnValues = taskQuery.createObjectReferenceQuery().listValues(COMPANY, null); + assertEquals(3, columnValues.size()); - columnValues = taskQuery.createObjectReferenceQuery() - .listValues(SYSTEM, null); - assertEquals(3, columnValues.size()); + columnValues = taskQuery.createObjectReferenceQuery().listValues(SYSTEM, null); + assertEquals(3, columnValues.size()); - columnValues = taskQuery.createObjectReferenceQuery() - .systemIn("System1") - .listValues(SYSTEM, null); - assertEquals(1, columnValues.size()); - } + columnValues = + taskQuery.createObjectReferenceQuery().systemIn("System1").listValues(SYSTEM, null); + assertEquals(1, columnValues.size()); + } - @Test - void testFindObjectReferenceByCompany() { - TaskQuery taskQuery = taskanaEngine.getTaskService().createTaskQuery(); + @Test + void testFindObjectReferenceByCompany() { + TaskQuery taskQuery = taskanaEngine.getTaskService().createTaskQuery(); - List objectReferenceList = taskQuery.createObjectReferenceQuery() - .companyIn("Company1", "Company2") - .list(); + List objectReferenceList = + taskQuery.createObjectReferenceQuery().companyIn("Company1", "Company2").list(); - assertNotNull(objectReferenceList); - assertEquals(2, objectReferenceList.size()); - } + assertNotNull(objectReferenceList); + assertEquals(2, objectReferenceList.size()); + } - @Test - void testFindObjectReferenceBySystem() { - TaskQuery taskQuery = taskanaEngine.getTaskService().createTaskQuery(); + @Test + void testFindObjectReferenceBySystem() { + TaskQuery taskQuery = taskanaEngine.getTaskService().createTaskQuery(); - List objectReferenceList = taskQuery.createObjectReferenceQuery() + List objectReferenceList = + taskQuery + .createObjectReferenceQuery() .companyIn("Company1", "Company2") .systemIn("System2") .list(); - assertNotNull(objectReferenceList); - assertEquals(1, objectReferenceList.size()); - } + assertNotNull(objectReferenceList); + assertEquals(1, objectReferenceList.size()); + } - @Test - void testFindObjectReferenceBySystemInstance() { - TaskQuery taskQuery = taskanaEngine.getTaskService().createTaskQuery(); + @Test + void testFindObjectReferenceBySystemInstance() { + TaskQuery taskQuery = taskanaEngine.getTaskService().createTaskQuery(); - List objectReferenceList = taskQuery.createObjectReferenceQuery() + List objectReferenceList = + taskQuery + .createObjectReferenceQuery() .companyIn("Company1", "Company2") .systemInstanceIn("Instance1") .list(); - assertNotNull(objectReferenceList); - assertEquals(1, objectReferenceList.size()); - } + assertNotNull(objectReferenceList); + assertEquals(1, objectReferenceList.size()); + } - @Test - void testFindObjectReferenceByType() { - TaskQuery taskQuery = taskanaEngine.getTaskService().createTaskQuery(); + @Test + void testFindObjectReferenceByType() { + TaskQuery taskQuery = taskanaEngine.getTaskService().createTaskQuery(); - List objectReferenceList = taskQuery.createObjectReferenceQuery() - .typeIn("Type2", "Type3") - .list(); + List objectReferenceList = + taskQuery.createObjectReferenceQuery().typeIn("Type2", "Type3").list(); - assertNotNull(objectReferenceList); - assertEquals(2, objectReferenceList.size()); - } + assertNotNull(objectReferenceList); + assertEquals(2, objectReferenceList.size()); + } - @Test - void testFindObjectReferenceByValue() { - TaskQuery taskQuery = taskanaEngine.getTaskService().createTaskQuery(); + @Test + void testFindObjectReferenceByValue() { + TaskQuery taskQuery = taskanaEngine.getTaskService().createTaskQuery(); - List objectReferenceList = taskQuery.createObjectReferenceQuery() - .valueIn("Value1", "Value3") - .list(); - - assertNotNull(objectReferenceList); - assertEquals(2, objectReferenceList.size()); - } + List objectReferenceList = + taskQuery.createObjectReferenceQuery().valueIn("Value1", "Value3").list(); + assertNotNull(objectReferenceList); + assertEquals(2, objectReferenceList.size()); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/objectreference/QueryObjectreferencesWithPaginationAccTest.java b/lib/taskana-core/src/test/java/acceptance/objectreference/QueryObjectreferencesWithPaginationAccTest.java index 9fc56a118..d9916ae93 100644 --- a/lib/taskana-core/src/test/java/acceptance/objectreference/QueryObjectreferencesWithPaginationAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/objectreference/QueryObjectreferencesWithPaginationAccTest.java @@ -3,15 +3,14 @@ package acceptance.objectreference; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; +import acceptance.AbstractAccTest; import java.util.List; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.ObjectReference; import pro.taskana.ObjectReferenceQuery; import pro.taskana.TaskQuery; @@ -19,121 +18,119 @@ import pro.taskana.TaskService; import pro.taskana.exceptions.TaskanaRuntimeException; import pro.taskana.security.JAASExtension; -/** - * Acceptance test for all "query classifications with pagination" scenarios. - */ +/** Acceptance test for all "query classifications with pagination" scenarios. */ @ExtendWith(JAASExtension.class) class QueryObjectreferencesWithPaginationAccTest extends AbstractAccTest { - private TaskService taskService; - private TaskQuery taskQuery; - private ObjectReferenceQuery objRefQuery; + private TaskService taskService; + private TaskQuery taskQuery; + private ObjectReferenceQuery objRefQuery; - QueryObjectreferencesWithPaginationAccTest() { - super(); - } + QueryObjectreferencesWithPaginationAccTest() { + super(); + } - @BeforeEach - void before() { - taskService = taskanaEngine.getTaskService(); - taskQuery = taskService.createTaskQuery(); - objRefQuery = taskQuery.createObjectReferenceQuery(); - } + @BeforeEach + void before() { + taskService = taskanaEngine.getTaskService(); + taskQuery = taskService.createTaskQuery(); + objRefQuery = taskQuery.createObjectReferenceQuery(); + } - @Test - void testGetFirstPageOfObjectRefQueryWithOffset() { + @Test + void testGetFirstPageOfObjectRefQueryWithOffset() { - List results = objRefQuery.list(0, 5); - assertThat(results.size(), equalTo(3)); - } + List results = objRefQuery.list(0, 5); + assertThat(results.size(), equalTo(3)); + } - @Test - void testGetSecondPageOfObjectRefQueryWithOffset() { - List results = objRefQuery.list(2, 5); - assertThat(results.size(), equalTo(1)); - } + @Test + void testGetSecondPageOfObjectRefQueryWithOffset() { + List results = objRefQuery.list(2, 5); + assertThat(results.size(), equalTo(1)); + } - @Test - void testListOffsetAndLimitOutOfBounds() { - // both will be 0, working - List results = objRefQuery.list(-1, -3); - assertThat(results.size(), equalTo(0)); + @Test + void testListOffsetAndLimitOutOfBounds() { + // both will be 0, working + List results = objRefQuery.list(-1, -3); + assertThat(results.size(), equalTo(0)); - // limit will be 0 - results = objRefQuery.list(1, -3); - assertThat(results.size(), equalTo(0)); + // limit will be 0 + results = objRefQuery.list(1, -3); + assertThat(results.size(), equalTo(0)); - // offset will be 0 - results = objRefQuery.list(-1, 3); - assertThat(results.size(), equalTo(3)); - } + // offset will be 0 + results = objRefQuery.list(-1, 3); + assertThat(results.size(), equalTo(3)); + } - @Test - void testPaginationWithPages() { - // Getting full page - int pageNumber = 1; - int pageSize = 10; - List results = objRefQuery.listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(3)); + @Test + void testPaginationWithPages() { + // Getting full page + int pageNumber = 1; + int pageSize = 10; + List results = objRefQuery.listPage(pageNumber, pageSize); + assertThat(results.size(), equalTo(3)); - // Getting full page - pageNumber = 2; - pageSize = 2; - results = objRefQuery.listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(1)); + // Getting full page + pageNumber = 2; + pageSize = 2; + results = objRefQuery.listPage(pageNumber, pageSize); + assertThat(results.size(), equalTo(1)); - // Getting last results on 1 big page - pageNumber = 1; - pageSize = 100; - results = objRefQuery.listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(3)); + // Getting last results on 1 big page + pageNumber = 1; + pageSize = 100; + results = objRefQuery.listPage(pageNumber, pageSize); + assertThat(results.size(), equalTo(3)); - // Getting last results on multiple pages - pageNumber = 2; - pageSize = 2; - results = objRefQuery.listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(1)); - } + // Getting last results on multiple pages + pageNumber = 2; + pageSize = 2; + results = objRefQuery.listPage(pageNumber, pageSize); + assertThat(results.size(), equalTo(1)); + } - @Test - void testPaginationNullAndNegativeLimitsIgnoring() { - // 0 limit/size = 0 results - int pageNumber = 2; - int pageSize = 0; - List results = objRefQuery.listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(0)); + @Test + void testPaginationNullAndNegativeLimitsIgnoring() { + // 0 limit/size = 0 results + int pageNumber = 2; + int pageSize = 0; + List results = objRefQuery.listPage(pageNumber, pageSize); + assertThat(results.size(), equalTo(0)); - // Negative will be 0 = all results - pageNumber = 2; - pageSize = -1; - results = objRefQuery.listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(0)); + // Negative will be 0 = all results + pageNumber = 2; + pageSize = -1; + results = objRefQuery.listPage(pageNumber, pageSize); + assertThat(results.size(), equalTo(0)); - // Negative page = first page - pageNumber = -1; - pageSize = 10; - results = objRefQuery.listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(3)); - } + // Negative page = first page + pageNumber = -1; + pageSize = 10; + results = objRefQuery.listPage(pageNumber, pageSize); + assertThat(results.size(), equalTo(3)); + } - /** - * Testcase only for DB2 users, because H2 doesn´t throw a Exception when the offset is set to high.
- * Using DB2 should throw a unchecked RuntimeException for a offset which is out of bounds. - */ - @Disabled - @Test - void testPaginationThrowingExceptionWhenPageOutOfBounds() { - // entrypoint set outside result amount - int pageNumber = 6; - int pageSize = 10; - Assertions.assertThrows(TaskanaRuntimeException.class, () -> - objRefQuery.listPage(pageNumber, pageSize)); - } - - @Test - void testCountOfClassificationsQuery() { - long count = objRefQuery.count(); - assertThat(count, equalTo(3L)); - } + /** + * Testcase only for DB2 users, because H2 doesn´t throw a Exception when the offset is set to + * high.
+ * Using DB2 should throw a unchecked RuntimeException for a offset which is out of bounds. + */ + @Disabled + @Test + void testPaginationThrowingExceptionWhenPageOutOfBounds() { + // entrypoint set outside result amount + int pageNumber = 6; + int pageSize = 10; + Assertions.assertThrows( + TaskanaRuntimeException.class, () -> objRefQuery.listPage(pageNumber, pageSize)); + } + @Test + void testCountOfClassificationsQuery() { + long count = objRefQuery.count(); + assertThat(count, equalTo(3L)); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/report/AbstractReportAccTest.java b/lib/taskana-core/src/test/java/acceptance/report/AbstractReportAccTest.java index 8bc6c241a..6a4077143 100644 --- a/lib/taskana-core/src/test/java/acceptance/report/AbstractReportAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/report/AbstractReportAccTest.java @@ -1,9 +1,7 @@ package acceptance.report; import java.sql.SQLException; - import javax.sql.DataSource; - import org.junit.jupiter.api.BeforeAll; import pro.taskana.TaskanaEngine; @@ -11,33 +9,29 @@ import pro.taskana.configuration.TaskanaEngineConfiguration; import pro.taskana.impl.configuration.TaskanaEngineTestConfiguration; import pro.taskana.sampledata.SampleDataGenerator; -/** - * Abstract test class for all report building tests. - */ +/** Abstract test class for all report building tests. */ public class AbstractReportAccTest { - protected static TaskanaEngineConfiguration taskanaEngineConfiguration; - protected static TaskanaEngine taskanaEngine; + protected static TaskanaEngineConfiguration taskanaEngineConfiguration; + protected static TaskanaEngine taskanaEngine; - // checkstyle needs this constructor, since this is only a "utility" class - protected AbstractReportAccTest() { - } + // checkstyle needs this constructor, since this is only a "utility" class + protected AbstractReportAccTest() {} - @BeforeAll - public static void setupTest() throws Exception { - resetDb(); - } + @BeforeAll + public static void setupTest() throws Exception { + resetDb(); + } - private static void resetDb() throws SQLException { - DataSource dataSource = TaskanaEngineTestConfiguration.getDataSource(); - String schemaName = TaskanaEngineTestConfiguration.getSchemaName(); - SampleDataGenerator sampleDataGenerator = new SampleDataGenerator(dataSource, schemaName); - taskanaEngineConfiguration = new TaskanaEngineConfiguration(dataSource, false, - schemaName); - taskanaEngineConfiguration.setGermanPublicHolidaysEnabled(false); - taskanaEngine = taskanaEngineConfiguration.buildTaskanaEngine(); - taskanaEngine.setConnectionManagementMode(TaskanaEngine.ConnectionManagementMode.AUTOCOMMIT); - sampleDataGenerator.clearDb(); - sampleDataGenerator.generateMonitorData(); - } + private static void resetDb() throws SQLException { + DataSource dataSource = TaskanaEngineTestConfiguration.getDataSource(); + String schemaName = TaskanaEngineTestConfiguration.getSchemaName(); + SampleDataGenerator sampleDataGenerator = new SampleDataGenerator(dataSource, schemaName); + taskanaEngineConfiguration = new TaskanaEngineConfiguration(dataSource, false, schemaName); + taskanaEngineConfiguration.setGermanPublicHolidaysEnabled(false); + taskanaEngine = taskanaEngineConfiguration.buildTaskanaEngine(); + taskanaEngine.setConnectionManagementMode(TaskanaEngine.ConnectionManagementMode.AUTOCOMMIT); + sampleDataGenerator.clearDb(); + sampleDataGenerator.generateMonitorData(); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/report/GetCustomAttributeValuesForReportAccTest.java b/lib/taskana-core/src/test/java/acceptance/report/GetCustomAttributeValuesForReportAccTest.java index a9dc08a6c..126fa9c5b 100644 --- a/lib/taskana-core/src/test/java/acceptance/report/GetCustomAttributeValuesForReportAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/report/GetCustomAttributeValuesForReportAccTest.java @@ -9,7 +9,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -20,89 +19,91 @@ import pro.taskana.exceptions.NotAuthorizedException; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "classification report" scenarios. - */ +/** Acceptance test for all "classification report" scenarios. */ @ExtendWith(JAASExtension.class) class GetCustomAttributeValuesForReportAccTest extends AbstractReportAccTest { - @Test - void testRoleCheck() { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @Test + void testRoleCheck() { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - Assertions.assertThrows(NotAuthorizedException.class, () -> - taskMonitorService.createWorkbasketReportBuilder() + Assertions.assertThrows( + NotAuthorizedException.class, + () -> + taskMonitorService + .createWorkbasketReportBuilder() .listCustomAttributeValuesForCustomAttributeName(CustomField.CUSTOM_2)); + } - } + @WithAccessId(userName = "monitor") + @Test + void testGetCustomAttributeValuesForOneWorkbasket() throws NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - @WithAccessId( - userName = "monitor") - @Test - void testGetCustomAttributeValuesForOneWorkbasket() throws NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - - List values = taskMonitorService.createWorkbasketReportBuilder() + List values = + taskMonitorService + .createWorkbasketReportBuilder() .workbasketIdIn(Collections.singletonList("WBI:000000000000000000000000000000000001")) .listCustomAttributeValuesForCustomAttributeName(CustomField.CUSTOM_2); - assertNotNull(values); - assertEquals(2, values.size()); - assertTrue(values.contains("Vollkasko")); - assertTrue(values.contains("Teilkasko")); - } + assertNotNull(values); + assertEquals(2, values.size()); + assertTrue(values.contains("Vollkasko")); + assertTrue(values.contains("Teilkasko")); + } - @WithAccessId( - userName = "monitor") - @Test - void testGetCustomAttributeValuesForOneDomain() throws NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @WithAccessId(userName = "monitor") + @Test + void testGetCustomAttributeValuesForOneDomain() throws NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - List values = taskMonitorService.createWorkbasketReportBuilder() + List values = + taskMonitorService + .createWorkbasketReportBuilder() .domainIn(Collections.singletonList("DOMAIN_A")) .listCustomAttributeValuesForCustomAttributeName(CustomField.CUSTOM_16); - assertNotNull(values); - assertEquals(26, values.size()); - } + assertNotNull(values); + assertEquals(26, values.size()); + } - @WithAccessId( - userName = "monitor") - @Test - void testGetCustomAttributeValuesForCustomAttribute() - throws NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @WithAccessId(userName = "monitor") + @Test + void testGetCustomAttributeValuesForCustomAttribute() throws NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - Map customAttributeFilter = new HashMap<>(); - customAttributeFilter.put(CustomField.CUSTOM_2, "Vollkasko"); - customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); + Map customAttributeFilter = new HashMap<>(); + customAttributeFilter.put(CustomField.CUSTOM_2, "Vollkasko"); + customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); - List values = taskMonitorService.createCategoryReportBuilder() + List values = + taskMonitorService + .createCategoryReportBuilder() .customAttributeFilterIn(customAttributeFilter) .listCustomAttributeValuesForCustomAttributeName(CustomField.CUSTOM_16); - assertNotNull(values); - assertEquals(12, values.size()); - } + assertNotNull(values); + assertEquals(12, values.size()); + } - @WithAccessId( - userName = "monitor") - @Test - void testGetCustomAttributeValuesForExcludedClassifications() - throws NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @WithAccessId(userName = "monitor") + @Test + void testGetCustomAttributeValuesForExcludedClassifications() throws NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - List domains = new ArrayList<>(); - domains.add("DOMAIN_A"); - domains.add("DOMAIN_B"); - domains.add("DOMAIN_C"); + List domains = new ArrayList<>(); + domains.add("DOMAIN_A"); + domains.add("DOMAIN_B"); + domains.add("DOMAIN_C"); - List values = taskMonitorService.createCategoryReportBuilder() + List values = + taskMonitorService + .createCategoryReportBuilder() .domainIn(domains) - .excludedClassificationIdIn(Collections.singletonList("CLI:000000000000000000000000000000000003")) + .excludedClassificationIdIn( + Collections.singletonList("CLI:000000000000000000000000000000000003")) .listCustomAttributeValuesForCustomAttributeName(CustomField.CUSTOM_16); - assertNotNull(values); - assertEquals(43, values.size()); - } - + assertNotNull(values); + assertEquals(43, values.size()); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/report/GetTaskIdsOfCategoryReportAccTest.java b/lib/taskana-core/src/test/java/acceptance/report/GetTaskIdsOfCategoryReportAccTest.java index 64bc5a26b..a8052ce72 100644 --- a/lib/taskana-core/src/test/java/acceptance/report/GetTaskIdsOfCategoryReportAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/report/GetTaskIdsOfCategoryReportAccTest.java @@ -9,7 +9,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -24,324 +23,333 @@ import pro.taskana.impl.report.header.TimeIntervalColumnHeader; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "get task ids of category report" scenarios. - */ +/** Acceptance test for all "get task ids of category report" scenarios. */ @ExtendWith(JAASExtension.class) class GetTaskIdsOfCategoryReportAccTest extends AbstractReportAccTest { - @Test - void testRoleCheck() { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @Test + void testRoleCheck() { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - List columnHeaders = getListOfColumnHeaders(); + List columnHeaders = getListOfColumnHeaders(); - List selectedItems = new ArrayList<>(); + List selectedItems = new ArrayList<>(); - Assertions.assertThrows(NotAuthorizedException.class, () -> - taskMonitorService.createCategoryReportBuilder().listTaskIdsForSelectedItems(selectedItems)); - } + Assertions.assertThrows( + NotAuthorizedException.class, + () -> + taskMonitorService + .createCategoryReportBuilder() + .listTaskIdsForSelectedItems(selectedItems)); + } - @WithAccessId( - userName = "monitor") - @Test - void testGetTaskIdsOfCategoryReport() throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @WithAccessId(userName = "monitor") + @Test + void testGetTaskIdsOfCategoryReport() throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - List columnHeaders = getListOfColumnHeaders(); + List columnHeaders = getListOfColumnHeaders(); - List selectedItems = new ArrayList<>(); + List selectedItems = new ArrayList<>(); - SelectedItem s1 = new SelectedItem(); - s1.setKey("EXTERN"); - s1.setLowerAgeLimit(-5); - s1.setUpperAgeLimit(-2); - selectedItems.add(s1); + SelectedItem s1 = new SelectedItem(); + s1.setKey("EXTERN"); + s1.setLowerAgeLimit(-5); + s1.setUpperAgeLimit(-2); + selectedItems.add(s1); - SelectedItem s2 = new SelectedItem(); - s2.setKey("AUTOMATIC"); - s2.setLowerAgeLimit(Integer.MIN_VALUE); - s2.setUpperAgeLimit(-11); - selectedItems.add(s2); + SelectedItem s2 = new SelectedItem(); + s2.setKey("AUTOMATIC"); + s2.setLowerAgeLimit(Integer.MIN_VALUE); + s2.setUpperAgeLimit(-11); + selectedItems.add(s2); - SelectedItem s3 = new SelectedItem(); - s3.setKey("MANUAL"); - s3.setLowerAgeLimit(0); - s3.setUpperAgeLimit(0); - selectedItems.add(s3); + SelectedItem s3 = new SelectedItem(); + s3.setKey("MANUAL"); + s3.setLowerAgeLimit(0); + s3.setUpperAgeLimit(0); + selectedItems.add(s3); - List ids = taskMonitorService.createCategoryReportBuilder() + List ids = + taskMonitorService + .createCategoryReportBuilder() .withColumnHeaders(columnHeaders) .inWorkingDays() .listTaskIdsForSelectedItems(selectedItems); - assertEquals(11, ids.size()); - assertTrue(ids.contains("TKI:000000000000000000000000000000000006")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000020")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000021")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000022")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000023")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000024")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000026")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000027")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000028")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000031")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000032")); - } + assertEquals(11, ids.size()); + assertTrue(ids.contains("TKI:000000000000000000000000000000000006")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000020")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000021")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000022")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000023")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000024")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000026")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000027")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000028")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000031")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000032")); + } - @WithAccessId( - userName = "monitor") - @Test - void testGetTaskIdsOfCategoryReportWithWorkbasketFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @WithAccessId(userName = "monitor") + @Test + void testGetTaskIdsOfCategoryReportWithWorkbasketFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - List workbasketIds = Collections.singletonList("WBI:000000000000000000000000000000000001"); - List columnHeaders = getListOfColumnHeaders(); + List workbasketIds = + Collections.singletonList("WBI:000000000000000000000000000000000001"); + List columnHeaders = getListOfColumnHeaders(); - List selectedItems = new ArrayList<>(); + List selectedItems = new ArrayList<>(); - SelectedItem s1 = new SelectedItem(); - s1.setKey("EXTERN"); - s1.setLowerAgeLimit(-5); - s1.setUpperAgeLimit(-2); - selectedItems.add(s1); + SelectedItem s1 = new SelectedItem(); + s1.setKey("EXTERN"); + s1.setLowerAgeLimit(-5); + s1.setUpperAgeLimit(-2); + selectedItems.add(s1); - SelectedItem s2 = new SelectedItem(); - s2.setKey("AUTOMATIC"); - s2.setLowerAgeLimit(Integer.MIN_VALUE); - s2.setUpperAgeLimit(-11); - selectedItems.add(s2); + SelectedItem s2 = new SelectedItem(); + s2.setKey("AUTOMATIC"); + s2.setLowerAgeLimit(Integer.MIN_VALUE); + s2.setUpperAgeLimit(-11); + selectedItems.add(s2); - SelectedItem s3 = new SelectedItem(); - s3.setKey("MANUAL"); - s3.setLowerAgeLimit(0); - s3.setUpperAgeLimit(0); - selectedItems.add(s3); + SelectedItem s3 = new SelectedItem(); + s3.setKey("MANUAL"); + s3.setLowerAgeLimit(0); + s3.setUpperAgeLimit(0); + selectedItems.add(s3); - List ids = taskMonitorService.createCategoryReportBuilder() + List ids = + taskMonitorService + .createCategoryReportBuilder() .withColumnHeaders(columnHeaders) .inWorkingDays() .workbasketIdIn(workbasketIds) .listTaskIdsForSelectedItems(selectedItems); - assertEquals(4, ids.size()); - assertTrue(ids.contains("TKI:000000000000000000000000000000000006")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000020")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000026")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000031")); - } + assertEquals(4, ids.size()); + assertTrue(ids.contains("TKI:000000000000000000000000000000000006")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000020")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000026")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000031")); + } - @WithAccessId( - userName = "monitor") - @Test - void testGetTaskIdsOfCategoryReportWithStateFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @WithAccessId(userName = "monitor") + @Test + void testGetTaskIdsOfCategoryReportWithStateFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - List states = Collections.singletonList(TaskState.READY); - List columnHeaders = getListOfColumnHeaders(); + List states = Collections.singletonList(TaskState.READY); + List columnHeaders = getListOfColumnHeaders(); - List selectedItems = new ArrayList<>(); + List selectedItems = new ArrayList<>(); - SelectedItem s1 = new SelectedItem(); - s1.setKey("EXTERN"); - s1.setLowerAgeLimit(-5); - s1.setUpperAgeLimit(-2); - selectedItems.add(s1); + SelectedItem s1 = new SelectedItem(); + s1.setKey("EXTERN"); + s1.setLowerAgeLimit(-5); + s1.setUpperAgeLimit(-2); + selectedItems.add(s1); - SelectedItem s2 = new SelectedItem(); - s2.setKey("AUTOMATIC"); - s2.setLowerAgeLimit(Integer.MIN_VALUE); - s2.setUpperAgeLimit(-11); - selectedItems.add(s2); + SelectedItem s2 = new SelectedItem(); + s2.setKey("AUTOMATIC"); + s2.setLowerAgeLimit(Integer.MIN_VALUE); + s2.setUpperAgeLimit(-11); + selectedItems.add(s2); - SelectedItem s3 = new SelectedItem(); - s3.setKey("MANUAL"); - s3.setLowerAgeLimit(0); - s3.setUpperAgeLimit(0); - selectedItems.add(s3); + SelectedItem s3 = new SelectedItem(); + s3.setKey("MANUAL"); + s3.setLowerAgeLimit(0); + s3.setUpperAgeLimit(0); + selectedItems.add(s3); - List ids = taskMonitorService.createCategoryReportBuilder() + List ids = + taskMonitorService + .createCategoryReportBuilder() .withColumnHeaders(columnHeaders) .inWorkingDays() .stateIn(states) .listTaskIdsForSelectedItems(selectedItems); - assertEquals(11, ids.size()); - assertTrue(ids.contains("TKI:000000000000000000000000000000000006")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000020")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000021")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000022")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000023")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000024")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000026")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000027")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000028")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000031")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000032")); - } + assertEquals(11, ids.size()); + assertTrue(ids.contains("TKI:000000000000000000000000000000000006")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000020")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000021")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000022")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000023")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000024")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000026")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000027")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000028")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000031")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000032")); + } - @WithAccessId( - userName = "monitor") - @Test - void testGetTaskIdsOfCategoryReportWithCategoryFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @WithAccessId(userName = "monitor") + @Test + void testGetTaskIdsOfCategoryReportWithCategoryFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - List categories = Arrays.asList("AUTOMATIC", "MANUAL"); - List columnHeaders = getListOfColumnHeaders(); + List categories = Arrays.asList("AUTOMATIC", "MANUAL"); + List columnHeaders = getListOfColumnHeaders(); - List selectedItems = new ArrayList<>(); + List selectedItems = new ArrayList<>(); - SelectedItem s1 = new SelectedItem(); - s1.setKey("AUTOMATIC"); - s1.setLowerAgeLimit(Integer.MIN_VALUE); - s1.setUpperAgeLimit(-11); - selectedItems.add(s1); + SelectedItem s1 = new SelectedItem(); + s1.setKey("AUTOMATIC"); + s1.setLowerAgeLimit(Integer.MIN_VALUE); + s1.setUpperAgeLimit(-11); + selectedItems.add(s1); - SelectedItem s2 = new SelectedItem(); - s2.setKey("MANUAL"); - s2.setLowerAgeLimit(0); - s2.setUpperAgeLimit(0); - selectedItems.add(s2); + SelectedItem s2 = new SelectedItem(); + s2.setKey("MANUAL"); + s2.setLowerAgeLimit(0); + s2.setUpperAgeLimit(0); + selectedItems.add(s2); - List ids = taskMonitorService.createCategoryReportBuilder() + List ids = + taskMonitorService + .createCategoryReportBuilder() .withColumnHeaders(columnHeaders) .inWorkingDays() .categoryIn(categories) .listTaskIdsForSelectedItems(selectedItems); - assertEquals(3, ids.size()); - assertTrue(ids.contains("TKI:000000000000000000000000000000000006")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000031")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000032")); - } + assertEquals(3, ids.size()); + assertTrue(ids.contains("TKI:000000000000000000000000000000000006")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000031")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000032")); + } - @WithAccessId( - userName = "monitor") - @Test - void testGetTaskIdsOfCategoryReportWithDomainFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @WithAccessId(userName = "monitor") + @Test + void testGetTaskIdsOfCategoryReportWithDomainFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - List domains = Collections.singletonList("DOMAIN_A"); - List columnHeaders = getListOfColumnHeaders(); + List domains = Collections.singletonList("DOMAIN_A"); + List columnHeaders = getListOfColumnHeaders(); - List selectedItems = new ArrayList<>(); + List selectedItems = new ArrayList<>(); - SelectedItem s1 = new SelectedItem(); - s1.setKey("EXTERN"); - s1.setLowerAgeLimit(-5); - s1.setUpperAgeLimit(-2); - selectedItems.add(s1); + SelectedItem s1 = new SelectedItem(); + s1.setKey("EXTERN"); + s1.setLowerAgeLimit(-5); + s1.setUpperAgeLimit(-2); + selectedItems.add(s1); - SelectedItem s2 = new SelectedItem(); - s2.setKey("AUTOMATIC"); - s2.setLowerAgeLimit(Integer.MIN_VALUE); - s2.setUpperAgeLimit(-11); - selectedItems.add(s2); + SelectedItem s2 = new SelectedItem(); + s2.setKey("AUTOMATIC"); + s2.setLowerAgeLimit(Integer.MIN_VALUE); + s2.setUpperAgeLimit(-11); + selectedItems.add(s2); - SelectedItem s3 = new SelectedItem(); - s3.setKey("MANUAL"); - s3.setLowerAgeLimit(0); - s3.setUpperAgeLimit(0); - selectedItems.add(s3); + SelectedItem s3 = new SelectedItem(); + s3.setKey("MANUAL"); + s3.setLowerAgeLimit(0); + s3.setUpperAgeLimit(0); + selectedItems.add(s3); - List ids = taskMonitorService.createCategoryReportBuilder() + List ids = + taskMonitorService + .createCategoryReportBuilder() .withColumnHeaders(columnHeaders) .inWorkingDays() .domainIn(domains) .listTaskIdsForSelectedItems(selectedItems); - assertEquals(4, ids.size()); - assertTrue(ids.contains("TKI:000000000000000000000000000000000020")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000021")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000022")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000028")); - } + assertEquals(4, ids.size()); + assertTrue(ids.contains("TKI:000000000000000000000000000000000020")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000021")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000022")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000028")); + } - @WithAccessId( - userName = "monitor") - @Test - void testGetTaskIdsOfCategoryReportWithCustomFieldValueFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @WithAccessId(userName = "monitor") + @Test + void testGetTaskIdsOfCategoryReportWithCustomFieldValueFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - Map customAttributeFilter = new HashMap<>(); - customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); - List columnHeaders = getListOfColumnHeaders(); + Map customAttributeFilter = new HashMap<>(); + customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); + List columnHeaders = getListOfColumnHeaders(); - List selectedItems = new ArrayList<>(); + List selectedItems = new ArrayList<>(); - SelectedItem s1 = new SelectedItem(); - s1.setKey("EXTERN"); - s1.setLowerAgeLimit(-5); - s1.setUpperAgeLimit(-2); - selectedItems.add(s1); + SelectedItem s1 = new SelectedItem(); + s1.setKey("EXTERN"); + s1.setLowerAgeLimit(-5); + s1.setUpperAgeLimit(-2); + selectedItems.add(s1); - SelectedItem s2 = new SelectedItem(); - s2.setKey("AUTOMATIC"); - s2.setLowerAgeLimit(Integer.MIN_VALUE); - s2.setUpperAgeLimit(-11); - selectedItems.add(s2); + SelectedItem s2 = new SelectedItem(); + s2.setKey("AUTOMATIC"); + s2.setLowerAgeLimit(Integer.MIN_VALUE); + s2.setUpperAgeLimit(-11); + selectedItems.add(s2); - SelectedItem s3 = new SelectedItem(); - s3.setKey("MANUAL"); - s3.setLowerAgeLimit(0); - s3.setUpperAgeLimit(0); - selectedItems.add(s3); + SelectedItem s3 = new SelectedItem(); + s3.setKey("MANUAL"); + s3.setLowerAgeLimit(0); + s3.setUpperAgeLimit(0); + selectedItems.add(s3); - List ids = taskMonitorService.createCategoryReportBuilder() + List ids = + taskMonitorService + .createCategoryReportBuilder() .withColumnHeaders(columnHeaders) .inWorkingDays() .customAttributeFilterIn(customAttributeFilter) .listTaskIdsForSelectedItems(selectedItems); - assertEquals(5, ids.size()); - assertTrue(ids.contains("TKI:000000000000000000000000000000000020")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000024")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000027")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000031")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000032")); - } + assertEquals(5, ids.size()); + assertTrue(ids.contains("TKI:000000000000000000000000000000000020")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000024")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000027")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000031")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000032")); + } - @WithAccessId( - userName = "monitor") - @Test - void testThrowsExceptionIfSubKeysAreUsed() { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @WithAccessId(userName = "monitor") + @Test + void testThrowsExceptionIfSubKeysAreUsed() { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - List columnHeaders = getListOfColumnHeaders(); + List columnHeaders = getListOfColumnHeaders(); - List selectedItems = new ArrayList<>(); + List selectedItems = new ArrayList<>(); - SelectedItem s1 = new SelectedItem(); - s1.setKey("EXTERN"); - s1.setSubKey("INVALID"); - s1.setLowerAgeLimit(-5); - s1.setUpperAgeLimit(-2); - selectedItems.add(s1); + SelectedItem s1 = new SelectedItem(); + s1.setKey("EXTERN"); + s1.setSubKey("INVALID"); + s1.setLowerAgeLimit(-5); + s1.setUpperAgeLimit(-2); + selectedItems.add(s1); - Assertions.assertThrows(InvalidArgumentException.class, () -> - taskMonitorService.createCategoryReportBuilder() + Assertions.assertThrows( + InvalidArgumentException.class, + () -> + taskMonitorService + .createCategoryReportBuilder() .withColumnHeaders(columnHeaders) - .listTaskIdsForSelectedItems( - selectedItems)); - } - - private List getListOfColumnHeaders() { - List columnHeaders = new ArrayList<>(); - columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -11)); - columnHeaders.add(new TimeIntervalColumnHeader(-10, -6)); - columnHeaders.add(new TimeIntervalColumnHeader(-5, -2)); - columnHeaders.add(new TimeIntervalColumnHeader(-1)); - columnHeaders.add(new TimeIntervalColumnHeader(0)); - columnHeaders.add(new TimeIntervalColumnHeader(1)); - columnHeaders.add(new TimeIntervalColumnHeader(2, 5)); - columnHeaders.add(new TimeIntervalColumnHeader(6, 10)); - columnHeaders.add(new TimeIntervalColumnHeader(11, Integer.MAX_VALUE)); - return columnHeaders; - } + .listTaskIdsForSelectedItems(selectedItems)); + } + private List getListOfColumnHeaders() { + List columnHeaders = new ArrayList<>(); + columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -11)); + columnHeaders.add(new TimeIntervalColumnHeader(-10, -6)); + columnHeaders.add(new TimeIntervalColumnHeader(-5, -2)); + columnHeaders.add(new TimeIntervalColumnHeader(-1)); + columnHeaders.add(new TimeIntervalColumnHeader(0)); + columnHeaders.add(new TimeIntervalColumnHeader(1)); + columnHeaders.add(new TimeIntervalColumnHeader(2, 5)); + columnHeaders.add(new TimeIntervalColumnHeader(6, 10)); + columnHeaders.add(new TimeIntervalColumnHeader(11, Integer.MAX_VALUE)); + return columnHeaders; + } } diff --git a/lib/taskana-core/src/test/java/acceptance/report/GetTaskIdsOfClassificationReportAccTest.java b/lib/taskana-core/src/test/java/acceptance/report/GetTaskIdsOfClassificationReportAccTest.java index 3e8be8d4a..ed877bb7e 100644 --- a/lib/taskana-core/src/test/java/acceptance/report/GetTaskIdsOfClassificationReportAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/report/GetTaskIdsOfClassificationReportAccTest.java @@ -5,7 +5,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.List; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -18,180 +17,185 @@ import pro.taskana.impl.report.header.TimeIntervalColumnHeader; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "get task ids of classification report" scenarios. - */ +/** Acceptance test for all "get task ids of classification report" scenarios. */ @ExtendWith(JAASExtension.class) class GetTaskIdsOfClassificationReportAccTest extends AbstractReportAccTest { - @Test - void testRoleCheck() { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @Test + void testRoleCheck() { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - List selectedItems = new ArrayList<>(); + List selectedItems = new ArrayList<>(); - SelectedItem s1 = new SelectedItem(); - s1.setKey("L10000"); - s1.setLowerAgeLimit(0); - s1.setUpperAgeLimit(0); - selectedItems.add(s1); + SelectedItem s1 = new SelectedItem(); + s1.setKey("L10000"); + s1.setLowerAgeLimit(0); + s1.setUpperAgeLimit(0); + selectedItems.add(s1); - SelectedItem s2 = new SelectedItem(); - s2.setKey("L10000"); - s2.setLowerAgeLimit(Integer.MIN_VALUE); - s2.setUpperAgeLimit(-11); - selectedItems.add(s2); + SelectedItem s2 = new SelectedItem(); + s2.setKey("L10000"); + s2.setLowerAgeLimit(Integer.MIN_VALUE); + s2.setUpperAgeLimit(-11); + selectedItems.add(s2); - SelectedItem s3 = new SelectedItem(); - s3.setKey("L30000"); - s3.setLowerAgeLimit(Integer.MIN_VALUE); - s3.setUpperAgeLimit(-11); - selectedItems.add(s3); + SelectedItem s3 = new SelectedItem(); + s3.setKey("L30000"); + s3.setLowerAgeLimit(Integer.MIN_VALUE); + s3.setUpperAgeLimit(-11); + selectedItems.add(s3); - Assertions.assertThrows(NotAuthorizedException.class, () -> - taskMonitorService.createClassificationReportBuilder().listTaskIdsForSelectedItems(selectedItems)); - } + Assertions.assertThrows( + NotAuthorizedException.class, + () -> + taskMonitorService + .createClassificationReportBuilder() + .listTaskIdsForSelectedItems(selectedItems)); + } - @WithAccessId( - userName = "monitor") - @Test - void testGetTaskIdsOfClassificationReport() throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @WithAccessId(userName = "monitor") + @Test + void testGetTaskIdsOfClassificationReport() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - List columnHeaders = getListOfColumnHeaders(); + List columnHeaders = getListOfColumnHeaders(); - List selectedItems = new ArrayList<>(); + List selectedItems = new ArrayList<>(); - SelectedItem s1 = new SelectedItem(); - s1.setKey("L10000"); - s1.setLowerAgeLimit(0); - s1.setUpperAgeLimit(0); - selectedItems.add(s1); + SelectedItem s1 = new SelectedItem(); + s1.setKey("L10000"); + s1.setLowerAgeLimit(0); + s1.setUpperAgeLimit(0); + selectedItems.add(s1); - SelectedItem s2 = new SelectedItem(); - s2.setKey("L10000"); - s2.setLowerAgeLimit(Integer.MIN_VALUE); - s2.setUpperAgeLimit(-11); - selectedItems.add(s2); + SelectedItem s2 = new SelectedItem(); + s2.setKey("L10000"); + s2.setLowerAgeLimit(Integer.MIN_VALUE); + s2.setUpperAgeLimit(-11); + selectedItems.add(s2); - SelectedItem s3 = new SelectedItem(); - s3.setKey("L30000"); - s3.setLowerAgeLimit(Integer.MIN_VALUE); - s3.setUpperAgeLimit(-11); - selectedItems.add(s3); + SelectedItem s3 = new SelectedItem(); + s3.setKey("L30000"); + s3.setLowerAgeLimit(Integer.MIN_VALUE); + s3.setUpperAgeLimit(-11); + selectedItems.add(s3); - List ids = taskMonitorService.createClassificationReportBuilder() + List ids = + taskMonitorService + .createClassificationReportBuilder() .withColumnHeaders(columnHeaders) .inWorkingDays() .listTaskIdsForSelectedItems(selectedItems); - assertEquals(6, ids.size()); - assertTrue(ids.contains("TKI:000000000000000000000000000000000001")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000004")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000007")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000010")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000033")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000006")); - } + assertEquals(6, ids.size()); + assertTrue(ids.contains("TKI:000000000000000000000000000000000001")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000004")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000007")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000010")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000033")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000006")); + } - @WithAccessId( - userName = "monitor") - @Test - void testGetTaskIdsOfClassificationReportWithAttachments() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @WithAccessId(userName = "monitor") + @Test + void testGetTaskIdsOfClassificationReportWithAttachments() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - List columnHeaders = getListOfColumnHeaders(); + List columnHeaders = getListOfColumnHeaders(); - List selectedItems = new ArrayList<>(); + List selectedItems = new ArrayList<>(); - SelectedItem s1 = new SelectedItem(); - s1.setKey("L10000"); - s1.setSubKey("L11000"); - s1.setLowerAgeLimit(0); - s1.setUpperAgeLimit(0); - selectedItems.add(s1); + SelectedItem s1 = new SelectedItem(); + s1.setKey("L10000"); + s1.setSubKey("L11000"); + s1.setLowerAgeLimit(0); + s1.setUpperAgeLimit(0); + selectedItems.add(s1); - SelectedItem s2 = new SelectedItem(); - s2.setKey("L10000"); - s2.setSubKey("L11000"); - s2.setLowerAgeLimit(Integer.MIN_VALUE); - s2.setUpperAgeLimit(-11); - selectedItems.add(s2); + SelectedItem s2 = new SelectedItem(); + s2.setKey("L10000"); + s2.setSubKey("L11000"); + s2.setLowerAgeLimit(Integer.MIN_VALUE); + s2.setUpperAgeLimit(-11); + selectedItems.add(s2); - SelectedItem s3 = new SelectedItem(); - s3.setKey("L30000"); - s3.setLowerAgeLimit(Integer.MIN_VALUE); - s3.setUpperAgeLimit(-11); - selectedItems.add(s3); + SelectedItem s3 = new SelectedItem(); + s3.setKey("L30000"); + s3.setLowerAgeLimit(Integer.MIN_VALUE); + s3.setUpperAgeLimit(-11); + selectedItems.add(s3); - List ids = taskMonitorService.createClassificationReportBuilder() + List ids = + taskMonitorService + .createClassificationReportBuilder() .withColumnHeaders(columnHeaders) .inWorkingDays() .listTaskIdsForSelectedItems(selectedItems); - assertEquals(2, ids.size()); - assertTrue(ids.contains("TKI:000000000000000000000000000000000001")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000033")); - } + assertEquals(2, ids.size()); + assertTrue(ids.contains("TKI:000000000000000000000000000000000001")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000033")); + } - @WithAccessId( - userName = "monitor") - @Test - void testGetTaskIdsOfClassificationReportWithDomainFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @WithAccessId(userName = "monitor") + @Test + void testGetTaskIdsOfClassificationReportWithDomainFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - List columnHeaders = getListOfColumnHeaders(); + List columnHeaders = getListOfColumnHeaders(); - List selectedItems = new ArrayList<>(); + List selectedItems = new ArrayList<>(); - SelectedItem s1 = new SelectedItem(); - s1.setKey("L10000"); - s1.setLowerAgeLimit(0); - s1.setUpperAgeLimit(0); - selectedItems.add(s1); + SelectedItem s1 = new SelectedItem(); + s1.setKey("L10000"); + s1.setLowerAgeLimit(0); + s1.setUpperAgeLimit(0); + selectedItems.add(s1); - SelectedItem s2 = new SelectedItem(); - s2.setKey("L10000"); - s2.setLowerAgeLimit(Integer.MIN_VALUE); - s2.setUpperAgeLimit(-11); - selectedItems.add(s2); + SelectedItem s2 = new SelectedItem(); + s2.setKey("L10000"); + s2.setLowerAgeLimit(Integer.MIN_VALUE); + s2.setUpperAgeLimit(-11); + selectedItems.add(s2); - SelectedItem s3 = new SelectedItem(); - s3.setKey("L30000"); - s3.setLowerAgeLimit(Integer.MIN_VALUE); - s3.setUpperAgeLimit(-11); - selectedItems.add(s3); + SelectedItem s3 = new SelectedItem(); + s3.setKey("L30000"); + s3.setLowerAgeLimit(Integer.MIN_VALUE); + s3.setUpperAgeLimit(-11); + selectedItems.add(s3); - List domains = new ArrayList<>(); - domains.add("DOMAIN_B"); - domains.add("DOMAIN_C"); + List domains = new ArrayList<>(); + domains.add("DOMAIN_B"); + domains.add("DOMAIN_C"); - List ids = taskMonitorService.createClassificationReportBuilder() + List ids = + taskMonitorService + .createClassificationReportBuilder() .withColumnHeaders(columnHeaders) .inWorkingDays() .domainIn(domains) .listTaskIdsForSelectedItems(selectedItems); - assertEquals(3, ids.size()); - assertTrue(ids.contains("TKI:000000000000000000000000000000000001")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000004")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000006")); - } - - private List getListOfColumnHeaders() { - List columnHeaders = new ArrayList<>(); - columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -11)); - columnHeaders.add(new TimeIntervalColumnHeader(-10, -6)); - columnHeaders.add(new TimeIntervalColumnHeader(-5, -2)); - columnHeaders.add(new TimeIntervalColumnHeader(-1)); - columnHeaders.add(new TimeIntervalColumnHeader(0)); - columnHeaders.add(new TimeIntervalColumnHeader(1)); - columnHeaders.add(new TimeIntervalColumnHeader(2, 5)); - columnHeaders.add(new TimeIntervalColumnHeader(6, 10)); - columnHeaders.add(new TimeIntervalColumnHeader(11, Integer.MAX_VALUE)); - return columnHeaders; - } + assertEquals(3, ids.size()); + assertTrue(ids.contains("TKI:000000000000000000000000000000000001")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000004")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000006")); + } + private List getListOfColumnHeaders() { + List columnHeaders = new ArrayList<>(); + columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -11)); + columnHeaders.add(new TimeIntervalColumnHeader(-10, -6)); + columnHeaders.add(new TimeIntervalColumnHeader(-5, -2)); + columnHeaders.add(new TimeIntervalColumnHeader(-1)); + columnHeaders.add(new TimeIntervalColumnHeader(0)); + columnHeaders.add(new TimeIntervalColumnHeader(1)); + columnHeaders.add(new TimeIntervalColumnHeader(2, 5)); + columnHeaders.add(new TimeIntervalColumnHeader(6, 10)); + columnHeaders.add(new TimeIntervalColumnHeader(11, Integer.MAX_VALUE)); + return columnHeaders; + } } diff --git a/lib/taskana-core/src/test/java/acceptance/report/GetTaskIdsOfCustomFieldValueReportAccTest.java b/lib/taskana-core/src/test/java/acceptance/report/GetTaskIdsOfCustomFieldValueReportAccTest.java index 470999ab2..dd76e9b2a 100644 --- a/lib/taskana-core/src/test/java/acceptance/report/GetTaskIdsOfCustomFieldValueReportAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/report/GetTaskIdsOfCustomFieldValueReportAccTest.java @@ -9,7 +9,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -24,320 +23,329 @@ import pro.taskana.impl.report.header.TimeIntervalColumnHeader; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "get task ids of category report" scenarios. - */ +/** Acceptance test for all "get task ids of category report" scenarios. */ @ExtendWith(JAASExtension.class) class GetTaskIdsOfCustomFieldValueReportAccTest extends AbstractReportAccTest { - @Test - void testRoleCheck() { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @Test + void testRoleCheck() { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - List columnHeaders = getListOfColumnHeaders(); + List columnHeaders = getListOfColumnHeaders(); - List selectedItems = new ArrayList<>(); + List selectedItems = new ArrayList<>(); - Assertions.assertThrows(NotAuthorizedException.class, () -> - taskMonitorService.createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) + Assertions.assertThrows( + NotAuthorizedException.class, + () -> + taskMonitorService + .createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) .listTaskIdsForSelectedItems(selectedItems)); - } + } - @WithAccessId( - userName = "monitor") - @Test - void testGetTaskIdsOfCustomFieldValueReport() throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @WithAccessId(userName = "monitor") + @Test + void testGetTaskIdsOfCustomFieldValueReport() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - List columnHeaders = getListOfColumnHeaders(); + List columnHeaders = getListOfColumnHeaders(); - List selectedItems = new ArrayList<>(); + List selectedItems = new ArrayList<>(); - SelectedItem s1 = new SelectedItem(); - s1.setKey("Geschaeftsstelle A"); - s1.setLowerAgeLimit(-5); - s1.setUpperAgeLimit(-2); - selectedItems.add(s1); + SelectedItem s1 = new SelectedItem(); + s1.setKey("Geschaeftsstelle A"); + s1.setLowerAgeLimit(-5); + s1.setUpperAgeLimit(-2); + selectedItems.add(s1); - SelectedItem s2 = new SelectedItem(); - s2.setKey("Geschaeftsstelle B"); - s2.setLowerAgeLimit(Integer.MIN_VALUE); - s2.setUpperAgeLimit(-11); - selectedItems.add(s2); + SelectedItem s2 = new SelectedItem(); + s2.setKey("Geschaeftsstelle B"); + s2.setLowerAgeLimit(Integer.MIN_VALUE); + s2.setUpperAgeLimit(-11); + selectedItems.add(s2); - SelectedItem s3 = new SelectedItem(); - s3.setKey("Geschaeftsstelle C"); - s3.setLowerAgeLimit(0); - s3.setUpperAgeLimit(0); - selectedItems.add(s3); + SelectedItem s3 = new SelectedItem(); + s3.setKey("Geschaeftsstelle C"); + s3.setLowerAgeLimit(0); + s3.setUpperAgeLimit(0); + selectedItems.add(s3); - List ids = taskMonitorService.createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) + List ids = + taskMonitorService + .createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) .withColumnHeaders(columnHeaders) .inWorkingDays() .listTaskIdsForSelectedItems(selectedItems); - assertEquals(8, ids.size()); - assertTrue(ids.contains("TKI:000000000000000000000000000000000002")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000006")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000009")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000020")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000024")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000027")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000029")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000033")); - } + assertEquals(8, ids.size()); + assertTrue(ids.contains("TKI:000000000000000000000000000000000002")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000006")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000009")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000020")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000024")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000027")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000029")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000033")); + } - @WithAccessId( - userName = "monitor") - @Test - void testGetTaskIdsOfCustomFieldValueReportWithWorkbasketFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @WithAccessId(userName = "monitor") + @Test + void testGetTaskIdsOfCustomFieldValueReportWithWorkbasketFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - List workbasketIds = Collections.singletonList("WBI:000000000000000000000000000000000001"); - List columnHeaders = getListOfColumnHeaders(); + List workbasketIds = + Collections.singletonList("WBI:000000000000000000000000000000000001"); + List columnHeaders = getListOfColumnHeaders(); - List selectedItems = new ArrayList<>(); + List selectedItems = new ArrayList<>(); - SelectedItem s1 = new SelectedItem(); - s1.setKey("Geschaeftsstelle A"); - s1.setLowerAgeLimit(-5); - s1.setUpperAgeLimit(-2); - selectedItems.add(s1); + SelectedItem s1 = new SelectedItem(); + s1.setKey("Geschaeftsstelle A"); + s1.setLowerAgeLimit(-5); + s1.setUpperAgeLimit(-2); + selectedItems.add(s1); - SelectedItem s2 = new SelectedItem(); - s2.setKey("Geschaeftsstelle B"); - s2.setLowerAgeLimit(Integer.MIN_VALUE); - s2.setUpperAgeLimit(-11); - selectedItems.add(s2); + SelectedItem s2 = new SelectedItem(); + s2.setKey("Geschaeftsstelle B"); + s2.setLowerAgeLimit(Integer.MIN_VALUE); + s2.setUpperAgeLimit(-11); + selectedItems.add(s2); - SelectedItem s3 = new SelectedItem(); - s3.setKey("Geschaeftsstelle C"); - s3.setLowerAgeLimit(0); - s3.setUpperAgeLimit(0); - selectedItems.add(s3); + SelectedItem s3 = new SelectedItem(); + s3.setKey("Geschaeftsstelle C"); + s3.setLowerAgeLimit(0); + s3.setUpperAgeLimit(0); + selectedItems.add(s3); - List ids = taskMonitorService.createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) + List ids = + taskMonitorService + .createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) .withColumnHeaders(columnHeaders) .inWorkingDays() .workbasketIdIn(workbasketIds) .listTaskIdsForSelectedItems(selectedItems); - assertEquals(3, ids.size()); - assertTrue(ids.contains("TKI:000000000000000000000000000000000006")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000009")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000020")); - } + assertEquals(3, ids.size()); + assertTrue(ids.contains("TKI:000000000000000000000000000000000006")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000009")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000020")); + } - @WithAccessId( - userName = "monitor") - @Test - void testGetTaskIdsOfCustomFieldValueReportWithStateFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @WithAccessId(userName = "monitor") + @Test + void testGetTaskIdsOfCustomFieldValueReportWithStateFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - List columnHeaders = getListOfColumnHeaders(); + List columnHeaders = getListOfColumnHeaders(); - List selectedItems = new ArrayList<>(); + List selectedItems = new ArrayList<>(); - SelectedItem s1 = new SelectedItem(); - s1.setKey("Geschaeftsstelle A"); - s1.setLowerAgeLimit(-5); - s1.setUpperAgeLimit(-2); - selectedItems.add(s1); + SelectedItem s1 = new SelectedItem(); + s1.setKey("Geschaeftsstelle A"); + s1.setLowerAgeLimit(-5); + s1.setUpperAgeLimit(-2); + selectedItems.add(s1); - SelectedItem s2 = new SelectedItem(); - s2.setKey("Geschaeftsstelle B"); - s2.setLowerAgeLimit(Integer.MIN_VALUE); - s2.setUpperAgeLimit(-11); - selectedItems.add(s2); + SelectedItem s2 = new SelectedItem(); + s2.setKey("Geschaeftsstelle B"); + s2.setLowerAgeLimit(Integer.MIN_VALUE); + s2.setUpperAgeLimit(-11); + selectedItems.add(s2); - SelectedItem s3 = new SelectedItem(); - s3.setKey("Geschaeftsstelle C"); - s3.setLowerAgeLimit(0); - s3.setUpperAgeLimit(0); - selectedItems.add(s3); + SelectedItem s3 = new SelectedItem(); + s3.setKey("Geschaeftsstelle C"); + s3.setLowerAgeLimit(0); + s3.setUpperAgeLimit(0); + selectedItems.add(s3); - List ids = taskMonitorService.createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) + List ids = + taskMonitorService + .createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) .withColumnHeaders(columnHeaders) .inWorkingDays() .stateIn(Collections.singletonList(TaskState.READY)) .listTaskIdsForSelectedItems(selectedItems); - assertEquals(8, ids.size()); - assertTrue(ids.contains("TKI:000000000000000000000000000000000002")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000006")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000009")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000020")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000024")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000027")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000029")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000033")); - } + assertEquals(8, ids.size()); + assertTrue(ids.contains("TKI:000000000000000000000000000000000002")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000006")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000009")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000020")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000024")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000027")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000029")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000033")); + } - @WithAccessId( - userName = "monitor") - @Test - void testGetTaskIdsOfCustomFieldValueReportWithCategoryFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @WithAccessId(userName = "monitor") + @Test + void testGetTaskIdsOfCustomFieldValueReportWithCategoryFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - List categories = Arrays.asList("AUTOMATIC", "MANUAL"); - List columnHeaders = getListOfColumnHeaders(); + List categories = Arrays.asList("AUTOMATIC", "MANUAL"); + List columnHeaders = getListOfColumnHeaders(); - List selectedItems = new ArrayList<>(); + List selectedItems = new ArrayList<>(); - SelectedItem s1 = new SelectedItem(); - s1.setKey("Geschaeftsstelle A"); - s1.setLowerAgeLimit(-5); - s1.setUpperAgeLimit(-2); - selectedItems.add(s1); + SelectedItem s1 = new SelectedItem(); + s1.setKey("Geschaeftsstelle A"); + s1.setLowerAgeLimit(-5); + s1.setUpperAgeLimit(-2); + selectedItems.add(s1); - SelectedItem s2 = new SelectedItem(); - s2.setKey("Geschaeftsstelle B"); - s2.setLowerAgeLimit(Integer.MIN_VALUE); - s2.setUpperAgeLimit(-11); - selectedItems.add(s2); + SelectedItem s2 = new SelectedItem(); + s2.setKey("Geschaeftsstelle B"); + s2.setLowerAgeLimit(Integer.MIN_VALUE); + s2.setUpperAgeLimit(-11); + selectedItems.add(s2); - SelectedItem s3 = new SelectedItem(); - s3.setKey("Geschaeftsstelle C"); - s3.setLowerAgeLimit(0); - s3.setUpperAgeLimit(0); - selectedItems.add(s3); + SelectedItem s3 = new SelectedItem(); + s3.setKey("Geschaeftsstelle C"); + s3.setLowerAgeLimit(0); + s3.setUpperAgeLimit(0); + selectedItems.add(s3); - List ids = taskMonitorService.createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) + List ids = + taskMonitorService + .createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) .withColumnHeaders(columnHeaders) .inWorkingDays() .categoryIn(categories) .listTaskIdsForSelectedItems(selectedItems); - assertEquals(3, ids.size()); - assertTrue(ids.contains("TKI:000000000000000000000000000000000006")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000009")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000029")); - } + assertEquals(3, ids.size()); + assertTrue(ids.contains("TKI:000000000000000000000000000000000006")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000009")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000029")); + } - @WithAccessId( - userName = "monitor") - @Test - void testGetTaskIdsOfCustomFieldValueReportWithDomainFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @WithAccessId(userName = "monitor") + @Test + void testGetTaskIdsOfCustomFieldValueReportWithDomainFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - List columnHeaders = getListOfColumnHeaders(); + List columnHeaders = getListOfColumnHeaders(); - List selectedItems = new ArrayList<>(); + List selectedItems = new ArrayList<>(); - SelectedItem s1 = new SelectedItem(); - s1.setKey("Geschaeftsstelle A"); - s1.setLowerAgeLimit(-5); - s1.setUpperAgeLimit(-2); - selectedItems.add(s1); + SelectedItem s1 = new SelectedItem(); + s1.setKey("Geschaeftsstelle A"); + s1.setLowerAgeLimit(-5); + s1.setUpperAgeLimit(-2); + selectedItems.add(s1); - SelectedItem s2 = new SelectedItem(); - s2.setKey("Geschaeftsstelle B"); - s2.setLowerAgeLimit(Integer.MIN_VALUE); - s2.setUpperAgeLimit(-11); - selectedItems.add(s2); + SelectedItem s2 = new SelectedItem(); + s2.setKey("Geschaeftsstelle B"); + s2.setLowerAgeLimit(Integer.MIN_VALUE); + s2.setUpperAgeLimit(-11); + selectedItems.add(s2); - SelectedItem s3 = new SelectedItem(); - s3.setKey("Geschaeftsstelle C"); - s3.setLowerAgeLimit(0); - s3.setUpperAgeLimit(0); - selectedItems.add(s3); + SelectedItem s3 = new SelectedItem(); + s3.setKey("Geschaeftsstelle C"); + s3.setLowerAgeLimit(0); + s3.setUpperAgeLimit(0); + selectedItems.add(s3); - List ids = taskMonitorService.createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) + List ids = + taskMonitorService + .createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) .withColumnHeaders(columnHeaders) .inWorkingDays() .domainIn(Collections.singletonList("DOMAIN_A")) .listTaskIdsForSelectedItems(selectedItems); - assertEquals(3, ids.size()); - assertTrue(ids.contains("TKI:000000000000000000000000000000000009")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000020")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000033")); - } + assertEquals(3, ids.size()); + assertTrue(ids.contains("TKI:000000000000000000000000000000000009")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000020")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000033")); + } - @WithAccessId( - userName = "monitor") - @Test - void testGetTaskIdsOfCustomFieldValueReportWithCustomFieldValueFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @WithAccessId(userName = "monitor") + @Test + void testGetTaskIdsOfCustomFieldValueReportWithCustomFieldValueFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - Map customAttributeFilter = new HashMap<>(); - customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); - List columnHeaders = getListOfColumnHeaders(); + Map customAttributeFilter = new HashMap<>(); + customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); + List columnHeaders = getListOfColumnHeaders(); - List selectedItems = new ArrayList<>(); + List selectedItems = new ArrayList<>(); - SelectedItem s1 = new SelectedItem(); - s1.setKey("Geschaeftsstelle A"); - s1.setLowerAgeLimit(-5); - s1.setUpperAgeLimit(-2); - selectedItems.add(s1); + SelectedItem s1 = new SelectedItem(); + s1.setKey("Geschaeftsstelle A"); + s1.setLowerAgeLimit(-5); + s1.setUpperAgeLimit(-2); + selectedItems.add(s1); - SelectedItem s2 = new SelectedItem(); - s2.setKey("Geschaeftsstelle B"); - s2.setLowerAgeLimit(Integer.MIN_VALUE); - s2.setUpperAgeLimit(-11); - selectedItems.add(s2); + SelectedItem s2 = new SelectedItem(); + s2.setKey("Geschaeftsstelle B"); + s2.setLowerAgeLimit(Integer.MIN_VALUE); + s2.setUpperAgeLimit(-11); + selectedItems.add(s2); - SelectedItem s3 = new SelectedItem(); - s3.setKey("Geschaeftsstelle C"); - s3.setLowerAgeLimit(0); - s3.setUpperAgeLimit(0); - selectedItems.add(s3); + SelectedItem s3 = new SelectedItem(); + s3.setKey("Geschaeftsstelle C"); + s3.setLowerAgeLimit(0); + s3.setUpperAgeLimit(0); + selectedItems.add(s3); - List ids = taskMonitorService.createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) + List ids = + taskMonitorService + .createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) .withColumnHeaders(columnHeaders) .inWorkingDays() .customAttributeFilterIn(customAttributeFilter) .listTaskIdsForSelectedItems(selectedItems); - assertEquals(4, ids.size()); - assertTrue(ids.contains("TKI:000000000000000000000000000000000020")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000024")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000027")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000029")); - } + assertEquals(4, ids.size()); + assertTrue(ids.contains("TKI:000000000000000000000000000000000020")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000024")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000027")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000029")); + } - @WithAccessId( - userName = "monitor") - @Test - void testThrowsExceptionIfSubKeysAreUsed() { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @WithAccessId(userName = "monitor") + @Test + void testThrowsExceptionIfSubKeysAreUsed() { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - List columnHeaders = getListOfColumnHeaders(); + List columnHeaders = getListOfColumnHeaders(); - List selectedItems = new ArrayList<>(); + List selectedItems = new ArrayList<>(); - SelectedItem s1 = new SelectedItem(); - s1.setKey("Geschaeftsstelle A"); - s1.setSubKey("INVALID"); - s1.setLowerAgeLimit(-5); - s1.setUpperAgeLimit(-2); - selectedItems.add(s1); + SelectedItem s1 = new SelectedItem(); + s1.setKey("Geschaeftsstelle A"); + s1.setSubKey("INVALID"); + s1.setLowerAgeLimit(-5); + s1.setUpperAgeLimit(-2); + selectedItems.add(s1); - Assertions.assertThrows(InvalidArgumentException.class, () -> - taskMonitorService.createCategoryReportBuilder() + Assertions.assertThrows( + InvalidArgumentException.class, + () -> + taskMonitorService + .createCategoryReportBuilder() .withColumnHeaders(columnHeaders) - .listTaskIdsForSelectedItems( - selectedItems)); - } - - private List getListOfColumnHeaders() { - List columnHeaders = new ArrayList<>(); - columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -11)); - columnHeaders.add(new TimeIntervalColumnHeader(-10, -6)); - columnHeaders.add(new TimeIntervalColumnHeader(-5, -2)); - columnHeaders.add(new TimeIntervalColumnHeader(-1)); - columnHeaders.add(new TimeIntervalColumnHeader(0)); - columnHeaders.add(new TimeIntervalColumnHeader(1)); - columnHeaders.add(new TimeIntervalColumnHeader(2, 5)); - columnHeaders.add(new TimeIntervalColumnHeader(6, 10)); - columnHeaders.add(new TimeIntervalColumnHeader(11, Integer.MAX_VALUE)); - return columnHeaders; - } + .listTaskIdsForSelectedItems(selectedItems)); + } + private List getListOfColumnHeaders() { + List columnHeaders = new ArrayList<>(); + columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -11)); + columnHeaders.add(new TimeIntervalColumnHeader(-10, -6)); + columnHeaders.add(new TimeIntervalColumnHeader(-5, -2)); + columnHeaders.add(new TimeIntervalColumnHeader(-1)); + columnHeaders.add(new TimeIntervalColumnHeader(0)); + columnHeaders.add(new TimeIntervalColumnHeader(1)); + columnHeaders.add(new TimeIntervalColumnHeader(2, 5)); + columnHeaders.add(new TimeIntervalColumnHeader(6, 10)); + columnHeaders.add(new TimeIntervalColumnHeader(11, Integer.MAX_VALUE)); + return columnHeaders; + } } diff --git a/lib/taskana-core/src/test/java/acceptance/report/GetTaskIdsOfWorkbasketReportAccTest.java b/lib/taskana-core/src/test/java/acceptance/report/GetTaskIdsOfWorkbasketReportAccTest.java index e7f9b0ced..235c04e63 100644 --- a/lib/taskana-core/src/test/java/acceptance/report/GetTaskIdsOfWorkbasketReportAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/report/GetTaskIdsOfWorkbasketReportAccTest.java @@ -6,7 +6,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Collections; import java.util.List; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -19,121 +18,125 @@ import pro.taskana.impl.report.header.TimeIntervalColumnHeader; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "get task ids of workbasket report" scenarios. - */ +/** Acceptance test for all "get task ids of workbasket report" scenarios. */ @ExtendWith(JAASExtension.class) class GetTaskIdsOfWorkbasketReportAccTest extends AbstractReportAccTest { - @Test - void testRoleCheck() { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @Test + void testRoleCheck() { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - List columnHeaders = getListOfColumnHeaders(); + List columnHeaders = getListOfColumnHeaders(); - List selectedItems = new ArrayList<>(); + List selectedItems = new ArrayList<>(); - Assertions.assertThrows(NotAuthorizedException.class, () -> - taskMonitorService.createWorkbasketReportBuilder().listTaskIdsForSelectedItems(selectedItems)); - } + Assertions.assertThrows( + NotAuthorizedException.class, + () -> + taskMonitorService + .createWorkbasketReportBuilder() + .listTaskIdsForSelectedItems(selectedItems)); + } - @WithAccessId( - userName = "monitor") - @Test - void testGetTaskIdsOfWorkbasketReport() throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @WithAccessId(userName = "monitor") + @Test + void testGetTaskIdsOfWorkbasketReport() throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - List columnHeaders = getListOfColumnHeaders(); + List columnHeaders = getListOfColumnHeaders(); - List selectedItems = new ArrayList<>(); + List selectedItems = new ArrayList<>(); - SelectedItem s1 = new SelectedItem(); - s1.setKey("USER_1_1"); - s1.setLowerAgeLimit(0); - s1.setUpperAgeLimit(0); - selectedItems.add(s1); + SelectedItem s1 = new SelectedItem(); + s1.setKey("USER_1_1"); + s1.setLowerAgeLimit(0); + s1.setUpperAgeLimit(0); + selectedItems.add(s1); - SelectedItem s2 = new SelectedItem(); - s2.setKey("USER_1_1"); - s2.setLowerAgeLimit(Integer.MIN_VALUE); - s2.setUpperAgeLimit(-11); - selectedItems.add(s2); + SelectedItem s2 = new SelectedItem(); + s2.setKey("USER_1_1"); + s2.setLowerAgeLimit(Integer.MIN_VALUE); + s2.setUpperAgeLimit(-11); + selectedItems.add(s2); - SelectedItem s3 = new SelectedItem(); - s3.setKey("USER_1_2"); - s3.setLowerAgeLimit(1000); - s3.setUpperAgeLimit(Integer.MAX_VALUE); - selectedItems.add(s3); + SelectedItem s3 = new SelectedItem(); + s3.setKey("USER_1_2"); + s3.setLowerAgeLimit(1000); + s3.setUpperAgeLimit(Integer.MAX_VALUE); + selectedItems.add(s3); - List ids = taskMonitorService.createWorkbasketReportBuilder() + List ids = + taskMonitorService + .createWorkbasketReportBuilder() .withColumnHeaders(columnHeaders) .inWorkingDays() .listTaskIdsForSelectedItems(selectedItems); - assertEquals(7, ids.size()); - assertTrue(ids.contains("TKI:000000000000000000000000000000000001")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000004")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000006")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000009")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000010")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000031")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000050")); - } + assertEquals(7, ids.size()); + assertTrue(ids.contains("TKI:000000000000000000000000000000000001")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000004")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000006")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000009")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000010")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000031")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000050")); + } - @WithAccessId( - userName = "monitor") - @Test - void testGetTaskIdsOfWorkbasketReportWithExcludedClassifications() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @WithAccessId(userName = "monitor") + @Test + void testGetTaskIdsOfWorkbasketReportWithExcludedClassifications() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - List columnHeaders = getListOfColumnHeaders(); + List columnHeaders = getListOfColumnHeaders(); - List selectedItems = new ArrayList<>(); + List selectedItems = new ArrayList<>(); - SelectedItem s1 = new SelectedItem(); - s1.setKey("USER_1_1"); - s1.setLowerAgeLimit(0); - s1.setUpperAgeLimit(0); - selectedItems.add(s1); + SelectedItem s1 = new SelectedItem(); + s1.setKey("USER_1_1"); + s1.setLowerAgeLimit(0); + s1.setUpperAgeLimit(0); + selectedItems.add(s1); - SelectedItem s2 = new SelectedItem(); - s2.setKey("USER_1_1"); - s2.setLowerAgeLimit(Integer.MIN_VALUE); - s2.setUpperAgeLimit(-11); - selectedItems.add(s2); + SelectedItem s2 = new SelectedItem(); + s2.setKey("USER_1_1"); + s2.setLowerAgeLimit(Integer.MIN_VALUE); + s2.setUpperAgeLimit(-11); + selectedItems.add(s2); - SelectedItem s3 = new SelectedItem(); - s3.setKey("USER_1_2"); - s3.setLowerAgeLimit(1000); - s3.setUpperAgeLimit(Integer.MAX_VALUE); - selectedItems.add(s3); + SelectedItem s3 = new SelectedItem(); + s3.setKey("USER_1_2"); + s3.setLowerAgeLimit(1000); + s3.setUpperAgeLimit(Integer.MAX_VALUE); + selectedItems.add(s3); - List ids = taskMonitorService.createWorkbasketReportBuilder() + List ids = + taskMonitorService + .createWorkbasketReportBuilder() .withColumnHeaders(columnHeaders) .inWorkingDays() - .excludedClassificationIdIn(Collections.singletonList("CLI:000000000000000000000000000000000001")) + .excludedClassificationIdIn( + Collections.singletonList("CLI:000000000000000000000000000000000001")) .listTaskIdsForSelectedItems(selectedItems); - assertEquals(4, ids.size()); - assertTrue(ids.contains("TKI:000000000000000000000000000000000006")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000009")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000031")); - assertTrue(ids.contains("TKI:000000000000000000000000000000000050")); - } - - private List getListOfColumnHeaders() { - List columnHeaders = new ArrayList<>(); - columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -11)); - columnHeaders.add(new TimeIntervalColumnHeader(-10, -6)); - columnHeaders.add(new TimeIntervalColumnHeader(-5, -2)); - columnHeaders.add(new TimeIntervalColumnHeader(-1)); - columnHeaders.add(new TimeIntervalColumnHeader(0)); - columnHeaders.add(new TimeIntervalColumnHeader(1)); - columnHeaders.add(new TimeIntervalColumnHeader(2, 5)); - columnHeaders.add(new TimeIntervalColumnHeader(6, 10)); - columnHeaders.add(new TimeIntervalColumnHeader(11, Integer.MAX_VALUE)); - return columnHeaders; - } + assertEquals(4, ids.size()); + assertTrue(ids.contains("TKI:000000000000000000000000000000000006")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000009")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000031")); + assertTrue(ids.contains("TKI:000000000000000000000000000000000050")); + } + private List getListOfColumnHeaders() { + List columnHeaders = new ArrayList<>(); + columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -11)); + columnHeaders.add(new TimeIntervalColumnHeader(-10, -6)); + columnHeaders.add(new TimeIntervalColumnHeader(-5, -2)); + columnHeaders.add(new TimeIntervalColumnHeader(-1)); + columnHeaders.add(new TimeIntervalColumnHeader(0)); + columnHeaders.add(new TimeIntervalColumnHeader(1)); + columnHeaders.add(new TimeIntervalColumnHeader(2, 5)); + columnHeaders.add(new TimeIntervalColumnHeader(6, 10)); + columnHeaders.add(new TimeIntervalColumnHeader(11, Integer.MAX_VALUE)); + return columnHeaders; + } } diff --git a/lib/taskana-core/src/test/java/acceptance/report/ProvideCategoryReportAccTest.java b/lib/taskana-core/src/test/java/acceptance/report/ProvideCategoryReportAccTest.java index 1e9ca2714..bda4dcd1a 100644 --- a/lib/taskana-core/src/test/java/acceptance/report/ProvideCategoryReportAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/report/ProvideCategoryReportAccTest.java @@ -11,7 +11,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.IntStream; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -28,391 +27,402 @@ import pro.taskana.report.CategoryReport; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "category report" scenarios. - */ +/** Acceptance test for all "category report" scenarios. */ @ExtendWith(JAASExtension.class) class ProvideCategoryReportAccTest extends AbstractReportAccTest { - private static final Logger LOGGER = LoggerFactory.getLogger(ProvideCategoryReportAccTest.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ProvideCategoryReportAccTest.class); - @Test - void testRoleCheck() { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @Test + void testRoleCheck() { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - Assertions.assertThrows(NotAuthorizedException.class, () -> - taskMonitorService.createCategoryReportBuilder().buildReport()); + Assertions.assertThrows( + NotAuthorizedException.class, + () -> taskMonitorService.createCategoryReportBuilder().buildReport()); + } + + @WithAccessId(userName = "monitor") + @Test + void testGetTotalNumbersOfTasksOfCategoryReport() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + CategoryReport report = taskMonitorService.createCategoryReportBuilder().buildReport(); + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report)); } - @WithAccessId( - userName = "monitor") - @Test - void testGetTotalNumbersOfTasksOfCategoryReport() throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(3, report.rowSize()); - CategoryReport report = taskMonitorService.createCategoryReportBuilder().buildReport(); + assertEquals(33, report.getRow("EXTERN").getTotalValue()); + assertEquals(7, report.getRow("AUTOMATIC").getTotalValue()); + assertEquals(10, report.getRow("MANUAL").getTotalValue()); + assertEquals(0, report.getRow("EXTERN").getCells().length); + assertEquals(0, report.getRow("AUTOMATIC").getCells().length); + assertEquals(0, report.getRow("MANUAL").getCells().length); + assertEquals(50, report.getSumRow().getTotalValue()); + } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report)); - } + @WithAccessId(userName = "monitor") + @Test + void testGetCategoryReportWithReportLineItemDefinitions() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - assertNotNull(report); - assertEquals(3, report.rowSize()); + List columnHeaders = getListOfColumnHeaders(); - assertEquals(33, report.getRow("EXTERN").getTotalValue()); - assertEquals(7, report.getRow("AUTOMATIC").getTotalValue()); - assertEquals(10, report.getRow("MANUAL").getTotalValue()); - assertEquals(0, report.getRow("EXTERN").getCells().length); - assertEquals(0, report.getRow("AUTOMATIC").getCells().length); - assertEquals(0, report.getRow("MANUAL").getCells().length); - assertEquals(50, report.getSumRow().getTotalValue()); - } - - @WithAccessId( - userName = "monitor") - @Test - void testGetCategoryReportWithReportLineItemDefinitions() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - - List columnHeaders = getListOfColumnHeaders(); - - CategoryReport report = taskMonitorService.createCategoryReportBuilder() + CategoryReport report = + taskMonitorService + .createCategoryReportBuilder() .withColumnHeaders(columnHeaders) .inWorkingDays() .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - int sumLineCount = IntStream.of(report.getSumRow().getCells()).sum(); - - assertNotNull(report); - assertEquals(3, report.rowSize()); - - assertEquals(33, report.getRow("EXTERN").getTotalValue()); - assertEquals(7, report.getRow("AUTOMATIC").getTotalValue()); - assertEquals(10, report.getRow("MANUAL").getTotalValue()); - - int[] sumRow = report.getSumRow().getCells(); - assertArrayEquals(new int[] {10, 9, 11, 0, 4, 0, 7, 4, 5}, sumRow); - assertEquals(50, report.getSumRow().getTotalValue()); - assertEquals(50, sumLineCount); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId(userName = "monitor") - @Test - void testEachItemOfCategoryReport() throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + int sumLineCount = IntStream.of(report.getSumRow().getCells()).sum(); - List columnHeaders = getShortListOfColumnHeaders(); + assertNotNull(report); + assertEquals(3, report.rowSize()); - CategoryReport report = taskMonitorService.createCategoryReportBuilder() + assertEquals(33, report.getRow("EXTERN").getTotalValue()); + assertEquals(7, report.getRow("AUTOMATIC").getTotalValue()); + assertEquals(10, report.getRow("MANUAL").getTotalValue()); + + int[] sumRow = report.getSumRow().getCells(); + assertArrayEquals(new int[] {10, 9, 11, 0, 4, 0, 7, 4, 5}, sumRow); + assertEquals(50, report.getSumRow().getTotalValue()); + assertEquals(50, sumLineCount); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfCategoryReport() throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List columnHeaders = getShortListOfColumnHeaders(); + + CategoryReport report = + taskMonitorService + .createCategoryReportBuilder() .withColumnHeaders(columnHeaders) .inWorkingDays() .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(3, report.rowSize()); - - int[] row1 = report.getRow("EXTERN").getCells(); - assertArrayEquals(new int[] {15, 8, 2, 6, 2}, row1); - - int[] row2 = report.getRow("AUTOMATIC").getCells(); - assertArrayEquals(new int[] {2, 1, 0, 1, 3}, row2); - - int[] row3 = report.getRow("MANUAL").getCells(); - assertArrayEquals(new int[] {2, 2, 2, 0, 4}, row3); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfCategoryReportNotInWorkingDays() throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(3, report.rowSize()); - List columnHeaders = getShortListOfColumnHeaders(); + int[] row1 = report.getRow("EXTERN").getCells(); + assertArrayEquals(new int[] {15, 8, 2, 6, 2}, row1); - CategoryReport report = taskMonitorService.createCategoryReportBuilder() + int[] row2 = report.getRow("AUTOMATIC").getCells(); + assertArrayEquals(new int[] {2, 1, 0, 1, 3}, row2); + + int[] row3 = report.getRow("MANUAL").getCells(); + assertArrayEquals(new int[] {2, 2, 2, 0, 4}, row3); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfCategoryReportNotInWorkingDays() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List columnHeaders = getShortListOfColumnHeaders(); + + CategoryReport report = + taskMonitorService + .createCategoryReportBuilder() .withColumnHeaders(columnHeaders) .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(3, report.rowSize()); - - int[] row1 = report.getRow("EXTERN").getCells(); - assertArrayEquals(new int[] {23, 0, 2, 0, 8}, row1); - - int[] row2 = report.getRow("AUTOMATIC").getCells(); - assertArrayEquals(new int[] {3, 0, 0, 0, 4}, row2); - - int[] row3 = report.getRow("MANUAL").getCells(); - assertArrayEquals(new int[] {4, 0, 2, 0, 4}, row3); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfCategoryReportWithWorkbasketFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(3, report.rowSize()); - List workbasketIds = Collections.singletonList("WBI:000000000000000000000000000000000001"); - List columnHeaders = getShortListOfColumnHeaders(); + int[] row1 = report.getRow("EXTERN").getCells(); + assertArrayEquals(new int[] {23, 0, 2, 0, 8}, row1); - CategoryReport report = taskMonitorService.createCategoryReportBuilder() + int[] row2 = report.getRow("AUTOMATIC").getCells(); + assertArrayEquals(new int[] {3, 0, 0, 0, 4}, row2); + + int[] row3 = report.getRow("MANUAL").getCells(); + assertArrayEquals(new int[] {4, 0, 2, 0, 4}, row3); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfCategoryReportWithWorkbasketFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List workbasketIds = + Collections.singletonList("WBI:000000000000000000000000000000000001"); + List columnHeaders = getShortListOfColumnHeaders(); + + CategoryReport report = + taskMonitorService + .createCategoryReportBuilder() .withColumnHeaders(columnHeaders) .inWorkingDays() .workbasketIdIn(workbasketIds) .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(3, report.rowSize()); - - int[] row1 = report.getRow("EXTERN").getCells(); - assertArrayEquals(new int[] {10, 2, 0, 0, 0}, row1); - - int[] row2 = report.getRow("AUTOMATIC").getCells(); - assertArrayEquals(new int[] {2, 1, 0, 1, 1}, row2); - - int[] row3 = report.getRow("MANUAL").getCells(); - assertArrayEquals(new int[] {1, 0, 1, 0, 1}, row3); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfCategoryReportWithStateFilter() throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(3, report.rowSize()); - List states = Collections.singletonList(TaskState.READY); - List columnHeaders = getShortListOfColumnHeaders(); + int[] row1 = report.getRow("EXTERN").getCells(); + assertArrayEquals(new int[] {10, 2, 0, 0, 0}, row1); - CategoryReport report = taskMonitorService.createCategoryReportBuilder() + int[] row2 = report.getRow("AUTOMATIC").getCells(); + assertArrayEquals(new int[] {2, 1, 0, 1, 1}, row2); + + int[] row3 = report.getRow("MANUAL").getCells(); + assertArrayEquals(new int[] {1, 0, 1, 0, 1}, row3); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfCategoryReportWithStateFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List states = Collections.singletonList(TaskState.READY); + List columnHeaders = getShortListOfColumnHeaders(); + + CategoryReport report = + taskMonitorService + .createCategoryReportBuilder() .withColumnHeaders(columnHeaders) .stateIn(states) .inWorkingDays() .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(3, report.rowSize()); - - int[] row1 = report.getRow("EXTERN").getCells(); - assertArrayEquals(new int[] {15, 8, 2, 6, 0}, row1); - - int[] row2 = report.getRow("AUTOMATIC").getCells(); - assertArrayEquals(new int[] {2, 1, 0, 1, 0}, row2); - - int[] row3 = report.getRow("MANUAL").getCells(); - assertArrayEquals(new int[] {2, 2, 2, 0, 0}, row3); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfCategoryReportWithCategoryFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(3, report.rowSize()); - List categories = Arrays.asList("AUTOMATIC", "MANUAL"); - List columnHeaders = getShortListOfColumnHeaders(); + int[] row1 = report.getRow("EXTERN").getCells(); + assertArrayEquals(new int[] {15, 8, 2, 6, 0}, row1); - CategoryReport report = taskMonitorService.createCategoryReportBuilder() + int[] row2 = report.getRow("AUTOMATIC").getCells(); + assertArrayEquals(new int[] {2, 1, 0, 1, 0}, row2); + + int[] row3 = report.getRow("MANUAL").getCells(); + assertArrayEquals(new int[] {2, 2, 2, 0, 0}, row3); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfCategoryReportWithCategoryFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List categories = Arrays.asList("AUTOMATIC", "MANUAL"); + List columnHeaders = getShortListOfColumnHeaders(); + + CategoryReport report = + taskMonitorService + .createCategoryReportBuilder() .withColumnHeaders(columnHeaders) .categoryIn(categories) .inWorkingDays() .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(2, report.rowSize()); - - int[] row1 = report.getRow("AUTOMATIC").getCells(); - assertArrayEquals(new int[] {2, 1, 0, 1, 3}, row1); - - int[] row2 = report.getRow("MANUAL").getCells(); - assertArrayEquals(new int[] {2, 2, 2, 0, 4}, row2); - + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfCategoryReportWithDomainFilter() throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(2, report.rowSize()); - List domains = Collections.singletonList("DOMAIN_A"); - List columnHeaders = getShortListOfColumnHeaders(); + int[] row1 = report.getRow("AUTOMATIC").getCells(); + assertArrayEquals(new int[] {2, 1, 0, 1, 3}, row1); - CategoryReport report = taskMonitorService.createCategoryReportBuilder() + int[] row2 = report.getRow("MANUAL").getCells(); + assertArrayEquals(new int[] {2, 2, 2, 0, 4}, row2); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfCategoryReportWithDomainFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List domains = Collections.singletonList("DOMAIN_A"); + List columnHeaders = getShortListOfColumnHeaders(); + + CategoryReport report = + taskMonitorService + .createCategoryReportBuilder() .withColumnHeaders(columnHeaders) .domainIn(domains) .inWorkingDays() .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(3, report.rowSize()); - - int[] row1 = report.getRow("EXTERN").getCells(); - assertArrayEquals(new int[] {8, 4, 2, 4, 0}, row1); - - int[] row2 = report.getRow("AUTOMATIC").getCells(); - assertArrayEquals(new int[] {1, 0, 0, 1, 1}, row2); - - int[] row3 = report.getRow("MANUAL").getCells(); - assertArrayEquals(new int[] {2, 0, 0, 0, 3}, row3); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfCategoryReportWithCustomFieldValueFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(3, report.rowSize()); - Map customAttributeFilter = new HashMap<>(); - customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); - List columnHeaders = getShortListOfColumnHeaders(); + int[] row1 = report.getRow("EXTERN").getCells(); + assertArrayEquals(new int[] {8, 4, 2, 4, 0}, row1); - CategoryReport report = taskMonitorService.createCategoryReportBuilder() + int[] row2 = report.getRow("AUTOMATIC").getCells(); + assertArrayEquals(new int[] {1, 0, 0, 1, 1}, row2); + + int[] row3 = report.getRow("MANUAL").getCells(); + assertArrayEquals(new int[] {2, 0, 0, 0, 3}, row3); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfCategoryReportWithCustomFieldValueFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + Map customAttributeFilter = new HashMap<>(); + customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); + List columnHeaders = getShortListOfColumnHeaders(); + + CategoryReport report = + taskMonitorService + .createCategoryReportBuilder() .withColumnHeaders(columnHeaders) .customAttributeFilterIn(customAttributeFilter) .inWorkingDays() .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(3, report.rowSize()); - - int[] row1 = report.getRow("EXTERN").getCells(); - assertArrayEquals(new int[] {9, 3, 1, 3, 0}, row1); - - int[] row2 = report.getRow("AUTOMATIC").getCells(); - assertArrayEquals(new int[] {1, 0, 0, 1, 1}, row2); - - int[] row3 = report.getRow("MANUAL").getCells(); - assertArrayEquals(new int[] {1, 1, 2, 0, 2}, row3); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - private List getListOfColumnHeaders() { - List columnHeaders = new ArrayList<>(); - columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -11)); - columnHeaders.add(new TimeIntervalColumnHeader(-10, -6)); - columnHeaders.add(new TimeIntervalColumnHeader(-5, -2)); - columnHeaders.add(new TimeIntervalColumnHeader(-1)); - columnHeaders.add(new TimeIntervalColumnHeader(0)); - columnHeaders.add(new TimeIntervalColumnHeader(1)); - columnHeaders.add(new TimeIntervalColumnHeader(2, 5)); - columnHeaders.add(new TimeIntervalColumnHeader(6, 10)); - columnHeaders.add(new TimeIntervalColumnHeader(11, Integer.MAX_VALUE)); - return columnHeaders; + assertNotNull(report); + assertEquals(3, report.rowSize()); + + int[] row1 = report.getRow("EXTERN").getCells(); + assertArrayEquals(new int[] {9, 3, 1, 3, 0}, row1); + + int[] row2 = report.getRow("AUTOMATIC").getCells(); + assertArrayEquals(new int[] {1, 0, 0, 1, 1}, row2); + + int[] row3 = report.getRow("MANUAL").getCells(); + assertArrayEquals(new int[] {1, 1, 2, 0, 2}, row3); + } + + private List getListOfColumnHeaders() { + List columnHeaders = new ArrayList<>(); + columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -11)); + columnHeaders.add(new TimeIntervalColumnHeader(-10, -6)); + columnHeaders.add(new TimeIntervalColumnHeader(-5, -2)); + columnHeaders.add(new TimeIntervalColumnHeader(-1)); + columnHeaders.add(new TimeIntervalColumnHeader(0)); + columnHeaders.add(new TimeIntervalColumnHeader(1)); + columnHeaders.add(new TimeIntervalColumnHeader(2, 5)); + columnHeaders.add(new TimeIntervalColumnHeader(6, 10)); + columnHeaders.add(new TimeIntervalColumnHeader(11, Integer.MAX_VALUE)); + return columnHeaders; + } + + private List getShortListOfColumnHeaders() { + List columnHeaders = new ArrayList<>(); + columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -6)); + columnHeaders.add(new TimeIntervalColumnHeader(-5, -1)); + columnHeaders.add(new TimeIntervalColumnHeader(0)); + columnHeaders.add(new TimeIntervalColumnHeader(1, 5)); + columnHeaders.add(new TimeIntervalColumnHeader(6, Integer.MAX_VALUE)); + return columnHeaders; + } + + private String reportToString(CategoryReport report) { + return reportToString(report, null); + } + + private String reportToString( + CategoryReport report, List columnHeaders) { + String formatColumWidth = "| %-7s "; + String formatFirstColumn = "| %-36s %-4s "; + String formatFirstColumnFirstLine = "| %-29s %12s "; + String formatFirstColumnSumLine = "| %-36s %-5s"; + int reportWidth = columnHeaders == null ? 46 : columnHeaders.size() * 10 + 46; + + StringBuilder builder = new StringBuilder(); + builder.append("\n"); + for (int i = 0; i < reportWidth; i++) { + builder.append("-"); } - - private List getShortListOfColumnHeaders() { - List columnHeaders = new ArrayList<>(); - columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -6)); - columnHeaders.add(new TimeIntervalColumnHeader(-5, -1)); - columnHeaders.add(new TimeIntervalColumnHeader(0)); - columnHeaders.add(new TimeIntervalColumnHeader(1, 5)); - columnHeaders.add(new TimeIntervalColumnHeader(6, Integer.MAX_VALUE)); - return columnHeaders; + builder.append("\n"); + builder.append(String.format(formatFirstColumnFirstLine, "Categories", "Total")); + if (columnHeaders != null) { + for (TimeIntervalColumnHeader def : columnHeaders) { + if (def.getLowerAgeLimit() == Integer.MIN_VALUE) { + builder.append(String.format(formatColumWidth, "< " + def.getUpperAgeLimit())); + } else if (def.getUpperAgeLimit() == Integer.MAX_VALUE) { + builder.append(String.format(formatColumWidth, "> " + def.getLowerAgeLimit())); + } else if (def.getLowerAgeLimit() == def.getUpperAgeLimit()) { + if (def.getLowerAgeLimit() == 0) { + builder.append(String.format(formatColumWidth, "today")); + } else { + builder.append(String.format(formatColumWidth, def.getLowerAgeLimit())); + } + } else { + builder.append( + String.format( + formatColumWidth, def.getLowerAgeLimit() + ".." + def.getUpperAgeLimit())); + } + } } + builder.append("|\n"); - private String reportToString(CategoryReport report) { - return reportToString(report, null); + for (int i = 0; i < reportWidth; i++) { + builder.append("-"); } + builder.append("\n"); - private String reportToString(CategoryReport report, - List columnHeaders) { - String formatColumWidth = "| %-7s "; - String formatFirstColumn = "| %-36s %-4s "; - String formatFirstColumnFirstLine = "| %-29s %12s "; - String formatFirstColumnSumLine = "| %-36s %-5s"; - int reportWidth = columnHeaders == null ? 46 : columnHeaders.size() * 10 + 46; - - StringBuilder builder = new StringBuilder(); - builder.append("\n"); - for (int i = 0; i < reportWidth; i++) { - builder.append("-"); + for (String rl : report.rowTitles()) { + builder.append(String.format(formatFirstColumn, rl, report.getRow(rl).getTotalValue())); + if (columnHeaders != null) { + for (int cell : report.getRow(rl).getCells()) { + builder.append(String.format(formatColumWidth, cell)); } - builder.append("\n"); - builder.append(String.format(formatFirstColumnFirstLine, "Categories", "Total")); - if (columnHeaders != null) { - for (TimeIntervalColumnHeader def : columnHeaders) { - if (def.getLowerAgeLimit() == Integer.MIN_VALUE) { - builder.append(String.format(formatColumWidth, "< " + def.getUpperAgeLimit())); - } else if (def.getUpperAgeLimit() == Integer.MAX_VALUE) { - builder.append(String.format(formatColumWidth, "> " + def.getLowerAgeLimit())); - } else if (def.getLowerAgeLimit() == def.getUpperAgeLimit()) { - if (def.getLowerAgeLimit() == 0) { - builder.append(String.format(formatColumWidth, "today")); - } else { - builder.append(String.format(formatColumWidth, def.getLowerAgeLimit())); - } - } else { - builder.append( - String.format(formatColumWidth, def.getLowerAgeLimit() + ".." + def.getUpperAgeLimit())); - } - } - } - builder.append("|\n"); - - for (int i = 0; i < reportWidth; i++) { - builder.append("-"); - } - builder.append("\n"); - - for (String rl : report.rowTitles()) { - builder - .append(String.format(formatFirstColumn, rl, report.getRow(rl).getTotalValue())); - if (columnHeaders != null) { - for (int cell : report.getRow(rl).getCells()) { - builder.append(String.format(formatColumWidth, cell)); - } - } - builder.append("|\n"); - for (int i = 0; i < reportWidth; i++) { - builder.append("-"); - } - builder.append("\n"); - } - builder.append(String.format(formatFirstColumnSumLine, "Total", report.getSumRow().getTotalValue())); - for (int cell : report.getSumRow().getCells()) { - builder.append(String.format(formatColumWidth, cell)); - } - builder.append("|\n"); - for (int i = 0; i < reportWidth; i++) { - builder.append("-"); - } - builder.append("\n"); - return builder.toString(); + } + builder.append("|\n"); + for (int i = 0; i < reportWidth; i++) { + builder.append("-"); + } + builder.append("\n"); } - + builder.append( + String.format(formatFirstColumnSumLine, "Total", report.getSumRow().getTotalValue())); + for (int cell : report.getSumRow().getCells()) { + builder.append(String.format(formatColumWidth, cell)); + } + builder.append("|\n"); + for (int i = 0; i < reportWidth; i++) { + builder.append("-"); + } + builder.append("\n"); + return builder.toString(); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/report/ProvideClassificationReportAccTest.java b/lib/taskana-core/src/test/java/acceptance/report/ProvideClassificationReportAccTest.java index 13f6fa61e..948c632d6 100644 --- a/lib/taskana-core/src/test/java/acceptance/report/ProvideClassificationReportAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/report/ProvideClassificationReportAccTest.java @@ -11,7 +11,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.IntStream; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -28,445 +27,454 @@ import pro.taskana.report.ClassificationReport; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "classification report" scenarios. - */ +/** Acceptance test for all "classification report" scenarios. */ @ExtendWith(JAASExtension.class) class ProvideClassificationReportAccTest extends AbstractReportAccTest { - private static final Logger LOGGER = LoggerFactory.getLogger(ProvideClassificationReportAccTest.class); + private static final Logger LOGGER = + LoggerFactory.getLogger(ProvideClassificationReportAccTest.class); - @Test - void testRoleCheck() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @Test + void testRoleCheck() throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - Assertions.assertThrows(NotAuthorizedException.class, () -> - taskMonitorService.createClassificationReportBuilder().buildReport()); + Assertions.assertThrows( + NotAuthorizedException.class, + () -> taskMonitorService.createClassificationReportBuilder().buildReport()); + } + + @WithAccessId(userName = "monitor") + @Test + void testGetTotalNumbersOfTasksOfClassificationReport() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + ClassificationReport report = + taskMonitorService.createClassificationReportBuilder().buildReport(); + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report)); } - @WithAccessId( - userName = "monitor") - @Test - void testGetTotalNumbersOfTasksOfClassificationReport() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(5, report.rowSize()); - ClassificationReport report = taskMonitorService.createClassificationReportBuilder().buildReport(); + assertEquals(10, report.getRow("L10000").getTotalValue()); + assertEquals(10, report.getRow("L20000").getTotalValue()); + assertEquals(7, report.getRow("L30000").getTotalValue()); + assertEquals(10, report.getRow("L40000").getTotalValue()); + assertEquals(13, report.getRow("L50000").getTotalValue()); + assertEquals(0, report.getRow("L10000").getCells().length); + assertEquals(0, report.getRow("L20000").getCells().length); + assertEquals(0, report.getRow("L30000").getCells().length); + assertEquals(0, report.getRow("L40000").getCells().length); + assertEquals(0, report.getRow("L50000").getCells().length); + assertEquals(50, report.getSumRow().getTotalValue()); + } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report)); - } + @WithAccessId(userName = "monitor") + @Test + void testGetClassificationReportWithReportLineItemDefinitions() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - assertNotNull(report); - assertEquals(5, report.rowSize()); + List columnHeaders = getListOfColumnsHeaders(); - assertEquals(10, report.getRow("L10000").getTotalValue()); - assertEquals(10, report.getRow("L20000").getTotalValue()); - assertEquals(7, report.getRow("L30000").getTotalValue()); - assertEquals(10, report.getRow("L40000").getTotalValue()); - assertEquals(13, report.getRow("L50000").getTotalValue()); - assertEquals(0, report.getRow("L10000").getCells().length); - assertEquals(0, report.getRow("L20000").getCells().length); - assertEquals(0, report.getRow("L30000").getCells().length); - assertEquals(0, report.getRow("L40000").getCells().length); - assertEquals(0, report.getRow("L50000").getCells().length); - assertEquals(50, report.getSumRow().getTotalValue()); - } - - @WithAccessId( - userName = "monitor") - @Test - void testGetClassificationReportWithReportLineItemDefinitions() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - - List columnHeaders = getListOfColumnsHeaders(); - - ClassificationReport report = taskMonitorService.createClassificationReportBuilder() + ClassificationReport report = + taskMonitorService + .createClassificationReportBuilder() .withColumnHeaders(columnHeaders) .inWorkingDays() .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - int sumLineCount = IntStream.of(report.getSumRow().getCells()).sum(); - - assertNotNull(report); - assertEquals(5, report.rowSize()); - - assertEquals(10, report.getRow("L10000").getTotalValue()); - assertEquals(10, report.getRow("L20000").getTotalValue()); - assertEquals(7, report.getRow("L30000").getTotalValue()); - assertEquals(10, report.getRow("L40000").getTotalValue()); - assertEquals(13, report.getRow("L50000").getTotalValue()); - - assertEquals(10, report.getSumRow().getCells()[0]); - assertEquals(9, report.getSumRow().getCells()[1]); - assertEquals(11, report.getSumRow().getCells()[2]); - assertEquals(0, report.getSumRow().getCells()[3]); - assertEquals(4, report.getSumRow().getCells()[4]); - assertEquals(0, report.getSumRow().getCells()[5]); - assertEquals(7, report.getSumRow().getCells()[6]); - assertEquals(4, report.getSumRow().getCells()[7]); - assertEquals(5, report.getSumRow().getCells()[8]); - assertEquals(50, report.getSumRow().getTotalValue()); - assertEquals(50, sumLineCount); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfClassificationReport() throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + int sumLineCount = IntStream.of(report.getSumRow().getCells()).sum(); - List columnHeaders = getShortListOfColumnHeaders(); + assertNotNull(report); + assertEquals(5, report.rowSize()); - ClassificationReport report = taskMonitorService.createClassificationReportBuilder() + assertEquals(10, report.getRow("L10000").getTotalValue()); + assertEquals(10, report.getRow("L20000").getTotalValue()); + assertEquals(7, report.getRow("L30000").getTotalValue()); + assertEquals(10, report.getRow("L40000").getTotalValue()); + assertEquals(13, report.getRow("L50000").getTotalValue()); + + assertEquals(10, report.getSumRow().getCells()[0]); + assertEquals(9, report.getSumRow().getCells()[1]); + assertEquals(11, report.getSumRow().getCells()[2]); + assertEquals(0, report.getSumRow().getCells()[3]); + assertEquals(4, report.getSumRow().getCells()[4]); + assertEquals(0, report.getSumRow().getCells()[5]); + assertEquals(7, report.getSumRow().getCells()[6]); + assertEquals(4, report.getSumRow().getCells()[7]); + assertEquals(5, report.getSumRow().getCells()[8]); + assertEquals(50, report.getSumRow().getTotalValue()); + assertEquals(50, sumLineCount); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfClassificationReport() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List columnHeaders = getShortListOfColumnHeaders(); + + ClassificationReport report = + taskMonitorService + .createClassificationReportBuilder() .withColumnHeaders(columnHeaders) .inWorkingDays() .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(5, report.rowSize()); - - int[] row1 = report.getRow("L10000").getCells(); - assertArrayEquals(new int[] {7, 2, 1, 0, 0}, row1); - - int[] row2 = report.getRow("L20000").getCells(); - assertArrayEquals(new int[] {5, 3, 1, 1, 0}, row2); - - int[] row3 = report.getRow("L30000").getCells(); - assertArrayEquals(new int[] {2, 1, 0, 1, 3}, row3); - - int[] row4 = report.getRow("L40000").getCells(); - assertArrayEquals(new int[] {2, 2, 2, 0, 4}, row4); - - int[] row5 = report.getRow("L50000").getCells(); - assertArrayEquals(new int[] {3, 3, 0, 5, 2}, row5); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfClassificationReportNotInWorkingDays() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(5, report.rowSize()); - List columnHeaders = getShortListOfColumnHeaders(); + int[] row1 = report.getRow("L10000").getCells(); + assertArrayEquals(new int[] {7, 2, 1, 0, 0}, row1); - ClassificationReport report = taskMonitorService.createClassificationReportBuilder() + int[] row2 = report.getRow("L20000").getCells(); + assertArrayEquals(new int[] {5, 3, 1, 1, 0}, row2); + + int[] row3 = report.getRow("L30000").getCells(); + assertArrayEquals(new int[] {2, 1, 0, 1, 3}, row3); + + int[] row4 = report.getRow("L40000").getCells(); + assertArrayEquals(new int[] {2, 2, 2, 0, 4}, row4); + + int[] row5 = report.getRow("L50000").getCells(); + assertArrayEquals(new int[] {3, 3, 0, 5, 2}, row5); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfClassificationReportNotInWorkingDays() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List columnHeaders = getShortListOfColumnHeaders(); + + ClassificationReport report = + taskMonitorService + .createClassificationReportBuilder() .withColumnHeaders(columnHeaders) .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(5, report.rowSize()); - - int[] row1 = report.getRow("L10000").getCells(); - assertArrayEquals(new int[] {9, 0, 1, 0, 0}, row1); - - int[] row2 = report.getRow("L20000").getCells(); - assertArrayEquals(new int[] {8, 0, 1, 0, 1}, row2); - - int[] row3 = report.getRow("L30000").getCells(); - assertArrayEquals(new int[] {3, 0, 0, 0, 4}, row3); - - int[] row4 = report.getRow("L40000").getCells(); - assertArrayEquals(new int[] {4, 0, 2, 0, 4}, row4); - - int[] row5 = report.getRow("L50000").getCells(); - assertArrayEquals(new int[] {6, 0, 0, 0, 7}, row5); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfClassificationReportWithWorkbasketFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(5, report.rowSize()); - List workbasketIds = Collections.singletonList("WBI:000000000000000000000000000000000001"); - List columnHeaders = getShortListOfColumnHeaders(); + int[] row1 = report.getRow("L10000").getCells(); + assertArrayEquals(new int[] {9, 0, 1, 0, 0}, row1); - ClassificationReport report = taskMonitorService.createClassificationReportBuilder() + int[] row2 = report.getRow("L20000").getCells(); + assertArrayEquals(new int[] {8, 0, 1, 0, 1}, row2); + + int[] row3 = report.getRow("L30000").getCells(); + assertArrayEquals(new int[] {3, 0, 0, 0, 4}, row3); + + int[] row4 = report.getRow("L40000").getCells(); + assertArrayEquals(new int[] {4, 0, 2, 0, 4}, row4); + + int[] row5 = report.getRow("L50000").getCells(); + assertArrayEquals(new int[] {6, 0, 0, 0, 7}, row5); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfClassificationReportWithWorkbasketFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List workbasketIds = + Collections.singletonList("WBI:000000000000000000000000000000000001"); + List columnHeaders = getShortListOfColumnHeaders(); + + ClassificationReport report = + taskMonitorService + .createClassificationReportBuilder() .withColumnHeaders(columnHeaders) .workbasketIdIn(workbasketIds) .inWorkingDays() .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(5, report.rowSize()); - - int[] row1 = report.getRow("L10000").getCells(); - assertArrayEquals(new int[] {6, 0, 0, 0, 0}, row1); - - int[] row2 = report.getRow("L20000").getCells(); - assertArrayEquals(new int[] {2, 0, 0, 0, 0}, row2); - - int[] row3 = report.getRow("L30000").getCells(); - assertArrayEquals(new int[] {2, 1, 0, 1, 1}, row3); - - int[] row4 = report.getRow("L40000").getCells(); - assertArrayEquals(new int[] {1, 0, 1, 0, 1}, row4); - - int[] row5 = report.getRow("L50000").getCells(); - assertArrayEquals(new int[] {2, 2, 0, 0, 0}, row5); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfClassificationReportWithStateFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(5, report.rowSize()); - List states = Collections.singletonList(TaskState.READY); - List columnHeaders = getShortListOfColumnHeaders(); + int[] row1 = report.getRow("L10000").getCells(); + assertArrayEquals(new int[] {6, 0, 0, 0, 0}, row1); - ClassificationReport report = taskMonitorService.createClassificationReportBuilder() + int[] row2 = report.getRow("L20000").getCells(); + assertArrayEquals(new int[] {2, 0, 0, 0, 0}, row2); + + int[] row3 = report.getRow("L30000").getCells(); + assertArrayEquals(new int[] {2, 1, 0, 1, 1}, row3); + + int[] row4 = report.getRow("L40000").getCells(); + assertArrayEquals(new int[] {1, 0, 1, 0, 1}, row4); + + int[] row5 = report.getRow("L50000").getCells(); + assertArrayEquals(new int[] {2, 2, 0, 0, 0}, row5); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfClassificationReportWithStateFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List states = Collections.singletonList(TaskState.READY); + List columnHeaders = getShortListOfColumnHeaders(); + + ClassificationReport report = + taskMonitorService + .createClassificationReportBuilder() .withColumnHeaders(columnHeaders) .stateIn(states) .inWorkingDays() .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(5, report.rowSize()); - - int[] row1 = report.getRow("L10000").getCells(); - assertArrayEquals(new int[] {7, 2, 1, 0, 0}, row1); - - int[] row2 = report.getRow("L20000").getCells(); - assertArrayEquals(new int[] {5, 3, 1, 1, 0}, row2); - - int[] row3 = report.getRow("L30000").getCells(); - assertArrayEquals(new int[] {2, 1, 0, 1, 0}, row3); - - int[] row4 = report.getRow("L40000").getCells(); - assertArrayEquals(new int[] {2, 2, 2, 0, 0}, row4); - - int[] row5 = report.getRow("L50000").getCells(); - assertArrayEquals(new int[] {3, 3, 0, 5, 0}, row5); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfClassificationReportWithCategoryFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(5, report.rowSize()); - List categories = Arrays.asList("AUTOMATIC", "MANUAL"); - List columnHeaders = getShortListOfColumnHeaders(); + int[] row1 = report.getRow("L10000").getCells(); + assertArrayEquals(new int[] {7, 2, 1, 0, 0}, row1); - ClassificationReport report = taskMonitorService.createClassificationReportBuilder() + int[] row2 = report.getRow("L20000").getCells(); + assertArrayEquals(new int[] {5, 3, 1, 1, 0}, row2); + + int[] row3 = report.getRow("L30000").getCells(); + assertArrayEquals(new int[] {2, 1, 0, 1, 0}, row3); + + int[] row4 = report.getRow("L40000").getCells(); + assertArrayEquals(new int[] {2, 2, 2, 0, 0}, row4); + + int[] row5 = report.getRow("L50000").getCells(); + assertArrayEquals(new int[] {3, 3, 0, 5, 0}, row5); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfClassificationReportWithCategoryFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List categories = Arrays.asList("AUTOMATIC", "MANUAL"); + List columnHeaders = getShortListOfColumnHeaders(); + + ClassificationReport report = + taskMonitorService + .createClassificationReportBuilder() .withColumnHeaders(columnHeaders) .categoryIn(categories) .inWorkingDays() .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(2, report.rowSize()); - - int[] row1 = report.getRow("L30000").getCells(); - assertArrayEquals(new int[] {2, 1, 0, 1, 3}, row1); - - int[] row2 = report.getRow("L40000").getCells(); - assertArrayEquals(new int[] {2, 2, 2, 0, 4}, row2); - + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfClassificationReportWithDomainFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(2, report.rowSize()); - List domains = Collections.singletonList("DOMAIN_A"); - List columnHeaders = getShortListOfColumnHeaders(); + int[] row1 = report.getRow("L30000").getCells(); + assertArrayEquals(new int[] {2, 1, 0, 1, 3}, row1); - ClassificationReport report = taskMonitorService.createClassificationReportBuilder() + int[] row2 = report.getRow("L40000").getCells(); + assertArrayEquals(new int[] {2, 2, 2, 0, 4}, row2); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfClassificationReportWithDomainFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List domains = Collections.singletonList("DOMAIN_A"); + List columnHeaders = getShortListOfColumnHeaders(); + + ClassificationReport report = + taskMonitorService + .createClassificationReportBuilder() .withColumnHeaders(columnHeaders) .domainIn(domains) .inWorkingDays() .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(5, report.rowSize()); - - int[] row1 = report.getRow("L10000").getCells(); - assertArrayEquals(new int[] {5, 2, 1, 0, 0}, row1); - - int[] row2 = report.getRow("L20000").getCells(); - assertArrayEquals(new int[] {3, 1, 1, 1, 0}, row2); - - int[] row3 = report.getRow("L30000").getCells(); - assertArrayEquals(new int[] {1, 0, 0, 1, 1}, row3); - - int[] row4 = report.getRow("L40000").getCells(); - assertArrayEquals(new int[] {2, 0, 0, 0, 3}, row4); - - int[] row5 = report.getRow("L50000").getCells(); - assertArrayEquals(new int[] {0, 1, 0, 3, 0}, row5); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfClassificationReportWithCustomFieldValueFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(5, report.rowSize()); - Map customAttributeFilter = new HashMap<>(); - customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); - List columnHeaders = getShortListOfColumnHeaders(); + int[] row1 = report.getRow("L10000").getCells(); + assertArrayEquals(new int[] {5, 2, 1, 0, 0}, row1); - ClassificationReport report = taskMonitorService.createClassificationReportBuilder() + int[] row2 = report.getRow("L20000").getCells(); + assertArrayEquals(new int[] {3, 1, 1, 1, 0}, row2); + + int[] row3 = report.getRow("L30000").getCells(); + assertArrayEquals(new int[] {1, 0, 0, 1, 1}, row3); + + int[] row4 = report.getRow("L40000").getCells(); + assertArrayEquals(new int[] {2, 0, 0, 0, 3}, row4); + + int[] row5 = report.getRow("L50000").getCells(); + assertArrayEquals(new int[] {0, 1, 0, 3, 0}, row5); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfClassificationReportWithCustomFieldValueFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + Map customAttributeFilter = new HashMap<>(); + customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); + List columnHeaders = getShortListOfColumnHeaders(); + + ClassificationReport report = + taskMonitorService + .createClassificationReportBuilder() .withColumnHeaders(columnHeaders) .customAttributeFilterIn(customAttributeFilter) .inWorkingDays() .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(5, report.rowSize()); - - int[] row1 = report.getRow("L10000").getCells(); - assertArrayEquals(new int[] {4, 0, 0, 0, 0}, row1); - - int[] row2 = report.getRow("L20000").getCells(); - assertArrayEquals(new int[] {4, 1, 1, 1, 0}, row2); - - int[] row3 = report.getRow("L30000").getCells(); - assertArrayEquals(new int[] {1, 0, 0, 1, 1}, row3); - - int[] row4 = report.getRow("L40000").getCells(); - assertArrayEquals(new int[] {1, 1, 2, 0, 2}, row4); - - int[] row5 = report.getRow("L50000").getCells(); - assertArrayEquals(new int[] {1, 2, 0, 2, 0}, row5); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - private List getListOfColumnsHeaders() { - List columnHeaders = new ArrayList<>(); - columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -11)); - columnHeaders.add(new TimeIntervalColumnHeader(-10, -6)); - columnHeaders.add(new TimeIntervalColumnHeader(-5, -2)); - columnHeaders.add(new TimeIntervalColumnHeader(-1)); - columnHeaders.add(new TimeIntervalColumnHeader(0)); - columnHeaders.add(new TimeIntervalColumnHeader(1)); - columnHeaders.add(new TimeIntervalColumnHeader(2, 5)); - columnHeaders.add(new TimeIntervalColumnHeader(6, 10)); - columnHeaders.add(new TimeIntervalColumnHeader(11, Integer.MAX_VALUE)); - return columnHeaders; + assertNotNull(report); + assertEquals(5, report.rowSize()); + + int[] row1 = report.getRow("L10000").getCells(); + assertArrayEquals(new int[] {4, 0, 0, 0, 0}, row1); + + int[] row2 = report.getRow("L20000").getCells(); + assertArrayEquals(new int[] {4, 1, 1, 1, 0}, row2); + + int[] row3 = report.getRow("L30000").getCells(); + assertArrayEquals(new int[] {1, 0, 0, 1, 1}, row3); + + int[] row4 = report.getRow("L40000").getCells(); + assertArrayEquals(new int[] {1, 1, 2, 0, 2}, row4); + + int[] row5 = report.getRow("L50000").getCells(); + assertArrayEquals(new int[] {1, 2, 0, 2, 0}, row5); + } + + private List getListOfColumnsHeaders() { + List columnHeaders = new ArrayList<>(); + columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -11)); + columnHeaders.add(new TimeIntervalColumnHeader(-10, -6)); + columnHeaders.add(new TimeIntervalColumnHeader(-5, -2)); + columnHeaders.add(new TimeIntervalColumnHeader(-1)); + columnHeaders.add(new TimeIntervalColumnHeader(0)); + columnHeaders.add(new TimeIntervalColumnHeader(1)); + columnHeaders.add(new TimeIntervalColumnHeader(2, 5)); + columnHeaders.add(new TimeIntervalColumnHeader(6, 10)); + columnHeaders.add(new TimeIntervalColumnHeader(11, Integer.MAX_VALUE)); + return columnHeaders; + } + + private List getShortListOfColumnHeaders() { + List reportLineItemDefinitions = new ArrayList<>(); + reportLineItemDefinitions.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -6)); + reportLineItemDefinitions.add(new TimeIntervalColumnHeader(-5, -1)); + reportLineItemDefinitions.add(new TimeIntervalColumnHeader(0)); + reportLineItemDefinitions.add(new TimeIntervalColumnHeader(1, 5)); + reportLineItemDefinitions.add(new TimeIntervalColumnHeader(6, Integer.MAX_VALUE)); + return reportLineItemDefinitions; + } + + private String reportToString(ClassificationReport report) { + return reportToString(report, null); + } + + private String reportToString( + ClassificationReport report, List columnHeaders) { + String formatColumWidth = "| %-7s "; + String formatFirstColumn = "| %-36s %-4s "; + String formatFirstColumnFirstLine = "| %-29s %12s "; + String formatFirstColumnSumLine = "| %-36s %-5s"; + int reportWidth = columnHeaders == null ? 46 : columnHeaders.size() * 10 + 46; + + StringBuilder builder = new StringBuilder(); + builder.append("\n"); + for (int i = 0; i < reportWidth; i++) { + builder.append("-"); } - - private List getShortListOfColumnHeaders() { - List reportLineItemDefinitions = new ArrayList<>(); - reportLineItemDefinitions.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -6)); - reportLineItemDefinitions.add(new TimeIntervalColumnHeader(-5, -1)); - reportLineItemDefinitions.add(new TimeIntervalColumnHeader(0)); - reportLineItemDefinitions.add(new TimeIntervalColumnHeader(1, 5)); - reportLineItemDefinitions.add(new TimeIntervalColumnHeader(6, Integer.MAX_VALUE)); - return reportLineItemDefinitions; + builder.append("\n"); + builder.append(String.format(formatFirstColumnFirstLine, "Classifications", "Total")); + if (columnHeaders != null) { + for (TimeIntervalColumnHeader def : columnHeaders) { + if (def.getLowerAgeLimit() == Integer.MIN_VALUE) { + builder.append(String.format(formatColumWidth, "< " + def.getUpperAgeLimit())); + } else if (def.getUpperAgeLimit() == Integer.MAX_VALUE) { + builder.append(String.format(formatColumWidth, "> " + def.getLowerAgeLimit())); + } else if (def.getLowerAgeLimit() == def.getUpperAgeLimit()) { + if (def.getLowerAgeLimit() == 0) { + builder.append(String.format(formatColumWidth, "today")); + } else { + builder.append(String.format(formatColumWidth, def.getLowerAgeLimit())); + } + } else { + builder.append( + String.format( + formatColumWidth, def.getLowerAgeLimit() + ".." + def.getUpperAgeLimit())); + } + } } + builder.append("|\n"); - private String reportToString(ClassificationReport report) { - return reportToString(report, null); + for (int i = 0; i < reportWidth; i++) { + builder.append("-"); } + builder.append("\n"); - private String reportToString(ClassificationReport report, List columnHeaders) { - String formatColumWidth = "| %-7s "; - String formatFirstColumn = "| %-36s %-4s "; - String formatFirstColumnFirstLine = "| %-29s %12s "; - String formatFirstColumnSumLine = "| %-36s %-5s"; - int reportWidth = columnHeaders == null ? 46 : columnHeaders.size() * 10 + 46; - - StringBuilder builder = new StringBuilder(); - builder.append("\n"); - for (int i = 0; i < reportWidth; i++) { - builder.append("-"); + for (String rl : report.rowTitles()) { + builder.append(String.format(formatFirstColumn, rl, report.getRow(rl).getTotalValue())); + if (columnHeaders != null) { + for (int cell : report.getRow(rl).getCells()) { + builder.append(String.format(formatColumWidth, cell)); } - builder.append("\n"); - builder.append(String.format(formatFirstColumnFirstLine, "Classifications", "Total")); - if (columnHeaders != null) { - for (TimeIntervalColumnHeader def : columnHeaders) { - if (def.getLowerAgeLimit() == Integer.MIN_VALUE) { - builder.append(String.format(formatColumWidth, "< " + def.getUpperAgeLimit())); - } else if (def.getUpperAgeLimit() == Integer.MAX_VALUE) { - builder.append(String.format(formatColumWidth, "> " + def.getLowerAgeLimit())); - } else if (def.getLowerAgeLimit() == def.getUpperAgeLimit()) { - if (def.getLowerAgeLimit() == 0) { - builder.append(String.format(formatColumWidth, "today")); - } else { - builder.append(String.format(formatColumWidth, def.getLowerAgeLimit())); - } - } else { - builder.append( - String.format(formatColumWidth, def.getLowerAgeLimit() + ".." + def.getUpperAgeLimit())); - } - } - } - builder.append("|\n"); - - for (int i = 0; i < reportWidth; i++) { - builder.append("-"); - } - builder.append("\n"); - - for (String rl : report.rowTitles()) { - builder - .append(String.format(formatFirstColumn, rl, report.getRow(rl).getTotalValue())); - if (columnHeaders != null) { - for (int cell : report.getRow(rl).getCells()) { - builder.append(String.format(formatColumWidth, cell)); - } - } - builder.append("|\n"); - for (int i = 0; i < reportWidth; i++) { - builder.append("-"); - } - builder.append("\n"); - } - builder.append(String.format(formatFirstColumnSumLine, "Total", report.getSumRow().getTotalValue())); - for (int cell : report.getSumRow().getCells()) { - builder.append(String.format(formatColumWidth, cell)); - } - builder.append("|\n"); - for (int i = 0; i < reportWidth; i++) { - builder.append("-"); - } - builder.append("\n"); - return builder.toString(); + } + builder.append("|\n"); + for (int i = 0; i < reportWidth; i++) { + builder.append("-"); + } + builder.append("\n"); } - + builder.append( + String.format(formatFirstColumnSumLine, "Total", report.getSumRow().getTotalValue())); + for (int cell : report.getSumRow().getCells()) { + builder.append(String.format(formatColumWidth, cell)); + } + builder.append("|\n"); + for (int i = 0; i < reportWidth; i++) { + builder.append("-"); + } + builder.append("\n"); + return builder.toString(); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/report/ProvideCustomFieldValueReportAccTest.java b/lib/taskana-core/src/test/java/acceptance/report/ProvideCustomFieldValueReportAccTest.java index e3ddd9ed3..b9b591692 100644 --- a/lib/taskana-core/src/test/java/acceptance/report/ProvideCustomFieldValueReportAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/report/ProvideCustomFieldValueReportAccTest.java @@ -10,7 +10,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -27,417 +26,429 @@ import pro.taskana.report.CustomFieldValueReport; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "classification report" scenarios. - */ +/** Acceptance test for all "classification report" scenarios. */ @ExtendWith(JAASExtension.class) class ProvideCustomFieldValueReportAccTest extends AbstractReportAccTest { - private static final Logger LOGGER = LoggerFactory.getLogger(ProvideCustomFieldValueReportAccTest.class); + private static final Logger LOGGER = + LoggerFactory.getLogger(ProvideCustomFieldValueReportAccTest.class); - @Test - void testRoleCheck() { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @Test + void testRoleCheck() { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - Assertions.assertThrows(NotAuthorizedException.class, () -> - taskMonitorService.createCustomFieldValueReportBuilder(CustomField.CUSTOM_1).buildReport()); + Assertions.assertThrows( + NotAuthorizedException.class, + () -> + taskMonitorService + .createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) + .buildReport()); + } + + @WithAccessId(userName = "monitor") + @Test + void testGetTotalNumbersOfTasksOfCustomFieldValueReportForCustom1() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + CustomFieldValueReport report = + taskMonitorService.createCustomFieldValueReportBuilder(CustomField.CUSTOM_1).buildReport(); + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report)); } - @WithAccessId( - userName = "monitor") - @Test - void testGetTotalNumbersOfTasksOfCustomFieldValueReportForCustom1() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(3, report.rowSize()); - CustomFieldValueReport report = taskMonitorService.createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) - .buildReport(); + assertEquals(25, report.getRow("Geschaeftsstelle A").getTotalValue()); + assertEquals(10, report.getRow("Geschaeftsstelle B").getTotalValue()); + assertEquals(15, report.getRow("Geschaeftsstelle C").getTotalValue()); + assertEquals(0, report.getRow("Geschaeftsstelle A").getCells().length); + assertEquals(0, report.getRow("Geschaeftsstelle B").getCells().length); + assertEquals(0, report.getRow("Geschaeftsstelle C").getCells().length); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report)); - } + assertEquals(50, report.getSumRow().getTotalValue()); + } - assertNotNull(report); - assertEquals(3, report.rowSize()); + @WithAccessId(userName = "monitor") + @Test + void testGetTotalNumbersOfTasksOfCustomFieldValueReportForCustom2() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - assertEquals(25, report.getRow("Geschaeftsstelle A").getTotalValue()); - assertEquals(10, report.getRow("Geschaeftsstelle B").getTotalValue()); - assertEquals(15, report.getRow("Geschaeftsstelle C").getTotalValue()); - assertEquals(0, report.getRow("Geschaeftsstelle A").getCells().length); - assertEquals(0, report.getRow("Geschaeftsstelle B").getCells().length); - assertEquals(0, report.getRow("Geschaeftsstelle C").getCells().length); + CustomFieldValueReport report = + taskMonitorService.createCustomFieldValueReportBuilder(CustomField.CUSTOM_2).buildReport(); - assertEquals(50, report.getSumRow().getTotalValue()); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report)); } - @WithAccessId( - userName = "monitor") - @Test - void testGetTotalNumbersOfTasksOfCustomFieldValueReportForCustom2() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(2, report.rowSize()); - CustomFieldValueReport report = taskMonitorService.createCustomFieldValueReportBuilder(CustomField.CUSTOM_2) - .buildReport(); + assertEquals(21, report.getRow("Vollkasko").getTotalValue()); + assertEquals(29, report.getRow("Teilkasko").getTotalValue()); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report)); - } + assertEquals(0, report.getRow("Vollkasko").getCells().length); + assertEquals(0, report.getRow("Teilkasko").getCells().length); - assertNotNull(report); - assertEquals(2, report.rowSize()); + assertEquals(50, report.getSumRow().getTotalValue()); + } - assertEquals(21, report.getRow("Vollkasko").getTotalValue()); - assertEquals(29, report.getRow("Teilkasko").getTotalValue()); + @WithAccessId(userName = "monitor") + @Test + void testGetCustomFieldValueReportWithReportLineItemDefinitions() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - assertEquals(0, report.getRow("Vollkasko").getCells().length); - assertEquals(0, report.getRow("Teilkasko").getCells().length); + CustomField customField = CustomField.CUSTOM_1; + List columnHeaders = getListOfColumnHeaders(); - assertEquals(50, report.getSumRow().getTotalValue()); - } - - @WithAccessId( - userName = "monitor") - @Test - void testGetCustomFieldValueReportWithReportLineItemDefinitions() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - - CustomField customField = CustomField.CUSTOM_1; - List columnHeaders = getListOfColumnHeaders(); - - CustomFieldValueReport report = taskMonitorService.createCustomFieldValueReportBuilder(customField) + CustomFieldValueReport report = + taskMonitorService + .createCustomFieldValueReportBuilder(customField) .withColumnHeaders(columnHeaders) .inWorkingDays() .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(3, report.rowSize()); - - assertEquals(25, report.getRow("Geschaeftsstelle A").getTotalValue()); - assertEquals(10, report.getRow("Geschaeftsstelle B").getTotalValue()); - assertEquals(15, report.getRow("Geschaeftsstelle C").getTotalValue()); - - assertArrayEquals(new int[] {10, 9, 11, 0, 4, 0, 7, 4, 5}, report.getSumRow().getCells()); - - assertEquals(50, report.getSumRow().getTotalValue()); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfCustomFieldValueReport() throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(3, report.rowSize()); - List columnHeaders = getShortListOfColumnHeaders(); + assertEquals(25, report.getRow("Geschaeftsstelle A").getTotalValue()); + assertEquals(10, report.getRow("Geschaeftsstelle B").getTotalValue()); + assertEquals(15, report.getRow("Geschaeftsstelle C").getTotalValue()); - CustomFieldValueReport report = taskMonitorService.createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) + assertArrayEquals(new int[] {10, 9, 11, 0, 4, 0, 7, 4, 5}, report.getSumRow().getCells()); + + assertEquals(50, report.getSumRow().getTotalValue()); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfCustomFieldValueReport() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List columnHeaders = getShortListOfColumnHeaders(); + + CustomFieldValueReport report = + taskMonitorService + .createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) .withColumnHeaders(columnHeaders) .inWorkingDays() .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(3, report.rowSize()); - - int[] row1 = report.getRow("Geschaeftsstelle A").getCells(); - assertArrayEquals(new int[] {11, 4, 3, 4, 3}, row1); - - int[] row2 = report.getRow("Geschaeftsstelle B").getCells(); - assertArrayEquals(new int[] {5, 3, 0, 2, 0}, row2); - - int[] row3 = report.getRow("Geschaeftsstelle C").getCells(); - assertArrayEquals(new int[] {3, 4, 1, 1, 6}, row3); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfCustomFieldValueReportNotInWorkingDays() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(3, report.rowSize()); - List columnHeaders = getShortListOfColumnHeaders(); + int[] row1 = report.getRow("Geschaeftsstelle A").getCells(); + assertArrayEquals(new int[] {11, 4, 3, 4, 3}, row1); - CustomFieldValueReport report = taskMonitorService.createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) + int[] row2 = report.getRow("Geschaeftsstelle B").getCells(); + assertArrayEquals(new int[] {5, 3, 0, 2, 0}, row2); + + int[] row3 = report.getRow("Geschaeftsstelle C").getCells(); + assertArrayEquals(new int[] {3, 4, 1, 1, 6}, row3); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfCustomFieldValueReportNotInWorkingDays() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List columnHeaders = getShortListOfColumnHeaders(); + + CustomFieldValueReport report = + taskMonitorService + .createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) .withColumnHeaders(columnHeaders) .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(3, report.rowSize()); - - int[] row1 = report.getRow("Geschaeftsstelle A").getCells(); - assertArrayEquals(new int[] {15, 0, 3, 0, 7}, row1); - - int[] row2 = report.getRow("Geschaeftsstelle B").getCells(); - assertArrayEquals(new int[] {8, 0, 0, 0, 2}, row2); - - int[] row3 = report.getRow("Geschaeftsstelle C").getCells(); - assertArrayEquals(new int[] {7, 0, 1, 0, 7}, row3); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfCustomFieldValueReportWithWorkbasketFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(3, report.rowSize()); - List workbasketIds = Collections.singletonList("WBI:000000000000000000000000000000000001"); - List columnHeaders = getShortListOfColumnHeaders(); + int[] row1 = report.getRow("Geschaeftsstelle A").getCells(); + assertArrayEquals(new int[] {15, 0, 3, 0, 7}, row1); - CustomFieldValueReport report = taskMonitorService.createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) + int[] row2 = report.getRow("Geschaeftsstelle B").getCells(); + assertArrayEquals(new int[] {8, 0, 0, 0, 2}, row2); + + int[] row3 = report.getRow("Geschaeftsstelle C").getCells(); + assertArrayEquals(new int[] {7, 0, 1, 0, 7}, row3); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfCustomFieldValueReportWithWorkbasketFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List workbasketIds = + Collections.singletonList("WBI:000000000000000000000000000000000001"); + List columnHeaders = getShortListOfColumnHeaders(); + + CustomFieldValueReport report = + taskMonitorService + .createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) .withColumnHeaders(columnHeaders) .inWorkingDays() .workbasketIdIn(workbasketIds) .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(3, report.rowSize()); - - int[] row1 = report.getRow("Geschaeftsstelle A").getCells(); - assertArrayEquals(new int[] {6, 1, 1, 1, 1}, row1); - - int[] row2 = report.getRow("Geschaeftsstelle B").getCells(); - assertArrayEquals(new int[] {4, 1, 0, 0, 0}, row2); - - int[] row3 = report.getRow("Geschaeftsstelle C").getCells(); - assertArrayEquals(new int[] {3, 1, 0, 0, 1}, row3); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfCustomFieldValueReportWithStateFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(3, report.rowSize()); - List states = Collections.singletonList(TaskState.READY); - List columnHeaders = getShortListOfColumnHeaders(); + int[] row1 = report.getRow("Geschaeftsstelle A").getCells(); + assertArrayEquals(new int[] {6, 1, 1, 1, 1}, row1); - CustomFieldValueReport report = taskMonitorService.createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) + int[] row2 = report.getRow("Geschaeftsstelle B").getCells(); + assertArrayEquals(new int[] {4, 1, 0, 0, 0}, row2); + + int[] row3 = report.getRow("Geschaeftsstelle C").getCells(); + assertArrayEquals(new int[] {3, 1, 0, 0, 1}, row3); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfCustomFieldValueReportWithStateFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List states = Collections.singletonList(TaskState.READY); + List columnHeaders = getShortListOfColumnHeaders(); + + CustomFieldValueReport report = + taskMonitorService + .createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) .withColumnHeaders(columnHeaders) .inWorkingDays() .stateIn(states) .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(3, report.rowSize()); - - int[] row1 = report.getRow("Geschaeftsstelle A").getCells(); - assertArrayEquals(new int[] {11, 4, 3, 4, 0}, row1); - - int[] row2 = report.getRow("Geschaeftsstelle B").getCells(); - assertArrayEquals(new int[] {5, 3, 0, 2, 0}, row2); - - int[] row3 = report.getRow("Geschaeftsstelle C").getCells(); - assertArrayEquals(new int[] {3, 4, 1, 1, 0}, row3); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfCustomFieldValueReportWithCategoryFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(3, report.rowSize()); - List categories = Arrays.asList("AUTOMATIC", "MANUAL"); - List columnHeaders = getShortListOfColumnHeaders(); + int[] row1 = report.getRow("Geschaeftsstelle A").getCells(); + assertArrayEquals(new int[] {11, 4, 3, 4, 0}, row1); - CustomFieldValueReport report = taskMonitorService.createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) + int[] row2 = report.getRow("Geschaeftsstelle B").getCells(); + assertArrayEquals(new int[] {5, 3, 0, 2, 0}, row2); + + int[] row3 = report.getRow("Geschaeftsstelle C").getCells(); + assertArrayEquals(new int[] {3, 4, 1, 1, 0}, row3); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfCustomFieldValueReportWithCategoryFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List categories = Arrays.asList("AUTOMATIC", "MANUAL"); + List columnHeaders = getShortListOfColumnHeaders(); + + CustomFieldValueReport report = + taskMonitorService + .createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) .withColumnHeaders(columnHeaders) .inWorkingDays() .categoryIn(categories) .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(3, report.rowSize()); - - int[] row1 = report.getRow("Geschaeftsstelle A").getCells(); - assertArrayEquals(new int[] {2, 1, 2, 1, 3}, row1); - - int[] row2 = report.getRow("Geschaeftsstelle B").getCells(); - assertArrayEquals(new int[] {2, 0, 0, 0, 0}, row2); - - int[] row3 = report.getRow("Geschaeftsstelle C").getCells(); - assertArrayEquals(new int[] {0, 2, 0, 0, 4}, row3); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfCustomFieldValueReportWithDomainFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(3, report.rowSize()); - List domains = Collections.singletonList("DOMAIN_A"); - List columnHeaders = getShortListOfColumnHeaders(); + int[] row1 = report.getRow("Geschaeftsstelle A").getCells(); + assertArrayEquals(new int[] {2, 1, 2, 1, 3}, row1); - CustomFieldValueReport report = taskMonitorService.createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) + int[] row2 = report.getRow("Geschaeftsstelle B").getCells(); + assertArrayEquals(new int[] {2, 0, 0, 0, 0}, row2); + + int[] row3 = report.getRow("Geschaeftsstelle C").getCells(); + assertArrayEquals(new int[] {0, 2, 0, 0, 4}, row3); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfCustomFieldValueReportWithDomainFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List domains = Collections.singletonList("DOMAIN_A"); + List columnHeaders = getShortListOfColumnHeaders(); + + CustomFieldValueReport report = + taskMonitorService + .createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) .withColumnHeaders(columnHeaders) .inWorkingDays() .domainIn(domains) .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(3, report.rowSize()); - - int[] row1 = report.getRow("Geschaeftsstelle A").getCells(); - assertArrayEquals(new int[] {8, 1, 1, 4, 1}, row1); - - int[] row2 = report.getRow("Geschaeftsstelle B").getCells(); - assertArrayEquals(new int[] {2, 2, 0, 1, 0}, row2); - - int[] row3 = report.getRow("Geschaeftsstelle C").getCells(); - assertArrayEquals(new int[] {1, 1, 1, 0, 3}, row3); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfCustomFieldValueReportWithCustomFieldValueFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(3, report.rowSize()); - Map customAttributeFilter = new HashMap<>(); - customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); - List columnHeaders = getShortListOfColumnHeaders(); + int[] row1 = report.getRow("Geschaeftsstelle A").getCells(); + assertArrayEquals(new int[] {8, 1, 1, 4, 1}, row1); - CustomFieldValueReport report = taskMonitorService.createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) + int[] row2 = report.getRow("Geschaeftsstelle B").getCells(); + assertArrayEquals(new int[] {2, 2, 0, 1, 0}, row2); + + int[] row3 = report.getRow("Geschaeftsstelle C").getCells(); + assertArrayEquals(new int[] {1, 1, 1, 0, 3}, row3); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfCustomFieldValueReportWithCustomFieldValueFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + Map customAttributeFilter = new HashMap<>(); + customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); + List columnHeaders = getShortListOfColumnHeaders(); + + CustomFieldValueReport report = + taskMonitorService + .createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) .customAttributeFilterIn(customAttributeFilter) .withColumnHeaders(columnHeaders) .inWorkingDays() .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(1, report.rowSize()); - - int[] row1 = report.getRow("Geschaeftsstelle A").getCells(); - assertArrayEquals(new int[] {11, 4, 3, 4, 3}, row1); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - private List getListOfColumnHeaders() { - List columnHeaders = new ArrayList<>(); - columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -11)); - columnHeaders.add(new TimeIntervalColumnHeader(-10, -6)); - columnHeaders.add(new TimeIntervalColumnHeader(-5, -2)); - columnHeaders.add(new TimeIntervalColumnHeader(-1)); - columnHeaders.add(new TimeIntervalColumnHeader(0)); - columnHeaders.add(new TimeIntervalColumnHeader(1)); - columnHeaders.add(new TimeIntervalColumnHeader(2, 5)); - columnHeaders.add(new TimeIntervalColumnHeader(6, 10)); - columnHeaders.add(new TimeIntervalColumnHeader(11, Integer.MAX_VALUE)); - return columnHeaders; + assertNotNull(report); + assertEquals(1, report.rowSize()); + + int[] row1 = report.getRow("Geschaeftsstelle A").getCells(); + assertArrayEquals(new int[] {11, 4, 3, 4, 3}, row1); + } + + private List getListOfColumnHeaders() { + List columnHeaders = new ArrayList<>(); + columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -11)); + columnHeaders.add(new TimeIntervalColumnHeader(-10, -6)); + columnHeaders.add(new TimeIntervalColumnHeader(-5, -2)); + columnHeaders.add(new TimeIntervalColumnHeader(-1)); + columnHeaders.add(new TimeIntervalColumnHeader(0)); + columnHeaders.add(new TimeIntervalColumnHeader(1)); + columnHeaders.add(new TimeIntervalColumnHeader(2, 5)); + columnHeaders.add(new TimeIntervalColumnHeader(6, 10)); + columnHeaders.add(new TimeIntervalColumnHeader(11, Integer.MAX_VALUE)); + return columnHeaders; + } + + private List getShortListOfColumnHeaders() { + List columnHeaders = new ArrayList<>(); + columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -6)); + columnHeaders.add(new TimeIntervalColumnHeader(-5, -1)); + columnHeaders.add(new TimeIntervalColumnHeader(0)); + columnHeaders.add(new TimeIntervalColumnHeader(1, 5)); + columnHeaders.add(new TimeIntervalColumnHeader(6, Integer.MAX_VALUE)); + return columnHeaders; + } + + private String reportToString(CustomFieldValueReport report) { + return reportToString(report, null); + } + + private String reportToString( + CustomFieldValueReport report, List columnHeaders) { + String formatColumWidth = "| %-7s "; + String formatFirstColumn = "| %-36s %-4s "; + String formatFirstColumnFirstLine = "| %-29s %12s "; + String formatFirstColumnSumLine = "| %-36s %-5s"; + int reportWidth = columnHeaders == null ? 46 : columnHeaders.size() * 10 + 46; + + StringBuilder builder = new StringBuilder(); + builder.append("\n"); + for (int i = 0; i < reportWidth; i++) { + builder.append("-"); } - - private List getShortListOfColumnHeaders() { - List columnHeaders = new ArrayList<>(); - columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -6)); - columnHeaders.add(new TimeIntervalColumnHeader(-5, -1)); - columnHeaders.add(new TimeIntervalColumnHeader(0)); - columnHeaders.add(new TimeIntervalColumnHeader(1, 5)); - columnHeaders.add(new TimeIntervalColumnHeader(6, Integer.MAX_VALUE)); - return columnHeaders; + builder.append("\n"); + builder.append(String.format(formatFirstColumnFirstLine, "Custom field values", "Total")); + if (columnHeaders != null) { + for (TimeIntervalColumnHeader def : columnHeaders) { + if (def.getLowerAgeLimit() == Integer.MIN_VALUE) { + builder.append(String.format(formatColumWidth, "< " + def.getUpperAgeLimit())); + } else if (def.getUpperAgeLimit() == Integer.MAX_VALUE) { + builder.append(String.format(formatColumWidth, "> " + def.getLowerAgeLimit())); + } else if (def.getLowerAgeLimit() == def.getUpperAgeLimit()) { + if (def.getLowerAgeLimit() == 0) { + builder.append(String.format(formatColumWidth, "today")); + } else { + builder.append(String.format(formatColumWidth, def.getLowerAgeLimit())); + } + } else { + builder.append( + String.format( + formatColumWidth, def.getLowerAgeLimit() + ".." + def.getUpperAgeLimit())); + } + } } + builder.append("|\n"); - private String reportToString(CustomFieldValueReport report) { - return reportToString(report, null); + for (int i = 0; i < reportWidth; i++) { + builder.append("-"); } + builder.append("\n"); - private String reportToString(CustomFieldValueReport report, List columnHeaders) { - String formatColumWidth = "| %-7s "; - String formatFirstColumn = "| %-36s %-4s "; - String formatFirstColumnFirstLine = "| %-29s %12s "; - String formatFirstColumnSumLine = "| %-36s %-5s"; - int reportWidth = columnHeaders == null ? 46 : columnHeaders.size() * 10 + 46; - - StringBuilder builder = new StringBuilder(); - builder.append("\n"); - for (int i = 0; i < reportWidth; i++) { - builder.append("-"); + for (String rl : report.rowTitles()) { + builder.append(String.format(formatFirstColumn, rl, report.getRow(rl).getTotalValue())); + if (columnHeaders != null) { + for (int cell : report.getRow(rl).getCells()) { + builder.append(String.format(formatColumWidth, cell)); } - builder.append("\n"); - builder.append(String.format(formatFirstColumnFirstLine, "Custom field values", "Total")); - if (columnHeaders != null) { - for (TimeIntervalColumnHeader def : columnHeaders) { - if (def.getLowerAgeLimit() == Integer.MIN_VALUE) { - builder.append(String.format(formatColumWidth, "< " + def.getUpperAgeLimit())); - } else if (def.getUpperAgeLimit() == Integer.MAX_VALUE) { - builder.append(String.format(formatColumWidth, "> " + def.getLowerAgeLimit())); - } else if (def.getLowerAgeLimit() == def.getUpperAgeLimit()) { - if (def.getLowerAgeLimit() == 0) { - builder.append(String.format(formatColumWidth, "today")); - } else { - builder.append(String.format(formatColumWidth, def.getLowerAgeLimit())); - } - } else { - builder.append( - String.format(formatColumWidth, def.getLowerAgeLimit() + ".." + def.getUpperAgeLimit())); - } - } - } - builder.append("|\n"); - - for (int i = 0; i < reportWidth; i++) { - builder.append("-"); - } - builder.append("\n"); - - for (String rl : report.rowTitles()) { - builder - .append(String.format(formatFirstColumn, rl, report.getRow(rl).getTotalValue())); - if (columnHeaders != null) { - for (int cell : report.getRow(rl).getCells()) { - builder.append(String.format(formatColumWidth, cell)); - } - } - builder.append("|\n"); - for (int i = 0; i < reportWidth; i++) { - builder.append("-"); - } - builder.append("\n"); - } - builder.append(String.format(formatFirstColumnSumLine, "Total", report.getSumRow().getTotalValue())); - for (int cell : report.getSumRow().getCells()) { - builder.append(String.format(formatColumWidth, cell)); - } - builder.append("|\n"); - for (int i = 0; i < reportWidth; i++) { - builder.append("-"); - } - builder.append("\n"); - return builder.toString(); + } + builder.append("|\n"); + for (int i = 0; i < reportWidth; i++) { + builder.append("-"); + } + builder.append("\n"); } - + builder.append( + String.format(formatFirstColumnSumLine, "Total", report.getSumRow().getTotalValue())); + for (int cell : report.getSumRow().getCells()) { + builder.append(String.format(formatColumWidth, cell)); + } + builder.append("|\n"); + for (int i = 0; i < reportWidth; i++) { + builder.append("-"); + } + builder.append("\n"); + return builder.toString(); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/report/ProvideDetailedClassificationReportAccTest.java b/lib/taskana-core/src/test/java/acceptance/report/ProvideDetailedClassificationReportAccTest.java index 98129ca48..51e35ac45 100644 --- a/lib/taskana-core/src/test/java/acceptance/report/ProvideDetailedClassificationReportAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/report/ProvideDetailedClassificationReportAccTest.java @@ -10,7 +10,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -30,631 +29,641 @@ import pro.taskana.report.ClassificationReport.DetailedClassificationReport; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "detailed classification report" scenarios. - */ +/** Acceptance test for all "detailed classification report" scenarios. */ @ExtendWith(JAASExtension.class) class ProvideDetailedClassificationReportAccTest extends AbstractReportAccTest { - private static final Logger LOGGER = LoggerFactory.getLogger(ProvideDetailedClassificationReportAccTest.class); + private static final Logger LOGGER = + LoggerFactory.getLogger(ProvideDetailedClassificationReportAccTest.class); - @Test - void testRoleCheck() { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @Test + void testRoleCheck() { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - Assertions.assertThrows(NotAuthorizedException.class, () -> - taskMonitorService.createClassificationReportBuilder().buildDetailedReport()); + Assertions.assertThrows( + NotAuthorizedException.class, + () -> taskMonitorService.createClassificationReportBuilder().buildDetailedReport()); + } + + @WithAccessId(userName = "monitor") + @Test + void testGetTotalNumbersOfTasksOfDetailedClassificationReport() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + DetailedClassificationReport report = + taskMonitorService.createClassificationReportBuilder().buildDetailedReport(); + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report)); } - @WithAccessId( - userName = "monitor") - @Test - void testGetTotalNumbersOfTasksOfDetailedClassificationReport() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(5, report.rowSize()); - DetailedClassificationReport report = taskMonitorService.createClassificationReportBuilder() - .buildDetailedReport(); + FoldableRow row1 = report.getRow("L10000"); + assertEquals(10, row1.getTotalValue()); + assertEquals(3, row1.getFoldableRow("L11000").getTotalValue()); + assertEquals(7, row1.getFoldableRow("N/A").getTotalValue()); + assertEquals(0, row1.getCells().length); + assertEquals(2, row1.getFoldableRowCount()); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report)); - } + FoldableRow row2 = report.getRow("L20000"); + assertEquals(10, row2.getTotalValue()); + assertEquals(4, row2.getFoldableRow("L22000").getTotalValue()); + assertEquals(6, row2.getFoldableRow("N/A").getTotalValue()); + assertEquals(0, row2.getCells().length); + assertEquals(2, row2.getFoldableRowCount()); - assertNotNull(report); - assertEquals(5, report.rowSize()); + FoldableRow row3 = report.getRow("L30000"); + assertEquals(7, row3.getTotalValue()); + assertEquals(3, row3.getFoldableRow("L33000").getTotalValue()); + assertEquals(1, row3.getFoldableRow("L99000").getTotalValue()); + assertEquals(3, row3.getFoldableRow("N/A").getTotalValue()); + assertEquals(0, row3.getCells().length); + assertEquals(3, row3.getFoldableRowCount()); - FoldableRow row1 = report.getRow("L10000"); - assertEquals(10, row1.getTotalValue()); - assertEquals(3, row1.getFoldableRow("L11000").getTotalValue()); - assertEquals(7, row1.getFoldableRow("N/A").getTotalValue()); - assertEquals(0, row1.getCells().length); - assertEquals(2, row1.getFoldableRowCount()); + FoldableRow row4 = report.getRow("L40000"); + assertEquals(10, row4.getTotalValue()); + assertEquals(10, row4.getFoldableRow("N/A").getTotalValue()); + assertEquals(0, row4.getCells().length); + assertEquals(1, row4.getFoldableRowCount()); - FoldableRow row2 = report.getRow("L20000"); - assertEquals(10, row2.getTotalValue()); - assertEquals(4, row2.getFoldableRow("L22000").getTotalValue()); - assertEquals(6, row2.getFoldableRow("N/A").getTotalValue()); - assertEquals(0, row2.getCells().length); - assertEquals(2, row2.getFoldableRowCount()); + FoldableRow row5 = report.getRow("L50000"); + assertEquals(13, row5.getTotalValue()); + assertEquals(13, row5.getFoldableRow("N/A").getTotalValue()); + assertEquals(0, row5.getCells().length); + assertEquals(1, row5.getFoldableRowCount()); - FoldableRow row3 = report.getRow("L30000"); - assertEquals(7, row3.getTotalValue()); - assertEquals(3, row3.getFoldableRow("L33000").getTotalValue()); - assertEquals(1, row3.getFoldableRow("L99000").getTotalValue()); - assertEquals(3, row3.getFoldableRow("N/A").getTotalValue()); - assertEquals(0, row3.getCells().length); - assertEquals(3, row3.getFoldableRowCount()); + assertEquals(50, report.getSumRow().getTotalValue()); + } - FoldableRow row4 = report.getRow("L40000"); - assertEquals(10, row4.getTotalValue()); - assertEquals(10, row4.getFoldableRow("N/A").getTotalValue()); - assertEquals(0, row4.getCells().length); - assertEquals(1, row4.getFoldableRowCount()); + @WithAccessId(userName = "monitor") + @Test + void testGetDetailedClassificationReportWithReportLineItemDefinitions() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - FoldableRow row5 = report.getRow("L50000"); - assertEquals(13, row5.getTotalValue()); - assertEquals(13, row5.getFoldableRow("N/A").getTotalValue()); - assertEquals(0, row5.getCells().length); - assertEquals(1, row5.getFoldableRowCount()); + List columnHeaders = getListOfColumnHeaders(); - assertEquals(50, report.getSumRow().getTotalValue()); - } - - @WithAccessId( - userName = "monitor") - @Test - void testGetDetailedClassificationReportWithReportLineItemDefinitions() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - - List columnHeaders = getListOfColumnHeaders(); - - DetailedClassificationReport report = taskMonitorService.createClassificationReportBuilder() + DetailedClassificationReport report = + taskMonitorService + .createClassificationReportBuilder() .inWorkingDays() .withColumnHeaders(columnHeaders) .buildDetailedReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(5, report.rowSize()); - - assertEquals(10, report.getRow("L10000").getTotalValue()); - assertEquals(10, report.getRow("L20000").getTotalValue()); - assertEquals(7, report.getRow("L30000").getTotalValue()); - assertEquals(10, report.getRow("L40000").getTotalValue()); - assertEquals(13, report.getRow("L50000").getTotalValue()); - - int[] sumRow = report.getSumRow().getCells(); - assertArrayEquals(new int[] {10, 9, 11, 0, 4, 0, 7, 4, 5}, sumRow); - assertEquals(50, report.getSumRow().getTotalValue()); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfDetailedClassificationReport() throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(5, report.rowSize()); - List columnHeaders = getShortListOfColumnHeaders(); + assertEquals(10, report.getRow("L10000").getTotalValue()); + assertEquals(10, report.getRow("L20000").getTotalValue()); + assertEquals(7, report.getRow("L30000").getTotalValue()); + assertEquals(10, report.getRow("L40000").getTotalValue()); + assertEquals(13, report.getRow("L50000").getTotalValue()); - DetailedClassificationReport report = taskMonitorService.createClassificationReportBuilder() + int[] sumRow = report.getSumRow().getCells(); + assertArrayEquals(new int[] {10, 9, 11, 0, 4, 0, 7, 4, 5}, sumRow); + assertEquals(50, report.getSumRow().getTotalValue()); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfDetailedClassificationReport() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List columnHeaders = getShortListOfColumnHeaders(); + + DetailedClassificationReport report = + taskMonitorService + .createClassificationReportBuilder() .inWorkingDays() .withColumnHeaders(columnHeaders) .buildDetailedReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(5, report.rowSize()); - - FoldableRow line1 = report.getRow("L10000"); - assertArrayEquals(new int[] {7, 2, 1, 0, 0}, line1.getCells()); - - Row detailedLine1 = line1.getFoldableRow("L11000"); - assertArrayEquals(new int[] {2, 0, 1, 0, 0}, detailedLine1.getCells()); - - Row detailedLineNoAttachment1 = line1.getFoldableRow("N/A"); - assertArrayEquals(new int[] {5, 2, 0, 0, 0}, detailedLineNoAttachment1.getCells()); - - FoldableRow line2 = report.getRow("L20000"); - assertArrayEquals(new int[] {5, 3, 1, 1, 0}, line2.getCells()); - - Row detailedLine2 = line2.getFoldableRow("L22000"); - assertArrayEquals(new int[] {1, 1, 1, 1, 0}, detailedLine2.getCells()); - - Row detailedLineNoAttachment2 = line2.getFoldableRow("N/A"); - assertArrayEquals(new int[] {4, 2, 0, 0, 0}, detailedLineNoAttachment2.getCells()); - - FoldableRow line3 = report.getRow("L30000"); - assertArrayEquals(new int[] {2, 1, 0, 1, 3}, line3.getCells()); - - Row detailedLine3a = line3.getFoldableRow("L33000"); - assertArrayEquals(new int[] {0, 1, 0, 1, 1}, detailedLine3a.getCells()); - - Row detailedLine3b = line3.getFoldableRow("L99000"); - assertArrayEquals(new int[] {0, 0, 0, 0, 1}, detailedLine3b.getCells()); - - Row detailedLineNoAttachment3 = line3.getFoldableRow("N/A"); - assertArrayEquals(new int[] {2, 0, 0, 0, 1}, detailedLineNoAttachment3.getCells()); - - FoldableRow line4 = report.getRow("L40000"); - assertArrayEquals(new int[] {2, 2, 2, 0, 4}, line4.getCells()); - - Row detailedLineNoAttachment4 = line4.getFoldableRow("N/A"); - assertArrayEquals(new int[] {2, 2, 2, 0, 4}, detailedLineNoAttachment4.getCells()); - - FoldableRow line5 = report.getRow("L50000"); - assertArrayEquals(new int[] {3, 3, 0, 5, 2}, line5.getCells()); - - Row detailedLineNoAttachment5 = line5.getFoldableRow("N/A"); - assertArrayEquals(new int[] {3, 3, 0, 5, 2}, detailedLineNoAttachment5.getCells()); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfDetailedClassificationReportWithWorkbasketFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(5, report.rowSize()); - List workbasketIds = Collections.singletonList("WBI:000000000000000000000000000000000001"); - List columnHeaders = getShortListOfColumnHeaders(); + FoldableRow line1 = report.getRow("L10000"); + assertArrayEquals(new int[] {7, 2, 1, 0, 0}, line1.getCells()); - DetailedClassificationReport report = taskMonitorService.createClassificationReportBuilder() + Row detailedLine1 = line1.getFoldableRow("L11000"); + assertArrayEquals(new int[] {2, 0, 1, 0, 0}, detailedLine1.getCells()); + + Row detailedLineNoAttachment1 = line1.getFoldableRow("N/A"); + assertArrayEquals(new int[] {5, 2, 0, 0, 0}, detailedLineNoAttachment1.getCells()); + + FoldableRow line2 = report.getRow("L20000"); + assertArrayEquals(new int[] {5, 3, 1, 1, 0}, line2.getCells()); + + Row detailedLine2 = line2.getFoldableRow("L22000"); + assertArrayEquals(new int[] {1, 1, 1, 1, 0}, detailedLine2.getCells()); + + Row detailedLineNoAttachment2 = line2.getFoldableRow("N/A"); + assertArrayEquals(new int[] {4, 2, 0, 0, 0}, detailedLineNoAttachment2.getCells()); + + FoldableRow line3 = report.getRow("L30000"); + assertArrayEquals(new int[] {2, 1, 0, 1, 3}, line3.getCells()); + + Row detailedLine3a = line3.getFoldableRow("L33000"); + assertArrayEquals(new int[] {0, 1, 0, 1, 1}, detailedLine3a.getCells()); + + Row detailedLine3b = line3.getFoldableRow("L99000"); + assertArrayEquals(new int[] {0, 0, 0, 0, 1}, detailedLine3b.getCells()); + + Row detailedLineNoAttachment3 = line3.getFoldableRow("N/A"); + assertArrayEquals(new int[] {2, 0, 0, 0, 1}, detailedLineNoAttachment3.getCells()); + + FoldableRow line4 = report.getRow("L40000"); + assertArrayEquals(new int[] {2, 2, 2, 0, 4}, line4.getCells()); + + Row detailedLineNoAttachment4 = line4.getFoldableRow("N/A"); + assertArrayEquals(new int[] {2, 2, 2, 0, 4}, detailedLineNoAttachment4.getCells()); + + FoldableRow line5 = report.getRow("L50000"); + assertArrayEquals(new int[] {3, 3, 0, 5, 2}, line5.getCells()); + + Row detailedLineNoAttachment5 = line5.getFoldableRow("N/A"); + assertArrayEquals(new int[] {3, 3, 0, 5, 2}, detailedLineNoAttachment5.getCells()); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfDetailedClassificationReportWithWorkbasketFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List workbasketIds = + Collections.singletonList("WBI:000000000000000000000000000000000001"); + List columnHeaders = getShortListOfColumnHeaders(); + + DetailedClassificationReport report = + taskMonitorService + .createClassificationReportBuilder() .workbasketIdIn(workbasketIds) .inWorkingDays() .withColumnHeaders(columnHeaders) .buildDetailedReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(5, report.rowSize()); - - FoldableRow line1 = report.getRow("L10000"); - assertArrayEquals(new int[] {6, 0, 0, 0, 0}, line1.getCells()); - - Row detailedLine1 = line1.getFoldableRow("L11000"); - assertArrayEquals(new int[] {2, 0, 0, 0, 0}, detailedLine1.getCells()); - - Row detailedLineNoAttachment1 = line1.getFoldableRow("N/A"); - assertArrayEquals(new int[] {4, 0, 0, 0, 0}, detailedLineNoAttachment1.getCells()); - - FoldableRow line2 = report.getRow("L20000"); - assertArrayEquals(new int[] {2, 0, 0, 0, 0}, line2.getCells()); - - Row detailedLine2 = line2.getFoldableRow("L22000"); - assertArrayEquals(new int[] {1, 0, 0, 0, 0}, detailedLine2.getCells()); - - Row detailedLineNoAttachment2 = line2.getFoldableRow("N/A"); - assertArrayEquals(new int[] {1, 0, 0, 0, 0}, detailedLineNoAttachment2.getCells()); - - FoldableRow line3 = report.getRow("L30000"); - assertArrayEquals(new int[] {2, 1, 0, 1, 1}, line3.getCells()); - - Row detailedLine3a = line3.getFoldableRow("L33000"); - assertArrayEquals(new int[] {0, 1, 0, 1, 1}, detailedLine3a.getCells()); - - Row detailedLineNoAttachment3 = line3.getFoldableRow("N/A"); - assertArrayEquals(new int[] {2, 0, 0, 0, 0}, detailedLineNoAttachment3.getCells()); - - FoldableRow line4 = report.getRow("L40000"); - assertArrayEquals(new int[] {1, 0, 1, 0, 1}, line4.getCells()); - - Row detailedLineNoAttachment4 = line4.getFoldableRow("N/A"); - assertArrayEquals(new int[] {1, 0, 1, 0, 1}, detailedLineNoAttachment4.getCells()); - - FoldableRow line5 = report.getRow("L50000"); - assertArrayEquals(new int[] {2, 2, 0, 0, 0}, line5.getCells()); - - Row detailedLineNoAttachment5 = line5.getFoldableRow("N/A"); - assertArrayEquals(new int[] {2, 2, 0, 0, 0}, detailedLineNoAttachment5.getCells()); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfDetailedClassificationReportWithStateFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(5, report.rowSize()); - List states = Collections.singletonList(TaskState.READY); - List columnHeaders = getShortListOfColumnHeaders(); + FoldableRow line1 = report.getRow("L10000"); + assertArrayEquals(new int[] {6, 0, 0, 0, 0}, line1.getCells()); - DetailedClassificationReport report = taskMonitorService.createClassificationReportBuilder() + Row detailedLine1 = line1.getFoldableRow("L11000"); + assertArrayEquals(new int[] {2, 0, 0, 0, 0}, detailedLine1.getCells()); + + Row detailedLineNoAttachment1 = line1.getFoldableRow("N/A"); + assertArrayEquals(new int[] {4, 0, 0, 0, 0}, detailedLineNoAttachment1.getCells()); + + FoldableRow line2 = report.getRow("L20000"); + assertArrayEquals(new int[] {2, 0, 0, 0, 0}, line2.getCells()); + + Row detailedLine2 = line2.getFoldableRow("L22000"); + assertArrayEquals(new int[] {1, 0, 0, 0, 0}, detailedLine2.getCells()); + + Row detailedLineNoAttachment2 = line2.getFoldableRow("N/A"); + assertArrayEquals(new int[] {1, 0, 0, 0, 0}, detailedLineNoAttachment2.getCells()); + + FoldableRow line3 = report.getRow("L30000"); + assertArrayEquals(new int[] {2, 1, 0, 1, 1}, line3.getCells()); + + Row detailedLine3a = line3.getFoldableRow("L33000"); + assertArrayEquals(new int[] {0, 1, 0, 1, 1}, detailedLine3a.getCells()); + + Row detailedLineNoAttachment3 = line3.getFoldableRow("N/A"); + assertArrayEquals(new int[] {2, 0, 0, 0, 0}, detailedLineNoAttachment3.getCells()); + + FoldableRow line4 = report.getRow("L40000"); + assertArrayEquals(new int[] {1, 0, 1, 0, 1}, line4.getCells()); + + Row detailedLineNoAttachment4 = line4.getFoldableRow("N/A"); + assertArrayEquals(new int[] {1, 0, 1, 0, 1}, detailedLineNoAttachment4.getCells()); + + FoldableRow line5 = report.getRow("L50000"); + assertArrayEquals(new int[] {2, 2, 0, 0, 0}, line5.getCells()); + + Row detailedLineNoAttachment5 = line5.getFoldableRow("N/A"); + assertArrayEquals(new int[] {2, 2, 0, 0, 0}, detailedLineNoAttachment5.getCells()); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfDetailedClassificationReportWithStateFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List states = Collections.singletonList(TaskState.READY); + List columnHeaders = getShortListOfColumnHeaders(); + + DetailedClassificationReport report = + taskMonitorService + .createClassificationReportBuilder() .stateIn(states) .inWorkingDays() .withColumnHeaders(columnHeaders) .buildDetailedReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(5, report.rowSize()); - - FoldableRow line1 = report.getRow("L10000"); - assertArrayEquals(new int[] {7, 2, 1, 0, 0}, line1.getCells()); - - Row detailedLine1 = line1.getFoldableRow("L11000"); - assertArrayEquals(new int[] {2, 0, 1, 0, 0}, detailedLine1.getCells()); - - Row detailedLineNoAttachment1 = line1.getFoldableRow("N/A"); - assertArrayEquals(new int[] {5, 2, 0, 0, 0}, detailedLineNoAttachment1.getCells()); - - FoldableRow line2 = report.getRow("L20000"); - assertArrayEquals(new int[] {5, 3, 1, 1, 0}, line2.getCells()); - - Row detailedLine2 = line2.getFoldableRow("L22000"); - assertArrayEquals(new int[] {1, 1, 1, 1, 0}, detailedLine2.getCells()); - - Row detailedLineNoAttachment2 = line2.getFoldableRow("N/A"); - assertArrayEquals(new int[] {4, 2, 0, 0, 0}, detailedLineNoAttachment2.getCells()); - - FoldableRow line3 = report.getRow("L30000"); - assertArrayEquals(new int[] {2, 1, 0, 1, 0}, line3.getCells()); - - Row detailedLine3a = line3.getFoldableRow("L33000"); - assertArrayEquals(new int[] {0, 1, 0, 1, 0}, detailedLine3a.getCells()); - - Row detailedLineNoAttachment3 = line3.getFoldableRow("N/A"); - assertArrayEquals(new int[] {2, 0, 0, 0, 0}, detailedLineNoAttachment3.getCells()); - - FoldableRow line4 = report.getRow("L40000"); - assertArrayEquals(new int[] {2, 2, 2, 0, 0}, line4.getCells()); - - Row detailedLineNoAttachment4 = line4.getFoldableRow("N/A"); - assertArrayEquals(new int[] {2, 2, 2, 0, 0}, detailedLineNoAttachment4.getCells()); - - FoldableRow line5 = report.getRow("L50000"); - assertArrayEquals(new int[] {3, 3, 0, 5, 0}, line5.getCells()); - - Row detailedLineNoAttachment5 = line5.getFoldableRow("N/A"); - assertArrayEquals(new int[] {3, 3, 0, 5, 0}, detailedLineNoAttachment5.getCells()); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfDetailedClassificationReportNotInWorkingDays() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(5, report.rowSize()); - List columnHeaders = getShortListOfColumnHeaders(); + FoldableRow line1 = report.getRow("L10000"); + assertArrayEquals(new int[] {7, 2, 1, 0, 0}, line1.getCells()); - DetailedClassificationReport report = taskMonitorService.createClassificationReportBuilder() + Row detailedLine1 = line1.getFoldableRow("L11000"); + assertArrayEquals(new int[] {2, 0, 1, 0, 0}, detailedLine1.getCells()); + + Row detailedLineNoAttachment1 = line1.getFoldableRow("N/A"); + assertArrayEquals(new int[] {5, 2, 0, 0, 0}, detailedLineNoAttachment1.getCells()); + + FoldableRow line2 = report.getRow("L20000"); + assertArrayEquals(new int[] {5, 3, 1, 1, 0}, line2.getCells()); + + Row detailedLine2 = line2.getFoldableRow("L22000"); + assertArrayEquals(new int[] {1, 1, 1, 1, 0}, detailedLine2.getCells()); + + Row detailedLineNoAttachment2 = line2.getFoldableRow("N/A"); + assertArrayEquals(new int[] {4, 2, 0, 0, 0}, detailedLineNoAttachment2.getCells()); + + FoldableRow line3 = report.getRow("L30000"); + assertArrayEquals(new int[] {2, 1, 0, 1, 0}, line3.getCells()); + + Row detailedLine3a = line3.getFoldableRow("L33000"); + assertArrayEquals(new int[] {0, 1, 0, 1, 0}, detailedLine3a.getCells()); + + Row detailedLineNoAttachment3 = line3.getFoldableRow("N/A"); + assertArrayEquals(new int[] {2, 0, 0, 0, 0}, detailedLineNoAttachment3.getCells()); + + FoldableRow line4 = report.getRow("L40000"); + assertArrayEquals(new int[] {2, 2, 2, 0, 0}, line4.getCells()); + + Row detailedLineNoAttachment4 = line4.getFoldableRow("N/A"); + assertArrayEquals(new int[] {2, 2, 2, 0, 0}, detailedLineNoAttachment4.getCells()); + + FoldableRow line5 = report.getRow("L50000"); + assertArrayEquals(new int[] {3, 3, 0, 5, 0}, line5.getCells()); + + Row detailedLineNoAttachment5 = line5.getFoldableRow("N/A"); + assertArrayEquals(new int[] {3, 3, 0, 5, 0}, detailedLineNoAttachment5.getCells()); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfDetailedClassificationReportNotInWorkingDays() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List columnHeaders = getShortListOfColumnHeaders(); + + DetailedClassificationReport report = + taskMonitorService + .createClassificationReportBuilder() .withColumnHeaders(columnHeaders) .buildDetailedReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(5, report.rowSize()); - - FoldableRow line1 = report.getRow("L10000"); - assertArrayEquals(new int[] {9, 0, 1, 0, 0}, line1.getCells()); - - Row detailedLine1 = line1.getFoldableRow("L11000"); - assertArrayEquals(new int[] {2, 0, 1, 0, 0}, detailedLine1.getCells()); - - Row detailedLineNoAttachment1 = line1.getFoldableRow("N/A"); - assertArrayEquals(new int[] {7, 0, 0, 0, 0}, detailedLineNoAttachment1.getCells()); - - FoldableRow line2 = report.getRow("L20000"); - assertArrayEquals(new int[] {8, 0, 1, 0, 1}, line2.getCells()); - - Row detailedLine2 = line2.getFoldableRow("L22000"); - assertArrayEquals(new int[] {2, 0, 1, 0, 1}, detailedLine2.getCells()); - - Row detailedLineNoAttachment2 = line2.getFoldableRow("N/A"); - assertArrayEquals(new int[] {6, 0, 0, 0, 0}, detailedLineNoAttachment2.getCells()); - - FoldableRow line3 = report.getRow("L30000"); - assertArrayEquals(new int[] {3, 0, 0, 0, 4}, line3.getCells()); - - Row detailedLine3a = line3.getFoldableRow("L33000"); - assertArrayEquals(new int[] {1, 0, 0, 0, 2}, detailedLine3a.getCells()); - - Row detailedLine3b = line3.getFoldableRow("L99000"); - assertArrayEquals(new int[] {0, 0, 0, 0, 1}, detailedLine3b.getCells()); - - Row detailedLineNoAttachment3 = line3.getFoldableRow("N/A"); - assertArrayEquals(new int[] {2, 0, 0, 0, 1}, detailedLineNoAttachment3.getCells()); - - FoldableRow line4 = report.getRow("L40000"); - assertArrayEquals(new int[] {4, 0, 2, 0, 4}, line4.getCells()); - - Row detailedLineNoAttachment4 = line4.getFoldableRow("N/A"); - assertArrayEquals(new int[] {4, 0, 2, 0, 4}, detailedLineNoAttachment4.getCells()); - - FoldableRow line5 = report.getRow("L50000"); - assertArrayEquals(new int[] {6, 0, 0, 0, 7}, line5.getCells()); - - Row detailedLineNoAttachment5 = line5.getFoldableRow("N/A"); - assertArrayEquals(new int[] {6, 0, 0, 0, 7}, detailedLineNoAttachment5.getCells()); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfDetailedClassificationReportWithCategoryFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(5, report.rowSize()); - List categories = Arrays.asList("AUTOMATIC", "MANUAL"); - List columnHeaders = getShortListOfColumnHeaders(); + FoldableRow line1 = report.getRow("L10000"); + assertArrayEquals(new int[] {9, 0, 1, 0, 0}, line1.getCells()); - DetailedClassificationReport report = taskMonitorService.createClassificationReportBuilder() + Row detailedLine1 = line1.getFoldableRow("L11000"); + assertArrayEquals(new int[] {2, 0, 1, 0, 0}, detailedLine1.getCells()); + + Row detailedLineNoAttachment1 = line1.getFoldableRow("N/A"); + assertArrayEquals(new int[] {7, 0, 0, 0, 0}, detailedLineNoAttachment1.getCells()); + + FoldableRow line2 = report.getRow("L20000"); + assertArrayEquals(new int[] {8, 0, 1, 0, 1}, line2.getCells()); + + Row detailedLine2 = line2.getFoldableRow("L22000"); + assertArrayEquals(new int[] {2, 0, 1, 0, 1}, detailedLine2.getCells()); + + Row detailedLineNoAttachment2 = line2.getFoldableRow("N/A"); + assertArrayEquals(new int[] {6, 0, 0, 0, 0}, detailedLineNoAttachment2.getCells()); + + FoldableRow line3 = report.getRow("L30000"); + assertArrayEquals(new int[] {3, 0, 0, 0, 4}, line3.getCells()); + + Row detailedLine3a = line3.getFoldableRow("L33000"); + assertArrayEquals(new int[] {1, 0, 0, 0, 2}, detailedLine3a.getCells()); + + Row detailedLine3b = line3.getFoldableRow("L99000"); + assertArrayEquals(new int[] {0, 0, 0, 0, 1}, detailedLine3b.getCells()); + + Row detailedLineNoAttachment3 = line3.getFoldableRow("N/A"); + assertArrayEquals(new int[] {2, 0, 0, 0, 1}, detailedLineNoAttachment3.getCells()); + + FoldableRow line4 = report.getRow("L40000"); + assertArrayEquals(new int[] {4, 0, 2, 0, 4}, line4.getCells()); + + Row detailedLineNoAttachment4 = line4.getFoldableRow("N/A"); + assertArrayEquals(new int[] {4, 0, 2, 0, 4}, detailedLineNoAttachment4.getCells()); + + FoldableRow line5 = report.getRow("L50000"); + assertArrayEquals(new int[] {6, 0, 0, 0, 7}, line5.getCells()); + + Row detailedLineNoAttachment5 = line5.getFoldableRow("N/A"); + assertArrayEquals(new int[] {6, 0, 0, 0, 7}, detailedLineNoAttachment5.getCells()); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfDetailedClassificationReportWithCategoryFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List categories = Arrays.asList("AUTOMATIC", "MANUAL"); + List columnHeaders = getShortListOfColumnHeaders(); + + DetailedClassificationReport report = + taskMonitorService + .createClassificationReportBuilder() .categoryIn(categories) .inWorkingDays() .withColumnHeaders(columnHeaders) .buildDetailedReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(2, report.rowSize()); - - FoldableRow line1 = report.getRow("L30000"); - assertArrayEquals(new int[] {2, 1, 0, 1, 3}, line1.getCells()); - - Row detailedLine1a = line1.getFoldableRow("L33000"); - assertArrayEquals(new int[] {0, 1, 0, 1, 1}, detailedLine1a.getCells()); - - Row detailedLine1b = line1.getFoldableRow("L99000"); - assertArrayEquals(new int[] {0, 0, 0, 0, 1}, detailedLine1b.getCells()); - - Row detailedLine1WithoutAttachment = line1.getFoldableRow("N/A"); - assertArrayEquals(new int[] {2, 0, 0, 0, 1}, detailedLine1WithoutAttachment.getCells()); - - FoldableRow line2 = report.getRow("L40000"); - assertArrayEquals(new int[] {2, 2, 2, 0, 4}, line2.getCells()); - - Row detailedLine2WithoutAttachment = line2.getFoldableRow("N/A"); - assertArrayEquals(new int[] {2, 2, 2, 0, 4}, detailedLine2WithoutAttachment.getCells()); - + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfDetailedClassificationReportWithDomainFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(2, report.rowSize()); - List domains = Collections.singletonList("DOMAIN_A"); - List columnHeaders = getShortListOfColumnHeaders(); + FoldableRow line1 = report.getRow("L30000"); + assertArrayEquals(new int[] {2, 1, 0, 1, 3}, line1.getCells()); - DetailedClassificationReport report = taskMonitorService.createClassificationReportBuilder() + Row detailedLine1a = line1.getFoldableRow("L33000"); + assertArrayEquals(new int[] {0, 1, 0, 1, 1}, detailedLine1a.getCells()); + + Row detailedLine1b = line1.getFoldableRow("L99000"); + assertArrayEquals(new int[] {0, 0, 0, 0, 1}, detailedLine1b.getCells()); + + Row detailedLine1WithoutAttachment = line1.getFoldableRow("N/A"); + assertArrayEquals(new int[] {2, 0, 0, 0, 1}, detailedLine1WithoutAttachment.getCells()); + + FoldableRow line2 = report.getRow("L40000"); + assertArrayEquals(new int[] {2, 2, 2, 0, 4}, line2.getCells()); + + Row detailedLine2WithoutAttachment = line2.getFoldableRow("N/A"); + assertArrayEquals(new int[] {2, 2, 2, 0, 4}, detailedLine2WithoutAttachment.getCells()); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfDetailedClassificationReportWithDomainFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List domains = Collections.singletonList("DOMAIN_A"); + List columnHeaders = getShortListOfColumnHeaders(); + + DetailedClassificationReport report = + taskMonitorService + .createClassificationReportBuilder() .inWorkingDays() .withColumnHeaders(columnHeaders) .domainIn(domains) .buildDetailedReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(5, report.rowSize()); - - FoldableRow line1 = report.getRow("L10000"); - assertArrayEquals(new int[] {5, 2, 1, 0, 0}, line1.getCells()); - - Row detailedLine1 = line1.getFoldableRow("L11000"); - assertArrayEquals(new int[] {1, 0, 1, 0, 0}, detailedLine1.getCells()); - - Row detailedLineNoAttachment1 = line1.getFoldableRow("N/A"); - assertArrayEquals(new int[] {4, 2, 0, 0, 0}, detailedLineNoAttachment1.getCells()); - - FoldableRow line2 = report.getRow("L20000"); - assertArrayEquals(new int[] {3, 1, 1, 1, 0}, line2.getCells()); - - Row detailedLine2 = line2.getFoldableRow("L22000"); - assertArrayEquals(new int[] {1, 0, 1, 1, 0}, detailedLine2.getCells()); - - Row detailedLineNoAttachment2 = line2.getFoldableRow("N/A"); - assertArrayEquals(new int[] {2, 1, 0, 0, 0}, detailedLineNoAttachment2.getCells()); - - FoldableRow line3 = report.getRow("L30000"); - assertArrayEquals(new int[] {1, 0, 0, 1, 1}, line3.getCells()); - - Row detailedLine3 = line3.getFoldableRow("L33000"); - assertArrayEquals(new int[] {0, 0, 0, 1, 1}, detailedLine3.getCells()); - - Row detailedLineNoAttachment3 = line3.getFoldableRow("N/A"); - assertArrayEquals(new int[] {1, 0, 0, 0, 0}, detailedLineNoAttachment3.getCells()); - - FoldableRow line4 = report.getRow("L40000"); - assertArrayEquals(new int[] {2, 0, 0, 0, 3}, line4.getCells()); - - Row detailedLineNoAttachment4 = line4.getFoldableRow("N/A"); - assertArrayEquals(new int[] {2, 0, 0, 0, 3}, detailedLineNoAttachment4.getCells()); - - FoldableRow line5 = report.getRow("L50000"); - assertArrayEquals(new int[] {0, 1, 0, 3, 0}, line5.getCells()); - - Row detailedLineNoAttachment5 = line5.getFoldableRow("N/A"); - assertArrayEquals(new int[] {0, 1, 0, 3, 0}, detailedLineNoAttachment5.getCells()); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfDetailedClassificationReportWithCustomFieldValueFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(5, report.rowSize()); - Map customAttributeFilter = new HashMap<>(); - customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); - List columnHeaders = getShortListOfColumnHeaders(); + FoldableRow line1 = report.getRow("L10000"); + assertArrayEquals(new int[] {5, 2, 1, 0, 0}, line1.getCells()); - DetailedClassificationReport report = taskMonitorService.createClassificationReportBuilder() + Row detailedLine1 = line1.getFoldableRow("L11000"); + assertArrayEquals(new int[] {1, 0, 1, 0, 0}, detailedLine1.getCells()); + + Row detailedLineNoAttachment1 = line1.getFoldableRow("N/A"); + assertArrayEquals(new int[] {4, 2, 0, 0, 0}, detailedLineNoAttachment1.getCells()); + + FoldableRow line2 = report.getRow("L20000"); + assertArrayEquals(new int[] {3, 1, 1, 1, 0}, line2.getCells()); + + Row detailedLine2 = line2.getFoldableRow("L22000"); + assertArrayEquals(new int[] {1, 0, 1, 1, 0}, detailedLine2.getCells()); + + Row detailedLineNoAttachment2 = line2.getFoldableRow("N/A"); + assertArrayEquals(new int[] {2, 1, 0, 0, 0}, detailedLineNoAttachment2.getCells()); + + FoldableRow line3 = report.getRow("L30000"); + assertArrayEquals(new int[] {1, 0, 0, 1, 1}, line3.getCells()); + + Row detailedLine3 = line3.getFoldableRow("L33000"); + assertArrayEquals(new int[] {0, 0, 0, 1, 1}, detailedLine3.getCells()); + + Row detailedLineNoAttachment3 = line3.getFoldableRow("N/A"); + assertArrayEquals(new int[] {1, 0, 0, 0, 0}, detailedLineNoAttachment3.getCells()); + + FoldableRow line4 = report.getRow("L40000"); + assertArrayEquals(new int[] {2, 0, 0, 0, 3}, line4.getCells()); + + Row detailedLineNoAttachment4 = line4.getFoldableRow("N/A"); + assertArrayEquals(new int[] {2, 0, 0, 0, 3}, detailedLineNoAttachment4.getCells()); + + FoldableRow line5 = report.getRow("L50000"); + assertArrayEquals(new int[] {0, 1, 0, 3, 0}, line5.getCells()); + + Row detailedLineNoAttachment5 = line5.getFoldableRow("N/A"); + assertArrayEquals(new int[] {0, 1, 0, 3, 0}, detailedLineNoAttachment5.getCells()); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfDetailedClassificationReportWithCustomFieldValueFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + Map customAttributeFilter = new HashMap<>(); + customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); + List columnHeaders = getShortListOfColumnHeaders(); + + DetailedClassificationReport report = + taskMonitorService + .createClassificationReportBuilder() .customAttributeFilterIn(customAttributeFilter) .inWorkingDays() .withColumnHeaders(columnHeaders) .buildDetailedReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); + } + + assertNotNull(report); + assertEquals(5, report.rowSize()); + + FoldableRow line1 = report.getRow("L10000"); + assertArrayEquals(new int[] {4, 0, 0, 0, 0}, line1.getCells()); + + Row detailedLine1 = line1.getFoldableRow("L11000"); + assertArrayEquals(new int[] {1, 0, 0, 0, 0}, detailedLine1.getCells()); + + Row detailedLineNoAttachment1 = line1.getFoldableRow("N/A"); + assertArrayEquals(new int[] {3, 0, 0, 0, 0}, detailedLineNoAttachment1.getCells()); + + FoldableRow line2 = report.getRow("L20000"); + assertArrayEquals(new int[] {4, 1, 1, 1, 0}, line2.getCells()); + + Row detailedLine2 = line2.getFoldableRow("L22000"); + assertArrayEquals(new int[] {1, 1, 1, 1, 0}, detailedLine2.getCells()); + + Row detailedLineNoAttachment2 = line2.getFoldableRow("N/A"); + assertArrayEquals(new int[] {3, 0, 0, 0, 0}, detailedLineNoAttachment2.getCells()); + + FoldableRow line3 = report.getRow("L30000"); + assertArrayEquals(new int[] {1, 0, 0, 1, 1}, line3.getCells()); + + Row detailedLine3a = line3.getFoldableRow("L33000"); + assertArrayEquals(new int[] {0, 0, 0, 1, 0}, detailedLine3a.getCells()); + + Row detailedLineNoAttachment3 = line3.getFoldableRow("N/A"); + assertArrayEquals(new int[] {1, 0, 0, 0, 1}, detailedLineNoAttachment3.getCells()); + + FoldableRow line4 = report.getRow("L40000"); + assertArrayEquals(new int[] {1, 1, 2, 0, 2}, line4.getCells()); + + Row detailedLineNoAttachment4 = line4.getFoldableRow("N/A"); + assertArrayEquals(new int[] {1, 1, 2, 0, 2}, detailedLineNoAttachment4.getCells()); + + FoldableRow line5 = report.getRow("L50000"); + assertArrayEquals(new int[] {1, 2, 0, 2, 0}, line5.getCells()); + + Row detailedLineNoAttachment5 = line5.getFoldableRow("N/A"); + assertArrayEquals(new int[] {1, 2, 0, 2, 0}, detailedLineNoAttachment5.getCells()); + } + + private List getListOfColumnHeaders() { + List columnHeaders = new ArrayList<>(); + columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -11)); + columnHeaders.add(new TimeIntervalColumnHeader(-10, -6)); + columnHeaders.add(new TimeIntervalColumnHeader(-5, -2)); + columnHeaders.add(new TimeIntervalColumnHeader(-1)); + columnHeaders.add(new TimeIntervalColumnHeader(0)); + columnHeaders.add(new TimeIntervalColumnHeader(1)); + columnHeaders.add(new TimeIntervalColumnHeader(2, 5)); + columnHeaders.add(new TimeIntervalColumnHeader(6, 10)); + columnHeaders.add(new TimeIntervalColumnHeader(11, Integer.MAX_VALUE)); + return columnHeaders; + } + + private List getShortListOfColumnHeaders() { + List columnHeaders = new ArrayList<>(); + columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -6)); + columnHeaders.add(new TimeIntervalColumnHeader(-5, -1)); + columnHeaders.add(new TimeIntervalColumnHeader(0)); + columnHeaders.add(new TimeIntervalColumnHeader(1, 5)); + columnHeaders.add(new TimeIntervalColumnHeader(6, Integer.MAX_VALUE)); + return columnHeaders; + } + + private String reportToString(DetailedClassificationReport report) { + return reportToString(report, null); + } + + private String reportToString( + DetailedClassificationReport report, List columnHeaders) { + String formatColumWidth = "| %-7s "; + String formatFirstColumn = "| %-36s %-4s "; + String formatFirstColumnFirstLine = "| %-29s %12s "; + String formatFirstColumnDetailLines = "| + %-34s %-4s "; + String formatFirstColumnSumLine = "| %-36s %-5s"; + int reportWidth = columnHeaders == null ? 46 : columnHeaders.size() * 10 + 46; + + StringBuilder builder = new StringBuilder(); + builder.append("\n"); + for (int i = 0; i < reportWidth; i++) { + builder.append("-"); + } + builder.append("\n"); + builder.append( + String.format(formatFirstColumnFirstLine, "Classifications + Attachments", "Total")); + if (columnHeaders != null) { + for (TimeIntervalColumnHeader def : columnHeaders) { + if (def.getLowerAgeLimit() == Integer.MIN_VALUE) { + builder.append(String.format(formatColumWidth, "< " + def.getUpperAgeLimit())); + } else if (def.getUpperAgeLimit() == Integer.MAX_VALUE) { + builder.append(String.format(formatColumWidth, "> " + def.getLowerAgeLimit())); + } else if (def.getLowerAgeLimit() == def.getUpperAgeLimit()) { + if (def.getLowerAgeLimit() == 0) { + builder.append(String.format(formatColumWidth, "today")); + } else { + builder.append(String.format(formatColumWidth, def.getLowerAgeLimit())); + } + } else { + builder.append( + String.format( + formatColumWidth, def.getLowerAgeLimit() + ".." + def.getUpperAgeLimit())); } - - assertNotNull(report); - assertEquals(5, report.rowSize()); - - FoldableRow line1 = report.getRow("L10000"); - assertArrayEquals(new int[] {4, 0, 0, 0, 0}, line1.getCells()); - - Row detailedLine1 = line1.getFoldableRow("L11000"); - assertArrayEquals(new int[] {1, 0, 0, 0, 0}, detailedLine1.getCells()); - - Row detailedLineNoAttachment1 = line1.getFoldableRow("N/A"); - assertArrayEquals(new int[] {3, 0, 0, 0, 0}, detailedLineNoAttachment1.getCells()); - - FoldableRow line2 = report.getRow("L20000"); - assertArrayEquals(new int[] {4, 1, 1, 1, 0}, line2.getCells()); - - Row detailedLine2 = line2.getFoldableRow("L22000"); - assertArrayEquals(new int[] {1, 1, 1, 1, 0}, detailedLine2.getCells()); - - Row detailedLineNoAttachment2 = line2.getFoldableRow("N/A"); - assertArrayEquals(new int[] {3, 0, 0, 0, 0}, detailedLineNoAttachment2.getCells()); - - FoldableRow line3 = report.getRow("L30000"); - assertArrayEquals(new int[] {1, 0, 0, 1, 1}, line3.getCells()); - - Row detailedLine3a = line3.getFoldableRow("L33000"); - assertArrayEquals(new int[] {0, 0, 0, 1, 0}, detailedLine3a.getCells()); - - Row detailedLineNoAttachment3 = line3.getFoldableRow("N/A"); - assertArrayEquals(new int[] {1, 0, 0, 0, 1}, detailedLineNoAttachment3.getCells()); - - FoldableRow line4 = report.getRow("L40000"); - assertArrayEquals(new int[] {1, 1, 2, 0, 2}, line4.getCells()); - - Row detailedLineNoAttachment4 = line4.getFoldableRow("N/A"); - assertArrayEquals(new int[] {1, 1, 2, 0, 2}, detailedLineNoAttachment4.getCells()); - - FoldableRow line5 = report.getRow("L50000"); - assertArrayEquals(new int[] {1, 2, 0, 2, 0}, line5.getCells()); - - Row detailedLineNoAttachment5 = line5.getFoldableRow("N/A"); - assertArrayEquals(new int[] {1, 2, 0, 2, 0}, detailedLineNoAttachment5.getCells()); + } } - - private List getListOfColumnHeaders() { - List columnHeaders = new ArrayList<>(); - columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -11)); - columnHeaders.add(new TimeIntervalColumnHeader(-10, -6)); - columnHeaders.add(new TimeIntervalColumnHeader(-5, -2)); - columnHeaders.add(new TimeIntervalColumnHeader(-1)); - columnHeaders.add(new TimeIntervalColumnHeader(0)); - columnHeaders.add(new TimeIntervalColumnHeader(1)); - columnHeaders.add(new TimeIntervalColumnHeader(2, 5)); - columnHeaders.add(new TimeIntervalColumnHeader(6, 10)); - columnHeaders.add(new TimeIntervalColumnHeader(11, Integer.MAX_VALUE)); - return columnHeaders; + builder.append("|\n"); + for (int i = 0; i < reportWidth; i++) { + builder.append("-"); } + builder.append("\n"); - private List getShortListOfColumnHeaders() { - List columnHeaders = new ArrayList<>(); - columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -6)); - columnHeaders.add(new TimeIntervalColumnHeader(-5, -1)); - columnHeaders.add(new TimeIntervalColumnHeader(0)); - columnHeaders.add(new TimeIntervalColumnHeader(1, 5)); - columnHeaders.add(new TimeIntervalColumnHeader(6, Integer.MAX_VALUE)); - return columnHeaders; - } - - private String reportToString(DetailedClassificationReport report) { - return reportToString(report, null); - } - - private String reportToString(DetailedClassificationReport report, List columnHeaders) { - String formatColumWidth = "| %-7s "; - String formatFirstColumn = "| %-36s %-4s "; - String formatFirstColumnFirstLine = "| %-29s %12s "; - String formatFirstColumnDetailLines = "| + %-34s %-4s "; - String formatFirstColumnSumLine = "| %-36s %-5s"; - int reportWidth = columnHeaders == null ? 46 : columnHeaders.size() * 10 + 46; - - StringBuilder builder = new StringBuilder(); - builder.append("\n"); - for (int i = 0; i < reportWidth; i++) { - builder.append("-"); + for (String rl : report.rowTitles()) { + builder.append(String.format(formatFirstColumn, rl, report.getRow(rl).getTotalValue())); + if (columnHeaders != null) { + for (int cell : report.getRow(rl).getCells()) { + builder.append(String.format(formatColumWidth, cell)); } - builder.append("\n"); - builder.append(String.format(formatFirstColumnFirstLine, "Classifications + Attachments", "Total")); - if (columnHeaders != null) { - for (TimeIntervalColumnHeader def : columnHeaders) { - if (def.getLowerAgeLimit() == Integer.MIN_VALUE) { - builder.append(String.format(formatColumWidth, "< " + def.getUpperAgeLimit())); - } else if (def.getUpperAgeLimit() == Integer.MAX_VALUE) { - builder.append(String.format(formatColumWidth, "> " + def.getLowerAgeLimit())); - } else if (def.getLowerAgeLimit() == def.getUpperAgeLimit()) { - if (def.getLowerAgeLimit() == 0) { - builder.append(String.format(formatColumWidth, "today")); - } else { - builder.append(String.format(formatColumWidth, def.getLowerAgeLimit())); - } - } else { - builder.append( - String.format(formatColumWidth, def.getLowerAgeLimit() + ".." + def.getUpperAgeLimit())); - } - } + } + builder.append("|\n"); + for (String detaileLine : report.getRow(rl).getFoldableRowKeySet()) { + Row reportLine = report.getRow(rl).getFoldableRow(detaileLine); + builder.append( + String.format(formatFirstColumnDetailLines, detaileLine, reportLine.getTotalValue())); + for (int cell : reportLine.getCells()) { + builder.append(String.format(formatColumWidth, cell)); } builder.append("|\n"); - for (int i = 0; i < reportWidth; i++) { - builder.append("-"); - } - builder.append("\n"); + } - for (String rl : report.rowTitles()) { - builder - .append(String.format(formatFirstColumn, rl, report.getRow(rl).getTotalValue())); - if (columnHeaders != null) { - for (int cell : report.getRow(rl).getCells()) { - builder.append(String.format(formatColumWidth, cell)); - } - } - builder.append("|\n"); - for (String detaileLine : report.getRow(rl).getFoldableRowKeySet()) { - Row reportLine = report.getRow(rl).getFoldableRow(detaileLine); - builder.append( - String.format(formatFirstColumnDetailLines, detaileLine, reportLine.getTotalValue())); - for (int cell : reportLine.getCells()) { - builder.append(String.format(formatColumWidth, cell)); - } - builder.append("|\n"); - } - - for (int i = 0; i < reportWidth; i++) { - builder.append("-"); - } - builder.append("\n"); - } - builder.append(String.format(formatFirstColumnSumLine, "Total", report.getSumRow().getTotalValue())); - for (int cell : report.getSumRow().getCells()) { - builder.append(String.format(formatColumWidth, cell)); - } - builder.append("|\n"); - for (int i = 0; i < reportWidth; i++) { - builder.append("-"); - } - builder.append("\n"); - return builder.toString(); + for (int i = 0; i < reportWidth; i++) { + builder.append("-"); + } + builder.append("\n"); } - + builder.append( + String.format(formatFirstColumnSumLine, "Total", report.getSumRow().getTotalValue())); + for (int cell : report.getSumRow().getCells()) { + builder.append(String.format(formatColumWidth, cell)); + } + builder.append("|\n"); + for (int i = 0; i < reportWidth; i++) { + builder.append("-"); + } + builder.append("\n"); + return builder.toString(); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/report/ProvideTaskStatusReportAccTest.java b/lib/taskana-core/src/test/java/acceptance/report/ProvideTaskStatusReportAccTest.java index 9b8626f51..045e6165f 100644 --- a/lib/taskana-core/src/test/java/acceptance/report/ProvideTaskStatusReportAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/report/ProvideTaskStatusReportAccTest.java @@ -7,7 +7,6 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.Collections; import java.util.List; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -25,173 +24,174 @@ import pro.taskana.report.TaskStatusReport; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "task status report" scenarios. - */ +/** Acceptance test for all "task status report" scenarios. */ @ExtendWith(JAASExtension.class) class ProvideTaskStatusReportAccTest extends AbstractReportAccTest { - private static final Logger LOGGER = LoggerFactory.getLogger(ProvideWorkbasketReportAccTest.class); + private static final Logger LOGGER = + LoggerFactory.getLogger(ProvideWorkbasketReportAccTest.class); - @Test - void testRoleCheck() { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - Assertions.assertThrows(NotAuthorizedException.class, () -> - taskMonitorService.createTaskStatusReportBuilder().buildReport()); + @Test + void testRoleCheck() { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + Assertions.assertThrows( + NotAuthorizedException.class, + () -> taskMonitorService.createTaskStatusReportBuilder().buildReport()); + } + + @WithAccessId(userName = "monitor") + @Test + void testCompleteTaskStatusReport() throws NotAuthorizedException, InvalidArgumentException { + // given + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + // when + TaskStatusReport report = taskMonitorService.createTaskStatusReportBuilder().buildReport(); + // then + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report)); } + assertNotNull(report); + assertEquals(3, report.rowSize()); - @WithAccessId( - userName = "monitor") - @Test - void testCompleteTaskStatusReport() throws NotAuthorizedException, InvalidArgumentException { - // given - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - // when - TaskStatusReport report = taskMonitorService.createTaskStatusReportBuilder().buildReport(); - // then - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report)); - } - assertNotNull(report); - assertEquals(3, report.rowSize()); + Row row1 = report.getRow("DOMAIN_A"); + assertArrayEquals(new int[] {22, 4, 0}, row1.getCells()); + assertEquals(26, row1.getTotalValue()); - Row row1 = report.getRow("DOMAIN_A"); - assertArrayEquals(new int[] {22, 4, 0}, row1.getCells()); - assertEquals(26, row1.getTotalValue()); + Row row2 = report.getRow("DOMAIN_B"); + assertArrayEquals(new int[] {9, 3, 0}, row2.getCells()); + assertEquals(12, row2.getTotalValue()); - Row row2 = report.getRow("DOMAIN_B"); - assertArrayEquals(new int[] {9, 3, 0}, row2.getCells()); - assertEquals(12, row2.getTotalValue()); + Row row3 = report.getRow("DOMAIN_C"); + assertArrayEquals(new int[] {10, 2, 0}, row3.getCells()); + assertEquals(12, row3.getTotalValue()); - Row row3 = report.getRow("DOMAIN_C"); - assertArrayEquals(new int[] {10, 2, 0}, row3.getCells()); - assertEquals(12, row3.getTotalValue()); + Row sumRow = report.getSumRow(); + assertArrayEquals(new int[] {41, 9, 0}, sumRow.getCells()); + assertEquals(50, sumRow.getTotalValue()); + } - Row sumRow = report.getSumRow(); - assertArrayEquals(new int[] {41, 9, 0}, sumRow.getCells()); - assertEquals(50, sumRow.getTotalValue()); - } + @WithAccessId(userName = "admin") + @Test + void testCompleteTaskStatusReportAsAdmin() + throws NotAuthorizedException, InvalidArgumentException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + taskMonitorService.createTaskStatusReportBuilder().buildReport(); + } - @WithAccessId( - userName = "admin") - @Test - void testCompleteTaskStatusReportAsAdmin() throws NotAuthorizedException, InvalidArgumentException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - taskMonitorService.createTaskStatusReportBuilder().buildReport(); - } - - @WithAccessId( - userName = "monitor") - @Test - void testCompleteTaskStatusReportWithDomainFilter() throws NotAuthorizedException, InvalidArgumentException { - // given - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - // when - TaskStatusReport report = taskMonitorService + @WithAccessId(userName = "monitor") + @Test + void testCompleteTaskStatusReportWithDomainFilter() + throws NotAuthorizedException, InvalidArgumentException { + // given + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + // when + TaskStatusReport report = + taskMonitorService .createTaskStatusReportBuilder() .domainIn(asList("DOMAIN_C", "DOMAIN_A")) .buildReport(); - // then - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report)); - } - assertNotNull(report); - assertEquals(2, report.rowSize()); - - Row row1 = report.getRow("DOMAIN_A"); - assertArrayEquals(new int[] {22, 4, 0}, row1.getCells()); - assertEquals(26, row1.getTotalValue()); - - Row row2 = report.getRow("DOMAIN_C"); - assertArrayEquals(new int[] {10, 2, 0}, row2.getCells()); - assertEquals(12, row2.getTotalValue()); - - Row sumRow = report.getSumRow(); - assertArrayEquals(new int[] {32, 6, 0}, sumRow.getCells()); - assertEquals(38, sumRow.getTotalValue()); + // then + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report)); } + assertNotNull(report); + assertEquals(2, report.rowSize()); - @WithAccessId( - userName = "monitor") - @Test - void testCompleteTaskStatusReportWithStateFilter() throws NotAuthorizedException, InvalidArgumentException { - // given - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - // when - TaskStatusReport report = taskMonitorService + Row row1 = report.getRow("DOMAIN_A"); + assertArrayEquals(new int[] {22, 4, 0}, row1.getCells()); + assertEquals(26, row1.getTotalValue()); + + Row row2 = report.getRow("DOMAIN_C"); + assertArrayEquals(new int[] {10, 2, 0}, row2.getCells()); + assertEquals(12, row2.getTotalValue()); + + Row sumRow = report.getSumRow(); + assertArrayEquals(new int[] {32, 6, 0}, sumRow.getCells()); + assertEquals(38, sumRow.getTotalValue()); + } + + @WithAccessId(userName = "monitor") + @Test + void testCompleteTaskStatusReportWithStateFilter() + throws NotAuthorizedException, InvalidArgumentException { + // given + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + // when + TaskStatusReport report = + taskMonitorService .createTaskStatusReportBuilder() .stateIn(Collections.singletonList(TaskState.READY)) .buildReport(); - // then - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report)); - } - assertNotNull(report); - assertEquals(3, report.rowSize()); - - Row row1 = report.getRow("DOMAIN_A"); - assertArrayEquals(new int[] {22}, row1.getCells()); - assertEquals(22, row1.getTotalValue()); - - Row row2 = report.getRow("DOMAIN_B"); - assertArrayEquals(new int[] {9}, row2.getCells()); - assertEquals(9, row2.getTotalValue()); - - Row row3 = report.getRow("DOMAIN_C"); - assertArrayEquals(new int[] {10}, row3.getCells()); - assertEquals(10, row3.getTotalValue()); - - Row sumRow = report.getSumRow(); - assertArrayEquals(new int[] {41}, sumRow.getCells()); - assertEquals(41, sumRow.getTotalValue()); + // then + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report)); } + assertNotNull(report); + assertEquals(3, report.rowSize()); - private String reportToString(TaskStatusReport report) { - List columnHeaders = report.getColumnHeaders(); - String formatColumnWidth = "| %-7s "; - String formatFirstColumn = "| %-36s %-4s "; - String formatFirstColumnFirstLine = "| %-29s %12s "; - String formatFirstColumnSumLine = "| %-36s %-5s"; - int reportWidth = columnHeaders.size() * 10 + 46; + Row row1 = report.getRow("DOMAIN_A"); + assertArrayEquals(new int[] {22}, row1.getCells()); + assertEquals(22, row1.getTotalValue()); - StringBuilder builder = new StringBuilder(); - builder.append("\n"); - for (int i = 0; i < reportWidth; i++) { - builder.append("-"); - } - builder.append("\n"); - builder.append(String.format(formatFirstColumnFirstLine, "Domain", "Total")); - for (TaskStatusColumnHeader def : columnHeaders) { - builder.append(String.format(formatColumnWidth, def.getDisplayName())); - } - builder.append("|\n"); + Row row2 = report.getRow("DOMAIN_B"); + assertArrayEquals(new int[] {9}, row2.getCells()); + assertEquals(9, row2.getTotalValue()); - for (int i = 0; i < reportWidth; i++) { - builder.append("-"); - } - builder.append("\n"); + Row row3 = report.getRow("DOMAIN_C"); + assertArrayEquals(new int[] {10}, row3.getCells()); + assertEquals(10, row3.getTotalValue()); - for (String rl : report.rowTitles()) { - builder.append(String.format(formatFirstColumn, rl, report.getRow(rl).getTotalValue())); - for (int cell : report.getRow(rl).getCells()) { - builder.append(String.format(formatColumnWidth, cell)); - } - builder.append("|\n"); - for (int i = 0; i < reportWidth; i++) { - builder.append("-"); - } - builder.append("\n"); - } - builder.append(String.format(formatFirstColumnSumLine, "Total", report.getSumRow().getTotalValue())); - for (int cell : report.getSumRow().getCells()) { - builder.append(String.format(formatColumnWidth, cell)); - } - builder.append("|\n"); - for (int i = 0; i < reportWidth; i++) { - builder.append("-"); - } - builder.append("\n"); - return builder.toString(); + Row sumRow = report.getSumRow(); + assertArrayEquals(new int[] {41}, sumRow.getCells()); + assertEquals(41, sumRow.getTotalValue()); + } + + private String reportToString(TaskStatusReport report) { + List columnHeaders = report.getColumnHeaders(); + String formatColumnWidth = "| %-7s "; + String formatFirstColumn = "| %-36s %-4s "; + String formatFirstColumnFirstLine = "| %-29s %12s "; + String formatFirstColumnSumLine = "| %-36s %-5s"; + int reportWidth = columnHeaders.size() * 10 + 46; + + StringBuilder builder = new StringBuilder(); + builder.append("\n"); + for (int i = 0; i < reportWidth; i++) { + builder.append("-"); } + builder.append("\n"); + builder.append(String.format(formatFirstColumnFirstLine, "Domain", "Total")); + for (TaskStatusColumnHeader def : columnHeaders) { + builder.append(String.format(formatColumnWidth, def.getDisplayName())); + } + builder.append("|\n"); + for (int i = 0; i < reportWidth; i++) { + builder.append("-"); + } + builder.append("\n"); + + for (String rl : report.rowTitles()) { + builder.append(String.format(formatFirstColumn, rl, report.getRow(rl).getTotalValue())); + for (int cell : report.getRow(rl).getCells()) { + builder.append(String.format(formatColumnWidth, cell)); + } + builder.append("|\n"); + for (int i = 0; i < reportWidth; i++) { + builder.append("-"); + } + builder.append("\n"); + } + builder.append( + String.format(formatFirstColumnSumLine, "Total", report.getSumRow().getTotalValue())); + for (int cell : report.getSumRow().getCells()) { + builder.append(String.format(formatColumnWidth, cell)); + } + builder.append("|\n"); + for (int i = 0; i < reportWidth; i++) { + builder.append("-"); + } + builder.append("\n"); + return builder.toString(); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/report/ProvideTimestampReportAccTest.java b/lib/taskana-core/src/test/java/acceptance/report/ProvideTimestampReportAccTest.java index beab79e62..1e202e063 100644 --- a/lib/taskana-core/src/test/java/acceptance/report/ProvideTimestampReportAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/report/ProvideTimestampReportAccTest.java @@ -9,7 +9,6 @@ import java.util.HashSet; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; - import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -22,179 +21,178 @@ import pro.taskana.report.TimestampReport; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Test class for {@link TimestampReport}. - */ +/** Test class for {@link TimestampReport}. */ @ExtendWith(JAASExtension.class) class ProvideTimestampReportAccTest extends AbstractReportAccTest { - /** - * This test covers every insert operation of the TimestampReport. - * We have two definitions for org level 1: 'org1' and 'N/A'. - * All other org levels only contain 'N/A'. Thus this test only tests the separation for org level1. - * Since every OrgLevelRow is a FoldableRow this is sufficient - * to prove that the separation/grouping by detail mechanism works. - * - * @throws Exception if any error occurs during the test. - */ - @WithAccessId(userName = "monitor") - @Test - void testProperInsertionOfQueryItems() throws Exception { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + /** + * This test covers every insert operation of the TimestampReport. We have two definitions for org + * level 1: 'org1' and 'N/A'. All other org levels only contain 'N/A'. Thus this test only tests + * the separation for org level1. Since every OrgLevelRow is a FoldableRow this is sufficient to + * prove that the separation/grouping by detail mechanism works. + * + * @throws Exception if any error occurs during the test. + */ + @WithAccessId(userName = "monitor") + @Test + void testProperInsertionOfQueryItems() throws Exception { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - //last 14 days. Today excluded. - List headers = IntStream.range(-14, 0) + // last 14 days. Today excluded. + List headers = + IntStream.range(-14, 0) .mapToObj(TimeIntervalColumnHeader.Date::new) .collect(Collectors.toList()); - TimestampReport timestampReport = taskMonitorService.createTimestampReportBuilder() - .withColumnHeaders(headers) - .buildReport(); - final HashSet org1Set = new HashSet<>(Arrays.asList("N/A", "org1")); - final HashSet allOtherOrgLevelSet = new HashSet<>(Collections.singletonList("N/A")); + TimestampReport timestampReport = + taskMonitorService.createTimestampReportBuilder().withColumnHeaders(headers).buildReport(); + final HashSet org1Set = new HashSet<>(Arrays.asList("N/A", "org1")); + final HashSet allOtherOrgLevelSet = new HashSet<>(Collections.singletonList("N/A")); - assertEquals(2, timestampReport.getRows().size()); - assertEquals(new HashSet<>(Arrays.asList("CREATED", "COMPLETED")), - timestampReport.getRows().keySet()); + assertEquals(2, timestampReport.getRows().size()); + assertEquals( + new HashSet<>(Arrays.asList("CREATED", "COMPLETED")), timestampReport.getRows().keySet()); - // * * * * * * * * * * * * * * * * * * * * * TEST THE CREATED ROW * * * * * * * * * * * * * * * * * * * * * + // * * * * * * * * * * * * * * * * * * * * * TEST THE CREATED ROW * * * * * * * * * * * * * * + // * * * * * * * - TimestampRow statusRow = timestampReport.getRow("CREATED"); - assertEquals(2, statusRow.getFoldableRowCount()); - assertEquals(org1Set, statusRow.getFoldableRowKeySet()); - // 2 Entries with -8 days and one with -9 days. - assertArrayEquals(new int[] {0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0}, statusRow.getCells()); - assertEquals(3, statusRow.getTotalValue()); + TimestampRow statusRow = timestampReport.getRow("CREATED"); + assertEquals(2, statusRow.getFoldableRowCount()); + assertEquals(org1Set, statusRow.getFoldableRowKeySet()); + // 2 Entries with -8 days and one with -9 days. + assertArrayEquals(new int[] {0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0}, statusRow.getCells()); + assertEquals(3, statusRow.getTotalValue()); - // 'CREATED' -> 'org1' - TimestampRow.OrgLevel1Row org1Row = statusRow.getFoldableRow("org1"); - assertEquals(1, org1Row.getFoldableRowCount()); - assertEquals(allOtherOrgLevelSet, org1Row.getFoldableRowKeySet()); - // only task TKI:000000000000000000000000000000000029 in 'org1'. - assertArrayEquals(new int[] {0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0}, org1Row.getCells()); - assertEquals(1, org1Row.getTotalValue()); + // 'CREATED' -> 'org1' + TimestampRow.OrgLevel1Row org1Row = statusRow.getFoldableRow("org1"); + assertEquals(1, org1Row.getFoldableRowCount()); + assertEquals(allOtherOrgLevelSet, org1Row.getFoldableRowKeySet()); + // only task TKI:000000000000000000000000000000000029 in 'org1'. + assertArrayEquals(new int[] {0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0}, org1Row.getCells()); + assertEquals(1, org1Row.getTotalValue()); - // 'CREATED' -> 'org1'/'N/A' - TimestampRow.OrgLevel2Row org2Row = org1Row.getFoldableRow("N/A"); - assertEquals(1, org2Row.getFoldableRowCount()); - assertEquals(allOtherOrgLevelSet, org2Row.getFoldableRowKeySet()); - // Since no further separation (in org level) they should be the same. - assertArrayEquals(org1Row.getCells(), org2Row.getCells()); - assertEquals(org1Row.getTotalValue(), org2Row.getTotalValue()); + // 'CREATED' -> 'org1'/'N/A' + TimestampRow.OrgLevel2Row org2Row = org1Row.getFoldableRow("N/A"); + assertEquals(1, org2Row.getFoldableRowCount()); + assertEquals(allOtherOrgLevelSet, org2Row.getFoldableRowKeySet()); + // Since no further separation (in org level) they should be the same. + assertArrayEquals(org1Row.getCells(), org2Row.getCells()); + assertEquals(org1Row.getTotalValue(), org2Row.getTotalValue()); - // 'CREATED' -> 'org1'/'N/A'/'N/A' - TimestampRow.OrgLevel3Row org3Row = org2Row.getFoldableRow("N/A"); - assertEquals(1, org2Row.getFoldableRowCount()); - assertEquals(allOtherOrgLevelSet, org3Row.getFoldableRowKeySet()); - // Since no further separation (in org level) they should be the same. - assertArrayEquals(org2Row.getCells(), org3Row.getCells()); - assertEquals(org2Row.getTotalValue(), org3Row.getTotalValue()); + // 'CREATED' -> 'org1'/'N/A'/'N/A' + TimestampRow.OrgLevel3Row org3Row = org2Row.getFoldableRow("N/A"); + assertEquals(1, org2Row.getFoldableRowCount()); + assertEquals(allOtherOrgLevelSet, org3Row.getFoldableRowKeySet()); + // Since no further separation (in org level) they should be the same. + assertArrayEquals(org2Row.getCells(), org3Row.getCells()); + assertEquals(org2Row.getTotalValue(), org3Row.getTotalValue()); - // 'CREATED' -> 'org1'/'N/A'/'N/A'/'N/A' - SingleRow org4Row = org3Row.getFoldableRow("N/A"); - // Since no further separation (in org level) they should be the same. - assertArrayEquals(org3Row.getCells(), org4Row.getCells()); - assertEquals(org3Row.getTotalValue(), org4Row.getTotalValue()); + // 'CREATED' -> 'org1'/'N/A'/'N/A'/'N/A' + SingleRow org4Row = org3Row.getFoldableRow("N/A"); + // Since no further separation (in org level) they should be the same. + assertArrayEquals(org3Row.getCells(), org4Row.getCells()); + assertEquals(org3Row.getTotalValue(), org4Row.getTotalValue()); - // 'CREATED' -> 'N/A' - org1Row = statusRow.getFoldableRow("N/A"); - assertEquals(1, org1Row.getFoldableRowCount()); - assertEquals(allOtherOrgLevelSet, org1Row.getFoldableRowKeySet()); - // task TKI:000000000000000000000000000000000030, - // and TKI:000000000000000000000000000000000036 in 'N/A'. - assertArrayEquals(new int[] {0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0}, org1Row.getCells()); - assertEquals(2, org1Row.getTotalValue()); + // 'CREATED' -> 'N/A' + org1Row = statusRow.getFoldableRow("N/A"); + assertEquals(1, org1Row.getFoldableRowCount()); + assertEquals(allOtherOrgLevelSet, org1Row.getFoldableRowKeySet()); + // task TKI:000000000000000000000000000000000030, + // and TKI:000000000000000000000000000000000036 in 'N/A'. + assertArrayEquals(new int[] {0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0}, org1Row.getCells()); + assertEquals(2, org1Row.getTotalValue()); - // 'CREATED' -> 'N/A'/'N/A' - org2Row = org1Row.getFoldableRow("N/A"); - assertEquals(1, org2Row.getFoldableRowCount()); - assertEquals(allOtherOrgLevelSet, org2Row.getFoldableRowKeySet()); - // Since no further separation (in org level) they should be the same. - assertArrayEquals(org1Row.getCells(), org2Row.getCells()); - assertEquals(org1Row.getTotalValue(), org2Row.getTotalValue()); + // 'CREATED' -> 'N/A'/'N/A' + org2Row = org1Row.getFoldableRow("N/A"); + assertEquals(1, org2Row.getFoldableRowCount()); + assertEquals(allOtherOrgLevelSet, org2Row.getFoldableRowKeySet()); + // Since no further separation (in org level) they should be the same. + assertArrayEquals(org1Row.getCells(), org2Row.getCells()); + assertEquals(org1Row.getTotalValue(), org2Row.getTotalValue()); - // 'CREATED' -> 'N/A'/'N/A'/'N/A' - org3Row = org2Row.getFoldableRow("N/A"); - assertEquals(1, org2Row.getFoldableRowCount()); - assertEquals(allOtherOrgLevelSet, org3Row.getFoldableRowKeySet()); - // Since no further separation (in org level) they should be the same. - assertArrayEquals(org2Row.getCells(), org3Row.getCells()); - assertEquals(org2Row.getTotalValue(), org3Row.getTotalValue()); + // 'CREATED' -> 'N/A'/'N/A'/'N/A' + org3Row = org2Row.getFoldableRow("N/A"); + assertEquals(1, org2Row.getFoldableRowCount()); + assertEquals(allOtherOrgLevelSet, org3Row.getFoldableRowKeySet()); + // Since no further separation (in org level) they should be the same. + assertArrayEquals(org2Row.getCells(), org3Row.getCells()); + assertEquals(org2Row.getTotalValue(), org3Row.getTotalValue()); - // 'CREATED' -> 'N/A'/'N/A'/'N/A'/'N/A' - org4Row = org3Row.getFoldableRow("N/A"); - // Since no further separation (in org level) they should be the same. - assertArrayEquals(org3Row.getCells(), org4Row.getCells()); - assertEquals(org3Row.getTotalValue(), org4Row.getTotalValue()); + // 'CREATED' -> 'N/A'/'N/A'/'N/A'/'N/A' + org4Row = org3Row.getFoldableRow("N/A"); + // Since no further separation (in org level) they should be the same. + assertArrayEquals(org3Row.getCells(), org4Row.getCells()); + assertEquals(org3Row.getTotalValue(), org4Row.getTotalValue()); - // * * * * * * * * * * * * * * * * * * * * * TEST THE COMPLETED ROW * * * * * * * * * * * * * * * * * * * * * + // * * * * * * * * * * * * * * * * * * * * * TEST THE COMPLETED ROW * * * * * * * * * * * * * + // * * * * * * * * - statusRow = timestampReport.getRow("COMPLETED"); - assertEquals(2, statusRow.getFoldableRowCount()); - assertEquals(org1Set, statusRow.getFoldableRowKeySet()); - // 2 Entries with -1 days, one with -2 days and one with -7 days. - assertArrayEquals(new int[] {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 2}, statusRow.getCells()); - assertEquals(4, statusRow.getTotalValue()); + statusRow = timestampReport.getRow("COMPLETED"); + assertEquals(2, statusRow.getFoldableRowCount()); + assertEquals(org1Set, statusRow.getFoldableRowKeySet()); + // 2 Entries with -1 days, one with -2 days and one with -7 days. + assertArrayEquals(new int[] {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 2}, statusRow.getCells()); + assertEquals(4, statusRow.getTotalValue()); - // 'COMPLETED' -> 'org1' - org1Row = statusRow.getFoldableRow("org1"); - assertEquals(1, org1Row.getFoldableRowCount()); - assertEquals(allOtherOrgLevelSet, org1Row.getFoldableRowKeySet()); - // only task TKI:000000000000000000000000000000000029 in 'org1'. - assertArrayEquals(new int[] {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0}, org1Row.getCells()); - assertEquals(1, org1Row.getTotalValue()); + // 'COMPLETED' -> 'org1' + org1Row = statusRow.getFoldableRow("org1"); + assertEquals(1, org1Row.getFoldableRowCount()); + assertEquals(allOtherOrgLevelSet, org1Row.getFoldableRowKeySet()); + // only task TKI:000000000000000000000000000000000029 in 'org1'. + assertArrayEquals(new int[] {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0}, org1Row.getCells()); + assertEquals(1, org1Row.getTotalValue()); - // 'COMPLETED' -> 'org1'/'N/A' - org2Row = org1Row.getFoldableRow("N/A"); - assertEquals(1, org2Row.getFoldableRowCount()); - assertEquals(allOtherOrgLevelSet, org2Row.getFoldableRowKeySet()); - // Since no further separation (in org level) they should be the same. - assertArrayEquals(org1Row.getCells(), org2Row.getCells()); - assertEquals(org1Row.getTotalValue(), org2Row.getTotalValue()); + // 'COMPLETED' -> 'org1'/'N/A' + org2Row = org1Row.getFoldableRow("N/A"); + assertEquals(1, org2Row.getFoldableRowCount()); + assertEquals(allOtherOrgLevelSet, org2Row.getFoldableRowKeySet()); + // Since no further separation (in org level) they should be the same. + assertArrayEquals(org1Row.getCells(), org2Row.getCells()); + assertEquals(org1Row.getTotalValue(), org2Row.getTotalValue()); - // 'COMPLETED' -> 'org1'/'N/A'/'N/A' - org3Row = org2Row.getFoldableRow("N/A"); - assertEquals(1, org2Row.getFoldableRowCount()); - assertEquals(allOtherOrgLevelSet, org3Row.getFoldableRowKeySet()); - // Since no further separation (in org level) they should be the same. - assertArrayEquals(org2Row.getCells(), org3Row.getCells()); - assertEquals(org2Row.getTotalValue(), org3Row.getTotalValue()); + // 'COMPLETED' -> 'org1'/'N/A'/'N/A' + org3Row = org2Row.getFoldableRow("N/A"); + assertEquals(1, org2Row.getFoldableRowCount()); + assertEquals(allOtherOrgLevelSet, org3Row.getFoldableRowKeySet()); + // Since no further separation (in org level) they should be the same. + assertArrayEquals(org2Row.getCells(), org3Row.getCells()); + assertEquals(org2Row.getTotalValue(), org3Row.getTotalValue()); - // 'COMPLETED' -> 'org1'/'N/A'/'N/A'/'N/A' - org4Row = org3Row.getFoldableRow("N/A"); - // Since no further separation (in org level) they should be the same. - assertArrayEquals(org3Row.getCells(), org4Row.getCells()); - assertEquals(org3Row.getTotalValue(), org4Row.getTotalValue()); + // 'COMPLETED' -> 'org1'/'N/A'/'N/A'/'N/A' + org4Row = org3Row.getFoldableRow("N/A"); + // Since no further separation (in org level) they should be the same. + assertArrayEquals(org3Row.getCells(), org4Row.getCells()); + assertEquals(org3Row.getTotalValue(), org4Row.getTotalValue()); - // 'COMPLETED' -> 'N/A' - org1Row = statusRow.getFoldableRow("N/A"); - assertEquals(1, org1Row.getFoldableRowCount()); - assertEquals(allOtherOrgLevelSet, org1Row.getFoldableRowKeySet()); - // task TKI:000000000000000000000000000000000032, - // TKI:000000000000000000000000000000000034, - // and TKI:000000000000000000000000000000000037 in 'N/A'. - assertArrayEquals(new int[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2}, org1Row.getCells()); - assertEquals(3, org1Row.getTotalValue()); + // 'COMPLETED' -> 'N/A' + org1Row = statusRow.getFoldableRow("N/A"); + assertEquals(1, org1Row.getFoldableRowCount()); + assertEquals(allOtherOrgLevelSet, org1Row.getFoldableRowKeySet()); + // task TKI:000000000000000000000000000000000032, + // TKI:000000000000000000000000000000000034, + // and TKI:000000000000000000000000000000000037 in 'N/A'. + assertArrayEquals(new int[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2}, org1Row.getCells()); + assertEquals(3, org1Row.getTotalValue()); - // 'COMPLETED' -> 'N/A'/'N/A' - org2Row = org1Row.getFoldableRow("N/A"); - assertEquals(1, org2Row.getFoldableRowCount()); - assertEquals(allOtherOrgLevelSet, org2Row.getFoldableRowKeySet()); - // Since no further separation (in org level) they should be the same. - assertArrayEquals(org1Row.getCells(), org2Row.getCells()); - assertEquals(org1Row.getTotalValue(), org2Row.getTotalValue()); + // 'COMPLETED' -> 'N/A'/'N/A' + org2Row = org1Row.getFoldableRow("N/A"); + assertEquals(1, org2Row.getFoldableRowCount()); + assertEquals(allOtherOrgLevelSet, org2Row.getFoldableRowKeySet()); + // Since no further separation (in org level) they should be the same. + assertArrayEquals(org1Row.getCells(), org2Row.getCells()); + assertEquals(org1Row.getTotalValue(), org2Row.getTotalValue()); - // 'COMPLETED' -> 'N/A'/'N/A'/'N/A' - org3Row = org2Row.getFoldableRow("N/A"); - assertEquals(1, org2Row.getFoldableRowCount()); - assertEquals(allOtherOrgLevelSet, org3Row.getFoldableRowKeySet()); - // Since no further separation (in org level) they should be the same. - assertArrayEquals(org2Row.getCells(), org3Row.getCells()); - assertEquals(org2Row.getTotalValue(), org3Row.getTotalValue()); + // 'COMPLETED' -> 'N/A'/'N/A'/'N/A' + org3Row = org2Row.getFoldableRow("N/A"); + assertEquals(1, org2Row.getFoldableRowCount()); + assertEquals(allOtherOrgLevelSet, org3Row.getFoldableRowKeySet()); + // Since no further separation (in org level) they should be the same. + assertArrayEquals(org2Row.getCells(), org3Row.getCells()); + assertEquals(org2Row.getTotalValue(), org3Row.getTotalValue()); - // 'COMPLETED' -> 'N/A'/'N/A'/'N/A'/'N/A' - org4Row = org3Row.getFoldableRow("N/A"); - // Since no further separation (in org level) they should be the same. - assertArrayEquals(org3Row.getCells(), org4Row.getCells()); - assertEquals(org3Row.getTotalValue(), org4Row.getTotalValue()); - } + // 'COMPLETED' -> 'N/A'/'N/A'/'N/A'/'N/A' + org4Row = org3Row.getFoldableRow("N/A"); + // Since no further separation (in org level) they should be the same. + assertArrayEquals(org3Row.getCells(), org4Row.getCells()); + assertEquals(org3Row.getTotalValue(), org4Row.getTotalValue()); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/report/ProvideWorkbasketReportAccTest.java b/lib/taskana-core/src/test/java/acceptance/report/ProvideWorkbasketReportAccTest.java index 199a3407a..dbea8267d 100644 --- a/lib/taskana-core/src/test/java/acceptance/report/ProvideWorkbasketReportAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/report/ProvideWorkbasketReportAccTest.java @@ -11,7 +11,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.IntStream; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -29,465 +28,477 @@ import pro.taskana.report.WorkbasketReport; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "workbasket level report" scenarios. - */ +/** Acceptance test for all "workbasket level report" scenarios. */ @ExtendWith(JAASExtension.class) class ProvideWorkbasketReportAccTest extends AbstractReportAccTest { - private static final Logger LOGGER = LoggerFactory.getLogger(ProvideWorkbasketReportAccTest.class); + private static final Logger LOGGER = + LoggerFactory.getLogger(ProvideWorkbasketReportAccTest.class); - @Test - void testRoleCheck() { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + @Test + void testRoleCheck() { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - Assertions.assertThrows(NotAuthorizedException.class, () -> - taskMonitorService.createWorkbasketReportBuilder().buildReport()); + Assertions.assertThrows( + NotAuthorizedException.class, + () -> taskMonitorService.createWorkbasketReportBuilder().buildReport()); + } + + @WithAccessId(userName = "monitor") + @Test + void testGetTotalNumbersOfTasksOfWorkbasketReportBasedOnDueDate() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + WorkbasketReport report = taskMonitorService.createWorkbasketReportBuilder().buildReport(); + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report)); } - @WithAccessId( - userName = "monitor") - @Test - void testGetTotalNumbersOfTasksOfWorkbasketReportBasedOnDueDate() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(3, report.rowSize()); - WorkbasketReport report = taskMonitorService.createWorkbasketReportBuilder().buildReport(); + assertEquals(20, report.getRow("USER_1_1").getTotalValue()); + assertEquals(20, report.getRow("USER_1_2").getTotalValue()); + assertEquals(10, report.getRow("USER_1_3").getTotalValue()); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report)); - } + assertEquals(50, report.getSumRow().getTotalValue()); + } - assertNotNull(report); - assertEquals(3, report.rowSize()); + @WithAccessId(userName = "monitor") + @Test + void testGetWorkbasketReportWithReportLineItemDefinitions() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - assertEquals(20, report.getRow("USER_1_1").getTotalValue()); - assertEquals(20, report.getRow("USER_1_2").getTotalValue()); - assertEquals(10, report.getRow("USER_1_3").getTotalValue()); + List columnHeaders = getListOfColumnHeaders(); - assertEquals(50, report.getSumRow().getTotalValue()); - } - - @WithAccessId( - userName = "monitor") - @Test - void testGetWorkbasketReportWithReportLineItemDefinitions() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - - List columnHeaders = getListOfColumnHeaders(); - - WorkbasketReport report = taskMonitorService.createWorkbasketReportBuilder() + WorkbasketReport report = + taskMonitorService + .createWorkbasketReportBuilder() .withColumnHeaders(columnHeaders) .inWorkingDays() .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - int sumLineCount = IntStream.of(report.getSumRow().getCells()).sum(); - - assertNotNull(report); - assertEquals(3, report.rowSize()); - - assertEquals(20, report.getRow("USER_1_1").getTotalValue()); - assertEquals(20, report.getRow("USER_1_2").getTotalValue()); - assertEquals(10, report.getRow("USER_1_3").getTotalValue()); - - int[] sumRow = report.getSumRow().getCells(); - assertArrayEquals(new int[] {10, 9, 11, 0, 4, 0, 7, 4, 5}, sumRow); - - assertEquals(50, report.getSumRow().getTotalValue()); - assertEquals(50, sumLineCount); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfWorkbasketReport() throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + int sumLineCount = IntStream.of(report.getSumRow().getCells()).sum(); - List columnHeaders = getShortListOfColumnHeaders(); + assertNotNull(report); + assertEquals(3, report.rowSize()); - WorkbasketReport report = taskMonitorService.createWorkbasketReportBuilder() + assertEquals(20, report.getRow("USER_1_1").getTotalValue()); + assertEquals(20, report.getRow("USER_1_2").getTotalValue()); + assertEquals(10, report.getRow("USER_1_3").getTotalValue()); + + int[] sumRow = report.getSumRow().getCells(); + assertArrayEquals(new int[] {10, 9, 11, 0, 4, 0, 7, 4, 5}, sumRow); + + assertEquals(50, report.getSumRow().getTotalValue()); + assertEquals(50, sumLineCount); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfWorkbasketReport() throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List columnHeaders = getShortListOfColumnHeaders(); + + WorkbasketReport report = + taskMonitorService + .createWorkbasketReportBuilder() .withColumnHeaders(columnHeaders) .inWorkingDays() .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(3, report.rowSize()); - - int[] row1 = report.getRow("USER_1_1").getCells(); - assertArrayEquals(new int[] {13, 3, 1, 1, 2}, row1); - - int[] row2 = report.getRow("USER_1_2").getCells(); - assertArrayEquals(new int[] {4, 6, 3, 6, 1}, row2); - - int[] row3 = report.getRow("USER_1_3").getCells(); - assertArrayEquals(new int[] {2, 2, 0, 0, 6}, row3); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfWorkbasketReportNotInWorkingDays() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(3, report.rowSize()); - List columnHeaders = getShortListOfColumnHeaders(); + int[] row1 = report.getRow("USER_1_1").getCells(); + assertArrayEquals(new int[] {13, 3, 1, 1, 2}, row1); - WorkbasketReport report = taskMonitorService.createWorkbasketReportBuilder() + int[] row2 = report.getRow("USER_1_2").getCells(); + assertArrayEquals(new int[] {4, 6, 3, 6, 1}, row2); + + int[] row3 = report.getRow("USER_1_3").getCells(); + assertArrayEquals(new int[] {2, 2, 0, 0, 6}, row3); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfWorkbasketReportNotInWorkingDays() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List columnHeaders = getShortListOfColumnHeaders(); + + WorkbasketReport report = + taskMonitorService + .createWorkbasketReportBuilder() .withColumnHeaders(columnHeaders) .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(3, report.rowSize()); - - int[] row1 = report.getRow("USER_1_1").getCells(); - assertArrayEquals(new int[] {16, 0, 1, 0, 3}, row1); - - int[] row2 = report.getRow("USER_1_2").getCells(); - assertArrayEquals(new int[] {10, 0, 3, 0, 7}, row2); - - int[] row3 = report.getRow("USER_1_3").getCells(); - assertArrayEquals(new int[] {4, 0, 0, 0, 6}, row3); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfWorkbasketReportWithWorkbasketFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(3, report.rowSize()); - List workbasketIds = Collections.singletonList("WBI:000000000000000000000000000000000001"); - List columnHeaders = getShortListOfColumnHeaders(); + int[] row1 = report.getRow("USER_1_1").getCells(); + assertArrayEquals(new int[] {16, 0, 1, 0, 3}, row1); - WorkbasketReport report = taskMonitorService.createWorkbasketReportBuilder() + int[] row2 = report.getRow("USER_1_2").getCells(); + assertArrayEquals(new int[] {10, 0, 3, 0, 7}, row2); + + int[] row3 = report.getRow("USER_1_3").getCells(); + assertArrayEquals(new int[] {4, 0, 0, 0, 6}, row3); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfWorkbasketReportWithWorkbasketFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List workbasketIds = + Collections.singletonList("WBI:000000000000000000000000000000000001"); + List columnHeaders = getShortListOfColumnHeaders(); + + WorkbasketReport report = + taskMonitorService + .createWorkbasketReportBuilder() .withColumnHeaders(columnHeaders) .workbasketIdIn(workbasketIds) .inWorkingDays() .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(1, report.rowSize()); - - int[] row1 = report.getRow("USER_1_1").getCells(); - assertArrayEquals(new int[] {13, 3, 1, 1, 2}, row1); - + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfWorkbasketReportWithStateFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(1, report.rowSize()); - List states = Collections.singletonList(TaskState.READY); - List columnHeaders = getShortListOfColumnHeaders(); + int[] row1 = report.getRow("USER_1_1").getCells(); + assertArrayEquals(new int[] {13, 3, 1, 1, 2}, row1); + } - WorkbasketReport report = taskMonitorService.createWorkbasketReportBuilder() + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfWorkbasketReportWithStateFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List states = Collections.singletonList(TaskState.READY); + List columnHeaders = getShortListOfColumnHeaders(); + + WorkbasketReport report = + taskMonitorService + .createWorkbasketReportBuilder() .withColumnHeaders(columnHeaders) .stateIn(states) .inWorkingDays() .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(3, report.rowSize()); - - int[] row1 = report.getRow("USER_1_1").getCells(); - assertArrayEquals(new int[] {13, 3, 1, 1, 0}, row1); - - int[] row2 = report.getRow("USER_1_2").getCells(); - assertArrayEquals(new int[] {4, 6, 3, 6, 0}, row2); - - int[] row3 = report.getRow("USER_1_3").getCells(); - assertArrayEquals(new int[] {2, 2, 0, 0, 0}, row3); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfWorkbasketReportWithCategoryFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(3, report.rowSize()); - List categories = Arrays.asList("AUTOMATIC", "MANUAL"); - List columnHeaders = getShortListOfColumnHeaders(); + int[] row1 = report.getRow("USER_1_1").getCells(); + assertArrayEquals(new int[] {13, 3, 1, 1, 0}, row1); - WorkbasketReport report = taskMonitorService.createWorkbasketReportBuilder() + int[] row2 = report.getRow("USER_1_2").getCells(); + assertArrayEquals(new int[] {4, 6, 3, 6, 0}, row2); + + int[] row3 = report.getRow("USER_1_3").getCells(); + assertArrayEquals(new int[] {2, 2, 0, 0, 0}, row3); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfWorkbasketReportWithCategoryFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List categories = Arrays.asList("AUTOMATIC", "MANUAL"); + List columnHeaders = getShortListOfColumnHeaders(); + + WorkbasketReport report = + taskMonitorService + .createWorkbasketReportBuilder() .withColumnHeaders(columnHeaders) .categoryIn(categories) .inWorkingDays() .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(3, report.rowSize()); - - int[] row1 = report.getRow("USER_1_1").getCells(); - assertArrayEquals(new int[] {3, 1, 1, 1, 2}, row1); - - int[] row2 = report.getRow("USER_1_2").getCells(); - assertArrayEquals(new int[] {1, 1, 1, 0, 1}, row2); - - int[] row3 = report.getRow("USER_1_3").getCells(); - assertArrayEquals(new int[] {0, 1, 0, 0, 4}, row3); - + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfWorkbasketReportWithDomainFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(3, report.rowSize()); - List domains = Collections.singletonList("DOMAIN_A"); - List columnHeaders = getShortListOfColumnHeaders(); + int[] row1 = report.getRow("USER_1_1").getCells(); + assertArrayEquals(new int[] {3, 1, 1, 1, 2}, row1); - WorkbasketReport report = taskMonitorService.createWorkbasketReportBuilder() + int[] row2 = report.getRow("USER_1_2").getCells(); + assertArrayEquals(new int[] {1, 1, 1, 0, 1}, row2); + + int[] row3 = report.getRow("USER_1_3").getCells(); + assertArrayEquals(new int[] {0, 1, 0, 0, 4}, row3); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfWorkbasketReportWithDomainFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List domains = Collections.singletonList("DOMAIN_A"); + List columnHeaders = getShortListOfColumnHeaders(); + + WorkbasketReport report = + taskMonitorService + .createWorkbasketReportBuilder() .withColumnHeaders(columnHeaders) .domainIn(domains) .inWorkingDays() .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(3, report.rowSize()); - - int[] row1 = report.getRow("USER_1_1").getCells(); - assertArrayEquals(new int[] {8, 1, 0, 1, 2}, row1); - - int[] row2 = report.getRow("USER_1_2").getCells(); - assertArrayEquals(new int[] {2, 2, 2, 4, 0}, row2); - - int[] row3 = report.getRow("USER_1_3").getCells(); - assertArrayEquals(new int[] {1, 1, 0, 0, 2}, row3); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfWorkbasketReportWithCustomFieldValueFilter() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(3, report.rowSize()); - Map customAttributeFilter = new HashMap<>(); - customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); - List columnHeaders = getShortListOfColumnHeaders(); + int[] row1 = report.getRow("USER_1_1").getCells(); + assertArrayEquals(new int[] {8, 1, 0, 1, 2}, row1); - WorkbasketReport report = taskMonitorService.createWorkbasketReportBuilder() + int[] row2 = report.getRow("USER_1_2").getCells(); + assertArrayEquals(new int[] {2, 2, 2, 4, 0}, row2); + + int[] row3 = report.getRow("USER_1_3").getCells(); + assertArrayEquals(new int[] {1, 1, 0, 0, 2}, row3); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfWorkbasketReportWithCustomFieldValueFilter() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + Map customAttributeFilter = new HashMap<>(); + customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); + List columnHeaders = getShortListOfColumnHeaders(); + + WorkbasketReport report = + taskMonitorService + .createWorkbasketReportBuilder() .withColumnHeaders(columnHeaders) .customAttributeFilterIn(customAttributeFilter) .inWorkingDays() .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(3, report.rowSize()); - - int[] row1 = report.getRow("USER_1_1").getCells(); - assertArrayEquals(new int[] {6, 1, 1, 1, 1}, row1); - - int[] row2 = report.getRow("USER_1_2").getCells(); - assertArrayEquals(new int[] {3, 2, 2, 3, 1}, row2); - - int[] row3 = report.getRow("USER_1_3").getCells(); - assertArrayEquals(new int[] {2, 1, 0, 0, 1}, row3); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testEachItemOfWorkbasketReportForSelectedClassifications() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + assertNotNull(report); + assertEquals(3, report.rowSize()); - List columnHeaders = getShortListOfColumnHeaders(); - List combinedClassificationFilter = new ArrayList<>(); - combinedClassificationFilter - .add(new CombinedClassificationFilter("CLI:000000000000000000000000000000000003", - "CLI:000000000000000000000000000000000008")); - combinedClassificationFilter - .add(new CombinedClassificationFilter("CLI:000000000000000000000000000000000003", - "CLI:000000000000000000000000000000000009")); - combinedClassificationFilter - .add(new CombinedClassificationFilter("CLI:000000000000000000000000000000000002", - "CLI:000000000000000000000000000000000007")); - combinedClassificationFilter - .add(new CombinedClassificationFilter("CLI:000000000000000000000000000000000005")); + int[] row1 = report.getRow("USER_1_1").getCells(); + assertArrayEquals(new int[] {6, 1, 1, 1, 1}, row1); - WorkbasketReport report = taskMonitorService.createWorkbasketReportBuilder() + int[] row2 = report.getRow("USER_1_2").getCells(); + assertArrayEquals(new int[] {3, 2, 2, 3, 1}, row2); + + int[] row3 = report.getRow("USER_1_3").getCells(); + assertArrayEquals(new int[] {2, 1, 0, 0, 1}, row3); + } + + @WithAccessId(userName = "monitor") + @Test + void testEachItemOfWorkbasketReportForSelectedClassifications() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + + List columnHeaders = getShortListOfColumnHeaders(); + List combinedClassificationFilter = new ArrayList<>(); + combinedClassificationFilter.add( + new CombinedClassificationFilter( + "CLI:000000000000000000000000000000000003", + "CLI:000000000000000000000000000000000008")); + combinedClassificationFilter.add( + new CombinedClassificationFilter( + "CLI:000000000000000000000000000000000003", + "CLI:000000000000000000000000000000000009")); + combinedClassificationFilter.add( + new CombinedClassificationFilter( + "CLI:000000000000000000000000000000000002", + "CLI:000000000000000000000000000000000007")); + combinedClassificationFilter.add( + new CombinedClassificationFilter("CLI:000000000000000000000000000000000005")); + + WorkbasketReport report = + taskMonitorService + .createWorkbasketReportBuilder() .withColumnHeaders(columnHeaders) .combinedClassificationFilterIn(combinedClassificationFilter) .inWorkingDays() .buildReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report, columnHeaders)); - } - - assertNotNull(report); - assertEquals(3, report.rowSize()); - - int[] row1 = report.getRow("USER_1_1").getCells(); - assertArrayEquals(new int[] {3, 3, 0, 1, 1}, row1); - - int[] row2 = report.getRow("USER_1_2").getCells(); - assertArrayEquals(new int[] {0, 2, 1, 6, 0}, row2); - - int[] row3 = report.getRow("USER_1_3").getCells(); - assertArrayEquals(new int[] {1, 0, 0, 0, 3}, row3); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report, columnHeaders)); } - @WithAccessId( - userName = "monitor") - @Test - void testGetTotalNumbersOfTasksOfWorkbasketReportBasedOnPlannedDateWithReportLineItemDefinitions() - throws InvalidArgumentException, NotAuthorizedException { - TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); - List columnHeaders = getListOfColumnHeaders(); + assertNotNull(report); + assertEquals(3, report.rowSize()); - WorkbasketReport report = taskMonitorService.createWorkbasketReportBuilder() + int[] row1 = report.getRow("USER_1_1").getCells(); + assertArrayEquals(new int[] {3, 3, 0, 1, 1}, row1); + + int[] row2 = report.getRow("USER_1_2").getCells(); + assertArrayEquals(new int[] {0, 2, 1, 6, 0}, row2); + + int[] row3 = report.getRow("USER_1_3").getCells(); + assertArrayEquals(new int[] {1, 0, 0, 0, 3}, row3); + } + + @WithAccessId(userName = "monitor") + @Test + void testGetTotalNumbersOfTasksOfWorkbasketReportBasedOnPlannedDateWithReportLineItemDefinitions() + throws InvalidArgumentException, NotAuthorizedException { + TaskMonitorService taskMonitorService = taskanaEngine.getTaskMonitorService(); + List columnHeaders = getListOfColumnHeaders(); + + WorkbasketReport report = + taskMonitorService + .createWorkbasketReportBuilder() .withColumnHeaders(columnHeaders) .buildPlannedDateBasedReport(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(reportToString(report)); - } - - assertNotNull(report); - assertEquals(3, report.rowSize()); - - assertEquals(20, report.getRow("USER_1_1").getTotalValue()); - assertEquals(20, report.getRow("USER_1_2").getTotalValue()); - assertEquals(10, report.getRow("USER_1_3").getTotalValue()); - assertEquals(2, report.getRow("USER_1_1").getCells()[2]); - assertEquals(1, report.getRow("USER_1_2").getCells()[1]); - - assertEquals(50, report.getSumRow().getTotalValue()); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(reportToString(report)); } - private List getListOfColumnHeaders() { - List columnHeaders = new ArrayList<>(); - columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -11)); - columnHeaders.add(new TimeIntervalColumnHeader(-10, -6)); - columnHeaders.add(new TimeIntervalColumnHeader(-5, -2)); - columnHeaders.add(new TimeIntervalColumnHeader(-1)); - columnHeaders.add(new TimeIntervalColumnHeader(0)); - columnHeaders.add(new TimeIntervalColumnHeader(1)); - columnHeaders.add(new TimeIntervalColumnHeader(2, 5)); - columnHeaders.add(new TimeIntervalColumnHeader(6, 10)); - columnHeaders.add(new TimeIntervalColumnHeader(11, Integer.MAX_VALUE)); - return columnHeaders; + assertNotNull(report); + assertEquals(3, report.rowSize()); + + assertEquals(20, report.getRow("USER_1_1").getTotalValue()); + assertEquals(20, report.getRow("USER_1_2").getTotalValue()); + assertEquals(10, report.getRow("USER_1_3").getTotalValue()); + assertEquals(2, report.getRow("USER_1_1").getCells()[2]); + assertEquals(1, report.getRow("USER_1_2").getCells()[1]); + + assertEquals(50, report.getSumRow().getTotalValue()); + } + + private List getListOfColumnHeaders() { + List columnHeaders = new ArrayList<>(); + columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -11)); + columnHeaders.add(new TimeIntervalColumnHeader(-10, -6)); + columnHeaders.add(new TimeIntervalColumnHeader(-5, -2)); + columnHeaders.add(new TimeIntervalColumnHeader(-1)); + columnHeaders.add(new TimeIntervalColumnHeader(0)); + columnHeaders.add(new TimeIntervalColumnHeader(1)); + columnHeaders.add(new TimeIntervalColumnHeader(2, 5)); + columnHeaders.add(new TimeIntervalColumnHeader(6, 10)); + columnHeaders.add(new TimeIntervalColumnHeader(11, Integer.MAX_VALUE)); + return columnHeaders; + } + + private List getShortListOfColumnHeaders() { + List columnHeaders = new ArrayList<>(); + columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -6)); + columnHeaders.add(new TimeIntervalColumnHeader(-5, -1)); + columnHeaders.add(new TimeIntervalColumnHeader(0)); + columnHeaders.add(new TimeIntervalColumnHeader(1, 5)); + columnHeaders.add(new TimeIntervalColumnHeader(6, Integer.MAX_VALUE)); + return columnHeaders; + } + + private String reportToString(WorkbasketReport report) { + return reportToString(report, null); + } + + private String reportToString( + WorkbasketReport report, List reportLineItemDefinitions) { + String formatColumWidth = "| %-7s "; + String formatFirstColumn = "| %-36s %-4s "; + String formatFirstColumnFirstLine = "| %-29s %12s "; + String formatFirstColumnSumLine = "| %-36s %-5s"; + int reportWidth = + reportLineItemDefinitions == null ? 46 : reportLineItemDefinitions.size() * 10 + 46; + + StringBuilder builder = new StringBuilder(); + builder.append("\n"); + for (int i = 0; i < reportWidth; i++) { + builder.append("-"); } - - private List getShortListOfColumnHeaders() { - List columnHeaders = new ArrayList<>(); - columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -6)); - columnHeaders.add(new TimeIntervalColumnHeader(-5, -1)); - columnHeaders.add(new TimeIntervalColumnHeader(0)); - columnHeaders.add(new TimeIntervalColumnHeader(1, 5)); - columnHeaders.add(new TimeIntervalColumnHeader(6, Integer.MAX_VALUE)); - return columnHeaders; + builder.append("\n"); + builder.append(String.format(formatFirstColumnFirstLine, "Workbaskets", "Total")); + if (reportLineItemDefinitions != null) { + for (TimeIntervalColumnHeader def : reportLineItemDefinitions) { + if (def.getLowerAgeLimit() == Integer.MIN_VALUE) { + builder.append(String.format(formatColumWidth, "< " + def.getUpperAgeLimit())); + } else if (def.getUpperAgeLimit() == Integer.MAX_VALUE) { + builder.append(String.format(formatColumWidth, "> " + def.getLowerAgeLimit())); + } else if (def.getLowerAgeLimit() == def.getUpperAgeLimit()) { + if (def.getLowerAgeLimit() == 0) { + builder.append(String.format(formatColumWidth, "today")); + } else { + builder.append(String.format(formatColumWidth, def.getLowerAgeLimit())); + } + } else { + builder.append( + String.format( + formatColumWidth, def.getLowerAgeLimit() + ".." + def.getUpperAgeLimit())); + } + } } + builder.append("|\n"); - private String reportToString(WorkbasketReport report) { - return reportToString(report, null); + for (int i = 0; i < reportWidth; i++) { + builder.append("-"); } + builder.append("\n"); - private String reportToString(WorkbasketReport report, - List reportLineItemDefinitions) { - String formatColumWidth = "| %-7s "; - String formatFirstColumn = "| %-36s %-4s "; - String formatFirstColumnFirstLine = "| %-29s %12s "; - String formatFirstColumnSumLine = "| %-36s %-5s"; - int reportWidth = reportLineItemDefinitions == null ? 46 : reportLineItemDefinitions.size() * 10 + 46; - - StringBuilder builder = new StringBuilder(); - builder.append("\n"); - for (int i = 0; i < reportWidth; i++) { - builder.append("-"); + for (String rl : report.rowTitles()) { + builder.append(String.format(formatFirstColumn, rl, report.getRow(rl).getTotalValue())); + if (reportLineItemDefinitions != null) { + for (int cell : report.getRow(rl).getCells()) { + builder.append(String.format(formatColumWidth, cell)); } - builder.append("\n"); - builder.append(String.format(formatFirstColumnFirstLine, "Workbaskets", "Total")); - if (reportLineItemDefinitions != null) { - for (TimeIntervalColumnHeader def : reportLineItemDefinitions) { - if (def.getLowerAgeLimit() == Integer.MIN_VALUE) { - builder.append(String.format(formatColumWidth, "< " + def.getUpperAgeLimit())); - } else if (def.getUpperAgeLimit() == Integer.MAX_VALUE) { - builder.append(String.format(formatColumWidth, "> " + def.getLowerAgeLimit())); - } else if (def.getLowerAgeLimit() == def.getUpperAgeLimit()) { - if (def.getLowerAgeLimit() == 0) { - builder.append(String.format(formatColumWidth, "today")); - } else { - builder.append(String.format(formatColumWidth, def.getLowerAgeLimit())); - } - } else { - builder.append( - String.format(formatColumWidth, def.getLowerAgeLimit() + ".." + def.getUpperAgeLimit())); - } - } - } - builder.append("|\n"); - - for (int i = 0; i < reportWidth; i++) { - builder.append("-"); - } - builder.append("\n"); - - for (String rl : report.rowTitles()) { - builder - .append(String.format(formatFirstColumn, rl, report.getRow(rl).getTotalValue())); - if (reportLineItemDefinitions != null) { - for (int cell : report.getRow(rl).getCells()) { - builder.append(String.format(formatColumWidth, cell)); - } - } - builder.append("|\n"); - for (int i = 0; i < reportWidth; i++) { - builder.append("-"); - } - builder.append("\n"); - } - builder.append(String.format(formatFirstColumnSumLine, "Total", report.getSumRow().getTotalValue())); - for (int cell : report.getSumRow().getCells()) { - builder.append(String.format(formatColumWidth, cell)); - } - builder.append("|\n"); - for (int i = 0; i < reportWidth; i++) { - builder.append("-"); - } - builder.append("\n"); - return builder.toString(); + } + builder.append("|\n"); + for (int i = 0; i < reportWidth; i++) { + builder.append("-"); + } + builder.append("\n"); } - + builder.append( + String.format(formatFirstColumnSumLine, "Total", report.getSumRow().getTotalValue())); + for (int cell : report.getSumRow().getCells()) { + builder.append(String.format(formatColumWidth, cell)); + } + builder.append("|\n"); + for (int i = 0; i < reportWidth; i++) { + builder.append("-"); + } + builder.append("\n"); + return builder.toString(); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/security/ClassificationQueryAccTest.java b/lib/taskana-core/src/test/java/acceptance/security/ClassificationQueryAccTest.java index 458a071ec..7fb636449 100644 --- a/lib/taskana-core/src/test/java/acceptance/security/ClassificationQueryAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/security/ClassificationQueryAccTest.java @@ -3,12 +3,11 @@ package acceptance.security; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import acceptance.AbstractAccTest; import java.util.List; - import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.ClassificationService; import pro.taskana.ClassificationSummary; import pro.taskana.security.JAASExtension; @@ -22,43 +21,39 @@ import pro.taskana.security.WithAccessId; @ExtendWith(JAASExtension.class) class ClassificationQueryAccTest extends AbstractAccTest { - ClassificationQueryAccTest() { - super(); - } + ClassificationQueryAccTest() { + super(); + } - @Test - void testFindClassificationsByDomainUnauthenticated() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List classificationSummaryList = classificationService.createClassificationQuery() - .domainIn("DOMAIN_A") - .list(); + @Test + void testFindClassificationsByDomainUnauthenticated() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List classificationSummaryList = + classificationService.createClassificationQuery().domainIn("DOMAIN_A").list(); - assertNotNull(classificationSummaryList); - assertEquals(17, classificationSummaryList.size()); - } + assertNotNull(classificationSummaryList); + assertEquals(17, classificationSummaryList.size()); + } - @WithAccessId(userName = "businessadmin") - @Test - void testFindClassificationsByDomainBusinessAdmin() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List classificationSummaryList = classificationService.createClassificationQuery() - .domainIn("DOMAIN_A") - .list(); + @WithAccessId(userName = "businessadmin") + @Test + void testFindClassificationsByDomainBusinessAdmin() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List classificationSummaryList = + classificationService.createClassificationQuery().domainIn("DOMAIN_A").list(); - assertNotNull(classificationSummaryList); - assertEquals(17, classificationSummaryList.size()); - } + assertNotNull(classificationSummaryList); + assertEquals(17, classificationSummaryList.size()); + } - @WithAccessId(userName = "admin") - @Test - void testFindClassificationsByDomainAdmin() { - ClassificationService classificationService = taskanaEngine.getClassificationService(); - List classificationSummaryList = classificationService.createClassificationQuery() - .domainIn("DOMAIN_A") - .list(); - - assertNotNull(classificationSummaryList); - assertEquals(17, classificationSummaryList.size()); - } + @WithAccessId(userName = "admin") + @Test + void testFindClassificationsByDomainAdmin() { + ClassificationService classificationService = taskanaEngine.getClassificationService(); + List classificationSummaryList = + classificationService.createClassificationQuery().domainIn("DOMAIN_A").list(); + assertNotNull(classificationSummaryList); + assertEquals(17, classificationSummaryList.size()); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/security/TaskEngineAccTest.java b/lib/taskana-core/src/test/java/acceptance/security/TaskEngineAccTest.java index 0d703f312..dbf1dbd6e 100644 --- a/lib/taskana-core/src/test/java/acceptance/security/TaskEngineAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/security/TaskEngineAccTest.java @@ -3,60 +3,60 @@ package acceptance.security; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import acceptance.AbstractAccTest; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.TaskanaRole; import pro.taskana.exceptions.NotAuthorizedException; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for task queries and authorization. - */ +/** Acceptance test for task queries and authorization. */ @ExtendWith(JAASExtension.class) class TaskEngineAccTest extends AbstractAccTest { - TaskEngineAccTest() { - super(); - } + TaskEngineAccTest() { + super(); + } - @Test - void testUnauthenticated() { - assertFalse(taskanaEngine.isUserInRole(TaskanaRole.BUSINESS_ADMIN)); - assertFalse(taskanaEngine.isUserInRole(TaskanaRole.ADMIN)); - Assertions.assertThrows(NotAuthorizedException.class, () -> - taskanaEngine.checkRoleMembership(TaskanaRole.BUSINESS_ADMIN)); - } + @Test + void testUnauthenticated() { + assertFalse(taskanaEngine.isUserInRole(TaskanaRole.BUSINESS_ADMIN)); + assertFalse(taskanaEngine.isUserInRole(TaskanaRole.ADMIN)); + Assertions.assertThrows( + NotAuthorizedException.class, + () -> taskanaEngine.checkRoleMembership(TaskanaRole.BUSINESS_ADMIN)); + } - @WithAccessId( - userName = "user_1_1") // , groupNames = {"businessadmin"}) - @Test - void testUser() throws NotAuthorizedException { - assertFalse(taskanaEngine.isUserInRole(TaskanaRole.BUSINESS_ADMIN)); - assertFalse(taskanaEngine.isUserInRole(TaskanaRole.ADMIN)); - Assertions.assertThrows(NotAuthorizedException.class, () -> - taskanaEngine.checkRoleMembership(TaskanaRole.BUSINESS_ADMIN)); - } + @WithAccessId(userName = "user_1_1") // , groupNames = {"businessadmin"}) + @Test + void testUser() throws NotAuthorizedException { + assertFalse(taskanaEngine.isUserInRole(TaskanaRole.BUSINESS_ADMIN)); + assertFalse(taskanaEngine.isUserInRole(TaskanaRole.ADMIN)); + Assertions.assertThrows( + NotAuthorizedException.class, + () -> taskanaEngine.checkRoleMembership(TaskanaRole.BUSINESS_ADMIN)); + } - @WithAccessId( - userName = "user_1_1", groupNames = {"businessadmin"}) - @Test - void testBusinessAdmin() throws NotAuthorizedException { - assertTrue(taskanaEngine.isUserInRole(TaskanaRole.BUSINESS_ADMIN)); - assertFalse(taskanaEngine.isUserInRole(TaskanaRole.ADMIN)); - taskanaEngine.checkRoleMembership(TaskanaRole.BUSINESS_ADMIN); - } - - @WithAccessId( - userName = "user_1_1", groupNames = {"admin"}) - @Test - void testAdmin() throws NotAuthorizedException { - assertFalse(taskanaEngine.isUserInRole(TaskanaRole.BUSINESS_ADMIN)); - assertTrue(taskanaEngine.isUserInRole(TaskanaRole.ADMIN)); - taskanaEngine.checkRoleMembership(TaskanaRole.ADMIN); - } + @WithAccessId( + userName = "user_1_1", + groupNames = {"businessadmin"}) + @Test + void testBusinessAdmin() throws NotAuthorizedException { + assertTrue(taskanaEngine.isUserInRole(TaskanaRole.BUSINESS_ADMIN)); + assertFalse(taskanaEngine.isUserInRole(TaskanaRole.ADMIN)); + taskanaEngine.checkRoleMembership(TaskanaRole.BUSINESS_ADMIN); + } + @WithAccessId( + userName = "user_1_1", + groupNames = {"admin"}) + @Test + void testAdmin() throws NotAuthorizedException { + assertFalse(taskanaEngine.isUserInRole(TaskanaRole.BUSINESS_ADMIN)); + assertTrue(taskanaEngine.isUserInRole(TaskanaRole.ADMIN)); + taskanaEngine.checkRoleMembership(TaskanaRole.ADMIN); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/security/TaskQueryAccTest.java b/lib/taskana-core/src/test/java/acceptance/security/TaskQueryAccTest.java index fe920b207..ff9201b45 100644 --- a/lib/taskana-core/src/test/java/acceptance/security/TaskQueryAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/security/TaskQueryAccTest.java @@ -3,79 +3,64 @@ package acceptance.security; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; +import acceptance.AbstractAccTest; import java.util.List; - import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.TaskService; import pro.taskana.TaskSummary; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for task queries and authorization. - */ +/** Acceptance test for task queries and authorization. */ @ExtendWith(JAASExtension.class) class TaskQueryAccTest extends AbstractAccTest { - TaskQueryAccTest() { - super(); - } + TaskQueryAccTest() { + super(); + } - @Test - void testTaskQueryUnauthenticated() { - TaskService taskService = taskanaEngine.getTaskService(); + @Test + void testTaskQueryUnauthenticated() { + TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .ownerLike("%a%", "%u%") - .list(); + List results = taskService.createTaskQuery().ownerLike("%a%", "%u%").list(); - assertThat(results.size(), equalTo(0)); + assertThat(results.size(), equalTo(0)); + } - } + @WithAccessId(userName = "user_1_1") // , groupNames = {"businessadmin"}) + @Test + void testTaskQueryUser_1_1() { + TaskService taskService = taskanaEngine.getTaskService(); - @WithAccessId( - userName = "user_1_1") // , groupNames = {"businessadmin"}) - @Test - void testTaskQueryUser_1_1() { - TaskService taskService = taskanaEngine.getTaskService(); + List results = taskService.createTaskQuery().ownerLike("%a%", "%u%").list(); - List results = taskService.createTaskQuery() - .ownerLike("%a%", "%u%") - .list(); + assertThat(results.size(), equalTo(3)); + } - assertThat(results.size(), equalTo(3)); + @WithAccessId( + userName = "user_1_1", + groupNames = {"businessadmin"}) + @Test + void testTaskQueryUser_1_1BusinessAdm() { + TaskService taskService = taskanaEngine.getTaskService(); - } + List results = taskService.createTaskQuery().ownerLike("%a%", "%u%").list(); - @WithAccessId( - userName = "user_1_1", groupNames = {"businessadmin"}) - @Test - void testTaskQueryUser_1_1BusinessAdm() { - TaskService taskService = taskanaEngine.getTaskService(); + assertThat(results.size(), equalTo(3)); + } - List results = taskService.createTaskQuery() - .ownerLike("%a%", "%u%") - .list(); + @WithAccessId( + userName = "user_1_1", + groupNames = {"admin"}) + @Test + void testTaskQueryUser_1_1Admin() { + TaskService taskService = taskanaEngine.getTaskService(); - assertThat(results.size(), equalTo(3)); - - } - - @WithAccessId( - userName = "user_1_1", groupNames = {"admin"}) - @Test - void testTaskQueryUser_1_1Admin() { - TaskService taskService = taskanaEngine.getTaskService(); - - List results = taskService.createTaskQuery() - .ownerLike("%a%", "%u%") - .list(); - - assertThat(results.size(), equalTo(25)); - - } + List results = taskService.createTaskQuery().ownerLike("%a%", "%u%").list(); + assertThat(results.size(), equalTo(25)); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/security/WorkbasketQueryAccTest.java b/lib/taskana-core/src/test/java/acceptance/security/WorkbasketQueryAccTest.java index 3627f92e4..1c2a0239b 100644 --- a/lib/taskana-core/src/test/java/acceptance/security/WorkbasketQueryAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/security/WorkbasketQueryAccTest.java @@ -2,13 +2,12 @@ package acceptance.security; import static org.junit.jupiter.api.Assertions.assertEquals; +import acceptance.AbstractAccTest; import java.util.List; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.WorkbasketPermission; import pro.taskana.WorkbasketService; import pro.taskana.WorkbasketSummary; @@ -17,83 +16,86 @@ import pro.taskana.exceptions.NotAuthorizedException; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for workbasket queries and authorization. - */ +/** Acceptance test for workbasket queries and authorization. */ @ExtendWith(JAASExtension.class) class WorkbasketQueryAccTest extends AbstractAccTest { - WorkbasketQueryAccTest() { - super(); - } + WorkbasketQueryAccTest() { + super(); + } - @Test - void testQueryWorkbasketByUnauthenticated() throws InvalidArgumentException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .nameLike("%") - .list(); - assertEquals(0L, results.size()); - Assertions.assertThrows(NotAuthorizedException.class, () -> - workbasketService.createWorkbasketQuery() + @Test + void testQueryWorkbasketByUnauthenticated() throws InvalidArgumentException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().nameLike("%").list(); + assertEquals(0L, results.size()); + Assertions.assertThrows( + NotAuthorizedException.class, + () -> + workbasketService + .createWorkbasketQuery() .nameLike("%") - .accessIdsHavePermission(WorkbasketPermission.TRANSFER, "teamlead_1", "group_1", "group_2") + .accessIdsHavePermission( + WorkbasketPermission.TRANSFER, "teamlead_1", "group_1", "group_2") .list()); - } + } - @WithAccessId( - userName = "unknown") - @Test - void testQueryWorkbasketByUnknownUser() throws InvalidArgumentException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .nameLike("%") - .list(); - assertEquals(0L, results.size()); + @WithAccessId(userName = "unknown") + @Test + void testQueryWorkbasketByUnknownUser() throws InvalidArgumentException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().nameLike("%").list(); + assertEquals(0L, results.size()); - Assertions.assertThrows(NotAuthorizedException.class, () -> - workbasketService.createWorkbasketQuery() + Assertions.assertThrows( + NotAuthorizedException.class, + () -> + workbasketService + .createWorkbasketQuery() .nameLike("%") - .accessIdsHavePermission(WorkbasketPermission.TRANSFER, "teamlead_1", "group_1", "group_2") + .accessIdsHavePermission( + WorkbasketPermission.TRANSFER, "teamlead_1", "group_1", "group_2") .list()); - } + } - @WithAccessId( - userName = "unknown", - groupNames = "businessadmin") - @Test - void testQueryWorkbasketByBusinessAdmin() throws NotAuthorizedException, InvalidArgumentException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .nameLike("%") - .list(); - assertEquals(25L, results.size()); + @WithAccessId(userName = "unknown", groupNames = "businessadmin") + @Test + void testQueryWorkbasketByBusinessAdmin() + throws NotAuthorizedException, InvalidArgumentException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().nameLike("%").list(); + assertEquals(25L, results.size()); - results = workbasketService.createWorkbasketQuery() + results = + workbasketService + .createWorkbasketQuery() .nameLike("%") - .accessIdsHavePermission(WorkbasketPermission.TRANSFER, "teamlead_1", "group_1", "group_2") + .accessIdsHavePermission( + WorkbasketPermission.TRANSFER, "teamlead_1", "group_1", "group_2") .list(); - assertEquals(13L, results.size()); + assertEquals(13L, results.size()); + } - } + @WithAccessId(userName = "unknown", groupNames = "admin") + @Test + void testQueryWorkbasketByAdmin() throws NotAuthorizedException, InvalidArgumentException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().nameLike("%").list(); + assertEquals(25L, results.size()); - @WithAccessId( - userName = "unknown", - groupNames = "admin") - @Test - void testQueryWorkbasketByAdmin() throws NotAuthorizedException, InvalidArgumentException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() + results = + workbasketService + .createWorkbasketQuery() .nameLike("%") - .list(); - assertEquals(25L, results.size()); - - results = workbasketService.createWorkbasketQuery() - .nameLike("%") - .accessIdsHavePermission(WorkbasketPermission.TRANSFER, "teamlead_1", "group_1", "group_2") + .accessIdsHavePermission( + WorkbasketPermission.TRANSFER, "teamlead_1", "group_1", "group_2") .list(); - assertEquals(13L, results.size()); - } + assertEquals(13L, results.size()); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/task/CallbackStateAccTest.java b/lib/taskana-core/src/test/java/acceptance/task/CallbackStateAccTest.java index 0e9c2669a..3e2892e3e 100644 --- a/lib/taskana-core/src/test/java/acceptance/task/CallbackStateAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/task/CallbackStateAccTest.java @@ -4,18 +4,17 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import acceptance.AbstractAccTest; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.BulkOperationResults; import pro.taskana.CallbackState; import pro.taskana.Task; @@ -35,340 +34,372 @@ import pro.taskana.impl.TaskImpl; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "create task" scenarios. - */ +/** Acceptance test for all "create task" scenarios. */ @ExtendWith(JAASExtension.class) class CallbackStateAccTest extends AbstractAccTest { - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testCreateTaskWithDifferentCallbackStates() - throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException { + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testCreateTaskWithDifferentCallbackStates() + throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException { - TaskService taskService = taskanaEngine.getTaskService(); - TaskImpl createdTask = createTask(taskService, CallbackState.NONE); - createdTask = (TaskImpl) taskService.getTask(createdTask.getId()); - assertEquals(CallbackState.NONE, createdTask.getCallbackState()); + TaskService taskService = taskanaEngine.getTaskService(); + TaskImpl createdTask = createTask(taskService, CallbackState.NONE); + createdTask = (TaskImpl) taskService.getTask(createdTask.getId()); + assertEquals(CallbackState.NONE, createdTask.getCallbackState()); - createdTask = createTask(taskService, CallbackState.CALLBACK_PROCESSING_REQUIRED); - createdTask = (TaskImpl) taskService.getTask(createdTask.getId()); - assertEquals(CallbackState.CALLBACK_PROCESSING_REQUIRED, createdTask.getCallbackState()); + createdTask = createTask(taskService, CallbackState.CALLBACK_PROCESSING_REQUIRED); + createdTask = (TaskImpl) taskService.getTask(createdTask.getId()); + assertEquals(CallbackState.CALLBACK_PROCESSING_REQUIRED, createdTask.getCallbackState()); - createdTask = createTask(taskService, CallbackState.CALLBACK_PROCESSING_COMPLETED); - createdTask = (TaskImpl) taskService.getTask(createdTask.getId()); - assertEquals(CallbackState.CALLBACK_PROCESSING_COMPLETED, createdTask.getCallbackState()); + createdTask = createTask(taskService, CallbackState.CALLBACK_PROCESSING_COMPLETED); + createdTask = (TaskImpl) taskService.getTask(createdTask.getId()); + assertEquals(CallbackState.CALLBACK_PROCESSING_COMPLETED, createdTask.getCallbackState()); - createdTask = createTask(taskService, CallbackState.CLAIMED); - createdTask = (TaskImpl) taskService.getTask(createdTask.getId()); - assertEquals(CallbackState.CLAIMED, createdTask.getCallbackState()); + createdTask = createTask(taskService, CallbackState.CLAIMED); + createdTask = (TaskImpl) taskService.getTask(createdTask.getId()); + assertEquals(CallbackState.CLAIMED, createdTask.getCallbackState()); + } - } + @WithAccessId( + userName = "admin", + groupNames = {"group_1"}) + @Test + void testDeletionOfTaskWithWrongCallbackStateIsBlocked() + throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException, + InvalidStateException, InvalidOwnerException { + TaskService taskService = taskanaEngine.getTaskService(); - @WithAccessId( - userName = "admin", - groupNames = {"group_1"}) - @Test - void testDeletionOfTaskWithWrongCallbackStateIsBlocked() - throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException, InvalidStateException, - InvalidOwnerException { - TaskService taskService = taskanaEngine.getTaskService(); + final TaskImpl createdTask = + createTask(taskanaEngine.getTaskService(), CallbackState.CALLBACK_PROCESSING_REQUIRED); + assertEquals(CallbackState.CALLBACK_PROCESSING_REQUIRED, createdTask.getCallbackState()); - final TaskImpl createdTask = createTask(taskanaEngine.getTaskService(), - CallbackState.CALLBACK_PROCESSING_REQUIRED); - assertEquals(CallbackState.CALLBACK_PROCESSING_REQUIRED, createdTask.getCallbackState()); + assertEquals(TaskState.READY, createdTask.getState()); + String endOfMessage = " cannot be deleted because its callback is not yet processed"; - assertEquals(TaskState.READY, createdTask.getState()); - String endOfMessage = " cannot be deleted because its callback is not yet processed"; + Throwable t = + Assertions.assertThrows( + InvalidStateException.class, () -> taskService.forceDeleteTask(createdTask.getId())); + assertTrue(t.getMessage().endsWith(endOfMessage)); - Throwable t = Assertions.assertThrows(InvalidStateException.class, - () -> taskService.forceDeleteTask(createdTask.getId())); - assertTrue(t.getMessage().endsWith(endOfMessage)); + final TaskImpl createdTask2 = (TaskImpl) taskService.claim(createdTask.getId()); - final TaskImpl createdTask2 = (TaskImpl) taskService.claim(createdTask.getId()); + assertEquals(TaskState.CLAIMED, createdTask2.getState()); - assertEquals(TaskState.CLAIMED, createdTask2.getState()); + Throwable t2 = + Assertions.assertThrows( + InvalidStateException.class, () -> taskService.forceDeleteTask(createdTask2.getId())); + assertTrue(t2.getMessage().endsWith(endOfMessage)); - Throwable t2 = Assertions.assertThrows(InvalidStateException.class, - () -> taskService.forceDeleteTask(createdTask2.getId())); - assertTrue(t2.getMessage().endsWith(endOfMessage)); + final TaskImpl createdTask3 = (TaskImpl) taskService.completeTask(createdTask.getId()); - final TaskImpl createdTask3 = (TaskImpl) taskService.completeTask(createdTask.getId()); + Throwable t3 = + Assertions.assertThrows( + InvalidStateException.class, () -> taskService.forceDeleteTask(createdTask3.getId())); + assertTrue(t3.getMessage().endsWith(endOfMessage)); + } - Throwable t3 = Assertions.assertThrows(InvalidStateException.class, - () -> taskService.forceDeleteTask(createdTask3.getId())); - assertTrue(t3.getMessage().endsWith(endOfMessage)); - } + @WithAccessId( + userName = "admin", + groupNames = {"group_1"}) + @Test + void testUpdateOfCallbackState() + throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException, + InvalidStateException, InvalidOwnerException { + TaskService taskService = taskanaEngine.getTaskService(); - @WithAccessId( - userName = "admin", - groupNames = {"group_1"}) - @Test - void testUpdateOfCallbackState() - throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException, InvalidStateException, - InvalidOwnerException { - TaskService taskService = taskanaEngine.getTaskService(); + TaskImpl createdTask1 = + createTask(taskanaEngine.getTaskService(), CallbackState.CALLBACK_PROCESSING_REQUIRED); + assertEquals(CallbackState.CALLBACK_PROCESSING_REQUIRED, createdTask1.getCallbackState()); - TaskImpl createdTask1 = createTask(taskanaEngine.getTaskService(), CallbackState.CALLBACK_PROCESSING_REQUIRED); - assertEquals(CallbackState.CALLBACK_PROCESSING_REQUIRED, createdTask1.getCallbackState()); + TaskImpl createdTask2 = + createTask(taskanaEngine.getTaskService(), CallbackState.CALLBACK_PROCESSING_REQUIRED); + assertEquals(CallbackState.CALLBACK_PROCESSING_REQUIRED, createdTask2.getCallbackState()); - TaskImpl createdTask2 = createTask(taskanaEngine.getTaskService(), CallbackState.CALLBACK_PROCESSING_REQUIRED); - assertEquals(CallbackState.CALLBACK_PROCESSING_REQUIRED, createdTask2.getCallbackState()); + TaskImpl createdTask3 = + createTask(taskanaEngine.getTaskService(), CallbackState.CALLBACK_PROCESSING_REQUIRED); + assertEquals(CallbackState.CALLBACK_PROCESSING_REQUIRED, createdTask3.getCallbackState()); - TaskImpl createdTask3 = createTask(taskanaEngine.getTaskService(), CallbackState.CALLBACK_PROCESSING_REQUIRED); - assertEquals(CallbackState.CALLBACK_PROCESSING_REQUIRED, createdTask3.getCallbackState()); + createdTask1 = (TaskImpl) taskService.forceCompleteTask(createdTask1.getId()); + createdTask2 = (TaskImpl) taskService.forceCompleteTask(createdTask2.getId()); + createdTask3 = (TaskImpl) taskService.forceCompleteTask(createdTask3.getId()); - createdTask1 = (TaskImpl) taskService.forceCompleteTask(createdTask1.getId()); - createdTask2 = (TaskImpl) taskService.forceCompleteTask(createdTask2.getId()); - createdTask3 = (TaskImpl) taskService.forceCompleteTask(createdTask3.getId()); + assertEquals(TaskState.COMPLETED, createdTask1.getState()); + assertEquals(TaskState.COMPLETED, createdTask2.getState()); + assertEquals(TaskState.COMPLETED, createdTask3.getState()); - assertEquals(TaskState.COMPLETED, createdTask1.getState()); - assertEquals(TaskState.COMPLETED, createdTask2.getState()); - assertEquals(TaskState.COMPLETED, createdTask3.getState()); - - List taskIds = new ArrayList<>( + List taskIds = + new ArrayList<>( Arrays.asList(createdTask1.getId(), createdTask2.getId(), createdTask3.getId())); - List externalIds = new ArrayList<>( - Arrays.asList(createdTask1.getExternalId(), createdTask2.getExternalId(), createdTask3.getExternalId())); - // delete should fail because callback_state = CALLBACK_PROCESSING_REQUIRED - BulkOperationResults bulkResult1 = taskService.deleteTasks(taskIds); + List externalIds = + new ArrayList<>( + Arrays.asList( + createdTask1.getExternalId(), + createdTask2.getExternalId(), + createdTask3.getExternalId())); + // delete should fail because callback_state = CALLBACK_PROCESSING_REQUIRED + BulkOperationResults bulkResult1 = taskService.deleteTasks(taskIds); - assertTrue(bulkResult1.containsErrors()); - List failedTaskIds = bulkResult1.getFailedIds(); + assertTrue(bulkResult1.containsErrors()); + List failedTaskIds = bulkResult1.getFailedIds(); - assertEquals(3, failedTaskIds.size()); - for (String taskId : failedTaskIds) { - TaskanaException excpt = bulkResult1.getErrorForId(taskId); - assertEquals("pro.taskana.exceptions.InvalidStateException", excpt.getClass().getName()); - } - - // now enable deletion by setting callback state to CALLBACK_PROCESSING_COMPLETED - BulkOperationResults bulkResult2 = taskService.setCallbackStateForTasks(externalIds, - CallbackState.CALLBACK_PROCESSING_COMPLETED); - assertFalse(bulkResult2.containsErrors()); - - taskIds = new ArrayList<>(Arrays.asList(createdTask1.getId(), createdTask2.getId(), createdTask3.getId())); - // now it should be possible to delete the tasks - BulkOperationResults bulkResult3 = taskService.deleteTasks(taskIds); - assertFalse(bulkResult3.containsErrors()); + assertEquals(3, failedTaskIds.size()); + for (String taskId : failedTaskIds) { + TaskanaException excpt = bulkResult1.getErrorForId(taskId); + assertEquals("pro.taskana.exceptions.InvalidStateException", excpt.getClass().getName()); } - @WithAccessId( - userName = "admin", - groupNames = {"group_1"}) - @Test - void testInvalidUpdateOfCallbackStateToNone() - throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - TaskAlreadyExistException, InvalidArgumentException { + // now enable deletion by setting callback state to CALLBACK_PROCESSING_COMPLETED + BulkOperationResults bulkResult2 = + taskService.setCallbackStateForTasks( + externalIds, CallbackState.CALLBACK_PROCESSING_COMPLETED); + assertFalse(bulkResult2.containsErrors()); - TaskService taskService = taskanaEngine.getTaskService(); + taskIds = + new ArrayList<>( + Arrays.asList(createdTask1.getId(), createdTask2.getId(), createdTask3.getId())); + // now it should be possible to delete the tasks + BulkOperationResults bulkResult3 = taskService.deleteTasks(taskIds); + assertFalse(bulkResult3.containsErrors()); + } - TaskImpl createdTask1 = createTask(taskService, CallbackState.CALLBACK_PROCESSING_REQUIRED); - assertEquals(CallbackState.CALLBACK_PROCESSING_REQUIRED, createdTask1.getCallbackState()); + @WithAccessId( + userName = "admin", + groupNames = {"group_1"}) + @Test + void testInvalidUpdateOfCallbackStateToNone() + throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + TaskAlreadyExistException, InvalidArgumentException { - TaskImpl createdTask2 = createTask(taskService, CallbackState.CLAIMED); - assertEquals(CallbackState.CLAIMED, createdTask2.getCallbackState()); + TaskService taskService = taskanaEngine.getTaskService(); - TaskImpl createdTask3 = createTask(taskService, CallbackState.CALLBACK_PROCESSING_COMPLETED); - assertEquals(CallbackState.CALLBACK_PROCESSING_COMPLETED, createdTask3.getCallbackState()); + TaskImpl createdTask1 = createTask(taskService, CallbackState.CALLBACK_PROCESSING_REQUIRED); + assertEquals(CallbackState.CALLBACK_PROCESSING_REQUIRED, createdTask1.getCallbackState()); - List externalIds = new ArrayList<>( - Arrays.asList(createdTask1.getExternalId(), createdTask2.getExternalId(), createdTask3.getExternalId())); + TaskImpl createdTask2 = createTask(taskService, CallbackState.CLAIMED); + assertEquals(CallbackState.CLAIMED, createdTask2.getCallbackState()); - //try to set CallbackState to NONE - BulkOperationResults bulkResult = taskService.setCallbackStateForTasks(externalIds, - CallbackState.NONE); + TaskImpl createdTask3 = createTask(taskService, CallbackState.CALLBACK_PROCESSING_COMPLETED); + assertEquals(CallbackState.CALLBACK_PROCESSING_COMPLETED, createdTask3.getCallbackState()); - //It's never allowed to set CallbackState to NONE over public API - assertTrue(bulkResult.containsErrors()); - List failedTaskIds = bulkResult.getFailedIds(); - assertTrue(failedTaskIds.size() == 3); + List externalIds = + new ArrayList<>( + Arrays.asList( + createdTask1.getExternalId(), + createdTask2.getExternalId(), + createdTask3.getExternalId())); - } + // try to set CallbackState to NONE + BulkOperationResults bulkResult = + taskService.setCallbackStateForTasks(externalIds, CallbackState.NONE); - @WithAccessId( - userName = "admin", - groupNames = {"group_1"}) - @Test - void testInvalidUpdateOfCallbackStateToComplete() - throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - TaskAlreadyExistException, InvalidArgumentException, InvalidOwnerException, InvalidStateException, - TaskNotFoundException { + // It's never allowed to set CallbackState to NONE over public API + assertTrue(bulkResult.containsErrors()); + List failedTaskIds = bulkResult.getFailedIds(); + assertTrue(failedTaskIds.size() == 3); + } - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "admin", + groupNames = {"group_1"}) + @Test + void testInvalidUpdateOfCallbackStateToComplete() + throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + TaskAlreadyExistException, InvalidArgumentException, InvalidOwnerException, + InvalidStateException, TaskNotFoundException { - TaskImpl createdTask1 = createTask(taskService, CallbackState.CALLBACK_PROCESSING_REQUIRED); - assertEquals(CallbackState.CALLBACK_PROCESSING_REQUIRED, createdTask1.getCallbackState()); + TaskService taskService = taskanaEngine.getTaskService(); - TaskImpl createdTask2 = createTask(taskService, CallbackState.CLAIMED); - assertEquals(CallbackState.CLAIMED, createdTask2.getCallbackState()); + TaskImpl createdTask1 = createTask(taskService, CallbackState.CALLBACK_PROCESSING_REQUIRED); + assertEquals(CallbackState.CALLBACK_PROCESSING_REQUIRED, createdTask1.getCallbackState()); - TaskImpl createdTask3 = createTask(taskService, CallbackState.CALLBACK_PROCESSING_COMPLETED); - assertEquals(CallbackState.CALLBACK_PROCESSING_COMPLETED, createdTask3.getCallbackState()); + TaskImpl createdTask2 = createTask(taskService, CallbackState.CLAIMED); + assertEquals(CallbackState.CLAIMED, createdTask2.getCallbackState()); - List externalIds = new ArrayList<>( - Arrays.asList(createdTask1.getExternalId(), createdTask2.getExternalId(), createdTask3.getExternalId())); + TaskImpl createdTask3 = createTask(taskService, CallbackState.CALLBACK_PROCESSING_COMPLETED); + assertEquals(CallbackState.CALLBACK_PROCESSING_COMPLETED, createdTask3.getCallbackState()); - //complete a task - createdTask3 = (TaskImpl) taskService.forceCompleteTask(createdTask3.getId()); + List externalIds = + new ArrayList<>( + Arrays.asList( + createdTask1.getExternalId(), + createdTask2.getExternalId(), + createdTask3.getExternalId())); - //It's only allowed to set CallbackState to COMPLETE, if TaskState equals COMPLETE, therefore 2 tasks should not get updated - BulkOperationResults bulkResult = taskService.setCallbackStateForTasks(externalIds, - CallbackState.CALLBACK_PROCESSING_COMPLETED); - assertTrue(bulkResult.containsErrors()); - List failedTaskIds = bulkResult.getFailedIds(); - assertTrue(failedTaskIds.size() == 2 && !failedTaskIds.contains(createdTask3.getExternalId())); + // complete a task + createdTask3 = (TaskImpl) taskService.forceCompleteTask(createdTask3.getId()); - } + // It's only allowed to set CallbackState to COMPLETE, if TaskState equals COMPLETE, therefore 2 + // tasks should not get updated + BulkOperationResults bulkResult = + taskService.setCallbackStateForTasks( + externalIds, CallbackState.CALLBACK_PROCESSING_COMPLETED); + assertTrue(bulkResult.containsErrors()); + List failedTaskIds = bulkResult.getFailedIds(); + assertTrue(failedTaskIds.size() == 2 && !failedTaskIds.contains(createdTask3.getExternalId())); + } - @WithAccessId( - userName = "admin", - groupNames = {"group_1"}) - @Test - void testInvalidUpdateOfCallbackStateToClaimed() - throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException, InvalidStateException, - InvalidOwnerException { + @WithAccessId( + userName = "admin", + groupNames = {"group_1"}) + @Test + void testInvalidUpdateOfCallbackStateToClaimed() + throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException, + InvalidStateException, InvalidOwnerException { - TaskService taskService = taskanaEngine.getTaskService(); + TaskService taskService = taskanaEngine.getTaskService(); - TaskImpl createdTask1 = createTask(taskService, CallbackState.CALLBACK_PROCESSING_REQUIRED); - assertEquals(CallbackState.CALLBACK_PROCESSING_REQUIRED, createdTask1.getCallbackState()); + TaskImpl createdTask1 = createTask(taskService, CallbackState.CALLBACK_PROCESSING_REQUIRED); + assertEquals(CallbackState.CALLBACK_PROCESSING_REQUIRED, createdTask1.getCallbackState()); - TaskImpl createdTask2 = createTask(taskService, CallbackState.CLAIMED); - assertEquals(CallbackState.CLAIMED, createdTask2.getCallbackState()); + TaskImpl createdTask2 = createTask(taskService, CallbackState.CLAIMED); + assertEquals(CallbackState.CLAIMED, createdTask2.getCallbackState()); - TaskImpl createdTask3 = createTask(taskService, CallbackState.CALLBACK_PROCESSING_COMPLETED); - assertEquals(CallbackState.CALLBACK_PROCESSING_COMPLETED, createdTask3.getCallbackState()); + TaskImpl createdTask3 = createTask(taskService, CallbackState.CALLBACK_PROCESSING_COMPLETED); + assertEquals(CallbackState.CALLBACK_PROCESSING_COMPLETED, createdTask3.getCallbackState()); - List externalIds = new ArrayList<>( - Arrays.asList(createdTask1.getExternalId(), createdTask2.getExternalId(), createdTask3.getExternalId())); + List externalIds = + new ArrayList<>( + Arrays.asList( + createdTask1.getExternalId(), + createdTask2.getExternalId(), + createdTask3.getExternalId())); - //claim two tasks - createdTask1 = (TaskImpl) taskService.forceClaim(createdTask1.getId()); - createdTask2 = (TaskImpl) taskService.forceClaim(createdTask2.getId()); + // claim two tasks + createdTask1 = (TaskImpl) taskService.forceClaim(createdTask1.getId()); + createdTask2 = (TaskImpl) taskService.forceClaim(createdTask2.getId()); - //It's only allowed to claim a task if the TaskState equals CLAIMED and the CallbackState equals REQUIRED - //Therefore 2 tasks should not get updated - BulkOperationResults bulkResult = taskService.setCallbackStateForTasks(externalIds, - CallbackState.CLAIMED); - assertTrue(bulkResult.containsErrors()); - List failedTaskIds = bulkResult.getFailedIds(); - assertTrue(failedTaskIds.size() == 2 && !failedTaskIds.contains(createdTask1.getExternalId())); + // It's only allowed to claim a task if the TaskState equals CLAIMED and the CallbackState + // equals REQUIRED + // Therefore 2 tasks should not get updated + BulkOperationResults bulkResult = + taskService.setCallbackStateForTasks(externalIds, CallbackState.CLAIMED); + assertTrue(bulkResult.containsErrors()); + List failedTaskIds = bulkResult.getFailedIds(); + assertTrue(failedTaskIds.size() == 2 && !failedTaskIds.contains(createdTask1.getExternalId())); + } - } + @WithAccessId( + userName = "admin", + groupNames = {"group_1"}) + @Test + void testInvalidUpdateOfCallbackStateToRequired() + throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + TaskAlreadyExistException, InvalidArgumentException { - @WithAccessId( - userName = "admin", - groupNames = {"group_1"}) - @Test - void testInvalidUpdateOfCallbackStateToRequired() - throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - TaskAlreadyExistException, InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); - TaskService taskService = taskanaEngine.getTaskService(); + TaskImpl createdTask1 = createTask(taskService, CallbackState.CALLBACK_PROCESSING_REQUIRED); + assertEquals(CallbackState.CALLBACK_PROCESSING_REQUIRED, createdTask1.getCallbackState()); - TaskImpl createdTask1 = createTask(taskService, CallbackState.CALLBACK_PROCESSING_REQUIRED); - assertEquals(CallbackState.CALLBACK_PROCESSING_REQUIRED, createdTask1.getCallbackState()); + TaskImpl createdTask2 = createTask(taskService, CallbackState.CLAIMED); + assertEquals(CallbackState.CLAIMED, createdTask2.getCallbackState()); - TaskImpl createdTask2 = createTask(taskService, CallbackState.CLAIMED); - assertEquals(CallbackState.CLAIMED, createdTask2.getCallbackState()); + TaskImpl createdTask3 = createTask(taskService, CallbackState.CALLBACK_PROCESSING_COMPLETED); + assertEquals(CallbackState.CALLBACK_PROCESSING_COMPLETED, createdTask3.getCallbackState()); - TaskImpl createdTask3 = createTask(taskService, CallbackState.CALLBACK_PROCESSING_COMPLETED); - assertEquals(CallbackState.CALLBACK_PROCESSING_COMPLETED, createdTask3.getCallbackState()); + List externalIds = + new ArrayList<>( + Arrays.asList( + createdTask1.getExternalId(), + createdTask2.getExternalId(), + createdTask3.getExternalId())); - List externalIds = new ArrayList<>( - Arrays.asList(createdTask1.getExternalId(), createdTask2.getExternalId(), createdTask3.getExternalId())); - - //It's only allowed to set the CallbackState to REQUIRED if the TaskState doesn't equal COMPLETE - //Therefore 1 task should not get updated - BulkOperationResults bulkResult = taskService.setCallbackStateForTasks(externalIds, - CallbackState.CALLBACK_PROCESSING_REQUIRED); - assertTrue(bulkResult.containsErrors()); - List failedTaskIds = bulkResult.getFailedIds(); - assertTrue(failedTaskIds.size() == 1 && failedTaskIds.contains(createdTask3.getExternalId())); - - } - - @WithAccessId( - userName = "admin", - groupNames = {"group_1"}) - @Test - void testQueriesWithCallbackState() throws Exception { - resetDb(false); - TaskService taskService = taskanaEngine.getTaskService(); - - List claimedTasks = taskService.createTaskQuery() - .stateIn(TaskState.CLAIMED) - .list(); - assertTrue(claimedTasks.size() > 10); - taskService.forceCompleteTask(claimedTasks.get(0).getTaskId()); - taskService.forceCompleteTask(claimedTasks.get(1).getTaskId()); - taskService.forceCompleteTask(claimedTasks.get(2).getTaskId()); - - // now we should have several completed tasks with callback state NONE. - // let's set it to CALLBACK_PROCESSING_REQUIRED - List completedTasks = taskService.createTaskQuery() - .stateIn(TaskState.COMPLETED) - .list(); - long numberOfCompletedTasksAtStartOfTest = completedTasks.size(); - List externalIds = completedTasks.stream().map(TaskSummary::getExternalId).collect(Collectors.toList()); - BulkOperationResults bulkResultCompleted = taskService.setCallbackStateForTasks( + // It's only allowed to set the CallbackState to REQUIRED if the TaskState doesn't equal + // COMPLETE + // Therefore 1 task should not get updated + BulkOperationResults bulkResult = + taskService.setCallbackStateForTasks( externalIds, CallbackState.CALLBACK_PROCESSING_REQUIRED); - assertFalse(bulkResultCompleted.containsErrors()); + assertTrue(bulkResult.containsErrors()); + List failedTaskIds = bulkResult.getFailedIds(); + assertTrue(failedTaskIds.size() == 1 && failedTaskIds.contains(createdTask3.getExternalId())); + } - // now complete some additional tasks - taskService.forceCompleteTask(claimedTasks.get(3).getTaskId()); - taskService.forceCompleteTask(claimedTasks.get(4).getTaskId()); - taskService.forceCompleteTask(claimedTasks.get(5).getTaskId()); + @WithAccessId( + userName = "admin", + groupNames = {"group_1"}) + @Test + void testQueriesWithCallbackState() throws Exception { + resetDb(false); + TaskService taskService = taskanaEngine.getTaskService(); - // now lets retrieve those completed tasks that have callback_processing_required - List tasksToBeActedUpon = taskService.createTaskQuery() + List claimedTasks = + taskService.createTaskQuery().stateIn(TaskState.CLAIMED).list(); + assertTrue(claimedTasks.size() > 10); + taskService.forceCompleteTask(claimedTasks.get(0).getTaskId()); + taskService.forceCompleteTask(claimedTasks.get(1).getTaskId()); + taskService.forceCompleteTask(claimedTasks.get(2).getTaskId()); + + // now we should have several completed tasks with callback state NONE. + // let's set it to CALLBACK_PROCESSING_REQUIRED + List completedTasks = + taskService.createTaskQuery().stateIn(TaskState.COMPLETED).list(); + long numberOfCompletedTasksAtStartOfTest = completedTasks.size(); + List externalIds = + completedTasks.stream().map(TaskSummary::getExternalId).collect(Collectors.toList()); + BulkOperationResults bulkResultCompleted = + taskService.setCallbackStateForTasks( + externalIds, CallbackState.CALLBACK_PROCESSING_REQUIRED); + assertFalse(bulkResultCompleted.containsErrors()); + + // now complete some additional tasks + taskService.forceCompleteTask(claimedTasks.get(3).getTaskId()); + taskService.forceCompleteTask(claimedTasks.get(4).getTaskId()); + taskService.forceCompleteTask(claimedTasks.get(5).getTaskId()); + + // now lets retrieve those completed tasks that have callback_processing_required + List tasksToBeActedUpon = + taskService + .createTaskQuery() .stateIn(TaskState.COMPLETED) .callbackStateIn(CallbackState.CALLBACK_PROCESSING_REQUIRED) .list(); - assertEquals(tasksToBeActedUpon.size(), numberOfCompletedTasksAtStartOfTest); - // now we set callback state to callback_processing_completed - externalIds = tasksToBeActedUpon.stream().map(TaskSummary::getExternalId).collect(Collectors.toList()); - BulkOperationResults bulkResult = taskService.setCallbackStateForTasks(externalIds, - CallbackState.CALLBACK_PROCESSING_COMPLETED); - assertFalse(bulkResult.containsErrors()); + assertEquals(tasksToBeActedUpon.size(), numberOfCompletedTasksAtStartOfTest); + // now we set callback state to callback_processing_completed + externalIds = + tasksToBeActedUpon.stream().map(TaskSummary::getExternalId).collect(Collectors.toList()); + BulkOperationResults bulkResult = + taskService.setCallbackStateForTasks( + externalIds, CallbackState.CALLBACK_PROCESSING_COMPLETED); + assertFalse(bulkResult.containsErrors()); - long numOfTasksRemaining = taskService.createTaskQuery() + long numOfTasksRemaining = + taskService + .createTaskQuery() .stateIn(TaskState.COMPLETED) .callbackStateIn(CallbackState.CALLBACK_PROCESSING_REQUIRED) .count(); - assertEquals(0, numOfTasksRemaining); + assertEquals(0, numOfTasksRemaining); + } + private TaskImpl createTask(TaskService taskService, CallbackState callbackState) + throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + TaskAlreadyExistException, InvalidArgumentException { + Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); + newTask.setClassificationKey("L12010"); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + newTask.setClassificationKey("L12010"); + HashMap callbackInfo = new HashMap<>(); + callbackInfo.put(Task.CALLBACK_STATE, callbackState.name()); + newTask.setCallbackInfo(callbackInfo); + augmentCallbackInfo(newTask); + + return (TaskImpl) taskService.createTask(newTask); + } + + private void augmentCallbackInfo(Task task) { + Map callbackInfo = task.getCallbackInfo(); + for (int i = 1; i <= 10; i++) { + callbackInfo.put("info_" + i, "Value of info_" + i); } - - private TaskImpl createTask(TaskService taskService, CallbackState callbackState) - throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - TaskAlreadyExistException, InvalidArgumentException { - Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); - newTask.setClassificationKey("L12010"); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - newTask.setClassificationKey("L12010"); - HashMap callbackInfo = new HashMap<>(); - callbackInfo.put(Task.CALLBACK_STATE, callbackState.name()); - newTask.setCallbackInfo(callbackInfo); - augmentCallbackInfo(newTask); - - return (TaskImpl) taskService.createTask(newTask); - } - - private void augmentCallbackInfo(Task task) { - Map callbackInfo = task.getCallbackInfo(); - for (int i = 1; i <= 10; i++) { - callbackInfo.put("info_" + i, "Value of info_" + i); - } - task.setCallbackInfo(callbackInfo); - - } - + task.setCallbackInfo(callbackInfo); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/task/CompleteTaskAccTest.java b/lib/taskana-core/src/test/java/acceptance/task/CompleteTaskAccTest.java index 4be31cb24..99f076048 100644 --- a/lib/taskana-core/src/test/java/acceptance/task/CompleteTaskAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/task/CompleteTaskAccTest.java @@ -6,13 +6,12 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import acceptance.AbstractAccTest; import java.time.Instant; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.Task; import pro.taskana.TaskService; import pro.taskana.TaskState; @@ -29,287 +28,300 @@ import pro.taskana.security.CurrentUserContext; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance tests for all claim and complete scenarios. - */ - +/** Acceptance tests for all claim and complete scenarios. */ @ExtendWith(JAASExtension.class) class CompleteTaskAccTest extends AbstractAccTest { - CompleteTaskAccTest() { - super(); - } + CompleteTaskAccTest() { + super(); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testCompleteTask() - throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, NotAuthorizedException { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testCompleteTask() + throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, + NotAuthorizedException { + TaskService taskService = taskanaEngine.getTaskService(); - assertEquals(TaskState.CLAIMED, - taskService.getTask("TKI:000000000000000000000000000000000001").getState()); + assertEquals( + TaskState.CLAIMED, + taskService.getTask("TKI:000000000000000000000000000000000001").getState()); - Task completedTask = taskService.completeTask("TKI:000000000000000000000000000000000001"); - assertNotNull(completedTask); - assertNotNull(completedTask.getCompleted()); - assertEquals(TaskState.COMPLETED, completedTask.getState()); - assertNotEquals(completedTask.getCreated(), completedTask.getModified()); - } + Task completedTask = taskService.completeTask("TKI:000000000000000000000000000000000001"); + assertNotNull(completedTask); + assertNotNull(completedTask.getCompleted()); + assertEquals(TaskState.COMPLETED, completedTask.getState()); + assertNotEquals(completedTask.getCreated(), completedTask.getModified()); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testCompleteTaskTwice() - throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, NotAuthorizedException { - TaskService taskService = taskanaEngine.getTaskService(); - Task completedTask = taskService.completeTask("TKI:000000000000000000000000000000000002"); - Task completedTask2 = taskService.completeTask("TKI:000000000000000000000000000000000002"); - assertEquals(completedTask, completedTask2); - } + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testCompleteTaskTwice() + throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, + NotAuthorizedException { + TaskService taskService = taskanaEngine.getTaskService(); + Task completedTask = taskService.completeTask("TKI:000000000000000000000000000000000002"); + Task completedTask2 = taskService.completeTask("TKI:000000000000000000000000000000000002"); + assertEquals(completedTask, completedTask2); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testForceCompleteAlreadyClaimed() - throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException, - InvalidOwnerException, InvalidStateException { + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testForceCompleteAlreadyClaimed() + throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException, + InvalidOwnerException, InvalidStateException { - TaskService taskService = taskanaEngine.getTaskService(); - Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); - newTask.setClassificationKey("T2100"); - newTask.setOwner("other"); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - TaskImpl newTaskImpl = (TaskImpl) newTask; - newTaskImpl.setState(TaskState.CLAIMED); - newTaskImpl.setClaimed(Instant.now()); + TaskService taskService = taskanaEngine.getTaskService(); + Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); + newTask.setClassificationKey("T2100"); + newTask.setOwner("other"); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + TaskImpl newTaskImpl = (TaskImpl) newTask; + newTaskImpl.setState(TaskState.CLAIMED); + newTaskImpl.setClaimed(Instant.now()); - Task createdTask = taskService.createTask(newTaskImpl); - Task completedTask = taskService.forceCompleteTask(createdTask.getId()); + Task createdTask = taskService.createTask(newTaskImpl); + Task completedTask = taskService.forceCompleteTask(createdTask.getId()); - assertEquals(TaskState.COMPLETED, completedTask.getState()); - assertNotNull(completedTask.getCompleted()); - assertTrue(isBeforeOrEqual(completedTask.getCreated(), completedTask.getModified())); - assertEquals(completedTask.getModified(), completedTask.getCompleted()); - } + assertEquals(TaskState.COMPLETED, completedTask.getState()); + assertNotNull(completedTask.getCompleted()); + assertTrue(isBeforeOrEqual(completedTask.getCreated(), completedTask.getModified())); + assertEquals(completedTask.getModified(), completedTask.getCompleted()); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testForceCompleteNotClaimed() - throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException, - InvalidOwnerException, InvalidStateException { + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testForceCompleteNotClaimed() + throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException, + InvalidOwnerException, InvalidStateException { - TaskService taskService = taskanaEngine.getTaskService(); - Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); - newTask.setClassificationKey("T2100"); - newTask.setOwner("other"); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - TaskImpl newTaskImpl = (TaskImpl) newTask; - newTaskImpl.setClaimed(Instant.now()); + TaskService taskService = taskanaEngine.getTaskService(); + Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); + newTask.setClassificationKey("T2100"); + newTask.setOwner("other"); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + TaskImpl newTaskImpl = (TaskImpl) newTask; + newTaskImpl.setClaimed(Instant.now()); - Task createdTask = taskService.createTask(newTaskImpl); - Task completedTask = taskService.forceCompleteTask(createdTask.getId()); + Task createdTask = taskService.createTask(newTaskImpl); + Task completedTask = taskService.forceCompleteTask(createdTask.getId()); - assertEquals(TaskState.COMPLETED, completedTask.getState()); - assertNotNull(completedTask.getCompleted()); - assertTrue(isBeforeOrEqual(completedTask.getCreated(), completedTask.getModified())); - assertEquals(completedTask.getModified(), completedTask.getCompleted()); - } + assertEquals(TaskState.COMPLETED, completedTask.getState()); + assertNotNull(completedTask.getCompleted()); + assertTrue(isBeforeOrEqual(completedTask.getCreated(), completedTask.getModified())); + assertEquals(completedTask.getModified(), completedTask.getCompleted()); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testCompleteTaskThrowsErrors() { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testCompleteTaskThrowsErrors() { + TaskService taskService = taskanaEngine.getTaskService(); - Assertions.assertThrows(TaskNotFoundException.class, () -> - taskService.completeTask("TKI:0000000000000000000000000000000000xx")); + Assertions.assertThrows( + TaskNotFoundException.class, + () -> taskService.completeTask("TKI:0000000000000000000000000000000000xx")); - Assertions.assertThrows(NotAuthorizedException.class, () -> - taskService.completeTask("TKI:000000000000000000000000000000000004")); + Assertions.assertThrows( + NotAuthorizedException.class, + () -> taskService.completeTask("TKI:000000000000000000000000000000000004")); - Assertions.assertThrows(InvalidStateException.class, () -> - taskService.completeTask("TKI:000000000000000000000000000000000025")); + Assertions.assertThrows( + InvalidStateException.class, + () -> taskService.completeTask("TKI:000000000000000000000000000000000025")); - Assertions.assertThrows(InvalidOwnerException.class, () -> - taskService.completeTask("TKI:000000000000000000000000000000000027")); - } + Assertions.assertThrows( + InvalidOwnerException.class, + () -> taskService.completeTask("TKI:000000000000000000000000000000000027")); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testClaimTaskWithDefaultFlag() - throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException, InvalidStateException, - InvalidOwnerException { + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testClaimTaskWithDefaultFlag() + throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException, + InvalidStateException, InvalidOwnerException { - TaskService taskService = taskanaEngine.getTaskService(); - Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); - newTask.setClassificationKey("T2100"); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - newTask.setOwner(null); - Task createdTask = taskService.createTask(newTask); + TaskService taskService = taskanaEngine.getTaskService(); + Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); + newTask.setClassificationKey("T2100"); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + newTask.setOwner(null); + Task createdTask = taskService.createTask(newTask); - assertNotNull(createdTask); - assertNull(createdTask.getClaimed()); + assertNotNull(createdTask); + assertNull(createdTask.getClaimed()); - Instant before = createdTask.getCreated(); - Task claimedTask = taskService.claim(createdTask.getId()); + Instant before = createdTask.getCreated(); + Task claimedTask = taskService.claim(createdTask.getId()); - assertNotNull(claimedTask.getOwner()); - assertEquals(claimedTask.getOwner(), CurrentUserContext.getUserid()); - assertNotNull(claimedTask.getClaimed()); - assertTrue(isBeforeOrEqual(before, claimedTask.getClaimed())); - assertTrue(isBeforeOrEqual(claimedTask.getCreated(), claimedTask.getClaimed())); - assertTrue(isBeforeOrEqual(claimedTask.getClaimed(), Instant.now())); - assertEquals(claimedTask.getClaimed(), claimedTask.getModified()); - } + assertNotNull(claimedTask.getOwner()); + assertEquals(claimedTask.getOwner(), CurrentUserContext.getUserid()); + assertNotNull(claimedTask.getClaimed()); + assertTrue(isBeforeOrEqual(before, claimedTask.getClaimed())); + assertTrue(isBeforeOrEqual(claimedTask.getCreated(), claimedTask.getClaimed())); + assertTrue(isBeforeOrEqual(claimedTask.getClaimed(), Instant.now())); + assertEquals(claimedTask.getClaimed(), claimedTask.getModified()); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testForceClaimTaskFromOtherUser() - throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException, - InvalidStateException, InvalidOwnerException { + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testForceClaimTaskFromOtherUser() + throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException, + InvalidStateException, InvalidOwnerException { - TaskService taskService = taskanaEngine.getTaskService(); - Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); - newTask.setClassificationKey("T2100"); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - newTask.setOwner("other_user"); - Task createdTask = taskService.createTask(newTask); + TaskService taskService = taskanaEngine.getTaskService(); + Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); + newTask.setClassificationKey("T2100"); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + newTask.setOwner("other_user"); + Task createdTask = taskService.createTask(newTask); - assertNotNull(createdTask); - assertEquals(createdTask.getOwner(), "other_user"); + assertNotNull(createdTask); + assertEquals(createdTask.getOwner(), "other_user"); - Instant beforeForceClaim = Instant.now(); - Task taskAfterClaim = taskService.forceClaim(createdTask.getId()); + Instant beforeForceClaim = Instant.now(); + Task taskAfterClaim = taskService.forceClaim(createdTask.getId()); - assertEquals(CurrentUserContext.getUserid(), taskAfterClaim.getOwner()); - assertTrue(isBeforeOrEqual(beforeForceClaim, taskAfterClaim.getModified())); - assertTrue(isBeforeOrEqual(beforeForceClaim, taskAfterClaim.getClaimed())); - assertTrue(isBeforeOrEqual(taskAfterClaim.getCreated(), taskAfterClaim.getModified())); + assertEquals(CurrentUserContext.getUserid(), taskAfterClaim.getOwner()); + assertTrue(isBeforeOrEqual(beforeForceClaim, taskAfterClaim.getModified())); + assertTrue(isBeforeOrEqual(beforeForceClaim, taskAfterClaim.getClaimed())); + assertTrue(isBeforeOrEqual(taskAfterClaim.getCreated(), taskAfterClaim.getModified())); - assertEquals(TaskState.CLAIMED, taskAfterClaim.getState()); - assertTrue(taskAfterClaim.isRead()); - } + assertEquals(TaskState.CLAIMED, taskAfterClaim.getState()); + assertTrue(taskAfterClaim.isRead()); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testClaimTaskNotExisting() { + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testClaimTaskNotExisting() { - TaskService taskService = taskanaEngine.getTaskService(); - Assertions.assertThrows(TaskNotFoundException.class, () -> taskService.claim("NOT_EXISTING")); - } + TaskService taskService = taskanaEngine.getTaskService(); + Assertions.assertThrows(TaskNotFoundException.class, () -> taskService.claim("NOT_EXISTING")); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testClaimTaskWithInvalidState() { + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testClaimTaskWithInvalidState() { - TaskService taskService = taskanaEngine.getTaskService(); - Assertions.assertThrows(InvalidStateException.class, () -> - taskService.forceClaim("TKI:000000000000000000000000000000000036")); - } + TaskService taskService = taskanaEngine.getTaskService(); + Assertions.assertThrows( + InvalidStateException.class, + () -> taskService.forceClaim("TKI:000000000000000000000000000000000036")); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testClaimTaskWithInvalidOwner() { + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testClaimTaskWithInvalidOwner() { - TaskService taskService = taskanaEngine.getTaskService(); - Assertions.assertThrows(InvalidOwnerException.class, () -> - taskService.claim("TKI:000000000000000000000000000000000100")); - } + TaskService taskService = taskanaEngine.getTaskService(); + Assertions.assertThrows( + InvalidOwnerException.class, + () -> taskService.claim("TKI:000000000000000000000000000000000100")); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testCancelClaimForcedWithInvalidState() { + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testCancelClaimForcedWithInvalidState() { - TaskService taskService = taskanaEngine.getTaskService(); - Assertions.assertThrows(InvalidStateException.class, () -> - taskService.forceCancelClaim("TKI:000000000000000000000000000000000036")); - } + TaskService taskService = taskanaEngine.getTaskService(); + Assertions.assertThrows( + InvalidStateException.class, + () -> taskService.forceCancelClaim("TKI:000000000000000000000000000000000036")); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testCancelClaimDefaultFlag() - throws NotAuthorizedException, WorkbasketNotFoundException, ClassificationNotFoundException, - TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException, - InvalidStateException, InvalidOwnerException { + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testCancelClaimDefaultFlag() + throws NotAuthorizedException, WorkbasketNotFoundException, ClassificationNotFoundException, + TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException, + InvalidStateException, InvalidOwnerException { - TaskService taskService = taskanaEngine.getTaskService(); - Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); - newTask.setClassificationKey("T2100"); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - Task createdTask = taskService.createTask(newTask); + TaskService taskService = taskanaEngine.getTaskService(); + Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); + newTask.setClassificationKey("T2100"); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + Task createdTask = taskService.createTask(newTask); - assertNotNull(createdTask); - assertEquals(createdTask.getState(), TaskState.READY); + assertNotNull(createdTask); + assertEquals(createdTask.getState(), TaskState.READY); - createdTask = taskService.cancelClaim(createdTask.getId()); + createdTask = taskService.cancelClaim(createdTask.getId()); - assertNotNull(createdTask); - assertEquals(createdTask.getState(), TaskState.READY); - } + assertNotNull(createdTask); + assertEquals(createdTask.getState(), TaskState.READY); + } - @WithAccessId( - userName = "admin", - groupNames = {"admin"}) - @Test - void testForceCancelClaimSuccessfull() - throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, - NotAuthorizedException, InterruptedException { + @WithAccessId( + userName = "admin", + groupNames = {"admin"}) + @Test + void testForceCancelClaimSuccessfull() + throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, + NotAuthorizedException, InterruptedException { - TaskService taskService = taskanaEngine.getTaskService(); - Task taskBefore = taskService.getTask("TKI:000000000000000000000000000000000043"); + TaskService taskService = taskanaEngine.getTaskService(); + Task taskBefore = taskService.getTask("TKI:000000000000000000000000000000000043"); - assertNotNull(taskBefore); - assertEquals(TaskState.CLAIMED, taskBefore.getState()); + assertNotNull(taskBefore); + assertEquals(TaskState.CLAIMED, taskBefore.getState()); - Instant before = Instant.now(); - Thread.sleep(1); - Task taskAfter = taskService.forceCancelClaim("TKI:000000000000000000000000000000000043"); + Instant before = Instant.now(); + Thread.sleep(1); + Task taskAfter = taskService.forceCancelClaim("TKI:000000000000000000000000000000000043"); - assertNotNull(taskAfter); - assertEquals(TaskState.READY, taskAfter.getState()); - assertNull(taskAfter.getClaimed()); - assertTrue(taskAfter.getModified().isAfter(before)); - assertNull(taskAfter.getOwner()); - assertTrue(taskAfter.isRead()); - } + assertNotNull(taskAfter); + assertEquals(TaskState.READY, taskAfter.getState()); + assertNull(taskAfter.getClaimed()); + assertTrue(taskAfter.getModified().isAfter(before)); + assertNull(taskAfter.getOwner()); + assertTrue(taskAfter.isRead()); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testCancelClaimWithInvalidOwner() { + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testCancelClaimWithInvalidOwner() { - TaskService taskService = taskanaEngine.getTaskService(); - Assertions.assertThrows(InvalidOwnerException.class, () -> - taskService.cancelClaim("TKI:000000000000000000000000000000000100")); - } + TaskService taskService = taskanaEngine.getTaskService(); + Assertions.assertThrows( + InvalidOwnerException.class, + () -> taskService.cancelClaim("TKI:000000000000000000000000000000000100")); + } - private boolean isBeforeOrEqual(Instant before, Instant after) { - return before.isBefore(after) || before.equals(after); - } + private boolean isBeforeOrEqual(Instant before, Instant after) { + return before.isBefore(after) || before.equals(after); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/task/CreateTaskAccTest.java b/lib/taskana-core/src/test/java/acceptance/task/CreateTaskAccTest.java index 5620dcf06..5910f0313 100644 --- a/lib/taskana-core/src/test/java/acceptance/task/CreateTaskAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/task/CreateTaskAccTest.java @@ -8,6 +8,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import acceptance.AbstractAccTest; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; @@ -15,7 +16,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; - import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSession; import org.junit.jupiter.api.Assertions; @@ -23,7 +23,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.Attachment; import pro.taskana.Classification; import pro.taskana.ClassificationService; @@ -48,722 +47,834 @@ import pro.taskana.security.CurrentUserContext; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "create task" scenarios. - */ +/** Acceptance test for all "create task" scenarios. */ @ExtendWith(JAASExtension.class) class CreateTaskAccTest extends AbstractAccTest { - private TaskService taskService; - private ClassificationService classificationService; + private TaskService taskService; + private ClassificationService classificationService; - @BeforeEach - void setup() { - taskService = taskanaEngine.getTaskService(); - classificationService = taskanaEngine.getClassificationService(); + @BeforeEach + void setup() { + taskService = taskanaEngine.getTaskService(); + classificationService = taskanaEngine.getClassificationService(); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testCreateSimpleManualTask() + throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, + WorkbasketNotFoundException, TaskAlreadyExistException { + + Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); + newTask.setClassificationKey("T2100"); + ObjectReference objectReference = + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567"); + newTask.setPrimaryObjRef(objectReference); + newTask.setOwner("user_1_1"); + Task createdTask = taskService.createTask(newTask); + + assertNotNull(createdTask); + assertThat(createdTask.getCreator(), equalTo(CurrentUserContext.getUserid())); + assertThat(createdTask.getOwner(), equalTo("user_1_1")); + assertEquals("USER_1_1", createdTask.getWorkbasketKey()); + assertEquals("T-Vertragstermin VERA", createdTask.getName()); + assertEquals(objectReference, createdTask.getPrimaryObjRef()); + assertNotNull(createdTask.getCreated()); + assertNotNull(createdTask.getModified()); + assertNotNull(createdTask.getBusinessProcessId()); + assertNull(createdTask.getClaimed()); + assertNull(createdTask.getCompleted()); + assertEquals(createdTask.getCreated(), createdTask.getModified()); + assertEquals(createdTask.getCreated(), createdTask.getPlanned()); + assertEquals(TaskState.READY, createdTask.getState()); + assertNull(createdTask.getParentBusinessProcessId()); + assertEquals(2, createdTask.getPriority()); + assertFalse(createdTask.isRead()); + assertFalse(createdTask.isTransferred()); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testCreateTaskWithPlanned() + throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, + WorkbasketNotFoundException, TaskAlreadyExistException { + + Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); + Instant instantPlanned = Instant.now().plus(2, ChronoUnit.HOURS); + newTask.setClassificationKey("T2100"); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + newTask.setOwner("user_1_1"); + newTask.setPlanned(instantPlanned); + Task createdTask = taskService.createTask(newTask); + + assertNotNull(createdTask); + assertNotNull(createdTask.getCreated()); + assertNotNull(createdTask.getPlanned()); + assertEquals(instantPlanned, createdTask.getPlanned()); + assertTrue(createdTask.getCreated().isBefore(createdTask.getPlanned())); + + // verify that planned takes place 2 hours after creation (+- 5 seconds) + Instant plannedAdjusted = createdTask.getPlanned().minus(2, ChronoUnit.HOURS); + long difference = + Duration.between(createdTask.getCreated(), plannedAdjusted).abs().getSeconds(); + // add some tolerance to ignore that "created" depends on execution speed + long tolerance = 5; + assertTrue(Math.abs(difference) < tolerance); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testCreateTaskWithInvalidPlannedAndDue() { + + Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); + Instant instantPlanned = Instant.now().plus(2, ChronoUnit.HOURS); + newTask.setClassificationKey("T2100"); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + newTask.setOwner("user_1_1"); + + newTask.setPlanned(instantPlanned); + newTask.setDue(instantPlanned); // due date not according to service level + Assertions.assertThrows(InvalidArgumentException.class, () -> taskService.createTask(newTask)); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testCreateTaskWithValidPlannedAndDue() + throws ClassificationNotFoundException, InvalidArgumentException { + + Classification classification = classificationService.getClassification("T2100", "DOMAIN_A"); + long serviceLevelDays = Duration.parse(classification.getServiceLevel()).toDays(); + + Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); + Instant instantPlanned = Instant.now(); + newTask.setClassificationKey(classification.getKey()); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + newTask.setOwner("user_1_1"); + + DaysToWorkingDaysConverter converter = DaysToWorkingDaysConverter.initialize(); + // TODO: this is a temporal bug fix because we did not define what happens when a task is + // planned on the weekend. + long i = converter.convertWorkingDaysToDays(instantPlanned, 0); + newTask.setPlanned(instantPlanned.plus(Duration.ofDays(i))); + // due date according to service level + long calendarDays = converter.convertWorkingDaysToDays(newTask.getPlanned(), serviceLevelDays); + Instant shouldBeDueDate = newTask.getPlanned().plus(Duration.ofDays(calendarDays)); + + newTask.setDue(shouldBeDueDate); + Assertions.assertDoesNotThrow(() -> taskService.createTask(newTask)); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testIdempotencyOfTaskCreation() + throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, + WorkbasketNotFoundException, TaskAlreadyExistException { + + Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); + newTask.setExternalId("MyExternalId"); + newTask.setClassificationKey("T2100"); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + Task createdTask = taskService.createTask(newTask); + + assertNotNull(createdTask); + assertThat(createdTask.getCreator(), equalTo(CurrentUserContext.getUserid())); + assertEquals("T-Vertragstermin VERA", createdTask.getName()); + assertEquals("1234567", createdTask.getPrimaryObjRef().getValue()); + assertNotNull(createdTask.getExternalId()); + assertNotNull(createdTask.getCreated()); + assertNotNull(createdTask.getModified()); + assertNotNull(createdTask.getBusinessProcessId()); + assertNull(createdTask.getClaimed()); + assertNull(createdTask.getCompleted()); + assertEquals(createdTask.getCreated(), createdTask.getModified()); + assertEquals(createdTask.getCreated(), createdTask.getPlanned()); + assertEquals(TaskState.READY, createdTask.getState()); + assertNull(createdTask.getParentBusinessProcessId()); + assertEquals(2, createdTask.getPriority()); + assertFalse(createdTask.isRead()); + assertFalse(createdTask.isTransferred()); + + Task newTask2 = taskService.newTask("USER_1_1", "DOMAIN_A"); + newTask2.setExternalId("MyExternalId"); + newTask2.setClassificationKey("T2100"); + newTask2.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + + Assertions.assertThrows( + TaskAlreadyExistException.class, () -> taskService.createTask(newTask2)); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testCreateSimpleTaskWithCustomAttributes() + throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, + WorkbasketNotFoundException, TaskAlreadyExistException, TaskNotFoundException, + NoSuchFieldException, IllegalAccessException { + + Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); + newTask.setClassificationKey("T2100"); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + Map customAttributesForCreate = createSimpleCustomProperties(13); + newTask.setCustomAttributes(customAttributesForCreate); + Task createdTask = taskService.createTask(newTask); + + assertNotNull(createdTask); + assertEquals("T-Vertragstermin VERA", createdTask.getName()); + assertEquals("1234567", createdTask.getPrimaryObjRef().getValue()); + assertNotNull(createdTask.getCreated()); + assertNotNull(createdTask.getModified()); + assertNotNull(createdTask.getBusinessProcessId()); + assertNull(createdTask.getClaimed()); + assertNull(createdTask.getCompleted()); + assertEquals(createdTask.getCreated(), createdTask.getModified()); + assertEquals(createdTask.getCreated(), createdTask.getPlanned()); + assertEquals(TaskState.READY, createdTask.getState()); + assertNull(createdTask.getParentBusinessProcessId()); + assertEquals(2, createdTask.getPriority()); + assertFalse(createdTask.isRead()); + assertFalse(createdTask.isTransferred()); + // verify that the database content is as expected + TaskanaEngineProxyForTest engineProxy = new TaskanaEngineProxyForTest(taskanaEngine); + try { + SqlSession session = engineProxy.getSqlSession(); + Configuration config = session.getConfiguration(); + if (!config.hasMapper(TaskTestMapper.class)) { + config.addMapper(TaskTestMapper.class); + } + TaskTestMapper mapper = session.getMapper(TaskTestMapper.class); + + engineProxy.openConnection(); + String customProperties = mapper.getCustomAttributesAsString(createdTask.getId()); + assertTrue(customProperties.contains("\"Property_13\":\"Property Value of Property_13\"")); + assertTrue(customProperties.contains("\"Property_12\":\"Property Value of Property_12\"")); + assertTrue(customProperties.contains("\"Property_11\":\"Property Value of Property_11\"")); + assertTrue(customProperties.contains("\"Property_10\":\"Property Value of Property_10\"")); + assertTrue(customProperties.contains("\"Property_9\":\"Property Value of Property_9\"")); + assertTrue(customProperties.contains("\"Property_8\":\"Property Value of Property_8\"")); + assertTrue(customProperties.contains("\"Property_7\":\"Property Value of Property_7\"")); + assertTrue(customProperties.contains("\"Property_6\":\"Property Value of Property_6\"")); + assertTrue(customProperties.contains("\"Property_5\":\"Property Value of Property_5\"")); + assertTrue(customProperties.contains("\"Property_4\":\"Property Value of Property_4\"")); + assertTrue(customProperties.contains("\"Property_3\":\"Property Value of Property_3\"")); + assertTrue(customProperties.contains("\"Property_2\":\"Property Value of Property_2\"")); + assertTrue(customProperties.contains("\"Property_1\":\"Property Value of Property_1\"")); + } finally { + engineProxy.returnConnection(); } + // verify that the map is correctly retrieved from the database + Task retrievedTask = taskService.getTask(createdTask.getId()); + Map customAttributesFromDb = retrievedTask.getCustomAttributes(); + assertNotNull(customAttributesFromDb); + assertEquals(customAttributesFromDb, customAttributesForCreate); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testCreateSimpleManualTask() - throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, - WorkbasketNotFoundException, TaskAlreadyExistException { + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testCreateExternalTaskWithAttachment() + throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, + WorkbasketNotFoundException, TaskAlreadyExistException, TaskNotFoundException, + NoSuchFieldException, IllegalAccessException { - Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); - newTask.setClassificationKey("T2100"); - ObjectReference objectReference = createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", - "1234567"); - newTask.setPrimaryObjRef(objectReference); - newTask.setOwner("user_1_1"); - Task createdTask = taskService.createTask(newTask); - - assertNotNull(createdTask); - assertThat(createdTask.getCreator(), equalTo(CurrentUserContext.getUserid())); - assertThat(createdTask.getOwner(), equalTo("user_1_1")); - assertEquals("USER_1_1", createdTask.getWorkbasketKey()); - assertEquals("T-Vertragstermin VERA", createdTask.getName()); - assertEquals(objectReference, createdTask.getPrimaryObjRef()); - assertNotNull(createdTask.getCreated()); - assertNotNull(createdTask.getModified()); - assertNotNull(createdTask.getBusinessProcessId()); - assertNull(createdTask.getClaimed()); - assertNull(createdTask.getCompleted()); - assertEquals(createdTask.getCreated(), createdTask.getModified()); - assertEquals(createdTask.getCreated(), createdTask.getPlanned()); - assertEquals(TaskState.READY, createdTask.getState()); - assertNull(createdTask.getParentBusinessProcessId()); - assertEquals(2, createdTask.getPriority()); - assertFalse(createdTask.isRead()); - assertFalse(createdTask.isTransferred()); - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testCreateTaskWithPlanned() - throws NotAuthorizedException, InvalidArgumentException, - ClassificationNotFoundException, WorkbasketNotFoundException, TaskAlreadyExistException { - - Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); - Instant instantPlanned = Instant.now().plus(2, ChronoUnit.HOURS); - newTask.setClassificationKey("T2100"); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - newTask.setOwner("user_1_1"); - newTask.setPlanned(instantPlanned); - Task createdTask = taskService.createTask(newTask); - - assertNotNull(createdTask); - assertNotNull(createdTask.getCreated()); - assertNotNull(createdTask.getPlanned()); - assertEquals(instantPlanned, createdTask.getPlanned()); - assertTrue(createdTask.getCreated().isBefore(createdTask.getPlanned())); - - //verify that planned takes place 2 hours after creation (+- 5 seconds) - Instant plannedAdjusted = createdTask.getPlanned().minus(2, ChronoUnit.HOURS); - long difference = Duration.between(createdTask.getCreated(), plannedAdjusted).abs().getSeconds(); - //add some tolerance to ignore that "created" depends on execution speed - long tolerance = 5; - assertTrue(Math.abs(difference) < tolerance); - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testCreateTaskWithInvalidPlannedAndDue() { - - Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); - Instant instantPlanned = Instant.now().plus(2, ChronoUnit.HOURS); - newTask.setClassificationKey("T2100"); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - newTask.setOwner("user_1_1"); - - newTask.setPlanned(instantPlanned); - newTask.setDue(instantPlanned); //due date not according to service level - Assertions.assertThrows(InvalidArgumentException.class, () -> taskService.createTask(newTask)); - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testCreateTaskWithValidPlannedAndDue() throws ClassificationNotFoundException, InvalidArgumentException { - - Classification classification = classificationService.getClassification("T2100", "DOMAIN_A"); - long serviceLevelDays = Duration.parse(classification.getServiceLevel()).toDays(); - - Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); - Instant instantPlanned = Instant.now(); - newTask.setClassificationKey(classification.getKey()); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - newTask.setOwner("user_1_1"); - - DaysToWorkingDaysConverter converter = DaysToWorkingDaysConverter.initialize(); - //TODO: this is a temporal bug fix because we did not define what happens when a task is planned on the weekend. - long i = converter.convertWorkingDaysToDays(instantPlanned, 0); - newTask.setPlanned(instantPlanned.plus(Duration.ofDays(i))); - //due date according to service level - long calendarDays = converter.convertWorkingDaysToDays(newTask.getPlanned(), serviceLevelDays); - Instant shouldBeDueDate = newTask.getPlanned().plus(Duration.ofDays(calendarDays)); - - newTask.setDue(shouldBeDueDate); - Assertions.assertDoesNotThrow(() -> taskService.createTask(newTask)); - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testIdempotencyOfTaskCreation() - throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, - WorkbasketNotFoundException, TaskAlreadyExistException { - - Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); - newTask.setExternalId("MyExternalId"); - newTask.setClassificationKey("T2100"); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - Task createdTask = taskService.createTask(newTask); - - assertNotNull(createdTask); - assertThat(createdTask.getCreator(), equalTo(CurrentUserContext.getUserid())); - assertEquals("T-Vertragstermin VERA", createdTask.getName()); - assertEquals("1234567", createdTask.getPrimaryObjRef().getValue()); - assertNotNull(createdTask.getExternalId()); - assertNotNull(createdTask.getCreated()); - assertNotNull(createdTask.getModified()); - assertNotNull(createdTask.getBusinessProcessId()); - assertNull(createdTask.getClaimed()); - assertNull(createdTask.getCompleted()); - assertEquals(createdTask.getCreated(), createdTask.getModified()); - assertEquals(createdTask.getCreated(), createdTask.getPlanned()); - assertEquals(TaskState.READY, createdTask.getState()); - assertNull(createdTask.getParentBusinessProcessId()); - assertEquals(2, createdTask.getPriority()); - assertFalse(createdTask.isRead()); - assertFalse(createdTask.isTransferred()); - - Task newTask2 = taskService.newTask("USER_1_1", "DOMAIN_A"); - newTask2.setExternalId("MyExternalId"); - newTask2.setClassificationKey("T2100"); - newTask2.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - - Assertions.assertThrows(TaskAlreadyExistException.class, () -> - taskService.createTask(newTask2)); - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testCreateSimpleTaskWithCustomAttributes() - throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, - WorkbasketNotFoundException, TaskAlreadyExistException, TaskNotFoundException, NoSuchFieldException, - IllegalAccessException { - - Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); - newTask.setClassificationKey("T2100"); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - Map customAttributesForCreate = createSimpleCustomProperties(13); - newTask.setCustomAttributes(customAttributesForCreate); - Task createdTask = taskService.createTask(newTask); - - assertNotNull(createdTask); - assertEquals("T-Vertragstermin VERA", createdTask.getName()); - assertEquals("1234567", createdTask.getPrimaryObjRef().getValue()); - assertNotNull(createdTask.getCreated()); - assertNotNull(createdTask.getModified()); - assertNotNull(createdTask.getBusinessProcessId()); - assertNull(createdTask.getClaimed()); - assertNull(createdTask.getCompleted()); - assertEquals(createdTask.getCreated(), createdTask.getModified()); - assertEquals(createdTask.getCreated(), createdTask.getPlanned()); - assertEquals(TaskState.READY, createdTask.getState()); - assertNull(createdTask.getParentBusinessProcessId()); - assertEquals(2, createdTask.getPriority()); - assertFalse(createdTask.isRead()); - assertFalse(createdTask.isTransferred()); - // verify that the database content is as expected - TaskanaEngineProxyForTest engineProxy = new TaskanaEngineProxyForTest(taskanaEngine); - try { - SqlSession session = engineProxy.getSqlSession(); - Configuration config = session.getConfiguration(); - if (!config.hasMapper(TaskTestMapper.class)) { - config.addMapper(TaskTestMapper.class); - } - TaskTestMapper mapper = session.getMapper(TaskTestMapper.class); - - engineProxy.openConnection(); - String customProperties = mapper.getCustomAttributesAsString(createdTask.getId()); - assertTrue(customProperties.contains("\"Property_13\":\"Property Value of Property_13\"")); - assertTrue(customProperties.contains("\"Property_12\":\"Property Value of Property_12\"")); - assertTrue(customProperties.contains("\"Property_11\":\"Property Value of Property_11\"")); - assertTrue(customProperties.contains("\"Property_10\":\"Property Value of Property_10\"")); - assertTrue(customProperties.contains("\"Property_9\":\"Property Value of Property_9\"")); - assertTrue(customProperties.contains("\"Property_8\":\"Property Value of Property_8\"")); - assertTrue(customProperties.contains("\"Property_7\":\"Property Value of Property_7\"")); - assertTrue(customProperties.contains("\"Property_6\":\"Property Value of Property_6\"")); - assertTrue(customProperties.contains("\"Property_5\":\"Property Value of Property_5\"")); - assertTrue(customProperties.contains("\"Property_4\":\"Property Value of Property_4\"")); - assertTrue(customProperties.contains("\"Property_3\":\"Property Value of Property_3\"")); - assertTrue(customProperties.contains("\"Property_2\":\"Property Value of Property_2\"")); - assertTrue(customProperties.contains("\"Property_1\":\"Property Value of Property_1\"")); - } finally { - engineProxy.returnConnection(); - } - // verify that the map is correctly retrieved from the database - Task retrievedTask = taskService.getTask(createdTask.getId()); - Map customAttributesFromDb = retrievedTask.getCustomAttributes(); - assertNotNull(customAttributesFromDb); - assertEquals(customAttributesFromDb, customAttributesForCreate); - - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testCreateExternalTaskWithAttachment() - throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, - WorkbasketNotFoundException, TaskAlreadyExistException, TaskNotFoundException, NoSuchFieldException, - IllegalAccessException { - - Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); - newTask.setClassificationKey("L12010"); - Map customAttributesForCreate = createSimpleCustomProperties(27); - newTask.addAttachment(createAttachment("DOCTYPE_DEFAULT", - createObjectReference("COMPANY_A", "SYSTEM_B", "INSTANCE_B", "ArchiveId", + Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); + newTask.setClassificationKey("L12010"); + Map customAttributesForCreate = createSimpleCustomProperties(27); + newTask.addAttachment( + createAttachment( + "DOCTYPE_DEFAULT", + createObjectReference( + "COMPANY_A", + "SYSTEM_B", + "INSTANCE_B", + "ArchiveId", "12345678901234567890123456789012345678901234567890"), - "E-MAIL", "2018-01-15", customAttributesForCreate)); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - Task createdTask = taskService.createTask(newTask); - assertNotNull(createdTask.getId()); - assertThat(createdTask.getCreator(), equalTo(CurrentUserContext.getUserid())); + "E-MAIL", + "2018-01-15", + customAttributesForCreate)); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + Task createdTask = taskService.createTask(newTask); + assertNotNull(createdTask.getId()); + assertThat(createdTask.getCreator(), equalTo(CurrentUserContext.getUserid())); - // verify that the database content is as expected - TaskanaEngineProxyForTest engineProxy = new TaskanaEngineProxyForTest(taskanaEngine); - try { - SqlSession session = engineProxy.getSqlSession(); - AttachmentMapper mapper = session.getMapper(AttachmentMapper.class); - engineProxy.openConnection(); - String customProperties = mapper.getCustomAttributesAsString(createdTask.getAttachments().get(0).getId()); - assertTrue(customProperties.contains("\"Property_26\":\"Property Value of Property_26\"")); - assertTrue(customProperties.contains("\"Property_25\":\"Property Value of Property_25\"")); - assertTrue(customProperties.contains("\"Property_21\":\"Property Value of Property_21\"")); - assertTrue(customProperties.contains("\"Property_19\":\"Property Value of Property_19\"")); - assertTrue(customProperties.contains("\"Property_16\":\"Property Value of Property_16\"")); - assertTrue(customProperties.contains("\"Property_12\":\"Property Value of Property_12\"")); - assertTrue(customProperties.contains("\"Property_11\":\"Property Value of Property_11\"")); - assertTrue(customProperties.contains("\"Property_7\":\"Property Value of Property_7\"")); - assertTrue(customProperties.contains("\"Property_6\":\"Property Value of Property_6\"")); - } finally { - engineProxy.returnConnection(); - } - - Task readTask = taskService.getTask(createdTask.getId()); - assertNotNull(readTask); - assertThat(readTask.getCreator(), equalTo(CurrentUserContext.getUserid())); - assertNotNull(readTask.getAttachments()); - assertEquals(1, readTask.getAttachments().size()); - assertNotNull(readTask.getAttachments().get(0).getCreated()); - assertNotNull(readTask.getAttachments().get(0).getModified()); - assertEquals(readTask.getAttachments().get(0).getCreated(), readTask.getAttachments().get(0).getModified()); - assertNotNull(readTask.getAttachments().get(0).getClassificationSummary()); - assertNotNull(readTask.getAttachments().get(0).getClassificationSummary().getId()); - assertNotNull(readTask.getAttachments().get(0).getClassificationSummary().getKey()); - assertNotNull(readTask.getAttachments().get(0).getClassificationSummary().getType()); - assertNotNull(readTask.getAttachments().get(0).getClassificationSummary().getCategory()); - assertNotNull(readTask.getAttachments().get(0).getClassificationSummary().getDomain()); - assertNotNull(readTask.getAttachments().get(0).getClassificationSummary().getServiceLevel()); - assertNotNull(readTask.getAttachments().get(0).getReceived()); - assertNotNull(readTask.getAttachments().get(0).getChannel()); - assertNotNull(readTask.getAttachments().get(0).getObjectReference()); - // verify that the map is correctly retrieved from the database - Map customAttributesFromDb = readTask.getAttachments().get(0).getCustomAttributes(); - assertNotNull(customAttributesFromDb); - assertEquals(customAttributesFromDb, customAttributesForCreate); + // verify that the database content is as expected + TaskanaEngineProxyForTest engineProxy = new TaskanaEngineProxyForTest(taskanaEngine); + try { + SqlSession session = engineProxy.getSqlSession(); + AttachmentMapper mapper = session.getMapper(AttachmentMapper.class); + engineProxy.openConnection(); + String customProperties = + mapper.getCustomAttributesAsString(createdTask.getAttachments().get(0).getId()); + assertTrue(customProperties.contains("\"Property_26\":\"Property Value of Property_26\"")); + assertTrue(customProperties.contains("\"Property_25\":\"Property Value of Property_25\"")); + assertTrue(customProperties.contains("\"Property_21\":\"Property Value of Property_21\"")); + assertTrue(customProperties.contains("\"Property_19\":\"Property Value of Property_19\"")); + assertTrue(customProperties.contains("\"Property_16\":\"Property Value of Property_16\"")); + assertTrue(customProperties.contains("\"Property_12\":\"Property Value of Property_12\"")); + assertTrue(customProperties.contains("\"Property_11\":\"Property Value of Property_11\"")); + assertTrue(customProperties.contains("\"Property_7\":\"Property Value of Property_7\"")); + assertTrue(customProperties.contains("\"Property_6\":\"Property Value of Property_6\"")); + } finally { + engineProxy.returnConnection(); } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testCreateExternalTaskWithMultipleAttachments() - throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, - WorkbasketNotFoundException, TaskAlreadyExistException, TaskNotFoundException { + Task readTask = taskService.getTask(createdTask.getId()); + assertNotNull(readTask); + assertThat(readTask.getCreator(), equalTo(CurrentUserContext.getUserid())); + assertNotNull(readTask.getAttachments()); + assertEquals(1, readTask.getAttachments().size()); + assertNotNull(readTask.getAttachments().get(0).getCreated()); + assertNotNull(readTask.getAttachments().get(0).getModified()); + assertEquals( + readTask.getAttachments().get(0).getCreated(), + readTask.getAttachments().get(0).getModified()); + assertNotNull(readTask.getAttachments().get(0).getClassificationSummary()); + assertNotNull(readTask.getAttachments().get(0).getClassificationSummary().getId()); + assertNotNull(readTask.getAttachments().get(0).getClassificationSummary().getKey()); + assertNotNull(readTask.getAttachments().get(0).getClassificationSummary().getType()); + assertNotNull(readTask.getAttachments().get(0).getClassificationSummary().getCategory()); + assertNotNull(readTask.getAttachments().get(0).getClassificationSummary().getDomain()); + assertNotNull(readTask.getAttachments().get(0).getClassificationSummary().getServiceLevel()); + assertNotNull(readTask.getAttachments().get(0).getReceived()); + assertNotNull(readTask.getAttachments().get(0).getChannel()); + assertNotNull(readTask.getAttachments().get(0).getObjectReference()); + // verify that the map is correctly retrieved from the database + Map customAttributesFromDb = + readTask.getAttachments().get(0).getCustomAttributes(); + assertNotNull(customAttributesFromDb); + assertEquals(customAttributesFromDb, customAttributesForCreate); + } - Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); - newTask.setClassificationKey("L12010"); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - newTask.addAttachment(createAttachment("DOCTYPE_DEFAULT", - createObjectReference("COMPANY_A", "SYSTEM_B", "INSTANCE_B", "ArchiveId", + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testCreateExternalTaskWithMultipleAttachments() + throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, + WorkbasketNotFoundException, TaskAlreadyExistException, TaskNotFoundException { + + Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); + newTask.setClassificationKey("L12010"); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + newTask.addAttachment( + createAttachment( + "DOCTYPE_DEFAULT", + createObjectReference( + "COMPANY_A", + "SYSTEM_B", + "INSTANCE_B", + "ArchiveId", "12345678901234567890123456789012345678901234567890"), - "E-MAIL", "2018-01-15", createSimpleCustomProperties(3))); - newTask.addAttachment(createAttachment("DOCTYPE_DEFAULT", - createObjectReference("COMPANY_A", "SYSTEM_B", "INSTANCE_B", "ArchiveId", + "E-MAIL", + "2018-01-15", + createSimpleCustomProperties(3))); + newTask.addAttachment( + createAttachment( + "DOCTYPE_DEFAULT", + createObjectReference( + "COMPANY_A", + "SYSTEM_B", + "INSTANCE_B", + "ArchiveId", "12345678901234567890123456789012345678901234567890"), - "E-MAIL", "2018-01-15", createSimpleCustomProperties(3))); - Task createdTask = taskService.createTask(newTask); + "E-MAIL", + "2018-01-15", + createSimpleCustomProperties(3))); + Task createdTask = taskService.createTask(newTask); - assertNotNull(createdTask.getId()); - assertThat(createdTask.getCreator(), equalTo(CurrentUserContext.getUserid())); + assertNotNull(createdTask.getId()); + assertThat(createdTask.getCreator(), equalTo(CurrentUserContext.getUserid())); - Task readTask = taskService.getTask(createdTask.getId()); - assertNotNull(readTask); - assertThat(readTask.getCreator(), equalTo(CurrentUserContext.getUserid())); - assertNotNull(readTask.getAttachments()); - assertEquals(2, readTask.getAttachments().size()); - assertNotNull(readTask.getAttachments().get(1).getCreated()); - assertNotNull(readTask.getAttachments().get(1).getModified()); - assertEquals(readTask.getAttachments().get(0).getCreated(), readTask.getAttachments().get(1).getModified()); - // assertNotNull(readTask.getAttachments().get(0).getClassification()); - assertNotNull(readTask.getAttachments().get(0).getObjectReference()); - } + Task readTask = taskService.getTask(createdTask.getId()); + assertNotNull(readTask); + assertThat(readTask.getCreator(), equalTo(CurrentUserContext.getUserid())); + assertNotNull(readTask.getAttachments()); + assertEquals(2, readTask.getAttachments().size()); + assertNotNull(readTask.getAttachments().get(1).getCreated()); + assertNotNull(readTask.getAttachments().get(1).getModified()); + assertEquals( + readTask.getAttachments().get(0).getCreated(), + readTask.getAttachments().get(1).getModified()); + // assertNotNull(readTask.getAttachments().get(0).getClassification()); + assertNotNull(readTask.getAttachments().get(0).getObjectReference()); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testCalculationOfDueDateAtCreate() - throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, - WorkbasketNotFoundException, TaskAlreadyExistException, TaskNotFoundException { + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testCalculationOfDueDateAtCreate() + throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, + WorkbasketNotFoundException, TaskAlreadyExistException, TaskNotFoundException { - //SL P16D - Classification classification = classificationService.getClassification("L110105", "DOMAIN_A"); - long serviceLevelDays = Duration.parse(classification.getServiceLevel()).toDays(); - assertTrue(serviceLevelDays > 5); + // SL P16D + Classification classification = classificationService.getClassification("L110105", "DOMAIN_A"); + long serviceLevelDays = Duration.parse(classification.getServiceLevel()).toDays(); + assertTrue(serviceLevelDays > 5); - Task newTask = taskService.newTask("USER_1_1", classification.getDomain()); - newTask.setClassificationKey(classification.getKey()); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + Task newTask = taskService.newTask("USER_1_1", classification.getDomain()); + newTask.setClassificationKey(classification.getKey()); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - Instant planned = Instant.now().plus(10, ChronoUnit.DAYS); - newTask.setPlanned(planned); - Task createdTask = taskService.createTask(newTask); - assertNotNull(createdTask.getId()); + Instant planned = Instant.now().plus(10, ChronoUnit.DAYS); + newTask.setPlanned(planned); + Task createdTask = taskService.createTask(newTask); + assertNotNull(createdTask.getId()); - Task readTask = taskService.getTask(createdTask.getId()); - assertNotNull(readTask); - assertEquals(planned, readTask.getPlanned()); + Task readTask = taskService.getTask(createdTask.getId()); + assertNotNull(readTask); + assertEquals(planned, readTask.getPlanned()); - long calendarDays = DaysToWorkingDaysConverter.initialize() + long calendarDays = + DaysToWorkingDaysConverter.initialize() .convertWorkingDaysToDays(readTask.getPlanned(), serviceLevelDays); - Instant shouldBeDueDate = readTask.getPlanned().plus(Duration.ofDays(calendarDays)); - assertEquals(readTask.getDue(), shouldBeDueDate); - } + Instant shouldBeDueDate = readTask.getPlanned().plus(Duration.ofDays(calendarDays)); + assertEquals(readTask.getDue(), shouldBeDueDate); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testCalculationOfPlannedDateAtCreate() - throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, - WorkbasketNotFoundException, TaskAlreadyExistException, TaskNotFoundException { + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testCalculationOfPlannedDateAtCreate() + throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, + WorkbasketNotFoundException, TaskAlreadyExistException, TaskNotFoundException { - //SL P16D - Classification classification = classificationService.getClassification("L110105", "DOMAIN_A"); - long serviceLevelDays = Duration.parse(classification.getServiceLevel()).toDays(); - assertTrue(serviceLevelDays > 5); + // SL P16D + Classification classification = classificationService.getClassification("L110105", "DOMAIN_A"); + long serviceLevelDays = Duration.parse(classification.getServiceLevel()).toDays(); + assertTrue(serviceLevelDays > 5); - Task newTask = taskService.newTask("USER_1_1", classification.getDomain()); - newTask.setClassificationKey(classification.getKey()); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + Task newTask = taskService.newTask("USER_1_1", classification.getDomain()); + newTask.setClassificationKey(classification.getKey()); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - Instant due = Instant.now().plus(40, ChronoUnit.DAYS); - newTask.setDue(due); - Task createdTask = taskService.createTask(newTask); - assertNotNull(createdTask.getId()); + Instant due = Instant.now().plus(40, ChronoUnit.DAYS); + newTask.setDue(due); + Task createdTask = taskService.createTask(newTask); + assertNotNull(createdTask.getId()); - Task readTask = taskService.getTask(createdTask.getId()); - assertNotNull(readTask); - assertEquals(due, readTask.getDue()); + Task readTask = taskService.getTask(createdTask.getId()); + assertNotNull(readTask); + assertEquals(due, readTask.getDue()); - long calendarDaysToSubstract = DaysToWorkingDaysConverter.initialize() - .convertWorkingDaysToDays(due, -serviceLevelDays); + long calendarDaysToSubstract = + DaysToWorkingDaysConverter.initialize().convertWorkingDaysToDays(due, -serviceLevelDays); - assertTrue(calendarDaysToSubstract < 0); - assertTrue(calendarDaysToSubstract <= -serviceLevelDays); + assertTrue(calendarDaysToSubstract < 0); + assertTrue(calendarDaysToSubstract <= -serviceLevelDays); - Instant shouldBePlannedDate = due.plus(Duration.ofDays(calendarDaysToSubstract)); - assertEquals(readTask.getPlanned(), shouldBePlannedDate); - } + Instant shouldBePlannedDate = due.plus(Duration.ofDays(calendarDaysToSubstract)); + assertEquals(readTask.getPlanned(), shouldBePlannedDate); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testPrioDurationOfTaskFromAttachmentsAtCreate() - throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, - WorkbasketNotFoundException, TaskAlreadyExistException, TaskNotFoundException { + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testPrioDurationOfTaskFromAttachmentsAtCreate() + throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, + WorkbasketNotFoundException, TaskAlreadyExistException, TaskNotFoundException { - Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); - newTask.setClassificationKey("L12010"); // prio 8, SL P7D - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); + newTask.setClassificationKey("L12010"); // prio 8, SL P7D + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - newTask.addAttachment(createAttachment("DOCTYPE_DEFAULT", // prio 99, SL P2000D - createObjectReference("COMPANY_A", "SYSTEM_B", "INSTANCE_B", "ArchiveId", + newTask.addAttachment( + createAttachment( + "DOCTYPE_DEFAULT", // prio 99, SL P2000D + createObjectReference( + "COMPANY_A", + "SYSTEM_B", + "INSTANCE_B", + "ArchiveId", "12345678901234567890123456789012345678901234567890"), - "E-MAIL", "2018-01-15", createSimpleCustomProperties(3))); - newTask.addAttachment(createAttachment("L1060", // prio 1, SL P1D - createObjectReference("COMPANY_A", "SYSTEM_B", "INSTANCE_B", "ArchiveId", + "E-MAIL", + "2018-01-15", + createSimpleCustomProperties(3))); + newTask.addAttachment( + createAttachment( + "L1060", // prio 1, SL P1D + createObjectReference( + "COMPANY_A", + "SYSTEM_B", + "INSTANCE_B", + "ArchiveId", "12345678901234567890123456789012345678901234567890"), - "E-MAIL", "2018-01-15", createSimpleCustomProperties(3))); - Task createdTask = taskService.createTask(newTask); + "E-MAIL", + "2018-01-15", + createSimpleCustomProperties(3))); + Task createdTask = taskService.createTask(newTask); - assertNotNull(createdTask.getId()); - assertThat(createdTask.getCreator(), equalTo(CurrentUserContext.getUserid())); + assertNotNull(createdTask.getId()); + assertThat(createdTask.getCreator(), equalTo(CurrentUserContext.getUserid())); - Task readTask = taskService.getTask(createdTask.getId()); - assertNotNull(readTask); - assertThat(readTask.getCreator(), equalTo(CurrentUserContext.getUserid())); - assertNotNull(readTask.getAttachments()); - assertEquals(2, readTask.getAttachments().size()); - assertNotNull(readTask.getAttachments().get(1).getCreated()); - assertNotNull(readTask.getAttachments().get(1).getModified()); - assertEquals(readTask.getAttachments().get(0).getCreated(), readTask.getAttachments().get(1).getModified()); - // assertNotNull(readTask.getAttachments().get(0).getClassification()); - assertNotNull(readTask.getAttachments().get(0).getObjectReference()); + Task readTask = taskService.getTask(createdTask.getId()); + assertNotNull(readTask); + assertThat(readTask.getCreator(), equalTo(CurrentUserContext.getUserid())); + assertNotNull(readTask.getAttachments()); + assertEquals(2, readTask.getAttachments().size()); + assertNotNull(readTask.getAttachments().get(1).getCreated()); + assertNotNull(readTask.getAttachments().get(1).getModified()); + assertEquals( + readTask.getAttachments().get(0).getCreated(), + readTask.getAttachments().get(1).getModified()); + // assertNotNull(readTask.getAttachments().get(0).getClassification()); + assertNotNull(readTask.getAttachments().get(0).getObjectReference()); - assertEquals(99, readTask.getPriority()); + assertEquals(99, readTask.getPriority()); - DaysToWorkingDaysConverter converter = DaysToWorkingDaysConverter - .initialize(Collections.singletonList(new TimeIntervalColumnHeader(0)), Instant.now()); - long calendarDays = converter.convertWorkingDaysToDays(readTask.getPlanned(), 1); + DaysToWorkingDaysConverter converter = + DaysToWorkingDaysConverter.initialize( + Collections.singletonList(new TimeIntervalColumnHeader(0)), Instant.now()); + long calendarDays = converter.convertWorkingDaysToDays(readTask.getPlanned(), 1); - assertEquals(readTask.getDue(), readTask.getPlanned().plus(Duration.ofDays(calendarDays))); - } + assertEquals(readTask.getDue(), readTask.getPlanned().plus(Duration.ofDays(calendarDays))); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testThrowsExceptionIfAttachmentIsInvalid() - throws ClassificationNotFoundException { + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testThrowsExceptionIfAttachmentIsInvalid() throws ClassificationNotFoundException { - Consumer testCreateTask = (Attachment invalidAttachment) -> { - - Task taskWithInvalidAttachment = makeNewTask(taskService); - taskWithInvalidAttachment.addAttachment(invalidAttachment); - Assertions.assertThrows(InvalidArgumentException.class, () -> - taskService.createTask(taskWithInvalidAttachment), - "Should have thrown an InvalidArgumentException, because Attachment-ObjRef is null."); + Consumer testCreateTask = + (Attachment invalidAttachment) -> { + Task taskWithInvalidAttachment = makeNewTask(taskService); + taskWithInvalidAttachment.addAttachment(invalidAttachment); + Assertions.assertThrows( + InvalidArgumentException.class, + () -> taskService.createTask(taskWithInvalidAttachment), + "Should have thrown an InvalidArgumentException, because Attachment-ObjRef is null."); }; - testCreateTask.accept(createAttachment("DOCTYPE_DEFAULT", - null, - "E-MAIL", "2018-01-15", createSimpleCustomProperties(3))); + testCreateTask.accept( + createAttachment( + "DOCTYPE_DEFAULT", null, "E-MAIL", "2018-01-15", createSimpleCustomProperties(3))); - testCreateTask.accept(createAttachment("DOCTYPE_DEFAULT", + testCreateTask.accept( + createAttachment( + "DOCTYPE_DEFAULT", createObjectReference("COMPANY_A", "SYSTEM_B", "INSTANCE_B", "ArchiveId", null), - "E-MAIL", "2018-01-15", createSimpleCustomProperties(3))); + "E-MAIL", + "2018-01-15", + createSimpleCustomProperties(3))); - testCreateTask.accept(createAttachment("DOCTYPE_DEFAULT", - createObjectReference("COMPANY_A", "SYSTEM_B", "INSTANCE_B", null, + testCreateTask.accept( + createAttachment( + "DOCTYPE_DEFAULT", + createObjectReference( + "COMPANY_A", + "SYSTEM_B", + "INSTANCE_B", + null, "12345678901234567890123456789012345678901234567890"), - "E-MAIL", "2018-01-15", createSimpleCustomProperties(3))); + "E-MAIL", + "2018-01-15", + createSimpleCustomProperties(3))); - testCreateTask.accept(createAttachment("DOCTYPE_DEFAULT", - createObjectReference("COMPANY_A", "SYSTEM_B", null, "ArchiveId", + testCreateTask.accept( + createAttachment( + "DOCTYPE_DEFAULT", + createObjectReference( + "COMPANY_A", + "SYSTEM_B", + null, + "ArchiveId", "12345678901234567890123456789012345678901234567890"), - "E-MAIL", "2018-01-15", createSimpleCustomProperties(3))); + "E-MAIL", + "2018-01-15", + createSimpleCustomProperties(3))); - testCreateTask.accept(createAttachment("DOCTYPE_DEFAULT", - createObjectReference("COMPANY_A", null, "INSTANCE_B", "ArchiveId", + testCreateTask.accept( + createAttachment( + "DOCTYPE_DEFAULT", + createObjectReference( + "COMPANY_A", + null, + "INSTANCE_B", + "ArchiveId", "12345678901234567890123456789012345678901234567890"), - "E-MAIL", "2018-01-15", createSimpleCustomProperties(3))); + "E-MAIL", + "2018-01-15", + createSimpleCustomProperties(3))); - testCreateTask.accept(createAttachment("DOCTYPE_DEFAULT", - createObjectReference(null, "SYSTEM_B", "INSTANCE_B", "ArchiveId", + testCreateTask.accept( + createAttachment( + "DOCTYPE_DEFAULT", + createObjectReference( + null, + "SYSTEM_B", + "INSTANCE_B", + "ArchiveId", "12345678901234567890123456789012345678901234567890"), - "E-MAIL", "2018-01-15", createSimpleCustomProperties(3))); - } + "E-MAIL", + "2018-01-15", + createSimpleCustomProperties(3))); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testUseCustomNameIfSetForNewTask() - throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, - WorkbasketNotFoundException, TaskAlreadyExistException { + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testUseCustomNameIfSetForNewTask() + throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, + WorkbasketNotFoundException, TaskAlreadyExistException { - Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); - newTask.setClassificationKey("T2100"); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - newTask.setName("Test Name"); - Task createdTask = taskService.createTask(newTask); + Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); + newTask.setClassificationKey("T2100"); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + newTask.setName("Test Name"); + Task createdTask = taskService.createTask(newTask); - assertNotNull(createdTask); - assertThat(createdTask.getCreator(), equalTo(CurrentUserContext.getUserid())); - assertEquals("Test Name", createdTask.getName()); - } + assertNotNull(createdTask); + assertThat(createdTask.getCreator(), equalTo(CurrentUserContext.getUserid())); + assertEquals("Test Name", createdTask.getName()); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testUseClassificationMetadataFromCorrectDomainForNewTask() - throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, - WorkbasketNotFoundException, TaskAlreadyExistException { + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testUseClassificationMetadataFromCorrectDomainForNewTask() + throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, + WorkbasketNotFoundException, TaskAlreadyExistException { - Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); - newTask.setClassificationKey("T2100"); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - newTask.setName("Test Name"); - Task createdTask = taskService.createTask(newTask); + Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); + newTask.setClassificationKey("T2100"); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + newTask.setName("Test Name"); + Task createdTask = taskService.createTask(newTask); - assertNotNull(createdTask); - assertThat(createdTask.getCreator(), equalTo(CurrentUserContext.getUserid())); - assertEquals(2, createdTask.getPriority()); // priority is 22 in DOMAIN_B, task is created in DOMAIN_A - } + assertNotNull(createdTask); + assertThat(createdTask.getCreator(), equalTo(CurrentUserContext.getUserid())); + assertEquals( + 2, createdTask.getPriority()); // priority is 22 in DOMAIN_B, task is created in DOMAIN_A + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testGetExceptionIfWorkbasketDoesNotExist() { + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testGetExceptionIfWorkbasketDoesNotExist() { - Task newTask = taskService.newTask("UNKNOWN"); - newTask.setClassificationKey("T2100"); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + Task newTask = taskService.newTask("UNKNOWN"); + newTask.setClassificationKey("T2100"); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - Assertions.assertThrows(WorkbasketNotFoundException.class, () -> - taskService.createTask(newTask)); - } + Assertions.assertThrows( + WorkbasketNotFoundException.class, () -> taskService.createTask(newTask)); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testGetExceptionIfAppendIsNotPermitted() { + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testGetExceptionIfAppendIsNotPermitted() { - Task newTask = taskService.newTask("GPK_KSC", "DOMAIN_A"); - newTask.setClassificationKey("T2100"); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + Task newTask = taskService.newTask("GPK_KSC", "DOMAIN_A"); + newTask.setClassificationKey("T2100"); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - Assertions.assertThrows(NotAuthorizedException.class, () -> - taskService.createTask(newTask)); - } + Assertions.assertThrows(NotAuthorizedException.class, () -> taskService.createTask(newTask)); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testThrowsExceptionIfMandatoryPrimaryObjectReferenceIsNotSetOrIncomplete() { + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testThrowsExceptionIfMandatoryPrimaryObjectReferenceIsNotSetOrIncomplete() { - Consumer testCreateTask = (ObjectReference objectReference) -> { - - Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); - newTask.setClassificationKey("T2100"); - if (objectReference != null) { - newTask.setPrimaryObjRef(objectReference); - } - Assertions.assertThrows(InvalidArgumentException.class, () -> - taskService.createTask(newTask), - "Should have thrown an InvalidArgumentException, because ObjRef-ObjRef is null."); + Consumer testCreateTask = + (ObjectReference objectReference) -> { + Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); + newTask.setClassificationKey("T2100"); + if (objectReference != null) { + newTask.setPrimaryObjRef(objectReference); + } + Assertions.assertThrows( + InvalidArgumentException.class, + () -> taskService.createTask(newTask), + "Should have thrown an InvalidArgumentException, because ObjRef-ObjRef is null."); }; - testCreateTask.accept(null); - testCreateTask.accept(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", null)); - testCreateTask.accept(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", null, "1234567")); - testCreateTask.accept(createObjectReference("COMPANY_A", "SYSTEM_A", null, "VNR", "1234567")); - testCreateTask.accept(createObjectReference("COMPANY_A", null, "INSTANCE_A", "VNR", "1234567")); - testCreateTask.accept(createObjectReference(null, "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + testCreateTask.accept(null); + testCreateTask.accept( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", null)); + testCreateTask.accept( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", null, "1234567")); + testCreateTask.accept(createObjectReference("COMPANY_A", "SYSTEM_A", null, "VNR", "1234567")); + testCreateTask.accept(createObjectReference("COMPANY_A", null, "INSTANCE_A", "VNR", "1234567")); + testCreateTask.accept(createObjectReference(null, "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testSetDomainFromWorkbasket() + throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, + WorkbasketNotFoundException, TaskAlreadyExistException { + + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + + Workbasket workbasket = workbasketService.getWorkbasket("USER_1_1", "DOMAIN_A"); + + Task newTask = taskService.newTask("WBI:100000000000000000000000000000000006"); + newTask.setClassificationKey("T2100"); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + Task createdTask = taskService.createTask(newTask); + + assertNotNull(createdTask); + assertThat(createdTask.getCreator(), equalTo(CurrentUserContext.getUserid())); + assertNotNull(createdTask.getDomain()); + assertEquals(workbasket.getDomain(), createdTask.getDomain()); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testCreatedTaskObjectEqualsReadTaskObject() + throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, + WorkbasketNotFoundException, TaskAlreadyExistException, TaskNotFoundException { + + Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); + newTask.setClassificationKey("T2100"); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + for (int i = 1; i < 16; i++) { + newTask.setCustomAttribute(Integer.toString(i), "VALUE " + i); } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testSetDomainFromWorkbasket() - throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, - WorkbasketNotFoundException, TaskAlreadyExistException { - - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - - Workbasket workbasket = workbasketService.getWorkbasket("USER_1_1", "DOMAIN_A"); - - Task newTask = taskService.newTask("WBI:100000000000000000000000000000000006"); - newTask.setClassificationKey("T2100"); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - Task createdTask = taskService.createTask(newTask); - - assertNotNull(createdTask); - assertThat(createdTask.getCreator(), equalTo(CurrentUserContext.getUserid())); - assertNotNull(createdTask.getDomain()); - assertEquals(workbasket.getDomain(), createdTask.getDomain()); - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testCreatedTaskObjectEqualsReadTaskObject() - throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, - WorkbasketNotFoundException, TaskAlreadyExistException, TaskNotFoundException { - - Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); - newTask.setClassificationKey("T2100"); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - for (int i = 1; i < 16; i++) { - newTask.setCustomAttribute(Integer.toString(i), "VALUE " + i); - } - newTask.setCustomAttributes(createSimpleCustomProperties(5)); - newTask.setDescription("Description of test task"); - newTask.setNote("My note"); - newTask.addAttachment(createAttachment("DOCTYPE_DEFAULT", - createObjectReference("COMPANY_A", "SYSTEM_B", "INSTANCE_B", "ArchiveId", + newTask.setCustomAttributes(createSimpleCustomProperties(5)); + newTask.setDescription("Description of test task"); + newTask.setNote("My note"); + newTask.addAttachment( + createAttachment( + "DOCTYPE_DEFAULT", + createObjectReference( + "COMPANY_A", + "SYSTEM_B", + "INSTANCE_B", + "ArchiveId", "12345678901234567890123456789012345678901234567890"), - "E-MAIL", "2018-01-15", createSimpleCustomProperties(3))); - Task createdTask = taskService.createTask(newTask); - Task readTask = taskService.getTask(createdTask.getId()); + "E-MAIL", + "2018-01-15", + createSimpleCustomProperties(3))); + Task createdTask = taskService.createTask(newTask); + Task readTask = taskService.getTask(createdTask.getId()); - assertEquals(createdTask, readTask); + assertEquals(createdTask, readTask); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testCreateSimpleTaskWithCallbackInfo() + throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException { + + Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); + newTask.setClassificationKey("T2100"); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + + HashMap callbackInfo = new HashMap<>(); + for (int i = 1; i <= 10; i++) { + callbackInfo.put("info_" + i, "Value of info_" + i); } + newTask.setCallbackInfo(callbackInfo); + Task createdTask = taskService.createTask(newTask); - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testCreateSimpleTaskWithCallbackInfo() - throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException { + assertNotNull(createdTask); + assertEquals("1234567", createdTask.getPrimaryObjRef().getValue()); + assertNotNull(createdTask.getCreated()); + assertNotNull(createdTask.getModified()); + assertNotNull(createdTask.getBusinessProcessId()); + assertNull(createdTask.getClaimed()); + assertNull(createdTask.getCompleted()); + assertEquals(createdTask.getCreated(), createdTask.getModified()); + assertEquals(createdTask.getCreated(), createdTask.getPlanned()); + assertEquals(TaskState.READY, createdTask.getState()); + assertNull(createdTask.getParentBusinessProcessId()); + assertEquals(2, createdTask.getPriority()); + assertFalse(createdTask.isRead()); + assertFalse(createdTask.isTransferred()); - Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); - newTask.setClassificationKey("T2100"); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + Task retrievedTask = taskService.getTask(createdTask.getId()); + assertEquals(callbackInfo, retrievedTask.getCallbackInfo()); + } - HashMap callbackInfo = new HashMap<>(); - for (int i = 1; i <= 10; i++) { - callbackInfo.put("info_" + i, "Value of info_" + i); - } - newTask.setCallbackInfo(callbackInfo); - Task createdTask = taskService.createTask(newTask); + @Test + void testCreateTaskWithSecurityButNoUserId() { - assertNotNull(createdTask); - assertEquals("1234567", createdTask.getPrimaryObjRef().getValue()); - assertNotNull(createdTask.getCreated()); - assertNotNull(createdTask.getModified()); - assertNotNull(createdTask.getBusinessProcessId()); - assertNull(createdTask.getClaimed()); - assertNull(createdTask.getCompleted()); - assertEquals(createdTask.getCreated(), createdTask.getModified()); - assertEquals(createdTask.getCreated(), createdTask.getPlanned()); - assertEquals(TaskState.READY, createdTask.getState()); - assertNull(createdTask.getParentBusinessProcessId()); - assertEquals(2, createdTask.getPriority()); - assertFalse(createdTask.isRead()); - assertFalse(createdTask.isTransferred()); + Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); + newTask.setClassificationKey("T2100"); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_B", "SYSTEM_B", "INSTANCE_B", "VNR", "1234567")); - Task retrievedTask = taskService.getTask(createdTask.getId()); - assertEquals(callbackInfo, retrievedTask.getCallbackInfo()); + Assertions.assertThrows(NotAuthorizedException.class, () -> taskService.createTask(newTask)); + } - } + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testCreateTaskAlreadyExisting() throws NotAuthorizedException, TaskNotFoundException { - @Test - void testCreateTaskWithSecurityButNoUserId() { + Task existingTask = taskService.getTask("TKI:000000000000000000000000000000000000"); - Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); - newTask.setClassificationKey("T2100"); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_B", "SYSTEM_B", "INSTANCE_B", "VNR", "1234567")); + Assertions.assertThrows( + TaskAlreadyExistException.class, () -> taskService.createTask(existingTask)); + } - Assertions.assertThrows(NotAuthorizedException.class, () -> - taskService.createTask(newTask)); - } + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testCreateTaskNotAuthorizedOnWorkbasket() { - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testCreateTaskAlreadyExisting() - throws NotAuthorizedException, TaskNotFoundException { + Task task = taskService.newTask("TEAMLEAD_2", "DOMAIN_A"); - Task existingTask = taskService.getTask("TKI:000000000000000000000000000000000000"); - - Assertions.assertThrows(TaskAlreadyExistException.class, () -> - taskService.createTask(existingTask)); - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testCreateTaskNotAuthorizedOnWorkbasket() { - - Task task = taskService.newTask("TEAMLEAD_2", "DOMAIN_A"); - - Assertions.assertThrows(NotAuthorizedException.class, () -> - taskService.createTask(task)); - } - - private Task makeNewTask(TaskService taskService) { - Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); - newTask.setClassificationKey("L12010"); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - newTask.setClassificationKey("L12010"); - return newTask; - } + Assertions.assertThrows(NotAuthorizedException.class, () -> taskService.createTask(task)); + } + private Task makeNewTask(TaskService taskService) { + Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); + newTask.setClassificationKey("L12010"); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + newTask.setClassificationKey("L12010"); + return newTask; + } } diff --git a/lib/taskana-core/src/test/java/acceptance/task/DeleteTaskAccTest.java b/lib/taskana-core/src/test/java/acceptance/task/DeleteTaskAccTest.java index 7a0ecd0de..341776ea5 100644 --- a/lib/taskana-core/src/test/java/acceptance/task/DeleteTaskAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/task/DeleteTaskAccTest.java @@ -6,14 +6,13 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; +import acceptance.AbstractAccTest; import java.util.ArrayList; import java.util.List; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.BulkOperationResults; import pro.taskana.Task; import pro.taskana.TaskService; @@ -25,120 +24,122 @@ import pro.taskana.exceptions.TaskanaException; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "delete task" scenarios. - */ +/** Acceptance test for all "delete task" scenarios. */ @ExtendWith(JAASExtension.class) class DeleteTaskAccTest extends AbstractAccTest { - DeleteTaskAccTest() { - super(); - } + DeleteTaskAccTest() { + super(); + } - @WithAccessId( - userName = "user_1_2", - groupNames = {"group_1"}) - @Test - void testDeleteSingleTaskNotAuthorized() { + @WithAccessId( + userName = "user_1_2", + groupNames = {"group_1"}) + @Test + void testDeleteSingleTaskNotAuthorized() { - TaskService taskService = taskanaEngine.getTaskService(); - Assertions.assertThrows(NotAuthorizedException.class, () -> - taskService.deleteTask("TKI:000000000000000000000000000000000037")); - } + TaskService taskService = taskanaEngine.getTaskService(); + Assertions.assertThrows( + NotAuthorizedException.class, + () -> taskService.deleteTask("TKI:000000000000000000000000000000000037")); + } - @WithAccessId( - userName = "user_1_2", - groupNames = {"group_1", "admin"}) - @Test - void testDeleteSingleTask() - throws TaskNotFoundException, InvalidStateException, NotAuthorizedException { + @WithAccessId( + userName = "user_1_2", + groupNames = {"group_1", "admin"}) + @Test + void testDeleteSingleTask() + throws TaskNotFoundException, InvalidStateException, NotAuthorizedException { - TaskService taskService = taskanaEngine.getTaskService(); - Task task = taskService.getTask("TKI:000000000000000000000000000000000036"); + TaskService taskService = taskanaEngine.getTaskService(); + Task task = taskService.getTask("TKI:000000000000000000000000000000000036"); - taskService.deleteTask(task.getId()); + taskService.deleteTask(task.getId()); - Assertions.assertThrows(TaskNotFoundException.class, () -> - taskService.getTask("TKI:000000000000000000000000000000000036")); - } + Assertions.assertThrows( + TaskNotFoundException.class, + () -> taskService.getTask("TKI:000000000000000000000000000000000036")); + } - @WithAccessId( - userName = "user_1_2", - groupNames = {"group_1", "admin"}) - @Test - void testThrowsExceptionIfTaskIsNotCompleted() - throws TaskNotFoundException, NotAuthorizedException { - TaskService taskService = taskanaEngine.getTaskService(); - Task task = taskService.getTask("TKI:000000000000000000000000000000000029"); + @WithAccessId( + userName = "user_1_2", + groupNames = {"group_1", "admin"}) + @Test + void testThrowsExceptionIfTaskIsNotCompleted() + throws TaskNotFoundException, NotAuthorizedException { + TaskService taskService = taskanaEngine.getTaskService(); + Task task = taskService.getTask("TKI:000000000000000000000000000000000029"); - Assertions.assertThrows(InvalidStateException.class, () -> - taskService.deleteTask(task.getId())); - } + Assertions.assertThrows( + InvalidStateException.class, () -> taskService.deleteTask(task.getId())); + } - @WithAccessId( - userName = "user_1_2", - groupNames = {"group_1", "admin"}) - @Test - void testForceDeleteTaskIfNotCompleted() - throws TaskNotFoundException, InvalidStateException, NotAuthorizedException { - TaskService taskService = taskanaEngine.getTaskService(); - Task task = taskService.getTask("TKI:000000000000000000000000000000000027"); + @WithAccessId( + userName = "user_1_2", + groupNames = {"group_1", "admin"}) + @Test + void testForceDeleteTaskIfNotCompleted() + throws TaskNotFoundException, InvalidStateException, NotAuthorizedException { + TaskService taskService = taskanaEngine.getTaskService(); + Task task = taskService.getTask("TKI:000000000000000000000000000000000027"); - Assertions.assertThrows(InvalidStateException.class, () -> - taskService.deleteTask(task.getId()), "Should not be possible to delete claimed task without force flag"); + Assertions.assertThrows( + InvalidStateException.class, + () -> taskService.deleteTask(task.getId()), + "Should not be possible to delete claimed task without force flag"); - taskService.forceDeleteTask(task.getId()); + taskService.forceDeleteTask(task.getId()); - Assertions.assertThrows(TaskNotFoundException.class, () -> - taskService.getTask("TKI:000000000000000000000000000000000027")); - } + Assertions.assertThrows( + TaskNotFoundException.class, + () -> taskService.getTask("TKI:000000000000000000000000000000000027")); + } - @WithAccessId( - userName = "user_1_2", - groupNames = {"group_1"}) - @Test - void testBulkDeleteTask() - throws InvalidArgumentException { + @WithAccessId( + userName = "user_1_2", + groupNames = {"group_1"}) + @Test + void testBulkDeleteTask() throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); - ArrayList taskIdList = new ArrayList<>(); - taskIdList.add("TKI:000000000000000000000000000000000037"); - taskIdList.add("TKI:000000000000000000000000000000000038"); + TaskService taskService = taskanaEngine.getTaskService(); + ArrayList taskIdList = new ArrayList<>(); + taskIdList.add("TKI:000000000000000000000000000000000037"); + taskIdList.add("TKI:000000000000000000000000000000000038"); - BulkOperationResults results = taskService.deleteTasks(taskIdList); + BulkOperationResults results = taskService.deleteTasks(taskIdList); - assertFalse(results.containsErrors()); - Assertions.assertThrows(TaskNotFoundException.class, () -> - taskService.getTask("TKI:000000000000000000000000000000000038")); - } + assertFalse(results.containsErrors()); + Assertions.assertThrows( + TaskNotFoundException.class, + () -> taskService.getTask("TKI:000000000000000000000000000000000038")); + } - @WithAccessId( - userName = "user_1_2", - groupNames = {"group_1"}) - @Test - void testBulkDeleteTasksWithException() - throws TaskNotFoundException, InvalidArgumentException, NotAuthorizedException { + @WithAccessId( + userName = "user_1_2", + groupNames = {"group_1"}) + @Test + void testBulkDeleteTasksWithException() + throws TaskNotFoundException, InvalidArgumentException, NotAuthorizedException { - TaskService taskService = taskanaEngine.getTaskService(); - ArrayList taskIdList = new ArrayList<>(); - taskIdList.add("TKI:000000000000000000000000000000000039"); - taskIdList.add("TKI:000000000000000000000000000000000040"); - taskIdList.add("TKI:000000000000000000000000000000000028"); + TaskService taskService = taskanaEngine.getTaskService(); + ArrayList taskIdList = new ArrayList<>(); + taskIdList.add("TKI:000000000000000000000000000000000039"); + taskIdList.add("TKI:000000000000000000000000000000000040"); + taskIdList.add("TKI:000000000000000000000000000000000028"); - BulkOperationResults results = taskService.deleteTasks(taskIdList); + BulkOperationResults results = taskService.deleteTasks(taskIdList); - String expectedFailedId = "TKI:000000000000000000000000000000000028"; - assertTrue(results.containsErrors()); - List failedTaskIds = results.getFailedIds(); - assertEquals(1, failedTaskIds.size()); - assertEquals(expectedFailedId, failedTaskIds.get(0)); - assertSame(results.getErrorMap().get(expectedFailedId).getClass(), InvalidStateException.class); - - Task notDeletedTask = taskService.getTask("TKI:000000000000000000000000000000000028"); - assertNotNull(notDeletedTask); - Assertions.assertThrows(TaskNotFoundException.class, () -> - taskService.getTask("TKI:000000000000000000000000000000000040")); - - } + String expectedFailedId = "TKI:000000000000000000000000000000000028"; + assertTrue(results.containsErrors()); + List failedTaskIds = results.getFailedIds(); + assertEquals(1, failedTaskIds.size()); + assertEquals(expectedFailedId, failedTaskIds.get(0)); + assertSame(results.getErrorMap().get(expectedFailedId).getClass(), InvalidStateException.class); + Task notDeletedTask = taskService.getTask("TKI:000000000000000000000000000000000028"); + assertNotNull(notDeletedTask); + Assertions.assertThrows( + TaskNotFoundException.class, + () -> taskService.getTask("TKI:000000000000000000000000000000000040")); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/task/GetTaskAccTest.java b/lib/taskana-core/src/test/java/acceptance/task/GetTaskAccTest.java index b9f2c261a..b9cccc29c 100644 --- a/lib/taskana-core/src/test/java/acceptance/task/GetTaskAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/task/GetTaskAccTest.java @@ -5,13 +5,12 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import acceptance.AbstractAccTest; import java.util.HashMap; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.Task; import pro.taskana.TaskService; import pro.taskana.TaskState; @@ -21,79 +20,75 @@ import pro.taskana.exceptions.TaskNotFoundException; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "get task" scenarios. - */ - +/** Acceptance test for all "get task" scenarios. */ @ExtendWith(JAASExtension.class) class GetTaskAccTest extends AbstractAccTest { - GetTaskAccTest() { - super(); - } + GetTaskAccTest() { + super(); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testGetTaskById() - throws TaskNotFoundException, NotAuthorizedException, InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testGetTaskById() + throws TaskNotFoundException, NotAuthorizedException, InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); - Task task = taskService.getTask("TKI:000000000000000000000000000000000000"); + Task task = taskService.getTask("TKI:000000000000000000000000000000000000"); - assertNull(task.getCompleted()); - assertEquals("Task99", task.getName()); - assertEquals("creator_user_id", task.getCreator()); - assertEquals("Lorem ipsum was n Quatsch dolor sit amet.", task.getDescription()); - assertEquals("Some custom Note", task.getNote()); - assertEquals(1, task.getPriority()); - assertEquals(TaskState.CLAIMED, task.getState()); - assertEquals("MANUAL", task.getClassificationCategory()); - assertEquals("T2000", task.getClassificationSummary().getKey()); - assertEquals("CLI:100000000000000000000000000000000016", task.getClassificationSummary().getId()); - assertEquals("WBI:100000000000000000000000000000000006", task.getWorkbasketSummary().getId()); - assertEquals("USER_1_1", task.getWorkbasketKey()); - assertEquals("DOMAIN_A", task.getDomain()); - assertEquals("BPI21", task.getBusinessProcessId()); - assertEquals("PBPI21", task.getParentBusinessProcessId()); - assertEquals("user_1_1", task.getOwner()); - assertEquals("MyCompany1", task.getPrimaryObjRef().getCompany()); - assertEquals("MySystem1", task.getPrimaryObjRef().getSystem()); - assertEquals("MyInstance1", task.getPrimaryObjRef().getSystemInstance()); - assertEquals("MyType1", task.getPrimaryObjRef().getType()); - assertEquals("MyValue1", task.getPrimaryObjRef().getValue()); - assertTrue(task.isRead()); - assertFalse(task.isTransferred()); - assertEquals(new HashMap(), task.getCallbackInfo()); - assertEquals(new HashMap(), task.getCustomAttributes()); - assertEquals("custom1", task.getCustomAttribute("1")); - assertEquals("custom2", task.getCustomAttribute("2")); - assertEquals("custom3", task.getCustomAttribute("3")); - assertEquals("custom4", task.getCustomAttribute("4")); - assertEquals("custom5", task.getCustomAttribute("5")); - assertEquals("custom6", task.getCustomAttribute("6")); - assertEquals("custom7", task.getCustomAttribute("7")); - assertEquals("custom8", task.getCustomAttribute("8")); - assertEquals("custom9", task.getCustomAttribute("9")); - assertEquals("custom10", task.getCustomAttribute("10")); - assertEquals("custom11", task.getCustomAttribute("11")); - assertEquals("custom12", task.getCustomAttribute("12")); - assertEquals("custom13", task.getCustomAttribute("13")); - assertEquals("abc", task.getCustomAttribute("14")); - assertEquals("custom15", task.getCustomAttribute("15")); - assertEquals("custom16", task.getCustomAttribute("16")); - } + assertNull(task.getCompleted()); + assertEquals("Task99", task.getName()); + assertEquals("creator_user_id", task.getCreator()); + assertEquals("Lorem ipsum was n Quatsch dolor sit amet.", task.getDescription()); + assertEquals("Some custom Note", task.getNote()); + assertEquals(1, task.getPriority()); + assertEquals(TaskState.CLAIMED, task.getState()); + assertEquals("MANUAL", task.getClassificationCategory()); + assertEquals("T2000", task.getClassificationSummary().getKey()); + assertEquals( + "CLI:100000000000000000000000000000000016", task.getClassificationSummary().getId()); + assertEquals("WBI:100000000000000000000000000000000006", task.getWorkbasketSummary().getId()); + assertEquals("USER_1_1", task.getWorkbasketKey()); + assertEquals("DOMAIN_A", task.getDomain()); + assertEquals("BPI21", task.getBusinessProcessId()); + assertEquals("PBPI21", task.getParentBusinessProcessId()); + assertEquals("user_1_1", task.getOwner()); + assertEquals("MyCompany1", task.getPrimaryObjRef().getCompany()); + assertEquals("MySystem1", task.getPrimaryObjRef().getSystem()); + assertEquals("MyInstance1", task.getPrimaryObjRef().getSystemInstance()); + assertEquals("MyType1", task.getPrimaryObjRef().getType()); + assertEquals("MyValue1", task.getPrimaryObjRef().getValue()); + assertTrue(task.isRead()); + assertFalse(task.isTransferred()); + assertEquals(new HashMap(), task.getCallbackInfo()); + assertEquals(new HashMap(), task.getCustomAttributes()); + assertEquals("custom1", task.getCustomAttribute("1")); + assertEquals("custom2", task.getCustomAttribute("2")); + assertEquals("custom3", task.getCustomAttribute("3")); + assertEquals("custom4", task.getCustomAttribute("4")); + assertEquals("custom5", task.getCustomAttribute("5")); + assertEquals("custom6", task.getCustomAttribute("6")); + assertEquals("custom7", task.getCustomAttribute("7")); + assertEquals("custom8", task.getCustomAttribute("8")); + assertEquals("custom9", task.getCustomAttribute("9")); + assertEquals("custom10", task.getCustomAttribute("10")); + assertEquals("custom11", task.getCustomAttribute("11")); + assertEquals("custom12", task.getCustomAttribute("12")); + assertEquals("custom13", task.getCustomAttribute("13")); + assertEquals("abc", task.getCustomAttribute("14")); + assertEquals("custom15", task.getCustomAttribute("15")); + assertEquals("custom16", task.getCustomAttribute("16")); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testGetTaskByIdNotExisting() { - TaskService taskService = taskanaEngine.getTaskService(); - - Assertions.assertThrows(TaskNotFoundException.class, () -> - taskService.getTask("INVALID")); - } + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testGetTaskByIdNotExisting() { + TaskService taskService = taskanaEngine.getTaskService(); + Assertions.assertThrows(TaskNotFoundException.class, () -> taskService.getTask("INVALID")); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/task/QueryTaskByClassificationNameAccTest.java b/lib/taskana-core/src/test/java/acceptance/task/QueryTaskByClassificationNameAccTest.java index a1e1e2102..71617b0fc 100644 --- a/lib/taskana-core/src/test/java/acceptance/task/QueryTaskByClassificationNameAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/task/QueryTaskByClassificationNameAccTest.java @@ -3,12 +3,11 @@ package acceptance.task; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import acceptance.AbstractAccTest; import java.util.List; - import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.AttachmentSummary; import pro.taskana.BaseQuery.SortDirection; import pro.taskana.TaskQuery; @@ -19,164 +18,175 @@ import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; /** - * Acceptance test for the usecase of adding/removing an attachment of a task and update the result correctly. + * Acceptance test for the usecase of adding/removing an attachment of a task and update the result + * correctly. */ @ExtendWith(JAASExtension.class) class QueryTaskByClassificationNameAccTest extends AbstractAccTest { - private static SortDirection asc = SortDirection.ASCENDING; - private static SortDirection desc = SortDirection.DESCENDING; + private static SortDirection asc = SortDirection.ASCENDING; + private static SortDirection desc = SortDirection.DESCENDING; - QueryTaskByClassificationNameAccTest() { - super(); - } + QueryTaskByClassificationNameAccTest() { + super(); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"admin"}) - @Test - void testQueryTaskValuesForAttachmentClassificationName() { - TaskService taskService = taskanaEngine.getTaskService(); - List columnValueList = taskService.createTaskQuery() + @WithAccessId( + userName = "teamlead_1", + groupNames = {"admin"}) + @Test + void testQueryTaskValuesForAttachmentClassificationName() { + TaskService taskService = taskanaEngine.getTaskService(); + List columnValueList = + taskService + .createTaskQuery() .ownerLike("%user%") .orderByOwner(desc) .listValues(TaskQueryColumnName.A_CLASSIFICATION_NAME, null); - assertNotNull(columnValueList); - assertEquals(8, columnValueList.size()); - } + assertNotNull(columnValueList); + assertEquals(8, columnValueList.size()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"admin"}) - @Test - void testQueryTaskValuesForClassificationName() { - TaskService taskService = taskanaEngine.getTaskService(); - List columnValueList = taskService.createTaskQuery() + @WithAccessId( + userName = "teamlead_1", + groupNames = {"admin"}) + @Test + void testQueryTaskValuesForClassificationName() { + TaskService taskService = taskanaEngine.getTaskService(); + List columnValueList = + taskService + .createTaskQuery() .ownerLike("%user%") .orderByClassificationName(asc) .listValues(TaskQueryColumnName.CLASSIFICATION_NAME, null); - assertNotNull(columnValueList); - assertEquals(5, columnValueList.size()); - } + assertNotNull(columnValueList); + assertEquals(5, columnValueList.size()); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testQueryByClassificationNameIn() { - TaskService taskService = taskanaEngine.getTaskService(); - List tasks = taskService.createTaskQuery() - .classificationNameIn("Dynamik-Ablehnung") - .list(); - assertEquals(1, tasks.size()); + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testQueryByClassificationNameIn() { + TaskService taskService = taskanaEngine.getTaskService(); + List tasks = + taskService.createTaskQuery().classificationNameIn("Dynamik-Ablehnung").list(); + assertEquals(1, tasks.size()); - List attachmentSummaries = tasks.get(0).getAttachmentSummaries(); - assertNotNull(attachmentSummaries); - assertEquals(2, attachmentSummaries.size()); + List attachmentSummaries = tasks.get(0).getAttachmentSummaries(); + assertNotNull(attachmentSummaries); + assertEquals(2, attachmentSummaries.size()); - tasks = taskService.createTaskQuery() + tasks = + taskService + .createTaskQuery() .classificationNameIn("Dynamik-Ablehnung") .orderByClassificationName(SortDirection.ASCENDING) .list(); - assertEquals(1, tasks.size()); - } + assertEquals(1, tasks.size()); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testQueryByClassificationNameLike() { - TaskService taskService = taskanaEngine.getTaskService(); - List tasks = taskService.createTaskQuery() + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testQueryByClassificationNameLike() { + TaskService taskService = taskanaEngine.getTaskService(); + List tasks = + taskService + .createTaskQuery() .classificationNameLike("Dynamik%", "Widerruf") .orderByClassificationName(SortDirection.ASCENDING) .list(); - assertEquals(22, tasks.size()); + assertEquals(22, tasks.size()); - // without sort, the same number of tasks should be returned - tasks = taskService.createTaskQuery() - .classificationNameLike("Dynamik%", "Widerruf") - .list(); - assertEquals(22, tasks.size()); - } + // without sort, the same number of tasks should be returned + tasks = taskService.createTaskQuery().classificationNameLike("Dynamik%", "Widerruf").list(); + assertEquals(22, tasks.size()); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testSelectByAttachmentClassificationNameLike() { - TaskService taskService = taskanaEngine.getTaskService(); - // find Task with attachment classification names - List tasks = taskService.createTaskQuery() + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testSelectByAttachmentClassificationNameLike() { + TaskService taskService = taskanaEngine.getTaskService(); + // find Task with attachment classification names + List tasks = + taskService + .createTaskQuery() .attachmentClassificationNameLike("Widerruf", "Beratungsprotokoll", "Dynamik%") .orderByAttachmentClassificationName(SortDirection.ASCENDING) .list(); - assertEquals(7, tasks.size()); - // make sure that unordered query returns the same number of objects - tasks = taskService.createTaskQuery() + assertEquals(7, tasks.size()); + // make sure that unordered query returns the same number of objects + tasks = + taskService + .createTaskQuery() .attachmentClassificationNameLike("Widerruf", "Beratungsprotokoll", "Dynamik%") .list(); - assertEquals(7, tasks.size()); + assertEquals(7, tasks.size()); + } - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testSelectByAttachmentClassificationNameIn() { - TaskService taskService = taskanaEngine.getTaskService(); - // find Task with attachment classification names - List tasks = taskService.createTaskQuery() + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testSelectByAttachmentClassificationNameIn() { + TaskService taskService = taskanaEngine.getTaskService(); + // find Task with attachment classification names + List tasks = + taskService + .createTaskQuery() .attachmentClassificationNameIn("Widerruf", "Beratungsprotokoll", "Dynamikänderung") .orderByAttachmentClassificationName(SortDirection.ASCENDING) .list(); - assertEquals(4, tasks.size()); - // make sure that unordered query returns the same number of objects - tasks = taskService.createTaskQuery() + assertEquals(4, tasks.size()); + // make sure that unordered query returns the same number of objects + tasks = + taskService + .createTaskQuery() .attachmentClassificationNameIn("Widerruf", "Beratungsprotokoll", "Dynamikänderung") .list(); - assertEquals(4, tasks.size()); + assertEquals(4, tasks.size()); + } - } + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testQueryAndCountMatchForClassificationName() { + TaskService taskService = taskanaEngine.getTaskService(); + TaskQuery taskQuery = taskService.createTaskQuery(); + List tasks = + taskQuery.classificationNameIn("Widerruf", "Beratungsprotokoll", "Dynamikänderung").list(); + long numberOfTasks = + taskQuery.classificationNameIn("Widerruf", "Beratungsprotokoll", "Dynamikänderung").count(); + assertEquals(numberOfTasks, tasks.size()); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testQueryAndCountMatchForClassificationName() { - TaskService taskService = taskanaEngine.getTaskService(); - TaskQuery taskQuery = taskService.createTaskQuery(); - List tasks = taskQuery - .classificationNameIn("Widerruf", "Beratungsprotokoll", "Dynamikänderung") - .list(); - long numberOfTasks = taskQuery - .classificationNameIn("Widerruf", "Beratungsprotokoll", "Dynamikänderung") - .count(); - assertEquals(numberOfTasks, tasks.size()); - - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testQueryAndCountForAttachmentClassificationName() { - TaskService taskService = taskanaEngine.getTaskService(); - TaskQuery taskQuery = taskService.createTaskQuery(); - List tasks = taskQuery + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testQueryAndCountForAttachmentClassificationName() { + TaskService taskService = taskanaEngine.getTaskService(); + TaskQuery taskQuery = taskService.createTaskQuery(); + List tasks = + taskQuery .attachmentClassificationNameIn("Widerruf", "Beratungsprotokoll", "Dynamikänderung") .list(); - // we expect 4 result objects in this case, because task TKI:000000000000000000000000000000000001 has 2 attachments with different Classifications - // therefore task TKI:000000000000000000000000000000000001 occurs twice in the result set - assertEquals(4, tasks.size()); - long numberOfTasks = taskQuery + // we expect 4 result objects in this case, because task + // TKI:000000000000000000000000000000000001 has 2 attachments with different Classifications + // therefore task TKI:000000000000000000000000000000000001 occurs twice in the result set + assertEquals(4, tasks.size()); + long numberOfTasks = + taskQuery .attachmentClassificationNameIn("Widerruf", "Beratungsprotokoll", "Dynamikänderung") .count(); - assertEquals(3, numberOfTasks); - // the count returns only the number of tasks that have an attachment with the specified classification name. - // therefore, task 001 is counted only once. - } - + assertEquals(3, numberOfTasks); + // the count returns only the number of tasks that have an attachment with the specified + // classification name. + // therefore, task 001 is counted only once. + } } - diff --git a/lib/taskana-core/src/test/java/acceptance/task/QueryTaskWithAttachment.java b/lib/taskana-core/src/test/java/acceptance/task/QueryTaskWithAttachment.java index 8eee06b5c..2f5edb30b 100644 --- a/lib/taskana-core/src/test/java/acceptance/task/QueryTaskWithAttachment.java +++ b/lib/taskana-core/src/test/java/acceptance/task/QueryTaskWithAttachment.java @@ -5,12 +5,11 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import acceptance.AbstractAccTest; import java.util.List; - import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.Attachment; import pro.taskana.AttachmentSummary; import pro.taskana.Task; @@ -23,134 +22,150 @@ import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; /** - * Acceptance test for the usecase of adding/removing an attachment of a task and update the result correctly. + * Acceptance test for the usecase of adding/removing an attachment of a task and update the result + * correctly. */ @ExtendWith(JAASExtension.class) class QueryTaskWithAttachment extends AbstractAccTest { - QueryTaskWithAttachment() { - super(); + QueryTaskWithAttachment() { + super(); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testGetAttachmentSummariesFromTask() { + TaskService taskService = taskanaEngine.getTaskService(); + List tasks = taskService.createTaskQuery().classificationKeyIn("L110102").list(); + assertEquals(1, tasks.size()); + + List attachmentSummaries = tasks.get(0).getAttachmentSummaries(); + assertNotNull(attachmentSummaries); + assertEquals(2, attachmentSummaries.size()); + } + + @WithAccessId(userName = "user_1_2") + @Test + void testGetNoAttachmentSummaryFromTask() { + TaskService taskService = taskanaEngine.getTaskService(); + List tasks = taskService.createTaskQuery().list(); + assertEquals(20, tasks.size()); + + List attachmentSummaries = tasks.get(0).getAttachmentSummaries(); + assertNotNull(attachmentSummaries); + assertTrue(attachmentSummaries.isEmpty()); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testIfNewTaskHasEmptyAttachmentList() { + TaskService taskService = taskanaEngine.getTaskService(); + Task task = taskService.newTask("WBI:100000000000000000000000000000000006"); + assertNotNull(task.getAttachments()); + assertNotNull(task.asSummary().getAttachmentSummaries()); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testIfAttachmentSummariesAreCorrectUsingTaskQueryAndGetTaskById() + throws TaskNotFoundException, NotAuthorizedException { + TaskService taskService = taskanaEngine.getTaskService(); + // find Task with ID TKI:00...00 + List tasks = + taskService.createTaskQuery().idIn("TKI:000000000000000000000000000000000000").list(); + assertEquals(1, tasks.size()); + List queryAttachmentSummaries = tasks.get(0).getAttachmentSummaries(); + + Task originalTask = taskService.getTask("TKI:000000000000000000000000000000000000"); + List originalAttachments = originalTask.getAttachments(); + + assertEquals(originalAttachments.size(), queryAttachmentSummaries.size()); + + for (int i = 0; i < queryAttachmentSummaries.size(); i++) { + // Test if it's the Summary of the Original Attachment + assertEquals(originalAttachments.get(i).asSummary(), queryAttachmentSummaries.get(i)); + // Test if the values are correct + assertEquals( + originalAttachments.get(i).getChannel(), queryAttachmentSummaries.get(i).getChannel()); + assertEquals( + originalAttachments.get(i).getClassificationSummary(), + queryAttachmentSummaries.get(i).getClassificationSummary()); + assertEquals( + originalAttachments.get(i).getCreated(), queryAttachmentSummaries.get(i).getCreated()); + assertEquals(originalAttachments.get(i).getId(), queryAttachmentSummaries.get(i).getId()); + assertEquals( + originalAttachments.get(i).getModified(), queryAttachmentSummaries.get(i).getModified()); + assertEquals( + originalAttachments.get(i).getObjectReference(), + queryAttachmentSummaries.get(i).getObjectReference()); + assertEquals( + originalAttachments.get(i).getReceived(), queryAttachmentSummaries.get(i).getReceived()); + assertEquals( + originalAttachments.get(i).getTaskId(), queryAttachmentSummaries.get(i).getTaskId()); + + // Verify that they're not the same Object + assertNotEquals( + originalAttachments.get(i).hashCode(), queryAttachmentSummaries.get(i).hashCode()); + assertNotEquals( + originalAttachments.get(i).getClass(), queryAttachmentSummaries.get(i).getClass()); } + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testGetAttachmentSummariesFromTask() { - TaskService taskService = taskanaEngine.getTaskService(); - List tasks = taskService.createTaskQuery() - .classificationKeyIn("L110102") - .list(); - assertEquals(1, tasks.size()); - - List attachmentSummaries = tasks.get(0).getAttachmentSummaries(); - assertNotNull(attachmentSummaries); - assertEquals(2, attachmentSummaries.size()); - } - - @WithAccessId( - userName = "user_1_2") - @Test - void testGetNoAttachmentSummaryFromTask() { - TaskService taskService = taskanaEngine.getTaskService(); - List tasks = taskService.createTaskQuery() - .list(); - assertEquals(20, tasks.size()); - - List attachmentSummaries = tasks.get(0).getAttachmentSummaries(); - assertNotNull(attachmentSummaries); - assertTrue(attachmentSummaries.isEmpty()); - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testIfNewTaskHasEmptyAttachmentList() { - TaskService taskService = taskanaEngine.getTaskService(); - Task task = taskService.newTask("WBI:100000000000000000000000000000000006"); - assertNotNull(task.getAttachments()); - assertNotNull(task.asSummary().getAttachmentSummaries()); - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testIfAttachmentSummariesAreCorrectUsingTaskQueryAndGetTaskById() - throws TaskNotFoundException, NotAuthorizedException { - TaskService taskService = taskanaEngine.getTaskService(); - // find Task with ID TKI:00...00 - List tasks = taskService.createTaskQuery() - .idIn("TKI:000000000000000000000000000000000000") - .list(); - assertEquals(1, tasks.size()); - List queryAttachmentSummaries = tasks.get(0).getAttachmentSummaries(); - - Task originalTask = taskService.getTask("TKI:000000000000000000000000000000000000"); - List originalAttachments = originalTask.getAttachments(); - - assertEquals(originalAttachments.size(), queryAttachmentSummaries.size()); - - for (int i = 0; i < queryAttachmentSummaries.size(); i++) { - // Test if it's the Summary of the Original Attachment - assertEquals(originalAttachments.get(i).asSummary(), queryAttachmentSummaries.get(i)); - // Test if the values are correct - assertEquals(originalAttachments.get(i).getChannel(), queryAttachmentSummaries.get(i).getChannel()); - assertEquals(originalAttachments.get(i).getClassificationSummary(), - queryAttachmentSummaries.get(i).getClassificationSummary()); - assertEquals(originalAttachments.get(i).getCreated(), queryAttachmentSummaries.get(i).getCreated()); - assertEquals(originalAttachments.get(i).getId(), queryAttachmentSummaries.get(i).getId()); - assertEquals(originalAttachments.get(i).getModified(), queryAttachmentSummaries.get(i).getModified()); - assertEquals(originalAttachments.get(i).getObjectReference(), - queryAttachmentSummaries.get(i).getObjectReference()); - assertEquals(originalAttachments.get(i).getReceived(), queryAttachmentSummaries.get(i).getReceived()); - assertEquals(originalAttachments.get(i).getTaskId(), queryAttachmentSummaries.get(i).getTaskId()); - - // Verify that they're not the same Object - assertNotEquals(originalAttachments.get(i).hashCode(), queryAttachmentSummaries.get(i).hashCode()); - assertNotEquals(originalAttachments.get(i).getClass(), queryAttachmentSummaries.get(i).getClass()); - } - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testIfAttachmentSummariesAreCorrect() - throws InvalidArgumentException, TaskNotFoundException, NotAuthorizedException { - TaskService taskService = taskanaEngine.getTaskService(); - // find Task with ID TKI:00...00 - List tasks = taskService.createTaskQuery() + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testIfAttachmentSummariesAreCorrect() + throws InvalidArgumentException, TaskNotFoundException, NotAuthorizedException { + TaskService taskService = taskanaEngine.getTaskService(); + // find Task with ID TKI:00...00 + List tasks = + taskService + .createTaskQuery() .classificationKeyIn("T2000") .customAttributeIn("1", "custom1") .list(); - assertEquals(1, tasks.size()); - List queryAttachmentSummaries = tasks.get(0).getAttachmentSummaries(); + assertEquals(1, tasks.size()); + List queryAttachmentSummaries = tasks.get(0).getAttachmentSummaries(); - Task originalTask = taskService.getTask("TKI:000000000000000000000000000000000000"); - List originalAttachments = originalTask.getAttachments(); + Task originalTask = taskService.getTask("TKI:000000000000000000000000000000000000"); + List originalAttachments = originalTask.getAttachments(); - assertEquals(originalAttachments.size(), queryAttachmentSummaries.size()); + assertEquals(originalAttachments.size(), queryAttachmentSummaries.size()); - for (int i = 0; i < queryAttachmentSummaries.size(); i++) { - // Test if it's the Summary of the Original Attachment - assertEquals(originalAttachments.get(i).asSummary(), queryAttachmentSummaries.get(i)); - // Test if the values are correct - assertEquals(originalAttachments.get(i).getChannel(), queryAttachmentSummaries.get(i).getChannel()); - assertEquals(originalAttachments.get(i).getClassificationSummary(), - queryAttachmentSummaries.get(i).getClassificationSummary()); - assertEquals(originalAttachments.get(i).getCreated(), queryAttachmentSummaries.get(i).getCreated()); - assertEquals(originalAttachments.get(i).getId(), queryAttachmentSummaries.get(i).getId()); - assertEquals(originalAttachments.get(i).getModified(), queryAttachmentSummaries.get(i).getModified()); - assertEquals(originalAttachments.get(i).getObjectReference(), - queryAttachmentSummaries.get(i).getObjectReference()); - assertEquals(originalAttachments.get(i).getReceived(), queryAttachmentSummaries.get(i).getReceived()); - assertEquals(originalAttachments.get(i).getTaskId(), queryAttachmentSummaries.get(i).getTaskId()); + for (int i = 0; i < queryAttachmentSummaries.size(); i++) { + // Test if it's the Summary of the Original Attachment + assertEquals(originalAttachments.get(i).asSummary(), queryAttachmentSummaries.get(i)); + // Test if the values are correct + assertEquals( + originalAttachments.get(i).getChannel(), queryAttachmentSummaries.get(i).getChannel()); + assertEquals( + originalAttachments.get(i).getClassificationSummary(), + queryAttachmentSummaries.get(i).getClassificationSummary()); + assertEquals( + originalAttachments.get(i).getCreated(), queryAttachmentSummaries.get(i).getCreated()); + assertEquals(originalAttachments.get(i).getId(), queryAttachmentSummaries.get(i).getId()); + assertEquals( + originalAttachments.get(i).getModified(), queryAttachmentSummaries.get(i).getModified()); + assertEquals( + originalAttachments.get(i).getObjectReference(), + queryAttachmentSummaries.get(i).getObjectReference()); + assertEquals( + originalAttachments.get(i).getReceived(), queryAttachmentSummaries.get(i).getReceived()); + assertEquals( + originalAttachments.get(i).getTaskId(), queryAttachmentSummaries.get(i).getTaskId()); - // Verify that they're not the same Object - assertNotEquals(originalAttachments.get(i).hashCode(), queryAttachmentSummaries.get(i).hashCode()); - assertNotEquals(originalAttachments.get(i).getClass(), queryAttachmentSummaries.get(i).getClass()); - } + // Verify that they're not the same Object + assertNotEquals( + originalAttachments.get(i).hashCode(), queryAttachmentSummaries.get(i).hashCode()); + assertNotEquals( + originalAttachments.get(i).getClass(), queryAttachmentSummaries.get(i).getClass()); } + } } diff --git a/lib/taskana-core/src/test/java/acceptance/task/QueryTasksAccTest.java b/lib/taskana-core/src/test/java/acceptance/task/QueryTasksAccTest.java index 05afe8dde..0f145c6a4 100644 --- a/lib/taskana-core/src/test/java/acceptance/task/QueryTasksAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/task/QueryTasksAccTest.java @@ -15,11 +15,11 @@ import static pro.taskana.TaskQueryColumnName.CLASSIFICATION_KEY; import static pro.taskana.TaskQueryColumnName.OWNER; import static pro.taskana.TaskQueryColumnName.STATE; +import acceptance.AbstractAccTest; import java.sql.SQLException; import java.util.Arrays; import java.util.List; import java.util.Map; - import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSession; import org.junit.jupiter.api.Assertions; @@ -27,7 +27,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.Attachment; import pro.taskana.Task; import pro.taskana.TaskQuery; @@ -49,1436 +48,1406 @@ import pro.taskana.mappings.TaskTestMapper; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "query tasks with sorting" scenarios. - */ +/** Acceptance test for all "query tasks with sorting" scenarios. */ @ExtendWith(JAASExtension.class) class QueryTasksAccTest extends AbstractAccTest { - @BeforeEach - void before() throws SQLException { - //required if single tests modify database - //TODO split test class into readOnly & modifying tests to improve performance - resetDb(false); - } + @BeforeEach + void before() throws SQLException { + // required if single tests modify database + // TODO split test class into readOnly & modifying tests to improve performance + resetDb(false); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"admin"}) - @Test - void testQueryTaskValuesForEveryColumn() { - TaskService taskService = taskanaEngine.getTaskService(); - assertAll(() -> Arrays.stream(TaskQueryColumnName.values()).forEach(columnName -> - Assertions.assertDoesNotThrow(() -> taskService.createTaskQuery().listValues(columnName, ASCENDING), - "Column is not working " + columnName) - )); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"admin"}) + @Test + void testQueryTaskValuesForEveryColumn() { + TaskService taskService = taskanaEngine.getTaskService(); + assertAll( + () -> + Arrays.stream(TaskQueryColumnName.values()) + .forEach( + columnName -> + Assertions.assertDoesNotThrow( + () -> taskService.createTaskQuery().listValues(columnName, ASCENDING), + "Column is not working " + columnName))); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"admin"}) - @Test - void testQueryTaskValuesForColumnName() { - TaskService taskService = taskanaEngine.getTaskService(); - List columnValueList = taskService.createTaskQuery() + @WithAccessId( + userName = "teamlead_1", + groupNames = {"admin"}) + @Test + void testQueryTaskValuesForColumnName() { + TaskService taskService = taskanaEngine.getTaskService(); + List columnValueList = + taskService + .createTaskQuery() .ownerLike("%user%") .orderByOwner(DESCENDING) .listValues(OWNER, null); - assertNotNull(columnValueList); - assertEquals(3, columnValueList.size()); + assertNotNull(columnValueList); + assertEquals(3, columnValueList.size()); - columnValueList = taskService.createTaskQuery() - .listValues(STATE, null); - assertNotNull(columnValueList); - assertEquals(3, columnValueList.size()); - } + columnValueList = taskService.createTaskQuery().listValues(STATE, null); + assertNotNull(columnValueList); + assertEquals(3, columnValueList.size()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"admin"}) - @Test - void testQueryTaskValuesForColumnNameOnAttachments() { - TaskService taskService = taskanaEngine.getTaskService(); - List columnValueList = taskService.createTaskQuery() + @WithAccessId( + userName = "teamlead_1", + groupNames = {"admin"}) + @Test + void testQueryTaskValuesForColumnNameOnAttachments() { + TaskService taskService = taskanaEngine.getTaskService(); + List columnValueList = + taskService + .createTaskQuery() .attachmentReferenceValueIn("val4") .listValues(A_CHANNEL, null); - assertNotNull(columnValueList); - assertEquals(2, columnValueList.size()); + assertNotNull(columnValueList); + assertEquals(2, columnValueList.size()); - columnValueList = taskService.createTaskQuery() + columnValueList = + taskService + .createTaskQuery() .attachmentReferenceValueLike("%") .listValues(A_REF_VALUE, null); - assertNotNull(columnValueList); - assertEquals(6, columnValueList.size()); + assertNotNull(columnValueList); + assertEquals(6, columnValueList.size()); - columnValueList = taskService.createTaskQuery() + columnValueList = + taskService + .createTaskQuery() .orderByAttachmentClassificationId(DESCENDING) .listValues(A_CLASSIFICATION_ID, null); - assertNotNull(columnValueList); - assertEquals(12, columnValueList.size()); + assertNotNull(columnValueList); + assertEquals(12, columnValueList.size()); - columnValueList = taskService.createTaskQuery() + columnValueList = + taskService + .createTaskQuery() .orderByClassificationKey(DESCENDING) .listValues(CLASSIFICATION_KEY, null); - assertNotNull(columnValueList); - assertEquals(6, columnValueList.size()); + assertNotNull(columnValueList); + assertEquals(6, columnValueList.size()); + } + + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "group_2"}) + @Test + void testQueryForOwnerLike() { + TaskService taskService = taskanaEngine.getTaskService(); + + List results = + taskService.createTaskQuery().ownerLike("%a%", "%u%").orderByCreated(ASCENDING).list(); + + assertThat(results.size(), equalTo(25)); + TaskSummary previousSummary = null; + for (TaskSummary taskSummary : results) { + if (previousSummary != null) { + assertFalse(previousSummary.getCreated().isAfter(taskSummary.getCreated())); + } + previousSummary = taskSummary; + } + } + + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "group_2"}) + @Test + void testQueryForParentBusinessProcessId() { + TaskService taskService = taskanaEngine.getTaskService(); + + List results = + taskService.createTaskQuery().parentBusinessProcessIdLike("%PBPI%", "doc%3%").list(); + assertThat(results.size(), equalTo(24)); + for (TaskSummary taskSummary : results) { + assertNotNull(taskSummary.getExternalId()); } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "group_2"}) - @Test - void testQueryForOwnerLike() { - TaskService taskService = taskanaEngine.getTaskService(); + String[] parentIds = + results.stream().map(TaskSummary::getParentBusinessProcessId).toArray(String[]::new); - List results = taskService.createTaskQuery() - .ownerLike("%a%", "%u%") - .orderByCreated(ASCENDING) - .list(); + List result2 = + taskService.createTaskQuery().parentBusinessProcessIdIn(parentIds).list(); + assertThat(result2.size(), equalTo(24)); + } - assertThat(results.size(), equalTo(25)); - TaskSummary previousSummary = null; - for (TaskSummary taskSummary : results) { - if (previousSummary != null) { - assertFalse(previousSummary.getCreated().isAfter(taskSummary.getCreated())); - } - previousSummary = taskSummary; - } - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "group_2"}) + @Test + void testQueryForName() { + TaskService taskService = taskanaEngine.getTaskService(); - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "group_2"}) - @Test - void testQueryForParentBusinessProcessId() { - TaskService taskService = taskanaEngine.getTaskService(); + List results = taskService.createTaskQuery().nameLike("task%").list(); + assertThat(results.size(), equalTo(6)); - List results = taskService.createTaskQuery() - .parentBusinessProcessIdLike("%PBPI%", "doc%3%") - .list(); - assertThat(results.size(), equalTo(24)); - for (TaskSummary taskSummary : results) { - assertNotNull(taskSummary.getExternalId()); - } + String[] ids = results.stream().map(TaskSummary::getName).toArray(String[]::new); - String[] parentIds = results.stream() - .map(TaskSummary::getParentBusinessProcessId) - .toArray(String[]::new); + List result2 = taskService.createTaskQuery().nameIn(ids).list(); + assertThat(result2.size(), equalTo(6)); + } - List result2 = taskService.createTaskQuery() - .parentBusinessProcessIdIn(parentIds) - .list(); - assertThat(result2.size(), equalTo(24)); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "group_2"}) + @Test + void testQueryForClassificationKey() { + TaskService taskService = taskanaEngine.getTaskService(); - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "group_2"}) - @Test - void testQueryForName() { - TaskService taskService = taskanaEngine.getTaskService(); + List results = taskService.createTaskQuery().classificationKeyLike("L10%").list(); + assertThat(results.size(), equalTo(67)); - List results = taskService.createTaskQuery() - .nameLike("task%") - .list(); - assertThat(results.size(), equalTo(6)); + String[] ids = + results.stream().map(t -> t.getClassificationSummary().getKey()).toArray(String[]::new); - String[] ids = results.stream() - .map(TaskSummary::getName) - .toArray(String[]::new); + List result2 = taskService.createTaskQuery().classificationKeyIn(ids).list(); + assertThat(result2.size(), equalTo(67)); - List result2 = taskService.createTaskQuery() - .nameIn(ids) - .list(); - assertThat(result2.size(), equalTo(6)); - } + List result3 = + taskService.createTaskQuery().classificationKeyNotIn("T2100", "T2000").list(); + assertThat(result3.size(), equalTo(71)); - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "group_2"}) - @Test - void testQueryForClassificationKey() { - TaskService taskService = taskanaEngine.getTaskService(); + List result4 = + taskService.createTaskQuery().classificationKeyNotIn("L1050", "L1060", "T2100").list(); + assertThat(result4.size(), equalTo(6)); + } - List results = taskService.createTaskQuery() - .classificationKeyLike("L10%") - .list(); - assertThat(results.size(), equalTo(67)); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryForAttachmentInSummary() + throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, + TaskNotFoundException, ConcurrencyException, AttachmentPersistenceException { + TaskService taskService = taskanaEngine.getTaskService(); - String[] ids = results.stream() - .map(t -> t.getClassificationSummary().getKey()) - .toArray(String[]::new); - - List result2 = taskService.createTaskQuery() - .classificationKeyIn(ids) - .list(); - assertThat(result2.size(), equalTo(67)); - - List result3 = taskService.createTaskQuery() - .classificationKeyNotIn("T2100", "T2000") - .list(); - assertThat(result3.size(), equalTo(71)); - - List result4 = taskService.createTaskQuery() - .classificationKeyNotIn("L1050", "L1060", "T2100") - .list(); - assertThat(result4.size(), equalTo(6)); - } - - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryForAttachmentInSummary() - throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, - TaskNotFoundException, ConcurrencyException, AttachmentPersistenceException { - TaskService taskService = taskanaEngine.getTaskService(); - - Attachment attachment = createAttachment("DOCTYPE_DEFAULT", // prio 99, SL P2000D - createObjectReference("COMPANY_A", "SYSTEM_B", "INSTANCE_B", "ArchivETI", + Attachment attachment = + createAttachment( + "DOCTYPE_DEFAULT", // prio 99, SL P2000D + createObjectReference( + "COMPANY_A", + "SYSTEM_B", + "INSTANCE_B", + "ArchivETI", "12345678901234567890123456789012345678901234567890"), - "E-MAIL", "2018-01-15", createSimpleCustomProperties(3)); + "E-MAIL", + "2018-01-15", + createSimpleCustomProperties(3)); - Task task = taskService.getTask("TKI:000000000000000000000000000000000000"); - task.addAttachment(attachment); - taskService.updateTask(task); + Task task = taskService.getTask("TKI:000000000000000000000000000000000000"); + task.addAttachment(attachment); + taskService.updateTask(task); - List results = taskService.createTaskQuery() - .idIn("TKI:000000000000000000000000000000000000") + List results = + taskService.createTaskQuery().idIn("TKI:000000000000000000000000000000000000").list(); + assertThat(results.size(), equalTo(1)); + assertThat(results.get(0).getAttachmentSummaries().size(), equalTo(3)); + assertNotNull(results.get(0).getAttachmentSummaries().get(0)); + } + + @WithAccessId( + userName = "teamlead_1", + groupNames = {"admin"}) + @Test + void testQueryForExternalId() { + TaskService taskService = taskanaEngine.getTaskService(); + + List results = + taskService + .createTaskQuery() + .externalIdIn( + "ETI:000000000000000000000000000000000000", + "ETI:000000000000000000000000000000000001") .list(); - assertThat(results.size(), equalTo(1)); - assertThat(results.get(0).getAttachmentSummaries().size(), equalTo(3)); - assertNotNull(results.get(0).getAttachmentSummaries().get(0)); - } + assertThat(results.size(), equalTo(2)); - @WithAccessId( - userName = "teamlead_1", - groupNames = {"admin"}) - @Test - void testQueryForExternalId() { - TaskService taskService = taskanaEngine.getTaskService(); - - List results = taskService.createTaskQuery() - .externalIdIn("ETI:000000000000000000000000000000000000", "ETI:000000000000000000000000000000000001") - .list(); - assertThat(results.size(), equalTo(2)); - - List resultValues = taskService.createTaskQuery() + List resultValues = + taskService + .createTaskQuery() .externalIdLike("ETI:000000000000000000000000000000%") .listValues(TaskQueryColumnName.EXTERNAL_ID, DESCENDING); - assertThat(resultValues.size(), equalTo(70)); + assertThat(resultValues.size(), equalTo(70)); - long countAllExternalIds = taskService.createTaskQuery() - .externalIdLike("ETI:%") - .count(); - long countAllIds = taskService.createTaskQuery().count(); - assertEquals(countAllIds, countAllExternalIds); - } + long countAllExternalIds = taskService.createTaskQuery().externalIdLike("ETI:%").count(); + long countAllIds = taskService.createTaskQuery().count(); + assertEquals(countAllIds, countAllExternalIds); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryForCustom1() - throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryForCustom1() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + List results = + taskService + .createTaskQuery() .customAttributeLike("1", "custom%", "p%", "%xyz%", "efg") .list(); - assertThat(results.size(), equalTo(3)); + assertThat(results.size(), equalTo(3)); - String[] ids = results.stream() - .map(t -> { - try { + String[] ids = + results.stream() + .map( + t -> { + try { return t.getCustomAttribute("1"); - } catch (InvalidArgumentException e) { + } catch (InvalidArgumentException e) { e.printStackTrace(); return ""; - } - }).toArray(String[]::new); + } + }) + .toArray(String[]::new); - List result2 = taskService.createTaskQuery() - .customAttributeIn("1", ids) - .list(); - assertThat(result2.size(), equalTo(3)); - } + List result2 = taskService.createTaskQuery().customAttributeIn("1", ids).list(); + assertThat(result2.size(), equalTo(3)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryForCustom2() - throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryForCustom2() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .customAttributeLike("2", "custom%", "a%") - .list(); - assertThat(results.size(), equalTo(2)); + List results = + taskService.createTaskQuery().customAttributeLike("2", "custom%", "a%").list(); + assertThat(results.size(), equalTo(2)); - String[] ids = results.stream() - .map(t -> { - try { + String[] ids = + results.stream() + .map( + t -> { + try { return t.getCustomAttribute("2"); - } catch (InvalidArgumentException e) { + } catch (InvalidArgumentException e) { e.printStackTrace(); return ""; - } - }).toArray(String[]::new); + } + }) + .toArray(String[]::new); - List result2 = taskService.createTaskQuery() - .customAttributeIn("2", ids) - .list(); - assertThat(result2.size(), equalTo(2)); - } + List result2 = taskService.createTaskQuery().customAttributeIn("2", ids).list(); + assertThat(result2.size(), equalTo(2)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryForCustom3() - throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryForCustom3() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .customAttributeLike("3", "ffg") - .list(); - assertThat(results.size(), equalTo(1)); + List results = + taskService.createTaskQuery().customAttributeLike("3", "ffg").list(); + assertThat(results.size(), equalTo(1)); - String[] ids = results.stream() - .map(t -> { - try { + String[] ids = + results.stream() + .map( + t -> { + try { return t.getCustomAttribute("3"); - } catch (InvalidArgumentException e) { + } catch (InvalidArgumentException e) { e.printStackTrace(); return ""; - } - }).toArray(String[]::new); + } + }) + .toArray(String[]::new); - List result2 = taskService.createTaskQuery() - .customAttributeIn("3", ids) - .list(); - assertThat(result2.size(), equalTo(1)); - } + List result2 = taskService.createTaskQuery().customAttributeIn("3", ids).list(); + assertThat(result2.size(), equalTo(1)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryForCustom4() - throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryForCustom4() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .customAttributeLike("4", "%ust%", "%ty") - .list(); - assertThat(results.size(), equalTo(2)); + List results = + taskService.createTaskQuery().customAttributeLike("4", "%ust%", "%ty").list(); + assertThat(results.size(), equalTo(2)); - String[] ids = results.stream() - .map(t -> { - try { + String[] ids = + results.stream() + .map( + t -> { + try { return t.getCustomAttribute("4"); - } catch (InvalidArgumentException e) { + } catch (InvalidArgumentException e) { e.printStackTrace(); return ""; - } - }).toArray(String[]::new); + } + }) + .toArray(String[]::new); - List result2 = taskService.createTaskQuery() - .customAttributeIn("4", ids) - .list(); - assertThat(result2.size(), equalTo(2)); - } + List result2 = taskService.createTaskQuery().customAttributeIn("4", ids).list(); + assertThat(result2.size(), equalTo(2)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryForCustom5() - throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryForCustom5() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .customAttributeLike("5", "ew", "al") - .list(); - assertThat(results.size(), equalTo(2)); + List results = + taskService.createTaskQuery().customAttributeLike("5", "ew", "al").list(); + assertThat(results.size(), equalTo(2)); - String[] ids = results.stream() - .map(t -> { - try { + String[] ids = + results.stream() + .map( + t -> { + try { return t.getCustomAttribute("5"); - } catch (InvalidArgumentException e) { + } catch (InvalidArgumentException e) { e.printStackTrace(); return ""; - } - }).toArray(String[]::new); + } + }) + .toArray(String[]::new); - List result2 = taskService.createTaskQuery() - .customAttributeIn("5", ids) - .list(); - assertThat(result2.size(), equalTo(2)); - } + List result2 = taskService.createTaskQuery().customAttributeIn("5", ids).list(); + assertThat(result2.size(), equalTo(2)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryForCustom6() - throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryForCustom6() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .customAttributeLike("6", "%custom6%", "%vvg%", "11%") - .list(); - assertThat(results.size(), equalTo(3)); + List results = + taskService.createTaskQuery().customAttributeLike("6", "%custom6%", "%vvg%", "11%").list(); + assertThat(results.size(), equalTo(3)); - String[] ids = results.stream() - .map(t -> { - try { + String[] ids = + results.stream() + .map( + t -> { + try { return t.getCustomAttribute("6"); - } catch (InvalidArgumentException e) { + } catch (InvalidArgumentException e) { e.printStackTrace(); return ""; - } - }).toArray(String[]::new); + } + }) + .toArray(String[]::new); - List result2 = taskService.createTaskQuery() - .customAttributeIn("6", ids) - .list(); - assertThat(result2.size(), equalTo(3)); - } + List result2 = taskService.createTaskQuery().customAttributeIn("6", ids).list(); + assertThat(result2.size(), equalTo(3)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryForCustom7WithExceptionInLike() { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryForCustom7WithExceptionInLike() { + TaskService taskService = taskanaEngine.getTaskService(); - Assertions.assertThrows(InvalidArgumentException.class, () -> { - List results = taskService.createTaskQuery() - .customAttributeLike("7") - .list(); - assertThat(results.size(), equalTo(0)); + Assertions.assertThrows( + InvalidArgumentException.class, + () -> { + List results = taskService.createTaskQuery().customAttributeLike("7").list(); + assertThat(results.size(), equalTo(0)); }); - } + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryForCustom7WithExceptionInIn() - throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryForCustom7WithExceptionInIn() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .customAttributeLike("7", "fsdhfshk%") - .list(); - assertThat(results.size(), equalTo(0)); + List results = + taskService.createTaskQuery().customAttributeLike("7", "fsdhfshk%").list(); + assertThat(results.size(), equalTo(0)); - String[] ids = results.stream() - .map(t -> { - try { + String[] ids = + results.stream() + .map( + t -> { + try { return t.getCustomAttribute("7"); - } catch (InvalidArgumentException e) { + } catch (InvalidArgumentException e) { e.printStackTrace(); return ""; - } - }).toArray(String[]::new); + } + }) + .toArray(String[]::new); - Assertions.assertThrows(InvalidArgumentException.class, () -> { - List result2 = taskService.createTaskQuery() - .customAttributeIn("7", ids) - .list(); - assertThat(result2.size(), equalTo(0)); + Assertions.assertThrows( + InvalidArgumentException.class, + () -> { + List result2 = + taskService.createTaskQuery().customAttributeIn("7", ids).list(); + assertThat(result2.size(), equalTo(0)); }); - } + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryForCustom7WithException() - throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryForCustom7WithException() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .customAttributeLike("7", "%") - .list(); - assertThat(results.size(), equalTo(2)); + List results = taskService.createTaskQuery().customAttributeLike("7", "%").list(); + assertThat(results.size(), equalTo(2)); - String[] ids = results.stream() - .map(t -> { - try { + String[] ids = + results.stream() + .map( + t -> { + try { return t.getCustomAttribute("7"); - } catch (InvalidArgumentException e) { + } catch (InvalidArgumentException e) { e.printStackTrace(); return ""; - } - }).toArray(String[]::new); + } + }) + .toArray(String[]::new); - List result2 = taskService.createTaskQuery() - .customAttributeIn("7", ids) - .list(); - assertThat(result2.size(), equalTo(2)); - } + List result2 = taskService.createTaskQuery().customAttributeIn("7", ids).list(); + assertThat(result2.size(), equalTo(2)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryForCustom8() - throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryForCustom8() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .customAttributeLike("8", "%") - .list(); - assertThat(results.size(), equalTo(2)); + List results = taskService.createTaskQuery().customAttributeLike("8", "%").list(); + assertThat(results.size(), equalTo(2)); - String[] ids = results.stream() - .map(t -> { - try { + String[] ids = + results.stream() + .map( + t -> { + try { return t.getCustomAttribute("8"); - } catch (InvalidArgumentException e) { + } catch (InvalidArgumentException e) { e.printStackTrace(); return ""; - } - }).toArray(String[]::new); + } + }) + .toArray(String[]::new); - List result2 = taskService.createTaskQuery() - .customAttributeIn("8", ids) - .list(); - assertThat(result2.size(), equalTo(2)); - } + List result2 = taskService.createTaskQuery().customAttributeIn("8", ids).list(); + assertThat(result2.size(), equalTo(2)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryForCustom9() - throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryForCustom9() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .customAttributeLike("9", "%") - .list(); - assertThat(results.size(), equalTo(2)); + List results = taskService.createTaskQuery().customAttributeLike("9", "%").list(); + assertThat(results.size(), equalTo(2)); - String[] ids = results.stream() - .map(t -> { - try { + String[] ids = + results.stream() + .map( + t -> { + try { return t.getCustomAttribute("9"); - } catch (InvalidArgumentException e) { + } catch (InvalidArgumentException e) { e.printStackTrace(); return ""; - } - }).toArray(String[]::new); + } + }) + .toArray(String[]::new); - List result2 = taskService.createTaskQuery() - .customAttributeIn("9", ids) - .list(); - assertThat(result2.size(), equalTo(2)); - } + List result2 = taskService.createTaskQuery().customAttributeIn("9", ids).list(); + assertThat(result2.size(), equalTo(2)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryForCustom10() - throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryForCustom10() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .customAttributeLike("10", "%") - .list(); - assertThat(results.size(), equalTo(3)); + List results = taskService.createTaskQuery().customAttributeLike("10", "%").list(); + assertThat(results.size(), equalTo(3)); - String[] ids = results.stream() - .map(t -> { - try { + String[] ids = + results.stream() + .map( + t -> { + try { return t.getCustomAttribute("10"); - } catch (InvalidArgumentException e) { + } catch (InvalidArgumentException e) { e.printStackTrace(); return ""; - } - }).toArray(String[]::new); + } + }) + .toArray(String[]::new); - List result2 = taskService.createTaskQuery() - .customAttributeIn("10", ids) - .list(); - assertThat(result2.size(), equalTo(3)); - } + List result2 = taskService.createTaskQuery().customAttributeIn("10", ids).list(); + assertThat(result2.size(), equalTo(3)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryForCustom11() - throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryForCustom11() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .customAttributeLike("11", "%") - .list(); - assertThat(results.size(), equalTo(3)); + List results = taskService.createTaskQuery().customAttributeLike("11", "%").list(); + assertThat(results.size(), equalTo(3)); - String[] ids = results.stream() - .map(t -> { - try { + String[] ids = + results.stream() + .map( + t -> { + try { return t.getCustomAttribute("11"); - } catch (InvalidArgumentException e) { + } catch (InvalidArgumentException e) { e.printStackTrace(); return ""; - } - }).toArray(String[]::new); - List results2 = taskService.createTaskQuery() - .customAttributeIn("11", ids) - .list(); - assertThat(results2.size(), equalTo(3)); - } + } + }) + .toArray(String[]::new); + List results2 = taskService.createTaskQuery().customAttributeIn("11", ids).list(); + assertThat(results2.size(), equalTo(3)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryForCustom12() - throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryForCustom12() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .customAttributeLike("12", "%") - .list(); - assertThat(results.size(), equalTo(3)); + List results = taskService.createTaskQuery().customAttributeLike("12", "%").list(); + assertThat(results.size(), equalTo(3)); - String[] ids = results.stream() - .map(t -> { - try { + String[] ids = + results.stream() + .map( + t -> { + try { return t.getCustomAttribute("12"); - } catch (InvalidArgumentException e) { + } catch (InvalidArgumentException e) { e.printStackTrace(); return ""; - } - }).toArray(String[]::new); - List results2 = taskService.createTaskQuery() - .customAttributeIn("12", ids) - .list(); - assertThat(results2.size(), equalTo(3)); - } + } + }) + .toArray(String[]::new); + List results2 = taskService.createTaskQuery().customAttributeIn("12", ids).list(); + assertThat(results2.size(), equalTo(3)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryForCustom13() - throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryForCustom13() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .customAttributeLike("13", "%") - .list(); - assertThat(results.size(), equalTo(3)); + List results = taskService.createTaskQuery().customAttributeLike("13", "%").list(); + assertThat(results.size(), equalTo(3)); - String[] ids = results.stream() - .map(t -> { - try { + String[] ids = + results.stream() + .map( + t -> { + try { return t.getCustomAttribute("13"); - } catch (InvalidArgumentException e) { + } catch (InvalidArgumentException e) { e.printStackTrace(); return ""; - } - }).toArray(String[]::new); - List results2 = taskService.createTaskQuery() - .customAttributeIn("13", ids) - .list(); - assertThat(results2.size(), equalTo(3)); - } + } + }) + .toArray(String[]::new); + List results2 = taskService.createTaskQuery().customAttributeIn("13", ids).list(); + assertThat(results2.size(), equalTo(3)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryForCustom14() - throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryForCustom14() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .customAttributeLike("14", "%") - .list(); - assertThat(results.size(), equalTo(48)); + List results = taskService.createTaskQuery().customAttributeLike("14", "%").list(); + assertThat(results.size(), equalTo(48)); - String[] ids = results.stream() - .map(t -> { - try { + String[] ids = + results.stream() + .map( + t -> { + try { return t.getCustomAttribute("14"); - } catch (InvalidArgumentException e) { + } catch (InvalidArgumentException e) { e.printStackTrace(); return ""; - } - }).toArray(String[]::new); - List results2 = taskService.createTaskQuery() - .customAttributeIn("14", ids) - .list(); - assertThat(results2.size(), equalTo(48)); - } + } + }) + .toArray(String[]::new); + List results2 = taskService.createTaskQuery().customAttributeIn("14", ids).list(); + assertThat(results2.size(), equalTo(48)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryForCustom15() - throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryForCustom15() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .customAttributeLike("15", "%") - .list(); - assertThat(results.size(), equalTo(3)); + List results = taskService.createTaskQuery().customAttributeLike("15", "%").list(); + assertThat(results.size(), equalTo(3)); - String[] ids = results.stream() - .map(t -> { - try { + String[] ids = + results.stream() + .map( + t -> { + try { return t.getCustomAttribute("15"); - } catch (InvalidArgumentException e) { + } catch (InvalidArgumentException e) { e.printStackTrace(); return ""; - } - }).toArray(String[]::new); - List results2 = taskService.createTaskQuery() - .customAttributeIn("15", ids) - .list(); - assertThat(results2.size(), equalTo(3)); - } + } + }) + .toArray(String[]::new); + List results2 = taskService.createTaskQuery().customAttributeIn("15", ids).list(); + assertThat(results2.size(), equalTo(3)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryForCustom16() - throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryForCustom16() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .customAttributeLike("16", "%") - .list(); - assertThat(results.size(), equalTo(3)); + List results = taskService.createTaskQuery().customAttributeLike("16", "%").list(); + assertThat(results.size(), equalTo(3)); - String[] ids = results.stream() - .map(t -> { - try { + String[] ids = + results.stream() + .map( + t -> { + try { return t.getCustomAttribute("16"); - } catch (InvalidArgumentException e) { + } catch (InvalidArgumentException e) { e.printStackTrace(); return ""; - } - }).toArray(String[]::new); - List results2 = taskService.createTaskQuery() - .customAttributeIn("16", ids) - .list(); - assertThat(results2.size(), equalTo(3)); + } + }) + .toArray(String[]::new); + List results2 = taskService.createTaskQuery().customAttributeIn("16", ids).list(); + assertThat(results2.size(), equalTo(3)); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testQueryTaskByCustomAttributes() + throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, + WorkbasketNotFoundException, TaskAlreadyExistException, NoSuchFieldException, + IllegalAccessException { + + TaskService taskService = taskanaEngine.getTaskService(); + Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + newTask.setClassificationKey("T2100"); + Map customAttributesForCreate = + createSimpleCustomProperties(20000); // about 1 Meg + newTask.setCustomAttributes(customAttributesForCreate); + Task createdTask = taskService.createTask(newTask); + + assertNotNull(createdTask); + // query the task by custom attributes + TaskanaEngineProxyForTest engineProxy = new TaskanaEngineProxyForTest(taskanaEngine); + try { + SqlSession session = engineProxy.getSqlSession(); + Configuration config = session.getConfiguration(); + if (!config.hasMapper(TaskTestMapper.class)) { + config.addMapper(TaskTestMapper.class); + } + + TaskTestMapper mapper = session.getMapper(TaskTestMapper.class); + engineProxy.openConnection(); + List queryResult = + mapper.selectTasksByCustomAttributeLike("%Property Value of Property_1339%"); + + assertEquals(1, queryResult.size()); + Task retrievedTask = queryResult.get(0); + + assertEquals(createdTask.getId(), retrievedTask.getId()); + + // verify that the map is correctly retrieved from the database + Map customAttributesFromDb = retrievedTask.getCustomAttributes(); + assertNotNull(customAttributesFromDb); + assertEquals(customAttributesForCreate, customAttributesFromDb); + + } finally { + engineProxy.returnConnection(); } + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testQueryTaskByCustomAttributes() - throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, - WorkbasketNotFoundException, TaskAlreadyExistException, NoSuchFieldException, IllegalAccessException { + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testQueryAndCountMatch() { + TaskService taskService = taskanaEngine.getTaskService(); + TaskQuery taskQuery = taskService.createTaskQuery(); + List tasks = taskQuery.nameIn("Task99", "Task01", "Widerruf").list(); + long numberOfTasks = taskQuery.nameIn("Task99", "Task01", "Widerruf").count(); + assertEquals(numberOfTasks, tasks.size()); + } - TaskService taskService = taskanaEngine.getTaskService(); - Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - newTask.setClassificationKey("T2100"); - Map customAttributesForCreate = createSimpleCustomProperties(20000); // about 1 Meg - newTask.setCustomAttributes(customAttributesForCreate); - Task createdTask = taskService.createTask(newTask); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"businessadmin"}) + @Test + void testQueryAllPaged() { + TaskService taskService = taskanaEngine.getTaskService(); + TaskQuery taskQuery = taskService.createTaskQuery(); + long numberOfTasks = taskQuery.count(); + assertEquals(25, numberOfTasks); + List tasks = taskQuery.orderByDue(DESCENDING).list(); + assertEquals(25, tasks.size()); + List tasksp = taskQuery.orderByDue(DESCENDING).listPage(4, 5); + assertEquals(5, tasksp.size()); + tasksp = taskQuery.orderByDue(DESCENDING).listPage(5, 5); + assertEquals(5, tasksp.size()); + } - assertNotNull(createdTask); - // query the task by custom attributes - TaskanaEngineProxyForTest engineProxy = new TaskanaEngineProxyForTest(taskanaEngine); - try { - SqlSession session = engineProxy.getSqlSession(); - Configuration config = session.getConfiguration(); - if (!config.hasMapper(TaskTestMapper.class)) { - config.addMapper(TaskTestMapper.class); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForCreatorIn() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService.createTaskQuery().creatorIn("creator_user_id2", "creator_user_id3").list(); + assertEquals(4, results.size()); + } - TaskTestMapper mapper = session.getMapper(TaskTestMapper.class); - engineProxy.openConnection(); - List queryResult = mapper.selectTasksByCustomAttributeLike("%Property Value of Property_1339%"); + @WithAccessId(userName = "admin") + @Test + void testQueryForCreatorLike() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = taskService.createTaskQuery().creatorLike("ersTeLlEr%").list(); + assertEquals(3, results.size()); + } - assertEquals(1, queryResult.size()); - Task retrievedTask = queryResult.get(0); + @WithAccessId(userName = "admin") + @Test + void testQueryForNoteLike() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = taskService.createTaskQuery().noteLike("Some%").list(); + assertEquals(6, results.size()); + } - assertEquals(createdTask.getId(), retrievedTask.getId()); + @WithAccessId(userName = "admin") + @Test + void testQueryForClassificationCategoryIn() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService.createTaskQuery().classificationCategoryIn("MANUAL", "AUTOMATIC").list(); + assertEquals(3, results.size()); + } - // verify that the map is correctly retrieved from the database - Map customAttributesFromDb = retrievedTask.getCustomAttributes(); - assertNotNull(customAttributesFromDb); - assertEquals(customAttributesForCreate, customAttributesFromDb); + @WithAccessId(userName = "admin") + @Test + void testQueryForClassificationCategoryLike() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService.createTaskQuery().classificationCategoryLike("AUTO%").list(); + assertEquals(1, results.size()); + } - } finally { - engineProxy.returnConnection(); - } - } + @WithAccessId(userName = "admin") + @Test + void testQueryForPrimaryObjectReferenceCompanyLike() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService.createTaskQuery().primaryObjectReferenceCompanyLike("My%").list(); + assertEquals(6, results.size()); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testQueryAndCountMatch() { - TaskService taskService = taskanaEngine.getTaskService(); - TaskQuery taskQuery = taskService.createTaskQuery(); - List tasks = taskQuery - .nameIn("Task99", "Task01", "Widerruf") - .list(); - long numberOfTasks = taskQuery - .nameIn("Task99", "Task01", "Widerruf") - .count(); - assertEquals(numberOfTasks, tasks.size()); + @WithAccessId(userName = "admin") + @Test + void testQueryForPrimaryObjectReferenceSystemLike() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService.createTaskQuery().primaryObjectReferenceSystemLike("My%").list(); + assertEquals(6, results.size()); + } - } + @WithAccessId(userName = "admin") + @Test + void testQueryForPrimaryObjectReferenceSystemInstanceLike() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService.createTaskQuery().primaryObjectReferenceSystemInstanceLike("My%").list(); + assertEquals(6, results.size()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"businessadmin"}) - @Test - void testQueryAllPaged() { - TaskService taskService = taskanaEngine.getTaskService(); - TaskQuery taskQuery = taskService.createTaskQuery(); - long numberOfTasks = taskQuery.count(); - assertEquals(25, numberOfTasks); - List tasks = taskQuery - .orderByDue(DESCENDING) - .list(); - assertEquals(25, tasks.size()); - List tasksp = taskQuery - .orderByDue(DESCENDING) - .listPage(4, 5); - assertEquals(5, tasksp.size()); - tasksp = taskQuery - .orderByDue(DESCENDING) - .listPage(5, 5); - assertEquals(5, tasksp.size()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForPrimaryObjectReferenceTypeLike() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService.createTaskQuery().primaryObjectReferenceTypeLike("My%").list(); + assertEquals(6, results.size()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForCreatorIn() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .creatorIn("creator_user_id2", "creator_user_id3") - .list(); - assertEquals(4, results.size()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForReadEquals() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = taskService.createTaskQuery().readEquals(true).list(); + assertEquals(25, results.size()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForCreatorLike() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .creatorLike("ersTeLlEr%") - .list(); - assertEquals(3, results.size()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForTransferredEquals() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = taskService.createTaskQuery().transferredEquals(true).list(); + assertEquals(2, results.size()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForNoteLike() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .noteLike("Some%") - .list(); - assertEquals(6, results.size()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForBusinessProcessIdIn() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService.createTaskQuery().businessProcessIdIn("PI_0000000000003", "BPI21").list(); + assertEquals(8, results.size()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForClassificationCategoryIn() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .classificationCategoryIn("MANUAL", "AUTOMATIC") - .list(); - assertEquals(3, results.size()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForBusinessProcessIdLike() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = taskService.createTaskQuery().businessProcessIdLike("pI_%").list(); + assertEquals(67, results.size()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForClassificationCategoryLike() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .classificationCategoryLike("AUTO%") - .list(); - assertEquals(1, results.size()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForAttachmentClassificationKeyIn() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService.createTaskQuery().attachmentClassificationKeyIn("L110102").list(); + assertEquals(1, results.size()); + assertEquals("TKI:000000000000000000000000000000000002", results.get(0).getTaskId()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForPrimaryObjectReferenceCompanyLike() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .primaryObjectReferenceCompanyLike("My%") - .list(); - assertEquals(6, results.size()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForAttachmentClassificationKeyLike() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService.createTaskQuery().attachmentClassificationKeyLike("%10102").list(); + assertEquals(1, results.size()); + assertEquals("TKI:000000000000000000000000000000000002", results.get(0).getTaskId()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForPrimaryObjectReferenceSystemLike() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .primaryObjectReferenceSystemLike("My%") - .list(); - assertEquals(6, results.size()); - } - - @WithAccessId( - userName = "admin") - @Test - void testQueryForPrimaryObjectReferenceSystemInstanceLike() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .primaryObjectReferenceSystemInstanceLike("My%") - .list(); - assertEquals(6, results.size()); - } - - @WithAccessId( - userName = "admin") - @Test - void testQueryForPrimaryObjectReferenceTypeLike() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .primaryObjectReferenceTypeLike("My%") - .list(); - assertEquals(6, results.size()); - } - - @WithAccessId( - userName = "admin") - @Test - void testQueryForReadEquals() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .readEquals(true) - .list(); - assertEquals(25, results.size()); - } - - @WithAccessId( - userName = "admin") - @Test - void testQueryForTransferredEquals() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .transferredEquals(true) - .list(); - assertEquals(2, results.size()); - } - - @WithAccessId( - userName = "admin") - @Test - void testQueryForBusinessProcessIdIn() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .businessProcessIdIn("PI_0000000000003", "BPI21") - .list(); - assertEquals(8, results.size()); - } - - @WithAccessId( - userName = "admin") - @Test - void testQueryForBusinessProcessIdLike() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .businessProcessIdLike("pI_%") - .list(); - assertEquals(67, results.size()); - } - - @WithAccessId( - userName = "admin") - @Test - void testQueryForAttachmentClassificationKeyIn() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .attachmentClassificationKeyIn("L110102") - .list(); - assertEquals(1, results.size()); - assertEquals("TKI:000000000000000000000000000000000002", - results.get(0).getTaskId()); - } - - @WithAccessId( - userName = "admin") - @Test - void testQueryForAttachmentClassificationKeyLike() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .attachmentClassificationKeyLike("%10102") - .list(); - assertEquals(1, results.size()); - assertEquals("TKI:000000000000000000000000000000000002", - results.get(0).getTaskId()); - } - - @WithAccessId( - userName = "admin") - @Test - void testQueryForAttachmentclassificationIdIn() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId(userName = "admin") + @Test + void testQueryForAttachmentclassificationIdIn() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .attachmentClassificationIdIn("CLI:000000000000000000000000000000000002") .list(); - assertEquals(1, results.size()); - assertEquals("TKI:000000000000000000000000000000000001", - results.get(0).getTaskId()); - } + assertEquals(1, results.size()); + assertEquals("TKI:000000000000000000000000000000000001", results.get(0).getTaskId()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForAttachmentChannelLike() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .attachmentChannelLike("%6") - .list(); - assertEquals(2, results.size()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForAttachmentChannelLike() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = taskService.createTaskQuery().attachmentChannelLike("%6").list(); + assertEquals(2, results.size()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForAttachmentReferenceIn() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .attachmentReferenceValueIn("val4") - .list(); - assertEquals(6, results.size()); - assertEquals(1, results.get(5).getAttachmentSummaries().size()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForAttachmentReferenceIn() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService.createTaskQuery().attachmentReferenceValueIn("val4").list(); + assertEquals(6, results.size()); + assertEquals(1, results.get(5).getAttachmentSummaries().size()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForAttachmentReceivedIn() { - TaskService taskService = taskanaEngine.getTaskService(); - TimeInterval interval = new TimeInterval( - getInstant("2018-01-30T12:00:00"), - getInstant("2018-01-31T12:00:00")); - List results = taskService.createTaskQuery() + @WithAccessId(userName = "admin") + @Test + void testQueryForAttachmentReceivedIn() { + TaskService taskService = taskanaEngine.getTaskService(); + TimeInterval interval = + new TimeInterval(getInstant("2018-01-30T12:00:00"), getInstant("2018-01-31T12:00:00")); + List results = + taskService + .createTaskQuery() .attachmentReceivedWithin(interval) .orderByWorkbasketId(DESCENDING) .list(); - assertEquals(2, results.size()); - assertEquals("TKI:000000000000000000000000000000000001", results.get(0).getTaskId()); - assertEquals("TKI:000000000000000000000000000000000011", results.get(1).getTaskId()); - } + assertEquals(2, results.size()); + assertEquals("TKI:000000000000000000000000000000000001", results.get(0).getTaskId()); + assertEquals("TKI:000000000000000000000000000000000011", results.get(1).getTaskId()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByCreatorDesc() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .orderByCreator(DESCENDING) - .list(); - assertEquals("erstellerSpezial", results.get(0).getCreator()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByCreatorDesc() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = taskService.createTaskQuery().orderByCreator(DESCENDING).list(); + assertEquals("erstellerSpezial", results.get(0).getCreator()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByWorkbasketIdDesc() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .orderByWorkbasketId(DESCENDING) - .list(); - assertEquals("WBI:100000000000000000000000000000000015", - results.get(0).getWorkbasketSummary().getId()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByWorkbasketIdDesc() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService.createTaskQuery().orderByWorkbasketId(DESCENDING).list(); + assertEquals( + "WBI:100000000000000000000000000000000015", results.get(0).getWorkbasketSummary().getId()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByCustom1Asc() throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByCustom1Asc() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .customAttributeLike("1", "%") .orderByCustomAttribute("1", ASCENDING) .list(); - assertEquals("custom1", results.get(0).getCustomAttribute("1")); - } + assertEquals("custom1", results.get(0).getCustomAttribute("1")); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByCustom2Desc() throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByCustom2Desc() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .customAttributeLike("2", "%") .orderByCustomAttribute("2", DESCENDING) .list(); - assertEquals("custom2", results.get(0).getCustomAttribute("2")); - } + assertEquals("custom2", results.get(0).getCustomAttribute("2")); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByCustom3Asc() throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByCustom3Asc() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .customAttributeLike("3", "%") .orderByCustomAttribute("3", ASCENDING) .list(); - assertEquals("custom3", results.get(0).getCustomAttribute("3")); - } + assertEquals("custom3", results.get(0).getCustomAttribute("3")); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByCustom4Desc() throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByCustom4Desc() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .customAttributeLike("4", "%") .orderByCustomAttribute("4", DESCENDING) .list(); - assertEquals("rty", - results.get(0).getCustomAttribute("4")); - } + assertEquals("rty", results.get(0).getCustomAttribute("4")); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByCustom5Asc() throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByCustom5Asc() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .customAttributeLike("5", "%") .orderByCustomAttribute("5", ASCENDING) .list(); - assertEquals("al", results.get(0).getCustomAttribute("5")); - } + assertEquals("al", results.get(0).getCustomAttribute("5")); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByCustom6Desc() throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByCustom6Desc() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .customAttributeLike("6", "%") .orderByCustomAttribute("6", DESCENDING) .list(); - assertEquals("vvg", results.get(0).getCustomAttribute("6")); - } + assertEquals("vvg", results.get(0).getCustomAttribute("6")); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByCustom7Asc() throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByCustom7Asc() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .orderByCustomAttribute("7", ASCENDING) .customAttributeLike("7", "%") .list(); - assertEquals("custom7", results.get(0).getCustomAttribute("7")); - } + assertEquals("custom7", results.get(0).getCustomAttribute("7")); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByCustom8Desc() throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByCustom8Desc() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .orderByCustomAttribute("8", DESCENDING) .customAttributeLike("8", "%") .list(); - assertEquals("lnp", results.get(0).getCustomAttribute("8")); - } + assertEquals("lnp", results.get(0).getCustomAttribute("8")); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByCustom9Asc() throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByCustom9Asc() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .customAttributeLike("9", "%") .orderByCustomAttribute("9", ASCENDING) .list(); - assertEquals("bbq", results.get(0).getCustomAttribute("9")); - } + assertEquals("bbq", results.get(0).getCustomAttribute("9")); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByCustom10Desc() throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByCustom10Desc() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .customAttributeLike("10", "%") .orderByCustomAttribute("10", DESCENDING) .list(); - assertEquals("ert", results.get(0).getCustomAttribute("10")); - } + assertEquals("ert", results.get(0).getCustomAttribute("10")); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByCustom11Desc() throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByCustom11Desc() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .orderByCustomAttribute("11", DESCENDING) .customAttributeLike("11", "%") .list(); - assertEquals("ert", - results.get(0).getCustomAttribute("11")); + assertEquals("ert", results.get(0).getCustomAttribute("11")); + } - } - - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByCustom12Asc() throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByCustom12Asc() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .customAttributeLike("12", "%") .orderByCustomAttribute("12", ASCENDING) .list(); - assertEquals("custom12", results.get(0).getCustomAttribute("12")); - } + assertEquals("custom12", results.get(0).getCustomAttribute("12")); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByCustom13Desc() throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByCustom13Desc() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .customAttributeLike("13", "%") .orderByCustomAttribute("13", DESCENDING) .list(); - assertEquals("ert", - results.get(0).getCustomAttribute("13")); - } + assertEquals("ert", results.get(0).getCustomAttribute("13")); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByCustom14Asc() throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByCustom14Asc() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .customAttributeLike("14", "%") .orderByCustomAttribute("14", ASCENDING) .list(); - assertEquals("abc", results.get(0).getCustomAttribute("14")); - } + assertEquals("abc", results.get(0).getCustomAttribute("14")); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByCustom15Desc() throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByCustom15Desc() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .customAttributeLike("15", "%") .orderByCustomAttribute("15", DESCENDING) .list(); - assertEquals("ert", - results.get(0).getCustomAttribute("15")); - } + assertEquals("ert", results.get(0).getCustomAttribute("15")); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByCustom16Asc() throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByCustom16Asc() throws InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .customAttributeLike("16", "%") .orderByCustomAttribute("16", ASCENDING) .list(); - assertEquals("custom16", results.get(0).getCustomAttribute("16")); - } + assertEquals("custom16", results.get(0).getCustomAttribute("16")); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderWithDirectionNull() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .orderByPrimaryObjectReferenceSystemInstance(null) - .list(); - assertEquals("00", results.get(0).getPrimaryObjRef().getSystemInstance()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderWithDirectionNull() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService.createTaskQuery().orderByPrimaryObjectReferenceSystemInstance(null).list(); + assertEquals("00", results.get(0).getPrimaryObjRef().getSystemInstance()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByAttachmentClassificationIdAsc() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .idIn("TKI:000000000000000000000000000000000010", "TKI:000000000000000000000000000000000011", + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByAttachmentClassificationIdAsc() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() + .idIn( + "TKI:000000000000000000000000000000000010", + "TKI:000000000000000000000000000000000011", "TKI:000000000000000000000000000000000012") .orderByAttachmentClassificationId(ASCENDING) .list(); - assertEquals("TKI:000000000000000000000000000000000011", results.get(0).getTaskId()); - assertEquals("TKI:000000000000000000000000000000000010", results.get(results.size() - 1).getTaskId()); - } + assertEquals("TKI:000000000000000000000000000000000011", results.get(0).getTaskId()); + assertEquals( + "TKI:000000000000000000000000000000000010", results.get(results.size() - 1).getTaskId()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByAttachmentClassificationIdDesc() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .idIn("TKI:000000000000000000000000000000000010", "TKI:000000000000000000000000000000000011", + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByAttachmentClassificationIdDesc() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() + .idIn( + "TKI:000000000000000000000000000000000010", + "TKI:000000000000000000000000000000000011", "TKI:000000000000000000000000000000000012") .orderByAttachmentClassificationId(DESCENDING) .list(); - assertEquals("TKI:000000000000000000000000000000000010", results.get(0).getTaskId()); - assertEquals("TKI:000000000000000000000000000000000011", results.get(results.size() - 1).getTaskId()); - } + assertEquals("TKI:000000000000000000000000000000000010", results.get(0).getTaskId()); + assertEquals( + "TKI:000000000000000000000000000000000011", results.get(results.size() - 1).getTaskId()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByAttachmentClassificationKeyAsc() { + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByAttachmentClassificationKeyAsc() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .idIn("TKI:000000000000000000000000000000000010", "TKI:000000000000000000000000000000000011", + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() + .idIn( + "TKI:000000000000000000000000000000000010", + "TKI:000000000000000000000000000000000011", "TKI:000000000000000000000000000000000012") .orderByAttachmentClassificationKey(ASCENDING) .list(); - assertEquals("TKI:000000000000000000000000000000000010", results.get(0).getTaskId()); - assertEquals("TKI:000000000000000000000000000000000012", results.get(results.size() - 1).getTaskId()); - } + assertEquals("TKI:000000000000000000000000000000000010", results.get(0).getTaskId()); + assertEquals( + "TKI:000000000000000000000000000000000012", results.get(results.size() - 1).getTaskId()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByAttachmentClassificationKeyDesc() { + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByAttachmentClassificationKeyDesc() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .idIn("TKI:000000000000000000000000000000000010", "TKI:000000000000000000000000000000000011", + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() + .idIn( + "TKI:000000000000000000000000000000000010", + "TKI:000000000000000000000000000000000011", "TKI:000000000000000000000000000000000012") .orderByAttachmentClassificationKey(DESCENDING) .list(); - assertEquals("TKI:000000000000000000000000000000000012", results.get(0).getTaskId()); - assertEquals("TKI:000000000000000000000000000000000010", results.get(results.size() - 1).getTaskId()); - } + assertEquals("TKI:000000000000000000000000000000000012", results.get(0).getTaskId()); + assertEquals( + "TKI:000000000000000000000000000000000010", results.get(results.size() - 1).getTaskId()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByAttachmentRefValueDesc() { + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByAttachmentRefValueDesc() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .idIn("TKI:000000000000000000000000000000000010", "TKI:000000000000000000000000000000000011", + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() + .idIn( + "TKI:000000000000000000000000000000000010", + "TKI:000000000000000000000000000000000011", "TKI:000000000000000000000000000000000012") .orderByAttachmentReference(DESCENDING) .list(); - assertEquals("TKI:000000000000000000000000000000000012", results.get(0).getTaskId()); - assertEquals("TKI:000000000000000000000000000000000010", results.get(results.size() - 1).getTaskId()); - } + assertEquals("TKI:000000000000000000000000000000000012", results.get(0).getTaskId()); + assertEquals( + "TKI:000000000000000000000000000000000010", results.get(results.size() - 1).getTaskId()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByAttachmentChannelAscAndReferenceDesc() { + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByAttachmentChannelAscAndReferenceDesc() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .idIn("TKI:000000000000000000000000000000000010", "TKI:000000000000000000000000000000000011", + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() + .idIn( + "TKI:000000000000000000000000000000000010", + "TKI:000000000000000000000000000000000011", "TKI:000000000000000000000000000000000012") .orderByAttachmentChannel(ASCENDING) .orderByAttachmentReference(DESCENDING) .list(); - assertEquals("TKI:000000000000000000000000000000000012", results.get(0).getTaskId()); - assertEquals("TKI:000000000000000000000000000000000010", results.get(results.size() - 1).getTaskId()); - } + assertEquals("TKI:000000000000000000000000000000000012", results.get(0).getTaskId()); + assertEquals( + "TKI:000000000000000000000000000000000010", results.get(results.size() - 1).getTaskId()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForAttachmentLikeCHAndOrderByClassificationKeyDescAndAsc() { + @WithAccessId(userName = "admin") + @Test + void testQueryForAttachmentLikeCHAndOrderByClassificationKeyDescAndAsc() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .attachmentChannelLike("CH%") .orderByClassificationKey(DESCENDING) .list(); - assertEquals("T2000", results.get(0).getClassificationSummary().getKey()); - assertEquals("L1050", results.get(results.size() - 1).getClassificationSummary().getKey()); + assertEquals("T2000", results.get(0).getClassificationSummary().getKey()); + assertEquals("L1050", results.get(results.size() - 1).getClassificationSummary().getKey()); - results = taskService.createTaskQuery() + results = + taskService + .createTaskQuery() .attachmentChannelLike("CH%") .orderByClassificationKey(ASCENDING) .list(); - assertEquals("L1050", results.get(0).getClassificationSummary().getKey()); - assertEquals("T2000", results.get(results.size() - 1).getClassificationSummary().getKey()); - } + assertEquals("L1050", results.get(0).getClassificationSummary().getKey()); + assertEquals("T2000", results.get(results.size() - 1).getClassificationSummary().getKey()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "group_2"}) - @Test - void testQueryForExternalIdIn() { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "group_2"}) + @Test + void testQueryForExternalIdIn() { + TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .externalIdIn("ETI:000000000000000000000000000000000010", "ETI:000000000000000000000000000000000011", - "ETI:000000000000000000000000000000000012", "ETI:000000000000000000000000000000000013", - "ETI:000000000000000000000000000000000014", "ETI:000000000000000000000000000000000015", - "ETI:000000000000000000000000000000000016", "ETI:000000000000000000000000000000000017", - "ETI:000000000000000000000000000000000018", "ETI:000000000000000000000000000000000019") + List results = + taskService + .createTaskQuery() + .externalIdIn( + "ETI:000000000000000000000000000000000010", + "ETI:000000000000000000000000000000000011", + "ETI:000000000000000000000000000000000012", + "ETI:000000000000000000000000000000000013", + "ETI:000000000000000000000000000000000014", + "ETI:000000000000000000000000000000000015", + "ETI:000000000000000000000000000000000016", + "ETI:000000000000000000000000000000000017", + "ETI:000000000000000000000000000000000018", + "ETI:000000000000000000000000000000000019") .list(); - assertThat(results.size(), equalTo(10)); + assertThat(results.size(), equalTo(10)); - String[] ids = results.stream().map(TaskSummary::getTaskId).toArray(String[]::new); + String[] ids = results.stream().map(TaskSummary::getTaskId).toArray(String[]::new); - List result2 = taskService.createTaskQuery() - .idIn(ids) - .list(); - assertThat(result2.size(), equalTo(10)); - } + List result2 = taskService.createTaskQuery().idIn(ids).list(); + assertThat(result2.size(), equalTo(10)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "group_2"}) - @Test - void testQueryForExternalIdLike() { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "group_2"}) + @Test + void testQueryForExternalIdLike() { + TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + List results = + taskService + .createTaskQuery() .externalIdLike("ETI:00000000000000000000000000000000001%") .list(); - assertThat(results.size(), equalTo(10)); + assertThat(results.size(), equalTo(10)); - String[] ids = results.stream().map(TaskSummary::getTaskId).toArray(String[]::new); - - List result2 = taskService.createTaskQuery() - .idIn(ids) - .list(); - assertThat(result2.size(), equalTo(10)); - } + String[] ids = results.stream().map(TaskSummary::getTaskId).toArray(String[]::new); + List result2 = taskService.createTaskQuery().idIn(ids).list(); + assertThat(result2.size(), equalTo(10)); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/task/QueryTasksByObjectReferenceAccTest.java b/lib/taskana-core/src/test/java/acceptance/task/QueryTasksByObjectReferenceAccTest.java index 4b6b1705d..974a36e90 100644 --- a/lib/taskana-core/src/test/java/acceptance/task/QueryTasksByObjectReferenceAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/task/QueryTasksByObjectReferenceAccTest.java @@ -2,66 +2,59 @@ package acceptance.task; import static org.junit.jupiter.api.Assertions.assertEquals; +import acceptance.AbstractAccTest; import java.util.List; - import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.TaskService; import pro.taskana.TaskSummary; import pro.taskana.exceptions.SystemException; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "query tasks by object reference" scenarios. - */ +/** Acceptance test for all "query tasks by object reference" scenarios. */ @ExtendWith(JAASExtension.class) class QueryTasksByObjectReferenceAccTest extends AbstractAccTest { - QueryTasksByObjectReferenceAccTest() { - super(); - } + QueryTasksByObjectReferenceAccTest() { + super(); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "group_2"}) - @Test - void testQueryTasksByExcactValueOfObjectReference() - throws SystemException { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .primaryObjectReferenceValueIn("11223344", "22334455") - .list(); - assertEquals(33L, results.size()); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "group_2"}) + @Test + void testQueryTasksByExcactValueOfObjectReference() throws SystemException { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService.createTaskQuery().primaryObjectReferenceValueIn("11223344", "22334455").list(); + assertEquals(33L, results.size()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "group_2"}) - @Test - void testQueryTasksByExcactValueAndTypeOfObjectReference() - throws SystemException { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "group_2"}) + @Test + void testQueryTasksByExcactValueAndTypeOfObjectReference() throws SystemException { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .primaryObjectReferenceTypeIn("SDNR") .primaryObjectReferenceValueIn("11223344") .list(); - assertEquals(10L, results.size()); - } - - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "group_2"}) - @Test - void testQueryTasksByValueLikeOfObjectReference() - throws SystemException { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() - .primaryObjectReferenceValueLike("%567%") - .list(); - assertEquals(10L, results.size()); - } + assertEquals(10L, results.size()); + } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "group_2"}) + @Test + void testQueryTasksByValueLikeOfObjectReference() throws SystemException { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService.createTaskQuery().primaryObjectReferenceValueLike("%567%").list(); + assertEquals(10L, results.size()); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/task/QueryTasksByTimeIntervalsAccTest.java b/lib/taskana-core/src/test/java/acceptance/task/QueryTasksByTimeIntervalsAccTest.java index 27c41806c..dd0b45ff0 100644 --- a/lib/taskana-core/src/test/java/acceptance/task/QueryTasksByTimeIntervalsAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/task/QueryTasksByTimeIntervalsAccTest.java @@ -5,13 +5,12 @@ import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import acceptance.AbstractAccTest; import java.time.Instant; import java.util.List; - import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.BaseQuery.SortDirection; import pro.taskana.TaskService; import pro.taskana.TaskSummary; @@ -19,249 +18,227 @@ import pro.taskana.TimeInterval; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "query tasks with sorting" scenarios. - */ +/** Acceptance test for all "query tasks with sorting" scenarios. */ @ExtendWith(JAASExtension.class) class QueryTasksByTimeIntervalsAccTest extends AbstractAccTest { - private static SortDirection asc = SortDirection.ASCENDING; + private static SortDirection asc = SortDirection.ASCENDING; - QueryTasksByTimeIntervalsAccTest() { - super(); - } + QueryTasksByTimeIntervalsAccTest() { + super(); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "group_2"}) - @Test - void testCreatedWithin2Intervals() { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "group_2"}) + @Test + void testCreatedWithin2Intervals() { + TaskService taskService = taskanaEngine.getTaskService(); - TimeInterval interval1 = new TimeInterval( - getInstant("2018-01-29T15:55:10"), - getInstant("2018-01-29T15:55:17")); - TimeInterval interval2 = new TimeInterval( - getInstant("2018-01-29T15:55:23"), - getInstant("2018-01-29T15:55:25")); + TimeInterval interval1 = + new TimeInterval(getInstant("2018-01-29T15:55:10"), getInstant("2018-01-29T15:55:17")); + TimeInterval interval2 = + new TimeInterval(getInstant("2018-01-29T15:55:23"), getInstant("2018-01-29T15:55:25")); - List results = taskService.createTaskQuery() + List results = + taskService + .createTaskQuery() .createdWithin(interval1, interval2) .orderByCreated(asc) .list(); - assertThat(results.size(), equalTo(40)); - TaskSummary previousSummary = null; - for (TaskSummary taskSummary : results) { - Instant cr = taskSummary.getCreated(); - assertTrue(interval1.contains(cr) || interval2.contains(cr)); + assertThat(results.size(), equalTo(40)); + TaskSummary previousSummary = null; + for (TaskSummary taskSummary : results) { + Instant cr = taskSummary.getCreated(); + assertTrue(interval1.contains(cr) || interval2.contains(cr)); - if (previousSummary != null) { - assertFalse(previousSummary.getCreated().isAfter(taskSummary.getCreated())); - } - previousSummary = taskSummary; - } + if (previousSummary != null) { + assertFalse(previousSummary.getCreated().isAfter(taskSummary.getCreated())); + } + previousSummary = taskSummary; } + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "group_2"}) - @Test - void testCreatedBefore() { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "group_2"}) + @Test + void testCreatedBefore() { + TaskService taskService = taskanaEngine.getTaskService(); - TimeInterval interval1 = new TimeInterval( - null, - getInstant("2018-01-29T15:55:17")); + TimeInterval interval1 = new TimeInterval(null, getInstant("2018-01-29T15:55:17")); - List results = taskService.createTaskQuery() - .createdWithin(interval1) - .orderByCreated(asc) - .list(); + List results = + taskService.createTaskQuery().createdWithin(interval1).orderByCreated(asc).list(); - assertThat(results.size(), equalTo(37)); - TaskSummary previousSummary = null; - for (TaskSummary taskSummary : results) { - Instant cr = taskSummary.getCreated(); - assertTrue(interval1.contains(cr)); + assertThat(results.size(), equalTo(37)); + TaskSummary previousSummary = null; + for (TaskSummary taskSummary : results) { + Instant cr = taskSummary.getCreated(); + assertTrue(interval1.contains(cr)); - if (previousSummary != null) { - assertFalse(previousSummary.getCreated().isAfter(taskSummary.getCreated())); - } - previousSummary = taskSummary; - } + if (previousSummary != null) { + assertFalse(previousSummary.getCreated().isAfter(taskSummary.getCreated())); + } + previousSummary = taskSummary; } + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "group_2"}) - @Test - void testCreatedAfter() { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "group_2"}) + @Test + void testCreatedAfter() { + TaskService taskService = taskanaEngine.getTaskService(); - TimeInterval interval1 = new TimeInterval( - getInstant("2018-01-29T15:55:17"), null); + TimeInterval interval1 = new TimeInterval(getInstant("2018-01-29T15:55:17"), null); - List results = taskService.createTaskQuery() - .createdWithin(interval1) - .orderByCreated(asc) - .list(); + List results = + taskService.createTaskQuery().createdWithin(interval1).orderByCreated(asc).list(); - assertThat(results.size(), equalTo(38)); - TaskSummary previousSummary = null; - for (TaskSummary taskSummary : results) { - Instant cr = taskSummary.getCreated(); - assertTrue(interval1.contains(cr)); + assertThat(results.size(), equalTo(38)); + TaskSummary previousSummary = null; + for (TaskSummary taskSummary : results) { + Instant cr = taskSummary.getCreated(); + assertTrue(interval1.contains(cr)); - if (previousSummary != null) { - assertFalse(previousSummary.getCreated().isAfter(taskSummary.getCreated())); - } - previousSummary = taskSummary; - } + if (previousSummary != null) { + assertFalse(previousSummary.getCreated().isAfter(taskSummary.getCreated())); + } + previousSummary = taskSummary; } + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "group_2"}) - @Test - void testClaimedWithin2Intervals() { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "group_2"}) + @Test + void testClaimedWithin2Intervals() { + TaskService taskService = taskanaEngine.getTaskService(); - TimeInterval interval1 = new TimeInterval( - getInstant("2018-01-30T15:55:00"), - getInstant("2018-01-30T15:55:10")); - TimeInterval interval2 = new TimeInterval( - getInstant("2018-01-30T15:55:23"), - getInstant("2018-01-30T15:55:25")); + TimeInterval interval1 = + new TimeInterval(getInstant("2018-01-30T15:55:00"), getInstant("2018-01-30T15:55:10")); + TimeInterval interval2 = + new TimeInterval(getInstant("2018-01-30T15:55:23"), getInstant("2018-01-30T15:55:25")); - List results = taskService.createTaskQuery() + List results = + taskService + .createTaskQuery() .claimedWithin(interval1, interval2) .orderByCreated(asc) .list(); - assertThat(results.size(), equalTo(25)); - TaskSummary previousSummary = null; - for (TaskSummary taskSummary : results) { - Instant cr = taskSummary.getClaimed(); - assertTrue(interval1.contains(cr) || interval2.contains(cr)); + assertThat(results.size(), equalTo(25)); + TaskSummary previousSummary = null; + for (TaskSummary taskSummary : results) { + Instant cr = taskSummary.getClaimed(); + assertTrue(interval1.contains(cr) || interval2.contains(cr)); - if (previousSummary != null) { - assertFalse(previousSummary.getClaimed().isAfter(taskSummary.getClaimed())); - } - previousSummary = taskSummary; - } + if (previousSummary != null) { + assertFalse(previousSummary.getClaimed().isAfter(taskSummary.getClaimed())); + } + previousSummary = taskSummary; } + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "group_2"}) - @Test - void testCompletedWithin() { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "group_2"}) + @Test + void testCompletedWithin() { + TaskService taskService = taskanaEngine.getTaskService(); - TimeInterval interval = new TimeInterval( - getInstant("2018-01-30T16:55:23"), - getInstant("2018-01-30T16:55:25")); - List results = taskService.createTaskQuery() - .completedWithin(interval) - .orderByCompleted(asc) - .list(); + TimeInterval interval = + new TimeInterval(getInstant("2018-01-30T16:55:23"), getInstant("2018-01-30T16:55:25")); + List results = + taskService.createTaskQuery().completedWithin(interval).orderByCompleted(asc).list(); - assertThat(results.size(), equalTo(5)); - TaskSummary previousSummary = null; - for (TaskSummary taskSummary : results) { - Instant cr = taskSummary.getCompleted(); - assertTrue(interval.contains(cr)); + assertThat(results.size(), equalTo(5)); + TaskSummary previousSummary = null; + for (TaskSummary taskSummary : results) { + Instant cr = taskSummary.getCompleted(); + assertTrue(interval.contains(cr)); - if (previousSummary != null) { - assertFalse(previousSummary.getCompleted().isAfter(taskSummary.getCompleted())); - } - previousSummary = taskSummary; - } + if (previousSummary != null) { + assertFalse(previousSummary.getCompleted().isAfter(taskSummary.getCompleted())); + } + previousSummary = taskSummary; } + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "group_2"}) - @Test - void testModifiedWithin() { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "group_2"}) + @Test + void testModifiedWithin() { + TaskService taskService = taskanaEngine.getTaskService(); - TimeInterval interval = new TimeInterval( - getInstant("2018-01-30T15:55:00"), - getInstant("2018-01-30T15:55:22")); - List results = taskService.createTaskQuery() - .modifiedWithin(interval) - .orderByModified(asc) - .list(); + TimeInterval interval = + new TimeInterval(getInstant("2018-01-30T15:55:00"), getInstant("2018-01-30T15:55:22")); + List results = + taskService.createTaskQuery().modifiedWithin(interval).orderByModified(asc).list(); - assertThat(results.size(), equalTo(6)); - TaskSummary previousSummary = null; - for (TaskSummary taskSummary : results) { - Instant cr = taskSummary.getModified(); - assertTrue(interval.contains(cr)); + assertThat(results.size(), equalTo(6)); + TaskSummary previousSummary = null; + for (TaskSummary taskSummary : results) { + Instant cr = taskSummary.getModified(); + assertTrue(interval.contains(cr)); - if (previousSummary != null) { - assertFalse(previousSummary.getModified().isAfter(taskSummary.getModified())); - } - previousSummary = taskSummary; - } + if (previousSummary != null) { + assertFalse(previousSummary.getModified().isAfter(taskSummary.getModified())); + } + previousSummary = taskSummary; } + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "group_2"}) - @Test - void testPlannedWithin() { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "group_2"}) + @Test + void testPlannedWithin() { + TaskService taskService = taskanaEngine.getTaskService(); - TimeInterval interval = new TimeInterval( - getInstant("2018-01-29T15:55:00"), - getInstant("2018-01-30T15:55:22")); - List results = taskService.createTaskQuery() - .plannedWithin(interval) - .orderByPlanned(asc) - .list(); + TimeInterval interval = + new TimeInterval(getInstant("2018-01-29T15:55:00"), getInstant("2018-01-30T15:55:22")); + List results = + taskService.createTaskQuery().plannedWithin(interval).orderByPlanned(asc).list(); - assertThat(results.size(), equalTo(71)); - TaskSummary previousSummary = null; - for (TaskSummary taskSummary : results) { - Instant cr = taskSummary.getPlanned(); - assertTrue(interval.contains(cr)); + assertThat(results.size(), equalTo(71)); + TaskSummary previousSummary = null; + for (TaskSummary taskSummary : results) { + Instant cr = taskSummary.getPlanned(); + assertTrue(interval.contains(cr)); - if (previousSummary != null) { - assertFalse(previousSummary.getPlanned().isAfter(taskSummary.getPlanned())); - } - previousSummary = taskSummary; - } + if (previousSummary != null) { + assertFalse(previousSummary.getPlanned().isAfter(taskSummary.getPlanned())); + } + previousSummary = taskSummary; } + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "group_2"}) - @Test - void testDueWithin() { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "group_2"}) + @Test + void testDueWithin() { + TaskService taskService = taskanaEngine.getTaskService(); - TimeInterval interval = new TimeInterval( - getInstant("2018-01-29T15:55:00"), - getInstant("2018-01-30T15:55:22")); - List results = taskService.createTaskQuery() - .dueWithin(interval) - .orderByPlanned(asc) - .list(); + TimeInterval interval = + new TimeInterval(getInstant("2018-01-29T15:55:00"), getInstant("2018-01-30T15:55:22")); + List results = + taskService.createTaskQuery().dueWithin(interval).orderByPlanned(asc).list(); - assertThat(results.size(), equalTo(71)); - TaskSummary previousSummary = null; - for (TaskSummary taskSummary : results) { - Instant cr = taskSummary.getDue(); - assertTrue(interval.contains(cr)); + assertThat(results.size(), equalTo(71)); + TaskSummary previousSummary = null; + for (TaskSummary taskSummary : results) { + Instant cr = taskSummary.getDue(); + assertTrue(interval.contains(cr)); - if (previousSummary != null) { - assertFalse(previousSummary.getPlanned().isAfter(taskSummary.getPlanned())); - } - previousSummary = taskSummary; - } + if (previousSummary != null) { + assertFalse(previousSummary.getPlanned().isAfter(taskSummary.getPlanned())); + } + previousSummary = taskSummary; } - + } } diff --git a/lib/taskana-core/src/test/java/acceptance/task/QueryTasksByWorkbasketAccTest.java b/lib/taskana-core/src/test/java/acceptance/task/QueryTasksByWorkbasketAccTest.java index e88cfd87a..7af76033f 100644 --- a/lib/taskana-core/src/test/java/acceptance/task/QueryTasksByWorkbasketAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/task/QueryTasksByWorkbasketAccTest.java @@ -3,15 +3,14 @@ package acceptance.task; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; +import acceptance.AbstractAccTest; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.KeyDomain; import pro.taskana.TaskService; import pro.taskana.TaskSummary; @@ -19,64 +18,69 @@ import pro.taskana.exceptions.NotAuthorizedToQueryWorkbasketException; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "query tasks by workbasket" scenarios. - */ +/** Acceptance test for all "query tasks by workbasket" scenarios. */ @ExtendWith(JAASExtension.class) class QueryTasksByWorkbasketAccTest extends AbstractAccTest { - QueryTasksByWorkbasketAccTest() { - super(); - } + QueryTasksByWorkbasketAccTest() { + super(); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryForWorkbasketKeyDomain() { - TaskService taskService = taskanaEngine.getTaskService(); - List workbasketIdentifiers = Arrays.asList(new KeyDomain("GPK_KSC", "DOMAIN_A"), - new KeyDomain("USER_1_2", "DOMAIN_A")); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryForWorkbasketKeyDomain() { + TaskService taskService = taskanaEngine.getTaskService(); + List workbasketIdentifiers = + Arrays.asList(new KeyDomain("GPK_KSC", "DOMAIN_A"), new KeyDomain("USER_1_2", "DOMAIN_A")); - List results = taskService.createTaskQuery() + List results = + taskService + .createTaskQuery() .workbasketKeyDomainIn(workbasketIdentifiers.toArray(new KeyDomain[0])) .list(); - assertThat(results.size(), equalTo(42)); + assertThat(results.size(), equalTo(42)); - String[] ids = results.stream() + String[] ids = + results.stream() .map(t -> t.getWorkbasketSummary().getId()) .collect(Collectors.toList()) .toArray(new String[0]); - List result2 = taskService.createTaskQuery() - .workbasketIdIn(ids) - .list(); - assertThat(result2.size(), equalTo(42)); - } + List result2 = taskService.createTaskQuery().workbasketIdIn(ids).list(); + assertThat(result2.size(), equalTo(42)); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testThrowsExceptionIfNoOpenerPermissionOnQueriedWorkbasket() { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testThrowsExceptionIfNoOpenerPermissionOnQueriedWorkbasket() { + TaskService taskService = taskanaEngine.getTaskService(); - Assertions.assertThrows(NotAuthorizedToQueryWorkbasketException.class, () -> - taskService.createTaskQuery() + Assertions.assertThrows( + NotAuthorizedToQueryWorkbasketException.class, + () -> + taskService + .createTaskQuery() .workbasketKeyDomainIn(new KeyDomain("USER_2_1", "DOMAIN_A")) .list()); - } + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testThrowsExceptionIfNoOpenerPermissionOnAtLeastOneQueriedWorkbasket() { - TaskService taskService = taskanaEngine.getTaskService(); - Assertions.assertThrows(NotAuthorizedToQueryWorkbasketException.class, () -> - taskService.createTaskQuery() - .workbasketKeyDomainIn(new KeyDomain("USER_1_1", "DOMAIN_A"), new KeyDomain("USER_2_1", "DOMAIN_A")) + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testThrowsExceptionIfNoOpenerPermissionOnAtLeastOneQueriedWorkbasket() { + TaskService taskService = taskanaEngine.getTaskService(); + Assertions.assertThrows( + NotAuthorizedToQueryWorkbasketException.class, + () -> + taskService + .createTaskQuery() + .workbasketKeyDomainIn( + new KeyDomain("USER_1_1", "DOMAIN_A"), new KeyDomain("USER_2_1", "DOMAIN_A")) .list()); - } - + } } diff --git a/lib/taskana-core/src/test/java/acceptance/task/QueryTasksWithPaginationAccTest.java b/lib/taskana-core/src/test/java/acceptance/task/QueryTasksWithPaginationAccTest.java index 0247448dd..360e9eadb 100644 --- a/lib/taskana-core/src/test/java/acceptance/task/QueryTasksWithPaginationAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/task/QueryTasksWithPaginationAccTest.java @@ -3,14 +3,13 @@ package acceptance.task; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; +import acceptance.AbstractAccTest; import java.util.List; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.KeyDomain; import pro.taskana.TaskService; import pro.taskana.TaskSummary; @@ -18,182 +17,207 @@ import pro.taskana.exceptions.TaskanaRuntimeException; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "query tasks by workbasket with pagination" scenarios. - */ +/** Acceptance test for all "query tasks by workbasket with pagination" scenarios. */ @ExtendWith(JAASExtension.class) class QueryTasksWithPaginationAccTest extends AbstractAccTest { - QueryTasksWithPaginationAccTest() { - super(); - } + QueryTasksWithPaginationAccTest() { + super(); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testGetFirstPageOfTaskQueryWithOffset() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testGetFirstPageOfTaskQueryWithOffset() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .workbasketKeyDomainIn(new KeyDomain("GPK_KSC", "DOMAIN_A")) .list(0, 10); - assertThat(results.size(), equalTo(10)); - } + assertThat(results.size(), equalTo(10)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testSecondPageOfTaskQueryWithOffset() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testSecondPageOfTaskQueryWithOffset() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .workbasketKeyDomainIn(new KeyDomain("GPK_KSC", "DOMAIN_A")) .list(10, 10); - assertThat(results.size(), equalTo(10)); - } + assertThat(results.size(), equalTo(10)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testListOffsetAndLimitOutOfBounds() { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testListOffsetAndLimitOutOfBounds() { + TaskService taskService = taskanaEngine.getTaskService(); - // both will be 0, working - List results = taskService.createTaskQuery() + // both will be 0, working + List results = + taskService + .createTaskQuery() .workbasketKeyDomainIn(new KeyDomain("GPK_KSC", "DOMAIN_A")) .list(-1, -3); - assertThat(results.size(), equalTo(0)); + assertThat(results.size(), equalTo(0)); - // limit will be 0 - results = taskService.createTaskQuery() + // limit will be 0 + results = + taskService + .createTaskQuery() .workbasketKeyDomainIn(new KeyDomain("GPK_KSC", "DOMAIN_A")) .list(1, -3); - assertThat(results.size(), equalTo(0)); + assertThat(results.size(), equalTo(0)); - // offset will be 0 - results = taskService.createTaskQuery() + // offset will be 0 + results = + taskService + .createTaskQuery() .workbasketKeyDomainIn(new KeyDomain("GPK_KSC", "DOMAIN_A")) .list(-1, 3); - assertThat(results.size(), equalTo(3)); - } + assertThat(results.size(), equalTo(3)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testPaginationWithPages() { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testPaginationWithPages() { + TaskService taskService = taskanaEngine.getTaskService(); - // Getting full page - int pageNumber = 2; - int pageSize = 4; - List results = taskService.createTaskQuery() + // Getting full page + int pageNumber = 2; + int pageSize = 4; + List results = + taskService + .createTaskQuery() .workbasketKeyDomainIn(new KeyDomain("GPK_KSC", "DOMAIN_A")) .listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(4)); + assertThat(results.size(), equalTo(4)); - // Getting full page - pageNumber = 4; - pageSize = 1; - results = taskService.createTaskQuery() + // Getting full page + pageNumber = 4; + pageSize = 1; + results = + taskService + .createTaskQuery() .workbasketKeyDomainIn(new KeyDomain("GPK_KSC", "DOMAIN_A")) .listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(1)); + assertThat(results.size(), equalTo(1)); - // Getting last results on 1 big page - pageNumber = 1; - pageSize = 100; - results = taskService.createTaskQuery() + // Getting last results on 1 big page + pageNumber = 1; + pageSize = 100; + results = + taskService + .createTaskQuery() .workbasketKeyDomainIn(new KeyDomain("GPK_KSC", "DOMAIN_A")) .listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(22)); + assertThat(results.size(), equalTo(22)); - // Getting last results on multiple pages - pageNumber = 3; - pageSize = 10; - results = taskService.createTaskQuery() + // Getting last results on multiple pages + pageNumber = 3; + pageSize = 10; + results = + taskService + .createTaskQuery() .workbasketKeyDomainIn(new KeyDomain("GPK_KSC", "DOMAIN_A")) .listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(2)); - } + assertThat(results.size(), equalTo(2)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testPaginationNullAndNegativeLimitsIgnoring() { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testPaginationNullAndNegativeLimitsIgnoring() { + TaskService taskService = taskanaEngine.getTaskService(); - // 0 limit/size = 0 results - int pageNumber = 2; - int pageSize = 0; - List results = taskService.createTaskQuery() + // 0 limit/size = 0 results + int pageNumber = 2; + int pageSize = 0; + List results = + taskService + .createTaskQuery() .workbasketKeyDomainIn(new KeyDomain("GPK_KSC", "DOMAIN_A")) .listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(0)); + assertThat(results.size(), equalTo(0)); - // Negative size will be 0 = 0 results - pageNumber = 2; - pageSize = -1; - results = taskService.createTaskQuery() + // Negative size will be 0 = 0 results + pageNumber = 2; + pageSize = -1; + results = + taskService + .createTaskQuery() .workbasketKeyDomainIn(new KeyDomain("GPK_KSC", "DOMAIN_A")) .listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(0)); + assertThat(results.size(), equalTo(0)); - // Negative page = first page - pageNumber = -1; - pageSize = 10; - results = taskService.createTaskQuery() + // Negative page = first page + pageNumber = -1; + pageSize = 10; + results = + taskService + .createTaskQuery() .workbasketKeyDomainIn(new KeyDomain("GPK_KSC", "DOMAIN_A")) .listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(10)); - } + assertThat(results.size(), equalTo(10)); + } - /** - * Testcase only for DB2 users, because H2 doesn´t throw a Exception when the offset is set to high.
- * Using DB2 should throw a unchecked RuntimeException for a offset which is out of bounds. - */ - @Disabled - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testPaginationThrowingExceptionWhenPageOutOfBounds() { - TaskService taskService = taskanaEngine.getTaskService(); + /** + * Testcase only for DB2 users, because H2 doesn´t throw a Exception when the offset is set to + * high.
+ * Using DB2 should throw a unchecked RuntimeException for a offset which is out of bounds. + */ + @Disabled + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testPaginationThrowingExceptionWhenPageOutOfBounds() { + TaskService taskService = taskanaEngine.getTaskService(); - // entrypoint set outside result amount - int pageNumber = 6; - int pageSize = 10; + // entrypoint set outside result amount + int pageNumber = 6; + int pageSize = 10; - Assertions.assertThrows(TaskanaRuntimeException.class, () -> - taskService.createTaskQuery() + Assertions.assertThrows( + TaskanaRuntimeException.class, + () -> + taskService + .createTaskQuery() .workbasketKeyDomainIn(new KeyDomain("GPK_KSC", "DOMAIN_A")) .listPage(pageNumber, pageSize)); - } + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testCountOfTaskQuery() { - TaskService taskService = taskanaEngine.getTaskService(); - long count = taskService.createTaskQuery() + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testCountOfTaskQuery() { + TaskService taskService = taskanaEngine.getTaskService(); + long count = + taskService + .createTaskQuery() .workbasketKeyDomainIn(new KeyDomain("GPK_KSC", "DOMAIN_A")) .count(); - assertThat(count, equalTo(22L)); - } - - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testCountOfTaskQueryWithAttachmentChannelFilter() { - TaskService taskService = taskanaEngine.getTaskService(); - long count = taskService.createTaskQuery() - .attachmentChannelIn("ch6") - .count(); - assertThat(count, equalTo(2L)); - } + assertThat(count, equalTo(22L)); + } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testCountOfTaskQueryWithAttachmentChannelFilter() { + TaskService taskService = taskanaEngine.getTaskService(); + long count = taskService.createTaskQuery().attachmentChannelIn("ch6").count(); + assertThat(count, equalTo(2L)); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/task/QueryTasksWithSortingAccTest.java b/lib/taskana-core/src/test/java/acceptance/task/QueryTasksWithSortingAccTest.java index 60b9d6fed..83ab16b01 100644 --- a/lib/taskana-core/src/test/java/acceptance/task/QueryTasksWithSortingAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/task/QueryTasksWithSortingAccTest.java @@ -5,12 +5,11 @@ import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import acceptance.AbstractAccTest; import java.util.List; - import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.BaseQuery.SortDirection; import pro.taskana.KeyDomain; import pro.taskana.TaskService; @@ -19,79 +18,84 @@ import pro.taskana.TaskSummary; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "query tasks with sorting" scenarios. - */ +/** Acceptance test for all "query tasks with sorting" scenarios. */ @ExtendWith(JAASExtension.class) class QueryTasksWithSortingAccTest extends AbstractAccTest { - private static SortDirection asc = SortDirection.ASCENDING; - private static SortDirection desc = SortDirection.DESCENDING; + private static SortDirection asc = SortDirection.ASCENDING; + private static SortDirection desc = SortDirection.DESCENDING; - QueryTasksWithSortingAccTest() { - super(); - } + QueryTasksWithSortingAccTest() { + super(); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "group_2"}) - @Test - void testSortByModifiedAndDomain() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "group_2"}) + @Test + void testSortByModifiedAndDomain() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .workbasketKeyDomainIn(new KeyDomain("USER_3_2", "DOMAIN_B")) .orderByModified(desc) .orderByDomain(null) .list(); - assertThat(results.size(), equalTo(25)); - TaskSummary previousSummary = null; - for (TaskSummary taskSummary : results) { - if (previousSummary != null) { - assertFalse(previousSummary.getModified().isBefore(taskSummary.getModified())); - } - previousSummary = taskSummary; - } + assertThat(results.size(), equalTo(25)); + TaskSummary previousSummary = null; + for (TaskSummary taskSummary : results) { + if (previousSummary != null) { + assertFalse(previousSummary.getModified().isBefore(taskSummary.getModified())); + } + previousSummary = taskSummary; } + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "group_2"}) - @Test - void testSortByDomainNameAndCreated() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "group_2"}) + @Test + void testSortByDomainNameAndCreated() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .workbasketKeyDomainIn(new KeyDomain("USER_3_2", "DOMAIN_B")) .orderByDomain(asc) .orderByName(asc) .orderByCreated(null) .list(); - assertThat(results.size(), equalTo(25)); - TaskSummary previousSummary = null; - for (TaskSummary taskSummary : results) { - // System.out.println("domain: " + taskSummary.getDomain() + ", name: " + taskSummary.getName() + ", - // created: " + taskSummary.getCreated()); - if (previousSummary != null) { - assertTrue(taskSummary.getDomain().compareToIgnoreCase(previousSummary.getDomain()) >= 0); - if (taskSummary.getDomain().equals(previousSummary.getDomain())) { - assertTrue(taskSummary.getName().compareToIgnoreCase(previousSummary.getName()) >= 0); - if (taskSummary.getName().equals(previousSummary.getName())) { - assertFalse(taskSummary.getCreated().isBefore(previousSummary.getCreated())); - } - } - } - previousSummary = taskSummary; + assertThat(results.size(), equalTo(25)); + TaskSummary previousSummary = null; + for (TaskSummary taskSummary : results) { + // System.out.println("domain: " + taskSummary.getDomain() + ", name: " + + // taskSummary.getName() + ", + // created: " + taskSummary.getCreated()); + if (previousSummary != null) { + assertTrue(taskSummary.getDomain().compareToIgnoreCase(previousSummary.getDomain()) >= 0); + if (taskSummary.getDomain().equals(previousSummary.getDomain())) { + assertTrue(taskSummary.getName().compareToIgnoreCase(previousSummary.getName()) >= 0); + if (taskSummary.getName().equals(previousSummary.getName())) { + assertFalse(taskSummary.getCreated().isBefore(previousSummary.getCreated())); + } } + } + previousSummary = taskSummary; } + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "group_2"}) - @Test - void testSortByPorSystemNoteDueAndOwner() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "group_2"}) + @Test + void testSortByPorSystemNoteDueAndOwner() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .workbasketKeyDomainIn(new KeyDomain("USER_3_2", "DOMAIN_B")) .orderByPrimaryObjectReferenceSystem(SortDirection.DESCENDING) .orderByNote(null) @@ -99,24 +103,30 @@ class QueryTasksWithSortingAccTest extends AbstractAccTest { .orderByOwner(asc) .list(); - assertThat(results.size(), equalTo(25)); - TaskSummary previousSummary = null; - for (TaskSummary taskSummary : results) { - if (previousSummary != null) { - assertTrue(taskSummary.getPrimaryObjRef().getSystem().compareToIgnoreCase( - previousSummary.getPrimaryObjRef().getSystem()) <= 0); - } - previousSummary = taskSummary; - } + assertThat(results.size(), equalTo(25)); + TaskSummary previousSummary = null; + for (TaskSummary taskSummary : results) { + if (previousSummary != null) { + assertTrue( + taskSummary + .getPrimaryObjRef() + .getSystem() + .compareToIgnoreCase(previousSummary.getPrimaryObjRef().getSystem()) + <= 0); + } + previousSummary = taskSummary; } + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "group_2"}) - @Test - void testSortByPorSystemInstanceParentProcPlannedAndState() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "group_2"}) + @Test + void testSortByPorSystemInstanceParentProcPlannedAndState() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .workbasketKeyDomainIn(new KeyDomain("USER_3_2", "DOMAIN_B")) .orderByPrimaryObjectReferenceSystemInstance(desc) .orderByParentBusinessProcessId(asc) @@ -124,49 +134,62 @@ class QueryTasksWithSortingAccTest extends AbstractAccTest { .orderByState(asc) .list(); - assertThat(results.size(), equalTo(25)); - TaskSummary previousSummary = null; - for (TaskSummary taskSummary : results) { - if (previousSummary != null) { - assertTrue(taskSummary.getPrimaryObjRef().getSystemInstance().compareToIgnoreCase( - previousSummary.getPrimaryObjRef().getSystemInstance()) <= 0); - } - previousSummary = taskSummary; - } + assertThat(results.size(), equalTo(25)); + TaskSummary previousSummary = null; + for (TaskSummary taskSummary : results) { + if (previousSummary != null) { + assertTrue( + taskSummary + .getPrimaryObjRef() + .getSystemInstance() + .compareToIgnoreCase(previousSummary.getPrimaryObjRef().getSystemInstance()) + <= 0); + } + previousSummary = taskSummary; } + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "group_2"}) - @Test - void testSortByPorCompanyAndClaimed() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "group_2"}) + @Test + void testSortByPorCompanyAndClaimed() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .workbasketKeyDomainIn(new KeyDomain("USER_3_2", "DOMAIN_B")) .orderByPrimaryObjectReferenceCompany(desc) .orderByClaimed(asc) .list(); - assertThat(results.size(), equalTo(25)); - TaskSummary previousSummary = null; - for (TaskSummary taskSummary : results) { - // System.out.println("porCompany: " + taskSummary.getPrimaryObjRef().getCompany() + ", claimed: " - // + taskSummary.getClaimed()); - if (previousSummary != null) { - assertTrue(taskSummary.getPrimaryObjRef().getCompany().compareToIgnoreCase( - previousSummary.getPrimaryObjRef().getCompany()) <= 0); - } - previousSummary = taskSummary; - } + assertThat(results.size(), equalTo(25)); + TaskSummary previousSummary = null; + for (TaskSummary taskSummary : results) { + // System.out.println("porCompany: " + taskSummary.getPrimaryObjRef().getCompany() + ", + // claimed: " + // + taskSummary.getClaimed()); + if (previousSummary != null) { + assertTrue( + taskSummary + .getPrimaryObjRef() + .getCompany() + .compareToIgnoreCase(previousSummary.getPrimaryObjRef().getCompany()) + <= 0); + } + previousSummary = taskSummary; } + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "group_2"}) - @Test - void testSortByWbKeyPrioPorValueAndCompleted() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "group_2"}) + @Test + void testSortByWbKeyPrioPorValueAndCompleted() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .stateIn(TaskState.READY) .orderByWorkbasketKey(null) .workbasketIdIn("WBI:100000000000000000000000000000000015") @@ -175,24 +198,30 @@ class QueryTasksWithSortingAccTest extends AbstractAccTest { .orderByCompleted(desc) .list(); - assertThat(results.size(), equalTo(22)); - TaskSummary previousSummary = null; - for (TaskSummary taskSummary : results) { - if (previousSummary != null) { - assertTrue(taskSummary.getWorkbasketSummary().getKey().compareToIgnoreCase( - previousSummary.getWorkbasketSummary().getKey()) >= 0); - } - previousSummary = taskSummary; - } + assertThat(results.size(), equalTo(22)); + TaskSummary previousSummary = null; + for (TaskSummary taskSummary : results) { + if (previousSummary != null) { + assertTrue( + taskSummary + .getWorkbasketSummary() + .getKey() + .compareToIgnoreCase(previousSummary.getWorkbasketSummary().getKey()) + >= 0); + } + previousSummary = taskSummary; } + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "group_2"}) - @Test - void testSortBpIdClassificationIdDescriptionAndPorType() { - TaskService taskService = taskanaEngine.getTaskService(); - List results = taskService.createTaskQuery() + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "group_2"}) + @Test + void testSortBpIdClassificationIdDescriptionAndPorType() { + TaskService taskService = taskanaEngine.getTaskService(); + List results = + taskService + .createTaskQuery() .stateIn(TaskState.READY) .workbasketIdIn("WBI:100000000000000000000000000000000015") .orderByBusinessProcessId(asc) @@ -200,15 +229,17 @@ class QueryTasksWithSortingAccTest extends AbstractAccTest { .orderByPrimaryObjectReferenceType(SortDirection.DESCENDING) .list(); - assertThat(results.size(), equalTo(22)); - TaskSummary previousSummary = null; - for (TaskSummary taskSummary : results) { - if (previousSummary != null) { - assertTrue(taskSummary.getBusinessProcessId().compareToIgnoreCase( - previousSummary.getBusinessProcessId()) >= 0); - } - previousSummary = taskSummary; - } + assertThat(results.size(), equalTo(22)); + TaskSummary previousSummary = null; + for (TaskSummary taskSummary : results) { + if (previousSummary != null) { + assertTrue( + taskSummary + .getBusinessProcessId() + .compareToIgnoreCase(previousSummary.getBusinessProcessId()) + >= 0); + } + previousSummary = taskSummary; } - + } } diff --git a/lib/taskana-core/src/test/java/acceptance/task/TransferTaskAccTest.java b/lib/taskana-core/src/test/java/acceptance/task/TransferTaskAccTest.java index 0122761a3..2fca04c0f 100644 --- a/lib/taskana-core/src/test/java/acceptance/task/TransferTaskAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/task/TransferTaskAccTest.java @@ -8,17 +8,16 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import acceptance.AbstractAccTest; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.BulkOperationResults; import pro.taskana.Task; import pro.taskana.TaskService; @@ -34,338 +33,361 @@ import pro.taskana.exceptions.WorkbasketNotFoundException; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "transfer task" scenarios. - */ +/** Acceptance test for all "transfer task" scenarios. */ @ExtendWith(JAASExtension.class) class TransferTaskAccTest extends AbstractAccTest { - TransferTaskAccTest() { - super(); - } + TransferTaskAccTest() { + super(); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testTransferTaskToWorkbasketId() - throws NotAuthorizedException, WorkbasketNotFoundException, TaskNotFoundException, InvalidStateException, - InvalidOwnerException { - TaskService taskService = taskanaEngine.getTaskService(); - Task task = taskService.getTask("TKI:000000000000000000000000000000000003"); - taskService.claim(task.getId()); - taskService.setTaskRead(task.getId(), true); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testTransferTaskToWorkbasketId() + throws NotAuthorizedException, WorkbasketNotFoundException, TaskNotFoundException, + InvalidStateException, InvalidOwnerException { + TaskService taskService = taskanaEngine.getTaskService(); + Task task = taskService.getTask("TKI:000000000000000000000000000000000003"); + taskService.claim(task.getId()); + taskService.setTaskRead(task.getId(), true); - taskService.transfer(task.getId(), "WBI:100000000000000000000000000000000006"); + taskService.transfer(task.getId(), "WBI:100000000000000000000000000000000006"); - Task transferredTask = taskService.getTask("TKI:000000000000000000000000000000000003"); - assertNotNull(transferredTask); - assertTrue(transferredTask.isTransferred()); - assertFalse(transferredTask.isRead()); - assertEquals(TaskState.READY, transferredTask.getState()); - } + Task transferredTask = taskService.getTask("TKI:000000000000000000000000000000000003"); + assertNotNull(transferredTask); + assertTrue(transferredTask.isTransferred()); + assertFalse(transferredTask.isRead()); + assertEquals(TaskState.READY, transferredTask.getState()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testTransferTaskToWorkbasketKeyDomain() - throws NotAuthorizedException, WorkbasketNotFoundException, TaskNotFoundException, InvalidStateException, - InvalidOwnerException { - TaskService taskService = taskanaEngine.getTaskService(); - Task task = taskService.getTask("TKI:000000000000000000000000000000000003"); - taskService.claim(task.getId()); - taskService.setTaskRead(task.getId(), true); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testTransferTaskToWorkbasketKeyDomain() + throws NotAuthorizedException, WorkbasketNotFoundException, TaskNotFoundException, + InvalidStateException, InvalidOwnerException { + TaskService taskService = taskanaEngine.getTaskService(); + Task task = taskService.getTask("TKI:000000000000000000000000000000000003"); + taskService.claim(task.getId()); + taskService.setTaskRead(task.getId(), true); - taskService.transfer(task.getId(), "USER_1_1", "DOMAIN_A"); + taskService.transfer(task.getId(), "USER_1_1", "DOMAIN_A"); - Task transferredTask = taskService.getTask("TKI:000000000000000000000000000000000003"); - assertNotNull(transferredTask); - assertTrue(transferredTask.isTransferred()); - assertFalse(transferredTask.isRead()); - assertEquals(TaskState.READY, transferredTask.getState()); - } + Task transferredTask = taskService.getTask("TKI:000000000000000000000000000000000003"); + assertNotNull(transferredTask); + assertTrue(transferredTask.isTransferred()); + assertFalse(transferredTask.isRead()); + assertEquals(TaskState.READY, transferredTask.getState()); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testDomainChangingWhenTransferTask() - throws NotAuthorizedException, WorkbasketNotFoundException, TaskNotFoundException, InvalidStateException { - TaskService taskService = taskanaEngine.getTaskService(); - Task task = taskService.getTask("TKI:000000000000000000000000000000000000"); - String domain1 = task.getDomain(); + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testDomainChangingWhenTransferTask() + throws NotAuthorizedException, WorkbasketNotFoundException, TaskNotFoundException, + InvalidStateException { + TaskService taskService = taskanaEngine.getTaskService(); + Task task = taskService.getTask("TKI:000000000000000000000000000000000000"); + String domain1 = task.getDomain(); - Task transferedTask = taskService.transfer(task.getId(), "GPK_B_KSC_1", "DOMAIN_B"); + Task transferedTask = taskService.transfer(task.getId(), "GPK_B_KSC_1", "DOMAIN_B"); - assertNotNull(transferedTask); - assertNotEquals(domain1, transferedTask.getDomain()); - } + assertNotNull(transferedTask); + assertNotEquals(domain1, transferedTask.getDomain()); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testThrowsExceptionIfTransferWithNoTransferAuthorization() - throws NotAuthorizedException, TaskNotFoundException { - TaskService taskService = taskanaEngine.getTaskService(); - Task task = taskService.getTask("TKI:000000000000000000000000000000000001"); + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testThrowsExceptionIfTransferWithNoTransferAuthorization() + throws NotAuthorizedException, TaskNotFoundException { + TaskService taskService = taskanaEngine.getTaskService(); + Task task = taskService.getTask("TKI:000000000000000000000000000000000001"); - Assertions.assertThrows(NotAuthorizedException.class, () -> - taskService.transfer(task.getId(), "WBI:100000000000000000000000000000000005")); - } + Assertions.assertThrows( + NotAuthorizedException.class, + () -> taskService.transfer(task.getId(), "WBI:100000000000000000000000000000000005")); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testTransferDestinationWorkbasketDoesNotExist() - throws NotAuthorizedException, TaskNotFoundException, InvalidStateException, - InvalidOwnerException { - TaskService taskService = taskanaEngine.getTaskService(); - Task task = taskService.getTask("TKI:000000000000000000000000000000000003"); - taskService.claim(task.getId()); - taskService.setTaskRead(task.getId(), true); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testTransferDestinationWorkbasketDoesNotExist() + throws NotAuthorizedException, TaskNotFoundException, InvalidStateException, + InvalidOwnerException { + TaskService taskService = taskanaEngine.getTaskService(); + Task task = taskService.getTask("TKI:000000000000000000000000000000000003"); + taskService.claim(task.getId()); + taskService.setTaskRead(task.getId(), true); - Assertions.assertThrows(WorkbasketNotFoundException.class, () -> - taskService.transfer(task.getId(), "INVALID")); - } + Assertions.assertThrows( + WorkbasketNotFoundException.class, () -> taskService.transfer(task.getId(), "INVALID")); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testTransferTaskDoesNotExist() { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testTransferTaskDoesNotExist() { + TaskService taskService = taskanaEngine.getTaskService(); - Assertions.assertThrows(TaskNotFoundException.class, () -> - taskService.transfer("Invalid", "WBI:100000000000000000000000000000000006")); - } + Assertions.assertThrows( + TaskNotFoundException.class, + () -> taskService.transfer("Invalid", "WBI:100000000000000000000000000000000006")); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"teamlead_1"}) - @Test - void testTransferNotAuthorizationOnWorkbasketTransfer() { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"teamlead_1"}) + @Test + void testTransferNotAuthorizationOnWorkbasketTransfer() { + TaskService taskService = taskanaEngine.getTaskService(); - Assertions.assertThrows(NotAuthorizedException.class, () -> - taskService.transfer("TKI:200000000000000000000000000000000007", + Assertions.assertThrows( + NotAuthorizedException.class, + () -> + taskService.transfer( + "TKI:200000000000000000000000000000000007", "WBI:100000000000000000000000000000000006")); - } + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testThrowsExceptionIfTaskIsAlreadyCompleted() - throws NotAuthorizedException, TaskNotFoundException { - TaskService taskService = taskanaEngine.getTaskService(); - Task task = taskService.getTask("TKI:100000000000000000000000000000000006"); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testThrowsExceptionIfTaskIsAlreadyCompleted() + throws NotAuthorizedException, TaskNotFoundException { + TaskService taskService = taskanaEngine.getTaskService(); + Task task = taskService.getTask("TKI:100000000000000000000000000000000006"); - Assertions.assertThrows(InvalidStateException.class, () -> - taskService.transfer(task.getId(), "WBI:100000000000000000000000000000000005")); - } + Assertions.assertThrows( + InvalidStateException.class, + () -> taskService.transfer(task.getId(), "WBI:100000000000000000000000000000000005")); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testThrowsExceptionIfTransferWithNoAppendAuthorization() - throws NotAuthorizedException, TaskNotFoundException { - TaskService taskService = taskanaEngine.getTaskService(); - Task task = taskService.getTask("TKI:000000000000000000000000000000000002"); + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testThrowsExceptionIfTransferWithNoAppendAuthorization() + throws NotAuthorizedException, TaskNotFoundException { + TaskService taskService = taskanaEngine.getTaskService(); + Task task = taskService.getTask("TKI:000000000000000000000000000000000002"); - Assertions.assertThrows(NotAuthorizedException.class, () -> - taskService.transfer(task.getId(), "WBI:100000000000000000000000000000000008")); - } + Assertions.assertThrows( + NotAuthorizedException.class, + () -> taskService.transfer(task.getId(), "WBI:100000000000000000000000000000000008")); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testBulkTransferTaskToWorkbasketById() - throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException, TaskNotFoundException { - Instant before = Instant.now(); - TaskService taskService = taskanaEngine.getTaskService(); - ArrayList taskIdList = new ArrayList<>(); - taskIdList.add("TKI:000000000000000000000000000000000004"); - taskIdList.add("TKI:000000000000000000000000000000000005"); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testBulkTransferTaskToWorkbasketById() + throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException, + TaskNotFoundException { + Instant before = Instant.now(); + TaskService taskService = taskanaEngine.getTaskService(); + ArrayList taskIdList = new ArrayList<>(); + taskIdList.add("TKI:000000000000000000000000000000000004"); + taskIdList.add("TKI:000000000000000000000000000000000005"); - BulkOperationResults results = taskService - .transferTasks("WBI:100000000000000000000000000000000006", taskIdList); - assertFalse(results.containsErrors()); + BulkOperationResults results = + taskService.transferTasks("WBI:100000000000000000000000000000000006", taskIdList); + assertFalse(results.containsErrors()); - Workbasket wb = taskanaEngine.getWorkbasketService().getWorkbasket("USER_1_1", "DOMAIN_A"); - Task transferredTask = taskService.getTask("TKI:000000000000000000000000000000000004"); - assertNotNull(transferredTask); - assertTrue(transferredTask.isTransferred()); - assertFalse(transferredTask.isRead()); - assertEquals(TaskState.READY, transferredTask.getState()); - assertThat(transferredTask.getWorkbasketKey(), equalTo(wb.getKey())); - assertThat(transferredTask.getDomain(), equalTo(wb.getDomain())); - assertFalse(transferredTask.getModified().isBefore(before)); - assertThat(transferredTask.getOwner(), equalTo(null)); - transferredTask = taskService.getTask("TKI:000000000000000000000000000000000005"); - assertNotNull(transferredTask); - assertTrue(transferredTask.isTransferred()); - assertFalse(transferredTask.isRead()); - assertEquals(TaskState.READY, transferredTask.getState()); - assertThat(transferredTask.getWorkbasketKey(), equalTo(wb.getKey())); - assertThat(transferredTask.getDomain(), equalTo(wb.getDomain())); - assertFalse(transferredTask.getModified().isBefore(before)); - assertThat(transferredTask.getOwner(), equalTo(null)); - } + Workbasket wb = taskanaEngine.getWorkbasketService().getWorkbasket("USER_1_1", "DOMAIN_A"); + Task transferredTask = taskService.getTask("TKI:000000000000000000000000000000000004"); + assertNotNull(transferredTask); + assertTrue(transferredTask.isTransferred()); + assertFalse(transferredTask.isRead()); + assertEquals(TaskState.READY, transferredTask.getState()); + assertThat(transferredTask.getWorkbasketKey(), equalTo(wb.getKey())); + assertThat(transferredTask.getDomain(), equalTo(wb.getDomain())); + assertFalse(transferredTask.getModified().isBefore(before)); + assertThat(transferredTask.getOwner(), equalTo(null)); + transferredTask = taskService.getTask("TKI:000000000000000000000000000000000005"); + assertNotNull(transferredTask); + assertTrue(transferredTask.isTransferred()); + assertFalse(transferredTask.isRead()); + assertEquals(TaskState.READY, transferredTask.getState()); + assertThat(transferredTask.getWorkbasketKey(), equalTo(wb.getKey())); + assertThat(transferredTask.getDomain(), equalTo(wb.getDomain())); + assertFalse(transferredTask.getModified().isBefore(before)); + assertThat(transferredTask.getOwner(), equalTo(null)); + } - @WithAccessId(userName = "teamlead_1", groupNames = {"group_1"}) - @Test - void testBulkTransferTaskWithExceptions() - throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException, TaskNotFoundException { - TaskService taskService = taskanaEngine.getTaskService(); - Workbasket wb = taskanaEngine.getWorkbasketService().getWorkbasket("USER_1_1", "DOMAIN_A"); - Instant before = Instant.now(); - ArrayList taskIdList = new ArrayList<>(); - taskIdList.add("TKI:000000000000000000000000000000000006"); // working - taskIdList.add("TKI:000000000000000000000000000000000041"); // NotAuthorized READ - taskIdList.add("TKI:200000000000000000000000000000000006"); // NotAuthorized TRANSFER - taskIdList.add(""); // InvalidArgument - taskIdList.add(null); // InvalidArgument (added with ""), duplicate - taskIdList.add("TKI:000000000000000000000000000000000099"); // TaskNotFound - taskIdList.add("TKI:100000000000000000000000000000000006"); // already completed + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testBulkTransferTaskWithExceptions() + throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException, + TaskNotFoundException { + TaskService taskService = taskanaEngine.getTaskService(); + Workbasket wb = taskanaEngine.getWorkbasketService().getWorkbasket("USER_1_1", "DOMAIN_A"); + Instant before = Instant.now(); + ArrayList taskIdList = new ArrayList<>(); + taskIdList.add("TKI:000000000000000000000000000000000006"); // working + taskIdList.add("TKI:000000000000000000000000000000000041"); // NotAuthorized READ + taskIdList.add("TKI:200000000000000000000000000000000006"); // NotAuthorized TRANSFER + taskIdList.add(""); // InvalidArgument + taskIdList.add(null); // InvalidArgument (added with ""), duplicate + taskIdList.add("TKI:000000000000000000000000000000000099"); // TaskNotFound + taskIdList.add("TKI:100000000000000000000000000000000006"); // already completed - BulkOperationResults results = taskService - .transferTasks("WBI:100000000000000000000000000000000006", taskIdList); - // check for exceptions in bulk - assertTrue(results.containsErrors()); - assertThat(results.getErrorMap().values().size(), equalTo(5)); - assertEquals(results.getErrorForId("TKI:000000000000000000000000000000000041").getClass(), - NotAuthorizedException.class); - assertEquals(results.getErrorForId("TKI:200000000000000000000000000000000006").getClass(), - InvalidStateException.class); - assertEquals(results.getErrorForId("").getClass(), InvalidArgumentException.class); - assertEquals(results.getErrorForId("TKI:000000000000000000000000000000000099").getClass(), - TaskNotFoundException.class); - assertEquals(results.getErrorForId("TKI:100000000000000000000000000000000006").getClass(), - InvalidStateException.class); + BulkOperationResults results = + taskService.transferTasks("WBI:100000000000000000000000000000000006", taskIdList); + // check for exceptions in bulk + assertTrue(results.containsErrors()); + assertThat(results.getErrorMap().values().size(), equalTo(5)); + assertEquals( + results.getErrorForId("TKI:000000000000000000000000000000000041").getClass(), + NotAuthorizedException.class); + assertEquals( + results.getErrorForId("TKI:200000000000000000000000000000000006").getClass(), + InvalidStateException.class); + assertEquals(results.getErrorForId("").getClass(), InvalidArgumentException.class); + assertEquals( + results.getErrorForId("TKI:000000000000000000000000000000000099").getClass(), + TaskNotFoundException.class); + assertEquals( + results.getErrorForId("TKI:100000000000000000000000000000000006").getClass(), + InvalidStateException.class); - // verify valid requests - Task transferredTask = taskService.getTask("TKI:000000000000000000000000000000000006"); - assertNotNull(transferredTask); - assertTrue(transferredTask.isTransferred()); - assertFalse(transferredTask.isRead()); - assertEquals(TaskState.READY, transferredTask.getState()); - assertThat(transferredTask.getWorkbasketKey(), equalTo(wb.getKey())); - assertThat(transferredTask.getDomain(), equalTo(wb.getDomain())); - assertFalse(transferredTask.getModified().isBefore(before)); - assertThat(transferredTask.getOwner(), equalTo(null)); + // verify valid requests + Task transferredTask = taskService.getTask("TKI:000000000000000000000000000000000006"); + assertNotNull(transferredTask); + assertTrue(transferredTask.isTransferred()); + assertFalse(transferredTask.isRead()); + assertEquals(TaskState.READY, transferredTask.getState()); + assertThat(transferredTask.getWorkbasketKey(), equalTo(wb.getKey())); + assertThat(transferredTask.getDomain(), equalTo(wb.getDomain())); + assertFalse(transferredTask.getModified().isBefore(before)); + assertThat(transferredTask.getOwner(), equalTo(null)); - transferredTask = taskService.getTask("TKI:000000000000000000000000000000000002"); - assertNotNull(transferredTask); - assertFalse(transferredTask.isTransferred()); - assertEquals("USER_1_1", transferredTask.getWorkbasketKey()); + transferredTask = taskService.getTask("TKI:000000000000000000000000000000000002"); + assertNotNull(transferredTask); + assertFalse(transferredTask.isTransferred()); + assertEquals("USER_1_1", transferredTask.getWorkbasketKey()); - transferredTask = taskService.getTask("TKI:200000000000000000000000000000000006"); - assertNotNull(transferredTask); - assertFalse(transferredTask.isTransferred()); - assertEquals("TEAMLEAD_2", transferredTask.getWorkbasketKey()); + transferredTask = taskService.getTask("TKI:200000000000000000000000000000000006"); + assertNotNull(transferredTask); + assertFalse(transferredTask.isTransferred()); + assertEquals("TEAMLEAD_2", transferredTask.getWorkbasketKey()); - transferredTask = taskService.getTask("TKI:100000000000000000000000000000000006"); - assertNotNull(transferredTask); - assertFalse(transferredTask.isTransferred()); - assertEquals("TEAMLEAD_1", transferredTask.getWorkbasketKey()); - } + transferredTask = taskService.getTask("TKI:100000000000000000000000000000000006"); + assertNotNull(transferredTask); + assertFalse(transferredTask.isTransferred()); + assertEquals("TEAMLEAD_1", transferredTask.getWorkbasketKey()); + } - @WithAccessId(userName = "teamlead_1") - @Test - void testBulkTransferTaskWithoutAppendPermissionOnTarget() { - TaskService taskService = taskanaEngine.getTaskService(); - ArrayList taskIdList = new ArrayList<>(); - taskIdList.add("TKI:000000000000000000000000000000000006"); // working - taskIdList.add("TKI:000000000000000000000000000000000041"); // NotAuthorized READ + @WithAccessId(userName = "teamlead_1") + @Test + void testBulkTransferTaskWithoutAppendPermissionOnTarget() { + TaskService taskService = taskanaEngine.getTaskService(); + ArrayList taskIdList = new ArrayList<>(); + taskIdList.add("TKI:000000000000000000000000000000000006"); // working + taskIdList.add("TKI:000000000000000000000000000000000041"); // NotAuthorized READ - Throwable t = Assertions.assertThrows(NotAuthorizedException.class, () -> - taskService - .transferTasks("WBI:100000000000000000000000000000000010", taskIdList)); + Throwable t = + Assertions.assertThrows( + NotAuthorizedException.class, + () -> + taskService.transferTasks("WBI:100000000000000000000000000000000010", taskIdList)); - assertTrue(t.getMessage().contains("APPEND")); - } + assertTrue(t.getMessage().contains("APPEND")); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testTransferTasksWithListNotSupportingRemove() throws NotAuthorizedException, InvalidArgumentException, - WorkbasketNotFoundException { - TaskService taskService = taskanaEngine.getTaskService(); - List taskIds = Collections.singletonList("TKI:000000000000000000000000000000000006"); - taskService.transferTasks("WBI:100000000000000000000000000000000006", taskIds); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testTransferTasksWithListNotSupportingRemove() + throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException { + TaskService taskService = taskanaEngine.getTaskService(); + List taskIds = Collections.singletonList("TKI:000000000000000000000000000000000006"); + taskService.transferTasks("WBI:100000000000000000000000000000000006", taskIds); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testTransferTasksWithInvalidTasksIdList() { - TaskService taskService = taskanaEngine.getTaskService(); - // test with invalid list + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testTransferTasksWithInvalidTasksIdList() { + TaskService taskService = taskanaEngine.getTaskService(); + // test with invalid list - Throwable t = Assertions.assertThrows(InvalidArgumentException.class, () -> - taskService.transferTasks("WBI:100000000000000000000000000000000006", null)); - assertEquals(t.getMessage(), "TaskIds must not be null."); + Throwable t = + Assertions.assertThrows( + InvalidArgumentException.class, + () -> taskService.transferTasks("WBI:100000000000000000000000000000000006", null)); + assertEquals(t.getMessage(), "TaskIds must not be null."); - // test with list containing only invalid arguments - Throwable t2 = Assertions.assertThrows(InvalidArgumentException.class, () -> - taskService.transferTasks("WBI:100000000000000000000000000000000006", Arrays.asList("", "", "", null))); - assertEquals(t2.getMessage(), "TaskIds must not contain only invalid arguments."); - } + // test with list containing only invalid arguments + Throwable t2 = + Assertions.assertThrows( + InvalidArgumentException.class, + () -> + taskService.transferTasks( + "WBI:100000000000000000000000000000000006", Arrays.asList("", "", "", null))); + assertEquals(t2.getMessage(), "TaskIds must not contain only invalid arguments."); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testThrowsExceptionIfEmptyListIsSupplied() { - TaskService taskService = taskanaEngine.getTaskService(); - List taskIds = new ArrayList<>(); - Assertions.assertThrows(InvalidArgumentException.class, () -> - taskService.transferTasks("WBI:100000000000000000000000000000000006", taskIds)); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testThrowsExceptionIfEmptyListIsSupplied() { + TaskService taskService = taskanaEngine.getTaskService(); + List taskIds = new ArrayList<>(); + Assertions.assertThrows( + InvalidArgumentException.class, + () -> taskService.transferTasks("WBI:100000000000000000000000000000000006", taskIds)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testBulkTransferByWorkbasketAndDomainByKey() - throws WorkbasketNotFoundException, NotAuthorizedException, InvalidArgumentException, TaskNotFoundException { - Instant before = Instant.now(); - TaskService taskService = taskanaEngine.getTaskService(); - List taskIdList = new ArrayList<>(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testBulkTransferByWorkbasketAndDomainByKey() + throws WorkbasketNotFoundException, NotAuthorizedException, InvalidArgumentException, + TaskNotFoundException { + Instant before = Instant.now(); + TaskService taskService = taskanaEngine.getTaskService(); + List taskIdList = new ArrayList<>(); - taskIdList.add("TKI:000000000000000000000000000000000023"); - taskIdList.add("TKI:000000000000000000000000000000000024"); + taskIdList.add("TKI:000000000000000000000000000000000023"); + taskIdList.add("TKI:000000000000000000000000000000000024"); - BulkOperationResults results = taskService - .transferTasks("GPK_B_KSC_1", "DOMAIN_B", taskIdList); - assertFalse(results.containsErrors()); - - Workbasket wb = taskanaEngine.getWorkbasketService().getWorkbasket("GPK_B_KSC_1", "DOMAIN_B"); - Task transferredTask = taskService.getTask("TKI:000000000000000000000000000000000023"); - assertNotNull(transferredTask); - assertTrue(transferredTask.isTransferred()); - assertFalse(transferredTask.isRead()); - assertEquals(TaskState.READY, transferredTask.getState()); - assertThat(transferredTask.getWorkbasketKey(), equalTo(wb.getKey())); - assertThat(transferredTask.getDomain(), equalTo(wb.getDomain())); - assertFalse(transferredTask.getModified().isBefore(before)); - assertThat(transferredTask.getOwner(), equalTo(null)); - transferredTask = taskService.getTask("TKI:000000000000000000000000000000000024"); - assertNotNull(transferredTask); - assertTrue(transferredTask.isTransferred()); - assertFalse(transferredTask.isRead()); - assertEquals(TaskState.READY, transferredTask.getState()); - assertThat(transferredTask.getWorkbasketKey(), equalTo(wb.getKey())); - assertThat(transferredTask.getDomain(), equalTo(wb.getDomain())); - assertFalse(transferredTask.getModified().isBefore(before)); - assertThat(transferredTask.getOwner(), equalTo(null)); - } + BulkOperationResults results = + taskService.transferTasks("GPK_B_KSC_1", "DOMAIN_B", taskIdList); + assertFalse(results.containsErrors()); + Workbasket wb = taskanaEngine.getWorkbasketService().getWorkbasket("GPK_B_KSC_1", "DOMAIN_B"); + Task transferredTask = taskService.getTask("TKI:000000000000000000000000000000000023"); + assertNotNull(transferredTask); + assertTrue(transferredTask.isTransferred()); + assertFalse(transferredTask.isRead()); + assertEquals(TaskState.READY, transferredTask.getState()); + assertThat(transferredTask.getWorkbasketKey(), equalTo(wb.getKey())); + assertThat(transferredTask.getDomain(), equalTo(wb.getDomain())); + assertFalse(transferredTask.getModified().isBefore(before)); + assertThat(transferredTask.getOwner(), equalTo(null)); + transferredTask = taskService.getTask("TKI:000000000000000000000000000000000024"); + assertNotNull(transferredTask); + assertTrue(transferredTask.isTransferred()); + assertFalse(transferredTask.isRead()); + assertEquals(TaskState.READY, transferredTask.getState()); + assertThat(transferredTask.getWorkbasketKey(), equalTo(wb.getKey())); + assertThat(transferredTask.getDomain(), equalTo(wb.getDomain())); + assertFalse(transferredTask.getModified().isBefore(before)); + assertThat(transferredTask.getOwner(), equalTo(null)); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/task/UpdateTaskAccTest.java b/lib/taskana-core/src/test/java/acceptance/task/UpdateTaskAccTest.java index 135e90516..03ec3db41 100644 --- a/lib/taskana-core/src/test/java/acceptance/task/UpdateTaskAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/task/UpdateTaskAccTest.java @@ -10,17 +10,16 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import acceptance.AbstractAccTest; import java.time.Instant; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.ClassificationSummary; import pro.taskana.ObjectReference; import pro.taskana.Task; @@ -38,305 +37,300 @@ import pro.taskana.impl.TaskImpl; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "update task" scenarios. - */ +/** Acceptance test for all "update task" scenarios. */ @ExtendWith(JAASExtension.class) class UpdateTaskAccTest extends AbstractAccTest { - UpdateTaskAccTest() { - super(); + UpdateTaskAccTest() { + super(); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testUpdatePrimaryObjectReferenceOfTask() + throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, + TaskNotFoundException, ConcurrencyException, AttachmentPersistenceException { + + TaskService taskService = taskanaEngine.getTaskService(); + Task task = taskService.getTask("TKI:000000000000000000000000000000000000"); + Instant modifiedOriginal = task.getModified(); + task.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "7654321")); + task.setBusinessProcessId("MY_PROCESS_ID"); + task.setParentBusinessProcessId("MY_PARENT_PROCESS_ID"); + Task updatedTask = taskService.updateTask(task); + updatedTask = taskService.getTask(updatedTask.getId()); + + assertNotNull(updatedTask); + assertEquals("7654321", updatedTask.getPrimaryObjRef().getValue()); + assertNotNull(updatedTask.getCreated()); + assertNotNull(updatedTask.getModified()); + assertFalse(modifiedOriginal.isAfter(updatedTask.getModified())); + assertNotEquals(updatedTask.getCreated(), updatedTask.getModified()); + assertEquals(task.getCreated(), updatedTask.getCreated()); + assertEquals(task.isRead(), updatedTask.isRead()); + assertEquals("MY_PROCESS_ID", updatedTask.getBusinessProcessId()); + assertEquals("MY_PARENT_PROCESS_ID", updatedTask.getParentBusinessProcessId()); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testThrowsExceptionIfMandatoryPrimaryObjectReferenceIsNotSetOrIncomplete() + throws NotAuthorizedException, ClassificationNotFoundException, TaskNotFoundException, + ConcurrencyException, AttachmentPersistenceException { + + TaskService taskService = taskanaEngine.getTaskService(); + Task task = taskService.getTask("TKI:000000000000000000000000000000000000"); + task.setPrimaryObjRef(null); + Assertions.assertThrows(InvalidArgumentException.class, () -> taskService.updateTask(task)); + + task.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", null)); + Assertions.assertThrows(InvalidArgumentException.class, () -> taskService.updateTask(task)); + + task.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", null, "1234567")); + Assertions.assertThrows(InvalidArgumentException.class, () -> taskService.updateTask(task)); + + task.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", null, "VNR", "1234567")); + Assertions.assertThrows(InvalidArgumentException.class, () -> taskService.updateTask(task)); + + task.setPrimaryObjRef(createObjectReference("COMPANY_A", null, "INSTANCE_A", "VNR", "1234567")); + Assertions.assertThrows(InvalidArgumentException.class, () -> taskService.updateTask(task)); + + task.setPrimaryObjRef(createObjectReference(null, "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + Assertions.assertThrows(InvalidArgumentException.class, () -> taskService.updateTask(task)); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testThrowsExceptionIfTaskHasAlreadyBeenUpdated() + throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, + TaskNotFoundException, ConcurrencyException, AttachmentPersistenceException { + + TaskService taskService = taskanaEngine.getTaskService(); + Task task = taskService.getTask("TKI:000000000000000000000000000000000000"); + Task task2 = taskService.getTask("TKI:000000000000000000000000000000000000"); + + task.setCustomAttribute("1", "willi"); + taskService.updateTask(task); + + task2.setCustomAttribute("2", "Walter"); + // TODO flaky test ... if speed is too high, + Assertions.assertThrows( + ConcurrencyException.class, + () -> taskService.updateTask(task2), + "The task has already been updated by another user"); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testUpdateClassificationOfTask() + throws TaskNotFoundException, ClassificationNotFoundException, InvalidArgumentException, + ConcurrencyException, NotAuthorizedException, AttachmentPersistenceException { + + TaskService taskService = taskanaEngine.getTaskService(); + Task task = taskService.getTask("TKI:000000000000000000000000000000000000"); + ClassificationSummary classificationSummary = task.getClassificationSummary(); + task.setClassificationKey("T2100"); + Task updatedTask = taskService.updateTask(task); + updatedTask = taskService.getTask(updatedTask.getId()); + + assertNotNull(updatedTask); + assertEquals("T2100", updatedTask.getClassificationSummary().getKey()); + assertThat(updatedTask.getClassificationSummary(), not(equalTo(classificationSummary))); + assertNotEquals(updatedTask.getCreated(), updatedTask.getModified()); + assertEquals(task.getPlanned(), updatedTask.getPlanned()); + assertEquals(task.getName(), updatedTask.getName()); + assertEquals(task.getDescription(), updatedTask.getDescription()); + } + + @WithAccessId( + userName = "user_1_2", + groupNames = {"group_1"}) + @Test + void testUpdateReadFlagOfTask() throws TaskNotFoundException, NotAuthorizedException { + + TaskService taskService = taskanaEngine.getTaskService(); + + taskService.setTaskRead("TKI:000000000000000000000000000000000030", true); + Task updatedTask = taskService.getTask("TKI:000000000000000000000000000000000030"); + assertNotNull(updatedTask); + assertTrue(updatedTask.isRead()); + assertFalse(updatedTask.getCreated().equals(updatedTask.getModified())); + + taskService.setTaskRead("TKI:000000000000000000000000000000000030", false); + Task updatedTask2 = taskService.getTask("TKI:000000000000000000000000000000000030"); + assertNotNull(updatedTask2); + assertFalse(updatedTask2.isRead()); + assertFalse(updatedTask2.getModified().isBefore(updatedTask.getModified())); + + Assertions.assertThrows( + TaskNotFoundException.class, () -> taskService.setTaskRead("INVALID", true)); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testCustomPropertiesOfTask() + throws TaskNotFoundException, ClassificationNotFoundException, InvalidArgumentException, + ConcurrencyException, NotAuthorizedException, AttachmentPersistenceException { + TaskService taskService = taskanaEngine.getTaskService(); + Task task = taskService.getTask("TKI:000000000000000000000000000000000000"); + task.setCustomAttribute("1", "T2100"); + Task updatedTask = taskService.updateTask(task); + updatedTask = taskService.getTask(updatedTask.getId()); + + assertNotNull(updatedTask); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testUpdateOfWorkbasketKeyWhatIsNotAllowed() + throws NotAuthorizedException, TaskNotFoundException { + + TaskService taskService = taskanaEngine.getTaskService(); + Task task = taskService.getTask("TKI:000000000000000000000000000000000000"); + ((TaskImpl) task).setWorkbasketKey("USER_2_2"); + + Assertions.assertThrows(InvalidArgumentException.class, () -> taskService.updateTask(task)); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testUpdateTasksByPorForUser1() throws InvalidArgumentException { + ObjectReference por = new ObjectReference(); + por.setCompany("00"); + por.setSystem("PASystem"); + por.setSystemInstance("00"); + por.setType("VNR"); + por.setValue("22334455"); + Map customProperties = new HashMap<>(); + customProperties.put("7", "This is modifiedValue 7"); + customProperties.put("14", null); + customProperties.put("3", "This is modifiedValue 3"); + customProperties.put("16", "This is modifiedValue 16"); + TaskService taskService = taskanaEngine.getTaskService(); + + List taskIds = taskService.updateTasks(por, customProperties); + assertEquals(0, taskIds.size()); + } + + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testUpdateTasksByPor() + throws InvalidArgumentException, TaskNotFoundException, NotAuthorizedException { + ObjectReference por = new ObjectReference(); + por.setCompany("00"); + por.setSystem("PASystem"); + por.setSystemInstance("00"); + por.setType("VNR"); + por.setValue("22334455"); + Map customProperties = new HashMap<>(); + customProperties.put("7", "This is modifiedValue 7"); + customProperties.put("14", null); + customProperties.put("3", "This is modifiedValue 3"); + customProperties.put("16", "This is modifiedValue 16"); + TaskService taskService = taskanaEngine.getTaskService(); + + List taskIds = taskService.updateTasks(por, customProperties); + assertEquals(6, taskIds.size()); + for (String taskId : taskIds) { + Task task = taskService.getTask(taskId); + assertEquals("This is modifiedValue 3", task.getCustomAttribute("3")); + assertEquals("This is modifiedValue 7", task.getCustomAttribute("7")); + assertEquals("This is modifiedValue 16", task.getCustomAttribute("16")); + assertNull(task.getCustomAttribute("14")); } + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testUpdatePrimaryObjectReferenceOfTask() - throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, TaskNotFoundException, - ConcurrencyException, AttachmentPersistenceException { - - TaskService taskService = taskanaEngine.getTaskService(); - Task task = taskService.getTask("TKI:000000000000000000000000000000000000"); - Instant modifiedOriginal = task.getModified(); - task.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "7654321")); - task.setBusinessProcessId("MY_PROCESS_ID"); - task.setParentBusinessProcessId("MY_PARENT_PROCESS_ID"); - Task updatedTask = taskService.updateTask(task); - updatedTask = taskService.getTask(updatedTask.getId()); - - assertNotNull(updatedTask); - assertEquals("7654321", updatedTask.getPrimaryObjRef().getValue()); - assertNotNull(updatedTask.getCreated()); - assertNotNull(updatedTask.getModified()); - assertFalse(modifiedOriginal.isAfter(updatedTask.getModified())); - assertNotEquals(updatedTask.getCreated(), updatedTask.getModified()); - assertEquals(task.getCreated(), updatedTask.getCreated()); - assertEquals(task.isRead(), updatedTask.isRead()); - assertEquals("MY_PROCESS_ID", updatedTask.getBusinessProcessId()); - assertEquals("MY_PARENT_PROCESS_ID", updatedTask.getParentBusinessProcessId()); - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testThrowsExceptionIfMandatoryPrimaryObjectReferenceIsNotSetOrIncomplete() - throws NotAuthorizedException, ClassificationNotFoundException, TaskNotFoundException, ConcurrencyException, - AttachmentPersistenceException { - - TaskService taskService = taskanaEngine.getTaskService(); - Task task = taskService.getTask("TKI:000000000000000000000000000000000000"); - task.setPrimaryObjRef(null); - Assertions.assertThrows(InvalidArgumentException.class, () -> taskService.updateTask(task)); - - task.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", null)); - Assertions.assertThrows(InvalidArgumentException.class, () -> taskService.updateTask(task)); - - task.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", null, "1234567")); - Assertions.assertThrows(InvalidArgumentException.class, () -> taskService.updateTask(task)); - - task.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", null, "VNR", "1234567")); - Assertions.assertThrows(InvalidArgumentException.class, () -> taskService.updateTask(task)); - - task.setPrimaryObjRef(createObjectReference("COMPANY_A", null, "INSTANCE_A", "VNR", "1234567")); - Assertions.assertThrows(InvalidArgumentException.class, () -> taskService.updateTask(task)); - - task.setPrimaryObjRef(createObjectReference(null, "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - Assertions.assertThrows(InvalidArgumentException.class, () -> taskService.updateTask(task)); - - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testThrowsExceptionIfTaskHasAlreadyBeenUpdated() - throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, - TaskNotFoundException, ConcurrencyException, AttachmentPersistenceException { - - TaskService taskService = taskanaEngine.getTaskService(); - Task task = taskService.getTask("TKI:000000000000000000000000000000000000"); - Task task2 = taskService.getTask("TKI:000000000000000000000000000000000000"); - - task.setCustomAttribute("1", "willi"); - taskService.updateTask(task); - - task2.setCustomAttribute("2", "Walter"); - //TODO flaky test ... if speed is too high, - Assertions.assertThrows(ConcurrencyException.class, () -> taskService.updateTask(task2), - "The task has already been updated by another user"); - - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testUpdateClassificationOfTask() - throws TaskNotFoundException, ClassificationNotFoundException, InvalidArgumentException, ConcurrencyException, - NotAuthorizedException, AttachmentPersistenceException { - - TaskService taskService = taskanaEngine.getTaskService(); - Task task = taskService.getTask("TKI:000000000000000000000000000000000000"); - ClassificationSummary classificationSummary = task.getClassificationSummary(); - task.setClassificationKey("T2100"); - Task updatedTask = taskService.updateTask(task); - updatedTask = taskService.getTask(updatedTask.getId()); - - assertNotNull(updatedTask); - assertEquals("T2100", updatedTask.getClassificationSummary().getKey()); - assertThat(updatedTask.getClassificationSummary(), not(equalTo(classificationSummary))); - assertNotEquals(updatedTask.getCreated(), updatedTask.getModified()); - assertEquals(task.getPlanned(), updatedTask.getPlanned()); - assertEquals(task.getName(), updatedTask.getName()); - assertEquals(task.getDescription(), updatedTask.getDescription()); - } - - @WithAccessId( - userName = "user_1_2", - groupNames = {"group_1"}) - @Test - void testUpdateReadFlagOfTask() - throws TaskNotFoundException, NotAuthorizedException { - - TaskService taskService = taskanaEngine.getTaskService(); - - taskService.setTaskRead("TKI:000000000000000000000000000000000030", true); - Task updatedTask = taskService.getTask("TKI:000000000000000000000000000000000030"); - assertNotNull(updatedTask); - assertTrue(updatedTask.isRead()); - assertFalse(updatedTask.getCreated().equals(updatedTask.getModified())); - - taskService.setTaskRead("TKI:000000000000000000000000000000000030", false); - Task updatedTask2 = taskService.getTask("TKI:000000000000000000000000000000000030"); - assertNotNull(updatedTask2); - assertFalse(updatedTask2.isRead()); - assertFalse(updatedTask2.getModified().isBefore(updatedTask.getModified())); - - Assertions.assertThrows(TaskNotFoundException.class, () -> taskService.setTaskRead("INVALID", true)); - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testCustomPropertiesOfTask() - throws TaskNotFoundException, ClassificationNotFoundException, InvalidArgumentException, ConcurrencyException, - NotAuthorizedException, AttachmentPersistenceException { - TaskService taskService = taskanaEngine.getTaskService(); - Task task = taskService.getTask("TKI:000000000000000000000000000000000000"); - task.setCustomAttribute("1", "T2100"); - Task updatedTask = taskService.updateTask(task); - updatedTask = taskService.getTask(updatedTask.getId()); - - assertNotNull(updatedTask); - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testUpdateOfWorkbasketKeyWhatIsNotAllowed() - throws NotAuthorizedException, - TaskNotFoundException { - - TaskService taskService = taskanaEngine.getTaskService(); - Task task = taskService.getTask("TKI:000000000000000000000000000000000000"); - ((TaskImpl) task).setWorkbasketKey("USER_2_2"); - - Assertions.assertThrows(InvalidArgumentException.class, () -> - taskService.updateTask(task)); - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testUpdateTasksByPorForUser1() throws InvalidArgumentException { - ObjectReference por = new ObjectReference(); - por.setCompany("00"); - por.setSystem("PASystem"); - por.setSystemInstance("00"); - por.setType("VNR"); - por.setValue("22334455"); - Map customProperties = new HashMap<>(); - customProperties.put("7", "This is modifiedValue 7"); - customProperties.put("14", null); - customProperties.put("3", "This is modifiedValue 3"); - customProperties.put("16", "This is modifiedValue 16"); - TaskService taskService = taskanaEngine.getTaskService(); - - List taskIds = taskService.updateTasks(por, customProperties); - assertEquals(0, taskIds.size()); - - } - - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testUpdateTasksByPor() - throws InvalidArgumentException, TaskNotFoundException, NotAuthorizedException { - ObjectReference por = new ObjectReference(); - por.setCompany("00"); - por.setSystem("PASystem"); - por.setSystemInstance("00"); - por.setType("VNR"); - por.setValue("22334455"); - Map customProperties = new HashMap<>(); - customProperties.put("7", "This is modifiedValue 7"); - customProperties.put("14", null); - customProperties.put("3", "This is modifiedValue 3"); - customProperties.put("16", "This is modifiedValue 16"); - TaskService taskService = taskanaEngine.getTaskService(); - - List taskIds = taskService.updateTasks(por, customProperties); - assertEquals(6, taskIds.size()); - for (String taskId : taskIds) { - Task task = taskService.getTask(taskId); - assertEquals("This is modifiedValue 3", task.getCustomAttribute("3")); - assertEquals("This is modifiedValue 7", task.getCustomAttribute("7")); - assertEquals("This is modifiedValue 16", task.getCustomAttribute("16")); - assertNull(task.getCustomAttribute("14")); - } - - } - - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"} - ) - @Test - void testUpdateTasksById() - throws InvalidArgumentException, TaskNotFoundException, NotAuthorizedException { - List taskIds = Arrays.asList( + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testUpdateTasksById() + throws InvalidArgumentException, TaskNotFoundException, NotAuthorizedException { + List taskIds = + Arrays.asList( "TKI:000000000000000000000000000000000008", "TKI:000000000000000000000000000000000009", "TKI:000000000000000000000000000000000010"); - Map customProperties = new HashMap<>(); - customProperties.put("1", "This is modifiedValue 1"); - customProperties.put("5", "This is modifiedValue 5"); - customProperties.put("10", "This is modifiedValue 10"); - customProperties.put("12", "This is modifiedValue 12"); - TaskService taskService = taskanaEngine.getTaskService(); - - List changedTasks = taskService.updateTasks(taskIds, customProperties); - assertEquals(3, changedTasks.size()); - for (String taskId : changedTasks) { - Task task = taskService.getTask(taskId); - assertEquals("This is modifiedValue 1", task.getCustomAttribute("1")); - assertEquals("This is modifiedValue 5", task.getCustomAttribute("5")); - assertEquals("This is modifiedValue 10", task.getCustomAttribute("10")); - assertEquals("This is modifiedValue 12", task.getCustomAttribute("12")); - assertNull(task.getCustomAttribute("2")); - } + Map customProperties = new HashMap<>(); + customProperties.put("1", "This is modifiedValue 1"); + customProperties.put("5", "This is modifiedValue 5"); + customProperties.put("10", "This is modifiedValue 10"); + customProperties.put("12", "This is modifiedValue 12"); + TaskService taskService = taskanaEngine.getTaskService(); + List changedTasks = taskService.updateTasks(taskIds, customProperties); + assertEquals(3, changedTasks.size()); + for (String taskId : changedTasks) { + Task task = taskService.getTask(taskId); + assertEquals("This is modifiedValue 1", task.getCustomAttribute("1")); + assertEquals("This is modifiedValue 5", task.getCustomAttribute("5")); + assertEquals("This is modifiedValue 10", task.getCustomAttribute("10")); + assertEquals("This is modifiedValue 12", task.getCustomAttribute("12")); + assertNull(task.getCustomAttribute("2")); } + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testUpdateCallbackInfoOfSimpleTask() - throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException, ConcurrencyException, - AttachmentPersistenceException { + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testUpdateCallbackInfoOfSimpleTask() + throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException, + ConcurrencyException, AttachmentPersistenceException { - TaskService taskService = taskanaEngine.getTaskService(); - Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); - newTask.setClassificationKey("T2100"); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - Task createdTask = taskService.createTask(newTask); + TaskService taskService = taskanaEngine.getTaskService(); + Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); + newTask.setClassificationKey("T2100"); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + Task createdTask = taskService.createTask(newTask); - assertNotNull(createdTask); - assertEquals("1234567", createdTask.getPrimaryObjRef().getValue()); - assertNotNull(createdTask.getCreated()); - assertNotNull(createdTask.getModified()); - assertNotNull(createdTask.getBusinessProcessId()); - assertEquals(null, createdTask.getClaimed()); - assertEquals(null, createdTask.getCompleted()); - assertEquals(createdTask.getCreated(), createdTask.getModified()); - assertEquals(createdTask.getCreated(), createdTask.getPlanned()); - assertEquals(TaskState.READY, createdTask.getState()); - assertEquals(null, createdTask.getParentBusinessProcessId()); - assertEquals(2, createdTask.getPriority()); - assertEquals(false, createdTask.isRead()); - assertEquals(false, createdTask.isTransferred()); + assertNotNull(createdTask); + assertEquals("1234567", createdTask.getPrimaryObjRef().getValue()); + assertNotNull(createdTask.getCreated()); + assertNotNull(createdTask.getModified()); + assertNotNull(createdTask.getBusinessProcessId()); + assertEquals(null, createdTask.getClaimed()); + assertEquals(null, createdTask.getCompleted()); + assertEquals(createdTask.getCreated(), createdTask.getModified()); + assertEquals(createdTask.getCreated(), createdTask.getPlanned()); + assertEquals(TaskState.READY, createdTask.getState()); + assertEquals(null, createdTask.getParentBusinessProcessId()); + assertEquals(2, createdTask.getPriority()); + assertEquals(false, createdTask.isRead()); + assertEquals(false, createdTask.isTransferred()); - Task retrievedTask = taskService.getTask(createdTask.getId()); - - HashMap callbackInfo = new HashMap<>(); - for (int i = 1; i <= 10; i++) { - callbackInfo.put("info_" + i, "Value of info_" + i); - } - retrievedTask.setCallbackInfo(callbackInfo); - taskService.updateTask(retrievedTask); - - Task retrievedUpdatedTask = taskService.getTask(createdTask.getId()); - - assertEquals(callbackInfo, retrievedUpdatedTask.getCallbackInfo()); + Task retrievedTask = taskService.getTask(createdTask.getId()); + HashMap callbackInfo = new HashMap<>(); + for (int i = 1; i <= 10; i++) { + callbackInfo.put("info_" + i, "Value of info_" + i); } + retrievedTask.setCallbackInfo(callbackInfo); + taskService.updateTask(retrievedTask); + Task retrievedUpdatedTask = taskService.getTask(createdTask.getId()); + + assertEquals(callbackInfo, retrievedUpdatedTask.getCallbackInfo()); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/task/UpdateTaskAttachmentsAccTest.java b/lib/taskana-core/src/test/java/acceptance/task/UpdateTaskAttachmentsAccTest.java index 1a1c3fc8a..b0b966da6 100644 --- a/lib/taskana-core/src/test/java/acceptance/task/UpdateTaskAttachmentsAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/task/UpdateTaskAttachmentsAccTest.java @@ -8,17 +8,16 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; +import acceptance.AbstractAccTest; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.List; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.Attachment; import pro.taskana.Classification; import pro.taskana.ClassificationSummary; @@ -41,498 +40,589 @@ import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; /** - * Acceptance test for the usecase of adding/removing an attachment of a task and update the result correctly. + * Acceptance test for the usecase of adding/removing an attachment of a task and update the result + * correctly. */ @ExtendWith(JAASExtension.class) class UpdateTaskAttachmentsAccTest extends AbstractAccTest { - private Task task; - private Attachment attachment; - private TaskService taskService; + private Task task; + private Attachment attachment; + private TaskService taskService; - UpdateTaskAttachmentsAccTest() { - super(); - } + UpdateTaskAttachmentsAccTest() { + super(); + } - // this method needs to run with access ids, otherwise getTask throws NotAuthorizedException - // since only @Test and not @Before methods are run by JAASRunner, we call this method explicitely at - // the begin of each testcase.... - private void setUpMethod() - throws TaskNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - InvalidArgumentException, ConcurrencyException, AttachmentPersistenceException { - taskService = taskanaEngine.getTaskService(); - task = taskService.getTask("TKI:000000000000000000000000000000000000"); // class T2000, prio 1, SL P1D - task.setClassificationKey("T2000"); - attachment = createAttachment("DOCTYPE_DEFAULT", // prio 99, SL P2000D - createObjectReference("COMPANY_A", "SYSTEM_B", "INSTANCE_B", "ArchiveId", - "12345678901234567890123456789012345678901234567890"), - "E-MAIL", "2018-01-15", createSimpleCustomProperties(3)); - task.getAttachments().clear(); - taskService.updateTask(task); - assertThat(task, not(equalTo(null))); - } + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testAddNewAttachment() + throws TaskNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + InvalidArgumentException, ConcurrencyException, AttachmentPersistenceException { + setUpMethod(); + int attachmentCount = task.getAttachments().size(); + assertEquals(1, task.getPriority()); + assertEquals(task.getDue(), task.getPlanned().plus(Duration.ofDays(1))); + task.addAttachment(attachment); - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testAddNewAttachment() - throws TaskNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - InvalidArgumentException, ConcurrencyException, AttachmentPersistenceException { - setUpMethod(); - int attachmentCount = task.getAttachments().size(); - assertEquals(1, task.getPriority()); - assertEquals(task.getDue(), task.getPlanned().plus(Duration.ofDays(1))); - task.addAttachment(attachment); + task = taskService.updateTask(task); - task = taskService.updateTask(task); + task = taskService.getTask(task.getId()); + assertThat(task.getAttachments().size(), equalTo(attachmentCount + 1)); + assertThat( + task.getAttachments().get(0).getClassificationSummary().getKey(), + equalTo("DOCTYPE_DEFAULT")); + assertThat( + task.getAttachments().get(0).getObjectReference().getCompany(), equalTo("COMPANY_A")); + assertThat(task.getAttachments().get(0).getObjectReference().getSystem(), equalTo("SYSTEM_B")); + assertThat( + task.getAttachments().get(0).getObjectReference().getSystemInstance(), + equalTo("INSTANCE_B")); + assertThat(task.getAttachments().get(0).getObjectReference().getType(), equalTo("ArchiveId")); + assertThat( + task.getAttachments().get(0).getObjectReference().getValue(), + equalTo("12345678901234567890123456789012345678901234567890")); + assertEquals(99, task.getPriority()); + assertEquals(task.getDue(), task.getPlanned().plus(Duration.ofDays(1))); + } - task = taskService.getTask(task.getId()); - assertThat(task.getAttachments().size(), equalTo(attachmentCount + 1)); - assertThat(task.getAttachments().get(0).getClassificationSummary().getKey(), equalTo("DOCTYPE_DEFAULT")); - assertThat(task.getAttachments().get(0).getObjectReference().getCompany(), equalTo("COMPANY_A")); - assertThat(task.getAttachments().get(0).getObjectReference().getSystem(), equalTo("SYSTEM_B")); - assertThat(task.getAttachments().get(0).getObjectReference().getSystemInstance(), equalTo("INSTANCE_B")); - assertThat(task.getAttachments().get(0).getObjectReference().getType(), equalTo("ArchiveId")); - assertThat(task.getAttachments().get(0).getObjectReference().getValue(), - equalTo("12345678901234567890123456789012345678901234567890")); - assertEquals(99, task.getPriority()); - assertEquals(task.getDue(), task.getPlanned().plus(Duration.ofDays(1))); - } + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testAddValidAttachmentTwice() + throws TaskNotFoundException, ClassificationNotFoundException, InvalidArgumentException, + ConcurrencyException, NotAuthorizedException, AttachmentPersistenceException { + setUpMethod(); + task.getAttachments().clear(); + task = taskService.updateTask(task); + task = taskService.getTask(task.getId()); + assertEquals(0, task.getAttachments().size()); - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testAddValidAttachmentTwice() - throws TaskNotFoundException, ClassificationNotFoundException, InvalidArgumentException, ConcurrencyException, - NotAuthorizedException, - AttachmentPersistenceException { - setUpMethod(); - task.getAttachments().clear(); - task = taskService.updateTask(task); - task = taskService.getTask(task.getId()); - assertEquals(0, task.getAttachments().size()); + AttachmentImpl attachment = (AttachmentImpl) this.attachment; + attachment.setId("TAI:000017"); + task.addAttachment(attachment); + task.addAttachment(attachment); + task = taskService.updateTask(task); - AttachmentImpl attachment = (AttachmentImpl) this.attachment; - attachment.setId("TAI:000017"); - task.addAttachment(attachment); - task.addAttachment(attachment); - task = taskService.updateTask(task); + assertEquals(1, task.getAttachments().size()); + } - assertEquals(1, task.getAttachments().size()); - } + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testAddNewAttachmentTwiceWithoutTaskanaMethodWillThrowAttachmentPersistenceException() + throws TaskNotFoundException, ClassificationNotFoundException, InvalidArgumentException, + ConcurrencyException, NotAuthorizedException, AttachmentPersistenceException { + setUpMethod(); + int attachmentCount = 0; + task.getAttachments().clear(); + task = taskService.updateTask(task); + task = taskService.getTask(task.getId()); + assertThat(task.getAttachments().size(), equalTo(attachmentCount)); - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testAddNewAttachmentTwiceWithoutTaskanaMethodWillThrowAttachmentPersistenceException() - throws TaskNotFoundException, ClassificationNotFoundException, InvalidArgumentException, ConcurrencyException, - NotAuthorizedException, - AttachmentPersistenceException { - setUpMethod(); - int attachmentCount = 0; - task.getAttachments().clear(); - task = taskService.updateTask(task); - task = taskService.getTask(task.getId()); - assertThat(task.getAttachments().size(), equalTo(attachmentCount)); + AttachmentImpl attachment = (AttachmentImpl) this.attachment; + attachment.setId("TAI:000017"); + task.getAttachments().add(attachment); + task.getAttachments().add(attachment); + task.getAttachments().add(attachment); + Assertions.assertThrows( + AttachmentPersistenceException.class, () -> task = taskService.updateTask(task)); + } - AttachmentImpl attachment = (AttachmentImpl) this.attachment; - attachment.setId("TAI:000017"); - task.getAttachments().add(attachment); - task.getAttachments().add(attachment); - task.getAttachments().add(attachment); - Assertions.assertThrows(AttachmentPersistenceException.class, () -> - task = taskService.updateTask(task)); - } + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testAddExistingAttachmentAgainWillUpdateWhenNotEqual() + throws TaskNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + InvalidArgumentException, ConcurrencyException, AttachmentPersistenceException { + setUpMethod(); + // Add attachment before + task = taskService.getTask(task.getId()); + int attachmentCount = task.getAttachments().size(); + task.addAttachment(attachment); + task = taskService.updateTask(task); + task = taskService.getTask(task.getId()); + assertThat(task.getAttachments().size(), equalTo(attachmentCount + 1)); - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testAddExistingAttachmentAgainWillUpdateWhenNotEqual() - throws TaskNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - InvalidArgumentException, ConcurrencyException, AttachmentPersistenceException { - setUpMethod(); - // Add attachment before - task = taskService.getTask(task.getId()); - int attachmentCount = task.getAttachments().size(); - task.addAttachment(attachment); - task = taskService.updateTask(task); - task = taskService.getTask(task.getId()); - assertThat(task.getAttachments().size(), equalTo(attachmentCount + 1)); + // Change sth. and add same (id) again - override/update + String newChannel = "UPDATED EXTERNAL SINCE LAST ADD"; + attachmentCount = task.getAttachments().size(); + Attachment updatedAttachment = task.getAttachments().get(0); + updatedAttachment.setChannel(newChannel); + Classification newClassification = + taskanaEngine + .getClassificationService() + .getClassification("CLI:000000000000000000000000000000000001"); // Prio 999, SL PT5H + updatedAttachment.setClassificationSummary(newClassification.asSummary()); + task.addAttachment(updatedAttachment); + task = taskService.updateTask(task); + task = taskService.getTask(task.getId()); + assertThat(task.getAttachments().size(), equalTo(attachmentCount)); + assertThat(task.getAttachments().get(0).getChannel(), equalTo(newChannel)); + assertEquals(999, task.getPriority()); - // Change sth. and add same (id) again - override/update - String newChannel = "UPDATED EXTERNAL SINCE LAST ADD"; - attachmentCount = task.getAttachments().size(); - Attachment updatedAttachment = task.getAttachments().get(0); - updatedAttachment.setChannel(newChannel); - Classification newClassification = taskanaEngine.getClassificationService() - .getClassification("CLI:000000000000000000000000000000000001"); // Prio 999, SL PT5H - updatedAttachment.setClassificationSummary(newClassification.asSummary()); - task.addAttachment(updatedAttachment); - task = taskService.updateTask(task); - task = taskService.getTask(task.getId()); - assertThat(task.getAttachments().size(), equalTo(attachmentCount)); - assertThat(task.getAttachments().get(0).getChannel(), equalTo(newChannel)); - assertEquals(999, task.getPriority()); - - DaysToWorkingDaysConverter converter = DaysToWorkingDaysConverter - .initialize(Collections.singletonList(new TimeIntervalColumnHeader(0)), Instant.now()); - long calendarDays = converter.convertWorkingDaysToDays(task.getDue(), 1); - assertEquals(task.getDue(), task.getPlanned().plus(Duration.ofDays(calendarDays))); - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testAddExistingAttachmentAgainWillDoNothingWhenEqual() - throws TaskNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - InvalidArgumentException, ConcurrencyException, AttachmentPersistenceException { - setUpMethod(); - // Add Attachment before - int attachmentCount = task.getAttachments().size(); - ((AttachmentImpl) attachment).setId("TAI:0001"); - task.addAttachment(attachment); - task.addAttachment(attachment); // overwrite, same id - task.addAttachment(attachment); // overwrite, same id - task = taskService.updateTask(task); - task = taskService.getTask(task.getId()); - assertThat(task.getAttachments().size(), equalTo(attachmentCount + 1)); - - // Add same again - ignored - attachmentCount = task.getAttachments().size(); - Attachment redundantAttachment = task.getAttachments().get(0); - task.addAttachment(redundantAttachment); - task = taskService.updateTask(task); - assertThat(task.getAttachments().size(), equalTo(attachmentCount)); - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testAddAttachmentAsNullValueWillBeIgnored() - throws TaskNotFoundException, ClassificationNotFoundException, InvalidArgumentException, ConcurrencyException, - NotAuthorizedException, AttachmentPersistenceException { - setUpMethod(); - // Try to add a single NULL-Element - int attachmentCount = task.getAttachments().size(); - task.addAttachment(null); - task = taskService.updateTask(task); - task = taskService.getTask(task.getId()); - assertThat(task.getAttachments().size(), equalTo(attachmentCount)); - - // Try to set the Attachments to NULL and update it - ((TaskImpl) task).setAttachments(null); - task = taskService.updateTask(task); - assertThat(task.getAttachments().size(), equalTo(attachmentCount)); // locally, not persisted - task = taskService.getTask(task.getId()); - assertThat(task.getAttachments().size(), equalTo(attachmentCount)); // persisted values not changed - - // Test no NullPointer on NULL-Value and removing it on current data. - // New loading can do this, but returned value should got this "function", too. - attachmentCount = task.getAttachments().size(); - task.getAttachments().add(null); - task.getAttachments().add(null); - task.getAttachments().add(null); - task = taskService.updateTask(task); - assertThat(task.getAttachments().size(), equalTo(attachmentCount)); // locally, not persisted - task = taskService.getTask(task.getId()); - assertThat(task.getAttachments().size(), equalTo(attachmentCount)); // persisted values not changed - assertEquals(1, task.getPriority()); - assertEquals(task.getDue(), task.getPlanned().plus(Duration.ofDays(1))); - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testRemoveAttachment() - throws TaskNotFoundException, ClassificationNotFoundException, InvalidArgumentException, ConcurrencyException, - NotAuthorizedException, AttachmentPersistenceException { - setUpMethod(); - task.addAttachment(attachment); - task = taskService.updateTask(task); - assertEquals(99, task.getPriority()); - assertEquals(task.getDue(), task.getPlanned().plus(Duration.ofDays(1))); - int attachmentCount = task.getAttachments().size(); - Attachment attachmentToRemove = task.getAttachments().get(0); - task.removeAttachment(attachmentToRemove.getId()); - task = taskService.updateTask(task); - assertThat(task.getAttachments().size(), equalTo(attachmentCount - 1)); // locally, removed and not persisted - task = taskService.getTask(task.getId()); - assertThat(task.getAttachments().size(), equalTo(attachmentCount - 1)); // persisted, values removed - assertEquals(1, task.getPriority()); - assertEquals(task.getDue(), task.getPlanned().plus(Duration.ofDays(1))); - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testRemoveAttachmentWithNullAndNotAddedId() - throws TaskNotFoundException, ClassificationNotFoundException, InvalidArgumentException, ConcurrencyException, - NotAuthorizedException, AttachmentPersistenceException { - setUpMethod(); - task.addAttachment(attachment); - task = taskService.updateTask(task); - int attachmentCount = task.getAttachments().size(); - - task.removeAttachment(null); - task = taskService.updateTask(task); - assertThat(task.getAttachments().size(), equalTo(attachmentCount)); // locally, nothing changed - task = taskService.getTask(task.getId()); - assertThat(task.getAttachments().size(), equalTo(attachmentCount)); // persisted, still same - - task.removeAttachment("INVALID ID HERE"); - task = taskService.updateTask(task); - assertThat(task.getAttachments().size(), equalTo(attachmentCount)); // locally, nothing changed - task = taskService.getTask(task.getId()); - assertThat(task.getAttachments().size(), equalTo(attachmentCount)); // persisted, still same - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testUpdateAttachment() - throws TaskNotFoundException, ClassificationNotFoundException, InvalidArgumentException, ConcurrencyException, - NotAuthorizedException, AttachmentPersistenceException { - setUpMethod(); - ((TaskImpl) task).setAttachments(new ArrayList<>()); - task = taskService.updateTask(task); - assertEquals(1, task.getPriority()); - assertEquals(task.getDue(), task.getPlanned().plus(Duration.ofDays(1))); - - Attachment attachment = this.attachment; - task.addAttachment(attachment); - task = taskService.updateTask(task); - assertEquals(99, task.getPriority()); - assertEquals(task.getDue(), task.getPlanned().plus(Duration.ofDays(1))); - - int attachmentCount = task.getAttachments().size(); - - String newChannel = attachment.getChannel() + "-X"; - task.getAttachments().get(0).setChannel(newChannel); - Classification newClassification = taskanaEngine.getClassificationService() - .getClassification("CLI:000000000000000000000000000000000001"); // Prio 999, SL PT5H - task.getAttachments().get(0).setClassificationSummary(newClassification.asSummary()); - task = taskService.updateTask(task); - task = taskService.getTask(task.getId()); - assertThat(task.getAttachments().size(), equalTo(attachmentCount)); - assertThat(task.getAttachments().get(0).getChannel(), equalTo(newChannel)); - assertEquals(999, task.getPriority()); - - DaysToWorkingDaysConverter converter = DaysToWorkingDaysConverter - .initialize(Collections.singletonList(new TimeIntervalColumnHeader(0)), Instant.now()); - long calendarDays = converter.convertWorkingDaysToDays(task.getDue(), 1); - - assertEquals(task.getDue(), task.getPlanned().plus(Duration.ofDays(calendarDays))); - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void modifyExistingAttachment() - throws TaskNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - InvalidArgumentException, ConcurrencyException, AttachmentPersistenceException { - setUpMethod(); - // setup test - assertThat(task.getAttachments().size(), equalTo(0)); - task.addAttachment(attachment); - - Attachment attachment2 = createAttachment("L10303", // prio 101, SL PT7H - createObjectReference("COMPANY_B", "SYSTEM_C", "INSTANCE_C", "ArchiveId", - "ABC45678901234567890123456789012345678901234567890"), - "ROHRPOST", "2018-01-15", createSimpleCustomProperties(4)); - task.addAttachment(attachment2); - task = taskService.updateTask(task); - task = taskService.getTask(task.getId()); - assertEquals(101, task.getPriority()); - DaysToWorkingDaysConverter converter = DaysToWorkingDaysConverter - .initialize(Collections.singletonList(new TimeIntervalColumnHeader(0)), Instant.now()); - long calendarDays = converter.convertWorkingDaysToDays(task.getDue(), 1); - - assertEquals(task.getDue(), task.getPlanned().plus(Duration.ofDays(calendarDays))); - - assertThat(task.getAttachments().size(), equalTo(2)); - List attachments = task.getAttachments(); - boolean rohrpostFound = false; - boolean emailFound = false; - for (Attachment att : attachments) { - String channel = att.getChannel(); - int custAttSize = att.getCustomAttributes().size(); - if ("ROHRPOST".equals(channel)) { - rohrpostFound = true; - } else if ("E-MAIL".equals(channel)) { - emailFound = true; - } else { - fail("unexpected attachment detected " + att); - } - assertTrue(("ROHRPOST".equals(channel) && custAttSize == 4) - || ("E-MAIL".equals(channel) && custAttSize == 3)); - } - assertTrue(rohrpostFound && emailFound); - - ClassificationSummary newClassificationSummary = taskanaEngine.getClassificationService() - .getClassification("CLI:100000000000000000000000000000000006") // Prio 5, SL P16D - .asSummary(); - // modify existing attachment - for (Attachment att : task.getAttachments()) { - att.setClassificationSummary(newClassificationSummary); - if (att.getCustomAttributes().size() == 3) { - att.setChannel("FAX"); - } - } - // modify existing attachment and task classification - task.setClassificationKey("DOCTYPE_DEFAULT"); // Prio 99, SL P2000D - task = taskService.updateTask(task); - task = taskService.getTask(task.getId()); - assertEquals(99, task.getPriority()); - - calendarDays = converter.convertWorkingDaysToDays(task.getDue(), 16); - - assertEquals(task.getDue(), task.getPlanned().plus(Duration.ofDays(calendarDays))); - - rohrpostFound = false; - boolean faxFound = false; - - for (Attachment att : task.getAttachments()) { - String channel = att.getChannel(); - int custAttSize = att.getCustomAttributes().size(); - if ("FAX".equals(channel)) { - faxFound = true; - } else if ("ROHRPOST".equals(channel)) { - rohrpostFound = true; - } else { - fail("unexpected attachment detected " + att); - } - - assertTrue(("ROHRPOST".equals(channel) && custAttSize == 4) - || ("FAX".equals(channel) && custAttSize == 3)); - } - assertTrue(faxFound && rohrpostFound); - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void replaceExistingAttachments() - throws TaskNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - InvalidArgumentException, ConcurrencyException, AttachmentPersistenceException { - setUpMethod(); - // setup test - assertThat(task.getAttachments().size(), equalTo(0)); - task.addAttachment(attachment); - Attachment attachment2 = createAttachment("DOCTYPE_DEFAULT", - createObjectReference("COMPANY_B", "SYSTEM_C", "INSTANCE_C", "ArchiveId", - "ABC45678901234567890123456789012345678901234567890"), - "E-MAIL", "2018-01-15", createSimpleCustomProperties(4)); - task.addAttachment(attachment2); - task = taskService.updateTask(task); - task = taskService.getTask(task.getId()); - assertThat(task.getAttachments().size(), equalTo(2)); - assertThat(task.getAttachments().get(0).getClassificationSummary().getKey(), equalTo("DOCTYPE_DEFAULT")); - - Attachment attachment3 = createAttachment("DOCTYPE_DEFAULT", - createObjectReference("COMPANY_C", "SYSTEM_7", "INSTANCE_7", "ArchiveId", - "ABC4567890123456789012345678901234567890DEF"), - "DHL", "2018-01-15", createSimpleCustomProperties(4)); - - // replace existing attachments by new via addAttachment call - task.getAttachments().clear(); - task.addAttachment(attachment3); - task = taskService.updateTask(task); - assertThat(task.getAttachments().size(), equalTo(1)); - assertThat(task.getAttachments().get(0).getChannel(), equalTo("DHL")); - - // setup environment for 2nd version of replacement (list.add call) - task.getAttachments().add(attachment2); - task = taskService.updateTask(task); - assertThat(task.getAttachments().size(), equalTo(2)); - assertThat(task.getAttachments().get(1).getChannel(), equalTo("E-MAIL")); - // replace attachments - task.getAttachments().clear(); - task.getAttachments().add(attachment3); - task = taskService.updateTask(task); - assertThat(task.getAttachments().size(), equalTo(1)); - assertThat(task.getAttachments().get(0).getChannel(), equalTo("DHL")); - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testPrioDurationOfTaskFromAttachmentsAtUpdate() - throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, - WorkbasketNotFoundException, TaskAlreadyExistException, TaskNotFoundException, ConcurrencyException, - AttachmentPersistenceException { - - setUpMethod(); - TaskService taskService = taskanaEngine.getTaskService(); - Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); - newTask.setClassificationKey("L12010"); // prio 8, SL P7D - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - - newTask.addAttachment(createAttachment("DOCTYPE_DEFAULT", // prio 99, SL P2000D - createObjectReference("COMPANY_A", "SYSTEM_B", "INSTANCE_B", "ArchiveId", - "12345678901234567890123456789012345678901234567890"), - "E-MAIL", "2018-01-15", createSimpleCustomProperties(3))); - newTask.addAttachment(createAttachment("L1060", // prio 1, SL P1D - createObjectReference("COMPANY_A", "SYSTEM_B", "INSTANCE_B", "ArchiveId", - "12345678901234567890123456789012345678901234567890"), - "E-MAIL", "2018-01-15", createSimpleCustomProperties(3))); - Task createdTask = taskService.createTask(newTask); - - assertNotNull(createdTask.getId()); - assertThat(createdTask.getCreator(), equalTo(CurrentUserContext.getUserid())); - - Task readTask = taskService.getTask(createdTask.getId()); - assertNotNull(readTask); - assertThat(readTask.getCreator(), equalTo(CurrentUserContext.getUserid())); - assertNotNull(readTask.getAttachments()); - assertEquals(2, readTask.getAttachments().size()); - assertNotNull(readTask.getAttachments().get(1).getCreated()); - assertNotNull(readTask.getAttachments().get(1).getModified()); - assertEquals(readTask.getAttachments().get(0).getCreated(), readTask.getAttachments().get(1).getModified()); - // assertNotNull(readTask.getAttachments().get(0).getClassification()); - assertNotNull(readTask.getAttachments().get(0).getObjectReference()); - - assertEquals(99, readTask.getPriority()); - - DaysToWorkingDaysConverter converter = DaysToWorkingDaysConverter.initialize( + DaysToWorkingDaysConverter converter = + DaysToWorkingDaysConverter.initialize( Collections.singletonList(new TimeIntervalColumnHeader(0)), Instant.now()); - long calendarDays = converter.convertWorkingDaysToDays(readTask.getPlanned(), 1); + long calendarDays = converter.convertWorkingDaysToDays(task.getDue(), 1); + assertEquals(task.getDue(), task.getPlanned().plus(Duration.ofDays(calendarDays))); + } - assertEquals(readTask.getDue(), readTask.getPlanned().plus(Duration.ofDays(calendarDays))); + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testAddExistingAttachmentAgainWillDoNothingWhenEqual() + throws TaskNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + InvalidArgumentException, ConcurrencyException, AttachmentPersistenceException { + setUpMethod(); + // Add Attachment before + int attachmentCount = task.getAttachments().size(); + ((AttachmentImpl) attachment).setId("TAI:0001"); + task.addAttachment(attachment); + task.addAttachment(attachment); // overwrite, same id + task.addAttachment(attachment); // overwrite, same id + task = taskService.updateTask(task); + task = taskService.getTask(task.getId()); + assertThat(task.getAttachments().size(), equalTo(attachmentCount + 1)); + + // Add same again - ignored + attachmentCount = task.getAttachments().size(); + Attachment redundantAttachment = task.getAttachments().get(0); + task.addAttachment(redundantAttachment); + task = taskService.updateTask(task); + assertThat(task.getAttachments().size(), equalTo(attachmentCount)); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testAddAttachmentAsNullValueWillBeIgnored() + throws TaskNotFoundException, ClassificationNotFoundException, InvalidArgumentException, + ConcurrencyException, NotAuthorizedException, AttachmentPersistenceException { + setUpMethod(); + // Try to add a single NULL-Element + int attachmentCount = task.getAttachments().size(); + task.addAttachment(null); + task = taskService.updateTask(task); + task = taskService.getTask(task.getId()); + assertThat(task.getAttachments().size(), equalTo(attachmentCount)); + + // Try to set the Attachments to NULL and update it + ((TaskImpl) task).setAttachments(null); + task = taskService.updateTask(task); + assertThat(task.getAttachments().size(), equalTo(attachmentCount)); // locally, not persisted + task = taskService.getTask(task.getId()); + assertThat( + task.getAttachments().size(), equalTo(attachmentCount)); // persisted values not changed + + // Test no NullPointer on NULL-Value and removing it on current data. + // New loading can do this, but returned value should got this "function", too. + attachmentCount = task.getAttachments().size(); + task.getAttachments().add(null); + task.getAttachments().add(null); + task.getAttachments().add(null); + task = taskService.updateTask(task); + assertThat(task.getAttachments().size(), equalTo(attachmentCount)); // locally, not persisted + task = taskService.getTask(task.getId()); + assertThat( + task.getAttachments().size(), equalTo(attachmentCount)); // persisted values not changed + assertEquals(1, task.getPriority()); + assertEquals(task.getDue(), task.getPlanned().plus(Duration.ofDays(1))); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testRemoveAttachment() + throws TaskNotFoundException, ClassificationNotFoundException, InvalidArgumentException, + ConcurrencyException, NotAuthorizedException, AttachmentPersistenceException { + setUpMethod(); + task.addAttachment(attachment); + task = taskService.updateTask(task); + assertEquals(99, task.getPriority()); + assertEquals(task.getDue(), task.getPlanned().plus(Duration.ofDays(1))); + int attachmentCount = task.getAttachments().size(); + Attachment attachmentToRemove = task.getAttachments().get(0); + task.removeAttachment(attachmentToRemove.getId()); + task = taskService.updateTask(task); + assertThat( + task.getAttachments().size(), + equalTo(attachmentCount - 1)); // locally, removed and not persisted + task = taskService.getTask(task.getId()); + assertThat( + task.getAttachments().size(), equalTo(attachmentCount - 1)); // persisted, values removed + assertEquals(1, task.getPriority()); + assertEquals(task.getDue(), task.getPlanned().plus(Duration.ofDays(1))); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testRemoveAttachmentWithNullAndNotAddedId() + throws TaskNotFoundException, ClassificationNotFoundException, InvalidArgumentException, + ConcurrencyException, NotAuthorizedException, AttachmentPersistenceException { + setUpMethod(); + task.addAttachment(attachment); + task = taskService.updateTask(task); + int attachmentCount = task.getAttachments().size(); + + task.removeAttachment(null); + task = taskService.updateTask(task); + assertThat(task.getAttachments().size(), equalTo(attachmentCount)); // locally, nothing changed + task = taskService.getTask(task.getId()); + assertThat(task.getAttachments().size(), equalTo(attachmentCount)); // persisted, still same + + task.removeAttachment("INVALID ID HERE"); + task = taskService.updateTask(task); + assertThat(task.getAttachments().size(), equalTo(attachmentCount)); // locally, nothing changed + task = taskService.getTask(task.getId()); + assertThat(task.getAttachments().size(), equalTo(attachmentCount)); // persisted, still same + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testUpdateAttachment() + throws TaskNotFoundException, ClassificationNotFoundException, InvalidArgumentException, + ConcurrencyException, NotAuthorizedException, AttachmentPersistenceException { + setUpMethod(); + ((TaskImpl) task).setAttachments(new ArrayList<>()); + task = taskService.updateTask(task); + assertEquals(1, task.getPriority()); + assertEquals(task.getDue(), task.getPlanned().plus(Duration.ofDays(1))); + + Attachment attachment = this.attachment; + task.addAttachment(attachment); + task = taskService.updateTask(task); + assertEquals(99, task.getPriority()); + assertEquals(task.getDue(), task.getPlanned().plus(Duration.ofDays(1))); + + int attachmentCount = task.getAttachments().size(); + + String newChannel = attachment.getChannel() + "-X"; + task.getAttachments().get(0).setChannel(newChannel); + Classification newClassification = + taskanaEngine + .getClassificationService() + .getClassification("CLI:000000000000000000000000000000000001"); // Prio 999, SL PT5H + task.getAttachments().get(0).setClassificationSummary(newClassification.asSummary()); + task = taskService.updateTask(task); + task = taskService.getTask(task.getId()); + assertThat(task.getAttachments().size(), equalTo(attachmentCount)); + assertThat(task.getAttachments().get(0).getChannel(), equalTo(newChannel)); + assertEquals(999, task.getPriority()); + + DaysToWorkingDaysConverter converter = + DaysToWorkingDaysConverter.initialize( + Collections.singletonList(new TimeIntervalColumnHeader(0)), Instant.now()); + long calendarDays = converter.convertWorkingDaysToDays(task.getDue(), 1); + + assertEquals(task.getDue(), task.getPlanned().plus(Duration.ofDays(calendarDays))); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void modifyExistingAttachment() + throws TaskNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + InvalidArgumentException, ConcurrencyException, AttachmentPersistenceException { + setUpMethod(); + // setup test + assertThat(task.getAttachments().size(), equalTo(0)); + task.addAttachment(attachment); + + Attachment attachment2 = + createAttachment( + "L10303", // prio 101, SL PT7H + createObjectReference( + "COMPANY_B", + "SYSTEM_C", + "INSTANCE_C", + "ArchiveId", + "ABC45678901234567890123456789012345678901234567890"), + "ROHRPOST", + "2018-01-15", + createSimpleCustomProperties(4)); + task.addAttachment(attachment2); + task = taskService.updateTask(task); + task = taskService.getTask(task.getId()); + assertEquals(101, task.getPriority()); + DaysToWorkingDaysConverter converter = + DaysToWorkingDaysConverter.initialize( + Collections.singletonList(new TimeIntervalColumnHeader(0)), Instant.now()); + long calendarDays = converter.convertWorkingDaysToDays(task.getDue(), 1); + + assertEquals(task.getDue(), task.getPlanned().plus(Duration.ofDays(calendarDays))); + + assertThat(task.getAttachments().size(), equalTo(2)); + List attachments = task.getAttachments(); + boolean rohrpostFound = false; + boolean emailFound = false; + for (Attachment att : attachments) { + String channel = att.getChannel(); + int custAttSize = att.getCustomAttributes().size(); + if ("ROHRPOST".equals(channel)) { + rohrpostFound = true; + } else if ("E-MAIL".equals(channel)) { + emailFound = true; + } else { + fail("unexpected attachment detected " + att); + } + assertTrue( + ("ROHRPOST".equals(channel) && custAttSize == 4) + || ("E-MAIL".equals(channel) && custAttSize == 3)); } + assertTrue(rohrpostFound && emailFound); - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testAddCustomAttributeToAttachment() - throws TaskNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - InvalidArgumentException, ConcurrencyException, AttachmentPersistenceException { + ClassificationSummary newClassificationSummary = + taskanaEngine + .getClassificationService() + .getClassification("CLI:100000000000000000000000000000000006") // Prio 5, SL P16D + .asSummary(); + // modify existing attachment + for (Attachment att : task.getAttachments()) { + att.setClassificationSummary(newClassificationSummary); + if (att.getCustomAttributes().size() == 3) { + att.setChannel("FAX"); + } + } + // modify existing attachment and task classification + task.setClassificationKey("DOCTYPE_DEFAULT"); // Prio 99, SL P2000D + task = taskService.updateTask(task); + task = taskService.getTask(task.getId()); + assertEquals(99, task.getPriority()); - TaskService taskService = taskanaEngine.getTaskService(); - task = taskService.getTask("TKI:000000000000000000000000000000000000"); // class T2000, prio 1, SL P1D - attachment = createAttachment("DOCTYPE_DEFAULT", // prio 99, SL P2000D - createObjectReference("COMPANY_A", "SYSTEM_B", "INSTANCE_B", "ArchiveId", + calendarDays = converter.convertWorkingDaysToDays(task.getDue(), 16); + + assertEquals(task.getDue(), task.getPlanned().plus(Duration.ofDays(calendarDays))); + + rohrpostFound = false; + boolean faxFound = false; + + for (Attachment att : task.getAttachments()) { + String channel = att.getChannel(); + int custAttSize = att.getCustomAttributes().size(); + if ("FAX".equals(channel)) { + faxFound = true; + } else if ("ROHRPOST".equals(channel)) { + rohrpostFound = true; + } else { + fail("unexpected attachment detected " + att); + } + + assertTrue( + ("ROHRPOST".equals(channel) && custAttSize == 4) + || ("FAX".equals(channel) && custAttSize == 3)); + } + assertTrue(faxFound && rohrpostFound); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void replaceExistingAttachments() + throws TaskNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + InvalidArgumentException, ConcurrencyException, AttachmentPersistenceException { + setUpMethod(); + // setup test + assertThat(task.getAttachments().size(), equalTo(0)); + task.addAttachment(attachment); + Attachment attachment2 = + createAttachment( + "DOCTYPE_DEFAULT", + createObjectReference( + "COMPANY_B", + "SYSTEM_C", + "INSTANCE_C", + "ArchiveId", + "ABC45678901234567890123456789012345678901234567890"), + "E-MAIL", + "2018-01-15", + createSimpleCustomProperties(4)); + task.addAttachment(attachment2); + task = taskService.updateTask(task); + task = taskService.getTask(task.getId()); + assertThat(task.getAttachments().size(), equalTo(2)); + assertThat( + task.getAttachments().get(0).getClassificationSummary().getKey(), + equalTo("DOCTYPE_DEFAULT")); + + Attachment attachment3 = + createAttachment( + "DOCTYPE_DEFAULT", + createObjectReference( + "COMPANY_C", + "SYSTEM_7", + "INSTANCE_7", + "ArchiveId", + "ABC4567890123456789012345678901234567890DEF"), + "DHL", + "2018-01-15", + createSimpleCustomProperties(4)); + + // replace existing attachments by new via addAttachment call + task.getAttachments().clear(); + task.addAttachment(attachment3); + task = taskService.updateTask(task); + assertThat(task.getAttachments().size(), equalTo(1)); + assertThat(task.getAttachments().get(0).getChannel(), equalTo("DHL")); + + // setup environment for 2nd version of replacement (list.add call) + task.getAttachments().add(attachment2); + task = taskService.updateTask(task); + assertThat(task.getAttachments().size(), equalTo(2)); + assertThat(task.getAttachments().get(1).getChannel(), equalTo("E-MAIL")); + // replace attachments + task.getAttachments().clear(); + task.getAttachments().add(attachment3); + task = taskService.updateTask(task); + assertThat(task.getAttachments().size(), equalTo(1)); + assertThat(task.getAttachments().get(0).getChannel(), equalTo("DHL")); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testPrioDurationOfTaskFromAttachmentsAtUpdate() + throws NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException, + WorkbasketNotFoundException, TaskAlreadyExistException, TaskNotFoundException, + ConcurrencyException, AttachmentPersistenceException { + + setUpMethod(); + TaskService taskService = taskanaEngine.getTaskService(); + Task newTask = taskService.newTask("USER_1_1", "DOMAIN_A"); + newTask.setClassificationKey("L12010"); // prio 8, SL P7D + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + + newTask.addAttachment( + createAttachment( + "DOCTYPE_DEFAULT", // prio 99, SL P2000D + createObjectReference( + "COMPANY_A", + "SYSTEM_B", + "INSTANCE_B", + "ArchiveId", "12345678901234567890123456789012345678901234567890"), - "E-MAIL", "2018-01-15", null); - attachment.getCustomAttributes().put("TEST_KEY", "TEST_VALUE"); - task.addAttachment(attachment); - taskService.updateTask(task); - Task updatedTask = taskService.getTask("TKI:000000000000000000000000000000000000"); - Attachment updatedAttachment = updatedTask.getAttachments().stream() - .filter(a -> attachment.getId().equals(a.getId())).findFirst().orElse(null); - assertNotNull(updatedAttachment); - assertEquals("TEST_VALUE", updatedAttachment.getCustomAttributes().get("TEST_KEY")); - } + "E-MAIL", + "2018-01-15", + createSimpleCustomProperties(3))); + newTask.addAttachment( + createAttachment( + "L1060", // prio 1, SL P1D + createObjectReference( + "COMPANY_A", + "SYSTEM_B", + "INSTANCE_B", + "ArchiveId", + "12345678901234567890123456789012345678901234567890"), + "E-MAIL", + "2018-01-15", + createSimpleCustomProperties(3))); + Task createdTask = taskService.createTask(newTask); + + assertNotNull(createdTask.getId()); + assertThat(createdTask.getCreator(), equalTo(CurrentUserContext.getUserid())); + + Task readTask = taskService.getTask(createdTask.getId()); + assertNotNull(readTask); + assertThat(readTask.getCreator(), equalTo(CurrentUserContext.getUserid())); + assertNotNull(readTask.getAttachments()); + assertEquals(2, readTask.getAttachments().size()); + assertNotNull(readTask.getAttachments().get(1).getCreated()); + assertNotNull(readTask.getAttachments().get(1).getModified()); + assertEquals( + readTask.getAttachments().get(0).getCreated(), + readTask.getAttachments().get(1).getModified()); + // assertNotNull(readTask.getAttachments().get(0).getClassification()); + assertNotNull(readTask.getAttachments().get(0).getObjectReference()); + + assertEquals(99, readTask.getPriority()); + + DaysToWorkingDaysConverter converter = + DaysToWorkingDaysConverter.initialize( + Collections.singletonList(new TimeIntervalColumnHeader(0)), Instant.now()); + long calendarDays = converter.convertWorkingDaysToDays(readTask.getPlanned(), 1); + + assertEquals(readTask.getDue(), readTask.getPlanned().plus(Duration.ofDays(calendarDays))); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testAddCustomAttributeToAttachment() + throws TaskNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + InvalidArgumentException, ConcurrencyException, AttachmentPersistenceException { + + TaskService taskService = taskanaEngine.getTaskService(); + task = + taskService.getTask( + "TKI:000000000000000000000000000000000000"); // class T2000, prio 1, SL P1D + attachment = + createAttachment( + "DOCTYPE_DEFAULT", // prio 99, SL P2000D + createObjectReference( + "COMPANY_A", + "SYSTEM_B", + "INSTANCE_B", + "ArchiveId", + "12345678901234567890123456789012345678901234567890"), + "E-MAIL", + "2018-01-15", + null); + attachment.getCustomAttributes().put("TEST_KEY", "TEST_VALUE"); + task.addAttachment(attachment); + taskService.updateTask(task); + Task updatedTask = taskService.getTask("TKI:000000000000000000000000000000000000"); + Attachment updatedAttachment = + updatedTask.getAttachments().stream() + .filter(a -> attachment.getId().equals(a.getId())) + .findFirst() + .orElse(null); + assertNotNull(updatedAttachment); + assertEquals("TEST_VALUE", updatedAttachment.getCustomAttributes().get("TEST_KEY")); + } + + // this method needs to run with access ids, otherwise getTask throws NotAuthorizedException + // since only @Test and not @Before methods are run by JAASRunner, we call this method explicitely + // at + // the begin of each testcase.... + private void setUpMethod() + throws TaskNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + InvalidArgumentException, ConcurrencyException, AttachmentPersistenceException { + taskService = taskanaEngine.getTaskService(); + task = + taskService.getTask( + "TKI:000000000000000000000000000000000000"); // class T2000, prio 1, SL P1D + task.setClassificationKey("T2000"); + attachment = + createAttachment( + "DOCTYPE_DEFAULT", // prio 99, SL P2000D + createObjectReference( + "COMPANY_A", + "SYSTEM_B", + "INSTANCE_B", + "ArchiveId", + "12345678901234567890123456789012345678901234567890"), + "E-MAIL", + "2018-01-15", + createSimpleCustomProperties(3)); + task.getAttachments().clear(); + taskService.updateTask(task); + assertThat(task, not(equalTo(null))); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/task/WorkOnTaskAccTest.java b/lib/taskana-core/src/test/java/acceptance/task/WorkOnTaskAccTest.java index 0a66e63fc..8015fb7aa 100644 --- a/lib/taskana-core/src/test/java/acceptance/task/WorkOnTaskAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/task/WorkOnTaskAccTest.java @@ -9,16 +9,15 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import acceptance.AbstractAccTest; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.List; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.BulkOperationResults; import pro.taskana.Task; import pro.taskana.TaskService; @@ -32,250 +31,248 @@ import pro.taskana.exceptions.TaskanaException; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "work on task" scenarios. This includes claim, complete... - */ +/** Acceptance test for all "work on task" scenarios. This includes claim, complete... */ @ExtendWith(JAASExtension.class) class WorkOnTaskAccTest extends AbstractAccTest { - WorkOnTaskAccTest() { - super(); - } + WorkOnTaskAccTest() { + super(); + } - @WithAccessId( - userName = "user_1_2", - groupNames = {"group_1"}) - @Test - void testClaimTask() - throws NotAuthorizedException, TaskNotFoundException, - InvalidStateException, InvalidOwnerException { - TaskService taskService = taskanaEngine.getTaskService(); - Task task = taskService.getTask("TKI:000000000000000000000000000000000025"); + @WithAccessId( + userName = "user_1_2", + groupNames = {"group_1"}) + @Test + void testClaimTask() + throws NotAuthorizedException, TaskNotFoundException, InvalidStateException, + InvalidOwnerException { + TaskService taskService = taskanaEngine.getTaskService(); + Task task = taskService.getTask("TKI:000000000000000000000000000000000025"); - taskService.claim(task.getId()); + taskService.claim(task.getId()); - Task claimedTask = taskService.getTask("TKI:000000000000000000000000000000000025"); - assertNotNull(claimedTask); - assertEquals(TaskState.CLAIMED, claimedTask.getState()); - assertNotNull(claimedTask.getClaimed()); - assertNotEquals(claimedTask.getCreated(), claimedTask.getModified()); - assertEquals(claimedTask.getClaimed(), claimedTask.getModified()); - assertTrue(claimedTask.isRead()); - assertEquals("user_1_2", claimedTask.getOwner()); - } + Task claimedTask = taskService.getTask("TKI:000000000000000000000000000000000025"); + assertNotNull(claimedTask); + assertEquals(TaskState.CLAIMED, claimedTask.getState()); + assertNotNull(claimedTask.getClaimed()); + assertNotEquals(claimedTask.getCreated(), claimedTask.getModified()); + assertEquals(claimedTask.getClaimed(), claimedTask.getModified()); + assertTrue(claimedTask.isRead()); + assertEquals("user_1_2", claimedTask.getOwner()); + } - @WithAccessId( - userName = "user_1_2", - groupNames = {"group_1"}) - @Test - void testThrowsExceptionIfTaskIsAlreadyClaimed() - throws NotAuthorizedException, TaskNotFoundException { - TaskService taskService = taskanaEngine.getTaskService(); - Task task = taskService.getTask("TKI:000000000000000000000000000000000026"); + @WithAccessId( + userName = "user_1_2", + groupNames = {"group_1"}) + @Test + void testThrowsExceptionIfTaskIsAlreadyClaimed() + throws NotAuthorizedException, TaskNotFoundException { + TaskService taskService = taskanaEngine.getTaskService(); + Task task = taskService.getTask("TKI:000000000000000000000000000000000026"); - Assertions.assertThrows(InvalidOwnerException.class, () -> - taskService.claim(task.getId())); - } + Assertions.assertThrows(InvalidOwnerException.class, () -> taskService.claim(task.getId())); + } - @WithAccessId( - userName = "user_1_2", - groupNames = {"group_1"}) - @Test - void testClaimAlreadyClaimedByCallerTask() - throws NotAuthorizedException, TaskNotFoundException, - InvalidStateException, InvalidOwnerException { - TaskService taskService = taskanaEngine.getTaskService(); - Task task = taskService.getTask("TKI:000000000000000000000000000000000027"); + @WithAccessId( + userName = "user_1_2", + groupNames = {"group_1"}) + @Test + void testClaimAlreadyClaimedByCallerTask() + throws NotAuthorizedException, TaskNotFoundException, InvalidStateException, + InvalidOwnerException { + TaskService taskService = taskanaEngine.getTaskService(); + Task task = taskService.getTask("TKI:000000000000000000000000000000000027"); - taskService.claim(task.getId()); - } + taskService.claim(task.getId()); + } - @WithAccessId( - userName = "user_1_2", - groupNames = {"group_1"}) - @Test - void testForceClaimTaskWhichIsAlreadyClaimedByAnotherUser() - throws NotAuthorizedException, TaskNotFoundException { - TaskService taskService = taskanaEngine.getTaskService(); - Task task = taskService.getTask("TKI:000000000000000000000000000000000028"); + @WithAccessId( + userName = "user_1_2", + groupNames = {"group_1"}) + @Test + void testForceClaimTaskWhichIsAlreadyClaimedByAnotherUser() + throws NotAuthorizedException, TaskNotFoundException { + TaskService taskService = taskanaEngine.getTaskService(); + Task task = taskService.getTask("TKI:000000000000000000000000000000000028"); - Assertions.assertThrows(InvalidOwnerException.class, () -> - taskService.claim(task.getId())); - } + Assertions.assertThrows(InvalidOwnerException.class, () -> taskService.claim(task.getId())); + } - @WithAccessId( - userName = "user_1_2", - groupNames = {"group_1"}) - @Test - void testCancelClaimTask() - throws NotAuthorizedException, TaskNotFoundException, - InvalidStateException, InvalidOwnerException { - TaskService taskService = taskanaEngine.getTaskService(); - Task claimedTask = taskService.getTask("TKI:000000000000000000000000000000000029"); + @WithAccessId( + userName = "user_1_2", + groupNames = {"group_1"}) + @Test + void testCancelClaimTask() + throws NotAuthorizedException, TaskNotFoundException, InvalidStateException, + InvalidOwnerException { + TaskService taskService = taskanaEngine.getTaskService(); + Task claimedTask = taskService.getTask("TKI:000000000000000000000000000000000029"); - taskService.cancelClaim(claimedTask.getId()); + taskService.cancelClaim(claimedTask.getId()); - Task unclaimedTask = taskService.getTask("TKI:000000000000000000000000000000000029"); - assertNotNull(unclaimedTask); - assertEquals(TaskState.READY, unclaimedTask.getState()); - assertNull(unclaimedTask.getClaimed()); - assertTrue(unclaimedTask.isRead()); - assertNull(unclaimedTask.getOwner()); - } + Task unclaimedTask = taskService.getTask("TKI:000000000000000000000000000000000029"); + assertNotNull(unclaimedTask); + assertEquals(TaskState.READY, unclaimedTask.getState()); + assertNull(unclaimedTask.getClaimed()); + assertTrue(unclaimedTask.isRead()); + assertNull(unclaimedTask.getOwner()); + } - @WithAccessId( - userName = "user_1_2", - groupNames = {"group_1"}) - @Test - void testThrowsExceptionIfCancelClaimOfTaskFromAnotherUser() - throws NotAuthorizedException, TaskNotFoundException { - TaskService taskService = taskanaEngine.getTaskService(); - Task claimedTask = taskService.getTask("TKI:000000000000000000000000000000000030"); + @WithAccessId( + userName = "user_1_2", + groupNames = {"group_1"}) + @Test + void testThrowsExceptionIfCancelClaimOfTaskFromAnotherUser() + throws NotAuthorizedException, TaskNotFoundException { + TaskService taskService = taskanaEngine.getTaskService(); + Task claimedTask = taskService.getTask("TKI:000000000000000000000000000000000030"); - Assertions.assertThrows(InvalidOwnerException.class, () -> - taskService.cancelClaim(claimedTask.getId())); - } + Assertions.assertThrows( + InvalidOwnerException.class, () -> taskService.cancelClaim(claimedTask.getId())); + } - @WithAccessId( - userName = "user_1_2", - groupNames = {"group_1"}) - @Test - void testForceCancelClaimOfTaskFromAnotherUser() - throws NotAuthorizedException, TaskNotFoundException, - InvalidStateException, InvalidOwnerException { - TaskService taskService = taskanaEngine.getTaskService(); - Task claimedTask = taskService.getTask("TKI:000000000000000000000000000000000031"); + @WithAccessId( + userName = "user_1_2", + groupNames = {"group_1"}) + @Test + void testForceCancelClaimOfTaskFromAnotherUser() + throws NotAuthorizedException, TaskNotFoundException, InvalidStateException, + InvalidOwnerException { + TaskService taskService = taskanaEngine.getTaskService(); + Task claimedTask = taskService.getTask("TKI:000000000000000000000000000000000031"); - taskService.forceCancelClaim(claimedTask.getId()); + taskService.forceCancelClaim(claimedTask.getId()); - Task unclaimedTask = taskService.getTask("TKI:000000000000000000000000000000000031"); - assertNotNull(unclaimedTask); - assertEquals(TaskState.READY, unclaimedTask.getState()); - assertNull(unclaimedTask.getClaimed()); - assertTrue(unclaimedTask.isRead()); - assertNull(unclaimedTask.getOwner()); - } + Task unclaimedTask = taskService.getTask("TKI:000000000000000000000000000000000031"); + assertNotNull(unclaimedTask); + assertEquals(TaskState.READY, unclaimedTask.getState()); + assertNull(unclaimedTask.getClaimed()); + assertTrue(unclaimedTask.isRead()); + assertNull(unclaimedTask.getOwner()); + } - @WithAccessId( - userName = "user_1_2", - groupNames = {"group_1"}) - @Test - void testCompleteTask() - throws NotAuthorizedException, TaskNotFoundException, - InvalidStateException, InvalidOwnerException { - Instant before = Instant.now().minus(Duration.ofSeconds(3L)); - TaskService taskService = taskanaEngine.getTaskService(); - Task claimedTask = taskService.getTask("TKI:000000000000000000000000000000000032"); + @WithAccessId( + userName = "user_1_2", + groupNames = {"group_1"}) + @Test + void testCompleteTask() + throws NotAuthorizedException, TaskNotFoundException, InvalidStateException, + InvalidOwnerException { + Instant before = Instant.now().minus(Duration.ofSeconds(3L)); + TaskService taskService = taskanaEngine.getTaskService(); + Task claimedTask = taskService.getTask("TKI:000000000000000000000000000000000032"); - taskService.completeTask(claimedTask.getId()); + taskService.completeTask(claimedTask.getId()); - Task completedTask = taskService.getTask("TKI:000000000000000000000000000000000032"); - assertNotNull(completedTask); - assertEquals(TaskState.COMPLETED, completedTask.getState()); - assertNotNull(completedTask.getCompleted()); - assertEquals(completedTask.getCompleted(), completedTask.getModified()); - assertTrue(completedTask.getCompleted().isAfter(before)); - assertTrue(completedTask.getModified().isAfter(before)); - assertTrue(completedTask.isRead()); - assertEquals("user_1_2", completedTask.getOwner()); - } + Task completedTask = taskService.getTask("TKI:000000000000000000000000000000000032"); + assertNotNull(completedTask); + assertEquals(TaskState.COMPLETED, completedTask.getState()); + assertNotNull(completedTask.getCompleted()); + assertEquals(completedTask.getCompleted(), completedTask.getModified()); + assertTrue(completedTask.getCompleted().isAfter(before)); + assertTrue(completedTask.getModified().isAfter(before)); + assertTrue(completedTask.isRead()); + assertEquals("user_1_2", completedTask.getOwner()); + } - @WithAccessId( - userName = "user_1_2", - groupNames = {"group_1"}) - @Test - void testForceCompleteUnclaimedTask() - throws NotAuthorizedException, TaskNotFoundException, - InvalidStateException, InvalidOwnerException { - TaskService taskService = taskanaEngine.getTaskService(); - Task claimedTask = taskService.getTask("TKI:000000000000000000000000000000000033"); + @WithAccessId( + userName = "user_1_2", + groupNames = {"group_1"}) + @Test + void testForceCompleteUnclaimedTask() + throws NotAuthorizedException, TaskNotFoundException, InvalidStateException, + InvalidOwnerException { + TaskService taskService = taskanaEngine.getTaskService(); + Task claimedTask = taskService.getTask("TKI:000000000000000000000000000000000033"); - taskService.forceCompleteTask(claimedTask.getId()); + taskService.forceCompleteTask(claimedTask.getId()); - Task completedTask = taskService.getTask("TKI:000000000000000000000000000000000033"); - assertNotNull(completedTask); - assertEquals(TaskState.COMPLETED, completedTask.getState()); - assertNotNull(completedTask.getCompleted()); - assertEquals(completedTask.getCompleted(), completedTask.getModified()); - assertTrue(completedTask.isRead()); - assertEquals("user_1_2", completedTask.getOwner()); - } + Task completedTask = taskService.getTask("TKI:000000000000000000000000000000000033"); + assertNotNull(completedTask); + assertEquals(TaskState.COMPLETED, completedTask.getState()); + assertNotNull(completedTask.getCompleted()); + assertEquals(completedTask.getCompleted(), completedTask.getModified()); + assertTrue(completedTask.isRead()); + assertEquals("user_1_2", completedTask.getOwner()); + } - @WithAccessId( - userName = "user_1_2", - groupNames = {"group_1"}) - @Test - void testThrowsExceptionIfCompletingClaimedTaskOfAnotherUser() - throws NotAuthorizedException, TaskNotFoundException { - TaskService taskService = taskanaEngine.getTaskService(); - Task claimedTask = taskService.getTask("TKI:000000000000000000000000000000000034"); + @WithAccessId( + userName = "user_1_2", + groupNames = {"group_1"}) + @Test + void testThrowsExceptionIfCompletingClaimedTaskOfAnotherUser() + throws NotAuthorizedException, TaskNotFoundException { + TaskService taskService = taskanaEngine.getTaskService(); + Task claimedTask = taskService.getTask("TKI:000000000000000000000000000000000034"); - Assertions.assertThrows(InvalidOwnerException.class, () -> - taskService.completeTask(claimedTask.getId())); - } + Assertions.assertThrows( + InvalidOwnerException.class, () -> taskService.completeTask(claimedTask.getId())); + } - @WithAccessId( - userName = "user_1_2", - groupNames = {"group_1"}) - @Test - void testForceCompleteClaimedTaskOfAnotherUser() - throws NotAuthorizedException, TaskNotFoundException, - InvalidStateException, InvalidOwnerException { - TaskService taskService = taskanaEngine.getTaskService(); - Task claimedTask = taskService.getTask("TKI:000000000000000000000000000000000035"); + @WithAccessId( + userName = "user_1_2", + groupNames = {"group_1"}) + @Test + void testForceCompleteClaimedTaskOfAnotherUser() + throws NotAuthorizedException, TaskNotFoundException, InvalidStateException, + InvalidOwnerException { + TaskService taskService = taskanaEngine.getTaskService(); + Task claimedTask = taskService.getTask("TKI:000000000000000000000000000000000035"); - taskService.forceCompleteTask(claimedTask.getId()); + taskService.forceCompleteTask(claimedTask.getId()); - Task completedTask = taskService.getTask("TKI:000000000000000000000000000000000035"); - assertNotNull(completedTask); - assertEquals(TaskState.COMPLETED, completedTask.getState()); - assertNotNull(completedTask.getCompleted()); - assertEquals(completedTask.getCompleted(), completedTask.getModified()); - assertTrue(completedTask.isRead()); - assertEquals("user_1_2", completedTask.getOwner()); - } + Task completedTask = taskService.getTask("TKI:000000000000000000000000000000000035"); + assertNotNull(completedTask); + assertEquals(TaskState.COMPLETED, completedTask.getState()); + assertNotNull(completedTask.getCompleted()); + assertEquals(completedTask.getCompleted(), completedTask.getModified()); + assertTrue(completedTask.isRead()); + assertEquals("user_1_2", completedTask.getOwner()); + } - @WithAccessId( - userName = "user_1_2", - groupNames = {"group_1"}) - @Test - void testBulkCompleteTasks() - throws NotAuthorizedException, InvalidArgumentException, TaskNotFoundException { + @WithAccessId( + userName = "user_1_2", + groupNames = {"group_1"}) + @Test + void testBulkCompleteTasks() + throws NotAuthorizedException, InvalidArgumentException, TaskNotFoundException { - TaskService taskService = taskanaEngine.getTaskService(); - List taskIdList = new ArrayList<>(); - taskIdList.add("TKI:000000000000000000000000000000000100"); - taskIdList.add("TKI:000000000000000000000000000000000101"); + TaskService taskService = taskanaEngine.getTaskService(); + List taskIdList = new ArrayList<>(); + taskIdList.add("TKI:000000000000000000000000000000000100"); + taskIdList.add("TKI:000000000000000000000000000000000101"); - BulkOperationResults results = taskService.completeTasks(taskIdList); + BulkOperationResults results = taskService.completeTasks(taskIdList); - assertFalse(results.containsErrors()); - Task completedTask1 = taskService.getTask("TKI:000000000000000000000000000000000100"); - assertEquals(TaskState.COMPLETED, completedTask1.getState()); - assertNotNull(completedTask1.getCompleted()); - Task completedTask2 = taskService.getTask("TKI:000000000000000000000000000000000101"); - assertEquals(TaskState.COMPLETED, completedTask2.getState()); - assertNotNull(completedTask2.getCompleted()); - } + assertFalse(results.containsErrors()); + Task completedTask1 = taskService.getTask("TKI:000000000000000000000000000000000100"); + assertEquals(TaskState.COMPLETED, completedTask1.getState()); + assertNotNull(completedTask1.getCompleted()); + Task completedTask2 = taskService.getTask("TKI:000000000000000000000000000000000101"); + assertEquals(TaskState.COMPLETED, completedTask2.getState()); + assertNotNull(completedTask2.getCompleted()); + } - @WithAccessId( - userName = "user_1_2", - groupNames = {"group_1"}) - @Test - void testBulkDeleteTasksWithException() - throws InvalidArgumentException { + @WithAccessId( + userName = "user_1_2", + groupNames = {"group_1"}) + @Test + void testBulkDeleteTasksWithException() throws InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); - List taskIdList = new ArrayList<>(); - taskIdList.add("TKI:000000000000000000000000000000000102"); - taskIdList.add("TKI:000000000000000000000000000000003333"); + TaskService taskService = taskanaEngine.getTaskService(); + List taskIdList = new ArrayList<>(); + taskIdList.add("TKI:000000000000000000000000000000000102"); + taskIdList.add("TKI:000000000000000000000000000000003333"); - BulkOperationResults results = taskService.deleteTasks(taskIdList); - - assertTrue(results.containsErrors()); - assertThat(results.getErrorMap().size(), equalTo(2)); - assertTrue(results.getErrorForId("TKI:000000000000000000000000000000003333") instanceof TaskNotFoundException); - assertTrue(results.getErrorForId("TKI:000000000000000000000000000000000102") instanceof InvalidStateException); - } + BulkOperationResults results = taskService.deleteTasks(taskIdList); + assertTrue(results.containsErrors()); + assertThat(results.getErrorMap().size(), equalTo(2)); + assertTrue( + results.getErrorForId("TKI:000000000000000000000000000000003333") + instanceof TaskNotFoundException); + assertTrue( + results.getErrorForId("TKI:000000000000000000000000000000000102") + instanceof InvalidStateException); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/taskrouting/TaskRoutingAccTest.java b/lib/taskana-core/src/test/java/acceptance/taskrouting/TaskRoutingAccTest.java index 421e42649..0371fc2f6 100644 --- a/lib/taskana-core/src/test/java/acceptance/taskrouting/TaskRoutingAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/taskrouting/TaskRoutingAccTest.java @@ -2,11 +2,11 @@ package acceptance.taskrouting; import static org.junit.jupiter.api.Assertions.assertEquals; +import acceptance.AbstractAccTest; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.Task; import pro.taskana.TaskService; import pro.taskana.exceptions.ClassificationNotFoundException; @@ -19,54 +19,62 @@ import pro.taskana.impl.TaskImpl; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "create task" scenarios. - */ +/** Acceptance test for all "create task" scenarios. */ @ExtendWith(JAASExtension.class) class TaskRoutingAccTest extends AbstractAccTest { - @WithAccessId(userName = "admin", groupNames = {"group_1"}) - @Test - void testCreateTaskWithoutWorkbasketAndVoidNewTaskMethod() - throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException { - TaskService taskService = taskanaEngine.getTaskService(); + @WithAccessId( + userName = "admin", + groupNames = {"group_1"}) + @Test + void testCreateTaskWithoutWorkbasketAndVoidNewTaskMethod() + throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException { + TaskService taskService = taskanaEngine.getTaskService(); - Task newTask = taskService.newTask(); - newTask.setClassificationKey("L10303"); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - final Task taskToCreate = newTask; - Assertions.assertThrows(InvalidArgumentException.class, () -> taskService.createTask(taskToCreate)); - ((TaskImpl) taskToCreate).setDomain("DOMAIN_C"); - Assertions.assertThrows(InvalidArgumentException.class, () -> taskService.createTask(taskToCreate)); - ((TaskImpl) taskToCreate).setDomain("DOMAIN_B"); - Task createdTask = taskService.createTask(taskToCreate); - assertEquals("WBI:100000000000000000000000000000000011", createdTask.getWorkbasketSummary().getId()); - } + Task newTask = taskService.newTask(); + newTask.setClassificationKey("L10303"); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + final Task taskToCreate = newTask; + Assertions.assertThrows( + InvalidArgumentException.class, () -> taskService.createTask(taskToCreate)); + ((TaskImpl) taskToCreate).setDomain("DOMAIN_C"); + Assertions.assertThrows( + InvalidArgumentException.class, () -> taskService.createTask(taskToCreate)); + ((TaskImpl) taskToCreate).setDomain("DOMAIN_B"); + Task createdTask = taskService.createTask(taskToCreate); + assertEquals( + "WBI:100000000000000000000000000000000011", createdTask.getWorkbasketSummary().getId()); + } - @WithAccessId(userName = "admin", groupNames = {"group_1"}) - @Test - void testCreateTaskWithNullWorkbasket() - throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException { - TaskImpl createdTaskA = createTask("DOMAIN_A", "L12010"); - assertEquals("WBI:100000000000000000000000000000000001", createdTaskA.getWorkbasketSummary().getId()); - TaskImpl createdTaskB = createTask("DOMAIN_B", "T21001"); - assertEquals("WBI:100000000000000000000000000000000011", createdTaskB.getWorkbasketSummary().getId()); - Assertions.assertThrows(InvalidArgumentException.class, () -> createTask(null, "L12010")); - } + @WithAccessId( + userName = "admin", + groupNames = {"group_1"}) + @Test + void testCreateTaskWithNullWorkbasket() + throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + TaskAlreadyExistException, InvalidArgumentException, TaskNotFoundException { + TaskImpl createdTaskA = createTask("DOMAIN_A", "L12010"); + assertEquals( + "WBI:100000000000000000000000000000000001", createdTaskA.getWorkbasketSummary().getId()); + TaskImpl createdTaskB = createTask("DOMAIN_B", "T21001"); + assertEquals( + "WBI:100000000000000000000000000000000011", createdTaskB.getWorkbasketSummary().getId()); + Assertions.assertThrows(InvalidArgumentException.class, () -> createTask(null, "L12010")); + } - private TaskImpl createTask(String domain, String classificationKey) - throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - TaskAlreadyExistException, InvalidArgumentException { - TaskService taskService = taskanaEngine.getTaskService(); + private TaskImpl createTask(String domain, String classificationKey) + throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + TaskAlreadyExistException, InvalidArgumentException { + TaskService taskService = taskanaEngine.getTaskService(); - Task newTask = taskService.newTask(null, domain); - newTask.setClassificationKey(classificationKey); - - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - TaskImpl createdTask = (TaskImpl) taskService.createTask(newTask); - return createdTask; - } + Task newTask = taskService.newTask(null, domain); + newTask.setClassificationKey(classificationKey); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + TaskImpl createdTask = (TaskImpl) taskService.createTask(newTask); + return createdTask; + } } diff --git a/lib/taskana-core/src/test/java/acceptance/taskrouting/TestTaskRoutingProviderForDomainA.java b/lib/taskana-core/src/test/java/acceptance/taskrouting/TestTaskRoutingProviderForDomainA.java index 1b81ed417..b9a3bba44 100644 --- a/lib/taskana-core/src/test/java/acceptance/taskrouting/TestTaskRoutingProviderForDomainA.java +++ b/lib/taskana-core/src/test/java/acceptance/taskrouting/TestTaskRoutingProviderForDomainA.java @@ -4,25 +4,22 @@ import pro.taskana.Task; import pro.taskana.TaskanaEngine; import pro.taskana.taskrouting.api.TaskRoutingProvider; -/** - * This is a sample implementation of TaskRouter. - */ +/** This is a sample implementation of TaskRouter. */ public class TestTaskRoutingProviderForDomainA implements TaskRoutingProvider { - TaskanaEngine theEngine; + TaskanaEngine theEngine; - @Override - public void initialize(TaskanaEngine taskanaEngine) { - theEngine = taskanaEngine; + @Override + public void initialize(TaskanaEngine taskanaEngine) { + theEngine = taskanaEngine; + } + + @Override + public String determineWorkbasketId(Task task) { + if ("DOMAIN_A".equals(task.getDomain())) { + return "WBI:100000000000000000000000000000000001"; + } else { + return null; } - - @Override - public String determineWorkbasketId(Task task) { - if ("DOMAIN_A".equals(task.getDomain())) { - return "WBI:100000000000000000000000000000000001"; - } else { - return null; - } - } - + } } diff --git a/lib/taskana-core/src/test/java/acceptance/taskrouting/TestTaskRoutingProviderForDomainB.java b/lib/taskana-core/src/test/java/acceptance/taskrouting/TestTaskRoutingProviderForDomainB.java index cdcc19ffa..42b10f3a5 100644 --- a/lib/taskana-core/src/test/java/acceptance/taskrouting/TestTaskRoutingProviderForDomainB.java +++ b/lib/taskana-core/src/test/java/acceptance/taskrouting/TestTaskRoutingProviderForDomainB.java @@ -4,25 +4,22 @@ import pro.taskana.Task; import pro.taskana.TaskanaEngine; import pro.taskana.taskrouting.api.TaskRoutingProvider; -/** - * This is a sample implementation of TaskRouter. - */ +/** This is a sample implementation of TaskRouter. */ public class TestTaskRoutingProviderForDomainB implements TaskRoutingProvider { - TaskanaEngine theEngine; + TaskanaEngine theEngine; - @Override - public void initialize(TaskanaEngine taskanaEngine) { - theEngine = taskanaEngine; + @Override + public void initialize(TaskanaEngine taskanaEngine) { + theEngine = taskanaEngine; + } + + @Override + public String determineWorkbasketId(Task task) { + if ("DOMAIN_B".equals(task.getDomain())) { + return "WBI:100000000000000000000000000000000011"; + } else { + return null; } - - @Override - public String determineWorkbasketId(Task task) { - if ("DOMAIN_B".equals(task.getDomain())) { - return "WBI:100000000000000000000000000000000011"; - } else { - return null; - } - } - + } } diff --git a/lib/taskana-core/src/test/java/acceptance/workbasket/CreateWorkbasketAccTest.java b/lib/taskana-core/src/test/java/acceptance/workbasket/CreateWorkbasketAccTest.java index b9c5a8b9b..2f9b04050 100644 --- a/lib/taskana-core/src/test/java/acceptance/workbasket/CreateWorkbasketAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/workbasket/CreateWorkbasketAccTest.java @@ -4,13 +4,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import acceptance.AbstractAccTest; import java.util.List; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.Workbasket; import pro.taskana.WorkbasketAccessItem; import pro.taskana.WorkbasketService; @@ -24,206 +23,207 @@ import pro.taskana.exceptions.WorkbasketNotFoundException; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "create workbasket" scenarios. - */ +/** Acceptance test for all "create workbasket" scenarios. */ @ExtendWith(JAASExtension.class) class CreateWorkbasketAccTest extends AbstractAccTest { - CreateWorkbasketAccTest() { - super(); - } + CreateWorkbasketAccTest() { + super(); + } - @WithAccessId( - userName = "user_1_2", - groupNames = {"businessadmin"}) - @Test - void testCreateWorkbasket() - throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException, - InvalidWorkbasketException, WorkbasketAlreadyExistException, DomainNotFoundException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - int before = workbasketService.createWorkbasketQuery().domainIn("DOMAIN_A").list().size(); + @WithAccessId( + userName = "user_1_2", + groupNames = {"businessadmin"}) + @Test + void testCreateWorkbasket() + throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException, + InvalidWorkbasketException, WorkbasketAlreadyExistException, DomainNotFoundException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + int before = workbasketService.createWorkbasketQuery().domainIn("DOMAIN_A").list().size(); - Workbasket workbasket = workbasketService.newWorkbasket("NT1234", "DOMAIN_A"); - workbasket.setName("Megabasket"); - workbasket.setType(WorkbasketType.GROUP); - workbasket.setOrgLevel1("company"); - workbasket = workbasketService.createWorkbasket(workbasket); - WorkbasketAccessItem wbai = workbasketService.newWorkbasketAccessItem(workbasket.getId(), "user_1_2"); - wbai.setPermRead(true); - workbasketService.createWorkbasketAccessItem(wbai); + Workbasket workbasket = workbasketService.newWorkbasket("NT1234", "DOMAIN_A"); + workbasket.setName("Megabasket"); + workbasket.setType(WorkbasketType.GROUP); + workbasket.setOrgLevel1("company"); + workbasket = workbasketService.createWorkbasket(workbasket); + WorkbasketAccessItem wbai = + workbasketService.newWorkbasketAccessItem(workbasket.getId(), "user_1_2"); + wbai.setPermRead(true); + workbasketService.createWorkbasketAccessItem(wbai); - int after = workbasketService.createWorkbasketQuery().domainIn("DOMAIN_A").list().size(); - assertEquals(before + 1, after); - Workbasket createdWorkbasket = workbasketService.getWorkbasket("NT1234", "DOMAIN_A"); - assertNotNull(createdWorkbasket); - assertNotNull(createdWorkbasket.getId()); - assertTrue(createdWorkbasket.getId().startsWith("WBI")); - assertEquals(workbasket, createdWorkbasket); - Workbasket createdWorkbasket2 = workbasketService.getWorkbasket(createdWorkbasket.getId()); - assertNotNull(createdWorkbasket); - assertEquals(createdWorkbasket, createdWorkbasket2); - } + int after = workbasketService.createWorkbasketQuery().domainIn("DOMAIN_A").list().size(); + assertEquals(before + 1, after); + Workbasket createdWorkbasket = workbasketService.getWorkbasket("NT1234", "DOMAIN_A"); + assertNotNull(createdWorkbasket); + assertNotNull(createdWorkbasket.getId()); + assertTrue(createdWorkbasket.getId().startsWith("WBI")); + assertEquals(workbasket, createdWorkbasket); + Workbasket createdWorkbasket2 = workbasketService.getWorkbasket(createdWorkbasket.getId()); + assertNotNull(createdWorkbasket); + assertEquals(createdWorkbasket, createdWorkbasket2); + } - @WithAccessId( - userName = "dummy") - @Test - void testCreateWorkbasketNotAuthorized() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + @WithAccessId(userName = "dummy") + @Test + void testCreateWorkbasketNotAuthorized() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - Workbasket workbasket = workbasketService.newWorkbasket("key3", "DOMAIN_A"); - workbasket.setName("Megabasket"); - workbasket.setType(WorkbasketType.GROUP); - workbasket.setOrgLevel1("company"); + Workbasket workbasket = workbasketService.newWorkbasket("key3", "DOMAIN_A"); + workbasket.setName("Megabasket"); + workbasket.setType(WorkbasketType.GROUP); + workbasket.setOrgLevel1("company"); - Assertions.assertThrows(NotAuthorizedException.class, () -> - workbasketService.createWorkbasket(workbasket)); + Assertions.assertThrows( + NotAuthorizedException.class, () -> workbasketService.createWorkbasket(workbasket)); + } - } + @WithAccessId( + userName = "user_1_2", + groupNames = {"businessadmin"}) + @Test + void testCreateWorkbasketWithInvalidDomain() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - @WithAccessId( - userName = "user_1_2", - groupNames = {"businessadmin"}) - @Test - void testCreateWorkbasketWithInvalidDomain() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + Workbasket workbasket = workbasketService.newWorkbasket("key3", "UNKNOWN_DOMAIN"); + workbasket.setName("Megabasket"); + workbasket.setType(WorkbasketType.GROUP); + workbasket.setOrgLevel1("company"); + Assertions.assertThrows( + DomainNotFoundException.class, () -> workbasketService.createWorkbasket(workbasket)); + } - Workbasket workbasket = workbasketService.newWorkbasket("key3", "UNKNOWN_DOMAIN"); - workbasket.setName("Megabasket"); - workbasket.setType(WorkbasketType.GROUP); - workbasket.setOrgLevel1("company"); - Assertions.assertThrows(DomainNotFoundException.class, () -> - workbasketService.createWorkbasket(workbasket)); - } + @WithAccessId( + userName = "dummy", + groupNames = {"businessadmin"}) + @Test + void testCreateWorkbasketWithMissingRequiredField() + throws NotAuthorizedException, WorkbasketAlreadyExistException, DomainNotFoundException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - @WithAccessId( - userName = "dummy", - groupNames = {"businessadmin"}) - @Test - void testCreateWorkbasketWithMissingRequiredField() - throws NotAuthorizedException, WorkbasketAlreadyExistException, - DomainNotFoundException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + Workbasket workbasket = workbasketService.newWorkbasket(null, "novatec"); + workbasket.setName("Megabasket"); + workbasket.setType(WorkbasketType.GROUP); + workbasket.setOrgLevel1("company"); + // missing key + Assertions.assertThrows( + InvalidWorkbasketException.class, () -> workbasketService.createWorkbasket(workbasket)); - Workbasket workbasket = workbasketService.newWorkbasket(null, "novatec"); - workbasket.setName("Megabasket"); - workbasket.setType(WorkbasketType.GROUP); - workbasket.setOrgLevel1("company"); - // missing key - Assertions.assertThrows(InvalidWorkbasketException.class, () -> workbasketService.createWorkbasket(workbasket)); + Workbasket workbasket2 = workbasketService.newWorkbasket("key", "novatec"); + workbasket2.setType(WorkbasketType.GROUP); + workbasket2.setOrgLevel1("company"); + // missing name + Assertions.assertThrows( + InvalidWorkbasketException.class, () -> workbasketService.createWorkbasket(workbasket2)); - Workbasket workbasket2 = workbasketService.newWorkbasket("key", "novatec"); - workbasket2.setType(WorkbasketType.GROUP); - workbasket2.setOrgLevel1("company"); - // missing name - Assertions.assertThrows(InvalidWorkbasketException.class, - () -> workbasketService.createWorkbasket(workbasket2)); + Workbasket workbasket3 = workbasketService.newWorkbasket("key", "novatec"); + workbasket3.setName("Megabasket"); + workbasket3.setOrgLevel1("company"); + // missing type + Assertions.assertThrows( + InvalidWorkbasketException.class, () -> workbasketService.createWorkbasket(workbasket3)); - Workbasket workbasket3 = workbasketService.newWorkbasket("key", "novatec"); - workbasket3.setName("Megabasket"); - workbasket3.setOrgLevel1("company"); - // missing type - Assertions.assertThrows(InvalidWorkbasketException.class, - () -> workbasketService.createWorkbasket(workbasket3)); + Workbasket workbasket4 = workbasketService.newWorkbasket("key", null); + workbasket4.setName("Megabasket"); + workbasket4.setType(WorkbasketType.GROUP); + workbasket4.setOrgLevel1("company"); + // missing domain + Assertions.assertThrows( + InvalidWorkbasketException.class, () -> workbasketService.createWorkbasket(workbasket4)); - Workbasket workbasket4 = workbasketService.newWorkbasket("key", null); - workbasket4.setName("Megabasket"); - workbasket4.setType(WorkbasketType.GROUP); - workbasket4.setOrgLevel1("company"); - // missing domain - Assertions.assertThrows(InvalidWorkbasketException.class, - () -> workbasketService.createWorkbasket(workbasket4)); + Workbasket workbasket5 = workbasketService.newWorkbasket("", "novatec"); + workbasket5.setName("Megabasket"); + workbasket5.setType(WorkbasketType.GROUP); + workbasket5.setOrgLevel1("company"); + // empty key + Assertions.assertThrows( + InvalidWorkbasketException.class, () -> workbasketService.createWorkbasket(workbasket5)); - Workbasket workbasket5 = workbasketService.newWorkbasket("", "novatec"); - workbasket5.setName("Megabasket"); - workbasket5.setType(WorkbasketType.GROUP); - workbasket5.setOrgLevel1("company"); - // empty key - Assertions.assertThrows(InvalidWorkbasketException.class, - () -> workbasketService.createWorkbasket(workbasket5)); + Workbasket workbasket6 = workbasketService.newWorkbasket("key", "novatec"); + workbasket6.setName(""); + workbasket6.setType(WorkbasketType.GROUP); + workbasket6.setOrgLevel1("company"); + // empty name + Assertions.assertThrows( + InvalidWorkbasketException.class, () -> workbasketService.createWorkbasket(workbasket)); + } - Workbasket workbasket6 = workbasketService.newWorkbasket("key", "novatec"); - workbasket6.setName(""); - workbasket6.setType(WorkbasketType.GROUP); - workbasket6.setOrgLevel1("company"); - // empty name - Assertions.assertThrows(InvalidWorkbasketException.class, () -> workbasketService.createWorkbasket(workbasket)); - } + @WithAccessId( + userName = "user_1_2", + groupNames = {"businessadmin"}) + @Test + void testThrowsExceptionIfWorkbasketWithCaseInsensitiveSameKeyDomainIsCreated() + throws NotAuthorizedException, InvalidWorkbasketException, WorkbasketAlreadyExistException, + DomainNotFoundException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - @WithAccessId( - userName = "user_1_2", - groupNames = {"businessadmin"}) - @Test - void testThrowsExceptionIfWorkbasketWithCaseInsensitiveSameKeyDomainIsCreated() - throws NotAuthorizedException, InvalidWorkbasketException, WorkbasketAlreadyExistException, - DomainNotFoundException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + Workbasket workbasket = workbasketService.newWorkbasket("X123456", "DOMAIN_A"); + workbasket.setName("Personal Workbasket for UID X123456"); + workbasket.setType(WorkbasketType.PERSONAL); + workbasket = workbasketService.createWorkbasket(workbasket); - Workbasket workbasket = workbasketService.newWorkbasket("X123456", "DOMAIN_A"); - workbasket.setName("Personal Workbasket for UID X123456"); - workbasket.setType(WorkbasketType.PERSONAL); - workbasket = workbasketService.createWorkbasket(workbasket); + Workbasket duplicateWorkbasketWithSmallX = + workbasketService.newWorkbasket("x123456", "DOMAIN_A"); + duplicateWorkbasketWithSmallX.setName("Personal Workbasket for UID X123456"); + duplicateWorkbasketWithSmallX.setType(WorkbasketType.PERSONAL); - Workbasket duplicateWorkbasketWithSmallX = workbasketService.newWorkbasket("x123456", "DOMAIN_A"); - duplicateWorkbasketWithSmallX.setName("Personal Workbasket for UID X123456"); - duplicateWorkbasketWithSmallX.setType(WorkbasketType.PERSONAL); + Assertions.assertThrows( + WorkbasketAlreadyExistException.class, + () -> workbasketService.createWorkbasket(duplicateWorkbasketWithSmallX)); + } - Assertions.assertThrows(WorkbasketAlreadyExistException.class, () -> - workbasketService.createWorkbasket(duplicateWorkbasketWithSmallX)); - } + @WithAccessId( + userName = "user_1_2", + groupNames = {"businessadmin"}) + @Test + void testCreateWorkbasketWithAlreadyExistingKeyAndDomainAndEmptyIdUpdatesOlderWorkbasket() + throws DomainNotFoundException, InvalidWorkbasketException, NotAuthorizedException, + WorkbasketAlreadyExistException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + // First create a new Workbasket. + Workbasket wb = workbasketService.newWorkbasket("newKey", "DOMAIN_A"); + wb.setType(WorkbasketType.GROUP); + wb.setName("this name"); + wb = workbasketService.createWorkbasket(wb); - @WithAccessId( - userName = "user_1_2", - groupNames = {"businessadmin"}) - @Test - void testCreateWorkbasketWithAlreadyExistingKeyAndDomainAndEmptyIdUpdatesOlderWorkbasket() - throws DomainNotFoundException, InvalidWorkbasketException, - NotAuthorizedException, WorkbasketAlreadyExistException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - // First create a new Workbasket. - Workbasket wb = workbasketService.newWorkbasket("newKey", "DOMAIN_A"); - wb.setType(WorkbasketType.GROUP); - wb.setName("this name"); - wb = workbasketService.createWorkbasket(wb); + // Second create a new Workbasket with same Key and Domain. + Workbasket sameKeyAndDomain = workbasketService.newWorkbasket("newKey", "DOMAIN_A"); + sameKeyAndDomain.setType(WorkbasketType.TOPIC); + sameKeyAndDomain.setName("new name"); - // Second create a new Workbasket with same Key and Domain. - Workbasket sameKeyAndDomain = workbasketService.newWorkbasket("newKey", "DOMAIN_A"); - sameKeyAndDomain.setType(WorkbasketType.TOPIC); - sameKeyAndDomain.setName("new name"); + Assertions.assertThrows( + WorkbasketAlreadyExistException.class, + () -> workbasketService.createWorkbasket(sameKeyAndDomain)); + } - Assertions.assertThrows(WorkbasketAlreadyExistException.class, () -> - workbasketService.createWorkbasket(sameKeyAndDomain)); - } + @WithAccessId( + userName = "user_1_2", + groupNames = {"businessadmin"}) + @Test + void testWorkbasketAccessItemSetName() + throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException, + InvalidWorkbasketException, WorkbasketAlreadyExistException, DomainNotFoundException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + int before = workbasketService.createWorkbasketQuery().domainIn("DOMAIN_A").list().size(); - @WithAccessId( - userName = "user_1_2", - groupNames = {"businessadmin"}) - @Test - void testWorkbasketAccessItemSetName() - throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException, - InvalidWorkbasketException, WorkbasketAlreadyExistException, DomainNotFoundException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - int before = workbasketService.createWorkbasketQuery().domainIn("DOMAIN_A").list().size(); + Workbasket workbasket = workbasketService.newWorkbasket("WBAIT1234", "DOMAIN_A"); + workbasket.setName("MyNewBasket"); + workbasket.setType(WorkbasketType.PERSONAL); + workbasket.setOrgLevel1("company"); + workbasket = workbasketService.createWorkbasket(workbasket); + WorkbasketAccessItem wbai = + workbasketService.newWorkbasketAccessItem(workbasket.getId(), "user_1_2"); + wbai.setPermRead(true); + wbai.setAccessName("Karl Napf"); + workbasketService.createWorkbasketAccessItem(wbai); - Workbasket workbasket = workbasketService.newWorkbasket("WBAIT1234", "DOMAIN_A"); - workbasket.setName("MyNewBasket"); - workbasket.setType(WorkbasketType.PERSONAL); - workbasket.setOrgLevel1("company"); - workbasket = workbasketService.createWorkbasket(workbasket); - WorkbasketAccessItem wbai = workbasketService.newWorkbasketAccessItem(workbasket.getId(), "user_1_2"); - wbai.setPermRead(true); - wbai.setAccessName("Karl Napf"); - workbasketService.createWorkbasketAccessItem(wbai); - - Workbasket createdWorkbasket = workbasketService.getWorkbasket("WBAIT1234", "DOMAIN_A"); - assertNotNull(createdWorkbasket); - assertNotNull(createdWorkbasket.getId()); - - List accessItems = workbasketService.getWorkbasketAccessItems(createdWorkbasket.getId()); - WorkbasketAccessItem item = accessItems.stream().filter(t -> wbai.getId().equals(t.getId())).findFirst().orElse( - null); - assertEquals("Karl Napf", item.getAccessName()); - - } + Workbasket createdWorkbasket = workbasketService.getWorkbasket("WBAIT1234", "DOMAIN_A"); + assertNotNull(createdWorkbasket); + assertNotNull(createdWorkbasket.getId()); + List accessItems = + workbasketService.getWorkbasketAccessItems(createdWorkbasket.getId()); + WorkbasketAccessItem item = + accessItems.stream().filter(t -> wbai.getId().equals(t.getId())).findFirst().orElse(null); + assertEquals("Karl Napf", item.getAccessName()); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/workbasket/DeleteWorkbasketAccTest.java b/lib/taskana-core/src/test/java/acceptance/workbasket/DeleteWorkbasketAccTest.java index 1c4fbf4ef..08eb82d6a 100644 --- a/lib/taskana-core/src/test/java/acceptance/workbasket/DeleteWorkbasketAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/workbasket/DeleteWorkbasketAccTest.java @@ -6,14 +6,13 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import acceptance.AbstractAccTest; import java.util.List; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.TaskService; import pro.taskana.Workbasket; import pro.taskana.WorkbasketAccessItem; @@ -31,174 +30,196 @@ import pro.taskana.impl.TaskImpl; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test which does test the deletion of a workbasket and all wanted failures. - */ +/** Acceptance test which does test the deletion of a workbasket and all wanted failures. */ @ExtendWith(JAASExtension.class) class DeleteWorkbasketAccTest extends AbstractAccTest { - private WorkbasketService workbasketService; + private WorkbasketService workbasketService; - private TaskService taskService; + private TaskService taskService; - @BeforeEach - void setUpMethod() { - workbasketService = taskanaEngine.getWorkbasketService(); - taskService = taskanaEngine.getTaskService(); - } + @BeforeEach + void setUpMethod() { + workbasketService = taskanaEngine.getWorkbasketService(); + taskService = taskanaEngine.getTaskService(); + } - @WithAccessId(userName = "admin", groupNames = {"businessadmin"}) - @Test - void testDeleteWorkbasket() - throws WorkbasketNotFoundException, NotAuthorizedException { - Workbasket wb = workbasketService.getWorkbasket("USER_2_2", "DOMAIN_A"); + @WithAccessId( + userName = "admin", + groupNames = {"businessadmin"}) + @Test + void testDeleteWorkbasket() throws WorkbasketNotFoundException, NotAuthorizedException { + Workbasket wb = workbasketService.getWorkbasket("USER_2_2", "DOMAIN_A"); - Assertions.assertThrows(WorkbasketNotFoundException.class, () -> { - workbasketService.deleteWorkbasket(wb.getId()); - workbasketService.getWorkbasket("USER_2_2", "DOMAIN_A"); - }, "There should be no result for a deleted Workbasket."); - } + Assertions.assertThrows( + WorkbasketNotFoundException.class, + () -> { + workbasketService.deleteWorkbasket(wb.getId()); + workbasketService.getWorkbasket("USER_2_2", "DOMAIN_A"); + }, + "There should be no result for a deleted Workbasket."); + } - @WithAccessId(userName = "elena") - @Test - void testDeleteWorkbasketNotAuthorized() { + @WithAccessId(userName = "elena") + @Test + void testDeleteWorkbasketNotAuthorized() { - Assertions.assertThrows(NotAuthorizedException.class, () -> { - Workbasket wb = workbasketService.getWorkbasket("TEAMLEAD_2", "DOMAIN_A"); - workbasketService.deleteWorkbasket(wb.getId()); + Assertions.assertThrows( + NotAuthorizedException.class, + () -> { + Workbasket wb = workbasketService.getWorkbasket("TEAMLEAD_2", "DOMAIN_A"); + workbasketService.deleteWorkbasket(wb.getId()); }); - } + } - @WithAccessId(userName = "elena") - @Test - void testGetWorkbasketNotAuthorized() { + @WithAccessId(userName = "elena") + @Test + void testGetWorkbasketNotAuthorized() { - Assertions.assertThrows(NotAuthorizedException.class, () -> - workbasketService.getWorkbasket("TEAMLEAD_2", "DOMAIN_A")); + Assertions.assertThrows( + NotAuthorizedException.class, + () -> workbasketService.getWorkbasket("TEAMLEAD_2", "DOMAIN_A")); + } - } + @WithAccessId( + userName = "user_1_1", + groupNames = {"teamlead_1", "group_1", "businessadmin"}) + @Test + void testDeleteWorkbasketAlsoAsDistributionTarget() + throws WorkbasketNotFoundException, NotAuthorizedException { + Workbasket wb = workbasketService.getWorkbasket("GPK_KSC_1", "DOMAIN_A"); + int distTargets = + workbasketService.getDistributionTargets("WBI:100000000000000000000000000000000001").size(); - @WithAccessId(userName = "user_1_1", groupNames = {"teamlead_1", "group_1", "businessadmin"}) - @Test - void testDeleteWorkbasketAlsoAsDistributionTarget() - throws WorkbasketNotFoundException, NotAuthorizedException { - Workbasket wb = workbasketService.getWorkbasket("GPK_KSC_1", "DOMAIN_A"); - int distTargets = workbasketService.getDistributionTargets("WBI:100000000000000000000000000000000001") - .size(); + Assertions.assertThrows( + WorkbasketNotFoundException.class, + () -> { + // WB deleted + workbasketService.deleteWorkbasket(wb.getId()); + workbasketService.getWorkbasket("GPK_KSC_1", "DOMAIN_A"); + }, + "There should be no result for a deleted Workbasket."); - Assertions.assertThrows(WorkbasketNotFoundException.class, () -> { - // WB deleted - workbasketService.deleteWorkbasket(wb.getId()); - workbasketService.getWorkbasket("GPK_KSC_1", "DOMAIN_A"); - }, "There should be no result for a deleted Workbasket."); + int newDistTargets = + workbasketService.getDistributionTargets("WBI:100000000000000000000000000000000001").size(); + assertThat(newDistTargets, equalTo(3)); + assertTrue(newDistTargets < distTargets); + } - int newDistTargets = workbasketService.getDistributionTargets("WBI:100000000000000000000000000000000001") - .size(); - assertThat(newDistTargets, equalTo(3)); - assertTrue(newDistTargets < distTargets); - } + @WithAccessId( + userName = "dummy", + groupNames = {"businessadmin"}) + @Test + void testDeleteWorkbasketWithNullOrEmptyParam() { + // Test Null-Value + Assertions.assertThrows( + InvalidArgumentException.class, + () -> workbasketService.deleteWorkbasket(null), + "delete() should have thrown an InvalidArgumentException, when the param ID is null."); - @WithAccessId( - userName = "dummy", - groupNames = {"businessadmin"}) - @Test - void testDeleteWorkbasketWithNullOrEmptyParam() { - // Test Null-Value - Assertions.assertThrows(InvalidArgumentException.class, () -> - workbasketService.deleteWorkbasket(null), - "delete() should have thrown an InvalidArgumentException, when the param ID is null."); + // Test EMPTY-Value - // Test EMPTY-Value + Assertions.assertThrows( + InvalidArgumentException.class, + () -> workbasketService.deleteWorkbasket(""), + "delete() should have thrown an InvalidArgumentException, when the param ID is EMPTY-String."); + } - Assertions.assertThrows(InvalidArgumentException.class, () -> - workbasketService.deleteWorkbasket(""), - "delete() should have thrown an InvalidArgumentException, when the param ID is EMPTY-String."); - } + @WithAccessId( + userName = "dummy", + groupNames = {"businessadmin"}) + @Test + void testDeleteWorkbasketButNotExisting() { + Assertions.assertThrows( + WorkbasketNotFoundException.class, + () -> workbasketService.deleteWorkbasket("SOME NOT EXISTING ID")); + } - @WithAccessId( - userName = "dummy", - groupNames = {"businessadmin"}) - @Test - void testDeleteWorkbasketButNotExisting() { - Assertions.assertThrows(WorkbasketNotFoundException.class, () -> - workbasketService.deleteWorkbasket("SOME NOT EXISTING ID")); - } + @WithAccessId( + userName = "user_1_2", + groupNames = {"businessadmin"}) + @Test + void testDeleteWorkbasketWhichIsUsed() + throws WorkbasketNotFoundException, NotAuthorizedException { + Workbasket wb = + workbasketService.getWorkbasket("USER_1_2", "DOMAIN_A"); // all rights, DOMAIN_A with Tasks + Assertions.assertThrows( + WorkbasketInUseException.class, () -> workbasketService.deleteWorkbasket(wb.getId())); + } - @WithAccessId(userName = "user_1_2", - groupNames = {"businessadmin"}) - @Test - void testDeleteWorkbasketWhichIsUsed() - throws WorkbasketNotFoundException, NotAuthorizedException { - Workbasket wb = workbasketService.getWorkbasket("USER_1_2", "DOMAIN_A"); // all rights, DOMAIN_A with Tasks - Assertions.assertThrows(WorkbasketInUseException.class, () -> - workbasketService.deleteWorkbasket(wb.getId())); - } + @WithAccessId( + userName = "user_1_2", + groupNames = {"businessadmin"}) + @Test + void testCreateAndDeleteWorkbasket() throws Exception { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - @WithAccessId( - userName = "user_1_2", - groupNames = {"businessadmin"}) - @Test - void testCreateAndDeleteWorkbasket() throws Exception { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + Workbasket workbasket = workbasketService.newWorkbasket("NT1234", "DOMAIN_A"); + workbasket.setName("TheUltimate"); + workbasket.setType(WorkbasketType.GROUP); + workbasket.setOrgLevel1("company"); + Workbasket workbasket2 = workbasketService.createWorkbasket(workbasket); + Assertions.assertThrows( + NotAuthorizedToQueryWorkbasketException.class, + () -> workbasketService.deleteWorkbasket(workbasket2.getId())); + } - Workbasket workbasket = workbasketService.newWorkbasket("NT1234", "DOMAIN_A"); - workbasket.setName("TheUltimate"); - workbasket.setType(WorkbasketType.GROUP); - workbasket.setOrgLevel1("company"); - Workbasket workbasket2 = workbasketService.createWorkbasket(workbasket); - Assertions.assertThrows(NotAuthorizedToQueryWorkbasketException.class, () -> - workbasketService.deleteWorkbasket(workbasket2.getId())); - } + @WithAccessId( + userName = "teamlead_2", + groupNames = {"businessadmin"}) + @Test + void testCascadingDeleteOfAccessItems() + throws WorkbasketNotFoundException, NotAuthorizedException, InvalidArgumentException { + Workbasket wb = workbasketService.getWorkbasket("WBI:100000000000000000000000000000000008"); + String wbId = wb.getId(); + // create 2 access Items + WorkbasketAccessItem accessItem = workbasketService.newWorkbasketAccessItem(wbId, "teamlead_2"); + accessItem.setPermAppend(true); + accessItem.setPermRead(true); + accessItem.setPermOpen(true); + workbasketService.createWorkbasketAccessItem(accessItem); + accessItem = workbasketService.newWorkbasketAccessItem(wbId, "elena"); + accessItem.setPermAppend(true); + accessItem.setPermRead(true); + accessItem.setPermOpen(true); + workbasketService.createWorkbasketAccessItem(accessItem); + List accessItemsBefore = workbasketService.getWorkbasketAccessItems(wbId); + assertEquals(5, accessItemsBefore.size()); - @WithAccessId(userName = "teamlead_2", groupNames = {"businessadmin"}) - @Test - void testCascadingDeleteOfAccessItems() - throws WorkbasketNotFoundException, NotAuthorizedException, InvalidArgumentException { - Workbasket wb = workbasketService.getWorkbasket("WBI:100000000000000000000000000000000008"); - String wbId = wb.getId(); - // create 2 access Items - WorkbasketAccessItem accessItem = workbasketService.newWorkbasketAccessItem(wbId, "teamlead_2"); - accessItem.setPermAppend(true); - accessItem.setPermRead(true); - accessItem.setPermOpen(true); - workbasketService.createWorkbasketAccessItem(accessItem); - accessItem = workbasketService.newWorkbasketAccessItem(wbId, "elena"); - accessItem.setPermAppend(true); - accessItem.setPermRead(true); - accessItem.setPermOpen(true); - workbasketService.createWorkbasketAccessItem(accessItem); - List accessItemsBefore = workbasketService.getWorkbasketAccessItems(wbId); - assertEquals(5, accessItemsBefore.size()); + Assertions.assertThrows( + WorkbasketNotFoundException.class, + () -> { + workbasketService.deleteWorkbasket(wbId); + workbasketService.getWorkbasket("WBI:100000000000000000000000000000000008"); + }, + "There should be no result for a deleted Workbasket."); - Assertions.assertThrows(WorkbasketNotFoundException.class, () -> { - workbasketService.deleteWorkbasket(wbId); - workbasketService.getWorkbasket("WBI:100000000000000000000000000000000008"); - }, "There should be no result for a deleted Workbasket."); + List accessItemsAfter = workbasketService.getWorkbasketAccessItems(wbId); + assertEquals(0, accessItemsAfter.size()); + } - List accessItemsAfter = workbasketService.getWorkbasketAccessItems(wbId); - assertEquals(0, accessItemsAfter.size()); - } + @WithAccessId( + userName = "admin", + groupNames = {"businessadmin"}) + @Test + void testMarkWorkbasketForDeletion() + throws WorkbasketInUseException, NotAuthorizedException, WorkbasketNotFoundException, + InvalidArgumentException, InvalidOwnerException, InvalidStateException, + TaskNotFoundException { + Workbasket wb = workbasketService.getWorkbasket("WBI:100000000000000000000000000000000006"); + boolean markedForDeletion; - @WithAccessId(userName = "admin", groupNames = {"businessadmin"}) - @Test - void testMarkWorkbasketForDeletion() - throws WorkbasketInUseException, NotAuthorizedException, WorkbasketNotFoundException, InvalidArgumentException, - InvalidOwnerException, InvalidStateException, TaskNotFoundException { - Workbasket wb = workbasketService.getWorkbasket("WBI:100000000000000000000000000000000006"); - boolean markedForDeletion; + TaskImpl task = (TaskImpl) taskService.getTask("TKI:000000000000000000000000000000000000"); + taskService.forceCompleteTask(task.getId()); + task = (TaskImpl) taskService.getTask("TKI:000000000000000000000000000000000001"); + taskService.forceCompleteTask(task.getId()); + task = (TaskImpl) taskService.getTask("TKI:000000000000000000000000000000000002"); + taskService.forceCompleteTask(task.getId()); - TaskImpl task = (TaskImpl) taskService.getTask("TKI:000000000000000000000000000000000000"); - taskService.forceCompleteTask(task.getId()); - task = (TaskImpl) taskService.getTask("TKI:000000000000000000000000000000000001"); - taskService.forceCompleteTask(task.getId()); - task = (TaskImpl) taskService.getTask("TKI:000000000000000000000000000000000002"); - taskService.forceCompleteTask(task.getId()); - - markedForDeletion = workbasketService.deleteWorkbasket(wb.getId()); - assertFalse(markedForDeletion); - - wb = workbasketService.getWorkbasket(wb.getId()); - assertTrue(wb.isMarkedForDeletion()); - } + markedForDeletion = workbasketService.deleteWorkbasket(wb.getId()); + assertFalse(markedForDeletion); + wb = workbasketService.getWorkbasket(wb.getId()); + assertTrue(wb.isMarkedForDeletion()); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/workbasket/DistributionTargetsAccTest.java b/lib/taskana-core/src/test/java/acceptance/workbasket/DistributionTargetsAccTest.java index 4d84f6084..58be12696 100644 --- a/lib/taskana-core/src/test/java/acceptance/workbasket/DistributionTargetsAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/workbasket/DistributionTargetsAccTest.java @@ -3,18 +3,17 @@ package acceptance.workbasket; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import acceptance.AbstractAccTest; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.Workbasket; import pro.taskana.WorkbasketService; import pro.taskana.WorkbasketSummary; @@ -23,288 +22,304 @@ import pro.taskana.exceptions.WorkbasketNotFoundException; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "get workbasket" scenarios. - */ +/** Acceptance test for all "get workbasket" scenarios. */ @ExtendWith(JAASExtension.class) class DistributionTargetsAccTest extends AbstractAccTest { - DistributionTargetsAccTest() { - super(); + DistributionTargetsAccTest() { + super(); + } + + @WithAccessId( + userName = "user_1_1", + groupNames = {"teamlead_1"}) + @Test + void testGetDistributionTargetsSucceedsById() + throws NotAuthorizedException, WorkbasketNotFoundException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + WorkbasketSummary workbasketSummary = + workbasketService.createWorkbasketQuery().keyIn("GPK_KSC").single(); + + List retrievedDistributionTargets = + workbasketService.getDistributionTargets(workbasketSummary.getId()); + + assertEquals(4, retrievedDistributionTargets.size()); + List expectedTargetIds = + new ArrayList<>( + Arrays.asList( + "WBI:100000000000000000000000000000000002", + "WBI:100000000000000000000000000000000003", + "WBI:100000000000000000000000000000000004", + "WBI:100000000000000000000000000000000005")); + + for (WorkbasketSummary wbSummary : retrievedDistributionTargets) { + assertTrue(expectedTargetIds.contains(wbSummary.getId())); } + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"teamlead_1"}) - @Test - void testGetDistributionTargetsSucceedsById() throws NotAuthorizedException, WorkbasketNotFoundException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - WorkbasketSummary workbasketSummary = workbasketService.createWorkbasketQuery() - .keyIn("GPK_KSC") - .single(); + @WithAccessId( + userName = "user_1_1", + groupNames = {"teamlead_1"}) + @Test + void testGetDistributionTargetsSucceeds() + throws NotAuthorizedException, WorkbasketNotFoundException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + WorkbasketSummary workbasketSummary = + workbasketService.createWorkbasketQuery().keyIn("GPK_KSC").single(); - List retrievedDistributionTargets = workbasketService - .getDistributionTargets(workbasketSummary.getId()); + List retrievedDistributionTargets = + workbasketService.getDistributionTargets( + workbasketSummary.getKey(), workbasketSummary.getDomain()); - assertEquals(4, retrievedDistributionTargets.size()); - List expectedTargetIds = new ArrayList<>( - Arrays.asList("WBI:100000000000000000000000000000000002", "WBI:100000000000000000000000000000000003", - "WBI:100000000000000000000000000000000004", "WBI:100000000000000000000000000000000005")); - - for (WorkbasketSummary wbSummary : retrievedDistributionTargets) { - assertTrue(expectedTargetIds.contains(wbSummary.getId())); - } + assertEquals(4, retrievedDistributionTargets.size()); + List expectedTargetIds = + new ArrayList<>( + Arrays.asList( + "WBI:100000000000000000000000000000000002", + "WBI:100000000000000000000000000000000003", + "WBI:100000000000000000000000000000000004", + "WBI:100000000000000000000000000000000005")); + for (WorkbasketSummary wbSummary : retrievedDistributionTargets) { + assertTrue(expectedTargetIds.contains(wbSummary.getId())); } + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"teamlead_1"}) - @Test - void testGetDistributionTargetsSucceeds() throws NotAuthorizedException, WorkbasketNotFoundException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - WorkbasketSummary workbasketSummary = workbasketService.createWorkbasketQuery() - .keyIn("GPK_KSC") - .single(); + @WithAccessId( + userName = "user_1_1", + groupNames = {"teamlead_1", "group_1", "group_2", "businessadmin"}) + @Test + void testDistributionTargetCallsWithNonExistingWorkbaskets() + throws NotAuthorizedException, WorkbasketNotFoundException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + String existingWb = "WBI:100000000000000000000000000000000001"; + String nonExistingWb = "WBI:100000000000000000000000000000000xx1"; - List retrievedDistributionTargets = workbasketService - .getDistributionTargets(workbasketSummary.getKey(), workbasketSummary.getDomain()); + Assertions.assertThrows( + WorkbasketNotFoundException.class, + () -> workbasketService.getDistributionTargets("WBI:100000000000000000000000000000000xx1")); - assertEquals(4, retrievedDistributionTargets.size()); - List expectedTargetIds = new ArrayList<>( - Arrays.asList("WBI:100000000000000000000000000000000002", "WBI:100000000000000000000000000000000003", - "WBI:100000000000000000000000000000000004", "WBI:100000000000000000000000000000000005")); + Assertions.assertThrows( + WorkbasketNotFoundException.class, + () -> + workbasketService.setDistributionTargets( + existingWb, new ArrayList<>(Arrays.asList(nonExistingWb)))); - for (WorkbasketSummary wbSummary : retrievedDistributionTargets) { - assertTrue(expectedTargetIds.contains(wbSummary.getId())); - } + Assertions.assertThrows( + WorkbasketNotFoundException.class, + () -> workbasketService.addDistributionTarget(existingWb, nonExistingWb)); - } + int beforeCount = workbasketService.getDistributionTargets(existingWb).size(); + workbasketService.removeDistributionTarget(existingWb, nonExistingWb); + int afterCount = workbasketService.getDistributionTargets(existingWb).size(); - @WithAccessId( - userName = "user_1_1", - groupNames = {"teamlead_1", "group_1", "group_2", "businessadmin"}) - @Test - void testDistributionTargetCallsWithNonExistingWorkbaskets() - throws NotAuthorizedException, WorkbasketNotFoundException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - String existingWb = "WBI:100000000000000000000000000000000001"; - String nonExistingWb = "WBI:100000000000000000000000000000000xx1"; + assertEquals(afterCount, beforeCount); + } - Assertions.assertThrows(WorkbasketNotFoundException.class, () -> - workbasketService.getDistributionTargets("WBI:100000000000000000000000000000000xx1")); + @WithAccessId( + userName = "user_3_1", + groupNames = {"group_1"}) + @Test + void testDistributionTargetCallsFailWithNotAuthorizedException() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + String existingWb = "WBI:100000000000000000000000000000000001"; - Assertions.assertThrows(WorkbasketNotFoundException.class, () -> - workbasketService.setDistributionTargets(existingWb, new ArrayList<>( - Arrays.asList(nonExistingWb)))); + Assertions.assertThrows( + NotAuthorizedException.class, () -> workbasketService.getDistributionTargets(existingWb)); - Assertions.assertThrows(WorkbasketNotFoundException.class, () -> - workbasketService.addDistributionTarget(existingWb, nonExistingWb)); + Assertions.assertThrows( + NotAuthorizedException.class, + () -> + workbasketService.setDistributionTargets( + existingWb, Arrays.asList("WBI:100000000000000000000000000000000002"))); - int beforeCount = workbasketService.getDistributionTargets(existingWb).size(); - workbasketService.removeDistributionTarget(existingWb, nonExistingWb); - int afterCount = workbasketService.getDistributionTargets(existingWb).size(); + Assertions.assertThrows( + NotAuthorizedException.class, + () -> + workbasketService.addDistributionTarget( + existingWb, "WBI:100000000000000000000000000000000002")); - assertEquals(afterCount, beforeCount); + Assertions.assertThrows( + NotAuthorizedException.class, + () -> + workbasketService.removeDistributionTarget( + existingWb, "WBI:100000000000000000000000000000000002")); + } - } + @WithAccessId( + userName = "user_2_2", + groupNames = {"group_1", "group_2", "businessadmin"}) + @Test + void testAddAndRemoveDistributionTargets() + throws NotAuthorizedException, WorkbasketNotFoundException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + Workbasket workbasket = workbasketService.getWorkbasket("GPK_KSC_1", "DOMAIN_A"); - @WithAccessId( - userName = "user_3_1", groupNames = {"group_1"}) - @Test - void testDistributionTargetCallsFailWithNotAuthorizedException() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - String existingWb = "WBI:100000000000000000000000000000000001"; + List distributionTargets = + workbasketService.getDistributionTargets(workbasket.getId()); + assertEquals(4, distributionTargets.size()); - Assertions.assertThrows(NotAuthorizedException.class, () -> - workbasketService.getDistributionTargets(existingWb)); + // add a new distribution target + Workbasket newTarget = workbasketService.getWorkbasket("GPK_B_KSC_2", "DOMAIN_B"); + workbasketService.addDistributionTarget(workbasket.getId(), newTarget.getId()); - Assertions.assertThrows(NotAuthorizedException.class, () -> - workbasketService.setDistributionTargets(existingWb, - Arrays.asList("WBI:100000000000000000000000000000000002"))); + distributionTargets = workbasketService.getDistributionTargets(workbasket.getId()); + assertEquals(5, distributionTargets.size()); - Assertions.assertThrows(NotAuthorizedException.class, () -> - workbasketService.addDistributionTarget(existingWb, + // remove the new target + workbasketService.removeDistributionTarget(workbasket.getId(), newTarget.getId()); + distributionTargets = workbasketService.getDistributionTargets(workbasket.getId()); + assertEquals(4, distributionTargets.size()); + + // remove the new target again Question: should this throw an exception? + workbasketService.removeDistributionTarget(workbasket.getId(), newTarget.getId()); + distributionTargets = workbasketService.getDistributionTargets(workbasket.getId()); + assertEquals(4, distributionTargets.size()); + } + + @WithAccessId( + userName = "user_2_2", + groupNames = {"businessadmin"}) + @Test + void testAddAndRemoveDistributionTargetsOnWorkbasketWithoutReadPermission() + throws NotAuthorizedException, WorkbasketNotFoundException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + Workbasket workbasket = workbasketService.getWorkbasket("GPK_B_KSC_2", "DOMAIN_B"); + + List distributionTargets = + workbasketService.getDistributionTargets(workbasket.getId()); + assertEquals(0, distributionTargets.size()); + + // add a new distribution target + Workbasket newTarget = workbasketService.getWorkbasket("GPK_KSC_1", "DOMAIN_A"); + workbasketService.addDistributionTarget(workbasket.getId(), newTarget.getId()); + + distributionTargets = workbasketService.getDistributionTargets(workbasket.getId()); + assertEquals(1, distributionTargets.size()); + + // remove the new target + workbasketService.removeDistributionTarget(workbasket.getId(), newTarget.getId()); + distributionTargets = workbasketService.getDistributionTargets(workbasket.getId()); + assertEquals(0, distributionTargets.size()); + } + + @WithAccessId( + userName = "user_2_2", + groupNames = {"group_1", "group_2"}) + @Test + void testAddDistributionTargetsFailsNotAuthorized() + throws NotAuthorizedException, WorkbasketNotFoundException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + Workbasket workbasket = workbasketService.getWorkbasket("GPK_KSC_1", "DOMAIN_A"); + + List distributionTargets = + workbasketService.getDistributionTargets(workbasket.getId()); + assertEquals(4, distributionTargets.size()); + + // add a new distribution target + Workbasket newTarget = workbasketService.getWorkbasket("GPK_B_KSC_2", "DOMAIN_B"); + + Assertions.assertThrows( + NotAuthorizedException.class, + () -> workbasketService.addDistributionTarget(workbasket.getId(), newTarget.getId())); + } + + @WithAccessId( + userName = "user_2_2", + groupNames = {"group_1", "group_2", "businessadmin"}) + @Test + void testSetDistributionTargets() + throws NotAuthorizedException, WorkbasketNotFoundException, SQLException, IOException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + + Workbasket sourceWorkbasket = workbasketService.getWorkbasket("GPK_KSC_1", "DOMAIN_A"); + + List initialDistributionTargets = + workbasketService.getDistributionTargets(sourceWorkbasket.getId()); + assertEquals(4, initialDistributionTargets.size()); + + List newDistributionTargets = + workbasketService.createWorkbasketQuery().keyIn("USER_1_1", "GPK_B_KSC_1").list(); + assertEquals(2, newDistributionTargets.size()); + + List newDistributionTargetIds = + newDistributionTargets.stream().map(WorkbasketSummary::getId).collect(Collectors.toList()); + + workbasketService.setDistributionTargets(sourceWorkbasket.getId(), newDistributionTargetIds); + List changedTargets = + workbasketService.getDistributionTargets(sourceWorkbasket.getId()); + assertEquals(2, changedTargets.size()); + + // reset DB to original state + resetDb(false); + } + + @WithAccessId( + userName = "user_2_2", + groupNames = {"group_1", "group_2"}) + @Test + void testGetDistributionSourcesById() throws NotAuthorizedException, WorkbasketNotFoundException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + + List distributionSources = + workbasketService.getDistributionSources("WBI:100000000000000000000000000000000004"); + + assertEquals(2, distributionSources.size()); + List expectedIds = + new ArrayList<>( + Arrays.asList( + "WBI:100000000000000000000000000000000001", "WBI:100000000000000000000000000000000002")); - Assertions.assertThrows(NotAuthorizedException.class, () -> - workbasketService.removeDistributionTarget(existingWb, + for (WorkbasketSummary foundSummary : distributionSources) { + assertTrue(expectedIds.contains(foundSummary.getId())); + } + } + + @WithAccessId( + userName = "user_2_2", + groupNames = {"group_1", "group_2"}) + @Test + void testGetDistributionSourcesByKeyDomain() + throws NotAuthorizedException, WorkbasketNotFoundException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + + List distributionSources = + workbasketService.getDistributionSources("TEAMLEAD_1", "DOMAIN_A"); + + assertEquals(2, distributionSources.size()); + List expectedIds = + new ArrayList<>( + Arrays.asList( + "WBI:100000000000000000000000000000000001", "WBI:100000000000000000000000000000000002")); + for (WorkbasketSummary foundSummary : distributionSources) { + assertTrue(expectedIds.contains(foundSummary.getId())); } + } - @WithAccessId( - userName = "user_2_2", - groupNames = {"group_1", "group_2", "businessadmin"}) - @Test - void testAddAndRemoveDistributionTargets() - throws NotAuthorizedException, WorkbasketNotFoundException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - Workbasket workbasket = workbasketService.getWorkbasket("GPK_KSC_1", "DOMAIN_A"); + @WithAccessId( + userName = "henry", + groupNames = {"undefinedgroup"}) + @Test + void testQueryDistributionSourcesThrowsNotAuthorized() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List distributionTargets = workbasketService.getDistributionTargets(workbasket.getId()); - assertEquals(4, distributionTargets.size()); + Assertions.assertThrows( + NotAuthorizedException.class, + () -> workbasketService.getDistributionSources("WBI:100000000000000000000000000000000004")); + } - // add a new distribution target - Workbasket newTarget = workbasketService.getWorkbasket("GPK_B_KSC_2", "DOMAIN_B"); - workbasketService.addDistributionTarget(workbasket.getId(), newTarget.getId()); - - distributionTargets = workbasketService.getDistributionTargets(workbasket.getId()); - assertEquals(5, distributionTargets.size()); - - // remove the new target - workbasketService.removeDistributionTarget(workbasket.getId(), newTarget.getId()); - distributionTargets = workbasketService.getDistributionTargets(workbasket.getId()); - assertEquals(4, distributionTargets.size()); - - // remove the new target again Question: should this throw an exception? - workbasketService.removeDistributionTarget(workbasket.getId(), newTarget.getId()); - distributionTargets = workbasketService.getDistributionTargets(workbasket.getId()); - assertEquals(4, distributionTargets.size()); - - } - - @WithAccessId( - userName = "user_2_2", - groupNames = {"businessadmin"}) - @Test - void testAddAndRemoveDistributionTargetsOnWorkbasketWithoutReadPermission() - throws NotAuthorizedException, WorkbasketNotFoundException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - Workbasket workbasket = workbasketService.getWorkbasket("GPK_B_KSC_2", "DOMAIN_B"); - - List distributionTargets = workbasketService.getDistributionTargets(workbasket.getId()); - assertEquals(0, distributionTargets.size()); - - // add a new distribution target - Workbasket newTarget = workbasketService.getWorkbasket("GPK_KSC_1", "DOMAIN_A"); - workbasketService.addDistributionTarget(workbasket.getId(), newTarget.getId()); - - distributionTargets = workbasketService.getDistributionTargets(workbasket.getId()); - assertEquals(1, distributionTargets.size()); - - // remove the new target - workbasketService.removeDistributionTarget(workbasket.getId(), newTarget.getId()); - distributionTargets = workbasketService.getDistributionTargets(workbasket.getId()); - assertEquals(0, distributionTargets.size()); - - } - - @WithAccessId( - userName = "user_2_2", - groupNames = {"group_1", "group_2"}) - @Test - void testAddDistributionTargetsFailsNotAuthorized() - throws NotAuthorizedException, WorkbasketNotFoundException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - Workbasket workbasket = workbasketService.getWorkbasket("GPK_KSC_1", "DOMAIN_A"); - - List distributionTargets = workbasketService.getDistributionTargets(workbasket.getId()); - assertEquals(4, distributionTargets.size()); - - // add a new distribution target - Workbasket newTarget = workbasketService.getWorkbasket("GPK_B_KSC_2", "DOMAIN_B"); - - Assertions.assertThrows(NotAuthorizedException.class, () -> - workbasketService.addDistributionTarget(workbasket.getId(), newTarget.getId())); - - } - - @WithAccessId( - userName = "user_2_2", - groupNames = {"group_1", "group_2", "businessadmin"}) - @Test - void testSetDistributionTargets() - throws NotAuthorizedException, WorkbasketNotFoundException, SQLException, IOException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - - Workbasket sourceWorkbasket = workbasketService.getWorkbasket("GPK_KSC_1", "DOMAIN_A"); - - List initialDistributionTargets = workbasketService - .getDistributionTargets(sourceWorkbasket.getId()); - assertEquals(4, initialDistributionTargets.size()); - - List newDistributionTargets = workbasketService.createWorkbasketQuery() - .keyIn("USER_1_1", "GPK_B_KSC_1") - .list(); - assertEquals(2, newDistributionTargets.size()); - - List newDistributionTargetIds = newDistributionTargets.stream() - .map(WorkbasketSummary::getId) - .collect(Collectors.toList()); - - workbasketService.setDistributionTargets(sourceWorkbasket.getId(), newDistributionTargetIds); - List changedTargets = workbasketService.getDistributionTargets(sourceWorkbasket.getId()); - assertEquals(2, changedTargets.size()); - - // reset DB to original state - resetDb(false); - - } - - @WithAccessId( - userName = "user_2_2", - groupNames = {"group_1", "group_2"}) - @Test - void testGetDistributionSourcesById() - throws NotAuthorizedException, WorkbasketNotFoundException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - - List distributionSources = workbasketService - .getDistributionSources("WBI:100000000000000000000000000000000004"); - - assertEquals(2, distributionSources.size()); - List expectedIds = new ArrayList<>( - Arrays.asList("WBI:100000000000000000000000000000000001", "WBI:100000000000000000000000000000000002")); - - for (WorkbasketSummary foundSummary : distributionSources) { - assertTrue(expectedIds.contains(foundSummary.getId())); - } - - } - - @WithAccessId( - userName = "user_2_2", - groupNames = {"group_1", "group_2"}) - @Test - void testGetDistributionSourcesByKeyDomain() - throws NotAuthorizedException, WorkbasketNotFoundException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - - List distributionSources = workbasketService - .getDistributionSources("TEAMLEAD_1", "DOMAIN_A"); - - assertEquals(2, distributionSources.size()); - List expectedIds = new ArrayList<>( - Arrays.asList("WBI:100000000000000000000000000000000001", "WBI:100000000000000000000000000000000002")); - - for (WorkbasketSummary foundSummary : distributionSources) { - assertTrue(expectedIds.contains(foundSummary.getId())); - } - } - - @WithAccessId( - userName = "henry", - groupNames = {"undefinedgroup"}) - @Test - void testQueryDistributionSourcesThrowsNotAuthorized() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - - Assertions.assertThrows(NotAuthorizedException.class, () -> - workbasketService - .getDistributionSources("WBI:100000000000000000000000000000000004")); - - } - - @WithAccessId( - userName = "user_2_2", - groupNames = {"group_1", "group_2"}) - @Test - void testQueryDistributionSourcesThrowsWorkbasketNotFound() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - - Assertions.assertThrows(WorkbasketNotFoundException.class, () -> workbasketService - .getDistributionSources("WBI:10dasgibtsdochnicht00000000000000004")); - } + @WithAccessId( + userName = "user_2_2", + groupNames = {"group_1", "group_2"}) + @Test + void testQueryDistributionSourcesThrowsWorkbasketNotFound() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + Assertions.assertThrows( + WorkbasketNotFoundException.class, + () -> workbasketService.getDistributionSources("WBI:10dasgibtsdochnicht00000000000000004")); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/workbasket/GetWorkbasketAccTest.java b/lib/taskana-core/src/test/java/acceptance/workbasket/GetWorkbasketAccTest.java index 7e8c5deaa..30de59042 100644 --- a/lib/taskana-core/src/test/java/acceptance/workbasket/GetWorkbasketAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/workbasket/GetWorkbasketAccTest.java @@ -3,13 +3,12 @@ package acceptance.workbasket; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import acceptance.AbstractAccTest; import java.util.List; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.Workbasket; import pro.taskana.WorkbasketPermission; import pro.taskana.WorkbasketService; @@ -20,160 +19,159 @@ import pro.taskana.exceptions.WorkbasketNotFoundException; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "get workbasket" scenarios. - */ +/** Acceptance test for all "get workbasket" scenarios. */ @ExtendWith(JAASExtension.class) class GetWorkbasketAccTest extends AbstractAccTest { - GetWorkbasketAccTest() { - super(); - } + GetWorkbasketAccTest() { + super(); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testGetWorkbasketById() - throws NotAuthorizedException, WorkbasketNotFoundException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testGetWorkbasketById() throws NotAuthorizedException, WorkbasketNotFoundException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - Workbasket workbasket = workbasketService.getWorkbasket("WBI:100000000000000000000000000000000007"); + Workbasket workbasket = + workbasketService.getWorkbasket("WBI:100000000000000000000000000000000007"); - assertEquals("DOMAIN_A", workbasket.getDomain()); - assertEquals("PPK User 2 KSC 1", workbasket.getDescription()); - assertEquals("PPK User 2 KSC 1", workbasket.getName()); - assertEquals("USER_1_2", workbasket.getKey()); - assertEquals(WorkbasketType.PERSONAL, workbasket.getType()); - assertEquals("Peter Maier", workbasket.getOwner()); - assertEquals("versicherung", workbasket.getOrgLevel1()); - assertEquals("abteilung", workbasket.getOrgLevel2()); - assertEquals("projekt", workbasket.getOrgLevel3()); - assertEquals("team", workbasket.getOrgLevel4()); - assertEquals("custom1", workbasket.getCustom1()); - assertEquals("custom2", workbasket.getCustom2()); - assertEquals("custom3", workbasket.getCustom3()); - assertEquals("custom4", workbasket.getCustom4()); - } + assertEquals("DOMAIN_A", workbasket.getDomain()); + assertEquals("PPK User 2 KSC 1", workbasket.getDescription()); + assertEquals("PPK User 2 KSC 1", workbasket.getName()); + assertEquals("USER_1_2", workbasket.getKey()); + assertEquals(WorkbasketType.PERSONAL, workbasket.getType()); + assertEquals("Peter Maier", workbasket.getOwner()); + assertEquals("versicherung", workbasket.getOrgLevel1()); + assertEquals("abteilung", workbasket.getOrgLevel2()); + assertEquals("projekt", workbasket.getOrgLevel3()); + assertEquals("team", workbasket.getOrgLevel4()); + assertEquals("custom1", workbasket.getCustom1()); + assertEquals("custom2", workbasket.getCustom2()); + assertEquals("custom3", workbasket.getCustom3()); + assertEquals("custom4", workbasket.getCustom4()); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testGetWorkbasketByKeyAndDomain() - throws NotAuthorizedException, WorkbasketNotFoundException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testGetWorkbasketByKeyAndDomain() + throws NotAuthorizedException, WorkbasketNotFoundException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - Workbasket workbasket = workbasketService.getWorkbasket("USER_1_2", "DOMAIN_A"); + Workbasket workbasket = workbasketService.getWorkbasket("USER_1_2", "DOMAIN_A"); - assertEquals("WBI:100000000000000000000000000000000007", workbasket.getId()); - assertEquals("PPK User 2 KSC 1", workbasket.getDescription()); - assertEquals("PPK User 2 KSC 1", workbasket.getName()); - assertEquals(WorkbasketType.PERSONAL, workbasket.getType()); - assertEquals("Peter Maier", workbasket.getOwner()); - assertEquals("versicherung", workbasket.getOrgLevel1()); - assertEquals("abteilung", workbasket.getOrgLevel2()); - assertEquals("projekt", workbasket.getOrgLevel3()); - assertEquals("team", workbasket.getOrgLevel4()); - assertEquals("custom1", workbasket.getCustom1()); - assertEquals("custom2", workbasket.getCustom2()); - assertEquals("custom3", workbasket.getCustom3()); - assertEquals("custom4", workbasket.getCustom4()); - } + assertEquals("WBI:100000000000000000000000000000000007", workbasket.getId()); + assertEquals("PPK User 2 KSC 1", workbasket.getDescription()); + assertEquals("PPK User 2 KSC 1", workbasket.getName()); + assertEquals(WorkbasketType.PERSONAL, workbasket.getType()); + assertEquals("Peter Maier", workbasket.getOwner()); + assertEquals("versicherung", workbasket.getOrgLevel1()); + assertEquals("abteilung", workbasket.getOrgLevel2()); + assertEquals("projekt", workbasket.getOrgLevel3()); + assertEquals("team", workbasket.getOrgLevel4()); + assertEquals("custom1", workbasket.getCustom1()); + assertEquals("custom2", workbasket.getCustom2()); + assertEquals("custom3", workbasket.getCustom3()); + assertEquals("custom4", workbasket.getCustom4()); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testGetWorkbasketPermissions() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List permissions = workbasketService - .getPermissionsForWorkbasket("WBI:100000000000000000000000000000000007"); + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testGetWorkbasketPermissions() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List permissions = + workbasketService.getPermissionsForWorkbasket("WBI:100000000000000000000000000000000007"); - assertEquals(4, permissions.size()); - assertTrue(permissions.contains(WorkbasketPermission.READ)); - assertTrue(permissions.contains(WorkbasketPermission.OPEN)); - assertTrue(permissions.contains(WorkbasketPermission.TRANSFER)); - assertTrue(permissions.contains(WorkbasketPermission.APPEND)); - } + assertEquals(4, permissions.size()); + assertTrue(permissions.contains(WorkbasketPermission.READ)); + assertTrue(permissions.contains(WorkbasketPermission.OPEN)); + assertTrue(permissions.contains(WorkbasketPermission.TRANSFER)); + assertTrue(permissions.contains(WorkbasketPermission.APPEND)); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testGetWorkbasketPermissionsForInvalidWorkbasketId() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List permissions = workbasketService - .getPermissionsForWorkbasket("WBI:invalid"); + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testGetWorkbasketPermissionsForInvalidWorkbasketId() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List permissions = + workbasketService.getPermissionsForWorkbasket("WBI:invalid"); - assertEquals(0, permissions.size()); - } + assertEquals(0, permissions.size()); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testGetWorkbasketAsSummary() - throws NotAuthorizedException, WorkbasketNotFoundException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testGetWorkbasketAsSummary() throws NotAuthorizedException, WorkbasketNotFoundException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - WorkbasketSummary workbasketSummary = workbasketService - .getWorkbasket("WBI:100000000000000000000000000000000007").asSummary(); + WorkbasketSummary workbasketSummary = + workbasketService.getWorkbasket("WBI:100000000000000000000000000000000007").asSummary(); - assertEquals("DOMAIN_A", workbasketSummary.getDomain()); - assertEquals("PPK User 2 KSC 1", workbasketSummary.getDescription()); - assertEquals("PPK User 2 KSC 1", workbasketSummary.getName()); - assertEquals("USER_1_2", workbasketSummary.getKey()); - assertEquals(WorkbasketType.PERSONAL, workbasketSummary.getType()); - assertEquals("Peter Maier", workbasketSummary.getOwner()); - assertEquals("versicherung", workbasketSummary.getOrgLevel1()); - assertEquals("abteilung", workbasketSummary.getOrgLevel2()); - assertEquals("projekt", workbasketSummary.getOrgLevel3()); - assertEquals("team", workbasketSummary.getOrgLevel4()); - assertEquals("custom1", workbasketSummary.getCustom1()); - assertEquals("custom2", workbasketSummary.getCustom2()); - assertEquals("custom3", workbasketSummary.getCustom3()); - assertEquals("custom4", workbasketSummary.getCustom4()); - assertEquals(false, workbasketSummary.isMarkedForDeletion()); - } + assertEquals("DOMAIN_A", workbasketSummary.getDomain()); + assertEquals("PPK User 2 KSC 1", workbasketSummary.getDescription()); + assertEquals("PPK User 2 KSC 1", workbasketSummary.getName()); + assertEquals("USER_1_2", workbasketSummary.getKey()); + assertEquals(WorkbasketType.PERSONAL, workbasketSummary.getType()); + assertEquals("Peter Maier", workbasketSummary.getOwner()); + assertEquals("versicherung", workbasketSummary.getOrgLevel1()); + assertEquals("abteilung", workbasketSummary.getOrgLevel2()); + assertEquals("projekt", workbasketSummary.getOrgLevel3()); + assertEquals("team", workbasketSummary.getOrgLevel4()); + assertEquals("custom1", workbasketSummary.getCustom1()); + assertEquals("custom2", workbasketSummary.getCustom2()); + assertEquals("custom3", workbasketSummary.getCustom3()); + assertEquals("custom4", workbasketSummary.getCustom4()); + assertEquals(false, workbasketSummary.isMarkedForDeletion()); + } - @Test - void testThrowsExceptionIfIdIsInvalid() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - Assertions.assertThrows(WorkbasketNotFoundException.class, () -> - workbasketService.getWorkbasket("INVALID_ID")); - } + @Test + void testThrowsExceptionIfIdIsInvalid() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + Assertions.assertThrows( + WorkbasketNotFoundException.class, () -> workbasketService.getWorkbasket("INVALID_ID")); + } - @Test - void testThrowsExceptionIfKeyOrDomainIsInvalid() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + @Test + void testThrowsExceptionIfKeyOrDomainIsInvalid() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - Assertions.assertThrows(WorkbasketNotFoundException.class, () -> - workbasketService.getWorkbasket("INVALID_KEY", "INVALID_DOMAIN")); - } + Assertions.assertThrows( + WorkbasketNotFoundException.class, + () -> workbasketService.getWorkbasket("INVALID_KEY", "INVALID_DOMAIN")); + } - @Test - void testGetByIdNotAuthorized() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - Assertions.assertThrows(NotAuthorizedException.class, () -> - workbasketService.getWorkbasket("WBI:100000000000000000000000000000000001")); - } + @Test + void testGetByIdNotAuthorized() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + Assertions.assertThrows( + NotAuthorizedException.class, + () -> workbasketService.getWorkbasket("WBI:100000000000000000000000000000000001")); + } - @Test - void testGetByKeyDomainNotAuthorized() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - Assertions.assertThrows(NotAuthorizedException.class, () -> - workbasketService.getWorkbasket("GPK_KSC", "DOMAIN_A")); - } - - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testGetWorkbasketByIdNotExisting() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - Assertions.assertThrows(WorkbasketNotFoundException.class, () -> - workbasketService.getWorkbasket("NOT EXISTING ID")); - } + @Test + void testGetByKeyDomainNotAuthorized() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + Assertions.assertThrows( + NotAuthorizedException.class, () -> workbasketService.getWorkbasket("GPK_KSC", "DOMAIN_A")); + } + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testGetWorkbasketByIdNotExisting() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + Assertions.assertThrows( + WorkbasketNotFoundException.class, + () -> workbasketService.getWorkbasket("NOT EXISTING ID")); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/workbasket/QueryWorkbasketAccTest.java b/lib/taskana-core/src/test/java/acceptance/workbasket/QueryWorkbasketAccTest.java index c4105abc3..474dbf52e 100644 --- a/lib/taskana-core/src/test/java/acceptance/workbasket/QueryWorkbasketAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/workbasket/QueryWorkbasketAccTest.java @@ -5,14 +5,13 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static pro.taskana.WorkbasketQueryColumnName.NAME; +import acceptance.AbstractAccTest; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.BaseQuery.SortDirection; import pro.taskana.WorkbasketPermission; import pro.taskana.WorkbasketQuery; @@ -24,705 +23,644 @@ import pro.taskana.exceptions.NotAuthorizedException; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "query workbasket by permission" scenarios. - */ +/** Acceptance test for all "query workbasket by permission" scenarios. */ @ExtendWith(JAASExtension.class) class QueryWorkbasketAccTest extends AbstractAccTest { - private static SortDirection asc = SortDirection.ASCENDING; - private static SortDirection desc = SortDirection.DESCENDING; + private static SortDirection asc = SortDirection.ASCENDING; + private static SortDirection desc = SortDirection.DESCENDING; - QueryWorkbasketAccTest() { - super(); - } + QueryWorkbasketAccTest() { + super(); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1_1"}) - @Test - void testQueryAllForUserMultipleTimes() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - WorkbasketQuery query = workbasketService.createWorkbasketQuery(); - long count = query.count(); - assertEquals(4, count); - List workbaskets = query.list(); - assertNotNull(workbaskets); - assertEquals(count, workbaskets.size()); - workbaskets = query.list(); - assertNotNull(workbaskets); - assertEquals(count, workbaskets.size()); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1_1"}) + @Test + void testQueryAllForUserMultipleTimes() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + WorkbasketQuery query = workbasketService.createWorkbasketQuery(); + long count = query.count(); + assertEquals(4, count); + List workbaskets = query.list(); + assertNotNull(workbaskets); + assertEquals(count, workbaskets.size()); + workbaskets = query.list(); + assertNotNull(workbaskets); + assertEquals(count, workbaskets.size()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"businessadmin"}) - @Test - void testQueryAllForBusinessAdminMultipleTimes() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - WorkbasketQuery query = workbasketService.createWorkbasketQuery(); - long count = query.count(); - assertEquals(25, count); - List workbaskets = query.list(); - assertNotNull(workbaskets); - assertEquals(count, workbaskets.size()); - workbaskets = query.list(); - assertNotNull(workbaskets); - assertEquals(count, workbaskets.size()); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"businessadmin"}) + @Test + void testQueryAllForBusinessAdminMultipleTimes() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + WorkbasketQuery query = workbasketService.createWorkbasketQuery(); + long count = query.count(); + assertEquals(25, count); + List workbaskets = query.list(); + assertNotNull(workbaskets); + assertEquals(count, workbaskets.size()); + workbaskets = query.list(); + assertNotNull(workbaskets); + assertEquals(count, workbaskets.size()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"admin"}) - @Test - void testQueryAllForAdminMultipleTimes() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - WorkbasketQuery query = workbasketService.createWorkbasketQuery(); - long count = query.count(); - assertEquals(25, count); - List workbaskets = query.list(); - assertNotNull(workbaskets); - assertEquals(count, workbaskets.size()); - workbaskets = query.list(); - assertNotNull(workbaskets); - assertEquals(count, workbaskets.size()); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"admin"}) + @Test + void testQueryAllForAdminMultipleTimes() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + WorkbasketQuery query = workbasketService.createWorkbasketQuery(); + long count = query.count(); + assertEquals(25, count); + List workbaskets = query.list(); + assertNotNull(workbaskets); + assertEquals(count, workbaskets.size()); + workbaskets = query.list(); + assertNotNull(workbaskets); + assertEquals(count, workbaskets.size()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryWorkbasketValuesForColumnName() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List columnValueList = workbasketService.createWorkbasketQuery() - .listValues(NAME, null); - assertNotNull(columnValueList); - assertEquals(10, columnValueList.size()); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryWorkbasketValuesForColumnName() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List columnValueList = workbasketService.createWorkbasketQuery().listValues(NAME, null); + assertNotNull(columnValueList); + assertEquals(10, columnValueList.size()); - columnValueList = workbasketService.createWorkbasketQuery() + columnValueList = + workbasketService + .createWorkbasketQuery() .nameLike("%korb%") .orderByName(asc) - .listValues(NAME, SortDirection.DESCENDING); // will override - assertNotNull(columnValueList); - assertEquals(4, columnValueList.size()); - } + .listValues(NAME, SortDirection.DESCENDING); // will override + assertNotNull(columnValueList); + assertEquals(4, columnValueList.size()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryWorkbasketByDomain() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .domainIn("DOMAIN_B") - .list(); - assertEquals(1L, results.size()); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryWorkbasketByDomain() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().domainIn("DOMAIN_B").list(); + assertEquals(1L, results.size()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryWorkbasketByDomainAndType() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryWorkbasketByDomainAndType() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService + .createWorkbasketQuery() .domainIn("DOMAIN_A") .typeIn(WorkbasketType.PERSONAL) .list(); - assertEquals(6L, results.size()); - } + assertEquals(6L, results.size()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryWorkbasketByName() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .nameIn("Gruppenpostkorb KSC") - .list(); - assertEquals(1L, results.size()); - assertEquals("GPK_KSC", results.get(0).getKey()); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryWorkbasketByName() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().nameIn("Gruppenpostkorb KSC").list(); + assertEquals(1L, results.size()); + assertEquals("GPK_KSC", results.get(0).getKey()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryWorkbasketByNameStartsWith() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .nameLike("%Gruppenpostkorb KSC%") - .list(); - assertEquals(3L, results.size()); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryWorkbasketByNameStartsWith() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().nameLike("%Gruppenpostkorb KSC%").list(); + assertEquals(3L, results.size()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryWorkbasketByNameContains() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryWorkbasketByNameContains() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService + .createWorkbasketQuery() .nameLike("%Teamlead%", "%Gruppenpostkorb KSC%") .list(); - assertEquals(5L, results.size()); - } + assertEquals(5L, results.size()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryWorkbasketByNameContainsCaseInsensitive() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .nameLike("%TEAMLEAD%") - .list(); - assertEquals(2L, results.size()); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryWorkbasketByNameContainsCaseInsensitive() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().nameLike("%TEAMLEAD%").list(); + assertEquals(2L, results.size()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryWorkbasketByDescription() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryWorkbasketByDescription() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService + .createWorkbasketQuery() .descriptionLike("%ppk%", "%gruppen%") .orderByType(desc) .orderByDescription(asc) .list(); - assertEquals(9L, results.size()); - } + assertEquals(9L, results.size()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryWorkbasketByOwnerLike() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryWorkbasketByOwnerLike() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService + .createWorkbasketQuery() .ownerLike("%an%", "%te%") .orderByOwner(asc) .list(); - assertEquals(1L, results.size()); - } + assertEquals(1L, results.size()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryWorkbasketByKey() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .keyIn("GPK_KSC") - .list(); - assertEquals(1L, results.size()); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryWorkbasketByKey() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().keyIn("GPK_KSC").list(); + assertEquals(1L, results.size()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryWorkbasketByMultipleKeys() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .keyIn("GPK_KSC_1", "GPK_KSC") - .list(); - assertEquals(2L, results.size()); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryWorkbasketByMultipleKeys() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().keyIn("GPK_KSC_1", "GPK_KSC").list(); + assertEquals(2L, results.size()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryWorkbasketByMultipleKeysWithUnknownKey() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .keyIn("GPK_KSC_1", "GPK_Ksc", "GPK_KSC_3") - .list(); - assertEquals(2L, results.size()); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryWorkbasketByMultipleKeysWithUnknownKey() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().keyIn("GPK_KSC_1", "GPK_Ksc", "GPK_KSC_3").list(); + assertEquals(2L, results.size()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryWorkbasketByKeyContains() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .keyLike("%KSC%") - .list(); - assertEquals(3L, results.size()); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryWorkbasketByKeyContains() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().keyLike("%KSC%").list(); + assertEquals(3L, results.size()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryWorkbasketByKeyContainsIgnoreCase() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .keyLike("%kSc%") - .list(); - assertEquals(3L, results.size()); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryWorkbasketByKeyContainsIgnoreCase() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().keyLike("%kSc%").list(); + assertEquals(3L, results.size()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryWorkbasketByKeyOrNameContainsIgnoreCase() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .keyOrNameLike("%kSc%") - .list(); - assertEquals(9L, results.size()); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryWorkbasketByKeyOrNameContainsIgnoreCase() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().keyOrNameLike("%kSc%").list(); + assertEquals(9L, results.size()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryWorkbasketByNameStartsWithSortedByNameAscending() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryWorkbasketByNameStartsWithSortedByNameAscending() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService + .createWorkbasketQuery() .nameLike("%Gruppenpostkorb KSC%") .orderByName(asc) .list(); - assertEquals(3L, results.size()); - assertEquals("GPK_KSC", results.get(0).getKey()); + assertEquals(3L, results.size()); + assertEquals("GPK_KSC", results.get(0).getKey()); - // check sort order is correct - WorkbasketSummary previousSummary = null; - for (WorkbasketSummary wbSummary : results) { - if (previousSummary != null) { - assertTrue(wbSummary.getName().compareToIgnoreCase( - previousSummary.getName()) >= 0); - } - previousSummary = wbSummary; - } + // check sort order is correct + WorkbasketSummary previousSummary = null; + for (WorkbasketSummary wbSummary : results) { + if (previousSummary != null) { + assertTrue(wbSummary.getName().compareToIgnoreCase(previousSummary.getName()) >= 0); + } + previousSummary = wbSummary; + } + } + @WithAccessId(userName = "max") + @Test + void testQueryWorkbasketByNameStartsWithSortedByNameDescending() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().nameLike("basxet%").orderByName(desc).list(); + assertEquals(10L, results.size()); + // check sort order is correct + WorkbasketSummary previousSummary = null; + for (WorkbasketSummary wbSummary : results) { + if (previousSummary != null) { + assertTrue(wbSummary.getName().compareToIgnoreCase(previousSummary.getName()) <= 0); + } + previousSummary = wbSummary; + } + } + + @WithAccessId(userName = "max") + @Test + void testQueryWorkbasketByNameStartsWithSortedByKeyAscending() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().nameLike("basxet%").orderByKey(asc).list(); + assertEquals(10L, results.size()); + // check sort order is correct + WorkbasketSummary previousSummary = null; + for (WorkbasketSummary wbSummary : results) { + if (previousSummary != null) { + assertTrue(wbSummary.getKey().compareToIgnoreCase(previousSummary.getKey()) >= 0); + } + previousSummary = wbSummary; + } + } + + @WithAccessId(userName = "max") + @Test + void testQueryWorkbasketByNameStartsWithSortedByKeyDescending() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().nameLike("basxet%").orderByKey(desc).list(); + assertEquals(10L, results.size()); + // check sort order is correct + WorkbasketSummary previousSummary = null; + for (WorkbasketSummary wbSummary : results) { + if (previousSummary != null) { + assertTrue(wbSummary.getKey().compareToIgnoreCase(previousSummary.getKey()) <= 0); + } + previousSummary = wbSummary; + } + } + + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryWorkbasketByCreated() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().createdWithin(todaysInterval()).list(); + assertEquals(9L, results.size()); + } + + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryWorkbasketByModified() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().modifiedWithin(todaysInterval()).list(); + assertEquals(9L, results.size()); + } + + @WithAccessId(userName = "unknown", groupNames = "admin") + @Test + void testQueryWorkbasketByAdmin() throws NotAuthorizedException, InvalidArgumentException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().nameLike("%").orderByName(desc).list(); + assertEquals(25L, results.size()); + // check sort order is correct + WorkbasketSummary previousSummary = null; + for (WorkbasketSummary wbSummary : results) { + if (previousSummary != null) { + assertTrue(wbSummary.getName().compareToIgnoreCase(previousSummary.getName()) <= 0); + } + previousSummary = wbSummary; } - @WithAccessId( - userName = "max") - @Test - void testQueryWorkbasketByNameStartsWithSortedByNameDescending() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .nameLike("basxet%") - .orderByName(desc) - .list(); - assertEquals(10L, results.size()); - // check sort order is correct - WorkbasketSummary previousSummary = null; - for (WorkbasketSummary wbSummary : results) { - if (previousSummary != null) { - assertTrue(wbSummary.getName().compareToIgnoreCase( - previousSummary.getName()) <= 0); - } - previousSummary = wbSummary; - } - } - - @WithAccessId( - userName = "max") - @Test - void testQueryWorkbasketByNameStartsWithSortedByKeyAscending() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .nameLike("basxet%") - .orderByKey(asc) - .list(); - assertEquals(10L, results.size()); - // check sort order is correct - WorkbasketSummary previousSummary = null; - for (WorkbasketSummary wbSummary : results) { - if (previousSummary != null) { - assertTrue(wbSummary.getKey().compareToIgnoreCase( - previousSummary.getKey()) >= 0); - } - previousSummary = wbSummary; - } - } - - @WithAccessId( - userName = "max") - @Test - void testQueryWorkbasketByNameStartsWithSortedByKeyDescending() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .nameLike("basxet%") - .orderByKey(desc) - .list(); - assertEquals(10L, results.size()); - // check sort order is correct - WorkbasketSummary previousSummary = null; - for (WorkbasketSummary wbSummary : results) { - if (previousSummary != null) { - assertTrue(wbSummary.getKey().compareToIgnoreCase( - previousSummary.getKey()) <= 0); - } - previousSummary = wbSummary; - } - } - - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryWorkbasketByCreated() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .createdWithin(todaysInterval()) - .list(); - assertEquals(9L, results.size()); - } - - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryWorkbasketByModified() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .modifiedWithin(todaysInterval()) - .list(); - assertEquals(9L, results.size()); - } - - @WithAccessId( - userName = "unknown", - groupNames = "admin") - @Test - void testQueryWorkbasketByAdmin() - throws NotAuthorizedException, InvalidArgumentException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() + results = + workbasketService + .createWorkbasketQuery() .nameLike("%") - .orderByName(desc) - .list(); - assertEquals(25L, results.size()); - // check sort order is correct - WorkbasketSummary previousSummary = null; - for (WorkbasketSummary wbSummary : results) { - if (previousSummary != null) { - assertTrue(wbSummary.getName().compareToIgnoreCase( - previousSummary.getName()) <= 0); - } - previousSummary = wbSummary; - } - - results = workbasketService.createWorkbasketQuery() - .nameLike("%") - .accessIdsHavePermission(WorkbasketPermission.TRANSFER, "teamlead_1", "group_1", "group_2") + .accessIdsHavePermission( + WorkbasketPermission.TRANSFER, "teamlead_1", "group_1", "group_2") .orderByName(desc) .list(); - assertEquals(13L, results.size()); + assertEquals(13L, results.size()); + } + @WithAccessId(userName = "teamlead_1", groupNames = "group_1") + @Test + void testQueryWorkbasketByDomainLike() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().domainLike("DOMAIN_%").orderByDomain(asc).list(); + + ArrayList expectedIds = + new ArrayList<>( + Arrays.asList( + "WBI:100000000000000000000000000000000001", + "WBI:100000000000000000000000000000000002", + "WBI:100000000000000000000000000000000004", + "WBI:100000000000000000000000000000000005", + "WBI:100000000000000000000000000000000006", + "WBI:100000000000000000000000000000000007", + "WBI:100000000000000000000000000000000008", + "WBI:100000000000000000000000000000000009", + "WBI:100000000000000000000000000000000010", + "WBI:100000000000000000000000000000000012")); + assertEquals(10L, results.size()); + for (String id : expectedIds) { + assertTrue(results.stream().anyMatch(wbSummary -> wbSummary.getId().equals(id))); } + } - @WithAccessId( - userName = "teamlead_1", - groupNames = "group_1") - @Test - void testQueryWorkbasketByDomainLike() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .domainLike("DOMAIN_%").orderByDomain(asc).list(); + @WithAccessId(userName = "admin", groupNames = "group_1") + @Test + void testQueryWorkbasketByOwnerInOrderByDomainDesc() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().ownerIn("owner0815").orderByDomain(desc).list(); - ArrayList expectedIds = new ArrayList<>( - Arrays.asList("WBI:100000000000000000000000000000000001", "WBI:100000000000000000000000000000000002", - "WBI:100000000000000000000000000000000004", "WBI:100000000000000000000000000000000005", - "WBI:100000000000000000000000000000000006", "WBI:100000000000000000000000000000000007", - "WBI:100000000000000000000000000000000008", "WBI:100000000000000000000000000000000009", - "WBI:100000000000000000000000000000000010", "WBI:100000000000000000000000000000000012")); - assertEquals(10L, results.size()); - for (String id : expectedIds) { - assertTrue(results.stream().anyMatch(wbSummary -> wbSummary.getId().equals(id))); - } - } + assertEquals(2L, results.size()); + assertEquals("WBI:100000000000000000000000000000000015", results.get(0).getId()); + assertEquals("WBI:100000000000000000000000000000000001", results.get(1).getId()); + } - @WithAccessId( - userName = "admin", - groupNames = "group_1") - @Test - void testQueryWorkbasketByOwnerInOrderByDomainDesc() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .ownerIn("owner0815").orderByDomain(desc).list(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testQueryForCustom1In() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().custom1In("ABCQVW").list(); - assertEquals(2L, results.size()); - assertEquals("WBI:100000000000000000000000000000000015", results.get(0).getId()); - assertEquals("WBI:100000000000000000000000000000000001", results.get(1).getId()); - } + assertEquals(1, results.size()); + assertEquals("WBI:100000000000000000000000000000000001", results.get(0).getId()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testQueryForCustom1In() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .custom1In("ABCQVW").list(); + @WithAccessId(userName = "admin") + @Test + void testQueryForCustom1Like() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().custom1Like("custo%").list(); + assertEquals(2, results.size()); + } - assertEquals(1, results.size()); - assertEquals("WBI:100000000000000000000000000000000001", results.get(0).getId()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForCustom2In() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().custom2In("cust2", "custom2").list(); + assertEquals(3, results.size()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForCustom1Like() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .custom1Like("custo%") - .list(); - assertEquals(2, results.size()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForCustom2Like() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().custom2Like("cusTo%").list(); + assertEquals(3, results.size()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForCustom2In() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .custom2In("cust2", "custom2") - .list(); - assertEquals(3, results.size()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForCustom3In() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().custom3In("custom3").list(); + assertEquals(2, results.size()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForCustom2Like() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .custom2Like("cusTo%") - .list(); - assertEquals(3, results.size()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForCustom3Like() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().custom3Like("cu%").list(); + assertEquals(3, results.size()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForCustom3In() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .custom3In("custom3") - .list(); - assertEquals(2, results.size()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForCustom4In() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().custom4In("custom4", "team").list(); + assertEquals(3, results.size()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForCustom3Like() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .custom3Like("cu%") - .list(); - assertEquals(3, results.size()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForCustom4Like() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().custom4Like("%u%").list(); + assertEquals(5, results.size()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForCustom4In() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .custom4In("custom4", "team") - .list(); - assertEquals(3, results.size()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForOrgLevl1In() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().orgLevel1In("orgl1", "").list(); + assertEquals(24, results.size()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForCustom4Like() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .custom4Like("%u%") - .list(); - assertEquals(5, results.size()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForOrgLevel1Like() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().orgLevel1Like("%1").list(); + assertEquals(2, results.size()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrgLevl1In() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .orgLevel1In("orgl1", "") - .list(); - assertEquals(24, results.size()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForOrgLevel2In() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().orgLevel2In("abteilung").list(); + assertEquals(1, results.size()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrgLevel1Like() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .orgLevel1Like("%1") - .list(); - assertEquals(2, results.size()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForOrgLevel2Like() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().orgLevel2Like("ab%").list(); + assertEquals(1, results.size()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrgLevel2In() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .orgLevel2In("abteilung") - .list(); - assertEquals(1, results.size()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForOrgLevel3In() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().orgLevel3In("orgl3").list(); + assertEquals(2, results.size()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrgLevel2Like() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .orgLevel2Like("ab%") - .list(); - assertEquals(1, results.size()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForOrgLevel3Like() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().orgLevel3Like("org%").list(); + assertEquals(2, results.size()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrgLevel3In() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .orgLevel3In("orgl3") - .list(); - assertEquals(2, results.size()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForOrgLevel4In() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().orgLevel4In("team", "orgl4").list(); + assertEquals(2, results.size()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrgLevel3Like() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .orgLevel3Like("org%") - .list(); - assertEquals(2, results.size()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForOrgLevel4Like() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().orgLevel4Like("%").list(); + assertEquals(25, results.size()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrgLevel4In() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .orgLevel4In("team", "orgl4") - .list(); - assertEquals(2, results.size()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByOrgLevel1Desc() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().orderByOrgLevel1(desc).list(); + assertEquals("WBI:100000000000000000000000000000000007", results.get(0).getId()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrgLevel4Like() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .orgLevel4Like("%") - .list(); - assertEquals(25, results.size()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByOrgLevel2Asc() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().orderByOrgLevel2(asc).list(); + assertEquals( + "WBI:100000000000000000000000000000000007", results.get(results.size() - 3).getId()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByOrgLevel1Desc() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .orderByOrgLevel1(desc) - .list(); - assertEquals("WBI:100000000000000000000000000000000007", results.get(0).getId()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByOrgLevel3Desc() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().orderByOrgLevel3(desc).list(); + assertEquals("WBI:100000000000000000000000000000000007", results.get(0).getId()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByOrgLevel2Asc() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .orderByOrgLevel2(asc) - .list(); - assertEquals("WBI:100000000000000000000000000000000007", results.get(results.size() - 3).getId()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByOrgLevel4Asc() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().orderByOrgLevel4(asc).list(); + assertEquals( + "WBI:100000000000000000000000000000000012", results.get(results.size() - 3).getId()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByOrgLevel3Desc() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .orderByOrgLevel3(desc) - .list(); - assertEquals("WBI:100000000000000000000000000000000007", results.get(0).getId()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByCustom1Asc() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().orderByCustom1(asc).list(); + assertEquals( + "WBI:100000000000000000000000000000000015", results.get(results.size() - 4).getId()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByOrgLevel4Asc() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .orderByOrgLevel4(asc) - .list(); - assertEquals("WBI:100000000000000000000000000000000012", results.get(results.size() - 3).getId()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByCustom2Desc() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().orderByCustom2(desc).list(); + assertEquals("WBI:100000000000000000000000000000000014", results.get(0).getId()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByCustom1Asc() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .orderByCustom1(asc) - .list(); - assertEquals("WBI:100000000000000000000000000000000015", results.get(results.size() - 4).getId()); - } - - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByCustom2Desc() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .orderByCustom2(desc) - .list(); - assertEquals("WBI:100000000000000000000000000000000014", results.get(0).getId()); - } - - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByCustom3Asc() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .orderByCustom3(asc) - .list(); - assertEquals("WBI:100000000000000000000000000000000015", results.get(results.size() - 4).getId()); - } - - @WithAccessId( - userName = "admin") - @Test - void testQueryForOrderByCustom4Desc() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .orderByCustom4(desc) - .list(); - assertEquals("WBI:100000000000000000000000000000000006", results.get(0).getId()); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByCustom3Asc() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().orderByCustom3(asc).list(); + assertEquals( + "WBI:100000000000000000000000000000000015", results.get(results.size() - 4).getId()); + } + @WithAccessId(userName = "admin") + @Test + void testQueryForOrderByCustom4Desc() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().orderByCustom4(desc).list(); + assertEquals("WBI:100000000000000000000000000000000006", results.get(0).getId()); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/workbasket/QueryWorkbasketAccessItemsAccTest.java b/lib/taskana-core/src/test/java/acceptance/workbasket/QueryWorkbasketAccessItemsAccTest.java index 3f8203a29..6969402fb 100644 --- a/lib/taskana-core/src/test/java/acceptance/workbasket/QueryWorkbasketAccessItemsAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/workbasket/QueryWorkbasketAccessItemsAccTest.java @@ -7,14 +7,13 @@ import static pro.taskana.AccessItemQueryColumnName.ACCESS_ID; import static pro.taskana.AccessItemQueryColumnName.WORKBASKET_ID; import static pro.taskana.AccessItemQueryColumnName.WORKBASKET_KEY; +import acceptance.AbstractAccTest; import java.util.Arrays; import java.util.List; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.BaseQuery.SortDirection; import pro.taskana.WorkbasketAccessItem; import pro.taskana.WorkbasketAccessItemQuery; @@ -23,183 +22,190 @@ import pro.taskana.exceptions.NotAuthorizedException; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "query access items for workbaskets" scenarios. - */ +/** Acceptance test for all "query access items for workbaskets" scenarios. */ @ExtendWith(JAASExtension.class) class QueryWorkbasketAccessItemsAccTest extends AbstractAccTest { - QueryWorkbasketAccessItemsAccTest() { - super(); - } + QueryWorkbasketAccessItemsAccTest() { + super(); + } - @WithAccessId( - userName = "dummy", - groupNames = {"businessadmin"}) - @Test - void testQueryWorkbasketAccessItemValuesForColumnName() throws NotAuthorizedException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List columnValueList = workbasketService.createWorkbasketAccessItemQuery() - .listValues(WORKBASKET_ID, null); - assertNotNull(columnValueList); - assertEquals(24, columnValueList.size()); + @WithAccessId( + userName = "dummy", + groupNames = {"businessadmin"}) + @Test + void testQueryWorkbasketAccessItemValuesForColumnName() throws NotAuthorizedException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List columnValueList = + workbasketService.createWorkbasketAccessItemQuery().listValues(WORKBASKET_ID, null); + assertNotNull(columnValueList); + assertEquals(24, columnValueList.size()); - columnValueList = workbasketService.createWorkbasketAccessItemQuery() - .listValues(ACCESS_ID, null); - assertNotNull(columnValueList); - assertEquals(9, columnValueList.size()); + columnValueList = + workbasketService.createWorkbasketAccessItemQuery().listValues(ACCESS_ID, null); + assertNotNull(columnValueList); + assertEquals(9, columnValueList.size()); - columnValueList = workbasketService.createWorkbasketAccessItemQuery() - .listValues(WORKBASKET_KEY, null); - assertNotNull(columnValueList); - assertEquals(24, columnValueList.size()); + columnValueList = + workbasketService.createWorkbasketAccessItemQuery().listValues(WORKBASKET_KEY, null); + assertNotNull(columnValueList); + assertEquals(24, columnValueList.size()); - long countEntries = workbasketService.createWorkbasketAccessItemQuery().count(); - assertTrue(columnValueList.size() < countEntries); // DISTINCT - } + long countEntries = workbasketService.createWorkbasketAccessItemQuery().count(); + assertTrue(columnValueList.size() < countEntries); // DISTINCT + } - @WithAccessId( - userName = "dummy", - groupNames = {"businessadmin"}) - @Test - void testQueryAccessItemsForAccessIds() - throws NotAuthorizedException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketAccessItemQuery() + @WithAccessId( + userName = "dummy", + groupNames = {"businessadmin"}) + @Test + void testQueryAccessItemsForAccessIds() throws NotAuthorizedException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService + .createWorkbasketAccessItemQuery() .accessIdIn("user_1_1", "group_1") .list(); - assertEquals(8L, results.size()); - } + assertEquals(8L, results.size()); + } - @WithAccessId( - userName = "dummy") - @Test - void testQueryAccessItemsForAccessIdsNotAuthorized() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + @WithAccessId(userName = "dummy") + @Test + void testQueryAccessItemsForAccessIdsNotAuthorized() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - Assertions.assertThrows(NotAuthorizedException.class, () -> - workbasketService.createWorkbasketAccessItemQuery() + Assertions.assertThrows( + NotAuthorizedException.class, + () -> + workbasketService + .createWorkbasketAccessItemQuery() .accessIdIn("user_1_1", "group_1") .list()); - } + } - @WithAccessId( - userName = "dummy", - groupNames = {"businessadmin"}) - @Test - void testQueryAccessItemsForAccessIdsOrderedDescending() - throws NotAuthorizedException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - WorkbasketAccessItemQuery query = workbasketService.createWorkbasketAccessItemQuery() + @WithAccessId( + userName = "dummy", + groupNames = {"businessadmin"}) + @Test + void testQueryAccessItemsForAccessIdsOrderedDescending() throws NotAuthorizedException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + WorkbasketAccessItemQuery query = + workbasketService + .createWorkbasketAccessItemQuery() .accessIdIn("user_1_1", "group_1") .orderByAccessId(SortDirection.DESCENDING) .orderByWorkbasketId(SortDirection.DESCENDING); - List results = query.list(); - long count = query.count(); - assertEquals(8L, results.size()); - assertEquals(results.size(), count); - assertEquals("WAI:100000000000000000000000000000000003", results.get(0).getId()); - } + List results = query.list(); + long count = query.count(); + assertEquals(8L, results.size()); + assertEquals(results.size(), count); + assertEquals("WAI:100000000000000000000000000000000003", results.get(0).getId()); + } - @WithAccessId( - userName = "dummy", - groupNames = {"businessadmin"}) - @Test - void testQueryAccessItemsForAccessIdsAndWorkbasketKey() - throws NotAuthorizedException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketAccessItemQuery() + @WithAccessId( + userName = "dummy", + groupNames = {"businessadmin"}) + @Test + void testQueryAccessItemsForAccessIdsAndWorkbasketKey() throws NotAuthorizedException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService + .createWorkbasketAccessItemQuery() .accessIdIn("user_1_1", "group_1") - .workbasketIdIn("WBI:100000000000000000000000000000000006", "WBI:100000000000000000000000000000000002") + .workbasketIdIn( + "WBI:100000000000000000000000000000000006", + "WBI:100000000000000000000000000000000002") .list(); - assertEquals(3L, results.size()); - } + assertEquals(3L, results.size()); + } - @WithAccessId( - userName = "dummy", - groupNames = {"businessadmin"}) - @Test - void testQueryAccessItemsForAccessIdsWorkbasketKeyLike() - throws NotAuthorizedException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketAccessItemQuery() - .workbasketKeyLike("GPK_KSC%") - .list(); - assertEquals(4L, results.size()); - } + @WithAccessId( + userName = "dummy", + groupNames = {"businessadmin"}) + @Test + void testQueryAccessItemsForAccessIdsWorkbasketKeyLike() throws NotAuthorizedException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketAccessItemQuery().workbasketKeyLike("GPK_KSC%").list(); + assertEquals(4L, results.size()); + } - @WithAccessId( - userName = "dummy", - groupNames = {"businessadmin"}) - @Test - void testQueryAccessItemsForAccessIdsWorkbasketKeyLikeAndOrderAsc() - throws NotAuthorizedException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketAccessItemQuery() + @WithAccessId( + userName = "dummy", + groupNames = {"businessadmin"}) + @Test + void testQueryAccessItemsForAccessIdsWorkbasketKeyLikeAndOrderAsc() + throws NotAuthorizedException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService + .createWorkbasketAccessItemQuery() .workbasketKeyLike("GPK_KSC%") .orderByWorkbasketKey(SortDirection.ASCENDING) .list(); - assertEquals(4L, results.size()); - assertEquals("GPK_KSC", results.get(0).getWorkbasketKey()); - assertEquals("GPK_KSC_2", results.get(3).getWorkbasketKey()); + assertEquals(4L, results.size()); + assertEquals("GPK_KSC", results.get(0).getWorkbasketKey()); + assertEquals("GPK_KSC_2", results.get(3).getWorkbasketKey()); + } - } - - @WithAccessId( - userName = "dummy", - groupNames = {"businessadmin"}) - @Test - void testQueryAccessItemsByWorkbasketKey() - throws NotAuthorizedException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketAccessItemQuery() + @WithAccessId( + userName = "dummy", + groupNames = {"businessadmin"}) + @Test + void testQueryAccessItemsByWorkbasketKey() throws NotAuthorizedException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService + .createWorkbasketAccessItemQuery() .workbasketIdIn("WBI:100000000000000000000000000000000006") .list(); - assertEquals(3L, results.size()); - } + assertEquals(3L, results.size()); + } - @WithAccessId( - userName = "dummy", - groupNames = {"businessadmin"}) - @Test - void testQueryAccessItemsByWorkbasketKeyOrderedDescending() - throws NotAuthorizedException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketAccessItemQuery() + @WithAccessId( + userName = "dummy", + groupNames = {"businessadmin"}) + @Test + void testQueryAccessItemsByWorkbasketKeyOrderedDescending() throws NotAuthorizedException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService + .createWorkbasketAccessItemQuery() .workbasketIdIn("WBI:100000000000000000000000000000000006") .orderByWorkbasketId(SortDirection.DESCENDING) .orderByAccessId(SortDirection.ASCENDING) .list(); - assertEquals(3L, results.size()); - assertEquals("WAI:100000000000000000000000000000000009", results.get(0).getId()); - } + assertEquals(3L, results.size()); + assertEquals("WAI:100000000000000000000000000000000009", results.get(0).getId()); + } - @WithAccessId( - userName = "admin") - @Test - void testQueryForIdIn() throws NotAuthorizedException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - String[] expectedIds = {"WAI:100000000000000000000000000000000001", - "WAI:100000000000000000000000000000000015", - "WAI:100000000000000000000000000000000007"}; - List results = workbasketService.createWorkbasketAccessItemQuery() - .idIn(expectedIds) - .list(); - for (String id : Arrays.asList(expectedIds)) { - assertTrue(results.stream().anyMatch(accessItem -> accessItem.getId().equals(id))); - } + @WithAccessId(userName = "admin") + @Test + void testQueryForIdIn() throws NotAuthorizedException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + String[] expectedIds = { + "WAI:100000000000000000000000000000000001", + "WAI:100000000000000000000000000000000015", + "WAI:100000000000000000000000000000000007" + }; + List results = + workbasketService.createWorkbasketAccessItemQuery().idIn(expectedIds).list(); + for (String id : Arrays.asList(expectedIds)) { + assertTrue(results.stream().anyMatch(accessItem -> accessItem.getId().equals(id))); } + } - @WithAccessId( - userName = "businessadmin") - @Test - void testQueryForOrderById() throws NotAuthorizedException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketAccessItemQuery() + @WithAccessId(userName = "businessadmin") + @Test + void testQueryForOrderById() throws NotAuthorizedException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService + .createWorkbasketAccessItemQuery() .orderById(SortDirection.ASCENDING) .list(); - assertEquals("0000000000000000000000000000000000000900", results.get(0).getId()); - assertEquals("WAI:100000000000000000000000000000000123", results.get(results.size() - 1).getId()); - } - + assertEquals("0000000000000000000000000000000000000900", results.get(0).getId()); + assertEquals( + "WAI:100000000000000000000000000000000123", results.get(results.size() - 1).getId()); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/workbasket/QueryWorkbasketByPermissionAccTest.java b/lib/taskana-core/src/test/java/acceptance/workbasket/QueryWorkbasketByPermissionAccTest.java index 58ab7bcb6..2996ecce1 100644 --- a/lib/taskana-core/src/test/java/acceptance/workbasket/QueryWorkbasketByPermissionAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/workbasket/QueryWorkbasketByPermissionAccTest.java @@ -3,15 +3,14 @@ package acceptance.workbasket; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import acceptance.AbstractAccTest; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.BaseQuery.SortDirection; import pro.taskana.WorkbasketPermission; import pro.taskana.WorkbasketService; @@ -22,147 +21,165 @@ import pro.taskana.exceptions.SystemException; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "query workbasket by permission" scenarios. - */ +/** Acceptance test for all "query workbasket by permission" scenarios. */ @ExtendWith(JAASExtension.class) class QueryWorkbasketByPermissionAccTest extends AbstractAccTest { - private static SortDirection asc = SortDirection.ASCENDING; - private static SortDirection desc = SortDirection.DESCENDING; + private static SortDirection asc = SortDirection.ASCENDING; + private static SortDirection desc = SortDirection.DESCENDING; - QueryWorkbasketByPermissionAccTest() { - super(); - } + QueryWorkbasketByPermissionAccTest() { + super(); + } - @WithAccessId( - userName = "dummy", - groupNames = {"businessadmin"}) - @Test - void testQueryAllTransferTargetsForUser() - throws NotAuthorizedException, InvalidArgumentException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() + @WithAccessId( + userName = "dummy", + groupNames = {"businessadmin"}) + @Test + void testQueryAllTransferTargetsForUser() + throws NotAuthorizedException, InvalidArgumentException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService + .createWorkbasketQuery() .accessIdsHavePermission(WorkbasketPermission.APPEND, "user_1_1") .list(); - assertEquals(1, results.size()); - assertEquals("USER_1_1", results.get(0).getKey()); - } + assertEquals(1, results.size()); + assertEquals("USER_1_1", results.get(0).getKey()); + } - @WithAccessId( - userName = "dummy") - @Test - void testQueryAllTransferTargetsForUserNotAuthorized() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + @WithAccessId(userName = "dummy") + @Test + void testQueryAllTransferTargetsForUserNotAuthorized() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - Assertions.assertThrows(NotAuthorizedException.class, () -> - workbasketService.createWorkbasketQuery() + Assertions.assertThrows( + NotAuthorizedException.class, + () -> + workbasketService + .createWorkbasketQuery() .accessIdsHavePermission(WorkbasketPermission.APPEND, "user_1_1") .list()); - } + } - @WithAccessId( - userName = "dummy", - groupNames = {"businessadmin"}) - @Test - void testQueryAllTransferTargetsForUserAndGroup() - throws NotAuthorizedException, InvalidArgumentException, SystemException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() + @WithAccessId( + userName = "dummy", + groupNames = {"businessadmin"}) + @Test + void testQueryAllTransferTargetsForUserAndGroup() + throws NotAuthorizedException, InvalidArgumentException, SystemException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService + .createWorkbasketQuery() .accessIdsHavePermission(WorkbasketPermission.APPEND, "user_1_1", "group_1") .list(); - assertEquals(6, results.size()); - } + assertEquals(6, results.size()); + } - @WithAccessId( - userName = "dummy", - groupNames = {"businessadmin"}) - @Test - void testQueryAllTransferTargetsForUserAndGroupSortedByNameAscending() - throws NotAuthorizedException, InvalidArgumentException, SystemException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() + @WithAccessId( + userName = "dummy", + groupNames = {"businessadmin"}) + @Test + void testQueryAllTransferTargetsForUserAndGroupSortedByNameAscending() + throws NotAuthorizedException, InvalidArgumentException, SystemException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService + .createWorkbasketQuery() .accessIdsHavePermission(WorkbasketPermission.APPEND, "user_1_1", "group_1") .orderByName(asc) .list(); - assertEquals(6, results.size()); - assertEquals("GPK_KSC_1", results.get(0).getKey()); - } + assertEquals(6, results.size()); + assertEquals("GPK_KSC_1", results.get(0).getKey()); + } - @WithAccessId( - userName = "dummy", - groupNames = {"businessadmin"}) - @Test - void testQueryAllTransferTargetsForUserAndGroupSortedByNameDescending() - throws NotAuthorizedException, InvalidArgumentException, SystemException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() + @WithAccessId( + userName = "dummy", + groupNames = {"businessadmin"}) + @Test + void testQueryAllTransferTargetsForUserAndGroupSortedByNameDescending() + throws NotAuthorizedException, InvalidArgumentException, SystemException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService + .createWorkbasketQuery() .accessIdsHavePermission(WorkbasketPermission.APPEND, "user_1_1", "group_1") .orderByName(desc) .orderByKey(asc) .list(); - assertEquals(6, results.size()); - assertEquals("USER_2_2", results.get(0).getKey()); - } + assertEquals(6, results.size()); + assertEquals("USER_2_2", results.get(0).getKey()); + } - @WithAccessId( - userName = "dummy", - groupNames = {"businessadmin"}) - @Test - void testQueryAllTransferSourcesForUserAndGroup() - throws NotAuthorizedException, InvalidArgumentException, SystemException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() + @WithAccessId( + userName = "dummy", + groupNames = {"businessadmin"}) + @Test + void testQueryAllTransferSourcesForUserAndGroup() + throws NotAuthorizedException, InvalidArgumentException, SystemException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService + .createWorkbasketQuery() .accessIdsHavePermission(WorkbasketPermission.DISTRIBUTE, "user_1_1", "group_1") .list(); - assertEquals(2, results.size()); - List keys = new ArrayList<>(Arrays.asList("GPK_KSC_1", "USER_1_1")); - for (WorkbasketSummary wb : results) { - assertTrue(keys.contains(wb.getKey())); - } + assertEquals(2, results.size()); + List keys = new ArrayList<>(Arrays.asList("GPK_KSC_1", "USER_1_1")); + for (WorkbasketSummary wb : results) { + assertTrue(keys.contains(wb.getKey())); } + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - void testQueryAllTransferTargetsForUserAndGroupFromSubject() - throws SystemException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + void testQueryAllTransferTargetsForUserAndGroupFromSubject() throws SystemException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService + .createWorkbasketQuery() .callerHasPermission(WorkbasketPermission.APPEND) .list(); - assertEquals(6, results.size()); - } + assertEquals(6, results.size()); + } - @WithAccessId(userName = "user_1_1") - @Test - void testQueryAllAvailableWorkbasketForOpeningForUserAndGroupFromSubject() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() + @WithAccessId(userName = "user_1_1") + @Test + void testQueryAllAvailableWorkbasketForOpeningForUserAndGroupFromSubject() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService + .createWorkbasketQuery() .callerHasPermission(WorkbasketPermission.READ) .list(); - assertEquals(1, results.size()); - } + assertEquals(1, results.size()); + } - @WithAccessId(userName = "teamlead_1", groupNames = {"businessadmin"}) - @Test - void testConsiderBusinessAdminPermissionsWhileQueryingWorkbaskets() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() + @WithAccessId( + userName = "teamlead_1", + groupNames = {"businessadmin"}) + @Test + void testConsiderBusinessAdminPermissionsWhileQueryingWorkbaskets() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService + .createWorkbasketQuery() .callerHasPermission(WorkbasketPermission.OPEN) .list(); - assertEquals(3, results.size()); - } + assertEquals(3, results.size()); + } - @WithAccessId(userName = "admin") - @Test - void testSkipAuthorizationCheckForAdminWhileQueryingWorkbaskets() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() + @WithAccessId(userName = "admin") + @Test + void testSkipAuthorizationCheckForAdminWhileQueryingWorkbaskets() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService + .createWorkbasketQuery() .callerHasPermission(WorkbasketPermission.OPEN) .list(); - assertEquals(25, results.size()); - } - + assertEquals(25, results.size()); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/workbasket/QueryWorkbasketsWithPaginationAccTest.java b/lib/taskana-core/src/test/java/acceptance/workbasket/QueryWorkbasketsWithPaginationAccTest.java index 4d5da851d..7e98c0a7a 100644 --- a/lib/taskana-core/src/test/java/acceptance/workbasket/QueryWorkbasketsWithPaginationAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/workbasket/QueryWorkbasketsWithPaginationAccTest.java @@ -3,193 +3,197 @@ package acceptance.workbasket; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; +import acceptance.AbstractAccTest; import java.util.List; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.WorkbasketService; import pro.taskana.WorkbasketSummary; import pro.taskana.exceptions.TaskanaRuntimeException; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "query classifications with pagination" scenarios. - */ +/** Acceptance test for all "query classifications with pagination" scenarios. */ @ExtendWith(JAASExtension.class) class QueryWorkbasketsWithPaginationAccTest extends AbstractAccTest { - QueryWorkbasketsWithPaginationAccTest() { - super(); - } + QueryWorkbasketsWithPaginationAccTest() { + super(); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testGetFirstPageOfWorkbasketQueryWithOffset() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .domainIn("DOMAIN_A") - .list(0, 5); - assertThat(results.size(), equalTo(5)); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testGetFirstPageOfWorkbasketQueryWithOffset() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().domainIn("DOMAIN_A").list(0, 5); + assertThat(results.size(), equalTo(5)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testGetSecondPageOfWorkbasketQueryWithOffset() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .domainIn("DOMAIN_A") - .list(5, 5); - assertThat(results.size(), equalTo(4)); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testGetSecondPageOfWorkbasketQueryWithOffset() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().domainIn("DOMAIN_A").list(5, 5); + assertThat(results.size(), equalTo(4)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testListOffsetAndLimitOutOfBounds() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testListOffsetAndLimitOutOfBounds() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - // both will be 0, working - List results = workbasketService.createWorkbasketQuery() - .domainIn("DOMAIN_A") - .list(-1, -3); - assertThat(results.size(), equalTo(0)); + // both will be 0, working + List results = + workbasketService.createWorkbasketQuery().domainIn("DOMAIN_A").list(-1, -3); + assertThat(results.size(), equalTo(0)); - // limit will be 0 - results = workbasketService.createWorkbasketQuery() - .domainIn("DOMAIN_A") - .list(1, -3); - assertThat(results.size(), equalTo(0)); + // limit will be 0 + results = workbasketService.createWorkbasketQuery().domainIn("DOMAIN_A").list(1, -3); + assertThat(results.size(), equalTo(0)); - // offset will be 0 - results = workbasketService.createWorkbasketQuery() - .domainIn("DOMAIN_A") - .list(-1, 3); - assertThat(results.size(), equalTo(3)); - } + // offset will be 0 + results = workbasketService.createWorkbasketQuery().domainIn("DOMAIN_A").list(-1, 3); + assertThat(results.size(), equalTo(3)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testPaginationWithPages() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testPaginationWithPages() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - // Getting full page - int pageNumber = 2; - int pageSize = 4; - List results = workbasketService.createWorkbasketQuery() + // Getting full page + int pageNumber = 2; + int pageSize = 4; + List results = + workbasketService + .createWorkbasketQuery() .domainIn("DOMAIN_A") .listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(4)); + assertThat(results.size(), equalTo(4)); - // Getting full page - pageNumber = 4; - pageSize = 1; - results = workbasketService.createWorkbasketQuery() + // Getting full page + pageNumber = 4; + pageSize = 1; + results = + workbasketService + .createWorkbasketQuery() .domainIn("DOMAIN_A") .listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(1)); + assertThat(results.size(), equalTo(1)); - // Getting last results on 1 big page - pageNumber = 1; - pageSize = 100; - results = workbasketService.createWorkbasketQuery() + // Getting last results on 1 big page + pageNumber = 1; + pageSize = 100; + results = + workbasketService + .createWorkbasketQuery() .domainIn("DOMAIN_A") .listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(9)); + assertThat(results.size(), equalTo(9)); - // Getting last results on multiple pages - pageNumber = 2; - pageSize = 5; - results = workbasketService.createWorkbasketQuery() + // Getting last results on multiple pages + pageNumber = 2; + pageSize = 5; + results = + workbasketService + .createWorkbasketQuery() .domainIn("DOMAIN_A") .listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(4)); - } + assertThat(results.size(), equalTo(4)); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testPaginationNullAndNegativeLimitsIgnoring() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testPaginationNullAndNegativeLimitsIgnoring() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - // 0 limit/size = 0 results - int pageNumber = 2; - int pageSize = 0; - List results = workbasketService.createWorkbasketQuery() + // 0 limit/size = 0 results + int pageNumber = 2; + int pageSize = 0; + List results = + workbasketService + .createWorkbasketQuery() .domainIn("DOMAIN_A") .listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(0)); + assertThat(results.size(), equalTo(0)); - // Negative size will be 0 = 0 results - pageNumber = 2; - pageSize = -1; - results = workbasketService.createWorkbasketQuery() + // Negative size will be 0 = 0 results + pageNumber = 2; + pageSize = -1; + results = + workbasketService + .createWorkbasketQuery() .domainIn("DOMAIN_A") .listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(0)); + assertThat(results.size(), equalTo(0)); - // Negative page = first page - pageNumber = -1; - pageSize = 10; - results = workbasketService.createWorkbasketQuery() + // Negative page = first page + pageNumber = -1; + pageSize = 10; + results = + workbasketService + .createWorkbasketQuery() .domainIn("DOMAIN_A") .listPage(pageNumber, pageSize); - assertThat(results.size(), equalTo(9)); - } + assertThat(results.size(), equalTo(9)); + } - /** - * Testcase only for DB2 users, because H2 doesn´t throw a Exception when the offset is set to high.
- * Using DB2 should throw a unchecked RuntimeException for a offset which is out of bounds. - */ - @Disabled - @Test - void testPaginationThrowingExceptionWhenPageOutOfBounds() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + /** + * Testcase only for DB2 users, because H2 doesn´t throw a Exception when the offset is set to + * high.
+ * Using DB2 should throw a unchecked RuntimeException for a offset which is out of bounds. + */ + @Disabled + @Test + void testPaginationThrowingExceptionWhenPageOutOfBounds() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - // entrypoint set outside result amount - int pageNumber = 6; - int pageSize = 10; + // entrypoint set outside result amount + int pageNumber = 6; + int pageSize = 10; - Assertions.assertThrows(TaskanaRuntimeException.class, () -> - workbasketService.createWorkbasketQuery() + Assertions.assertThrows( + TaskanaRuntimeException.class, + () -> + workbasketService + .createWorkbasketQuery() .domainIn("DOMAIN_A") .listPage(pageNumber, pageSize)); - } + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testCountOfWorkbasketQuery() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - long count = workbasketService.createWorkbasketQuery() - .domainIn("DOMAIN_A") - .count(); - assertThat(count, equalTo(9L)); - } - - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1"}) - @Test - void testWorkbasketQueryDomA() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List result = workbasketService.createWorkbasketQuery() - .domainIn("DOMAIN_A") - .list(); - assertThat(result.size(), equalTo(9)); - } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testCountOfWorkbasketQuery() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + long count = workbasketService.createWorkbasketQuery().domainIn("DOMAIN_A").count(); + assertThat(count, equalTo(9L)); + } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1"}) + @Test + void testWorkbasketQueryDomA() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List result = + workbasketService.createWorkbasketQuery().domainIn("DOMAIN_A").list(); + assertThat(result.size(), equalTo(9)); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/workbasket/UpdateWorkbasketAccTest.java b/lib/taskana-core/src/test/java/acceptance/workbasket/UpdateWorkbasketAccTest.java index fdfe33708..a5370b498 100644 --- a/lib/taskana-core/src/test/java/acceptance/workbasket/UpdateWorkbasketAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/workbasket/UpdateWorkbasketAccTest.java @@ -3,13 +3,12 @@ package acceptance.workbasket; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import acceptance.AbstractAccTest; import java.time.Instant; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.Workbasket; import pro.taskana.WorkbasketService; import pro.taskana.WorkbasketType; @@ -18,61 +17,57 @@ import pro.taskana.exceptions.WorkbasketNotFoundException; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "update workbasket" scenarios. - */ +/** Acceptance test for all "update workbasket" scenarios. */ @ExtendWith(JAASExtension.class) public class UpdateWorkbasketAccTest extends AbstractAccTest { - public UpdateWorkbasketAccTest() { - super(); - } + public UpdateWorkbasketAccTest() { + super(); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "businessadmin"}) - @Test - public void testUpdateWorkbasket() - throws NotAuthorizedException, WorkbasketNotFoundException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - Workbasket workbasket = workbasketService.getWorkbasket("GPK_KSC", "DOMAIN_A"); - Instant modified = workbasket.getModified(); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "businessadmin"}) + @Test + public void testUpdateWorkbasket() throws NotAuthorizedException, WorkbasketNotFoundException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + Workbasket workbasket = workbasketService.getWorkbasket("GPK_KSC", "DOMAIN_A"); + Instant modified = workbasket.getModified(); - workbasket.setName("new name"); - workbasket.setDescription("new description"); - workbasket.setType(WorkbasketType.TOPIC); - workbasket.setOrgLevel1("new level 1"); - workbasket.setOrgLevel2("new level 2"); - workbasket.setOrgLevel3("new level 3"); - workbasket.setOrgLevel4("new level 4"); - workbasket.setCustom1("new custom 1"); - workbasket.setCustom2("new custom 2"); - workbasket.setCustom3("new custom 3"); - workbasket.setCustom4("new custom 4"); - workbasket.setDescription("new description"); - workbasketService.updateWorkbasket(workbasket); + workbasket.setName("new name"); + workbasket.setDescription("new description"); + workbasket.setType(WorkbasketType.TOPIC); + workbasket.setOrgLevel1("new level 1"); + workbasket.setOrgLevel2("new level 2"); + workbasket.setOrgLevel3("new level 3"); + workbasket.setOrgLevel4("new level 4"); + workbasket.setCustom1("new custom 1"); + workbasket.setCustom2("new custom 2"); + workbasket.setCustom3("new custom 3"); + workbasket.setCustom4("new custom 4"); + workbasket.setDescription("new description"); + workbasketService.updateWorkbasket(workbasket); - Workbasket updatedWorkbasket = workbasketService.getWorkbasket("GPK_KSC", "DOMAIN_A"); - assertEquals(workbasket.getId(), updatedWorkbasket.getId()); - assertEquals(workbasket.getCreated(), updatedWorkbasket.getCreated()); - assertNotEquals(modified, updatedWorkbasket.getModified()); - assertEquals("new name", updatedWorkbasket.getName()); - assertEquals(WorkbasketType.TOPIC, updatedWorkbasket.getType()); - } + Workbasket updatedWorkbasket = workbasketService.getWorkbasket("GPK_KSC", "DOMAIN_A"); + assertEquals(workbasket.getId(), updatedWorkbasket.getId()); + assertEquals(workbasket.getCreated(), updatedWorkbasket.getCreated()); + assertNotEquals(modified, updatedWorkbasket.getModified()); + assertEquals("new name", updatedWorkbasket.getName()); + assertEquals(WorkbasketType.TOPIC, updatedWorkbasket.getType()); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_1"}) - @Test - public void testCheckAuthorizationToUpdateWorkbasket() - throws NotAuthorizedException, WorkbasketNotFoundException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - Workbasket workbasket = workbasketService.getWorkbasket("USER_1_1", "DOMAIN_A"); + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_1"}) + @Test + public void testCheckAuthorizationToUpdateWorkbasket() + throws NotAuthorizedException, WorkbasketNotFoundException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + Workbasket workbasket = workbasketService.getWorkbasket("USER_1_1", "DOMAIN_A"); - workbasket.setName("new name"); - - Assertions.assertThrows(NotAuthorizedException.class, () -> - workbasketService.updateWorkbasket(workbasket)); - } + workbasket.setName("new name"); + Assertions.assertThrows( + NotAuthorizedException.class, () -> workbasketService.updateWorkbasket(workbasket)); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/workbasket/UpdateWorkbasketAuthorizationsAccTest.java b/lib/taskana-core/src/test/java/acceptance/workbasket/UpdateWorkbasketAuthorizationsAccTest.java index caee90fd4..8970927c2 100644 --- a/lib/taskana-core/src/test/java/acceptance/workbasket/UpdateWorkbasketAuthorizationsAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/workbasket/UpdateWorkbasketAuthorizationsAccTest.java @@ -9,14 +9,13 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import acceptance.AbstractAccTest; import java.util.ArrayList; import java.util.List; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.KeyDomain; import pro.taskana.Task; import pro.taskana.TaskService; @@ -34,292 +33,294 @@ import pro.taskana.security.CurrentUserContext; import pro.taskana.security.JAASExtension; import pro.taskana.security.WithAccessId; -/** - * Acceptance test for all "update workbasket" scenarios. - */ +/** Acceptance test for all "update workbasket" scenarios. */ @ExtendWith(JAASExtension.class) class UpdateWorkbasketAuthorizationsAccTest extends AbstractAccTest { - UpdateWorkbasketAuthorizationsAccTest() { - super(); - } + UpdateWorkbasketAuthorizationsAccTest() { + super(); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "businessadmin"}) - @Test - void testUpdateWorkbasketAccessItemSucceeds() - throws InvalidArgumentException, NotAuthorizedException, WorkbasketNotFoundException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - WorkbasketAccessItem accessItem = workbasketService - .newWorkbasketAccessItem("WBI:100000000000000000000000000000000002", "user1"); - accessItem.setPermAppend(true); - accessItem.setPermCustom11(true); - accessItem.setPermRead(true); - accessItem = workbasketService.createWorkbasketAccessItem(accessItem); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "businessadmin"}) + @Test + void testUpdateWorkbasketAccessItemSucceeds() + throws InvalidArgumentException, NotAuthorizedException, WorkbasketNotFoundException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + WorkbasketAccessItem accessItem = + workbasketService.newWorkbasketAccessItem( + "WBI:100000000000000000000000000000000002", "user1"); + accessItem.setPermAppend(true); + accessItem.setPermCustom11(true); + accessItem.setPermRead(true); + accessItem = workbasketService.createWorkbasketAccessItem(accessItem); - WorkbasketAccessItem newItem = accessItem; - accessItem.setPermCustom1(true); - accessItem.setPermAppend(false); - accessItem.setAccessName("Rojas, Miguel"); - workbasketService.updateWorkbasketAccessItem(accessItem); - List items = workbasketService - .getWorkbasketAccessItems("WBI:100000000000000000000000000000000002"); + WorkbasketAccessItem newItem = accessItem; + accessItem.setPermCustom1(true); + accessItem.setPermAppend(false); + accessItem.setAccessName("Rojas, Miguel"); + workbasketService.updateWorkbasketAccessItem(accessItem); + List items = + workbasketService.getWorkbasketAccessItems("WBI:100000000000000000000000000000000002"); - WorkbasketAccessItem updatedItem = items.stream() - .filter(t -> newItem.getId().equals(t.getId())) - .findFirst() - .orElse(null); + WorkbasketAccessItem updatedItem = + items.stream().filter(t -> newItem.getId().equals(t.getId())).findFirst().orElse(null); - assertNotNull(updatedItem); - assertEquals("Rojas, Miguel", updatedItem.getAccessName()); - assertFalse(updatedItem.isPermAppend()); - assertTrue(updatedItem.isPermRead()); - assertTrue(updatedItem.isPermCustom11()); - assertTrue(updatedItem.isPermCustom1()); - assertFalse(updatedItem.isPermCustom2()); - } + assertNotNull(updatedItem); + assertEquals("Rojas, Miguel", updatedItem.getAccessName()); + assertFalse(updatedItem.isPermAppend()); + assertTrue(updatedItem.isPermRead()); + assertTrue(updatedItem.isPermCustom11()); + assertTrue(updatedItem.isPermCustom1()); + assertFalse(updatedItem.isPermCustom2()); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "businessadmin"}) - @Test - void testUpdateWorkbasketAccessItemRejected() - throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - WorkbasketAccessItem accessItem = workbasketService - .newWorkbasketAccessItem("WBI:100000000000000000000000000000000001", "user1"); - accessItem.setPermAppend(true); - accessItem.setPermCustom11(true); - accessItem.setPermRead(true); - WorkbasketAccessItem accessItemCreated = workbasketService.createWorkbasketAccessItem(accessItem); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "businessadmin"}) + @Test + void testUpdateWorkbasketAccessItemRejected() + throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + WorkbasketAccessItem accessItem = + workbasketService.newWorkbasketAccessItem( + "WBI:100000000000000000000000000000000001", "user1"); + accessItem.setPermAppend(true); + accessItem.setPermCustom11(true); + accessItem.setPermRead(true); + WorkbasketAccessItem accessItemCreated = + workbasketService.createWorkbasketAccessItem(accessItem); - accessItemCreated.setPermCustom1(true); - accessItemCreated.setPermAppend(false); - ((WorkbasketAccessItemImpl) accessItemCreated).setAccessId("willi"); + accessItemCreated.setPermCustom1(true); + accessItemCreated.setPermAppend(false); + ((WorkbasketAccessItemImpl) accessItemCreated).setAccessId("willi"); - Assertions.assertThrows(InvalidArgumentException.class, () -> - workbasketService.updateWorkbasketAccessItem(accessItemCreated), - "InvalidArgumentException was expected because access id was changed"); + Assertions.assertThrows( + InvalidArgumentException.class, + () -> workbasketService.updateWorkbasketAccessItem(accessItemCreated), + "InvalidArgumentException was expected because access id was changed"); - ((WorkbasketAccessItemImpl) accessItemCreated).setAccessId("user1"); - WorkbasketAccessItem accessItemUpdated = workbasketService.updateWorkbasketAccessItem(accessItemCreated); - assertFalse(accessItemUpdated.isPermAppend()); - assertTrue(accessItemUpdated.isPermRead()); - assertTrue(accessItemUpdated.isPermCustom11()); - assertTrue(accessItemUpdated.isPermCustom1()); - assertFalse(accessItemUpdated.isPermCustom2()); + ((WorkbasketAccessItemImpl) accessItemCreated).setAccessId("user1"); + WorkbasketAccessItem accessItemUpdated = + workbasketService.updateWorkbasketAccessItem(accessItemCreated); + assertFalse(accessItemUpdated.isPermAppend()); + assertTrue(accessItemUpdated.isPermRead()); + assertTrue(accessItemUpdated.isPermCustom11()); + assertTrue(accessItemUpdated.isPermCustom1()); + assertFalse(accessItemUpdated.isPermCustom2()); - ((WorkbasketAccessItemImpl) accessItemUpdated).setWorkbasketId("2"); + ((WorkbasketAccessItemImpl) accessItemUpdated).setWorkbasketId("2"); - Assertions.assertThrows(InvalidArgumentException.class, () -> - workbasketService.updateWorkbasketAccessItem(accessItemUpdated), - "InvalidArgumentException was expected because key was changed"); - } + Assertions.assertThrows( + InvalidArgumentException.class, + () -> workbasketService.updateWorkbasketAccessItem(accessItemUpdated), + "InvalidArgumentException was expected because key was changed"); + } - @WithAccessId( - userName = "user_1_1", - groupNames = {"group_2", "businessadmin"}) - @Test - void testUpdatedAccessItemLeadsToNotAuthorizedException() - throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException, - ClassificationNotFoundException, TaskAlreadyExistException { - TaskService taskService = taskanaEngine.getTaskService(); - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + @WithAccessId( + userName = "user_1_1", + groupNames = {"group_2", "businessadmin"}) + @Test + void testUpdatedAccessItemLeadsToNotAuthorizedException() + throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException, + ClassificationNotFoundException, TaskAlreadyExistException { + TaskService taskService = taskanaEngine.getTaskService(); + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - String wbKey = "USER_2_1"; - String wbDomain = "DOMAIN_A"; - String groupName = "group_2"; + String wbKey = "USER_2_1"; + String wbDomain = "DOMAIN_A"; + String groupName = "group_2"; - Task newTask = taskService.newTask(wbKey, wbDomain); - newTask.setClassificationKey("T2100"); - newTask.setPrimaryObjRef(createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); - Task createdTask = taskService.createTask(newTask); - List tasks = taskService.createTaskQuery() - .workbasketKeyDomainIn(new KeyDomain(wbKey, wbDomain)) - .list(); - assertEquals(1, tasks.size()); - assertThat(createdTask, not(equalTo(null))); + Task newTask = taskService.newTask(wbKey, wbDomain); + newTask.setClassificationKey("T2100"); + newTask.setPrimaryObjRef( + createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); + Task createdTask = taskService.createTask(newTask); + List tasks = + taskService.createTaskQuery().workbasketKeyDomainIn(new KeyDomain(wbKey, wbDomain)).list(); + assertEquals(1, tasks.size()); + assertThat(createdTask, not(equalTo(null))); - List accessItems = workbasketService - .getWorkbasketAccessItems("WBI:100000000000000000000000000000000008"); - WorkbasketAccessItem theAccessItem = accessItems.stream() + List accessItems = + workbasketService.getWorkbasketAccessItems("WBI:100000000000000000000000000000000008"); + WorkbasketAccessItem theAccessItem = + accessItems.stream() .filter(x -> groupName.equals(x.getAccessId())) .findFirst() .orElse(null); - assertNotNull(theAccessItem); - theAccessItem.setPermOpen(false); - workbasketService.updateWorkbasketAccessItem(theAccessItem); + assertNotNull(theAccessItem); + theAccessItem.setPermOpen(false); + workbasketService.updateWorkbasketAccessItem(theAccessItem); - Assertions.assertThrows(NotAuthorizedToQueryWorkbasketException.class, () -> - taskService.createTaskQuery() + Assertions.assertThrows( + NotAuthorizedToQueryWorkbasketException.class, + () -> + taskService + .createTaskQuery() .workbasketKeyDomainIn(new KeyDomain(wbKey, wbDomain)) .list()); + } + + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "businessadmin"}) + @Test + void testUpdatedAccessItemList() throws InvalidArgumentException, NotAuthorizedException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + final String wbId = "WBI:100000000000000000000000000000000004"; + List accessItems = workbasketService.getWorkbasketAccessItems(wbId); + int countBefore = accessItems.size(); + + // update some values + WorkbasketAccessItem item0 = accessItems.get(0); + item0.setPermAppend(false); + item0.setPermOpen(false); + item0.setPermTransfer(false); + final String updateId0 = item0.getId(); + WorkbasketAccessItem item1 = accessItems.get(1); + item1.setPermAppend(false); + item1.setPermOpen(false); + item1.setPermTransfer(false); + final String updateId1 = item1.getId(); + + workbasketService.setWorkbasketAccessItems(wbId, accessItems); + + List updatedAccessItems = + workbasketService.getWorkbasketAccessItems(wbId); + int countAfter = updatedAccessItems.size(); + assertThat(countAfter, equalTo(countBefore)); + + item0 = updatedAccessItems.stream().filter(i -> i.getId().equals(updateId0)).findFirst().get(); + assertFalse(item0.isPermAppend()); + assertFalse(item0.isPermOpen()); + assertFalse(item0.isPermTransfer()); + + item1 = updatedAccessItems.stream().filter(i -> i.getId().equals(updateId1)).findFirst().get(); + assertFalse(item1.isPermAppend()); + assertFalse(item1.isPermOpen()); + assertFalse(item1.isPermTransfer()); + } + + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "businessadmin"}) + @Test + void testUpdatedAccessItemListToEmptyList() + throws InvalidArgumentException, NotAuthorizedException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + final String wbId = "WBI:100000000000000000000000000000000004"; + List accessItems = workbasketService.getWorkbasketAccessItems(wbId); + int countBefore = accessItems.size(); + assertThat(3, equalTo(countBefore)); + + workbasketService.setWorkbasketAccessItems(wbId, new ArrayList<>()); + + List updatedAccessItems = + workbasketService.getWorkbasketAccessItems(wbId); + int countAfter = updatedAccessItems.size(); + assertThat(0, equalTo(countAfter)); + } + + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "businessadmin"}) + @Test + void testInsertAccessItemList() throws InvalidArgumentException, NotAuthorizedException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + final String wbId = "WBI:100000000000000000000000000000000004"; + List accessItems = workbasketService.getWorkbasketAccessItems(wbId); + int countBefore = accessItems.size(); + + // update some values + WorkbasketAccessItem item0 = accessItems.get(0); + item0.setPermAppend(false); + item0.setPermOpen(false); + item0.setPermTransfer(false); + final String updateId0 = item0.getId(); + // insert new entry + WorkbasketAccessItem newItem = + workbasketService.newWorkbasketAccessItem(wbId, CurrentUserContext.getUserid()); + newItem.setPermRead(true); + newItem.setPermOpen(true); + newItem.setPermCustom12(true); + accessItems.add(newItem); + + workbasketService.setWorkbasketAccessItems(wbId, accessItems); + + List updatedAccessItems = + workbasketService.getWorkbasketAccessItems(wbId); + int countAfter = updatedAccessItems.size(); + assertEquals((countBefore + 1), countAfter); + + item0 = updatedAccessItems.stream().filter(i -> i.getId().equals(updateId0)).findFirst().get(); + assertFalse(item0.isPermAppend()); + assertFalse(item0.isPermOpen()); + assertFalse(item0.isPermTransfer()); + assertFalse(item0.isPermAppend()); + assertFalse(item0.isPermTransfer()); + } + + @WithAccessId( + userName = "teamlead_1", + groupNames = {"group_1", "businessadmin"}) + @Test + void testDeleteAccessItemForAccessItemId() + throws NotAuthorizedException, InvalidArgumentException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + final String wbId = "WBI:100000000000000000000000000000000001"; + + List originalList = workbasketService.getWorkbasketAccessItems(wbId); + List originalIds = new ArrayList<>(); + for (WorkbasketAccessItem a : originalList) { + originalIds.add(a.getId()); } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "businessadmin"}) - @Test - void testUpdatedAccessItemList() throws InvalidArgumentException, NotAuthorizedException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - final String wbId = "WBI:100000000000000000000000000000000004"; - List accessItems = workbasketService - .getWorkbasketAccessItems(wbId); - int countBefore = accessItems.size(); + List accessList = new ArrayList<>(originalList); + WorkbasketAccessItem newItem = workbasketService.newWorkbasketAccessItem(wbId, "group_1"); + accessList.add(newItem); + assertNotEquals(originalList, accessList); + workbasketService.setWorkbasketAccessItems(wbId, accessList); - // update some values - WorkbasketAccessItem item0 = accessItems.get(0); - item0.setPermAppend(false); - item0.setPermOpen(false); - item0.setPermTransfer(false); - final String updateId0 = item0.getId(); - WorkbasketAccessItem item1 = accessItems.get(1); - item1.setPermAppend(false); - item1.setPermOpen(false); - item1.setPermTransfer(false); - final String updateId1 = item1.getId(); - - workbasketService.setWorkbasketAccessItems(wbId, accessItems); - - List updatedAccessItems = workbasketService - .getWorkbasketAccessItems(wbId); - int countAfter = updatedAccessItems.size(); - assertThat(countAfter, equalTo(countBefore)); - - item0 = updatedAccessItems.stream().filter(i -> i.getId().equals(updateId0)).findFirst().get(); - assertFalse(item0.isPermAppend()); - assertFalse(item0.isPermOpen()); - assertFalse(item0.isPermTransfer()); - - item1 = updatedAccessItems.stream().filter(i -> i.getId().equals(updateId1)).findFirst().get(); - assertFalse(item1.isPermAppend()); - assertFalse(item1.isPermOpen()); - assertFalse(item1.isPermTransfer()); + List modifiedList = + new ArrayList<>(workbasketService.getWorkbasketAccessItems(wbId)); + for (WorkbasketAccessItem a : modifiedList) { + if (!originalIds.contains(a.getId())) { + workbasketService.deleteWorkbasketAccessItem(a.getId()); + } } + List listEqualToOriginal = + new ArrayList<>(workbasketService.getWorkbasketAccessItems(wbId)); + assertEquals(originalList, listEqualToOriginal); + } - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "businessadmin"}) - @Test - void testUpdatedAccessItemListToEmptyList() throws InvalidArgumentException, NotAuthorizedException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - final String wbId = "WBI:100000000000000000000000000000000004"; - List accessItems = workbasketService - .getWorkbasketAccessItems(wbId); - int countBefore = accessItems.size(); - assertThat(3, equalTo(countBefore)); + @WithAccessId( + userName = "teamlead_1", + groupNames = {"businessadmin"}) + @Test + void testDeleteAccessItemsForAccessId() throws NotAuthorizedException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + final String accessId = "group_1"; + final long accessIdCountBefore = + workbasketService.createWorkbasketAccessItemQuery().accessIdIn(accessId).count(); - workbasketService.setWorkbasketAccessItems(wbId, new ArrayList<>()); + workbasketService.deleteWorkbasketAccessItemsForAccessId(accessId); - List updatedAccessItems = workbasketService - .getWorkbasketAccessItems(wbId); - int countAfter = updatedAccessItems.size(); - assertThat(0, equalTo(countAfter)); - } - - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "businessadmin"}) - @Test - void testInsertAccessItemList() throws InvalidArgumentException, NotAuthorizedException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - final String wbId = "WBI:100000000000000000000000000000000004"; - List accessItems = workbasketService - .getWorkbasketAccessItems(wbId); - int countBefore = accessItems.size(); - - // update some values - WorkbasketAccessItem item0 = accessItems.get(0); - item0.setPermAppend(false); - item0.setPermOpen(false); - item0.setPermTransfer(false); - final String updateId0 = item0.getId(); - // insert new entry - WorkbasketAccessItem newItem = workbasketService.newWorkbasketAccessItem(wbId, CurrentUserContext.getUserid()); - newItem.setPermRead(true); - newItem.setPermOpen(true); - newItem.setPermCustom12(true); - accessItems.add(newItem); - - workbasketService.setWorkbasketAccessItems(wbId, accessItems); - - List updatedAccessItems = workbasketService - .getWorkbasketAccessItems(wbId); - int countAfter = updatedAccessItems.size(); - assertEquals((countBefore + 1), countAfter); - - item0 = updatedAccessItems.stream().filter(i -> i.getId().equals(updateId0)).findFirst().get(); - assertFalse(item0.isPermAppend()); - assertFalse(item0.isPermOpen()); - assertFalse(item0.isPermTransfer()); - assertFalse(item0.isPermAppend()); - assertFalse(item0.isPermTransfer()); - } - - @WithAccessId( - userName = "teamlead_1", - groupNames = {"group_1", "businessadmin"}) - @Test - void testDeleteAccessItemForAccessItemId() throws NotAuthorizedException, InvalidArgumentException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - final String wbId = "WBI:100000000000000000000000000000000001"; - - List originalList = workbasketService.getWorkbasketAccessItems(wbId); - List originalIds = new ArrayList<>(); - for (WorkbasketAccessItem a : originalList) { - originalIds.add(a.getId()); - } - - List accessList = new ArrayList<>(originalList); - WorkbasketAccessItem newItem = workbasketService.newWorkbasketAccessItem(wbId, "group_1"); - accessList.add(newItem); - assertNotEquals(originalList, accessList); - workbasketService.setWorkbasketAccessItems(wbId, accessList); - - List modifiedList = new ArrayList<>( - workbasketService.getWorkbasketAccessItems(wbId)); - for (WorkbasketAccessItem a : modifiedList) { - if (!originalIds.contains(a.getId())) { - workbasketService.deleteWorkbasketAccessItem(a.getId()); - } - } - List listEqualToOriginal = new ArrayList<>( - workbasketService.getWorkbasketAccessItems(wbId)); - assertEquals(originalList, listEqualToOriginal); - } - - @WithAccessId( - userName = "teamlead_1", - groupNames = {"businessadmin"}) - @Test - void testDeleteAccessItemsForAccessId() throws NotAuthorizedException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - final String accessId = "group_1"; - final long accessIdCountBefore = workbasketService - .createWorkbasketAccessItemQuery() - .accessIdIn(accessId) - .count(); - - workbasketService.deleteWorkbasketAccessItemsForAccessId(accessId); - - final long accessIdCountAfter = workbasketService - .createWorkbasketAccessItemQuery() - .accessIdIn(accessId) - .count(); - assertTrue(accessIdCountBefore > accessIdCountAfter); - } - - @WithAccessId( - userName = "teamlead_1", - groupNames = {"businessadmin"}) - @Test - void testDeleteAccessItemsForAccessIdWithUnusedValuesThrowingNoException() throws NotAuthorizedException { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - workbasketService.deleteWorkbasketAccessItemsForAccessId(""); - workbasketService.deleteWorkbasketAccessItemsForAccessId(null); - workbasketService.deleteWorkbasketAccessItemsForAccessId("123UNUSED456"); - } + final long accessIdCountAfter = + workbasketService.createWorkbasketAccessItemQuery().accessIdIn(accessId).count(); + assertTrue(accessIdCountBefore > accessIdCountAfter); + } + @WithAccessId( + userName = "teamlead_1", + groupNames = {"businessadmin"}) + @Test + void testDeleteAccessItemsForAccessIdWithUnusedValuesThrowingNoException() + throws NotAuthorizedException { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + workbasketService.deleteWorkbasketAccessItemsForAccessId(""); + workbasketService.deleteWorkbasketAccessItemsForAccessId(null); + workbasketService.deleteWorkbasketAccessItemsForAccessId("123UNUSED456"); + } } diff --git a/lib/taskana-core/src/test/java/acceptance/workbasket/WorkbasketQueryWithOrderedPaginationAccTest.java b/lib/taskana-core/src/test/java/acceptance/workbasket/WorkbasketQueryWithOrderedPaginationAccTest.java index 12947802b..6569252fd 100644 --- a/lib/taskana-core/src/test/java/acceptance/workbasket/WorkbasketQueryWithOrderedPaginationAccTest.java +++ b/lib/taskana-core/src/test/java/acceptance/workbasket/WorkbasketQueryWithOrderedPaginationAccTest.java @@ -3,71 +3,59 @@ package acceptance.workbasket; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; +import acceptance.AbstractAccTest; import java.util.List; - import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import acceptance.AbstractAccTest; import pro.taskana.BaseQuery.SortDirection; import pro.taskana.WorkbasketService; import pro.taskana.WorkbasketSummary; import pro.taskana.security.JAASExtension; -/** - * Acceptance test for all "query classifications with pagination" scenarios. - */ +/** Acceptance test for all "query classifications with pagination" scenarios. */ @ExtendWith(JAASExtension.class) class WorkbasketQueryWithOrderedPaginationAccTest extends AbstractAccTest { - private static SortDirection asc = SortDirection.ASCENDING; - private static SortDirection desc = SortDirection.DESCENDING; + private static SortDirection asc = SortDirection.ASCENDING; + private static SortDirection desc = SortDirection.DESCENDING; - WorkbasketQueryWithOrderedPaginationAccTest() { - super(); - } + WorkbasketQueryWithOrderedPaginationAccTest() { + super(); + } - @Disabled - @Test - void testGetFirstPageOfTaskQueryWithOffset() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .domainIn("DOMAIN_A") - .orderByKey(asc) - .list(0, 5); - assertThat(results.size(), equalTo(5)); - assertThat(results.get(0).getKey(), equalTo("GPK_KSC")); - assertThat(results.get(4).getKey(), equalTo("key2")); + @Disabled + @Test + void testGetFirstPageOfTaskQueryWithOffset() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().domainIn("DOMAIN_A").orderByKey(asc).list(0, 5); + assertThat(results.size(), equalTo(5)); + assertThat(results.get(0).getKey(), equalTo("GPK_KSC")); + assertThat(results.get(4).getKey(), equalTo("key2")); - results = workbasketService.createWorkbasketQuery() - .domainIn("DOMAIN_A") - .orderByKey(desc) - .list(0, 5); - assertThat(results.size(), equalTo(5)); - assertThat(results.get(0).getKey(), equalTo("USER_2_2")); - assertThat(results.get(4).getKey(), equalTo("TEAMLEAD_2")); - } + results = + workbasketService.createWorkbasketQuery().domainIn("DOMAIN_A").orderByKey(desc).list(0, 5); + assertThat(results.size(), equalTo(5)); + assertThat(results.get(0).getKey(), equalTo("USER_2_2")); + assertThat(results.get(4).getKey(), equalTo("TEAMLEAD_2")); + } - @Disabled - @Test - void testGetSecondPageOfTaskQueryWithOffset() { - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - List results = workbasketService.createWorkbasketQuery() - .domainIn("DOMAIN_A") - .orderByKey(asc) - .list(5, 5); - assertThat(results.size(), equalTo(5)); - assertThat(results.get(0).getKey(), equalTo("key3")); - assertThat(results.get(4).getKey(), equalTo("USER_1_1")); - - results = workbasketService.createWorkbasketQuery() - .domainIn("DOMAIN_A") - .orderByKey(desc) - .list(5, 5); - assertThat(results.size(), equalTo(5)); - assertThat(results.get(0).getKey(), equalTo("TEAMLEAD_1")); - assertThat(results.get(4).getKey(), equalTo("key3")); - } + @Disabled + @Test + void testGetSecondPageOfTaskQueryWithOffset() { + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + List results = + workbasketService.createWorkbasketQuery().domainIn("DOMAIN_A").orderByKey(asc).list(5, 5); + assertThat(results.size(), equalTo(5)); + assertThat(results.get(0).getKey(), equalTo("key3")); + assertThat(results.get(4).getKey(), equalTo("USER_1_1")); + results = + workbasketService.createWorkbasketQuery().domainIn("DOMAIN_A").orderByKey(desc).list(5, 5); + assertThat(results.size(), equalTo(5)); + assertThat(results.get(0).getKey(), equalTo("TEAMLEAD_1")); + assertThat(results.get(4).getKey(), equalTo("key3")); + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/ArchitectureTest.java b/lib/taskana-core/src/test/java/pro/taskana/ArchitectureTest.java index 325a04621..73aa2dc02 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/ArchitectureTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/ArchitectureTest.java @@ -5,67 +5,67 @@ import static com.tngtech.archunit.library.GeneralCodingRules.NO_CLASSES_SHOULD_ import static com.tngtech.archunit.library.GeneralCodingRules.NO_CLASSES_SHOULD_THROW_GENERIC_EXCEPTIONS; import static com.tngtech.archunit.library.dependencies.SlicesRuleDefinition.slices; +import com.tngtech.archunit.core.domain.JavaClasses; +import com.tngtech.archunit.core.importer.ClassFileImporter; +import com.tngtech.archunit.lang.ArchRule; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import com.tngtech.archunit.core.domain.JavaClasses; -import com.tngtech.archunit.core.importer.ClassFileImporter; -import com.tngtech.archunit.lang.ArchRule; - /** - * Test architecture of classes in taskana. - * For more info and examples see https://www.archunit.org/userguide/html/000_Index.html + * Test architecture of classes in taskana. For more info and examples see + * https://www.archunit.org/userguide/html/000_Index.html */ class ArchitectureTest { - private static JavaClasses importedClasses; + private static JavaClasses importedClasses; - @BeforeAll - static void init() { - //time intensive operation should only be done once - importedClasses = new ClassFileImporter().importPackages("pro.taskana"); - } + @BeforeAll + static void init() { + // time intensive operation should only be done once + importedClasses = new ClassFileImporter().importPackages("pro.taskana"); + } - @Test - void mapperShouldBePlacedInMappingsPackage() { - ArchRule myRule = classes() - .that().haveSimpleNameEndingWith("Mapper") - .should().resideInAPackage("..mappings.."); + @Test + void mapperShouldBePlacedInMappingsPackage() { + ArchRule myRule = + classes() + .that() + .haveSimpleNameEndingWith("Mapper") + .should() + .resideInAPackage("..mappings.."); - myRule.check(importedClasses); - } + myRule.check(importedClasses); + } - @Test - void onlyExceptionsShouldResideInExceptionPackage() { - ArchRule myRule = classes() - .that().resideInAPackage("..exceptions") - .should().beAssignableTo(Throwable.class); - myRule.check(importedClasses); - } + @Test + void onlyExceptionsShouldResideInExceptionPackage() { + ArchRule myRule = + classes().that().resideInAPackage("..exceptions").should().beAssignableTo(Throwable.class); + myRule.check(importedClasses); + } - @Test - void noClassShouldThrowGenericException() { - NO_CLASSES_SHOULD_THROW_GENERIC_EXCEPTIONS.check(importedClasses); - } + @Test + void noClassShouldThrowGenericException() { + NO_CLASSES_SHOULD_THROW_GENERIC_EXCEPTIONS.check(importedClasses); + } - @Test - void noClassShouldAccessStandardStreams() { - NO_CLASSES_SHOULD_ACCESS_STANDARD_STREAMS.check(importedClasses); - } + @Test + void noClassShouldAccessStandardStreams() { + NO_CLASSES_SHOULD_ACCESS_STANDARD_STREAMS.check(importedClasses); + } - @Test - @Disabled - void freeOfCycles() { - ArchRule myRule = slices().matching("pro.taskana.(*)..").should().beFreeOfCycles(); - myRule.check(importedClasses); - } - - @Test - @Disabled - void freeOfCyclicDependencies() { - ArchRule myRule = slices().matching("pro.taskana.(*)..").should().notDependOnEachOther(); - myRule.check(importedClasses); - } + @Test + @Disabled + void freeOfCycles() { + ArchRule myRule = slices().matching("pro.taskana.(*)..").should().beFreeOfCycles(); + myRule.check(importedClasses); + } + @Test + @Disabled + void freeOfCyclicDependencies() { + ArchRule myRule = slices().matching("pro.taskana.(*)..").should().notDependOnEachOther(); + myRule.check(importedClasses); + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/PojoTest.java b/lib/taskana-core/src/test/java/pro/taskana/PojoTest.java index ba9f29684..fc58c8eb6 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/PojoTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/PojoTest.java @@ -1,14 +1,5 @@ package pro.taskana; -import java.util.Collection; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.DynamicTest; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestFactory; - import com.openpojo.reflection.impl.PojoClassFactory; import com.openpojo.validation.ValidatorBuilder; import com.openpojo.validation.rule.Rule; @@ -21,106 +12,110 @@ import com.openpojo.validation.test.impl.GetterTester; import com.openpojo.validation.test.impl.SetterTester; import com.tngtech.archunit.core.domain.JavaClass; import com.tngtech.archunit.core.importer.ClassFileImporter; - +import java.util.Collection; +import java.util.stream.Collectors; +import java.util.stream.Stream; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestFactory; -/** - * check classes with a custom equals and hashcode implementation for correctness. - */ +/** check classes with a custom equals and hashcode implementation for correctness. */ class PojoTest { - @Test - void testsThatPojoClassesAreFound() { - Assertions.assertTrue(getPojoClasses().count() > 0); - } + @Test + void testsThatPojoClassesAreFound() { + Assertions.assertTrue(getPojoClasses().count() > 0); + } - @TestFactory - Collection equalsContract() { - return - getPojoClasses() - .map(cl -> DynamicTest.dynamicTest("Check Hash and Equals for " + cl.getSimpleName(), + @TestFactory + Collection equalsContract() { + return getPojoClasses() + .map( + cl -> + DynamicTest.dynamicTest( + "Check Hash and Equals for " + cl.getSimpleName(), () -> verifyHashAndEquals(cl))) - .collect(Collectors.toList()); - } + .collect(Collectors.toList()); + } - @TestFactory - Collection validateGetters() { - return - getPojoClasses() - .map(cl -> DynamicTest.dynamicTest("Check Getter exist for " + cl.getSimpleName(), - () -> validateWithRules(cl, new GetterMustExistRule()) - )) - .collect(Collectors.toList()); - } + @TestFactory + Collection validateGetters() { + return getPojoClasses() + .map( + cl -> + DynamicTest.dynamicTest( + "Check Getter exist for " + cl.getSimpleName(), + () -> validateWithRules(cl, new GetterMustExistRule()))) + .collect(Collectors.toList()); + } - @TestFactory - Collection validateSetters() { - return - getPojoClasses() - .map(cl -> DynamicTest.dynamicTest("Check Setter for " + cl.getSimpleName(), - () -> validateWithRules(cl, new SetterMustExistRule()) - )) - .collect(Collectors.toList()); - } + @TestFactory + Collection validateSetters() { + return getPojoClasses() + .map( + cl -> + DynamicTest.dynamicTest( + "Check Setter for " + cl.getSimpleName(), + () -> validateWithRules(cl, new SetterMustExistRule()))) + .collect(Collectors.toList()); + } - @TestFactory - Collection validateGetAndSet() { - return - getPojoClasses() - .map(cl -> DynamicTest.dynamicTest("Test set & get " + cl.getSimpleName(), - () -> validateWithTester(cl, new GetterTester(), new SetterTester()) - )) - .collect(Collectors.toList()); - } + @TestFactory + Collection validateGetAndSet() { + return getPojoClasses() + .map( + cl -> + DynamicTest.dynamicTest( + "Test set & get " + cl.getSimpleName(), + () -> validateWithTester(cl, new GetterTester(), new SetterTester()))) + .collect(Collectors.toList()); + } - @TestFactory - Collection validateNoStaticExceptFinalFields() { - return - getPojoClasses() - .map(cl -> DynamicTest.dynamicTest("Check static fields for " + cl.getSimpleName(), - () -> validateWithRules(cl, new NoStaticExceptFinalRule()) - )) - .collect(Collectors.toList()); - } + @TestFactory + Collection validateNoStaticExceptFinalFields() { + return getPojoClasses() + .map( + cl -> + DynamicTest.dynamicTest( + "Check static fields for " + cl.getSimpleName(), + () -> validateWithRules(cl, new NoStaticExceptFinalRule()))) + .collect(Collectors.toList()); + } - @TestFactory - Collection validateNoPublicFields() { - return - getPojoClasses() - .map(cl -> DynamicTest.dynamicTest("Check public fields for " + cl.getSimpleName(), - () -> validateWithRules(cl, new NoPublicFieldsRule()) - )) - .collect(Collectors.toList()); - } + @TestFactory + Collection validateNoPublicFields() { + return getPojoClasses() + .map( + cl -> + DynamicTest.dynamicTest( + "Check public fields for " + cl.getSimpleName(), + () -> validateWithRules(cl, new NoPublicFieldsRule()))) + .collect(Collectors.toList()); + } - private void validateWithRules(Class cl, Rule... rules) { - ValidatorBuilder.create() - .with(rules) - .build() - .validate(PojoClassFactory.getPojoClass(cl)); - } + private void validateWithRules(Class cl, Rule... rules) { + ValidatorBuilder.create().with(rules).build().validate(PojoClassFactory.getPojoClass(cl)); + } - private void validateWithTester(Class cl, Tester... testers) { - ValidatorBuilder.create() - .with(testers) - .build() - .validate(PojoClassFactory.getPojoClass(cl)); - } + private void validateWithTester(Class cl, Tester... testers) { + ValidatorBuilder.create().with(testers).build().validate(PojoClassFactory.getPojoClass(cl)); + } - private void verifyHashAndEquals(Class cl) { - EqualsVerifier.forClass(cl) - .suppress(Warning.NONFINAL_FIELDS, Warning.STRICT_INHERITANCE) - .withRedefinedSuperclass() - .verify(); - } + private void verifyHashAndEquals(Class cl) { + EqualsVerifier.forClass(cl) + .suppress(Warning.NONFINAL_FIELDS, Warning.STRICT_INHERITANCE) + .withRedefinedSuperclass() + .verify(); + } - private Stream> getPojoClasses() { - //TODO how to identify pojos? Is overwritten equals method enough? - return new ClassFileImporter().importPackages("pro.taskana") - .stream() + private Stream> getPojoClasses() { + // TODO how to identify pojos? Is overwritten equals method enough? + return new ClassFileImporter() + .importPackages("pro.taskana").stream() .filter(javaClass -> javaClass.tryGetMethod("equals", Object.class).isPresent()) .map(JavaClass::reflect); - } + } } - diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/CategoryReportBuilderImplTest.java b/lib/taskana-core/src/test/java/pro/taskana/impl/CategoryReportBuilderImplTest.java index b92460af4..66b839c74 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/CategoryReportBuilderImplTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/CategoryReportBuilderImplTest.java @@ -15,7 +15,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -34,106 +33,120 @@ import pro.taskana.impl.report.item.MonitorQueryItem; import pro.taskana.mappings.TaskMonitorMapper; import pro.taskana.report.CategoryReport; -/** - * Unit Test for CategoryBuilderImpl. - */ +/** Unit Test for CategoryBuilderImpl. */ @ExtendWith(MockitoExtension.class) class CategoryReportBuilderImplTest { - @InjectMocks - private TaskMonitorServiceImpl cut; + @InjectMocks private TaskMonitorServiceImpl cut; - @Mock - private InternalTaskanaEngine internalTaskanaEngineMock; + @Mock private InternalTaskanaEngine internalTaskanaEngineMock; - @Mock - private TaskanaEngine taskanaEngineMock; + @Mock private TaskanaEngine taskanaEngineMock; - @Mock - private TaskanaEngineConfiguration taskanaEngineConfiguration; + @Mock private TaskanaEngineConfiguration taskanaEngineConfiguration; - @Mock - private TaskMonitorMapper taskMonitorMapperMock; + @Mock private TaskMonitorMapper taskMonitorMapperMock; - @BeforeEach - void setup() { - when(taskanaEngineMock.getConfiguration()).thenReturn(taskanaEngineConfiguration); - when(internalTaskanaEngineMock.getEngine()).thenReturn(taskanaEngineMock); - when(taskanaEngineConfiguration.isGermanPublicHolidaysEnabled()).thenReturn(true); - when(taskanaEngineConfiguration.getCustomHolidays()).thenReturn(null); - } + @BeforeEach + void setup() { + when(taskanaEngineMock.getConfiguration()).thenReturn(taskanaEngineConfiguration); + when(internalTaskanaEngineMock.getEngine()).thenReturn(taskanaEngineMock); + when(taskanaEngineConfiguration.isGermanPublicHolidaysEnabled()).thenReturn(true); + when(taskanaEngineConfiguration.getCustomHolidays()).thenReturn(null); + } - @Test - void testGetTotalNumbersOfCatgoryReport() throws InvalidArgumentException, NotAuthorizedException { - List workbasketIds = Collections.singletonList("WBI:000000000000000000000000000000000001"); - List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); - List categories = Collections.singletonList("EXTERN"); - List domains = Collections.singletonList("DOMAIN_A"); - List classificationIds = Collections.singletonList("L10000"); - List excludedClassificationIds = Collections.singletonList("L20000"); - Map customAttributeFilter = new HashMap<>(); - customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); + @Test + void testGetTotalNumbersOfCatgoryReport() + throws InvalidArgumentException, NotAuthorizedException { + List workbasketIds = + Collections.singletonList("WBI:000000000000000000000000000000000001"); + List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); + List categories = Collections.singletonList("EXTERN"); + List domains = Collections.singletonList("DOMAIN_A"); + List classificationIds = Collections.singletonList("L10000"); + List excludedClassificationIds = Collections.singletonList("L20000"); + Map customAttributeFilter = new HashMap<>(); + customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); - List expectedResult = new ArrayList<>(); - MonitorQueryItem monitorQueryItem = new MonitorQueryItem(); - monitorQueryItem.setKey("EXTERN"); - monitorQueryItem.setNumberOfTasks(1); - expectedResult.add(monitorQueryItem); - when(taskMonitorMapperMock.getTaskCountOfCategories(workbasketIds, states, categories, domains, - classificationIds, excludedClassificationIds, customAttributeFilter)).thenReturn(expectedResult); - - CategoryReport actualResult = cut.createCategoryReportBuilder() - .workbasketIdIn(workbasketIds) - .stateIn(states) - .categoryIn(categories) - .domainIn(domains) - .classificationIdIn(classificationIds) - .excludedClassificationIdIn(excludedClassificationIds) - .customAttributeFilterIn(customAttributeFilter) - .buildReport(); - - verify(internalTaskanaEngineMock, times(1)).openConnection(); - verify(internalTaskanaEngineMock, times(3)).getEngine(); - verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); - verify(taskanaEngineMock, times(2)).getConfiguration(); - verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); - verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); - verify(taskMonitorMapperMock, times(1)).getTaskCountOfCategories(any(), any(), any(), any(), any(), any(), - any()); - verify(internalTaskanaEngineMock, times(1)).returnConnection(); - verifyNoMoreInteractions(internalTaskanaEngineMock, taskanaEngineMock, taskMonitorMapperMock, - taskanaEngineConfiguration); - - assertNotNull(actualResult); - assertEquals(actualResult.getRow("EXTERN").getTotalValue(), 1); - assertEquals(actualResult.getSumRow().getTotalValue(), 1); - } - - @Test - void testGetCategoryReportWithReportLineItemDefinitions() - throws InvalidArgumentException, NotAuthorizedException { - List workbasketIds = Collections.singletonList("WBI:000000000000000000000000000000000001"); - List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); - List categories = Collections.singletonList("EXTERN"); - List domains = Collections.singletonList("DOMAIN_A"); - List classificationIds = Collections.singletonList("L10000"); - List excludedClassificationIds = Collections.singletonList("L20000"); - Map customAttributeFilter = new HashMap<>(); - customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); - List columnHeaders = Collections.singletonList( - new TimeIntervalColumnHeader(0, 0)); - - List expectedResult = new ArrayList<>(); - MonitorQueryItem monitorQueryItem = new MonitorQueryItem(); - monitorQueryItem.setKey("EXTERN"); - monitorQueryItem.setAgeInDays(0); - monitorQueryItem.setNumberOfTasks(1); - expectedResult.add(monitorQueryItem); - when(taskMonitorMapperMock.getTaskCountOfCategories(workbasketIds, states, categories, domains, + List expectedResult = new ArrayList<>(); + MonitorQueryItem monitorQueryItem = new MonitorQueryItem(); + monitorQueryItem.setKey("EXTERN"); + monitorQueryItem.setNumberOfTasks(1); + expectedResult.add(monitorQueryItem); + when(taskMonitorMapperMock.getTaskCountOfCategories( + workbasketIds, + states, + categories, + domains, classificationIds, - excludedClassificationIds, customAttributeFilter)).thenReturn(expectedResult); + excludedClassificationIds, + customAttributeFilter)) + .thenReturn(expectedResult); - CategoryReport actualResult = cut.createCategoryReportBuilder() + CategoryReport actualResult = + cut.createCategoryReportBuilder() + .workbasketIdIn(workbasketIds) + .stateIn(states) + .categoryIn(categories) + .domainIn(domains) + .classificationIdIn(classificationIds) + .excludedClassificationIdIn(excludedClassificationIds) + .customAttributeFilterIn(customAttributeFilter) + .buildReport(); + + verify(internalTaskanaEngineMock, times(1)).openConnection(); + verify(internalTaskanaEngineMock, times(3)).getEngine(); + verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); + verify(taskanaEngineMock, times(2)).getConfiguration(); + verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); + verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); + verify(taskMonitorMapperMock, times(1)) + .getTaskCountOfCategories(any(), any(), any(), any(), any(), any(), any()); + verify(internalTaskanaEngineMock, times(1)).returnConnection(); + verifyNoMoreInteractions( + internalTaskanaEngineMock, + taskanaEngineMock, + taskMonitorMapperMock, + taskanaEngineConfiguration); + + assertNotNull(actualResult); + assertEquals(actualResult.getRow("EXTERN").getTotalValue(), 1); + assertEquals(actualResult.getSumRow().getTotalValue(), 1); + } + + @Test + void testGetCategoryReportWithReportLineItemDefinitions() + throws InvalidArgumentException, NotAuthorizedException { + List workbasketIds = + Collections.singletonList("WBI:000000000000000000000000000000000001"); + List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); + List categories = Collections.singletonList("EXTERN"); + List domains = Collections.singletonList("DOMAIN_A"); + List classificationIds = Collections.singletonList("L10000"); + List excludedClassificationIds = Collections.singletonList("L20000"); + Map customAttributeFilter = new HashMap<>(); + customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); + List columnHeaders = + Collections.singletonList(new TimeIntervalColumnHeader(0, 0)); + + List expectedResult = new ArrayList<>(); + MonitorQueryItem monitorQueryItem = new MonitorQueryItem(); + monitorQueryItem.setKey("EXTERN"); + monitorQueryItem.setAgeInDays(0); + monitorQueryItem.setNumberOfTasks(1); + expectedResult.add(monitorQueryItem); + when(taskMonitorMapperMock.getTaskCountOfCategories( + workbasketIds, + states, + categories, + domains, + classificationIds, + excludedClassificationIds, + customAttributeFilter)) + .thenReturn(expectedResult); + + CategoryReport actualResult = + cut.createCategoryReportBuilder() .workbasketIdIn(workbasketIds) .stateIn(states) .categoryIn(categories) @@ -144,50 +157,65 @@ class CategoryReportBuilderImplTest { .withColumnHeaders(columnHeaders) .buildReport(); - verify(internalTaskanaEngineMock, times(1)).openConnection(); - verify(internalTaskanaEngineMock, times(3)).getEngine(); - verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); - verify(taskanaEngineMock, times(2)).getConfiguration(); - verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); - verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); - verify(taskMonitorMapperMock, times(1)).getTaskCountOfCategories(any(), any(), any(), any(), any(), any(), - any()); - verify(internalTaskanaEngineMock, times(1)).returnConnection(); - verifyNoMoreInteractions(internalTaskanaEngineMock, taskanaEngineMock, taskMonitorMapperMock, - taskanaEngineConfiguration); + verify(internalTaskanaEngineMock, times(1)).openConnection(); + verify(internalTaskanaEngineMock, times(3)).getEngine(); + verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); + verify(taskanaEngineMock, times(2)).getConfiguration(); + verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); + verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); + verify(taskMonitorMapperMock, times(1)) + .getTaskCountOfCategories(any(), any(), any(), any(), any(), any(), any()); + verify(internalTaskanaEngineMock, times(1)).returnConnection(); + verifyNoMoreInteractions( + internalTaskanaEngineMock, + taskanaEngineMock, + taskMonitorMapperMock, + taskanaEngineConfiguration); - assertNotNull(actualResult); - assertEquals(actualResult.getRow("EXTERN").getTotalValue(), 1); - assertEquals(actualResult.getRow("EXTERN").getCells()[0], 1); - assertEquals(actualResult.getSumRow().getTotalValue(), 1); - } + assertNotNull(actualResult); + assertEquals(actualResult.getRow("EXTERN").getTotalValue(), 1); + assertEquals(actualResult.getRow("EXTERN").getCells()[0], 1); + assertEquals(actualResult.getSumRow().getTotalValue(), 1); + } - @Test - void testListTaskIdsOfCategoryReportForSelectedItems() - throws InvalidArgumentException, NotAuthorizedException { - List workbasketIds = Collections.singletonList("WBI:000000000000000000000000000000000001"); - List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); - List categories = Collections.singletonList("EXTERN"); - List domains = Collections.singletonList("DOMAIN_A"); - List classificationIds = Collections.singletonList("L10000"); - List excludedClassificationIds = Collections.singletonList("L20000"); - Map customAttributeFilter = new HashMap<>(); - customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); - List columnHeaders = Collections.singletonList( - new TimeIntervalColumnHeader(0, 0)); + @Test + void testListTaskIdsOfCategoryReportForSelectedItems() + throws InvalidArgumentException, NotAuthorizedException { + List workbasketIds = + Collections.singletonList("WBI:000000000000000000000000000000000001"); + List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); + List categories = Collections.singletonList("EXTERN"); + List domains = Collections.singletonList("DOMAIN_A"); + List classificationIds = Collections.singletonList("L10000"); + List excludedClassificationIds = Collections.singletonList("L20000"); + Map customAttributeFilter = new HashMap<>(); + customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); + List columnHeaders = + Collections.singletonList(new TimeIntervalColumnHeader(0, 0)); - SelectedItem selectedItem = new SelectedItem(); - selectedItem.setKey("EXTERN"); - selectedItem.setLowerAgeLimit(1); - selectedItem.setUpperAgeLimit(5); - List selectedItems = Collections.singletonList(selectedItem); + SelectedItem selectedItem = new SelectedItem(); + selectedItem.setKey("EXTERN"); + selectedItem.setLowerAgeLimit(1); + selectedItem.setUpperAgeLimit(5); + List selectedItems = Collections.singletonList(selectedItem); - List expectedResult = Collections.singletonList("TKI:000000000000000000000000000000000001"); - when(taskMonitorMapperMock.getTaskIdsForSelectedItems(workbasketIds, - states, categories, domains, classificationIds, excludedClassificationIds, customAttributeFilter, - "CLASSIFICATION_CATEGORY", selectedItems, false)).thenReturn(expectedResult); + List expectedResult = + Collections.singletonList("TKI:000000000000000000000000000000000001"); + when(taskMonitorMapperMock.getTaskIdsForSelectedItems( + workbasketIds, + states, + categories, + domains, + classificationIds, + excludedClassificationIds, + customAttributeFilter, + "CLASSIFICATION_CATEGORY", + selectedItems, + false)) + .thenReturn(expectedResult); - List actualResult = cut.createCategoryReportBuilder() + List actualResult = + cut.createCategoryReportBuilder() .workbasketIdIn(workbasketIds) .stateIn(states) .categoryIn(categories) @@ -198,57 +226,70 @@ class CategoryReportBuilderImplTest { .withColumnHeaders(columnHeaders) .listTaskIdsForSelectedItems(selectedItems); - verify(internalTaskanaEngineMock, times(1)).openConnection(); - verify(internalTaskanaEngineMock, times(3)).getEngine(); - verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); - verify(taskanaEngineMock, times(2)).getConfiguration(); - verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); - verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); - verify(taskMonitorMapperMock, times(1)) - .getTaskIdsForSelectedItems(any(), any(), any(), any(), any(), any(), any(), any(), any(), eq(false)); - verify(internalTaskanaEngineMock, times(1)).returnConnection(); - verifyNoMoreInteractions(internalTaskanaEngineMock, taskanaEngineMock, taskMonitorMapperMock, - taskanaEngineConfiguration); + verify(internalTaskanaEngineMock, times(1)).openConnection(); + verify(internalTaskanaEngineMock, times(3)).getEngine(); + verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); + verify(taskanaEngineMock, times(2)).getConfiguration(); + verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); + verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); + verify(taskMonitorMapperMock, times(1)) + .getTaskIdsForSelectedItems( + any(), any(), any(), any(), any(), any(), any(), any(), any(), eq(false)); + verify(internalTaskanaEngineMock, times(1)).returnConnection(); + verifyNoMoreInteractions( + internalTaskanaEngineMock, + taskanaEngineMock, + taskMonitorMapperMock, + taskanaEngineConfiguration); - assertNotNull(actualResult); - assertEquals(expectedResult, actualResult); - } + assertNotNull(actualResult); + assertEquals(expectedResult, actualResult); + } - @Test - void testListTaskIdsForSelectedItemsIsEmptyResult() throws NotAuthorizedException, InvalidArgumentException { - SelectedItem selectedItem = new SelectedItem(); - List selectedItems = Collections.singletonList(selectedItem); - List result = cut.createCategoryReportBuilder() - .listTaskIdsForSelectedItems(selectedItems); - assertNotNull(result); - } + @Test + void testListTaskIdsForSelectedItemsIsEmptyResult() + throws NotAuthorizedException, InvalidArgumentException { + SelectedItem selectedItem = new SelectedItem(); + List selectedItems = Collections.singletonList(selectedItem); + List result = + cut.createCategoryReportBuilder().listTaskIdsForSelectedItems(selectedItems); + assertNotNull(result); + } - @Test - void testListCustomAttributeValuesForCustomAttributeName() - throws NotAuthorizedException { - List workbasketIds = Collections.singletonList("WBI:000000000000000000000000000000000001"); - List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); - List categories = Collections.singletonList("EXTERN"); - List domains = Collections.singletonList("DOMAIN_A"); - List classificationIds = Collections.singletonList("L10000"); - List excludedClassificationIds = Collections.singletonList("L20000"); - Map customAttributeFilter = new HashMap<>(); - customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); - List columnHeaders = Collections.singletonList( - new TimeIntervalColumnHeader(0, 0)); + @Test + void testListCustomAttributeValuesForCustomAttributeName() throws NotAuthorizedException { + List workbasketIds = + Collections.singletonList("WBI:000000000000000000000000000000000001"); + List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); + List categories = Collections.singletonList("EXTERN"); + List domains = Collections.singletonList("DOMAIN_A"); + List classificationIds = Collections.singletonList("L10000"); + List excludedClassificationIds = Collections.singletonList("L20000"); + Map customAttributeFilter = new HashMap<>(); + customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); + List columnHeaders = + Collections.singletonList(new TimeIntervalColumnHeader(0, 0)); - SelectedItem selectedItem = new SelectedItem(); - selectedItem.setKey("EXTERN"); - selectedItem.setLowerAgeLimit(1); - selectedItem.setUpperAgeLimit(5); - List selectedItems = Collections.singletonList(selectedItem); + SelectedItem selectedItem = new SelectedItem(); + selectedItem.setKey("EXTERN"); + selectedItem.setLowerAgeLimit(1); + selectedItem.setUpperAgeLimit(5); + List selectedItems = Collections.singletonList(selectedItem); - List expectedResult = Collections.singletonList("Geschaeftsstelle A"); - when(taskMonitorMapperMock.getCustomAttributeValuesForReport(workbasketIds, - states, categories, domains, classificationIds, excludedClassificationIds, customAttributeFilter, - CustomField.CUSTOM_1)).thenReturn(expectedResult); + List expectedResult = Collections.singletonList("Geschaeftsstelle A"); + when(taskMonitorMapperMock.getCustomAttributeValuesForReport( + workbasketIds, + states, + categories, + domains, + classificationIds, + excludedClassificationIds, + customAttributeFilter, + CustomField.CUSTOM_1)) + .thenReturn(expectedResult); - List actualResult = cut.createCategoryReportBuilder() + List actualResult = + cut.createCategoryReportBuilder() .workbasketIdIn(workbasketIds) .stateIn(states) .categoryIn(categories) @@ -259,27 +300,32 @@ class CategoryReportBuilderImplTest { .withColumnHeaders(columnHeaders) .listCustomAttributeValuesForCustomAttributeName(CustomField.CUSTOM_1); - verify(internalTaskanaEngineMock, times(1)).openConnection(); - verify(internalTaskanaEngineMock, times(3)).getEngine(); - verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); - verify(taskanaEngineMock, times(2)).getConfiguration(); - verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); - verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); - verify(taskMonitorMapperMock, times(1)) - .getCustomAttributeValuesForReport(any(), any(), any(), any(), any(), any(), any(), any()); - verify(internalTaskanaEngineMock, times(1)).returnConnection(); - verifyNoMoreInteractions(internalTaskanaEngineMock, taskanaEngineMock, taskMonitorMapperMock, - taskanaEngineConfiguration); + verify(internalTaskanaEngineMock, times(1)).openConnection(); + verify(internalTaskanaEngineMock, times(3)).getEngine(); + verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); + verify(taskanaEngineMock, times(2)).getConfiguration(); + verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); + verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); + verify(taskMonitorMapperMock, times(1)) + .getCustomAttributeValuesForReport(any(), any(), any(), any(), any(), any(), any(), any()); + verify(internalTaskanaEngineMock, times(1)).returnConnection(); + verifyNoMoreInteractions( + internalTaskanaEngineMock, + taskanaEngineMock, + taskMonitorMapperMock, + taskanaEngineConfiguration); - assertNotNull(actualResult); - assertEquals(expectedResult, actualResult); - } + assertNotNull(actualResult); + assertEquals(expectedResult, actualResult); + } - @Test - void testListCustomAttributeValuesForCustomAttributeNameIsEmptyResult() throws NotAuthorizedException { - List result = cut.createCategoryReportBuilder() + @Test + void testListCustomAttributeValuesForCustomAttributeNameIsEmptyResult() + throws NotAuthorizedException { + List result = + cut.createCategoryReportBuilder() .workbasketIdIn(Arrays.asList("DieGibtsSicherNed")) .listCustomAttributeValuesForCustomAttributeName(CustomField.CUSTOM_1); - assertNotNull(result); - } + assertNotNull(result); + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/ClassificationQueryImplTest.java b/lib/taskana-core/src/test/java/pro/taskana/impl/ClassificationQueryImplTest.java index 9c112e41a..5664c3378 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/ClassificationQueryImplTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/ClassificationQueryImplTest.java @@ -6,7 +6,6 @@ import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; - import org.apache.ibatis.session.SqlSession; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -21,55 +20,57 @@ import pro.taskana.ClassificationSummary; * * @author EH */ - @ExtendWith(MockitoExtension.class) class ClassificationQueryImplTest { - @InjectMocks - private ClassificationQueryImpl classificationQueryImpl; + @InjectMocks private ClassificationQueryImpl classificationQueryImpl; - @Mock - private InternalTaskanaEngine internalTaskanaEngine; + @Mock private InternalTaskanaEngine internalTaskanaEngine; - @Mock - private SqlSession sqlSession; + @Mock private SqlSession sqlSession; - @Test - void should_ReturnList_when_BuilderIsUsed() { - when(internalTaskanaEngine.getSqlSession()).thenReturn(sqlSession); - when(sqlSession.selectList(any(), any())).thenReturn(new ArrayList<>()); + @Test + void should_ReturnList_when_BuilderIsUsed() { + when(internalTaskanaEngine.getSqlSession()).thenReturn(sqlSession); + when(sqlSession.selectList(any(), any())).thenReturn(new ArrayList<>()); - List result = classificationQueryImpl.nameIn("test", "asd", "blubber") + List result = + classificationQueryImpl + .nameIn("test", "asd", "blubber") .typeIn("cool", "bla") .priorityIn(1, 2) .parentIdIn("superId") .list(); - assertNotNull(result); - } + assertNotNull(result); + } - @Test - void should_ReturnListWithOffset_when_BuilderIsUsed() { - when(internalTaskanaEngine.getSqlSession()).thenReturn(sqlSession); - when(sqlSession.selectList(any(), any(), any())).thenReturn(new ArrayList<>()); + @Test + void should_ReturnListWithOffset_when_BuilderIsUsed() { + when(internalTaskanaEngine.getSqlSession()).thenReturn(sqlSession); + when(sqlSession.selectList(any(), any(), any())).thenReturn(new ArrayList<>()); - List result = classificationQueryImpl.nameIn("test", "asd", "blubber") + List result = + classificationQueryImpl + .nameIn("test", "asd", "blubber") .typeIn("cool", "bla") .priorityIn(1, 2) .parentIdIn("superId") .list(1, 1); - assertNotNull(result); - } + assertNotNull(result); + } - @Test - void should_ReturnOneItem_when_BuilderIsUsed() { - when(internalTaskanaEngine.getSqlSession()).thenReturn(sqlSession); - when(sqlSession.selectOne(any(), any())).thenReturn(new ClassificationSummaryImpl()); + @Test + void should_ReturnOneItem_when_BuilderIsUsed() { + when(internalTaskanaEngine.getSqlSession()).thenReturn(sqlSession); + when(sqlSession.selectOne(any(), any())).thenReturn(new ClassificationSummaryImpl()); - ClassificationSummary result = classificationQueryImpl.nameIn("test", "asd", "blubber") + ClassificationSummary result = + classificationQueryImpl + .nameIn("test", "asd", "blubber") .typeIn("cool", "bla") .priorityIn(1, 2) .parentIdIn("superId") .single(); - assertNotNull(result); - } + assertNotNull(result); + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/ClassificationReportBuilderImplTest.java b/lib/taskana-core/src/test/java/pro/taskana/impl/ClassificationReportBuilderImplTest.java index 73d13f934..00eb1490f 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/ClassificationReportBuilderImplTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/ClassificationReportBuilderImplTest.java @@ -15,7 +15,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -37,55 +36,58 @@ import pro.taskana.mappings.TaskMonitorMapper; import pro.taskana.report.ClassificationReport; import pro.taskana.report.ClassificationReport.DetailedClassificationReport; -/** - * Unit Test for ClassificationReportBuilderImpl. - */ +/** Unit Test for ClassificationReportBuilderImpl. */ @ExtendWith(MockitoExtension.class) class ClassificationReportBuilderImplTest { - @InjectMocks - private TaskMonitorServiceImpl cut; + @InjectMocks private TaskMonitorServiceImpl cut; - @Mock - private InternalTaskanaEngine internalTaskanaEngineMock; + @Mock private InternalTaskanaEngine internalTaskanaEngineMock; - @Mock - private TaskanaEngine taskanaEngineMock; + @Mock private TaskanaEngine taskanaEngineMock; - @Mock - private TaskanaEngineConfiguration taskanaEngineConfiguration; + @Mock private TaskanaEngineConfiguration taskanaEngineConfiguration; - @Mock - private TaskMonitorMapper taskMonitorMapperMock; + @Mock private TaskMonitorMapper taskMonitorMapperMock; - @BeforeEach - void setup() { - when(internalTaskanaEngineMock.getEngine()).thenReturn(taskanaEngineMock); - when(taskanaEngineMock.getConfiguration()).thenReturn(taskanaEngineConfiguration); - when(taskanaEngineConfiguration.isGermanPublicHolidaysEnabled()).thenReturn(true); - when(taskanaEngineConfiguration.getCustomHolidays()).thenReturn(null); - } + @BeforeEach + void setup() { + when(internalTaskanaEngineMock.getEngine()).thenReturn(taskanaEngineMock); + when(taskanaEngineMock.getConfiguration()).thenReturn(taskanaEngineConfiguration); + when(taskanaEngineConfiguration.isGermanPublicHolidaysEnabled()).thenReturn(true); + when(taskanaEngineConfiguration.getCustomHolidays()).thenReturn(null); + } - @Test - void testGetTotalNumbersOfClassificationReport() throws InvalidArgumentException, NotAuthorizedException { - List workbasketIds = Collections.singletonList("WBI:000000000000000000000000000000000001"); - List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); - List categories = Collections.singletonList("EXTERN"); - List domains = Collections.singletonList("DOMAIN_A"); - List classificationIds = Collections.singletonList("L10000"); - List excludedClassificationIds = Collections.singletonList("L20000"); - Map customAttributeFilter = new HashMap<>(); - customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); + @Test + void testGetTotalNumbersOfClassificationReport() + throws InvalidArgumentException, NotAuthorizedException { + List workbasketIds = + Collections.singletonList("WBI:000000000000000000000000000000000001"); + List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); + List categories = Collections.singletonList("EXTERN"); + List domains = Collections.singletonList("DOMAIN_A"); + List classificationIds = Collections.singletonList("L10000"); + List excludedClassificationIds = Collections.singletonList("L20000"); + Map customAttributeFilter = new HashMap<>(); + customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); - List expectedResult = new ArrayList<>(); - MonitorQueryItem monitorQueryItem = new MonitorQueryItem(); - monitorQueryItem.setKey("CLI:000000000000000000000000000000000001"); - monitorQueryItem.setNumberOfTasks(1); - expectedResult.add(monitorQueryItem); - when(taskMonitorMapperMock.getTaskCountOfClassifications(workbasketIds, states, categories, domains, - classificationIds, excludedClassificationIds, customAttributeFilter)).thenReturn(expectedResult); + List expectedResult = new ArrayList<>(); + MonitorQueryItem monitorQueryItem = new MonitorQueryItem(); + monitorQueryItem.setKey("CLI:000000000000000000000000000000000001"); + monitorQueryItem.setNumberOfTasks(1); + expectedResult.add(monitorQueryItem); + when(taskMonitorMapperMock.getTaskCountOfClassifications( + workbasketIds, + states, + categories, + domains, + classificationIds, + excludedClassificationIds, + customAttributeFilter)) + .thenReturn(expectedResult); - ClassificationReport actualResult = cut.createClassificationReportBuilder() + ClassificationReport actualResult = + cut.createClassificationReportBuilder() .workbasketIdIn(workbasketIds) .stateIn(states) .categoryIn(categories) @@ -95,49 +97,61 @@ class ClassificationReportBuilderImplTest { .customAttributeFilterIn(customAttributeFilter) .buildReport(); - verify(internalTaskanaEngineMock, times(1)).openConnection(); - verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); - verify(taskanaEngineMock, times(2)).getConfiguration(); - verify(internalTaskanaEngineMock, times(3)).getEngine(); - verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); - verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); - verify(taskMonitorMapperMock, times(1)).getTaskCountOfClassifications(any(), any(), any(), any(), any(), any(), - any()); - verify(internalTaskanaEngineMock, times(1)).returnConnection(); - verifyNoMoreInteractions(internalTaskanaEngineMock, taskanaEngineMock, taskMonitorMapperMock, - taskanaEngineConfiguration); + verify(internalTaskanaEngineMock, times(1)).openConnection(); + verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); + verify(taskanaEngineMock, times(2)).getConfiguration(); + verify(internalTaskanaEngineMock, times(3)).getEngine(); + verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); + verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); + verify(taskMonitorMapperMock, times(1)) + .getTaskCountOfClassifications(any(), any(), any(), any(), any(), any(), any()); + verify(internalTaskanaEngineMock, times(1)).returnConnection(); + verifyNoMoreInteractions( + internalTaskanaEngineMock, + taskanaEngineMock, + taskMonitorMapperMock, + taskanaEngineConfiguration); - assertNotNull(actualResult); - assertEquals( - actualResult.getRow("CLI:000000000000000000000000000000000001").getTotalValue(), 1); - assertEquals(actualResult.getSumRow().getTotalValue(), 1); - } + assertNotNull(actualResult); + assertEquals( + actualResult.getRow("CLI:000000000000000000000000000000000001").getTotalValue(), 1); + assertEquals(actualResult.getSumRow().getTotalValue(), 1); + } - @Test - void testGetClassificationReportWithReportLineItemDefinitions() - throws InvalidArgumentException, NotAuthorizedException { - List workbasketIds = Collections.singletonList("WBI:000000000000000000000000000000000001"); - List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); - List categories = Collections.singletonList("EXTERN"); - List domains = Collections.singletonList("DOMAIN_A"); - List classificationIds = Collections.singletonList("L10000"); - List excludedClassificationIds = Collections.singletonList("L20000"); - Map customAttributeFilter = new HashMap<>(); - customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); + @Test + void testGetClassificationReportWithReportLineItemDefinitions() + throws InvalidArgumentException, NotAuthorizedException { + List workbasketIds = + Collections.singletonList("WBI:000000000000000000000000000000000001"); + List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); + List categories = Collections.singletonList("EXTERN"); + List domains = Collections.singletonList("DOMAIN_A"); + List classificationIds = Collections.singletonList("L10000"); + List excludedClassificationIds = Collections.singletonList("L20000"); + Map customAttributeFilter = new HashMap<>(); + customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); - List columnHeaders = Collections.singletonList( - new TimeIntervalColumnHeader(0, 0)); + List columnHeaders = + Collections.singletonList(new TimeIntervalColumnHeader(0, 0)); - List expectedResult = new ArrayList<>(); - MonitorQueryItem monitorQueryItem = new MonitorQueryItem(); - monitorQueryItem.setKey("CLI:000000000000000000000000000000000001"); - monitorQueryItem.setAgeInDays(0); - monitorQueryItem.setNumberOfTasks(1); - expectedResult.add(monitorQueryItem); - when(taskMonitorMapperMock.getTaskCountOfClassifications(workbasketIds, states, categories, domains, - classificationIds, excludedClassificationIds, customAttributeFilter)).thenReturn(expectedResult); + List expectedResult = new ArrayList<>(); + MonitorQueryItem monitorQueryItem = new MonitorQueryItem(); + monitorQueryItem.setKey("CLI:000000000000000000000000000000000001"); + monitorQueryItem.setAgeInDays(0); + monitorQueryItem.setNumberOfTasks(1); + expectedResult.add(monitorQueryItem); + when(taskMonitorMapperMock.getTaskCountOfClassifications( + workbasketIds, + states, + categories, + domains, + classificationIds, + excludedClassificationIds, + customAttributeFilter)) + .thenReturn(expectedResult); - ClassificationReport actualResult = cut.createClassificationReportBuilder() + ClassificationReport actualResult = + cut.createClassificationReportBuilder() .workbasketIdIn(workbasketIds) .stateIn(states) .categoryIn(categories) @@ -148,48 +162,60 @@ class ClassificationReportBuilderImplTest { .withColumnHeaders(columnHeaders) .buildReport(); - verify(internalTaskanaEngineMock, times(1)).openConnection(); - verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); - verify(taskanaEngineMock, times(2)).getConfiguration(); - verify(internalTaskanaEngineMock, times(3)).getEngine(); + verify(internalTaskanaEngineMock, times(1)).openConnection(); + verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); + verify(taskanaEngineMock, times(2)).getConfiguration(); + verify(internalTaskanaEngineMock, times(3)).getEngine(); - verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); - verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); - verify(taskMonitorMapperMock, times(1)).getTaskCountOfClassifications(any(), any(), any(), any(), any(), any(), - any()); - verify(internalTaskanaEngineMock, times(1)).returnConnection(); - verifyNoMoreInteractions(internalTaskanaEngineMock, taskanaEngineMock, taskMonitorMapperMock, - taskanaEngineConfiguration); + verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); + verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); + verify(taskMonitorMapperMock, times(1)) + .getTaskCountOfClassifications(any(), any(), any(), any(), any(), any(), any()); + verify(internalTaskanaEngineMock, times(1)).returnConnection(); + verifyNoMoreInteractions( + internalTaskanaEngineMock, + taskanaEngineMock, + taskMonitorMapperMock, + taskanaEngineConfiguration); - assertNotNull(actualResult); - assertEquals( - actualResult.getRow("CLI:000000000000000000000000000000000001").getTotalValue(), 1); - assertEquals(actualResult.getRow("CLI:000000000000000000000000000000000001").getCells()[0], 1); - assertEquals(actualResult.getSumRow().getTotalValue(), 1); - } + assertNotNull(actualResult); + assertEquals( + actualResult.getRow("CLI:000000000000000000000000000000000001").getTotalValue(), 1); + assertEquals(actualResult.getRow("CLI:000000000000000000000000000000000001").getCells()[0], 1); + assertEquals(actualResult.getSumRow().getTotalValue(), 1); + } - @Test - void testGetTotalNumbersOfDetailedClassificationReport() - throws InvalidArgumentException, NotAuthorizedException { - List workbasketIds = Collections.singletonList("WBI:000000000000000000000000000000000001"); - List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); - List categories = Collections.singletonList("EXTERN"); - List domains = Collections.singletonList("DOMAIN_A"); - List classificationIds = Collections.singletonList("L10000"); - List excludedClassificationIds = Collections.singletonList("L20000"); - Map customAttributeFilter = new HashMap<>(); - customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); + @Test + void testGetTotalNumbersOfDetailedClassificationReport() + throws InvalidArgumentException, NotAuthorizedException { + List workbasketIds = + Collections.singletonList("WBI:000000000000000000000000000000000001"); + List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); + List categories = Collections.singletonList("EXTERN"); + List domains = Collections.singletonList("DOMAIN_A"); + List classificationIds = Collections.singletonList("L10000"); + List excludedClassificationIds = Collections.singletonList("L20000"); + Map customAttributeFilter = new HashMap<>(); + customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); - List expectedResult = new ArrayList<>(); - DetailedMonitorQueryItem detailedMonitorQueryItem = new DetailedMonitorQueryItem(); - detailedMonitorQueryItem.setKey("CLI:000000000000000000000000000000000001"); - detailedMonitorQueryItem.setAttachmentKey("CLI:000000000000000000000000000000000006"); - detailedMonitorQueryItem.setNumberOfTasks(1); - expectedResult.add(detailedMonitorQueryItem); - when(taskMonitorMapperMock.getTaskCountOfDetailedClassifications(workbasketIds, states, categories, domains, - classificationIds, excludedClassificationIds, customAttributeFilter)).thenReturn(expectedResult); + List expectedResult = new ArrayList<>(); + DetailedMonitorQueryItem detailedMonitorQueryItem = new DetailedMonitorQueryItem(); + detailedMonitorQueryItem.setKey("CLI:000000000000000000000000000000000001"); + detailedMonitorQueryItem.setAttachmentKey("CLI:000000000000000000000000000000000006"); + detailedMonitorQueryItem.setNumberOfTasks(1); + expectedResult.add(detailedMonitorQueryItem); + when(taskMonitorMapperMock.getTaskCountOfDetailedClassifications( + workbasketIds, + states, + categories, + domains, + classificationIds, + excludedClassificationIds, + customAttributeFilter)) + .thenReturn(expectedResult); - DetailedClassificationReport actualResult = cut.createClassificationReportBuilder() + DetailedClassificationReport actualResult = + cut.createClassificationReportBuilder() .workbasketIdIn(workbasketIds) .stateIn(states) .categoryIn(categories) @@ -199,51 +225,64 @@ class ClassificationReportBuilderImplTest { .customAttributeFilterIn(customAttributeFilter) .buildDetailedReport(); - verify(internalTaskanaEngineMock, times(1)).openConnection(); - verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); - verify(taskanaEngineMock, times(2)).getConfiguration(); - verify(internalTaskanaEngineMock, times(3)).getEngine(); - verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); - verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); - verify(taskMonitorMapperMock, times(1)).getTaskCountOfDetailedClassifications(any(), any(), any(), any(), any(), - any(), - any()); - verify(internalTaskanaEngineMock, times(1)).returnConnection(); - verifyNoMoreInteractions(internalTaskanaEngineMock, taskanaEngineMock, taskMonitorMapperMock, - taskanaEngineConfiguration); + verify(internalTaskanaEngineMock, times(1)).openConnection(); + verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); + verify(taskanaEngineMock, times(2)).getConfiguration(); + verify(internalTaskanaEngineMock, times(3)).getEngine(); + verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); + verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); + verify(taskMonitorMapperMock, times(1)) + .getTaskCountOfDetailedClassifications(any(), any(), any(), any(), any(), any(), any()); + verify(internalTaskanaEngineMock, times(1)).returnConnection(); + verifyNoMoreInteractions( + internalTaskanaEngineMock, + taskanaEngineMock, + taskMonitorMapperMock, + taskanaEngineConfiguration); - FoldableRow line = actualResult.getRow("CLI:000000000000000000000000000000000001"); - assertNotNull(actualResult); - assertEquals(line.getTotalValue(), 1); - assertEquals(line.getFoldableRow("CLI:000000000000000000000000000000000006").getTotalValue(), 1); - assertEquals(actualResult.getSumRow().getTotalValue(), 1); - } + FoldableRow line = + actualResult.getRow("CLI:000000000000000000000000000000000001"); + assertNotNull(actualResult); + assertEquals(line.getTotalValue(), 1); + assertEquals( + line.getFoldableRow("CLI:000000000000000000000000000000000006").getTotalValue(), 1); + assertEquals(actualResult.getSumRow().getTotalValue(), 1); + } - @Test - void testGetDetailedClassificationReportWithReportLineItemDefinitions() - throws InvalidArgumentException, NotAuthorizedException { - List workbasketIds = Collections.singletonList("WBI:000000000000000000000000000000000001"); - List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); - List categories = Collections.singletonList("EXTERN"); - List domains = Collections.singletonList("DOMAIN_A"); - List classificationIds = Collections.singletonList("L10000"); - List excludedClassificationIds = Collections.singletonList("L20000"); - Map customAttributeFilter = new HashMap<>(); - customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); - List columnHeaders = Collections.singletonList( - new TimeIntervalColumnHeader(0, 0)); + @Test + void testGetDetailedClassificationReportWithReportLineItemDefinitions() + throws InvalidArgumentException, NotAuthorizedException { + List workbasketIds = + Collections.singletonList("WBI:000000000000000000000000000000000001"); + List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); + List categories = Collections.singletonList("EXTERN"); + List domains = Collections.singletonList("DOMAIN_A"); + List classificationIds = Collections.singletonList("L10000"); + List excludedClassificationIds = Collections.singletonList("L20000"); + Map customAttributeFilter = new HashMap<>(); + customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); + List columnHeaders = + Collections.singletonList(new TimeIntervalColumnHeader(0, 0)); - List expectedResult = new ArrayList<>(); - DetailedMonitorQueryItem detailedMonitorQueryItem = new DetailedMonitorQueryItem(); - detailedMonitorQueryItem.setKey("CLI:000000000000000000000000000000000001"); - detailedMonitorQueryItem.setAttachmentKey("CLI:000000000000000000000000000000000006"); - detailedMonitorQueryItem.setAgeInDays(0); - detailedMonitorQueryItem.setNumberOfTasks(1); - expectedResult.add(detailedMonitorQueryItem); - when(taskMonitorMapperMock.getTaskCountOfDetailedClassifications(workbasketIds, states, categories, domains, - classificationIds, excludedClassificationIds, customAttributeFilter)).thenReturn(expectedResult); + List expectedResult = new ArrayList<>(); + DetailedMonitorQueryItem detailedMonitorQueryItem = new DetailedMonitorQueryItem(); + detailedMonitorQueryItem.setKey("CLI:000000000000000000000000000000000001"); + detailedMonitorQueryItem.setAttachmentKey("CLI:000000000000000000000000000000000006"); + detailedMonitorQueryItem.setAgeInDays(0); + detailedMonitorQueryItem.setNumberOfTasks(1); + expectedResult.add(detailedMonitorQueryItem); + when(taskMonitorMapperMock.getTaskCountOfDetailedClassifications( + workbasketIds, + states, + categories, + domains, + classificationIds, + excludedClassificationIds, + customAttributeFilter)) + .thenReturn(expectedResult); - DetailedClassificationReport actualResult = cut.createClassificationReportBuilder() + DetailedClassificationReport actualResult = + cut.createClassificationReportBuilder() .workbasketIdIn(workbasketIds) .stateIn(states) .categoryIn(categories) @@ -254,54 +293,70 @@ class ClassificationReportBuilderImplTest { .withColumnHeaders(columnHeaders) .buildDetailedReport(); - verify(internalTaskanaEngineMock, times(1)).openConnection(); - verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); - verify(taskanaEngineMock, times(2)).getConfiguration(); - verify(internalTaskanaEngineMock, times(3)).getEngine(); - verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); - verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); - verify(taskMonitorMapperMock, times(1)).getTaskCountOfDetailedClassifications(any(), any(), any(), any(), any(), - any(), - any()); - verify(internalTaskanaEngineMock, times(1)).returnConnection(); - verifyNoMoreInteractions(internalTaskanaEngineMock, taskanaEngineMock, taskMonitorMapperMock, - taskanaEngineConfiguration); + verify(internalTaskanaEngineMock, times(1)).openConnection(); + verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); + verify(taskanaEngineMock, times(2)).getConfiguration(); + verify(internalTaskanaEngineMock, times(3)).getEngine(); + verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); + verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); + verify(taskMonitorMapperMock, times(1)) + .getTaskCountOfDetailedClassifications(any(), any(), any(), any(), any(), any(), any()); + verify(internalTaskanaEngineMock, times(1)).returnConnection(); + verifyNoMoreInteractions( + internalTaskanaEngineMock, + taskanaEngineMock, + taskMonitorMapperMock, + taskanaEngineConfiguration); - FoldableRow line = actualResult.getRow("CLI:000000000000000000000000000000000001"); - assertNotNull(actualResult); - assertEquals(line.getTotalValue(), 1); - assertEquals(line.getFoldableRow("CLI:000000000000000000000000000000000006").getTotalValue(), 1); - assertEquals(line.getCells()[0], 1); - assertEquals(line.getFoldableRow("CLI:000000000000000000000000000000000006").getCells()[0], 1); - assertEquals(actualResult.getSumRow().getTotalValue(), 1); - assertEquals(actualResult.getSumRow().getCells()[0], 1); - } + FoldableRow line = + actualResult.getRow("CLI:000000000000000000000000000000000001"); + assertNotNull(actualResult); + assertEquals(line.getTotalValue(), 1); + assertEquals( + line.getFoldableRow("CLI:000000000000000000000000000000000006").getTotalValue(), 1); + assertEquals(line.getCells()[0], 1); + assertEquals(line.getFoldableRow("CLI:000000000000000000000000000000000006").getCells()[0], 1); + assertEquals(actualResult.getSumRow().getTotalValue(), 1); + assertEquals(actualResult.getSumRow().getCells()[0], 1); + } - @Test - void testGetTaskIdsForSelectedItems() throws InvalidArgumentException, NotAuthorizedException { - List workbasketIds = Collections.singletonList("WBI:000000000000000000000000000000000001"); - List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); - List categories = Collections.singletonList("EXTERN"); - List domains = Collections.singletonList("DOMAIN_A"); - List classificationIds = Collections.singletonList("L10000"); - List excludedClassificationIds = Collections.singletonList("L20000"); - Map customAttributeFilter = new HashMap<>(); - customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); - List columnHeaders = Collections.singletonList( - new TimeIntervalColumnHeader(0, 0)); + @Test + void testGetTaskIdsForSelectedItems() throws InvalidArgumentException, NotAuthorizedException { + List workbasketIds = + Collections.singletonList("WBI:000000000000000000000000000000000001"); + List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); + List categories = Collections.singletonList("EXTERN"); + List domains = Collections.singletonList("DOMAIN_A"); + List classificationIds = Collections.singletonList("L10000"); + List excludedClassificationIds = Collections.singletonList("L20000"); + Map customAttributeFilter = new HashMap<>(); + customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); + List columnHeaders = + Collections.singletonList(new TimeIntervalColumnHeader(0, 0)); - SelectedItem selectedItem = new SelectedItem(); - selectedItem.setKey("EXTERN"); - selectedItem.setLowerAgeLimit(1); - selectedItem.setUpperAgeLimit(5); - List selectedItems = Collections.singletonList(selectedItem); + SelectedItem selectedItem = new SelectedItem(); + selectedItem.setKey("EXTERN"); + selectedItem.setLowerAgeLimit(1); + selectedItem.setUpperAgeLimit(5); + List selectedItems = Collections.singletonList(selectedItem); - List expectedResult = Collections.singletonList("TKI:000000000000000000000000000000000001"); - when(taskMonitorMapperMock.getTaskIdsForSelectedItems(workbasketIds, - states, categories, domains, classificationIds, excludedClassificationIds, customAttributeFilter, - "CLASSIFICATION_KEY", selectedItems, false)).thenReturn(expectedResult); + List expectedResult = + Collections.singletonList("TKI:000000000000000000000000000000000001"); + when(taskMonitorMapperMock.getTaskIdsForSelectedItems( + workbasketIds, + states, + categories, + domains, + classificationIds, + excludedClassificationIds, + customAttributeFilter, + "CLASSIFICATION_KEY", + selectedItems, + false)) + .thenReturn(expectedResult); - List actualResult = cut.createClassificationReportBuilder() + List actualResult = + cut.createClassificationReportBuilder() .workbasketIdIn(workbasketIds) .stateIn(states) .categoryIn(categories) @@ -312,59 +367,73 @@ class ClassificationReportBuilderImplTest { .withColumnHeaders(columnHeaders) .listTaskIdsForSelectedItems(selectedItems); - verify(internalTaskanaEngineMock, times(1)).openConnection(); - verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); - verify(taskanaEngineMock, times(2)).getConfiguration(); - verify(internalTaskanaEngineMock, times(3)).getEngine(); - verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); - verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); - verify(taskMonitorMapperMock, times(1)) - .getTaskIdsForSelectedItems(any(), any(), any(), any(), any(), any(), any(), any(), any(), eq(false)); - verify(internalTaskanaEngineMock, times(1)).returnConnection(); - verifyNoMoreInteractions(internalTaskanaEngineMock, taskanaEngineMock, taskMonitorMapperMock, - taskanaEngineConfiguration); + verify(internalTaskanaEngineMock, times(1)).openConnection(); + verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); + verify(taskanaEngineMock, times(2)).getConfiguration(); + verify(internalTaskanaEngineMock, times(3)).getEngine(); + verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); + verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); + verify(taskMonitorMapperMock, times(1)) + .getTaskIdsForSelectedItems( + any(), any(), any(), any(), any(), any(), any(), any(), any(), eq(false)); + verify(internalTaskanaEngineMock, times(1)).returnConnection(); + verifyNoMoreInteractions( + internalTaskanaEngineMock, + taskanaEngineMock, + taskMonitorMapperMock, + taskanaEngineConfiguration); - assertNotNull(actualResult); - assertEquals(expectedResult, actualResult); - } + assertNotNull(actualResult); + assertEquals(expectedResult, actualResult); + } - @Test - void testGetTaskIdsForSelectedItemsIsEmptyResult() throws NotAuthorizedException, InvalidArgumentException { - SelectedItem selectedItem = new SelectedItem(); - selectedItem.setKey("GIBTSNED"); - List selectedItems = Collections.singletonList(selectedItem); - List result = cut.createClassificationReportBuilder() + @Test + void testGetTaskIdsForSelectedItemsIsEmptyResult() + throws NotAuthorizedException, InvalidArgumentException { + SelectedItem selectedItem = new SelectedItem(); + selectedItem.setKey("GIBTSNED"); + List selectedItems = Collections.singletonList(selectedItem); + List result = + cut.createClassificationReportBuilder() .workbasketIdIn(Arrays.asList("DieGibtsEhNed")) .listTaskIdsForSelectedItems(selectedItems); - assertNotNull(result); - } + assertNotNull(result); + } - @Test - void testListCustomAttributeValuesForCustomAttributeName() - throws NotAuthorizedException { - List workbasketIds = Collections.singletonList("WBI:000000000000000000000000000000000001"); - List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); - List categories = Collections.singletonList("EXTERN"); - List domains = Collections.singletonList("DOMAIN_A"); - List classificationIds = Collections.singletonList("L10000"); - List excludedClassificationIds = Collections.singletonList("L20000"); - Map customAttributeFilter = new HashMap<>(); - customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); - List columnHeaders = Collections.singletonList( - new TimeIntervalColumnHeader(0, 0)); + @Test + void testListCustomAttributeValuesForCustomAttributeName() throws NotAuthorizedException { + List workbasketIds = + Collections.singletonList("WBI:000000000000000000000000000000000001"); + List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); + List categories = Collections.singletonList("EXTERN"); + List domains = Collections.singletonList("DOMAIN_A"); + List classificationIds = Collections.singletonList("L10000"); + List excludedClassificationIds = Collections.singletonList("L20000"); + Map customAttributeFilter = new HashMap<>(); + customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); + List columnHeaders = + Collections.singletonList(new TimeIntervalColumnHeader(0, 0)); - SelectedItem selectedItem = new SelectedItem(); - selectedItem.setKey("EXTERN"); - selectedItem.setLowerAgeLimit(1); - selectedItem.setUpperAgeLimit(5); - List selectedItems = Collections.singletonList(selectedItem); + SelectedItem selectedItem = new SelectedItem(); + selectedItem.setKey("EXTERN"); + selectedItem.setLowerAgeLimit(1); + selectedItem.setUpperAgeLimit(5); + List selectedItems = Collections.singletonList(selectedItem); - List expectedResult = Collections.singletonList("Geschaeftsstelle A"); - when(taskMonitorMapperMock.getCustomAttributeValuesForReport(workbasketIds, - states, categories, domains, classificationIds, excludedClassificationIds, customAttributeFilter, - CustomField.CUSTOM_1)).thenReturn(expectedResult); + List expectedResult = Collections.singletonList("Geschaeftsstelle A"); + when(taskMonitorMapperMock.getCustomAttributeValuesForReport( + workbasketIds, + states, + categories, + domains, + classificationIds, + excludedClassificationIds, + customAttributeFilter, + CustomField.CUSTOM_1)) + .thenReturn(expectedResult); - List actualResult = cut.createClassificationReportBuilder() + List actualResult = + cut.createClassificationReportBuilder() .workbasketIdIn(workbasketIds) .stateIn(states) .categoryIn(categories) @@ -375,29 +444,32 @@ class ClassificationReportBuilderImplTest { .withColumnHeaders(columnHeaders) .listCustomAttributeValuesForCustomAttributeName(CustomField.CUSTOM_1); - verify(internalTaskanaEngineMock, times(1)).openConnection(); - verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); - verify(taskanaEngineMock, times(2)).getConfiguration(); - verify(internalTaskanaEngineMock, times(3)).getEngine(); - verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); - verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); - verify(taskMonitorMapperMock, times(1)) - .getCustomAttributeValuesForReport(any(), any(), any(), any(), any(), any(), any(), any()); - verify(internalTaskanaEngineMock, times(1)).returnConnection(); - verifyNoMoreInteractions(internalTaskanaEngineMock, taskanaEngineMock, taskMonitorMapperMock, - taskanaEngineConfiguration); + verify(internalTaskanaEngineMock, times(1)).openConnection(); + verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); + verify(taskanaEngineMock, times(2)).getConfiguration(); + verify(internalTaskanaEngineMock, times(3)).getEngine(); + verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); + verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); + verify(taskMonitorMapperMock, times(1)) + .getCustomAttributeValuesForReport(any(), any(), any(), any(), any(), any(), any(), any()); + verify(internalTaskanaEngineMock, times(1)).returnConnection(); + verifyNoMoreInteractions( + internalTaskanaEngineMock, + taskanaEngineMock, + taskMonitorMapperMock, + taskanaEngineConfiguration); - assertNotNull(actualResult); - assertEquals(expectedResult, actualResult); - } + assertNotNull(actualResult); + assertEquals(expectedResult, actualResult); + } - @Test - void testListCustomAttributeValuesForCustomAttributeNameIsEmptyResult() - throws NotAuthorizedException { - List result = cut.createClassificationReportBuilder() + @Test + void testListCustomAttributeValuesForCustomAttributeNameIsEmptyResult() + throws NotAuthorizedException { + List result = + cut.createClassificationReportBuilder() .workbasketIdIn(Collections.singletonList("DieGibtsGarantiertNed")) .listCustomAttributeValuesForCustomAttributeName(CustomField.CUSTOM_10); - assertNotNull(result); - } - + assertNotNull(result); + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/ClassificationServiceImplTest.java b/lib/taskana-core/src/test/java/pro/taskana/impl/ClassificationServiceImplTest.java index 8ed741ba4..f9f3c985e 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/ClassificationServiceImplTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/ClassificationServiceImplTest.java @@ -26,55 +26,53 @@ import pro.taskana.mappings.ClassificationMapper; @ExtendWith(MockitoExtension.class) class ClassificationServiceImplTest { - @Spy - @InjectMocks - private ClassificationServiceImpl cutSpy; - @Mock - private ClassificationMapper classificationMapperMock; - @Mock - private TaskanaEngine taskanaEngineMock; - @Mock - private InternalTaskanaEngine internalTaskanaEngineMock; - @Mock - private ClassificationQueryImpl classificationQueryImplMock; + @Spy @InjectMocks private ClassificationServiceImpl cutSpy; + @Mock private ClassificationMapper classificationMapperMock; + @Mock private TaskanaEngine taskanaEngineMock; + @Mock private InternalTaskanaEngine internalTaskanaEngineMock; + @Mock private ClassificationQueryImpl classificationQueryImplMock; - @Test - void testCreateClassificationQuery() { - cutSpy.createClassificationQuery(); - verifyNoMoreInteractions(classificationMapperMock, internalTaskanaEngineMock, taskanaEngineMock, - classificationQueryImplMock); - } + @Test + void testCreateClassificationQuery() { + cutSpy.createClassificationQuery(); + verifyNoMoreInteractions( + classificationMapperMock, + internalTaskanaEngineMock, + taskanaEngineMock, + classificationQueryImplMock); + } - @Test - void testThrowExceptionIdIfClassificationIsCreatedWithAnExplicitId() { - when(internalTaskanaEngineMock.getEngine()).thenReturn(taskanaEngineMock); - InvalidArgumentException invalidArgumentException = Assertions.assertThrows(InvalidArgumentException.class, + @Test + void testThrowExceptionIdIfClassificationIsCreatedWithAnExplicitId() { + when(internalTaskanaEngineMock.getEngine()).thenReturn(taskanaEngineMock); + InvalidArgumentException invalidArgumentException = + Assertions.assertThrows( + InvalidArgumentException.class, () -> { - - Classification classification = createDummyClassification(); - when(internalTaskanaEngineMock.domainExists(any())).thenReturn(true); - cutSpy.createClassification(classification); + Classification classification = createDummyClassification(); + when(internalTaskanaEngineMock.domainExists(any())).thenReturn(true); + cutSpy.createClassification(classification); }); - assertEquals(invalidArgumentException.getMessage(), "ClassificationId should be null on creation"); - } + assertEquals( + invalidArgumentException.getMessage(), "ClassificationId should be null on creation"); + } - private Classification createDummyClassification() { - return this.createDummyClassification("ID: 1"); - } + private Classification createDummyClassification() { + return this.createDummyClassification("ID: 1"); + } - private Classification createDummyClassification(String id) { - - ClassificationImpl classificationImpl = new ClassificationImpl(); - classificationImpl.setDescription("A DUMMY FOR TESTING A SERVICE"); - classificationImpl.setName("SERVICE-DUMMY"); - classificationImpl.setDomain("DOMAIN_A"); - classificationImpl.setServiceLevel("P2D"); - classificationImpl.setId(id); - classificationImpl.setKey("ABC111"); - classificationImpl.setParentId(""); - classificationImpl.setParentKey(""); - return classificationImpl; - } + private Classification createDummyClassification(String id) { + ClassificationImpl classificationImpl = new ClassificationImpl(); + classificationImpl.setDescription("A DUMMY FOR TESTING A SERVICE"); + classificationImpl.setName("SERVICE-DUMMY"); + classificationImpl.setDomain("DOMAIN_A"); + classificationImpl.setServiceLevel("P2D"); + classificationImpl.setId(id); + classificationImpl.setKey("ABC111"); + classificationImpl.setParentId(""); + classificationImpl.setParentKey(""); + return classificationImpl; + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/CustomFieldValueReportBuilderImplTest.java b/lib/taskana-core/src/test/java/pro/taskana/impl/CustomFieldValueReportBuilderImplTest.java index 8eff34453..f1353a344 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/CustomFieldValueReportBuilderImplTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/CustomFieldValueReportBuilderImplTest.java @@ -14,7 +14,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -33,56 +32,59 @@ import pro.taskana.impl.report.item.MonitorQueryItem; import pro.taskana.mappings.TaskMonitorMapper; import pro.taskana.report.CustomFieldValueReport; -/** - * Unit Test for CustomFieldValueReportBuilderImpl. - */ +/** Unit Test for CustomFieldValueReportBuilderImpl. */ @ExtendWith(MockitoExtension.class) class CustomFieldValueReportBuilderImplTest { - @InjectMocks - private TaskMonitorServiceImpl cut; + @InjectMocks private TaskMonitorServiceImpl cut; - @Mock - private InternalTaskanaEngine internalTaskanaEngineMock; + @Mock private InternalTaskanaEngine internalTaskanaEngineMock; - @Mock - private TaskanaEngine taskanaEngineMock; + @Mock private TaskanaEngine taskanaEngineMock; - @Mock - private TaskanaEngineConfiguration taskanaEngineConfigurationMock; + @Mock private TaskanaEngineConfiguration taskanaEngineConfigurationMock; - @Mock - private TaskMonitorMapper taskMonitorMapperMock; + @Mock private TaskMonitorMapper taskMonitorMapperMock; - @BeforeEach - void setup() { - when(internalTaskanaEngineMock.getEngine()).thenReturn(taskanaEngineMock); - when(taskanaEngineMock.getConfiguration()).thenReturn(taskanaEngineConfigurationMock); - when(taskanaEngineConfigurationMock.isGermanPublicHolidaysEnabled()).thenReturn(true); - when(taskanaEngineConfigurationMock.getCustomHolidays()).thenReturn(null); - } + @BeforeEach + void setup() { + when(internalTaskanaEngineMock.getEngine()).thenReturn(taskanaEngineMock); + when(taskanaEngineMock.getConfiguration()).thenReturn(taskanaEngineConfigurationMock); + when(taskanaEngineConfigurationMock.isGermanPublicHolidaysEnabled()).thenReturn(true); + when(taskanaEngineConfigurationMock.getCustomHolidays()).thenReturn(null); + } - @Test - void testGetTotalNumbersOfCustomFieldValueReport() throws InvalidArgumentException, NotAuthorizedException { - List workbasketIds = Collections.singletonList("WBI:000000000000000000000000000000000001"); - List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); - List categories = Collections.singletonList("EXTERN"); - List domains = Collections.singletonList("DOMAIN_A"); - List classificationIds = Collections.singletonList("L10000"); - List excludedClassificationIds = Collections.singletonList("L20000"); - Map customAttributeFilter = new HashMap<>(); - customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); + @Test + void testGetTotalNumbersOfCustomFieldValueReport() + throws InvalidArgumentException, NotAuthorizedException { + List workbasketIds = + Collections.singletonList("WBI:000000000000000000000000000000000001"); + List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); + List categories = Collections.singletonList("EXTERN"); + List domains = Collections.singletonList("DOMAIN_A"); + List classificationIds = Collections.singletonList("L10000"); + List excludedClassificationIds = Collections.singletonList("L20000"); + Map customAttributeFilter = new HashMap<>(); + customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); - List expectedResult = new ArrayList<>(); - MonitorQueryItem monitorQueryItem = new MonitorQueryItem(); - monitorQueryItem.setKey("Geschaeftsstelle A"); - monitorQueryItem.setNumberOfTasks(1); - expectedResult.add(monitorQueryItem); - when(taskMonitorMapperMock.getTaskCountOfCustomFieldValues(CustomField.CUSTOM_1, workbasketIds, states, + List expectedResult = new ArrayList<>(); + MonitorQueryItem monitorQueryItem = new MonitorQueryItem(); + monitorQueryItem.setKey("Geschaeftsstelle A"); + monitorQueryItem.setNumberOfTasks(1); + expectedResult.add(monitorQueryItem); + when(taskMonitorMapperMock.getTaskCountOfCustomFieldValues( + CustomField.CUSTOM_1, + workbasketIds, + states, categories, - domains, classificationIds, excludedClassificationIds, customAttributeFilter)).thenReturn(expectedResult); + domains, + classificationIds, + excludedClassificationIds, + customAttributeFilter)) + .thenReturn(expectedResult); - CustomFieldValueReport actualResult = cut.createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) + CustomFieldValueReport actualResult = + cut.createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) .workbasketIdIn(workbasketIds) .stateIn(states) .categoryIn(categories) @@ -92,49 +94,60 @@ class CustomFieldValueReportBuilderImplTest { .customAttributeFilterIn(customAttributeFilter) .buildReport(); - verify(internalTaskanaEngineMock, times(1)).openConnection(); - verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); - verify(taskanaEngineMock, times(2)).getConfiguration(); - verify(internalTaskanaEngineMock, times(3)).getEngine(); - verify(taskanaEngineConfigurationMock, times(1)).isGermanPublicHolidaysEnabled(); - verify(taskanaEngineConfigurationMock, times(1)).getCustomHolidays(); - verify(taskMonitorMapperMock, times(1)).getTaskCountOfCustomFieldValues(any(), any(), any(), any(), any(), - any(), any(), - any()); - verify(internalTaskanaEngineMock, times(1)).returnConnection(); - verifyNoMoreInteractions(internalTaskanaEngineMock, taskanaEngineMock, taskMonitorMapperMock, - taskanaEngineConfigurationMock); + verify(internalTaskanaEngineMock, times(1)).openConnection(); + verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); + verify(taskanaEngineMock, times(2)).getConfiguration(); + verify(internalTaskanaEngineMock, times(3)).getEngine(); + verify(taskanaEngineConfigurationMock, times(1)).isGermanPublicHolidaysEnabled(); + verify(taskanaEngineConfigurationMock, times(1)).getCustomHolidays(); + verify(taskMonitorMapperMock, times(1)) + .getTaskCountOfCustomFieldValues(any(), any(), any(), any(), any(), any(), any(), any()); + verify(internalTaskanaEngineMock, times(1)).returnConnection(); + verifyNoMoreInteractions( + internalTaskanaEngineMock, + taskanaEngineMock, + taskMonitorMapperMock, + taskanaEngineConfigurationMock); - assertNotNull(actualResult); - assertEquals(actualResult.getRow("Geschaeftsstelle A").getTotalValue(), 1); - assertEquals(actualResult.getSumRow().getTotalValue(), 1); - } + assertNotNull(actualResult); + assertEquals(actualResult.getRow("Geschaeftsstelle A").getTotalValue(), 1); + assertEquals(actualResult.getSumRow().getTotalValue(), 1); + } - @Test - void testGetCustomFieldValueReportWithReportLineItemDefinitions() - throws InvalidArgumentException, NotAuthorizedException { - List workbasketIds = Collections.singletonList("WBI:000000000000000000000000000000000001"); - List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); - List categories = Collections.singletonList("EXTERN"); - List domains = Collections.singletonList("DOMAIN_A"); - List classificationIds = Collections.singletonList("L10000"); - List excludedClassificationIds = Collections.singletonList("L20000"); - Map customAttributeFilter = new HashMap<>(); - customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); - List columnHeaders = Collections.singletonList( - new TimeIntervalColumnHeader(0, 0)); + @Test + void testGetCustomFieldValueReportWithReportLineItemDefinitions() + throws InvalidArgumentException, NotAuthorizedException { + List workbasketIds = + Collections.singletonList("WBI:000000000000000000000000000000000001"); + List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); + List categories = Collections.singletonList("EXTERN"); + List domains = Collections.singletonList("DOMAIN_A"); + List classificationIds = Collections.singletonList("L10000"); + List excludedClassificationIds = Collections.singletonList("L20000"); + Map customAttributeFilter = new HashMap<>(); + customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); + List columnHeaders = + Collections.singletonList(new TimeIntervalColumnHeader(0, 0)); - List expectedResult = new ArrayList<>(); - MonitorQueryItem monitorQueryItem = new MonitorQueryItem(); - monitorQueryItem.setKey("Geschaeftsstelle A"); - monitorQueryItem.setAgeInDays(0); - monitorQueryItem.setNumberOfTasks(1); - expectedResult.add(monitorQueryItem); - when(taskMonitorMapperMock.getTaskCountOfCustomFieldValues(CustomField.CUSTOM_1, workbasketIds, states, + List expectedResult = new ArrayList<>(); + MonitorQueryItem monitorQueryItem = new MonitorQueryItem(); + monitorQueryItem.setKey("Geschaeftsstelle A"); + monitorQueryItem.setAgeInDays(0); + monitorQueryItem.setNumberOfTasks(1); + expectedResult.add(monitorQueryItem); + when(taskMonitorMapperMock.getTaskCountOfCustomFieldValues( + CustomField.CUSTOM_1, + workbasketIds, + states, categories, - domains, classificationIds, excludedClassificationIds, customAttributeFilter)).thenReturn(expectedResult); + domains, + classificationIds, + excludedClassificationIds, + customAttributeFilter)) + .thenReturn(expectedResult); - CustomFieldValueReport actualResult = cut.createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) + CustomFieldValueReport actualResult = + cut.createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) .workbasketIdIn(workbasketIds) .stateIn(states) .categoryIn(categories) @@ -145,50 +158,61 @@ class CustomFieldValueReportBuilderImplTest { .withColumnHeaders(columnHeaders) .buildReport(); - verify(internalTaskanaEngineMock, times(1)).openConnection(); - verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); - verify(taskanaEngineMock, times(2)).getConfiguration(); - verify(internalTaskanaEngineMock, times(3)).getEngine(); - verify(taskanaEngineConfigurationMock, times(1)).isGermanPublicHolidaysEnabled(); - verify(taskanaEngineConfigurationMock, times(1)).getCustomHolidays(); - verify(taskMonitorMapperMock, times(1)) - .getTaskCountOfCustomFieldValues(any(), any(), any(), any(), any(), any(), any(), any()); - verify(internalTaskanaEngineMock, times(1)).returnConnection(); - verifyNoMoreInteractions(internalTaskanaEngineMock, taskanaEngineMock, taskMonitorMapperMock, - taskanaEngineConfigurationMock); + verify(internalTaskanaEngineMock, times(1)).openConnection(); + verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); + verify(taskanaEngineMock, times(2)).getConfiguration(); + verify(internalTaskanaEngineMock, times(3)).getEngine(); + verify(taskanaEngineConfigurationMock, times(1)).isGermanPublicHolidaysEnabled(); + verify(taskanaEngineConfigurationMock, times(1)).getCustomHolidays(); + verify(taskMonitorMapperMock, times(1)) + .getTaskCountOfCustomFieldValues(any(), any(), any(), any(), any(), any(), any(), any()); + verify(internalTaskanaEngineMock, times(1)).returnConnection(); + verifyNoMoreInteractions( + internalTaskanaEngineMock, + taskanaEngineMock, + taskMonitorMapperMock, + taskanaEngineConfigurationMock); - assertNotNull(actualResult); - assertEquals(actualResult.getRow("Geschaeftsstelle A").getTotalValue(), 1); - assertEquals(actualResult.getRow("Geschaeftsstelle A").getCells()[0], 1); - assertEquals(actualResult.getSumRow().getTotalValue(), 1); - } + assertNotNull(actualResult); + assertEquals(actualResult.getRow("Geschaeftsstelle A").getTotalValue(), 1); + assertEquals(actualResult.getRow("Geschaeftsstelle A").getCells()[0], 1); + assertEquals(actualResult.getSumRow().getTotalValue(), 1); + } - @Test - void testListCustomAttributeValuesForCustomAttributeName() - throws NotAuthorizedException { - List workbasketIds = Collections.singletonList("WBI:000000000000000000000000000000000001"); - List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); - List categories = Collections.singletonList("EXTERN"); - List domains = Collections.singletonList("DOMAIN_A"); - List classificationIds = Collections.singletonList("L10000"); - List excludedClassificationIds = Collections.singletonList("L20000"); - Map customAttributeFilter = new HashMap<>(); - customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); - List columnHeaders = Collections.singletonList( - new TimeIntervalColumnHeader(0, 0)); + @Test + void testListCustomAttributeValuesForCustomAttributeName() throws NotAuthorizedException { + List workbasketIds = + Collections.singletonList("WBI:000000000000000000000000000000000001"); + List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); + List categories = Collections.singletonList("EXTERN"); + List domains = Collections.singletonList("DOMAIN_A"); + List classificationIds = Collections.singletonList("L10000"); + List excludedClassificationIds = Collections.singletonList("L20000"); + Map customAttributeFilter = new HashMap<>(); + customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); + List columnHeaders = + Collections.singletonList(new TimeIntervalColumnHeader(0, 0)); - SelectedItem selectedItem = new SelectedItem(); - selectedItem.setKey("EXTERN"); - selectedItem.setLowerAgeLimit(1); - selectedItem.setUpperAgeLimit(5); - List selectedItems = Collections.singletonList(selectedItem); + SelectedItem selectedItem = new SelectedItem(); + selectedItem.setKey("EXTERN"); + selectedItem.setLowerAgeLimit(1); + selectedItem.setUpperAgeLimit(5); + List selectedItems = Collections.singletonList(selectedItem); - List expectedResult = Collections.singletonList("Geschaeftsstelle A"); - when(taskMonitorMapperMock.getCustomAttributeValuesForReport(workbasketIds, - states, categories, domains, classificationIds, excludedClassificationIds, customAttributeFilter, - CustomField.CUSTOM_1)).thenReturn(expectedResult); + List expectedResult = Collections.singletonList("Geschaeftsstelle A"); + when(taskMonitorMapperMock.getCustomAttributeValuesForReport( + workbasketIds, + states, + categories, + domains, + classificationIds, + excludedClassificationIds, + customAttributeFilter, + CustomField.CUSTOM_1)) + .thenReturn(expectedResult); - List actualResult = cut.createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) + List actualResult = + cut.createCustomFieldValueReportBuilder(CustomField.CUSTOM_1) .workbasketIdIn(workbasketIds) .stateIn(states) .categoryIn(categories) @@ -199,19 +223,22 @@ class CustomFieldValueReportBuilderImplTest { .withColumnHeaders(columnHeaders) .listCustomAttributeValuesForCustomAttributeName(CustomField.CUSTOM_1); - verify(internalTaskanaEngineMock, times(1)).openConnection(); - verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); - verify(taskanaEngineMock, times(2)).getConfiguration(); - verify(internalTaskanaEngineMock, times(3)).getEngine(); - verify(taskanaEngineConfigurationMock, times(1)).isGermanPublicHolidaysEnabled(); - verify(taskanaEngineConfigurationMock, times(1)).getCustomHolidays(); - verify(taskMonitorMapperMock, times(1)) - .getCustomAttributeValuesForReport(any(), any(), any(), any(), any(), any(), any(), any()); - verify(internalTaskanaEngineMock, times(1)).returnConnection(); - verifyNoMoreInteractions(internalTaskanaEngineMock, taskanaEngineMock, taskMonitorMapperMock, - taskanaEngineConfigurationMock); + verify(internalTaskanaEngineMock, times(1)).openConnection(); + verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); + verify(taskanaEngineMock, times(2)).getConfiguration(); + verify(internalTaskanaEngineMock, times(3)).getEngine(); + verify(taskanaEngineConfigurationMock, times(1)).isGermanPublicHolidaysEnabled(); + verify(taskanaEngineConfigurationMock, times(1)).getCustomHolidays(); + verify(taskMonitorMapperMock, times(1)) + .getCustomAttributeValuesForReport(any(), any(), any(), any(), any(), any(), any(), any()); + verify(internalTaskanaEngineMock, times(1)).returnConnection(); + verifyNoMoreInteractions( + internalTaskanaEngineMock, + taskanaEngineMock, + taskMonitorMapperMock, + taskanaEngineConfigurationMock); - assertNotNull(actualResult); - assertEquals(expectedResult, actualResult); - } + assertNotNull(actualResult); + assertEquals(expectedResult, actualResult); + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/DaysToWorkingDaysConverterTest.java b/lib/taskana-core/src/test/java/pro/taskana/impl/DaysToWorkingDaysConverterTest.java index a21705d29..7096779c7 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/DaysToWorkingDaysConverterTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/DaysToWorkingDaysConverterTest.java @@ -10,393 +10,404 @@ import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import pro.taskana.exceptions.InvalidArgumentException; import pro.taskana.impl.report.header.TimeIntervalColumnHeader; -/** - * Test for the DaysToWorkingDaysConverter. - */ +/** Test for the DaysToWorkingDaysConverter. */ class DaysToWorkingDaysConverterTest { - @BeforeAll - static void setup() { - DaysToWorkingDaysConverter.setGermanPublicHolidaysEnabled(true); - LocalDate dayOfReformation = LocalDate.of(2018, 10, 31); - LocalDate allSaintsDays = LocalDate.of(2018, 11, 1); - DaysToWorkingDaysConverter.setCustomHolidays(Arrays.asList(dayOfReformation, allSaintsDays)); - } + @BeforeAll + static void setup() { + DaysToWorkingDaysConverter.setGermanPublicHolidaysEnabled(true); + LocalDate dayOfReformation = LocalDate.of(2018, 10, 31); + LocalDate allSaintsDays = LocalDate.of(2018, 11, 1); + DaysToWorkingDaysConverter.setCustomHolidays(Arrays.asList(dayOfReformation, allSaintsDays)); + } - @Test - void testConvertWorkingDaysToDaysForTasks() throws InvalidArgumentException { - List reportItems = singletonList(new TimeIntervalColumnHeader(0)); - Instant thursday0201 = Instant.parse("2018-02-01T07:00:00.000Z"); - DaysToWorkingDaysConverter converter = DaysToWorkingDaysConverter.initialize(reportItems, thursday0201); + @Test + void testConvertWorkingDaysToDaysForTasks() throws InvalidArgumentException { + List reportItems = singletonList(new TimeIntervalColumnHeader(0)); + Instant thursday0201 = Instant.parse("2018-02-01T07:00:00.000Z"); + DaysToWorkingDaysConverter converter = + DaysToWorkingDaysConverter.initialize(reportItems, thursday0201); - long days = converter.convertWorkingDaysToDays(thursday0201, -7); // = tuesday (sat + sun) - assertEquals(-9, days); - days = converter.convertWorkingDaysToDays(thursday0201, -6); // = wednesday (sat + sun) - assertEquals(-8, days); - days = converter.convertWorkingDaysToDays(thursday0201, -5); // = thursday (sat + sun) - assertEquals(-7, days); - days = converter.convertWorkingDaysToDays(thursday0201, -4); // = friday - assertEquals(-6, days); - days = converter.convertWorkingDaysToDays(thursday0201, -3); // monday - assertEquals(-3, days); - days = converter.convertWorkingDaysToDays(thursday0201, -2); // tuesday - assertEquals(-2, days); - days = converter.convertWorkingDaysToDays(thursday0201, -1); // wednesday - assertEquals(-1, days); - days = converter.convertWorkingDaysToDays(thursday0201, 0); // = thursday - assertEquals(0, days); - days = converter.convertWorkingDaysToDays(thursday0201, 1); // fri - assertEquals(1, days); - days = converter.convertWorkingDaysToDays(thursday0201, 2); // mon - assertEquals(4, days); - days = converter.convertWorkingDaysToDays(thursday0201, 3); // tues - assertEquals(5, days); - days = converter.convertWorkingDaysToDays(thursday0201, 4); // we - assertEquals(6, days); - days = converter.convertWorkingDaysToDays(thursday0201, 5); // thurs - assertEquals(7, days); - days = converter.convertWorkingDaysToDays(thursday0201, 6); // fri - assertEquals(8, days); - days = converter.convertWorkingDaysToDays(thursday0201, 7); // mon - assertEquals(11, days); - days = converter.convertWorkingDaysToDays(thursday0201, 8); // tue - assertEquals(12, days); - days = converter.convertWorkingDaysToDays(thursday0201, 9); // we - assertEquals(13, days); - days = converter.convertWorkingDaysToDays(thursday0201, 10); // thu - assertEquals(14, days); - days = converter.convertWorkingDaysToDays(thursday0201, 11); // fri - assertEquals(15, days); - } + long days = converter.convertWorkingDaysToDays(thursday0201, -7); // = tuesday (sat + sun) + assertEquals(-9, days); + days = converter.convertWorkingDaysToDays(thursday0201, -6); // = wednesday (sat + sun) + assertEquals(-8, days); + days = converter.convertWorkingDaysToDays(thursday0201, -5); // = thursday (sat + sun) + assertEquals(-7, days); + days = converter.convertWorkingDaysToDays(thursday0201, -4); // = friday + assertEquals(-6, days); + days = converter.convertWorkingDaysToDays(thursday0201, -3); // monday + assertEquals(-3, days); + days = converter.convertWorkingDaysToDays(thursday0201, -2); // tuesday + assertEquals(-2, days); + days = converter.convertWorkingDaysToDays(thursday0201, -1); // wednesday + assertEquals(-1, days); + days = converter.convertWorkingDaysToDays(thursday0201, 0); // = thursday + assertEquals(0, days); + days = converter.convertWorkingDaysToDays(thursday0201, 1); // fri + assertEquals(1, days); + days = converter.convertWorkingDaysToDays(thursday0201, 2); // mon + assertEquals(4, days); + days = converter.convertWorkingDaysToDays(thursday0201, 3); // tues + assertEquals(5, days); + days = converter.convertWorkingDaysToDays(thursday0201, 4); // we + assertEquals(6, days); + days = converter.convertWorkingDaysToDays(thursday0201, 5); // thurs + assertEquals(7, days); + days = converter.convertWorkingDaysToDays(thursday0201, 6); // fri + assertEquals(8, days); + days = converter.convertWorkingDaysToDays(thursday0201, 7); // mon + assertEquals(11, days); + days = converter.convertWorkingDaysToDays(thursday0201, 8); // tue + assertEquals(12, days); + days = converter.convertWorkingDaysToDays(thursday0201, 9); // we + assertEquals(13, days); + days = converter.convertWorkingDaysToDays(thursday0201, 10); // thu + assertEquals(14, days); + days = converter.convertWorkingDaysToDays(thursday0201, 11); // fri + assertEquals(15, days); + } - @Test - void testConvertWorkingDaysToDaysForKarFreitag() throws InvalidArgumentException { - List reportItems = singletonList(new TimeIntervalColumnHeader(0)); - Instant thursday0201 = Instant.parse("2018-02-01T07:00:00.000Z"); - DaysToWorkingDaysConverter converter = DaysToWorkingDaysConverter.initialize(reportItems, thursday0201); - Instant gruenDonnerstag2018 = Instant.parse("2018-03-29T01:00:00.000Z"); - long days = converter.convertWorkingDaysToDays(gruenDonnerstag2018, 0); - assertEquals(0, days); - days = converter.convertWorkingDaysToDays(gruenDonnerstag2018, 1); // Karfreitag - assertEquals(5, days); // osterdienstag - days = converter.convertWorkingDaysToDays(gruenDonnerstag2018, 2); // Karfreitag - assertEquals(6, days); // ostermittwoch - } + @Test + void testConvertWorkingDaysToDaysForKarFreitag() throws InvalidArgumentException { + List reportItems = singletonList(new TimeIntervalColumnHeader(0)); + Instant thursday0201 = Instant.parse("2018-02-01T07:00:00.000Z"); + DaysToWorkingDaysConverter converter = + DaysToWorkingDaysConverter.initialize(reportItems, thursday0201); + Instant gruenDonnerstag2018 = Instant.parse("2018-03-29T01:00:00.000Z"); + long days = converter.convertWorkingDaysToDays(gruenDonnerstag2018, 0); + assertEquals(0, days); + days = converter.convertWorkingDaysToDays(gruenDonnerstag2018, 1); // Karfreitag + assertEquals(5, days); // osterdienstag + days = converter.convertWorkingDaysToDays(gruenDonnerstag2018, 2); // Karfreitag + assertEquals(6, days); // ostermittwoch + } - @Test - void testConvertWorkingDaysToDaysForHolidays() throws InvalidArgumentException { - List reportItems = singletonList(new TimeIntervalColumnHeader(0)); - Instant thursday0201 = Instant.parse("2018-02-01T07:00:00.000Z"); - DaysToWorkingDaysConverter converter = DaysToWorkingDaysConverter.initialize(reportItems, thursday0201); + @Test + void testConvertWorkingDaysToDaysForHolidays() throws InvalidArgumentException { + List reportItems = singletonList(new TimeIntervalColumnHeader(0)); + Instant thursday0201 = Instant.parse("2018-02-01T07:00:00.000Z"); + DaysToWorkingDaysConverter converter = + DaysToWorkingDaysConverter.initialize(reportItems, thursday0201); - Instant freitag0427 = Instant.parse("2018-04-27T19:00:00.000Z"); - long days = converter.convertWorkingDaysToDays(freitag0427, 0); - assertEquals(0, days); - days = converter.convertWorkingDaysToDays(freitag0427, 1); - assertEquals(3, days); // 30.4. - days = converter.convertWorkingDaysToDays(freitag0427, 2); - assertEquals(5, days); // 2.5. - } + Instant freitag0427 = Instant.parse("2018-04-27T19:00:00.000Z"); + long days = converter.convertWorkingDaysToDays(freitag0427, 0); + assertEquals(0, days); + days = converter.convertWorkingDaysToDays(freitag0427, 1); + assertEquals(3, days); // 30.4. + days = converter.convertWorkingDaysToDays(freitag0427, 2); + assertEquals(5, days); // 2.5. + } - @Test - void testInitializeForDifferentDates() throws InvalidArgumentException { - DaysToWorkingDaysConverter instance1 = DaysToWorkingDaysConverter - .initialize(getShortListOfColumnHeaders(), Instant.parse("2018-02-04T00:00:00.000Z")); - DaysToWorkingDaysConverter instance2 = DaysToWorkingDaysConverter - .initialize(getShortListOfColumnHeaders(), Instant.parse("2018-02-05T00:00:00.000Z")); + @Test + void testInitializeForDifferentDates() throws InvalidArgumentException { + DaysToWorkingDaysConverter instance1 = + DaysToWorkingDaysConverter.initialize( + getShortListOfColumnHeaders(), Instant.parse("2018-02-04T00:00:00.000Z")); + DaysToWorkingDaysConverter instance2 = + DaysToWorkingDaysConverter.initialize( + getShortListOfColumnHeaders(), Instant.parse("2018-02-05T00:00:00.000Z")); - assertNotEquals(instance1, instance2); - } + assertNotEquals(instance1, instance2); + } - @Test - void testConvertDaysToWorkingDays() throws InvalidArgumentException { - DaysToWorkingDaysConverter instance = DaysToWorkingDaysConverter - .initialize(getLargeListOfColumnHeaders(), Instant.parse("2018-02-06T00:00:00.000Z")); + @Test + void testConvertDaysToWorkingDays() throws InvalidArgumentException { + DaysToWorkingDaysConverter instance = + DaysToWorkingDaysConverter.initialize( + getLargeListOfColumnHeaders(), Instant.parse("2018-02-06T00:00:00.000Z")); - assertEquals(-16, instance.convertDaysToWorkingDays(-16)); - assertEquals(-11, instance.convertDaysToWorkingDays(-15)); + assertEquals(-16, instance.convertDaysToWorkingDays(-16)); + assertEquals(-11, instance.convertDaysToWorkingDays(-15)); - assertEquals(-2, instance.convertDaysToWorkingDays(-4)); - assertEquals(-1, instance.convertDaysToWorkingDays(-3)); - assertEquals(-1, instance.convertDaysToWorkingDays(-2)); - assertEquals(-1, instance.convertDaysToWorkingDays(-1)); - assertEquals(0, instance.convertDaysToWorkingDays(0)); - assertEquals(1, instance.convertDaysToWorkingDays(1)); - assertEquals(2, instance.convertDaysToWorkingDays(2)); - assertEquals(3, instance.convertDaysToWorkingDays(3)); - assertEquals(3, instance.convertDaysToWorkingDays(4)); - assertEquals(3, instance.convertDaysToWorkingDays(5)); - assertEquals(4, instance.convertDaysToWorkingDays(6)); + assertEquals(-2, instance.convertDaysToWorkingDays(-4)); + assertEquals(-1, instance.convertDaysToWorkingDays(-3)); + assertEquals(-1, instance.convertDaysToWorkingDays(-2)); + assertEquals(-1, instance.convertDaysToWorkingDays(-1)); + assertEquals(0, instance.convertDaysToWorkingDays(0)); + assertEquals(1, instance.convertDaysToWorkingDays(1)); + assertEquals(2, instance.convertDaysToWorkingDays(2)); + assertEquals(3, instance.convertDaysToWorkingDays(3)); + assertEquals(3, instance.convertDaysToWorkingDays(4)); + assertEquals(3, instance.convertDaysToWorkingDays(5)); + assertEquals(4, instance.convertDaysToWorkingDays(6)); - assertEquals(11, instance.convertDaysToWorkingDays(15)); - assertEquals(16, instance.convertDaysToWorkingDays(16)); - } + assertEquals(11, instance.convertDaysToWorkingDays(15)); + assertEquals(16, instance.convertDaysToWorkingDays(16)); + } - @Test - void testConvertWorkingDaysToDays() throws InvalidArgumentException { - DaysToWorkingDaysConverter instance = DaysToWorkingDaysConverter - .initialize(getLargeListOfColumnHeaders(), Instant.parse("2018-02-27T00:00:00.000Z")); + @Test + void testConvertWorkingDaysToDays() throws InvalidArgumentException { + DaysToWorkingDaysConverter instance = + DaysToWorkingDaysConverter.initialize( + getLargeListOfColumnHeaders(), Instant.parse("2018-02-27T00:00:00.000Z")); - assertEquals(singletonList(-13), instance.convertWorkingDaysToDays(-13)); - assertEquals(singletonList(-12), instance.convertWorkingDaysToDays(-12)); + assertEquals(singletonList(-13), instance.convertWorkingDaysToDays(-13)); + assertEquals(singletonList(-12), instance.convertWorkingDaysToDays(-12)); - assertEquals(singletonList(-12), instance.convertWorkingDaysToDays(-8)); - assertEquals(singletonList(-11), instance.convertWorkingDaysToDays(-7)); - assertEquals(Arrays.asList(-8, -9, -10), instance.convertWorkingDaysToDays(-6)); - assertEquals(singletonList(-7), instance.convertWorkingDaysToDays(-5)); - assertEquals(singletonList(-6), instance.convertWorkingDaysToDays(-4)); - assertEquals(singletonList(-5), instance.convertWorkingDaysToDays(-3)); - assertEquals(singletonList(-4), instance.convertWorkingDaysToDays(-2)); - assertEquals(Arrays.asList(-1, -2, -3), instance.convertWorkingDaysToDays(-1)); - assertEquals(singletonList(0), instance.convertWorkingDaysToDays(0)); - assertEquals(singletonList(1), instance.convertWorkingDaysToDays(1)); - assertEquals(singletonList(2), instance.convertWorkingDaysToDays(2)); - assertEquals(Arrays.asList(3, 4, 5), instance.convertWorkingDaysToDays(3)); - assertEquals(singletonList(6), instance.convertWorkingDaysToDays(4)); - assertEquals(singletonList(7), instance.convertWorkingDaysToDays(5)); - assertEquals(singletonList(8), instance.convertWorkingDaysToDays(6)); - assertEquals(singletonList(9), instance.convertWorkingDaysToDays(7)); - assertEquals(Arrays.asList(10, 11, 12), instance.convertWorkingDaysToDays(8)); - assertEquals(singletonList(13), instance.convertWorkingDaysToDays(9)); - assertEquals(singletonList(14), instance.convertWorkingDaysToDays(10)); - assertEquals(singletonList(15), instance.convertWorkingDaysToDays(11)); + assertEquals(singletonList(-12), instance.convertWorkingDaysToDays(-8)); + assertEquals(singletonList(-11), instance.convertWorkingDaysToDays(-7)); + assertEquals(Arrays.asList(-8, -9, -10), instance.convertWorkingDaysToDays(-6)); + assertEquals(singletonList(-7), instance.convertWorkingDaysToDays(-5)); + assertEquals(singletonList(-6), instance.convertWorkingDaysToDays(-4)); + assertEquals(singletonList(-5), instance.convertWorkingDaysToDays(-3)); + assertEquals(singletonList(-4), instance.convertWorkingDaysToDays(-2)); + assertEquals(Arrays.asList(-1, -2, -3), instance.convertWorkingDaysToDays(-1)); + assertEquals(singletonList(0), instance.convertWorkingDaysToDays(0)); + assertEquals(singletonList(1), instance.convertWorkingDaysToDays(1)); + assertEquals(singletonList(2), instance.convertWorkingDaysToDays(2)); + assertEquals(Arrays.asList(3, 4, 5), instance.convertWorkingDaysToDays(3)); + assertEquals(singletonList(6), instance.convertWorkingDaysToDays(4)); + assertEquals(singletonList(7), instance.convertWorkingDaysToDays(5)); + assertEquals(singletonList(8), instance.convertWorkingDaysToDays(6)); + assertEquals(singletonList(9), instance.convertWorkingDaysToDays(7)); + assertEquals(Arrays.asList(10, 11, 12), instance.convertWorkingDaysToDays(8)); + assertEquals(singletonList(13), instance.convertWorkingDaysToDays(9)); + assertEquals(singletonList(14), instance.convertWorkingDaysToDays(10)); + assertEquals(singletonList(15), instance.convertWorkingDaysToDays(11)); - assertEquals(singletonList(12), instance.convertWorkingDaysToDays(12)); - assertEquals(singletonList(13), instance.convertWorkingDaysToDays(13)); - } + assertEquals(singletonList(12), instance.convertWorkingDaysToDays(12)); + assertEquals(singletonList(13), instance.convertWorkingDaysToDays(13)); + } - @Test - void testConvertWorkingDaysToDaysAtWeekend() throws InvalidArgumentException { - DaysToWorkingDaysConverter instance = DaysToWorkingDaysConverter - .initialize(getLargeListOfColumnHeaders(), Instant.parse("2018-03-10T00:00:00.000Z")); + @Test + void testConvertWorkingDaysToDaysAtWeekend() throws InvalidArgumentException { + DaysToWorkingDaysConverter instance = + DaysToWorkingDaysConverter.initialize( + getLargeListOfColumnHeaders(), Instant.parse("2018-03-10T00:00:00.000Z")); - assertEquals(singletonList(-13), instance.convertWorkingDaysToDays(-13)); - assertEquals(singletonList(-12), instance.convertWorkingDaysToDays(-12)); + assertEquals(singletonList(-13), instance.convertWorkingDaysToDays(-13)); + assertEquals(singletonList(-12), instance.convertWorkingDaysToDays(-12)); - assertEquals(singletonList(-10), instance.convertWorkingDaysToDays(-8)); - assertEquals(singletonList(-9), instance.convertWorkingDaysToDays(-7)); - assertEquals(singletonList(-8), instance.convertWorkingDaysToDays(-6)); - assertEquals(Arrays.asList(-5, -6, -7), instance.convertWorkingDaysToDays(-5)); - assertEquals(singletonList(-4), instance.convertWorkingDaysToDays(-4)); - assertEquals(singletonList(-3), instance.convertWorkingDaysToDays(-3)); - assertEquals(singletonList(-2), instance.convertWorkingDaysToDays(-2)); - assertEquals(singletonList(-1), instance.convertWorkingDaysToDays(-1)); - assertEquals(Arrays.asList(0, 1), instance.convertWorkingDaysToDays(0)); - assertEquals(singletonList(2), instance.convertWorkingDaysToDays(1)); - assertEquals(singletonList(3), instance.convertWorkingDaysToDays(2)); - assertEquals(singletonList(4), instance.convertWorkingDaysToDays(3)); - assertEquals(singletonList(5), instance.convertWorkingDaysToDays(4)); - assertEquals(Arrays.asList(6, 7, 8), instance.convertWorkingDaysToDays(5)); - assertEquals(singletonList(9), instance.convertWorkingDaysToDays(6)); - assertEquals(singletonList(10), instance.convertWorkingDaysToDays(7)); - assertEquals(singletonList(11), instance.convertWorkingDaysToDays(8)); - assertEquals(singletonList(12), instance.convertWorkingDaysToDays(9)); - assertEquals(Arrays.asList(13, 14, 15), instance.convertWorkingDaysToDays(10)); - assertEquals(singletonList(16), instance.convertWorkingDaysToDays(11)); + assertEquals(singletonList(-10), instance.convertWorkingDaysToDays(-8)); + assertEquals(singletonList(-9), instance.convertWorkingDaysToDays(-7)); + assertEquals(singletonList(-8), instance.convertWorkingDaysToDays(-6)); + assertEquals(Arrays.asList(-5, -6, -7), instance.convertWorkingDaysToDays(-5)); + assertEquals(singletonList(-4), instance.convertWorkingDaysToDays(-4)); + assertEquals(singletonList(-3), instance.convertWorkingDaysToDays(-3)); + assertEquals(singletonList(-2), instance.convertWorkingDaysToDays(-2)); + assertEquals(singletonList(-1), instance.convertWorkingDaysToDays(-1)); + assertEquals(Arrays.asList(0, 1), instance.convertWorkingDaysToDays(0)); + assertEquals(singletonList(2), instance.convertWorkingDaysToDays(1)); + assertEquals(singletonList(3), instance.convertWorkingDaysToDays(2)); + assertEquals(singletonList(4), instance.convertWorkingDaysToDays(3)); + assertEquals(singletonList(5), instance.convertWorkingDaysToDays(4)); + assertEquals(Arrays.asList(6, 7, 8), instance.convertWorkingDaysToDays(5)); + assertEquals(singletonList(9), instance.convertWorkingDaysToDays(6)); + assertEquals(singletonList(10), instance.convertWorkingDaysToDays(7)); + assertEquals(singletonList(11), instance.convertWorkingDaysToDays(8)); + assertEquals(singletonList(12), instance.convertWorkingDaysToDays(9)); + assertEquals(Arrays.asList(13, 14, 15), instance.convertWorkingDaysToDays(10)); + assertEquals(singletonList(16), instance.convertWorkingDaysToDays(11)); - assertEquals(singletonList(12), instance.convertWorkingDaysToDays(12)); - assertEquals(singletonList(13), instance.convertWorkingDaysToDays(13)); - } + assertEquals(singletonList(12), instance.convertWorkingDaysToDays(12)); + assertEquals(singletonList(13), instance.convertWorkingDaysToDays(13)); + } - @Test - void testConvertWorkingDaysToDaysOnEasterSunday() throws InvalidArgumentException { - DaysToWorkingDaysConverter instance = DaysToWorkingDaysConverter - .initialize(getLargeListOfColumnHeaders(), Instant.parse("2018-04-01T00:00:00.000Z")); + @Test + void testConvertWorkingDaysToDaysOnEasterSunday() throws InvalidArgumentException { + DaysToWorkingDaysConverter instance = + DaysToWorkingDaysConverter.initialize( + getLargeListOfColumnHeaders(), Instant.parse("2018-04-01T00:00:00.000Z")); - assertEquals(singletonList(-13), instance.convertWorkingDaysToDays(-13)); - assertEquals(singletonList(-12), instance.convertWorkingDaysToDays(-12)); + assertEquals(singletonList(-13), instance.convertWorkingDaysToDays(-13)); + assertEquals(singletonList(-12), instance.convertWorkingDaysToDays(-12)); - assertEquals(singletonList(-12), instance.convertWorkingDaysToDays(-8)); - assertEquals(singletonList(-11), instance.convertWorkingDaysToDays(-7)); - assertEquals(singletonList(-10), instance.convertWorkingDaysToDays(-6)); - assertEquals(singletonList(-9), instance.convertWorkingDaysToDays(-5)); - assertEquals(Arrays.asList(-6, -7, -8), instance.convertWorkingDaysToDays(-4)); - assertEquals(singletonList(-5), instance.convertWorkingDaysToDays(-3)); - assertEquals(singletonList(-4), instance.convertWorkingDaysToDays(-2)); - assertEquals(singletonList(-3), instance.convertWorkingDaysToDays(-1)); - assertEquals(Arrays.asList(0, 1, -1, -2), instance.convertWorkingDaysToDays(0)); - assertEquals(singletonList(2), instance.convertWorkingDaysToDays(1)); - assertEquals(singletonList(3), instance.convertWorkingDaysToDays(2)); - assertEquals(singletonList(4), instance.convertWorkingDaysToDays(3)); - assertEquals(Arrays.asList(5, 6, 7), instance.convertWorkingDaysToDays(4)); - assertEquals(singletonList(8), instance.convertWorkingDaysToDays(5)); - assertEquals(singletonList(9), instance.convertWorkingDaysToDays(6)); - assertEquals(singletonList(10), instance.convertWorkingDaysToDays(7)); - assertEquals(singletonList(11), instance.convertWorkingDaysToDays(8)); - assertEquals(Arrays.asList(12, 13, 14), instance.convertWorkingDaysToDays(9)); - assertEquals(singletonList(15), instance.convertWorkingDaysToDays(10)); - assertEquals(singletonList(16), instance.convertWorkingDaysToDays(11)); + assertEquals(singletonList(-12), instance.convertWorkingDaysToDays(-8)); + assertEquals(singletonList(-11), instance.convertWorkingDaysToDays(-7)); + assertEquals(singletonList(-10), instance.convertWorkingDaysToDays(-6)); + assertEquals(singletonList(-9), instance.convertWorkingDaysToDays(-5)); + assertEquals(Arrays.asList(-6, -7, -8), instance.convertWorkingDaysToDays(-4)); + assertEquals(singletonList(-5), instance.convertWorkingDaysToDays(-3)); + assertEquals(singletonList(-4), instance.convertWorkingDaysToDays(-2)); + assertEquals(singletonList(-3), instance.convertWorkingDaysToDays(-1)); + assertEquals(Arrays.asList(0, 1, -1, -2), instance.convertWorkingDaysToDays(0)); + assertEquals(singletonList(2), instance.convertWorkingDaysToDays(1)); + assertEquals(singletonList(3), instance.convertWorkingDaysToDays(2)); + assertEquals(singletonList(4), instance.convertWorkingDaysToDays(3)); + assertEquals(Arrays.asList(5, 6, 7), instance.convertWorkingDaysToDays(4)); + assertEquals(singletonList(8), instance.convertWorkingDaysToDays(5)); + assertEquals(singletonList(9), instance.convertWorkingDaysToDays(6)); + assertEquals(singletonList(10), instance.convertWorkingDaysToDays(7)); + assertEquals(singletonList(11), instance.convertWorkingDaysToDays(8)); + assertEquals(Arrays.asList(12, 13, 14), instance.convertWorkingDaysToDays(9)); + assertEquals(singletonList(15), instance.convertWorkingDaysToDays(10)); + assertEquals(singletonList(16), instance.convertWorkingDaysToDays(11)); - assertEquals(singletonList(12), instance.convertWorkingDaysToDays(12)); - assertEquals(singletonList(13), instance.convertWorkingDaysToDays(13)); - } + assertEquals(singletonList(12), instance.convertWorkingDaysToDays(12)); + assertEquals(singletonList(13), instance.convertWorkingDaysToDays(13)); + } - @Test - void testEasterHolidays() throws InvalidArgumentException { - DaysToWorkingDaysConverter instance = DaysToWorkingDaysConverter - .initialize(getLargeListOfColumnHeaders(), Instant.parse("2018-03-28T00:00:00.000Z")); + @Test + void testEasterHolidays() throws InvalidArgumentException { + DaysToWorkingDaysConverter instance = + DaysToWorkingDaysConverter.initialize( + getLargeListOfColumnHeaders(), Instant.parse("2018-03-28T00:00:00.000Z")); - assertEquals(0, instance.convertDaysToWorkingDays(0)); - assertEquals(1, instance.convertDaysToWorkingDays(1)); - assertEquals(1, instance.convertDaysToWorkingDays(2)); - assertEquals(1, instance.convertDaysToWorkingDays(3)); - assertEquals(1, instance.convertDaysToWorkingDays(4)); - assertEquals(1, instance.convertDaysToWorkingDays(5)); - assertEquals(2, instance.convertDaysToWorkingDays(6)); - } + assertEquals(0, instance.convertDaysToWorkingDays(0)); + assertEquals(1, instance.convertDaysToWorkingDays(1)); + assertEquals(1, instance.convertDaysToWorkingDays(2)); + assertEquals(1, instance.convertDaysToWorkingDays(3)); + assertEquals(1, instance.convertDaysToWorkingDays(4)); + assertEquals(1, instance.convertDaysToWorkingDays(5)); + assertEquals(2, instance.convertDaysToWorkingDays(6)); + } - @Test - void testWhitsunHolidays() throws InvalidArgumentException { - DaysToWorkingDaysConverter instance = DaysToWorkingDaysConverter - .initialize(getLargeListOfColumnHeaders(), Instant.parse("2018-05-16T00:00:00.000Z")); + @Test + void testWhitsunHolidays() throws InvalidArgumentException { + DaysToWorkingDaysConverter instance = + DaysToWorkingDaysConverter.initialize( + getLargeListOfColumnHeaders(), Instant.parse("2018-05-16T00:00:00.000Z")); - assertEquals(0, instance.convertDaysToWorkingDays(0)); - assertEquals(1, instance.convertDaysToWorkingDays(1)); - assertEquals(2, instance.convertDaysToWorkingDays(2)); - assertEquals(2, instance.convertDaysToWorkingDays(3)); - assertEquals(2, instance.convertDaysToWorkingDays(4)); - assertEquals(2, instance.convertDaysToWorkingDays(5)); - assertEquals(3, instance.convertDaysToWorkingDays(6)); - } + assertEquals(0, instance.convertDaysToWorkingDays(0)); + assertEquals(1, instance.convertDaysToWorkingDays(1)); + assertEquals(2, instance.convertDaysToWorkingDays(2)); + assertEquals(2, instance.convertDaysToWorkingDays(3)); + assertEquals(2, instance.convertDaysToWorkingDays(4)); + assertEquals(2, instance.convertDaysToWorkingDays(5)); + assertEquals(3, instance.convertDaysToWorkingDays(6)); + } - @Test - void testLabourDayHoliday() throws InvalidArgumentException { - DaysToWorkingDaysConverter instance = DaysToWorkingDaysConverter - .initialize(getLargeListOfColumnHeaders(), Instant.parse("2018-04-26T00:00:00.000Z")); + @Test + void testLabourDayHoliday() throws InvalidArgumentException { + DaysToWorkingDaysConverter instance = + DaysToWorkingDaysConverter.initialize( + getLargeListOfColumnHeaders(), Instant.parse("2018-04-26T00:00:00.000Z")); - assertEquals(0, instance.convertDaysToWorkingDays(0)); - assertEquals(1, instance.convertDaysToWorkingDays(1)); - assertEquals(1, instance.convertDaysToWorkingDays(2)); - assertEquals(1, instance.convertDaysToWorkingDays(3)); - assertEquals(2, instance.convertDaysToWorkingDays(4)); - assertEquals(2, instance.convertDaysToWorkingDays(5)); - assertEquals(3, instance.convertDaysToWorkingDays(6)); - assertEquals(4, instance.convertDaysToWorkingDays(7)); - } + assertEquals(0, instance.convertDaysToWorkingDays(0)); + assertEquals(1, instance.convertDaysToWorkingDays(1)); + assertEquals(1, instance.convertDaysToWorkingDays(2)); + assertEquals(1, instance.convertDaysToWorkingDays(3)); + assertEquals(2, instance.convertDaysToWorkingDays(4)); + assertEquals(2, instance.convertDaysToWorkingDays(5)); + assertEquals(3, instance.convertDaysToWorkingDays(6)); + assertEquals(4, instance.convertDaysToWorkingDays(7)); + } - @Test - void testAscensionDayHoliday() throws InvalidArgumentException { - DaysToWorkingDaysConverter instance = DaysToWorkingDaysConverter - .initialize(getLargeListOfColumnHeaders(), Instant.parse("2018-05-07T00:00:00.000Z")); + @Test + void testAscensionDayHoliday() throws InvalidArgumentException { + DaysToWorkingDaysConverter instance = + DaysToWorkingDaysConverter.initialize( + getLargeListOfColumnHeaders(), Instant.parse("2018-05-07T00:00:00.000Z")); - assertEquals(0, instance.convertDaysToWorkingDays(0)); - assertEquals(1, instance.convertDaysToWorkingDays(1)); - assertEquals(2, instance.convertDaysToWorkingDays(2)); - assertEquals(2, instance.convertDaysToWorkingDays(3)); - assertEquals(3, instance.convertDaysToWorkingDays(4)); - assertEquals(3, instance.convertDaysToWorkingDays(5)); - assertEquals(3, instance.convertDaysToWorkingDays(6)); - assertEquals(4, instance.convertDaysToWorkingDays(7)); - } + assertEquals(0, instance.convertDaysToWorkingDays(0)); + assertEquals(1, instance.convertDaysToWorkingDays(1)); + assertEquals(2, instance.convertDaysToWorkingDays(2)); + assertEquals(2, instance.convertDaysToWorkingDays(3)); + assertEquals(3, instance.convertDaysToWorkingDays(4)); + assertEquals(3, instance.convertDaysToWorkingDays(5)); + assertEquals(3, instance.convertDaysToWorkingDays(6)); + assertEquals(4, instance.convertDaysToWorkingDays(7)); + } - @Test - void testDayOfGermanUnityHoliday() throws InvalidArgumentException { - DaysToWorkingDaysConverter instance = DaysToWorkingDaysConverter - .initialize(getLargeListOfColumnHeaders(), Instant.parse("2018-10-01T00:00:00.000Z")); + @Test + void testDayOfGermanUnityHoliday() throws InvalidArgumentException { + DaysToWorkingDaysConverter instance = + DaysToWorkingDaysConverter.initialize( + getLargeListOfColumnHeaders(), Instant.parse("2018-10-01T00:00:00.000Z")); - assertEquals(0, instance.convertDaysToWorkingDays(0)); - assertEquals(1, instance.convertDaysToWorkingDays(1)); - assertEquals(1, instance.convertDaysToWorkingDays(2)); - assertEquals(2, instance.convertDaysToWorkingDays(3)); - assertEquals(3, instance.convertDaysToWorkingDays(4)); - assertEquals(3, instance.convertDaysToWorkingDays(5)); - assertEquals(3, instance.convertDaysToWorkingDays(6)); - assertEquals(4, instance.convertDaysToWorkingDays(7)); - } + assertEquals(0, instance.convertDaysToWorkingDays(0)); + assertEquals(1, instance.convertDaysToWorkingDays(1)); + assertEquals(1, instance.convertDaysToWorkingDays(2)); + assertEquals(2, instance.convertDaysToWorkingDays(3)); + assertEquals(3, instance.convertDaysToWorkingDays(4)); + assertEquals(3, instance.convertDaysToWorkingDays(5)); + assertEquals(3, instance.convertDaysToWorkingDays(6)); + assertEquals(4, instance.convertDaysToWorkingDays(7)); + } - @Test - void testChristmasAndNewYearHolidays() throws InvalidArgumentException { - DaysToWorkingDaysConverter instance = DaysToWorkingDaysConverter - .initialize(getLargeListOfColumnHeaders(), Instant.parse("2018-12-20T00:00:00.000Z")); + @Test + void testChristmasAndNewYearHolidays() throws InvalidArgumentException { + DaysToWorkingDaysConverter instance = + DaysToWorkingDaysConverter.initialize( + getLargeListOfColumnHeaders(), Instant.parse("2018-12-20T00:00:00.000Z")); - assertEquals(0, instance.convertDaysToWorkingDays(0)); - assertEquals(1, instance.convertDaysToWorkingDays(1)); - assertEquals(1, instance.convertDaysToWorkingDays(2)); - assertEquals(1, instance.convertDaysToWorkingDays(3)); - assertEquals(2, instance.convertDaysToWorkingDays(4)); - assertEquals(2, instance.convertDaysToWorkingDays(5)); - assertEquals(2, instance.convertDaysToWorkingDays(6)); - assertEquals(3, instance.convertDaysToWorkingDays(7)); - assertEquals(4, instance.convertDaysToWorkingDays(8)); - assertEquals(4, instance.convertDaysToWorkingDays(9)); - assertEquals(4, instance.convertDaysToWorkingDays(10)); - assertEquals(5, instance.convertDaysToWorkingDays(11)); - assertEquals(5, instance.convertDaysToWorkingDays(12)); - assertEquals(6, instance.convertDaysToWorkingDays(13)); - assertEquals(7, instance.convertDaysToWorkingDays(14)); - } + assertEquals(0, instance.convertDaysToWorkingDays(0)); + assertEquals(1, instance.convertDaysToWorkingDays(1)); + assertEquals(1, instance.convertDaysToWorkingDays(2)); + assertEquals(1, instance.convertDaysToWorkingDays(3)); + assertEquals(2, instance.convertDaysToWorkingDays(4)); + assertEquals(2, instance.convertDaysToWorkingDays(5)); + assertEquals(2, instance.convertDaysToWorkingDays(6)); + assertEquals(3, instance.convertDaysToWorkingDays(7)); + assertEquals(4, instance.convertDaysToWorkingDays(8)); + assertEquals(4, instance.convertDaysToWorkingDays(9)); + assertEquals(4, instance.convertDaysToWorkingDays(10)); + assertEquals(5, instance.convertDaysToWorkingDays(11)); + assertEquals(5, instance.convertDaysToWorkingDays(12)); + assertEquals(6, instance.convertDaysToWorkingDays(13)); + assertEquals(7, instance.convertDaysToWorkingDays(14)); + } - @Test - void testCustomHolidaysWithDayOfReformationAndAllSaintsDay() throws InvalidArgumentException { - DaysToWorkingDaysConverter instance = DaysToWorkingDaysConverter - .initialize(getLargeListOfColumnHeaders(), Instant.parse("2018-10-26T00:00:00.000Z")); + @Test + void testCustomHolidaysWithDayOfReformationAndAllSaintsDay() throws InvalidArgumentException { + DaysToWorkingDaysConverter instance = + DaysToWorkingDaysConverter.initialize( + getLargeListOfColumnHeaders(), Instant.parse("2018-10-26T00:00:00.000Z")); - assertEquals(0, instance.convertDaysToWorkingDays(0)); - assertEquals(0, instance.convertDaysToWorkingDays(1)); - assertEquals(0, instance.convertDaysToWorkingDays(2)); - assertEquals(1, instance.convertDaysToWorkingDays(3)); - assertEquals(2, instance.convertDaysToWorkingDays(4)); - assertEquals(2, instance.convertDaysToWorkingDays(5)); - assertEquals(2, instance.convertDaysToWorkingDays(6)); - assertEquals(3, instance.convertDaysToWorkingDays(7)); + assertEquals(0, instance.convertDaysToWorkingDays(0)); + assertEquals(0, instance.convertDaysToWorkingDays(1)); + assertEquals(0, instance.convertDaysToWorkingDays(2)); + assertEquals(1, instance.convertDaysToWorkingDays(3)); + assertEquals(2, instance.convertDaysToWorkingDays(4)); + assertEquals(2, instance.convertDaysToWorkingDays(5)); + assertEquals(2, instance.convertDaysToWorkingDays(6)); + assertEquals(3, instance.convertDaysToWorkingDays(7)); + } - } + @Test + void testGetEasterSunday() { - @Test - void testGetEasterSunday() { + assertEquals(LocalDate.of(2018, 4, 1), getEasterSunday(2018)); + assertEquals(LocalDate.of(2019, 4, 21), getEasterSunday(2019)); + assertEquals(LocalDate.of(2020, 4, 12), getEasterSunday(2020)); + assertEquals(LocalDate.of(2021, 4, 4), getEasterSunday(2021)); + assertEquals(LocalDate.of(2022, 4, 17), getEasterSunday(2022)); + assertEquals(LocalDate.of(2023, 4, 9), getEasterSunday(2023)); + assertEquals(LocalDate.of(2024, 3, 31), getEasterSunday(2024)); + assertEquals(LocalDate.of(2025, 4, 20), getEasterSunday(2025)); + assertEquals(LocalDate.of(2026, 4, 5), getEasterSunday(2026)); + assertEquals(LocalDate.of(2027, 3, 28), getEasterSunday(2027)); + assertEquals(LocalDate.of(2028, 4, 16), getEasterSunday(2028)); + assertEquals(LocalDate.of(2029, 4, 1), getEasterSunday(2029)); + assertEquals(LocalDate.of(2030, 4, 21), getEasterSunday(2030)); + assertEquals(LocalDate.of(2031, 4, 13), getEasterSunday(2031)); + assertEquals(LocalDate.of(2032, 3, 28), getEasterSunday(2032)); + assertEquals(LocalDate.of(2033, 4, 17), getEasterSunday(2033)); + assertEquals(LocalDate.of(2034, 4, 9), getEasterSunday(2034)); + assertEquals(LocalDate.of(2035, 3, 25), getEasterSunday(2035)); + assertEquals(LocalDate.of(2040, 4, 1), getEasterSunday(2040)); + assertEquals(LocalDate.of(2050, 4, 10), getEasterSunday(2050)); + assertEquals(LocalDate.of(2100, 3, 28), getEasterSunday(2100)); + } - assertEquals(LocalDate.of(2018, 4, 1), getEasterSunday(2018)); - assertEquals(LocalDate.of(2019, 4, 21), getEasterSunday(2019)); - assertEquals(LocalDate.of(2020, 4, 12), getEasterSunday(2020)); - assertEquals(LocalDate.of(2021, 4, 4), getEasterSunday(2021)); - assertEquals(LocalDate.of(2022, 4, 17), getEasterSunday(2022)); - assertEquals(LocalDate.of(2023, 4, 9), getEasterSunday(2023)); - assertEquals(LocalDate.of(2024, 3, 31), getEasterSunday(2024)); - assertEquals(LocalDate.of(2025, 4, 20), getEasterSunday(2025)); - assertEquals(LocalDate.of(2026, 4, 5), getEasterSunday(2026)); - assertEquals(LocalDate.of(2027, 3, 28), getEasterSunday(2027)); - assertEquals(LocalDate.of(2028, 4, 16), getEasterSunday(2028)); - assertEquals(LocalDate.of(2029, 4, 1), getEasterSunday(2029)); - assertEquals(LocalDate.of(2030, 4, 21), getEasterSunday(2030)); - assertEquals(LocalDate.of(2031, 4, 13), getEasterSunday(2031)); - assertEquals(LocalDate.of(2032, 3, 28), getEasterSunday(2032)); - assertEquals(LocalDate.of(2033, 4, 17), getEasterSunday(2033)); - assertEquals(LocalDate.of(2034, 4, 9), getEasterSunday(2034)); - assertEquals(LocalDate.of(2035, 3, 25), getEasterSunday(2035)); - assertEquals(LocalDate.of(2040, 4, 1), getEasterSunday(2040)); - assertEquals(LocalDate.of(2050, 4, 10), getEasterSunday(2050)); - assertEquals(LocalDate.of(2100, 3, 28), getEasterSunday(2100)); + private List getShortListOfColumnHeaders() { + List columnHeaders = new ArrayList<>(); + columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -3)); + columnHeaders.add(new TimeIntervalColumnHeader(-1, -2)); + columnHeaders.add(new TimeIntervalColumnHeader(0)); + columnHeaders.add(new TimeIntervalColumnHeader(1, 2)); + columnHeaders.add(new TimeIntervalColumnHeader(3, Integer.MAX_VALUE)); + return columnHeaders; + } - } - - private List getShortListOfColumnHeaders() { - List columnHeaders = new ArrayList<>(); - columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -3)); - columnHeaders.add(new TimeIntervalColumnHeader(-1, -2)); - columnHeaders.add(new TimeIntervalColumnHeader(0)); - columnHeaders.add(new TimeIntervalColumnHeader(1, 2)); - columnHeaders.add(new TimeIntervalColumnHeader(3, Integer.MAX_VALUE)); - return columnHeaders; - } - - private List getLargeListOfColumnHeaders() { - List columnHeaders = new ArrayList<>(); - columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -11)); - columnHeaders.add(new TimeIntervalColumnHeader(-10, -6)); - columnHeaders.add(new TimeIntervalColumnHeader(-5, -2)); - columnHeaders.add(new TimeIntervalColumnHeader(-1)); - columnHeaders.add(new TimeIntervalColumnHeader(0)); - columnHeaders.add(new TimeIntervalColumnHeader(1)); - columnHeaders.add(new TimeIntervalColumnHeader(2, 5)); - columnHeaders.add(new TimeIntervalColumnHeader(6, 10)); - columnHeaders.add(new TimeIntervalColumnHeader(11, Integer.MAX_VALUE)); - return columnHeaders; - } + private List getLargeListOfColumnHeaders() { + List columnHeaders = new ArrayList<>(); + columnHeaders.add(new TimeIntervalColumnHeader(Integer.MIN_VALUE, -11)); + columnHeaders.add(new TimeIntervalColumnHeader(-10, -6)); + columnHeaders.add(new TimeIntervalColumnHeader(-5, -2)); + columnHeaders.add(new TimeIntervalColumnHeader(-1)); + columnHeaders.add(new TimeIntervalColumnHeader(0)); + columnHeaders.add(new TimeIntervalColumnHeader(1)); + columnHeaders.add(new TimeIntervalColumnHeader(2, 5)); + columnHeaders.add(new TimeIntervalColumnHeader(6, 10)); + columnHeaders.add(new TimeIntervalColumnHeader(11, Integer.MAX_VALUE)); + return columnHeaders; + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/JunitHelper.java b/lib/taskana-core/src/test/java/pro/taskana/impl/JunitHelper.java index 52a341618..68e4ac703 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/JunitHelper.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/JunitHelper.java @@ -10,34 +10,33 @@ import pro.taskana.ObjectReference; */ public final class JunitHelper { - private JunitHelper() { + private JunitHelper() {} - } + public static ObjectReference createDefaultObjRef() { + return createObjRef("company", "system", "instance", "type", "value"); + } - public static ObjectReference createDefaultObjRef() { - return createObjRef("company", "system", "instance", "type", "value"); - } + public static ObjectReference createObjRef( + String company, String system, String instance, String type, String value) { + ObjectReference objRef = new ObjectReference(); + objRef.setCompany(company); + objRef.setSystem(system); + objRef.setSystemInstance(instance); + objRef.setType(type); + objRef.setValue(value); + return objRef; + } - public static ObjectReference createObjRef(String company, String system, String instance, String type, - String value) { - ObjectReference objRef = new ObjectReference(); - objRef.setCompany(company); - objRef.setSystem(system); - objRef.setSystemInstance(instance); - objRef.setType(type); - objRef.setValue(value); - return objRef; - } + public static Attachment createDefaultAttachment() { + return createAttachment("TAI:000", "CHANNEL", createDefaultObjRef()); + } - public static Attachment createDefaultAttachment() { - return createAttachment("TAI:000", "CHANNEL", createDefaultObjRef()); - } - - public static Attachment createAttachment(String id, String channel, ObjectReference objectReference) { - AttachmentImpl attachment = new AttachmentImpl(); - attachment.setChannel(channel); - attachment.setId(id); - attachment.setObjectReference(objectReference); - return attachment; - } + public static Attachment createAttachment( + String id, String channel, ObjectReference objectReference) { + AttachmentImpl attachment = new AttachmentImpl(); + attachment.setChannel(channel); + attachment.setId(id); + attachment.setObjectReference(objectReference); + return attachment; + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/ObjectReferenceQueryImplTest.java b/lib/taskana-core/src/test/java/pro/taskana/impl/ObjectReferenceQueryImplTest.java index 98321c906..576a2910c 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/ObjectReferenceQueryImplTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/ObjectReferenceQueryImplTest.java @@ -6,7 +6,6 @@ import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; - import org.apache.ibatis.session.SqlSession; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -24,55 +23,59 @@ import pro.taskana.ObjectReference; @ExtendWith(MockitoExtension.class) class ObjectReferenceQueryImplTest { - ObjectReferenceQueryImpl objectReferenceQueryImpl; + ObjectReferenceQueryImpl objectReferenceQueryImpl; - @Mock - InternalTaskanaEngine taskanaEngine; + @Mock InternalTaskanaEngine taskanaEngine; - @Mock - SqlSession sqlSession; + @Mock SqlSession sqlSession; - @BeforeEach - void setup() { - objectReferenceQueryImpl = new ObjectReferenceQueryImpl(taskanaEngine); - } + @BeforeEach + void setup() { + objectReferenceQueryImpl = new ObjectReferenceQueryImpl(taskanaEngine); + } - @Test - void should_ReturnList_when_BuilderIsUsed() { - when(taskanaEngine.getSqlSession()).thenReturn(sqlSession); - when(sqlSession.selectList(any(), any())).thenReturn(new ArrayList<>()); + @Test + void should_ReturnList_when_BuilderIsUsed() { + when(taskanaEngine.getSqlSession()).thenReturn(sqlSession); + when(sqlSession.selectList(any(), any())).thenReturn(new ArrayList<>()); - List result = objectReferenceQueryImpl.valueIn("test", "asd", "blubber") + List result = + objectReferenceQueryImpl + .valueIn("test", "asd", "blubber") .typeIn("cool", "bla") .systemInstanceIn("1", "2") .systemIn("superId") .list(); - assertNotNull(result); - } + assertNotNull(result); + } - @Test - void should_ReturnListWithOffset_when_BuilderIsUsed() { - when(taskanaEngine.getSqlSession()).thenReturn(sqlSession); - when(sqlSession.selectList(any(), any(), any())).thenReturn(new ArrayList<>()); + @Test + void should_ReturnListWithOffset_when_BuilderIsUsed() { + when(taskanaEngine.getSqlSession()).thenReturn(sqlSession); + when(sqlSession.selectList(any(), any(), any())).thenReturn(new ArrayList<>()); - List result = objectReferenceQueryImpl.valueIn("test", "asd", "blubber") + List result = + objectReferenceQueryImpl + .valueIn("test", "asd", "blubber") .typeIn("cool", "bla") .systemInstanceIn("1", "2") .systemIn("superId") .list(1, 1); - assertNotNull(result); - } + assertNotNull(result); + } - @Test - void should_ReturnOneItem_when_BuilderIsUsed() { - when(taskanaEngine.getSqlSession()).thenReturn(sqlSession); - when(sqlSession.selectOne(any(), any())).thenReturn(new ObjectReference()); + @Test + void should_ReturnOneItem_when_BuilderIsUsed() { + when(taskanaEngine.getSqlSession()).thenReturn(sqlSession); + when(sqlSession.selectOne(any(), any())).thenReturn(new ObjectReference()); - ObjectReference result = objectReferenceQueryImpl.valueIn("test", "asd", "blubber") + ObjectReference result = + objectReferenceQueryImpl + .valueIn("test", "asd", "blubber") .typeIn("cool", "bla") .systemInstanceIn("1", "2") .systemIn("superId") .single(); - assertNotNull(result); - } + assertNotNull(result); + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/TaskAttachmentTest.java b/lib/taskana-core/src/test/java/pro/taskana/impl/TaskAttachmentTest.java index b94f7fa3a..deb49d01f 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/TaskAttachmentTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/TaskAttachmentTest.java @@ -8,7 +8,6 @@ import java.time.Instant; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; @@ -20,131 +19,133 @@ import pro.taskana.ObjectReference; /** * Unit Test for methods needed fot attachment at TaskImpl.
- * This test should test every interaction with Attachments, which means adding, removing, nulling them. + * This test should test every interaction with Attachments, which means adding, removing, nulling + * them. */ @ExtendWith(MockitoExtension.class) class TaskAttachmentTest { - @InjectMocks - private TaskImpl cut; + @InjectMocks private TaskImpl cut; - @Test - void testAddAttachmentWithValidValue() { - Attachment attachment1 = createAttachment("ID1", "taskId1"); - Attachment attachment2 = createAttachment("ID2", "taskId1"); - Attachment attachment3 = createAttachment("ID3", "taskId1"); + @Test + void testAddAttachmentWithValidValue() { + Attachment attachment1 = createAttachment("ID1", "taskId1"); + Attachment attachment2 = createAttachment("ID2", "taskId1"); + Attachment attachment3 = createAttachment("ID3", "taskId1"); - cut.addAttachment(attachment1); - cut.addAttachment(attachment2); - cut.addAttachment(attachment3); + cut.addAttachment(attachment1); + cut.addAttachment(attachment2); + cut.addAttachment(attachment3); - assertThat(cut.getAttachments().size(), equalTo(3)); - } + assertThat(cut.getAttachments().size(), equalTo(3)); + } - @Test - void testAddNullValue() { - Attachment attachment1 = createAttachment("ID1", "taskId1"); - Attachment attachment2 = null; + @Test + void testAddNullValue() { + Attachment attachment1 = createAttachment("ID1", "taskId1"); + Attachment attachment2 = null; - cut.addAttachment(attachment1); - cut.addAttachment(attachment2); + cut.addAttachment(attachment1); + cut.addAttachment(attachment2); - assertThat(cut.getAttachments().size(), equalTo(1)); - } + assertThat(cut.getAttachments().size(), equalTo(1)); + } - @Test - void testAddSameTwice() { - // Same values, not same REF. Important. - Attachment attachment1 = createAttachment("ID1", "taskId1"); - Attachment attachment2 = createAttachment("ID1", "taskId1"); + @Test + void testAddSameTwice() { + // Same values, not same REF. Important. + Attachment attachment1 = createAttachment("ID1", "taskId1"); + Attachment attachment2 = createAttachment("ID1", "taskId1"); - cut.addAttachment(attachment1); - cut.addAttachment(attachment2); + cut.addAttachment(attachment1); + cut.addAttachment(attachment2); - assertThat(cut.getAttachments().size(), equalTo(1)); + assertThat(cut.getAttachments().size(), equalTo(1)); - // Check with not same vlaues (same ID) - String newChannel = "I will overwrite the other!"; - attachment1.setChannel(newChannel); - cut.addAttachment(attachment1); - assertThat(cut.getAttachments().size(), equalTo(1)); - assertThat(cut.getAttachments().get(0).getChannel(), equalTo(newChannel)); - } + // Check with not same vlaues (same ID) + String newChannel = "I will overwrite the other!"; + attachment1.setChannel(newChannel); + cut.addAttachment(attachment1); + assertThat(cut.getAttachments().size(), equalTo(1)); + assertThat(cut.getAttachments().get(0).getChannel(), equalTo(newChannel)); + } - @Test - void testRemoveAttachment() { - // Testing normal way - Attachment attachment1 = createAttachment("ID1", "taskId1"); - Attachment attachment2 = createAttachment("ID2", "taskId1"); - cut.addAttachment(attachment1); - cut.addAttachment(attachment2); + @Test + void testRemoveAttachment() { + // Testing normal way + Attachment attachment1 = createAttachment("ID1", "taskId1"); + Attachment attachment2 = createAttachment("ID2", "taskId1"); + cut.addAttachment(attachment1); + cut.addAttachment(attachment2); - Attachment actual = cut.removeAttachment(attachment2.getId()); + Attachment actual = cut.removeAttachment(attachment2.getId()); - assertThat(cut.getAttachments().size(), equalTo(1)); - assertThat(actual, equalTo(attachment2)); - } + assertThat(cut.getAttachments().size(), equalTo(1)); + assertThat(actual, equalTo(attachment2)); + } - @Test - void testRemoveLoopStopsAtResult() { - Attachment attachment1 = createAttachment("ID2", "taskId1"); - // adding same uncommon way to test that the loop will stop. - cut.getAttachments().add(attachment1); - cut.getAttachments().add(attachment1); - cut.getAttachments().add(attachment1); - assertThat(cut.getAttachments().size(), equalTo(3)); + @Test + void testRemoveLoopStopsAtResult() { + Attachment attachment1 = createAttachment("ID2", "taskId1"); + // adding same uncommon way to test that the loop will stop. + cut.getAttachments().add(attachment1); + cut.getAttachments().add(attachment1); + cut.getAttachments().add(attachment1); + assertThat(cut.getAttachments().size(), equalTo(3)); - Attachment actual = cut.removeAttachment(attachment1.getId()); + Attachment actual = cut.removeAttachment(attachment1.getId()); - assertThat(cut.getAttachments().size(), equalTo(2)); - assertThat(actual, equalTo(attachment1)); - } + assertThat(cut.getAttachments().size(), equalTo(2)); + assertThat(actual, equalTo(attachment1)); + } - @Test - void testGetAttachmentSummaries() { - ObjectReference objRef = new ObjectReference(); - objRef.setId("ObjRefId"); - objRef.setCompany("company"); + @Test + void testGetAttachmentSummaries() { + ObjectReference objRef = new ObjectReference(); + objRef.setId("ObjRefId"); + objRef.setCompany("company"); - Map customAttr = new HashMap<>(); - customAttr.put("key", "value"); + Map customAttr = new HashMap<>(); + customAttr.put("key", "value"); - Attachment attachment1 = createAttachment("ID1", "taskId1"); - attachment1.setChannel("channel"); - attachment1.setClassificationSummary(new ClassificationImpl().asSummary()); - attachment1.setReceived(Instant.now()); - attachment1.setObjectReference(objRef); - //attachment1.setCustomAttributes(customAttr); + Attachment attachment1 = createAttachment("ID1", "taskId1"); + attachment1.setChannel("channel"); + attachment1.setClassificationSummary(new ClassificationImpl().asSummary()); + attachment1.setReceived(Instant.now()); + attachment1.setObjectReference(objRef); + // attachment1.setCustomAttributes(customAttr); - cut.addAttachment(attachment1); + cut.addAttachment(attachment1); - List summaries = cut.asSummary().getAttachmentSummaries(); - AttachmentSummary attachmentSummary = summaries.get(0); + List summaries = cut.asSummary().getAttachmentSummaries(); + AttachmentSummary attachmentSummary = summaries.get(0); - assertThat(attachmentSummary, equalTo(attachment1.asSummary())); + assertThat(attachmentSummary, equalTo(attachment1.asSummary())); - assertThat(attachmentSummary.getId(), equalTo(attachment1.getId())); - assertThat(attachmentSummary.getTaskId(), equalTo(attachment1.getTaskId())); - assertThat(attachmentSummary.getChannel(), equalTo(attachment1.getChannel())); - assertThat(attachmentSummary.getClassificationSummary(), equalTo(attachment1.getClassificationSummary())); - assertThat(attachmentSummary.getObjectReference(), equalTo(attachment1.getObjectReference())); - assertThat(attachmentSummary.getCreated(), equalTo(attachment1.getCreated())); - assertThat(attachmentSummary.getReceived(), equalTo(attachment1.getReceived())); - assertThat(attachmentSummary.getModified(), equalTo(attachment1.getModified())); + assertThat(attachmentSummary.getId(), equalTo(attachment1.getId())); + assertThat(attachmentSummary.getTaskId(), equalTo(attachment1.getTaskId())); + assertThat(attachmentSummary.getChannel(), equalTo(attachment1.getChannel())); + assertThat( + attachmentSummary.getClassificationSummary(), + equalTo(attachment1.getClassificationSummary())); + assertThat(attachmentSummary.getObjectReference(), equalTo(attachment1.getObjectReference())); + assertThat(attachmentSummary.getCreated(), equalTo(attachment1.getCreated())); + assertThat(attachmentSummary.getReceived(), equalTo(attachment1.getReceived())); + assertThat(attachmentSummary.getModified(), equalTo(attachment1.getModified())); - // Must be different - assertNotEquals(attachmentSummary.hashCode(), attachment1.hashCode()); + // Must be different + assertNotEquals(attachmentSummary.hashCode(), attachment1.hashCode()); - cut.removeAttachment("ID1"); - assertThat(summaries.size(), equalTo(1)); - summaries = cut.asSummary().getAttachmentSummaries(); - assertThat(summaries.size(), equalTo(0)); - } + cut.removeAttachment("ID1"); + assertThat(summaries.size(), equalTo(1)); + summaries = cut.asSummary().getAttachmentSummaries(); + assertThat(summaries.size(), equalTo(0)); + } - private Attachment createAttachment(String id, String taskId) { - AttachmentImpl attachment = new AttachmentImpl(); - attachment.setId(id); - attachment.setTaskId(taskId); - return attachment; - } + private Attachment createAttachment(String id, String taskId) { + AttachmentImpl attachment = new AttachmentImpl(); + attachment.setId(id); + attachment.setTaskId(taskId); + return attachment; + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/TaskQueryImplTest.java b/lib/taskana-core/src/test/java/pro/taskana/impl/TaskQueryImplTest.java index bbd221b37..f05832d4e 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/TaskQueryImplTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/TaskQueryImplTest.java @@ -6,7 +6,6 @@ import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; - import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSession; import org.junit.jupiter.api.BeforeEach; @@ -28,70 +27,72 @@ import pro.taskana.configuration.DB; @ExtendWith(MockitoExtension.class) class TaskQueryImplTest { - @Mock - TaskServiceImpl taskServiceMock; + @Mock TaskServiceImpl taskServiceMock; - private TaskQueryImpl taskQueryImpl; - @Mock - private InternalTaskanaEngine internalTaskanaEngine; - @Mock - private TaskanaEngine taskanaEngine; - @Mock - private SqlSession sqlSession; + private TaskQueryImpl taskQueryImpl; + @Mock private InternalTaskanaEngine internalTaskanaEngine; + @Mock private TaskanaEngine taskanaEngine; + @Mock private SqlSession sqlSession; - @BeforeEach - void setup() { - when(internalTaskanaEngine.getEngine()).thenReturn(taskanaEngine); - when(taskanaEngine.getTaskService()).thenReturn(taskServiceMock); + @BeforeEach + void setup() { + when(internalTaskanaEngine.getEngine()).thenReturn(taskanaEngine); + when(taskanaEngine.getTaskService()).thenReturn(taskServiceMock); - Configuration configuration = new org.apache.ibatis.session.Configuration(); - configuration.setDatabaseId(DB.H2.dbProductId); - when(internalTaskanaEngine.getSqlSession()).thenReturn(sqlSession); - when(sqlSession.getConfiguration()).thenReturn(configuration); + Configuration configuration = new org.apache.ibatis.session.Configuration(); + configuration.setDatabaseId(DB.H2.dbProductId); + when(internalTaskanaEngine.getSqlSession()).thenReturn(sqlSession); + when(sqlSession.getConfiguration()).thenReturn(configuration); - taskQueryImpl = new TaskQueryImpl(internalTaskanaEngine); - } + taskQueryImpl = new TaskQueryImpl(internalTaskanaEngine); + } - @Test - void should_ReturnList_when_BuilderIsUsed() { - when(sqlSession.selectList(any(), any())).thenReturn(new ArrayList<>()); - List intermediate = new ArrayList<>(); - intermediate.add(new TaskSummaryImpl()); - when(taskServiceMock.augmentTaskSummariesByContainedSummaries(any())).thenReturn(intermediate); + @Test + void should_ReturnList_when_BuilderIsUsed() { + when(sqlSession.selectList(any(), any())).thenReturn(new ArrayList<>()); + List intermediate = new ArrayList<>(); + intermediate.add(new TaskSummaryImpl()); + when(taskServiceMock.augmentTaskSummariesByContainedSummaries(any())).thenReturn(intermediate); - List result = taskQueryImpl.nameIn("test", "asd", "blubber") + List result = + taskQueryImpl + .nameIn("test", "asd", "blubber") .priorityIn(1, 2) .stateIn(TaskState.CLAIMED, TaskState.COMPLETED) .list(); - assertNotNull(result); - } + assertNotNull(result); + } - @Test - void should_ReturnListWithOffset_when_BuilderIsUsed() { - when(sqlSession.selectList(any(), any(), any())).thenReturn(new ArrayList<>()); - List intermediate = new ArrayList<>(); - intermediate.add(new TaskSummaryImpl()); - when(taskServiceMock.augmentTaskSummariesByContainedSummaries(any())).thenReturn(intermediate); + @Test + void should_ReturnListWithOffset_when_BuilderIsUsed() { + when(sqlSession.selectList(any(), any(), any())).thenReturn(new ArrayList<>()); + List intermediate = new ArrayList<>(); + intermediate.add(new TaskSummaryImpl()); + when(taskServiceMock.augmentTaskSummariesByContainedSummaries(any())).thenReturn(intermediate); - List result = taskQueryImpl.nameIn("test", "asd", "blubber") + List result = + taskQueryImpl + .nameIn("test", "asd", "blubber") .priorityIn(1, 2) .stateIn(TaskState.CLAIMED, TaskState.COMPLETED) .list(1, 1); - assertNotNull(result); - } + assertNotNull(result); + } - @Test - void should_ReturnOneItem_when_BuilderIsUsed() { - when(sqlSession.selectOne(any(), any())).thenReturn(new TaskSummaryImpl()); - List intermediate = new ArrayList<>(); - intermediate.add(new TaskSummaryImpl()); + @Test + void should_ReturnOneItem_when_BuilderIsUsed() { + when(sqlSession.selectOne(any(), any())).thenReturn(new TaskSummaryImpl()); + List intermediate = new ArrayList<>(); + intermediate.add(new TaskSummaryImpl()); - when(taskServiceMock.augmentTaskSummariesByContainedSummaries(any())).thenReturn(intermediate); + when(taskServiceMock.augmentTaskSummariesByContainedSummaries(any())).thenReturn(intermediate); - TaskSummary result = taskQueryImpl.nameIn("test", "asd", "blubber") + TaskSummary result = + taskQueryImpl + .nameIn("test", "asd", "blubber") .priorityIn(1, 2) .stateIn(TaskState.CLAIMED, TaskState.COMPLETED) .single(); - assertNotNull(result); - } + assertNotNull(result); + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/TaskServiceImplTest.java b/lib/taskana-core/src/test/java/pro/taskana/impl/TaskServiceImplTest.java index 1898cf3a5..cd290232b 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/TaskServiceImplTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/TaskServiceImplTest.java @@ -7,7 +7,6 @@ import static org.mockito.Mockito.when; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; - import org.apache.ibatis.session.SqlSession; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -34,114 +33,105 @@ import pro.taskana.mappings.TaskMapper; @ExtendWith(MockitoExtension.class) class TaskServiceImplTest { - private TaskServiceImpl cut; + private TaskServiceImpl cut; - @Mock - private TaskanaEngineConfiguration taskanaEngineConfigurationMock; + @Mock private TaskanaEngineConfiguration taskanaEngineConfigurationMock; - @Mock - private InternalTaskanaEngine internalTaskanaEngineMock; + @Mock private InternalTaskanaEngine internalTaskanaEngineMock; - @Mock - private TaskanaEngine taskanaEngineMock; + @Mock private TaskanaEngine taskanaEngineMock; - @Mock - private TaskMapper taskMapperMock; + @Mock private TaskMapper taskMapperMock; - @Mock - private ObjectReferenceMapper objectReferenceMapperMock; + @Mock private ObjectReferenceMapper objectReferenceMapperMock; - @Mock - private WorkbasketService workbasketServiceMock; + @Mock private WorkbasketService workbasketServiceMock; - @Mock - private ClassificationServiceImpl classificationServiceImplMock; + @Mock private ClassificationServiceImpl classificationServiceImplMock; - @Mock - private AttachmentMapper attachmentMapperMock; + @Mock private AttachmentMapper attachmentMapperMock; - @Mock - private ClassificationQueryImpl classificationQueryImplMock; + @Mock private ClassificationQueryImpl classificationQueryImplMock; - @Mock - private SqlSession sqlSessionMock; + @Mock private SqlSession sqlSessionMock; - @BeforeEach - void setup() { - when(internalTaskanaEngineMock.getEngine()).thenReturn(taskanaEngineMock); - when(taskanaEngineMock.getWorkbasketService()).thenReturn(workbasketServiceMock); - when(taskanaEngineMock.getClassificationService()).thenReturn(classificationServiceImplMock); - cut = new TaskServiceImpl(internalTaskanaEngineMock, taskMapperMock, attachmentMapperMock); + @BeforeEach + void setup() { + when(internalTaskanaEngineMock.getEngine()).thenReturn(taskanaEngineMock); + when(taskanaEngineMock.getWorkbasketService()).thenReturn(workbasketServiceMock); + when(taskanaEngineMock.getClassificationService()).thenReturn(classificationServiceImplMock); + cut = new TaskServiceImpl(internalTaskanaEngineMock, taskMapperMock, attachmentMapperMock); + } + + @Test + void testTaskSummaryEqualsHashCode() throws InterruptedException { + Classification classification = createDummyClassification(); + Workbasket wb = createWorkbasket("WB-ID", "WB-Key"); + ObjectReference objectReference = JunitHelper.createDefaultObjRef(); + TaskImpl taskBefore = createUnitTestTask("ID", "taskName", wb.getKey(), classification); + taskBefore.setPrimaryObjRef(objectReference); + Thread.sleep(10); + TaskImpl taskAfter = createUnitTestTask("ID", "taskName", wb.getKey(), classification); + taskAfter.setPrimaryObjRef(objectReference); + TaskSummary summaryBefore = taskBefore.asSummary(); + TaskSummary summaryAfter = taskAfter.asSummary(); + + assertNotEquals(summaryBefore, summaryAfter); + assertNotEquals(summaryBefore.hashCode(), summaryAfter.hashCode()); + + taskAfter.setCreated(taskBefore.getCreated()); + taskAfter.setModified(taskBefore.getModified()); + summaryAfter = taskAfter.asSummary(); + assertEquals(summaryBefore, summaryAfter); + assertEquals(summaryBefore.hashCode(), summaryAfter.hashCode()); + + taskBefore.setModified(null); + summaryBefore = taskBefore.asSummary(); + assertNotEquals(summaryBefore, summaryAfter); + assertNotEquals(summaryBefore.hashCode(), summaryAfter.hashCode()); + + taskAfter.setModified(null); + summaryAfter = taskAfter.asSummary(); + assertEquals(summaryBefore, summaryAfter); + assertEquals(summaryBefore.hashCode(), summaryAfter.hashCode()); + } + + static TaskImpl createUnitTestTask( + String id, String name, String workbasketKey, Classification classification) { + TaskImpl task = new TaskImpl(); + task.setId(id); + task.setExternalId(id); + task.setName(name); + task.setWorkbasketKey(workbasketKey); + task.setDomain(""); + task.setAttachments(new ArrayList<>()); + Instant now = Instant.now().minus(Duration.ofMinutes(1L)); + task.setCreated(now); + task.setModified(now); + if (classification == null) { + classification = createDummyClassification(); } + task.setClassificationSummary(classification.asSummary()); + task.setClassificationKey(classification.getKey()); + task.setDomain(classification.getDomain()); + return task; + } - @Test - void testTaskSummaryEqualsHashCode() throws InterruptedException { - Classification classification = createDummyClassification(); - Workbasket wb = createWorkbasket("WB-ID", "WB-Key"); - ObjectReference objectReference = JunitHelper.createDefaultObjRef(); - TaskImpl taskBefore = createUnitTestTask("ID", "taskName", wb.getKey(), classification); - taskBefore.setPrimaryObjRef(objectReference); - Thread.sleep(10); - TaskImpl taskAfter = createUnitTestTask("ID", "taskName", wb.getKey(), classification); - taskAfter.setPrimaryObjRef(objectReference); - TaskSummary summaryBefore = taskBefore.asSummary(); - TaskSummary summaryAfter = taskAfter.asSummary(); + static Classification createDummyClassification() { + ClassificationImpl classification = new ClassificationImpl(); + classification.setName("dummy-classification"); + classification.setDomain("dummy-domain"); + classification.setKey("dummy-classification-key"); + classification.setId("DummyClassificationId"); + return classification; + } - assertNotEquals(summaryBefore, summaryAfter); - assertNotEquals(summaryBefore.hashCode(), summaryAfter.hashCode()); - - taskAfter.setCreated(taskBefore.getCreated()); - taskAfter.setModified(taskBefore.getModified()); - summaryAfter = taskAfter.asSummary(); - assertEquals(summaryBefore, summaryAfter); - assertEquals(summaryBefore.hashCode(), summaryAfter.hashCode()); - - taskBefore.setModified(null); - summaryBefore = taskBefore.asSummary(); - assertNotEquals(summaryBefore, summaryAfter); - assertNotEquals(summaryBefore.hashCode(), summaryAfter.hashCode()); - - taskAfter.setModified(null); - summaryAfter = taskAfter.asSummary(); - assertEquals(summaryBefore, summaryAfter); - assertEquals(summaryBefore.hashCode(), summaryAfter.hashCode()); - } - - static TaskImpl createUnitTestTask(String id, String name, String workbasketKey, Classification classification) { - TaskImpl task = new TaskImpl(); - task.setId(id); - task.setExternalId(id); - task.setName(name); - task.setWorkbasketKey(workbasketKey); - task.setDomain(""); - task.setAttachments(new ArrayList<>()); - Instant now = Instant.now().minus(Duration.ofMinutes(1L)); - task.setCreated(now); - task.setModified(now); - if (classification == null) { - classification = createDummyClassification(); - } - task.setClassificationSummary(classification.asSummary()); - task.setClassificationKey(classification.getKey()); - task.setDomain(classification.getDomain()); - return task; - } - - static Classification createDummyClassification() { - ClassificationImpl classification = new ClassificationImpl(); - classification.setName("dummy-classification"); - classification.setDomain("dummy-domain"); - classification.setKey("dummy-classification-key"); - classification.setId("DummyClassificationId"); - return classification; - } - - static WorkbasketImpl createWorkbasket(String id, String key) { - WorkbasketImpl workbasket = new WorkbasketImpl(); - workbasket.setId(id); - workbasket.setDomain("Domain1"); - workbasket.setKey(key); - workbasket.setName("Workbasket " + id); - return workbasket; - } + static WorkbasketImpl createWorkbasket(String id, String key) { + WorkbasketImpl workbasket = new WorkbasketImpl(); + workbasket.setId(id); + workbasket.setDomain("Domain1"); + workbasket.setKey(key); + workbasket.setName("Workbasket " + id); + return workbasket; + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/TaskStatusReportBuilderImplTest.java b/lib/taskana-core/src/test/java/pro/taskana/impl/TaskStatusReportBuilderImplTest.java index 285dc4656..ebc622ec1 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/TaskStatusReportBuilderImplTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/TaskStatusReportBuilderImplTest.java @@ -11,7 +11,6 @@ import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.Collections; import java.util.List; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -29,96 +28,96 @@ import pro.taskana.impl.report.item.TaskQueryItem; import pro.taskana.mappings.TaskMonitorMapper; import pro.taskana.report.TaskStatusReport; -/** - * Unit Test for TaskStatusReportBuilderImpl. - */ +/** Unit Test for TaskStatusReportBuilderImpl. */ @ExtendWith(MockitoExtension.class) class TaskStatusReportBuilderImplTest { - @InjectMocks - private TaskMonitorServiceImpl cut; + @InjectMocks private TaskMonitorServiceImpl cut; - @Mock - private InternalTaskanaEngine internalTaskanaEngineMock; + @Mock private InternalTaskanaEngine internalTaskanaEngineMock; - @Mock - private TaskanaEngine taskanaEngineMock; + @Mock private TaskanaEngine taskanaEngineMock; - @Mock - private TaskMonitorMapper taskMonitorMapperMock; + @Mock private TaskMonitorMapper taskMonitorMapperMock; - @BeforeEach - void setup() { - when(internalTaskanaEngineMock.getEngine()).thenReturn(taskanaEngineMock); - } + @BeforeEach + void setup() { + when(internalTaskanaEngineMock.getEngine()).thenReturn(taskanaEngineMock); + } - @Test - void testGetTaskStateReportWithoutFilters() throws NotAuthorizedException, InvalidArgumentException { - // given - TaskQueryItem queryItem1 = new TaskQueryItem(); - queryItem1.setCount(50); - queryItem1.setState(TaskState.READY); - queryItem1.setDomain("DOMAIN_X"); - TaskQueryItem queryItem2 = new TaskQueryItem(); - queryItem2.setCount(30); - queryItem2.setState(TaskState.COMPLETED); - queryItem2.setDomain("DOMAIN_X"); - List queryItems = Arrays.asList(queryItem1, queryItem2); - when(taskMonitorMapperMock.getTasksCountByState(null, null)).thenReturn(queryItems); + @Test + void testGetTaskStateReportWithoutFilters() + throws NotAuthorizedException, InvalidArgumentException { + // given + TaskQueryItem queryItem1 = new TaskQueryItem(); + queryItem1.setCount(50); + queryItem1.setState(TaskState.READY); + queryItem1.setDomain("DOMAIN_X"); + TaskQueryItem queryItem2 = new TaskQueryItem(); + queryItem2.setCount(30); + queryItem2.setState(TaskState.COMPLETED); + queryItem2.setDomain("DOMAIN_X"); + List queryItems = Arrays.asList(queryItem1, queryItem2); + when(taskMonitorMapperMock.getTasksCountByState(null, null)).thenReturn(queryItems); - // when - TaskStatusReport report = cut.createTaskStatusReportBuilder().buildReport(); + // when + TaskStatusReport report = cut.createTaskStatusReportBuilder().buildReport(); - // then - InOrder inOrder = inOrder(taskanaEngineMock, internalTaskanaEngineMock, taskMonitorMapperMock); - inOrder.verify(internalTaskanaEngineMock).getEngine(); - inOrder.verify(taskanaEngineMock).checkRoleMembership(TaskanaRole.MONITOR, TaskanaRole.ADMIN); - inOrder.verify(internalTaskanaEngineMock).openConnection(); - inOrder.verify(taskMonitorMapperMock).getTasksCountByState(eq(null), eq(null)); - inOrder.verify(internalTaskanaEngineMock).returnConnection(); - inOrder.verifyNoMoreInteractions(); - verifyNoMoreInteractions(taskanaEngineMock, internalTaskanaEngineMock, taskMonitorMapperMock); + // then + InOrder inOrder = inOrder(taskanaEngineMock, internalTaskanaEngineMock, taskMonitorMapperMock); + inOrder.verify(internalTaskanaEngineMock).getEngine(); + inOrder.verify(taskanaEngineMock).checkRoleMembership(TaskanaRole.MONITOR, TaskanaRole.ADMIN); + inOrder.verify(internalTaskanaEngineMock).openConnection(); + inOrder.verify(taskMonitorMapperMock).getTasksCountByState(eq(null), eq(null)); + inOrder.verify(internalTaskanaEngineMock).returnConnection(); + inOrder.verifyNoMoreInteractions(); + verifyNoMoreInteractions(taskanaEngineMock, internalTaskanaEngineMock, taskMonitorMapperMock); - assertNotNull(report); - assertEquals(1, report.rowSize()); - assertArrayEquals(new int[] {50, 0, 30}, report.getRow("DOMAIN_X").getCells()); - assertArrayEquals(new int[] {50, 0, 30}, report.getSumRow().getCells()); - assertEquals(80, report.getRow("DOMAIN_X").getTotalValue()); - assertEquals(80, report.getSumRow().getTotalValue()); - } + assertNotNull(report); + assertEquals(1, report.rowSize()); + assertArrayEquals(new int[] {50, 0, 30}, report.getRow("DOMAIN_X").getCells()); + assertArrayEquals(new int[] {50, 0, 30}, report.getSumRow().getCells()); + assertEquals(80, report.getRow("DOMAIN_X").getTotalValue()); + assertEquals(80, report.getSumRow().getTotalValue()); + } - @Test - void testGetTotalNumberOfTaskStateReport() throws NotAuthorizedException, InvalidArgumentException { - // given - TaskQueryItem queryItem1 = new TaskQueryItem(); - queryItem1.setCount(50); - queryItem1.setState(TaskState.READY); - queryItem1.setDomain("DOMAIN_X"); - TaskQueryItem queryItem2 = new TaskQueryItem(); - queryItem2.setCount(30); - queryItem2.setState(TaskState.COMPLETED); - queryItem2.setDomain("DOMAIN_X"); - List queryItems = Arrays.asList(queryItem1, queryItem2); - when(taskMonitorMapperMock.getTasksCountByState(eq(null), eq(Collections.emptyList()))).thenReturn(queryItems); + @Test + void testGetTotalNumberOfTaskStateReport() + throws NotAuthorizedException, InvalidArgumentException { + // given + TaskQueryItem queryItem1 = new TaskQueryItem(); + queryItem1.setCount(50); + queryItem1.setState(TaskState.READY); + queryItem1.setDomain("DOMAIN_X"); + TaskQueryItem queryItem2 = new TaskQueryItem(); + queryItem2.setCount(30); + queryItem2.setState(TaskState.COMPLETED); + queryItem2.setDomain("DOMAIN_X"); + List queryItems = Arrays.asList(queryItem1, queryItem2); + when(taskMonitorMapperMock.getTasksCountByState(eq(null), eq(Collections.emptyList()))) + .thenReturn(queryItems); - // when - TaskStatusReport report = cut.createTaskStatusReportBuilder().stateIn(Collections.emptyList()).buildReport(); + // when + TaskStatusReport report = + cut.createTaskStatusReportBuilder().stateIn(Collections.emptyList()).buildReport(); - // then - InOrder inOrder = inOrder(taskanaEngineMock, taskMonitorMapperMock, internalTaskanaEngineMock); - inOrder.verify(internalTaskanaEngineMock).getEngine(); - inOrder.verify(taskanaEngineMock).checkRoleMembership(TaskanaRole.MONITOR, TaskanaRole.ADMIN); - inOrder.verify(internalTaskanaEngineMock).openConnection(); - inOrder.verify(taskMonitorMapperMock).getTasksCountByState(eq(null), eq(Collections.emptyList())); - inOrder.verify(internalTaskanaEngineMock).returnConnection(); - inOrder.verifyNoMoreInteractions(); - verifyNoMoreInteractions(taskanaEngineMock, taskMonitorMapperMock, internalTaskanaEngineMock); + // then + InOrder inOrder = inOrder(taskanaEngineMock, taskMonitorMapperMock, internalTaskanaEngineMock); + inOrder.verify(internalTaskanaEngineMock).getEngine(); + inOrder.verify(taskanaEngineMock).checkRoleMembership(TaskanaRole.MONITOR, TaskanaRole.ADMIN); + inOrder.verify(internalTaskanaEngineMock).openConnection(); + inOrder + .verify(taskMonitorMapperMock) + .getTasksCountByState(eq(null), eq(Collections.emptyList())); + inOrder.verify(internalTaskanaEngineMock).returnConnection(); + inOrder.verifyNoMoreInteractions(); + verifyNoMoreInteractions(taskanaEngineMock, taskMonitorMapperMock, internalTaskanaEngineMock); - assertNotNull(report); - assertEquals(1, report.rowSize()); - assertArrayEquals(new int[0], report.getRow("DOMAIN_X").getCells()); - assertArrayEquals(new int[0], report.getSumRow().getCells()); - assertEquals(80, report.getRow("DOMAIN_X").getTotalValue()); - assertEquals(80, report.getSumRow().getTotalValue()); - } + assertNotNull(report); + assertEquals(1, report.rowSize()); + assertArrayEquals(new int[0], report.getRow("DOMAIN_X").getCells()); + assertArrayEquals(new int[0], report.getSumRow().getCells()); + assertEquals(80, report.getRow("DOMAIN_X").getTotalValue()); + assertEquals(80, report.getSumRow().getTotalValue()); + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/TaskTransferrerTest.java b/lib/taskana-core/src/test/java/pro/taskana/impl/TaskTransferrerTest.java index 3be9b7713..2ba4be282 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/TaskTransferrerTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/TaskTransferrerTest.java @@ -40,79 +40,78 @@ import pro.taskana.mappings.TaskMapper; @ExtendWith(MockitoExtension.class) class TaskTransferrerTest { - private TaskTransferrer cut; - @Mock - private TaskServiceImpl taskServiceImplMock; + private TaskTransferrer cut; + @Mock private TaskServiceImpl taskServiceImplMock; - @Mock - private TaskanaEngineConfiguration taskanaEngineConfigurationMock; + @Mock private TaskanaEngineConfiguration taskanaEngineConfigurationMock; - @Mock - private InternalTaskanaEngine internalTaskanaEngineMock; + @Mock private InternalTaskanaEngine internalTaskanaEngineMock; - @Mock - private TaskanaEngine taskanaEngineMock; + @Mock private TaskanaEngine taskanaEngineMock; - @Mock - private TaskMapper taskMapperMock; + @Mock private TaskMapper taskMapperMock; - @Mock - private ObjectReferenceMapper objectReferenceMapperMock; + @Mock private ObjectReferenceMapper objectReferenceMapperMock; - @Mock - private WorkbasketService workbasketServiceMock; + @Mock private WorkbasketService workbasketServiceMock; - @Mock - private ClassificationServiceImpl classificationServiceImplMock; + @Mock private ClassificationServiceImpl classificationServiceImplMock; - @Mock - private AttachmentMapper attachmentMapperMock; + @Mock private AttachmentMapper attachmentMapperMock; - @Mock - private ClassificationQueryImpl classificationQueryImplMock; + @Mock private ClassificationQueryImpl classificationQueryImplMock; - @Mock - private SqlSession sqlSessionMock; + @Mock private SqlSession sqlSessionMock; - @Test - void testTransferTaskToDestinationWorkbasketWithoutSecurity() - throws TaskNotFoundException, WorkbasketNotFoundException, NotAuthorizedException, InvalidStateException { + @Test + void testTransferTaskToDestinationWorkbasketWithoutSecurity() + throws TaskNotFoundException, WorkbasketNotFoundException, NotAuthorizedException, + InvalidStateException { - when(internalTaskanaEngineMock.getEngine()).thenReturn(taskanaEngineMock); - when(taskanaEngineMock.getWorkbasketService()).thenReturn(workbasketServiceMock); - cut = new TaskTransferrer(internalTaskanaEngineMock, taskMapperMock, taskServiceImplMock); + when(internalTaskanaEngineMock.getEngine()).thenReturn(taskanaEngineMock); + when(taskanaEngineMock.getWorkbasketService()).thenReturn(workbasketServiceMock); + cut = new TaskTransferrer(internalTaskanaEngineMock, taskMapperMock, taskServiceImplMock); - TaskTransferrer cutSpy = Mockito.spy(cut); - Workbasket destinationWorkbasket = TaskServiceImplTest.createWorkbasket("2", "k1"); - Workbasket sourceWorkbasket = TaskServiceImplTest.createWorkbasket("47", "key47"); - Classification dummyClassification = TaskServiceImplTest.createDummyClassification(); - TaskImpl task = TaskServiceImplTest.createUnitTestTask("1", "Unit Test Task 1", "key47", dummyClassification); - task.setWorkbasketSummary(sourceWorkbasket.asSummary()); - task.setRead(true); - when(workbasketServiceMock.getWorkbasket(destinationWorkbasket.getId())).thenReturn(destinationWorkbasket); - doReturn(task).when(taskServiceImplMock).getTask(task.getId()); + TaskTransferrer cutSpy = Mockito.spy(cut); + Workbasket destinationWorkbasket = TaskServiceImplTest.createWorkbasket("2", "k1"); + Workbasket sourceWorkbasket = TaskServiceImplTest.createWorkbasket("47", "key47"); + Classification dummyClassification = TaskServiceImplTest.createDummyClassification(); + TaskImpl task = + TaskServiceImplTest.createUnitTestTask( + "1", "Unit Test Task 1", "key47", dummyClassification); + task.setWorkbasketSummary(sourceWorkbasket.asSummary()); + task.setRead(true); + when(workbasketServiceMock.getWorkbasket(destinationWorkbasket.getId())) + .thenReturn(destinationWorkbasket); + doReturn(task).when(taskServiceImplMock).getTask(task.getId()); - Task actualTask = cutSpy.transfer(task.getId(), destinationWorkbasket.getId()); + Task actualTask = cutSpy.transfer(task.getId(), destinationWorkbasket.getId()); - verify(internalTaskanaEngineMock, times(1)).openConnection(); - verify(workbasketServiceMock, times(1)).checkAuthorization(destinationWorkbasket.getId(), - WorkbasketPermission.APPEND); - verify(workbasketServiceMock, times(1)).checkAuthorization(sourceWorkbasket.getId(), - WorkbasketPermission.TRANSFER); - verify(workbasketServiceMock, times(1)).getWorkbasket(destinationWorkbasket.getId()); - verify(taskMapperMock, times(1)).update(any()); - verify(internalTaskanaEngineMock, times(1)).returnConnection(); - verify(internalTaskanaEngineMock, times(1)).getEngine(); - verify(internalTaskanaEngineMock).getHistoryEventProducer(); - verify(taskanaEngineMock).getWorkbasketService(); - verifyNoMoreInteractions(attachmentMapperMock, taskanaEngineConfigurationMock, taskanaEngineMock, - internalTaskanaEngineMock, taskMapperMock, objectReferenceMapperMock, workbasketServiceMock, - sqlSessionMock, classificationQueryImplMock); + verify(internalTaskanaEngineMock, times(1)).openConnection(); + verify(workbasketServiceMock, times(1)) + .checkAuthorization(destinationWorkbasket.getId(), WorkbasketPermission.APPEND); + verify(workbasketServiceMock, times(1)) + .checkAuthorization(sourceWorkbasket.getId(), WorkbasketPermission.TRANSFER); + verify(workbasketServiceMock, times(1)).getWorkbasket(destinationWorkbasket.getId()); + verify(taskMapperMock, times(1)).update(any()); + verify(internalTaskanaEngineMock, times(1)).returnConnection(); + verify(internalTaskanaEngineMock, times(1)).getEngine(); + verify(internalTaskanaEngineMock).getHistoryEventProducer(); + verify(taskanaEngineMock).getWorkbasketService(); + verifyNoMoreInteractions( + attachmentMapperMock, + taskanaEngineConfigurationMock, + taskanaEngineMock, + internalTaskanaEngineMock, + taskMapperMock, + objectReferenceMapperMock, + workbasketServiceMock, + sqlSessionMock, + classificationQueryImplMock); - assertThat(actualTask.isRead(), equalTo(false)); - assertThat(actualTask.getState(), equalTo(TaskState.READY)); - assertThat(actualTask.isTransferred(), equalTo(true)); - assertThat(actualTask.getWorkbasketKey(), equalTo(destinationWorkbasket.getKey())); - } + assertThat(actualTask.isRead(), equalTo(false)); + assertThat(actualTask.getState(), equalTo(TaskState.READY)); + assertThat(actualTask.isTransferred(), equalTo(true)); + assertThat(actualTask.getWorkbasketKey(), equalTo(destinationWorkbasket.getKey())); + } } - diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/TaskanaEngineProxyForTest.java b/lib/taskana-core/src/test/java/pro/taskana/impl/TaskanaEngineProxyForTest.java index 26109b642..bf3888df4 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/TaskanaEngineProxyForTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/TaskanaEngineProxyForTest.java @@ -1,7 +1,6 @@ package pro.taskana.impl; import java.lang.reflect.Field; - import org.apache.ibatis.session.SqlSession; import pro.taskana.TaskanaEngine; @@ -13,24 +12,24 @@ import pro.taskana.TaskanaEngine; */ public class TaskanaEngineProxyForTest { - private InternalTaskanaEngine engine; + private InternalTaskanaEngine engine; - public TaskanaEngineProxyForTest(TaskanaEngine taskanaEngine) throws NoSuchFieldException, IllegalAccessException { - Field internal = TaskanaEngineImpl.class.getDeclaredField("internalTaskanaEngineImpl"); - internal.setAccessible(true); - engine = (InternalTaskanaEngine) internal.get(taskanaEngine); - } + public TaskanaEngineProxyForTest(TaskanaEngine taskanaEngine) + throws NoSuchFieldException, IllegalAccessException { + Field internal = TaskanaEngineImpl.class.getDeclaredField("internalTaskanaEngineImpl"); + internal.setAccessible(true); + engine = (InternalTaskanaEngine) internal.get(taskanaEngine); + } - public SqlSession getSqlSession() { - return engine.getSqlSession(); - } + public SqlSession getSqlSession() { + return engine.getSqlSession(); + } - public void openConnection() { - engine.openConnection(); - } - - public void returnConnection() { - engine.returnConnection(); - } + public void openConnection() { + engine.openConnection(); + } + public void returnConnection() { + engine.returnConnection(); + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/TestClassificationQuery.java b/lib/taskana-core/src/test/java/pro/taskana/impl/TestClassificationQuery.java index 395c1d819..594f16f21 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/TestClassificationQuery.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/TestClassificationQuery.java @@ -8,197 +8,195 @@ import pro.taskana.ClassificationQueryColumnName; import pro.taskana.ClassificationSummary; import pro.taskana.TimeInterval; -/** - * Created by BV on 26.10.2017. - */ +/** Created by BV on 26.10.2017. */ public class TestClassificationQuery implements ClassificationQuery { - private List classifications; - private String[] parentId; - private String[] parentKey; - private String description; + private List classifications; + private String[] parentId; + private String[] parentKey; + private String description; - public TestClassificationQuery(List classifications) { - this.classifications = classifications; - } + public TestClassificationQuery(List classifications) { + this.classifications = classifications; + } - @Override - public ClassificationQuery keyIn(String... key) { - return this; - } + @Override + public ClassificationQuery keyIn(String... key) { + return this; + } - @Override - public ClassificationQuery idIn(String... id) { - return this; - } + @Override + public ClassificationQuery idIn(String... id) { + return this; + } - @Override - public ClassificationQuery parentIdIn(String... parentId) { - this.parentId = parentId; - return this; - } + @Override + public ClassificationQuery parentIdIn(String... parentId) { + this.parentId = parentId; + return this; + } - @Override - public ClassificationQuery parentKeyIn(String... parentKey) { - this.parentKey = parentKey; - return this; - } + @Override + public ClassificationQuery parentKeyIn(String... parentKey) { + this.parentKey = parentKey; + return this; + } - @Override - public ClassificationQuery categoryIn(String... category) { - return this; - } + @Override + public ClassificationQuery categoryIn(String... category) { + return this; + } - @Override - public ClassificationQuery typeIn(String... type) { - return this; - } + @Override + public ClassificationQuery typeIn(String... type) { + return this; + } - @Override - public ClassificationQuery domainIn(String... domain) { - return this; - } + @Override + public ClassificationQuery domainIn(String... domain) { + return this; + } - @Override - public ClassificationQuery validInDomainEquals(Boolean validInDomain) { - return this; - } + @Override + public ClassificationQuery validInDomainEquals(Boolean validInDomain) { + return this; + } - @Override - public ClassificationQuery createdWithin(TimeInterval... created) { - return this; - } + @Override + public ClassificationQuery createdWithin(TimeInterval... created) { + return this; + } - @Override - public ClassificationQuery nameIn(String... name) { - return this; - } + @Override + public ClassificationQuery nameIn(String... name) { + return this; + } - @Override - public ClassificationQuery nameLike(String... nameLike) { - return this; - } + @Override + public ClassificationQuery nameLike(String... nameLike) { + return this; + } - @Override - public ClassificationQuery descriptionLike(String description) { - return this; - } + @Override + public ClassificationQuery descriptionLike(String description) { + return this; + } - @Override - public ClassificationQuery priorityIn(int... priorities) { - return this; - } + @Override + public ClassificationQuery priorityIn(int... priorities) { + return this; + } - @Override - public ClassificationQuery serviceLevelIn(String... serviceLevel) { - return this; - } + @Override + public ClassificationQuery serviceLevelIn(String... serviceLevel) { + return this; + } - @Override - public ClassificationQuery serviceLevelLike(String... serviceLevelLike) { - return this; - } + @Override + public ClassificationQuery serviceLevelLike(String... serviceLevelLike) { + return this; + } - @Override - public ClassificationQuery applicationEntryPointIn(String... applicationEntryPoint) { - return null; - } + @Override + public ClassificationQuery applicationEntryPointIn(String... applicationEntryPoint) { + return null; + } - @Override - public ClassificationQuery applicationEntryPointLike(String... applicationEntryPointLike) { - return this; - } + @Override + public ClassificationQuery applicationEntryPointLike(String... applicationEntryPointLike) { + return this; + } - @Override - public ClassificationQuery customAttributeIn(String num, String... customFields) { - return this; - } + @Override + public ClassificationQuery customAttributeIn(String num, String... customFields) { + return this; + } - @Override - public ClassificationQuery customAttributeLike(String num, String... custom1Like) { - return this; - } + @Override + public ClassificationQuery customAttributeLike(String num, String... custom1Like) { + return this; + } - @Override - public List list() { - List returnedClassifications = new ArrayList<>(); - returnedClassifications.addAll(classifications); - return returnedClassifications; - } + @Override + public List list() { + List returnedClassifications = new ArrayList<>(); + returnedClassifications.addAll(classifications); + return returnedClassifications; + } - @Override - public List list(int offset, int limit) { - return new ArrayList<>(); - } + @Override + public List list(int offset, int limit) { + return new ArrayList<>(); + } - @Override - public ClassificationSummary single() { - return null; - } + @Override + public ClassificationSummary single() { + return null; + } - @Override - public long count() { - return 0; - } + @Override + public long count() { + return 0; + } - @Override - public ClassificationQuery orderByKey(SortDirection sortDirection) { - return this; - } + @Override + public ClassificationQuery orderByKey(SortDirection sortDirection) { + return this; + } - @Override - public ClassificationQuery orderByParentId(SortDirection sortDirection) { - return this; - } + @Override + public ClassificationQuery orderByParentId(SortDirection sortDirection) { + return this; + } - @Override - public ClassificationQuery orderByParentKey(SortDirection sortDirection) { - return this; - } + @Override + public ClassificationQuery orderByParentKey(SortDirection sortDirection) { + return this; + } - @Override - public ClassificationQuery orderByCategory(SortDirection sortDirection) { - return this; - } + @Override + public ClassificationQuery orderByCategory(SortDirection sortDirection) { + return this; + } - @Override - public ClassificationQuery orderByDomain(SortDirection sortDirection) { - return this; - } + @Override + public ClassificationQuery orderByDomain(SortDirection sortDirection) { + return this; + } - @Override - public ClassificationQuery orderByName(SortDirection sortDirection) { - return this; - } + @Override + public ClassificationQuery orderByName(SortDirection sortDirection) { + return this; + } - @Override - public ClassificationQuery orderByServiceLevel(SortDirection sortDirection) { - return this; - } + @Override + public ClassificationQuery orderByServiceLevel(SortDirection sortDirection) { + return this; + } - @Override - public ClassificationQuery orderByPriority(SortDirection sortDirection) { - return this; - } + @Override + public ClassificationQuery orderByPriority(SortDirection sortDirection) { + return this; + } - @Override - public ClassificationQuery orderByApplicationEntryPoint(SortDirection sortDirection) { - return this; - } + @Override + public ClassificationQuery orderByApplicationEntryPoint(SortDirection sortDirection) { + return this; + } - @Override - public ClassificationQuery orderByCustomAttribute(String num, SortDirection sortDirection) { - return this; - } + @Override + public ClassificationQuery orderByCustomAttribute(String num, SortDirection sortDirection) { + return this; + } - @Override - public ClassificationQuery modifiedWithin(TimeInterval... modifiedIn) { - return this; - } - - @Override - public List listValues(ClassificationQueryColumnName dbColumnName, SortDirection sortDirection) { - return new ArrayList<>(); - } + @Override + public ClassificationQuery modifiedWithin(TimeInterval... modifiedIn) { + return this; + } + @Override + public List listValues( + ClassificationQueryColumnName dbColumnName, SortDirection sortDirection) { + return new ArrayList<>(); + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/WorkbasketAccessItemQueryImplTest.java b/lib/taskana-core/src/test/java/pro/taskana/impl/WorkbasketAccessItemQueryImplTest.java index 3698b60d5..8acdbb32d 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/WorkbasketAccessItemQueryImplTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/WorkbasketAccessItemQueryImplTest.java @@ -6,7 +6,6 @@ import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; - import org.apache.ibatis.session.SqlSession; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -24,41 +23,37 @@ import pro.taskana.WorkbasketAccessItem; @ExtendWith(MockitoExtension.class) class WorkbasketAccessItemQueryImplTest { - @InjectMocks - private WorkbasketAccessItemQueryImpl workbasketAccessItemQueryImpl; + @InjectMocks private WorkbasketAccessItemQueryImpl workbasketAccessItemQueryImpl; - @Mock - private InternalTaskanaEngine internalTaskanaEngine; + @Mock private InternalTaskanaEngine internalTaskanaEngine; - @Mock - private SqlSession sqlSession; + @Mock private SqlSession sqlSession; - @Test - void should_ReturnList_when_BuilderIsUsed() { - when(internalTaskanaEngine.openAndReturnConnection(any())).thenReturn(new ArrayList<>()); + @Test + void should_ReturnList_when_BuilderIsUsed() { + when(internalTaskanaEngine.openAndReturnConnection(any())).thenReturn(new ArrayList<>()); - List result = workbasketAccessItemQueryImpl.accessIdIn("test", "asd") - .list(); - assertNotNull(result); - } + List result = + workbasketAccessItemQueryImpl.accessIdIn("test", "asd").list(); + assertNotNull(result); + } - @Test - void should_ReturnListWithOffset_when_BuilderIsUsed() { - when(internalTaskanaEngine.getSqlSession()).thenReturn(sqlSession); - when(sqlSession.selectList(any(), any(), any())).thenReturn(new ArrayList<>()); + @Test + void should_ReturnListWithOffset_when_BuilderIsUsed() { + when(internalTaskanaEngine.getSqlSession()).thenReturn(sqlSession); + when(sqlSession.selectList(any(), any(), any())).thenReturn(new ArrayList<>()); - List result = workbasketAccessItemQueryImpl.accessIdIn("test", "asd") - .list(1, 1); - assertNotNull(result); - } + List result = + workbasketAccessItemQueryImpl.accessIdIn("test", "asd").list(1, 1); + assertNotNull(result); + } - @Test - void should_ReturnOneItem_when_BuilderIsUsed() { - when(internalTaskanaEngine.getSqlSession()).thenReturn(sqlSession); - when(sqlSession.selectOne(any(), any())).thenReturn(new WorkbasketAccessItemImpl()); + @Test + void should_ReturnOneItem_when_BuilderIsUsed() { + when(internalTaskanaEngine.getSqlSession()).thenReturn(sqlSession); + when(sqlSession.selectOne(any(), any())).thenReturn(new WorkbasketAccessItemImpl()); - WorkbasketAccessItem result = workbasketAccessItemQueryImpl.accessIdIn("test", "asd") - .single(); - assertNotNull(result); - } + WorkbasketAccessItem result = workbasketAccessItemQueryImpl.accessIdIn("test", "asd").single(); + assertNotNull(result); + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/WorkbasketQueryImplTest.java b/lib/taskana-core/src/test/java/pro/taskana/impl/WorkbasketQueryImplTest.java index 476da44ff..8b29e80c1 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/WorkbasketQueryImplTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/WorkbasketQueryImplTest.java @@ -6,7 +6,6 @@ import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; - import org.apache.ibatis.session.SqlSession; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -26,56 +25,55 @@ import pro.taskana.WorkbasketSummary; @ExtendWith(MockitoExtension.class) class WorkbasketQueryImplTest { - @InjectMocks - private WorkbasketQueryImpl workbasketQueryImpl; + @InjectMocks private WorkbasketQueryImpl workbasketQueryImpl; - @Mock - private InternalTaskanaEngine internalTaskanaEngine; + @Mock private InternalTaskanaEngine internalTaskanaEngine; - @Mock - private TaskanaEngine taskanaEngine; + @Mock private TaskanaEngine taskanaEngine; - @Mock - private SqlSession sqlSession; + @Mock private SqlSession sqlSession; - @BeforeEach - void setup() { - when(internalTaskanaEngine.getEngine()).thenReturn(taskanaEngine); - } + @BeforeEach + void setup() { + when(internalTaskanaEngine.getEngine()).thenReturn(taskanaEngine); + } - @Test - void should_ReturnList_when_BuilderIsUsed() { - when(internalTaskanaEngine.getSqlSession()).thenReturn(sqlSession); - when(sqlSession.selectList(any(), any())).thenReturn(new ArrayList<>()); + @Test + void should_ReturnList_when_BuilderIsUsed() { + when(internalTaskanaEngine.getSqlSession()).thenReturn(sqlSession); + when(sqlSession.selectList(any(), any())).thenReturn(new ArrayList<>()); - List result = workbasketQueryImpl + List result = + workbasketQueryImpl .nameIn("Gruppenpostkorb KSC 1", "Gruppenpostkorb KSC 2") .keyLike("GPK_%") .list(); - assertNotNull(result); - } + assertNotNull(result); + } - @Test - void should_ReturnListWithOffset_when_BuilderIsUsed() { - when(internalTaskanaEngine.getSqlSession()).thenReturn(sqlSession); - when(sqlSession.selectList(any(), any(), any())).thenReturn(new ArrayList<>()); + @Test + void should_ReturnListWithOffset_when_BuilderIsUsed() { + when(internalTaskanaEngine.getSqlSession()).thenReturn(sqlSession); + when(sqlSession.selectList(any(), any(), any())).thenReturn(new ArrayList<>()); - List result = workbasketQueryImpl + List result = + workbasketQueryImpl .nameIn("Gruppenpostkorb KSC 1", "Gruppenpostkorb KSC 2") .keyLike("GPK_%") .list(1, 1); - assertNotNull(result); - } + assertNotNull(result); + } - @Test - void should_ReturnOneItem_when_BuilderIsUsed() { - when(internalTaskanaEngine.getSqlSession()).thenReturn(sqlSession); - when(sqlSession.selectOne(any(), any())).thenReturn(new WorkbasketSummaryImpl()); + @Test + void should_ReturnOneItem_when_BuilderIsUsed() { + when(internalTaskanaEngine.getSqlSession()).thenReturn(sqlSession); + when(sqlSession.selectOne(any(), any())).thenReturn(new WorkbasketSummaryImpl()); - WorkbasketSummary result = workbasketQueryImpl + WorkbasketSummary result = + workbasketQueryImpl .nameIn("Gruppenpostkorb KSC 1", "Gruppenpostkorb KSC 2") .keyLike("GPK_%") .single(); - assertNotNull(result); - } + assertNotNull(result); + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/WorkbasketReportBuilderImplTest.java b/lib/taskana-core/src/test/java/pro/taskana/impl/WorkbasketReportBuilderImplTest.java index 5cbd699e8..347fa4ac4 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/WorkbasketReportBuilderImplTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/WorkbasketReportBuilderImplTest.java @@ -15,7 +15,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -37,60 +36,64 @@ import pro.taskana.impl.report.item.MonitorQueryItem; import pro.taskana.mappings.TaskMonitorMapper; import pro.taskana.report.WorkbasketReport; -/** - * Unit Test for WorkbasketReportBuilderImpl. - */ +/** Unit Test for WorkbasketReportBuilderImpl. */ @ExtendWith(MockitoExtension.class) class WorkbasketReportBuilderImplTest { - @InjectMocks - private TaskMonitorServiceImpl cut; + @InjectMocks private TaskMonitorServiceImpl cut; - @Mock - private InternalTaskanaEngine internalTaskanaEngineMock; + @Mock private InternalTaskanaEngine internalTaskanaEngineMock; - @Mock - private TaskanaEngine taskanaEngineMock; + @Mock private TaskanaEngine taskanaEngineMock; - @Mock - private TaskanaEngineConfiguration taskanaEngineConfiguration; + @Mock private TaskanaEngineConfiguration taskanaEngineConfiguration; - @Mock - private TaskMonitorMapper taskMonitorMapperMock; + @Mock private TaskMonitorMapper taskMonitorMapperMock; - @BeforeEach - void setup() { - when(internalTaskanaEngineMock.getEngine()).thenReturn(taskanaEngineMock); - when(taskanaEngineMock.getConfiguration()).thenReturn(taskanaEngineConfiguration); - when(taskanaEngineConfiguration.isGermanPublicHolidaysEnabled()).thenReturn(true); - when(taskanaEngineConfiguration.getCustomHolidays()).thenReturn(null); - } + @BeforeEach + void setup() { + when(internalTaskanaEngineMock.getEngine()).thenReturn(taskanaEngineMock); + when(taskanaEngineMock.getConfiguration()).thenReturn(taskanaEngineConfiguration); + when(taskanaEngineConfiguration.isGermanPublicHolidaysEnabled()).thenReturn(true); + when(taskanaEngineConfiguration.getCustomHolidays()).thenReturn(null); + } - @Test - void testGetTotalNumbersOfWorkbasketReportBasedOnDueDate() - throws InvalidArgumentException, NotAuthorizedException { - List workbasketIds = Collections.singletonList("WBI:000000000000000000000000000000000001"); - List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); - List categories = Collections.singletonList("EXTERN"); - List domains = Collections.singletonList("DOMAIN_A"); - List classificationIds = Collections.singletonList("L10000"); - List excludedClassificationIds = Collections.singletonList("L20000"); - Map customAttributeFilter = new HashMap<>(); - customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); - List combinedClassificationFilter = Collections.singletonList( - new CombinedClassificationFilter("CLI:000000000000000000000000000000000003", + @Test + void testGetTotalNumbersOfWorkbasketReportBasedOnDueDate() + throws InvalidArgumentException, NotAuthorizedException { + List workbasketIds = + Collections.singletonList("WBI:000000000000000000000000000000000001"); + List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); + List categories = Collections.singletonList("EXTERN"); + List domains = Collections.singletonList("DOMAIN_A"); + List classificationIds = Collections.singletonList("L10000"); + List excludedClassificationIds = Collections.singletonList("L20000"); + Map customAttributeFilter = new HashMap<>(); + customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); + List combinedClassificationFilter = + Collections.singletonList( + new CombinedClassificationFilter( + "CLI:000000000000000000000000000000000003", "CLI:000000000000000000000000000000000008")); - List expectedResult = new ArrayList<>(); - MonitorQueryItem monitorQueryItem = new MonitorQueryItem(); - monitorQueryItem.setKey("WBI:000000000000000000000000000000000001"); - monitorQueryItem.setNumberOfTasks(1); - expectedResult.add(monitorQueryItem); - when(taskMonitorMapperMock.getTaskCountOfWorkbaskets(workbasketIds, states, - categories, domains, classificationIds, excludedClassificationIds, customAttributeFilter, - combinedClassificationFilter)).thenReturn(expectedResult); + List expectedResult = new ArrayList<>(); + MonitorQueryItem monitorQueryItem = new MonitorQueryItem(); + monitorQueryItem.setKey("WBI:000000000000000000000000000000000001"); + monitorQueryItem.setNumberOfTasks(1); + expectedResult.add(monitorQueryItem); + when(taskMonitorMapperMock.getTaskCountOfWorkbaskets( + workbasketIds, + states, + categories, + domains, + classificationIds, + excludedClassificationIds, + customAttributeFilter, + combinedClassificationFilter)) + .thenReturn(expectedResult); - WorkbasketReport actualResult = cut.createWorkbasketReportBuilder() + WorkbasketReport actualResult = + cut.createWorkbasketReportBuilder() .workbasketIdIn(workbasketIds) .stateIn(states) .categoryIn(categories) @@ -101,53 +104,66 @@ class WorkbasketReportBuilderImplTest { .combinedClassificationFilterIn(combinedClassificationFilter) .buildReport(); - verify(internalTaskanaEngineMock, times(1)) - .openConnection(); - verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); - verify(taskanaEngineMock, times(2)).getConfiguration(); - verify(internalTaskanaEngineMock, times(3)).getEngine(); - verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); - verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); - verify(taskMonitorMapperMock, times(1)).getTaskCountOfWorkbaskets(any(), any(), any(), any(), - any(), any(), any(), any()); - verify(internalTaskanaEngineMock, times(1)).returnConnection(); - verifyNoMoreInteractions(internalTaskanaEngineMock, taskanaEngineMock, taskMonitorMapperMock, - taskanaEngineConfiguration); + verify(internalTaskanaEngineMock, times(1)).openConnection(); + verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); + verify(taskanaEngineMock, times(2)).getConfiguration(); + verify(internalTaskanaEngineMock, times(3)).getEngine(); + verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); + verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); + verify(taskMonitorMapperMock, times(1)) + .getTaskCountOfWorkbaskets(any(), any(), any(), any(), any(), any(), any(), any()); + verify(internalTaskanaEngineMock, times(1)).returnConnection(); + verifyNoMoreInteractions( + internalTaskanaEngineMock, + taskanaEngineMock, + taskMonitorMapperMock, + taskanaEngineConfiguration); - assertNotNull(actualResult); - assertEquals( - actualResult.getRow("WBI:000000000000000000000000000000000001").getTotalValue(), 1); - assertEquals(actualResult.getSumRow().getTotalValue(), 1); - } + assertNotNull(actualResult); + assertEquals( + actualResult.getRow("WBI:000000000000000000000000000000000001").getTotalValue(), 1); + assertEquals(actualResult.getSumRow().getTotalValue(), 1); + } - @Test - void testGetWorkbasketReportWithReportLineItemDefinitions() - throws InvalidArgumentException, NotAuthorizedException { - List workbasketIds = Collections.singletonList("WBI:000000000000000000000000000000000001"); - List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); - List categories = Collections.singletonList("EXTERN"); - List domains = Collections.singletonList("DOMAIN_A"); - List classificationIds = Collections.singletonList("L10000"); - List excludedClassificationIds = Collections.singletonList("L20000"); - Map customAttributeFilter = new HashMap<>(); - customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); - List combinedClassificationFilter = Collections.singletonList( - new CombinedClassificationFilter("CLI:000000000000000000000000000000000003", + @Test + void testGetWorkbasketReportWithReportLineItemDefinitions() + throws InvalidArgumentException, NotAuthorizedException { + List workbasketIds = + Collections.singletonList("WBI:000000000000000000000000000000000001"); + List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); + List categories = Collections.singletonList("EXTERN"); + List domains = Collections.singletonList("DOMAIN_A"); + List classificationIds = Collections.singletonList("L10000"); + List excludedClassificationIds = Collections.singletonList("L20000"); + Map customAttributeFilter = new HashMap<>(); + customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); + List combinedClassificationFilter = + Collections.singletonList( + new CombinedClassificationFilter( + "CLI:000000000000000000000000000000000003", "CLI:000000000000000000000000000000000008")); - List columnHeaders = Collections.singletonList( - new TimeIntervalColumnHeader(0, 0)); + List columnHeaders = + Collections.singletonList(new TimeIntervalColumnHeader(0, 0)); - List expectedResult = new ArrayList<>(); - MonitorQueryItem monitorQueryItem = new MonitorQueryItem(); - monitorQueryItem.setKey("WBI:000000000000000000000000000000000001"); - monitorQueryItem.setAgeInDays(0); - monitorQueryItem.setNumberOfTasks(1); - expectedResult.add(monitorQueryItem); - when(taskMonitorMapperMock.getTaskCountOfWorkbaskets(workbasketIds, states, - categories, domains, classificationIds, excludedClassificationIds, customAttributeFilter, - combinedClassificationFilter)).thenReturn(expectedResult); + List expectedResult = new ArrayList<>(); + MonitorQueryItem monitorQueryItem = new MonitorQueryItem(); + monitorQueryItem.setKey("WBI:000000000000000000000000000000000001"); + monitorQueryItem.setAgeInDays(0); + monitorQueryItem.setNumberOfTasks(1); + expectedResult.add(monitorQueryItem); + when(taskMonitorMapperMock.getTaskCountOfWorkbaskets( + workbasketIds, + states, + categories, + domains, + classificationIds, + excludedClassificationIds, + customAttributeFilter, + combinedClassificationFilter)) + .thenReturn(expectedResult); - WorkbasketReport actualResult = cut.createWorkbasketReportBuilder() + WorkbasketReport actualResult = + cut.createWorkbasketReportBuilder() .workbasketIdIn(workbasketIds) .stateIn(states) .categoryIn(categories) @@ -159,51 +175,66 @@ class WorkbasketReportBuilderImplTest { .withColumnHeaders(columnHeaders) .buildReport(); - verify(internalTaskanaEngineMock, times(1)).openConnection(); - verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); - verify(taskanaEngineMock, times(2)).getConfiguration(); - verify(internalTaskanaEngineMock, times(3)).getEngine(); - verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); - verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); - verify(taskMonitorMapperMock, times(1)).getTaskCountOfWorkbaskets(any(), any(), any(), any(), any(), any(), - any(), any()); - verify(internalTaskanaEngineMock, times(1)).returnConnection(); - verifyNoMoreInteractions(internalTaskanaEngineMock, taskanaEngineMock, taskMonitorMapperMock, - taskanaEngineConfiguration); + verify(internalTaskanaEngineMock, times(1)).openConnection(); + verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); + verify(taskanaEngineMock, times(2)).getConfiguration(); + verify(internalTaskanaEngineMock, times(3)).getEngine(); + verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); + verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); + verify(taskMonitorMapperMock, times(1)) + .getTaskCountOfWorkbaskets(any(), any(), any(), any(), any(), any(), any(), any()); + verify(internalTaskanaEngineMock, times(1)).returnConnection(); + verifyNoMoreInteractions( + internalTaskanaEngineMock, + taskanaEngineMock, + taskMonitorMapperMock, + taskanaEngineConfiguration); - assertNotNull(actualResult); - assertEquals( - actualResult.getRow("WBI:000000000000000000000000000000000001").getTotalValue(), 1); - assertEquals(actualResult.getRow("WBI:000000000000000000000000000000000001").getCells()[0], 1); - assertEquals(actualResult.getSumRow().getTotalValue(), 1); - } + assertNotNull(actualResult); + assertEquals( + actualResult.getRow("WBI:000000000000000000000000000000000001").getTotalValue(), 1); + assertEquals(actualResult.getRow("WBI:000000000000000000000000000000000001").getCells()[0], 1); + assertEquals(actualResult.getSumRow().getTotalValue(), 1); + } - @Test - void testGetTaskIdsOfCategoryReportForSelectedItems() - throws InvalidArgumentException, NotAuthorizedException { - List workbasketIds = Collections.singletonList("WBI:000000000000000000000000000000000001"); - List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); - List categories = Collections.singletonList("EXTERN"); - List domains = Collections.singletonList("DOMAIN_A"); - List classificationIds = Collections.singletonList("L10000"); - List excludedClassificationIds = Collections.singletonList("L20000"); - Map customAttributeFilter = new HashMap<>(); - customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); - List columnHeaders = Collections.singletonList( - new TimeIntervalColumnHeader(0, 0)); + @Test + void testGetTaskIdsOfCategoryReportForSelectedItems() + throws InvalidArgumentException, NotAuthorizedException { + List workbasketIds = + Collections.singletonList("WBI:000000000000000000000000000000000001"); + List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); + List categories = Collections.singletonList("EXTERN"); + List domains = Collections.singletonList("DOMAIN_A"); + List classificationIds = Collections.singletonList("L10000"); + List excludedClassificationIds = Collections.singletonList("L20000"); + Map customAttributeFilter = new HashMap<>(); + customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); + List columnHeaders = + Collections.singletonList(new TimeIntervalColumnHeader(0, 0)); - SelectedItem selectedItem = new SelectedItem(); - selectedItem.setKey("EXTERN"); - selectedItem.setLowerAgeLimit(1); - selectedItem.setUpperAgeLimit(5); - List selectedItems = Collections.singletonList(selectedItem); + SelectedItem selectedItem = new SelectedItem(); + selectedItem.setKey("EXTERN"); + selectedItem.setLowerAgeLimit(1); + selectedItem.setUpperAgeLimit(5); + List selectedItems = Collections.singletonList(selectedItem); - List expectedResult = Collections.singletonList("TKI:000000000000000000000000000000000001"); - when(taskMonitorMapperMock.getTaskIdsForSelectedItems(workbasketIds, - states, categories, domains, classificationIds, excludedClassificationIds, customAttributeFilter, - "WORKBASKET_KEY", selectedItems, false)).thenReturn(expectedResult); + List expectedResult = + Collections.singletonList("TKI:000000000000000000000000000000000001"); + when(taskMonitorMapperMock.getTaskIdsForSelectedItems( + workbasketIds, + states, + categories, + domains, + classificationIds, + excludedClassificationIds, + customAttributeFilter, + "WORKBASKET_KEY", + selectedItems, + false)) + .thenReturn(expectedResult); - List actualResult = cut.createWorkbasketReportBuilder() + List actualResult = + cut.createWorkbasketReportBuilder() .workbasketIdIn(workbasketIds) .stateIn(states) .categoryIn(categories) @@ -214,59 +245,74 @@ class WorkbasketReportBuilderImplTest { .withColumnHeaders(columnHeaders) .listTaskIdsForSelectedItems(selectedItems); - verify(internalTaskanaEngineMock, times(1)).openConnection(); - verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); - verify(taskanaEngineMock, times(2)).getConfiguration(); - verify(internalTaskanaEngineMock, times(3)).getEngine(); - verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); - verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); - verify(taskMonitorMapperMock, times(1)) - .getTaskIdsForSelectedItems(any(), any(), any(), any(), any(), any(), any(), any(), any(), eq(false)); - verify(internalTaskanaEngineMock, times(1)).returnConnection(); - verifyNoMoreInteractions(internalTaskanaEngineMock, taskanaEngineMock, taskMonitorMapperMock, - taskanaEngineConfiguration); + verify(internalTaskanaEngineMock, times(1)).openConnection(); + verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); + verify(taskanaEngineMock, times(2)).getConfiguration(); + verify(internalTaskanaEngineMock, times(3)).getEngine(); + verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); + verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); + verify(taskMonitorMapperMock, times(1)) + .getTaskIdsForSelectedItems( + any(), any(), any(), any(), any(), any(), any(), any(), any(), eq(false)); + verify(internalTaskanaEngineMock, times(1)).returnConnection(); + verifyNoMoreInteractions( + internalTaskanaEngineMock, + taskanaEngineMock, + taskMonitorMapperMock, + taskanaEngineConfiguration); - assertNotNull(actualResult); - assertEquals(expectedResult, actualResult); - } + assertNotNull(actualResult); + assertEquals(expectedResult, actualResult); + } - @Test - void testListTaskIdsForSelectedItemsIsEmptyResult() { - List selectedItems = new ArrayList<>(); - Assertions.assertThrows(InvalidArgumentException.class, () -> { - List result = cut.createWorkbasketReportBuilder() - .workbasketIdIn(Arrays.asList("DieGibtsGarantiertNed")) - .listTaskIdsForSelectedItems(selectedItems); - assertNotNull(result); + @Test + void testListTaskIdsForSelectedItemsIsEmptyResult() { + List selectedItems = new ArrayList<>(); + Assertions.assertThrows( + InvalidArgumentException.class, + () -> { + List result = + cut.createWorkbasketReportBuilder() + .workbasketIdIn(Arrays.asList("DieGibtsGarantiertNed")) + .listTaskIdsForSelectedItems(selectedItems); + assertNotNull(result); }); - } + } - @Test - void testListCustomAttributeValuesForCustomAttributeName() - throws NotAuthorizedException { - List workbasketIds = Collections.singletonList("WBI:000000000000000000000000000000000001"); - List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); - List categories = Collections.singletonList("EXTERN"); - List domains = Collections.singletonList("DOMAIN_A"); - List classificationIds = Collections.singletonList("L10000"); - List excludedClassificationIds = Collections.singletonList("L20000"); - Map customAttributeFilter = new HashMap<>(); - customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); - List columnHeaders = Collections.singletonList( - new TimeIntervalColumnHeader(0, 0)); + @Test + void testListCustomAttributeValuesForCustomAttributeName() throws NotAuthorizedException { + List workbasketIds = + Collections.singletonList("WBI:000000000000000000000000000000000001"); + List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); + List categories = Collections.singletonList("EXTERN"); + List domains = Collections.singletonList("DOMAIN_A"); + List classificationIds = Collections.singletonList("L10000"); + List excludedClassificationIds = Collections.singletonList("L20000"); + Map customAttributeFilter = new HashMap<>(); + customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); + List columnHeaders = + Collections.singletonList(new TimeIntervalColumnHeader(0, 0)); - SelectedItem selectedItem = new SelectedItem(); - selectedItem.setKey("EXTERN"); - selectedItem.setLowerAgeLimit(1); - selectedItem.setUpperAgeLimit(5); - List selectedItems = Collections.singletonList(selectedItem); + SelectedItem selectedItem = new SelectedItem(); + selectedItem.setKey("EXTERN"); + selectedItem.setLowerAgeLimit(1); + selectedItem.setUpperAgeLimit(5); + List selectedItems = Collections.singletonList(selectedItem); - List expectedResult = Collections.singletonList("Geschaeftsstelle A"); - when(taskMonitorMapperMock.getCustomAttributeValuesForReport(workbasketIds, - states, categories, domains, classificationIds, excludedClassificationIds, customAttributeFilter, - CustomField.CUSTOM_1)).thenReturn(expectedResult); + List expectedResult = Collections.singletonList("Geschaeftsstelle A"); + when(taskMonitorMapperMock.getCustomAttributeValuesForReport( + workbasketIds, + states, + categories, + domains, + classificationIds, + excludedClassificationIds, + customAttributeFilter, + CustomField.CUSTOM_1)) + .thenReturn(expectedResult); - List actualResult = cut.createWorkbasketReportBuilder() + List actualResult = + cut.createWorkbasketReportBuilder() .workbasketIdIn(workbasketIds) .stateIn(states) .categoryIn(categories) @@ -277,56 +323,71 @@ class WorkbasketReportBuilderImplTest { .withColumnHeaders(columnHeaders) .listCustomAttributeValuesForCustomAttributeName(CustomField.CUSTOM_1); - verify(internalTaskanaEngineMock, times(1)).openConnection(); - verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); - verify(taskanaEngineMock, times(2)).getConfiguration(); - verify(internalTaskanaEngineMock, times(3)).getEngine(); - verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); - verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); - verify(taskMonitorMapperMock, times(1)) - .getCustomAttributeValuesForReport(any(), any(), any(), any(), any(), any(), any(), any()); - verify(internalTaskanaEngineMock, times(1)).returnConnection(); - verifyNoMoreInteractions(internalTaskanaEngineMock, taskanaEngineMock, taskMonitorMapperMock, - taskanaEngineConfiguration); + verify(internalTaskanaEngineMock, times(1)).openConnection(); + verify(taskanaEngineMock, times(1)).checkRoleMembership(any()); + verify(taskanaEngineMock, times(2)).getConfiguration(); + verify(internalTaskanaEngineMock, times(3)).getEngine(); + verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); + verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); + verify(taskMonitorMapperMock, times(1)) + .getCustomAttributeValuesForReport(any(), any(), any(), any(), any(), any(), any(), any()); + verify(internalTaskanaEngineMock, times(1)).returnConnection(); + verifyNoMoreInteractions( + internalTaskanaEngineMock, + taskanaEngineMock, + taskMonitorMapperMock, + taskanaEngineConfiguration); - assertNotNull(actualResult); - assertEquals(expectedResult, actualResult); - } + assertNotNull(actualResult); + assertEquals(expectedResult, actualResult); + } - @Test - void testListCustomAttributeValuesForCustomAttributeNameIsEmptyResult() - throws NotAuthorizedException { - List result = cut.createWorkbasketReportBuilder() + @Test + void testListCustomAttributeValuesForCustomAttributeNameIsEmptyResult() + throws NotAuthorizedException { + List result = + cut.createWorkbasketReportBuilder() .workbasketIdIn(Arrays.asList("GibtsSicherNed")) .listCustomAttributeValuesForCustomAttributeName(CustomField.CUSTOM_14); - assertNotNull(result); - } + assertNotNull(result); + } - @Test - void testGetTotalNumbersOfWorkbasketReportBasedOnCreatedDate() - throws InvalidArgumentException, NotAuthorizedException { - List workbasketIds = Collections.singletonList("WBI:000000000000000000000000000000000001"); - List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); - List categories = Collections.singletonList("EXTERN"); - List domains = Collections.singletonList("DOMAIN_A"); - List classificationIds = Collections.singletonList("L10000"); - List excludedClassificationIds = Collections.singletonList("L20000"); - Map customAttributeFilter = new HashMap<>(); - customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); - List combinedClassificationFilter = Arrays - .asList(new CombinedClassificationFilter("CLI:000000000000000000000000000000000003", + @Test + void testGetTotalNumbersOfWorkbasketReportBasedOnCreatedDate() + throws InvalidArgumentException, NotAuthorizedException { + List workbasketIds = + Collections.singletonList("WBI:000000000000000000000000000000000001"); + List states = Arrays.asList(TaskState.CLAIMED, TaskState.READY); + List categories = Collections.singletonList("EXTERN"); + List domains = Collections.singletonList("DOMAIN_A"); + List classificationIds = Collections.singletonList("L10000"); + List excludedClassificationIds = Collections.singletonList("L20000"); + Map customAttributeFilter = new HashMap<>(); + customAttributeFilter.put(CustomField.CUSTOM_1, "Geschaeftsstelle A"); + List combinedClassificationFilter = + Arrays.asList( + new CombinedClassificationFilter( + "CLI:000000000000000000000000000000000003", "CLI:000000000000000000000000000000000008")); - List expectedResult = new ArrayList<>(); - MonitorQueryItem monitorQueryItem = new MonitorQueryItem(); - monitorQueryItem.setKey("WBI:000000000000000000000000000000000001"); - monitorQueryItem.setNumberOfTasks(1); - expectedResult.add(monitorQueryItem); - when(taskMonitorMapperMock.getTaskCountOfWorkbasketsBasedOnPlannedDate(workbasketIds, states, - categories, domains, classificationIds, excludedClassificationIds, customAttributeFilter, - combinedClassificationFilter)).thenReturn(expectedResult); + List expectedResult = new ArrayList<>(); + MonitorQueryItem monitorQueryItem = new MonitorQueryItem(); + monitorQueryItem.setKey("WBI:000000000000000000000000000000000001"); + monitorQueryItem.setNumberOfTasks(1); + expectedResult.add(monitorQueryItem); + when(taskMonitorMapperMock.getTaskCountOfWorkbasketsBasedOnPlannedDate( + workbasketIds, + states, + categories, + domains, + classificationIds, + excludedClassificationIds, + customAttributeFilter, + combinedClassificationFilter)) + .thenReturn(expectedResult); - WorkbasketReport actualResult = cut.createWorkbasketReportBuilder() + WorkbasketReport actualResult = + cut.createWorkbasketReportBuilder() .workbasketIdIn(workbasketIds) .stateIn(states) .categoryIn(categories) @@ -337,14 +398,14 @@ class WorkbasketReportBuilderImplTest { .combinedClassificationFilterIn(combinedClassificationFilter) .buildPlannedDateBasedReport(); - verify(internalTaskanaEngineMock, times(1)) - .openConnection(); - verify(taskanaEngineMock, times(1)).checkRoleMembership(TaskanaRole.MONITOR, TaskanaRole.ADMIN); - verify(taskanaEngineMock, times(2)).getConfiguration(); - verify(internalTaskanaEngineMock, times(3)).getEngine(); - verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); - verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); - verify(taskMonitorMapperMock, times(1)).getTaskCountOfWorkbasketsBasedOnPlannedDate( + verify(internalTaskanaEngineMock, times(1)).openConnection(); + verify(taskanaEngineMock, times(1)).checkRoleMembership(TaskanaRole.MONITOR, TaskanaRole.ADMIN); + verify(taskanaEngineMock, times(2)).getConfiguration(); + verify(internalTaskanaEngineMock, times(3)).getEngine(); + verify(taskanaEngineConfiguration, times(1)).isGermanPublicHolidaysEnabled(); + verify(taskanaEngineConfiguration, times(1)).getCustomHolidays(); + verify(taskMonitorMapperMock, times(1)) + .getTaskCountOfWorkbasketsBasedOnPlannedDate( workbasketIds, states, categories, @@ -353,13 +414,16 @@ class WorkbasketReportBuilderImplTest { excludedClassificationIds, customAttributeFilter, combinedClassificationFilter); - verify(internalTaskanaEngineMock, times(1)).returnConnection(); - verifyNoMoreInteractions(internalTaskanaEngineMock, taskanaEngineMock, taskMonitorMapperMock, - taskanaEngineConfiguration); + verify(internalTaskanaEngineMock, times(1)).returnConnection(); + verifyNoMoreInteractions( + internalTaskanaEngineMock, + taskanaEngineMock, + taskMonitorMapperMock, + taskanaEngineConfiguration); - assertNotNull(actualResult); - assertEquals( - actualResult.getRow("WBI:000000000000000000000000000000000001").getTotalValue(), 1); - assertEquals(actualResult.getSumRow().getTotalValue(), 1); - } + assertNotNull(actualResult); + assertEquals( + actualResult.getRow("WBI:000000000000000000000000000000000001").getTotalValue(), 1); + assertEquals(actualResult.getSumRow().getTotalValue(), 1); + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/WorkbasketServiceImplTest.java b/lib/taskana-core/src/test/java/pro/taskana/impl/WorkbasketServiceImplTest.java index 148e25130..72f6d8e43 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/WorkbasketServiceImplTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/WorkbasketServiceImplTest.java @@ -16,7 +16,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; @@ -51,167 +50,180 @@ import pro.taskana.mappings.WorkbasketMapper; @ExtendWith(MockitoExtension.class) class WorkbasketServiceImplTest { - @Spy - @InjectMocks - private WorkbasketServiceImpl workbasketServiceSpy; + @Spy @InjectMocks private WorkbasketServiceImpl workbasketServiceSpy; - @Mock - private WorkbasketMapper workbasketMapperMock; + @Mock private WorkbasketMapper workbasketMapperMock; - @Mock - private DistributionTargetMapper distributionTargetMapperMock; + @Mock private DistributionTargetMapper distributionTargetMapperMock; - @Mock - private WorkbasketAccessMapper workbasketAccessMapperMock; + @Mock private WorkbasketAccessMapper workbasketAccessMapperMock; - @Mock - private TaskService taskServiceMock; + @Mock private TaskService taskServiceMock; - @Mock - private TaskQuery taskQueryMock; + @Mock private TaskQuery taskQueryMock; - @Mock - private TaskanaEngine taskanaEngine; + @Mock private TaskanaEngine taskanaEngine; - @Mock - private InternalTaskanaEngine internalTaskanaEngineMock; + @Mock private InternalTaskanaEngine internalTaskanaEngineMock; - @Mock - private TaskanaEngineConfiguration taskanaEngineConfigurationMock; + @Mock private TaskanaEngineConfiguration taskanaEngineConfigurationMock; - @BeforeEach - void setup() { - when(internalTaskanaEngineMock.getEngine()).thenReturn(taskanaEngine); - } + @BeforeEach + void setup() { + when(internalTaskanaEngineMock.getEngine()).thenReturn(taskanaEngine); + } - @Test - void testCreateWorkbasket_WithDistibutionTargets() - throws WorkbasketNotFoundException, NotAuthorizedException, InvalidWorkbasketException, - WorkbasketAlreadyExistException, DomainNotFoundException { - final int distTargetAmount = 2; - WorkbasketImpl expectedWb = createTestWorkbasket(null, "Key-1"); - doReturn(expectedWb).when(workbasketServiceSpy).getWorkbasket(any()); - when(internalTaskanaEngineMock.domainExists(any())).thenReturn(true); + @Test + void testCreateWorkbasket_WithDistibutionTargets() + throws WorkbasketNotFoundException, NotAuthorizedException, InvalidWorkbasketException, + WorkbasketAlreadyExistException, DomainNotFoundException { + final int distTargetAmount = 2; + WorkbasketImpl expectedWb = createTestWorkbasket(null, "Key-1"); + doReturn(expectedWb).when(workbasketServiceSpy).getWorkbasket(any()); + when(internalTaskanaEngineMock.domainExists(any())).thenReturn(true); - Workbasket actualWb = workbasketServiceSpy.createWorkbasket(expectedWb); - workbasketServiceSpy.setDistributionTargets(expectedWb.getId(), - createTestDistributionTargets(distTargetAmount)); + Workbasket actualWb = workbasketServiceSpy.createWorkbasket(expectedWb); + workbasketServiceSpy.setDistributionTargets( + expectedWb.getId(), createTestDistributionTargets(distTargetAmount)); - verify(internalTaskanaEngineMock, times(4)).openConnection(); - verify(workbasketMapperMock, times(3)).insert(any()); - verify(workbasketServiceSpy, times(distTargetAmount + 1)).getWorkbasket(any()); - verify(distributionTargetMapperMock, times(1)).deleteAllDistributionTargetsBySourceId(any()); - verify(distributionTargetMapperMock, times(distTargetAmount)).insert(any(), any()); - verify(workbasketMapperMock, times(3)).findByKeyAndDomain(any(), any()); - verify(workbasketMapperMock, times(1)).update(any()); - verify(internalTaskanaEngineMock, times(4)).returnConnection(); - verify(taskanaEngine, times(4)).checkRoleMembership(any()); - verify(internalTaskanaEngineMock, times(4)).getEngine(); - verify(internalTaskanaEngineMock, times(3)).domainExists(any()); - verifyNoMoreInteractions(taskQueryMock, taskServiceMock, workbasketMapperMock, workbasketAccessMapperMock, - distributionTargetMapperMock, - internalTaskanaEngineMock, taskanaEngine, taskanaEngineConfigurationMock); - assertThat(actualWb.getId(), not(equalTo(null))); - assertThat(actualWb.getId(), startsWith("WBI")); - assertThat(actualWb.getCreated(), not(equalTo(null))); - assertThat(actualWb.getModified(), not(equalTo(null))); - } + verify(internalTaskanaEngineMock, times(4)).openConnection(); + verify(workbasketMapperMock, times(3)).insert(any()); + verify(workbasketServiceSpy, times(distTargetAmount + 1)).getWorkbasket(any()); + verify(distributionTargetMapperMock, times(1)).deleteAllDistributionTargetsBySourceId(any()); + verify(distributionTargetMapperMock, times(distTargetAmount)).insert(any(), any()); + verify(workbasketMapperMock, times(3)).findByKeyAndDomain(any(), any()); + verify(workbasketMapperMock, times(1)).update(any()); + verify(internalTaskanaEngineMock, times(4)).returnConnection(); + verify(taskanaEngine, times(4)).checkRoleMembership(any()); + verify(internalTaskanaEngineMock, times(4)).getEngine(); + verify(internalTaskanaEngineMock, times(3)).domainExists(any()); + verifyNoMoreInteractions( + taskQueryMock, + taskServiceMock, + workbasketMapperMock, + workbasketAccessMapperMock, + distributionTargetMapperMock, + internalTaskanaEngineMock, + taskanaEngine, + taskanaEngineConfigurationMock); + assertThat(actualWb.getId(), not(equalTo(null))); + assertThat(actualWb.getId(), startsWith("WBI")); + assertThat(actualWb.getCreated(), not(equalTo(null))); + assertThat(actualWb.getModified(), not(equalTo(null))); + } - @Test - void testCreateWorkbasket_DistibutionTargetNotExisting() throws Exception { - WorkbasketImpl expectedWb = createTestWorkbasket("ID-1", "Key-1"); - when(internalTaskanaEngineMock.domainExists(any())).thenReturn(true); - String otherWorkbasketId = "4711"; - List destinations = Collections.singletonList(otherWorkbasketId); - workbasketServiceSpy.createWorkbasket(expectedWb); - doReturn(expectedWb).when(workbasketServiceSpy).getWorkbasket(eq(expectedWb.getId())); + @Test + void testCreateWorkbasket_DistibutionTargetNotExisting() throws Exception { + WorkbasketImpl expectedWb = createTestWorkbasket("ID-1", "Key-1"); + when(internalTaskanaEngineMock.domainExists(any())).thenReturn(true); + String otherWorkbasketId = "4711"; + List destinations = Collections.singletonList(otherWorkbasketId); + workbasketServiceSpy.createWorkbasket(expectedWb); + doReturn(expectedWb).when(workbasketServiceSpy).getWorkbasket(eq(expectedWb.getId())); - WorkbasketNotFoundException e = Assertions.assertThrows( + WorkbasketNotFoundException e = + Assertions.assertThrows( WorkbasketNotFoundException.class, () -> workbasketServiceSpy.setDistributionTargets(expectedWb.getId(), destinations)); - Assertions.assertEquals(e.getId(), otherWorkbasketId); - Assertions.assertNull(e.getKey()); - Assertions.assertNull(e.getDomain()); + Assertions.assertEquals(e.getId(), otherWorkbasketId); + Assertions.assertNull(e.getKey()); + Assertions.assertNull(e.getDomain()); - verify(internalTaskanaEngineMock, times(3)).openConnection(); - verify(workbasketMapperMock, times(1)).insert(expectedWb); - verify(workbasketMapperMock, times(1)).findById(any()); - verify(workbasketMapperMock, times(1)).findByKeyAndDomain(any(), any()); - verify(workbasketServiceSpy, times(2)).getWorkbasket(any()); - verify(internalTaskanaEngineMock, times(3)).returnConnection(); - verify(taskanaEngine, times(2)).checkRoleMembership(any()); - verify(internalTaskanaEngineMock, times(2)).getEngine(); - verify(internalTaskanaEngineMock, times(1)).domainExists(any()); - verify(distributionTargetMapperMock).deleteAllDistributionTargetsBySourceId(eq(expectedWb.getId())); - verify(workbasketMapperMock).update(eq(expectedWb)); - verifyNoMoreInteractions(taskQueryMock, taskServiceMock, workbasketMapperMock, workbasketAccessMapperMock, - distributionTargetMapperMock, internalTaskanaEngineMock, taskanaEngine, taskanaEngineConfigurationMock); + verify(internalTaskanaEngineMock, times(3)).openConnection(); + verify(workbasketMapperMock, times(1)).insert(expectedWb); + verify(workbasketMapperMock, times(1)).findById(any()); + verify(workbasketMapperMock, times(1)).findByKeyAndDomain(any(), any()); + verify(workbasketServiceSpy, times(2)).getWorkbasket(any()); + verify(internalTaskanaEngineMock, times(3)).returnConnection(); + verify(taskanaEngine, times(2)).checkRoleMembership(any()); + verify(internalTaskanaEngineMock, times(2)).getEngine(); + verify(internalTaskanaEngineMock, times(1)).domainExists(any()); + verify(distributionTargetMapperMock) + .deleteAllDistributionTargetsBySourceId(eq(expectedWb.getId())); + verify(workbasketMapperMock).update(eq(expectedWb)); + verifyNoMoreInteractions( + taskQueryMock, + taskServiceMock, + workbasketMapperMock, + workbasketAccessMapperMock, + distributionTargetMapperMock, + internalTaskanaEngineMock, + taskanaEngine, + taskanaEngineConfigurationMock); + } - } + // TODO Add stored-check. Not getWorkbasket() because permissions are not set with this action + // here. + @Disabled + @Test + void testCreateWorkbasket_NotCreated() { + WorkbasketImpl expectedWb = createTestWorkbasket(null, "Key-1"); + when(workbasketMapperMock.findById(any())).thenThrow(WorkbasketNotFoundException.class); - // TODO Add stored-check. Not getWorkbasket() because permissions are not set with this action here. - @Disabled - @Test - void testCreateWorkbasket_NotCreated() { - WorkbasketImpl expectedWb = createTestWorkbasket(null, "Key-1"); - when(workbasketMapperMock.findById(any())).thenThrow(WorkbasketNotFoundException.class); + Assertions.assertThrows( + WorkbasketNotFoundException.class, () -> workbasketServiceSpy.createWorkbasket(expectedWb)); + verify(internalTaskanaEngineMock, times(1)).openConnection(); + verify(workbasketMapperMock, times(1)).insert(expectedWb); + verify(workbasketMapperMock, times(1)).findById(expectedWb.getId()); + verify(internalTaskanaEngineMock, times(1)).returnConnection(); + verifyNoMoreInteractions( + taskQueryMock, + taskServiceMock, + workbasketMapperMock, + workbasketAccessMapperMock, + distributionTargetMapperMock, + internalTaskanaEngineMock, + taskanaEngineConfigurationMock); + } + + @Test + void testDeleteWorkbasketIsUsed() throws NotAuthorizedException, WorkbasketNotFoundException { + Workbasket wb = createTestWorkbasket("WBI:0", "wb-key"); + List usages = Arrays.asList(new TaskSummaryImpl(), new TaskSummaryImpl()); + + WorkbasketNotFoundException e = Assertions.assertThrows( - WorkbasketNotFoundException.class, () -> workbasketServiceSpy.createWorkbasket(expectedWb)); - - verify(internalTaskanaEngineMock, times(1)).openConnection(); - verify(workbasketMapperMock, times(1)).insert(expectedWb); - verify(workbasketMapperMock, times(1)).findById(expectedWb.getId()); - verify(internalTaskanaEngineMock, times(1)).returnConnection(); - verifyNoMoreInteractions(taskQueryMock, taskServiceMock, workbasketMapperMock, workbasketAccessMapperMock, - distributionTargetMapperMock, - internalTaskanaEngineMock, taskanaEngineConfigurationMock); - - } - - @Test - void testDeleteWorkbasketIsUsed() - throws NotAuthorizedException, WorkbasketNotFoundException { - Workbasket wb = createTestWorkbasket("WBI:0", "wb-key"); - List usages = Arrays.asList(new TaskSummaryImpl(), new TaskSummaryImpl()); - - WorkbasketNotFoundException e = Assertions.assertThrows( WorkbasketNotFoundException.class, () -> workbasketServiceSpy.deleteWorkbasket(wb.getId())); - verify(internalTaskanaEngineMock, times(2)).openConnection(); - verify(workbasketServiceSpy, times(1)).getWorkbasket(wb.getId()); - verify(taskanaEngine, times(0)).getTaskService(); - verify(taskServiceMock, times(0)).createTaskQuery(); - verify(taskQueryMock, times(0)).workbasketIdIn(wb.getId()); - verify(taskQueryMock, times(0)).count(); - verify(internalTaskanaEngineMock, times(2)).returnConnection(); - verifyNoMoreInteractions(taskQueryMock, taskServiceMock, workbasketAccessMapperMock, - distributionTargetMapperMock, taskanaEngineConfigurationMock); - } + verify(internalTaskanaEngineMock, times(2)).openConnection(); + verify(workbasketServiceSpy, times(1)).getWorkbasket(wb.getId()); + verify(taskanaEngine, times(0)).getTaskService(); + verify(taskServiceMock, times(0)).createTaskQuery(); + verify(taskQueryMock, times(0)).workbasketIdIn(wb.getId()); + verify(taskQueryMock, times(0)).count(); + verify(internalTaskanaEngineMock, times(2)).returnConnection(); + verifyNoMoreInteractions( + taskQueryMock, + taskServiceMock, + workbasketAccessMapperMock, + distributionTargetMapperMock, + taskanaEngineConfigurationMock); + } - private WorkbasketImpl createTestWorkbasket(String id, String key) { - WorkbasketImpl workbasket = new WorkbasketImpl(); - workbasket.setId(id); - workbasket.setKey(key); - workbasket.setName("Workbasket " + id); - workbasket.setDescription("Description WB with Key " + key); - workbasket.setType(WorkbasketType.PERSONAL); - workbasket.setDomain("DOMAIN_A"); - return workbasket; - } + private WorkbasketImpl createTestWorkbasket(String id, String key) { + WorkbasketImpl workbasket = new WorkbasketImpl(); + workbasket.setId(id); + workbasket.setKey(key); + workbasket.setName("Workbasket " + id); + workbasket.setDescription("Description WB with Key " + key); + workbasket.setType(WorkbasketType.PERSONAL); + workbasket.setDomain("DOMAIN_A"); + return workbasket; + } - private List createTestDistributionTargets(int amount) - throws InvalidWorkbasketException, NotAuthorizedException, - WorkbasketAlreadyExistException, DomainNotFoundException { - List distributionsTargets = new ArrayList<>(); - amount = Math.max(amount, 0); - for (int i = 0; i < amount; i++) { - WorkbasketImpl wb = createTestWorkbasket("WB-ID-" + i, "WB-KEY-" + i); - workbasketServiceSpy.createWorkbasket(wb); - distributionsTargets.add(wb.getId()); - } - return distributionsTargets; + private List createTestDistributionTargets(int amount) + throws InvalidWorkbasketException, NotAuthorizedException, WorkbasketAlreadyExistException, + DomainNotFoundException { + List distributionsTargets = new ArrayList<>(); + amount = Math.max(amount, 0); + for (int i = 0; i < amount; i++) { + WorkbasketImpl wb = createTestWorkbasket("WB-ID-" + i, "WB-KEY-" + i); + workbasketServiceSpy.createWorkbasket(wb); + distributionsTargets.add(wb.getId()); } + return distributionsTargets; + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/configuration/TaskanaEngineTestConfiguration.java b/lib/taskana-core/src/test/java/pro/taskana/impl/configuration/TaskanaEngineTestConfiguration.java index 9f72dc193..4def80699 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/configuration/TaskanaEngineTestConfiguration.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/configuration/TaskanaEngineTestConfiguration.java @@ -6,9 +6,7 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; - import javax.sql.DataSource; - import org.apache.ibatis.datasource.pooled.PooledDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -20,166 +18,177 @@ import org.slf4j.LoggerFactory; */ public final class TaskanaEngineTestConfiguration { - private static final Logger LOGGER = LoggerFactory.getLogger(TaskanaEngineTestConfiguration.class); - private static final int POOL_TIME_TO_WAIT = 50; - private static DataSource dataSource = null; - private static String schemaName = null; + private static final Logger LOGGER = + LoggerFactory.getLogger(TaskanaEngineTestConfiguration.class); + private static final int POOL_TIME_TO_WAIT = 50; + private static DataSource dataSource = null; + private static String schemaName = null; - private TaskanaEngineTestConfiguration() { + private TaskanaEngineTestConfiguration() {} + + /** + * returns the Datasource used for Junit test. If the file {user.home}/taskanaUnitTest.properties + * is present, the Datasource is created according to the properties jdbcDriver, jdbcUrl, + * dbUserName and dbPassword. Assuming, the database has the name tskdb, a sample properties file + * for DB2 looks as follows: jdbcDriver=com.ibm.db2.jcc.DB2Driver + * jdbcUrl=jdbc:db2://localhost:50000/tskdb dbUserName=db2user dbPassword=db2password If any of + * these properties is missing, or the file doesn't exist, the default Datasource for h2 in-memory + * db is created. + * + * @return dataSource for unit test + */ + public static DataSource getDataSource() { + if (dataSource == null) { + String userHomeDirectroy = System.getProperty("user.home"); + String propertiesFileName = userHomeDirectroy + "/taskanaUnitTest.properties"; + File f = new File(propertiesFileName); + if (f.exists() && !f.isDirectory()) { + dataSource = createDataSourceFromProperties(propertiesFileName); + } else { + dataSource = createDefaultDataSource(); + } + } + return dataSource; + } + + /** + * returns the SchemaName used for Junit test. If the file {user.home}/taskanaUnitTest.properties + * is present, the SchemaName is created according to the property schemaName. a sample properties + * file for DB2 looks as follows: jdbcDriver=com.ibm.db2.jcc.DB2Driver + * jdbcUrl=jdbc:db2://localhost:50000/tskdb dbUserName=db2user dbPassword=db2password + * schemaName=TASKANA If any of these properties is missing, or the file doesn't exist, the + * default schemaName TASKANA is created used. + * + * @return String for unit test + */ + public static String getSchemaName() { + if (schemaName == null) { + String userHomeDirectroy = System.getProperty("user.home"); + String propertiesFileName = userHomeDirectroy + "/taskanaUnitTest.properties"; + File f = new File(propertiesFileName); + if (f.exists() && !f.isDirectory()) { + schemaName = getSchemaNameFromPropertiesObject(propertiesFileName); + } else { + schemaName = "TASKANA"; + } + } + return schemaName; + } + + /** + * create data source from properties file. + * + * @param propertiesFileName the name of the property file + * @return the parsed datasource. + */ + public static DataSource createDataSourceFromProperties(String propertiesFileName) { + DataSource ds; + try (InputStream input = new FileInputStream(propertiesFileName)) { + Properties prop = new Properties(); + prop.load(input); + boolean propertiesFileIsComplete = true; + String warningMessage = ""; + String jdbcDriver = prop.getProperty("jdbcDriver"); + if (jdbcDriver == null || jdbcDriver.length() == 0) { + propertiesFileIsComplete = false; + warningMessage += ", jdbcDriver property missing"; + } + String jdbcUrl = prop.getProperty("jdbcUrl"); + if (jdbcUrl == null || jdbcUrl.length() == 0) { + propertiesFileIsComplete = false; + warningMessage += ", jdbcUrl property missing"; + } + String dbUserName = prop.getProperty("dbUserName"); + if (dbUserName == null || dbUserName.length() == 0) { + propertiesFileIsComplete = false; + warningMessage += ", dbUserName property missing"; + } + String dbPassword = prop.getProperty("dbPassword"); + if (dbPassword == null || dbPassword.length() == 0) { + propertiesFileIsComplete = false; + warningMessage += ", dbPassword property missing"; + } + + if (propertiesFileIsComplete) { + ds = + new PooledDataSource( + Thread.currentThread().getContextClassLoader(), + jdbcDriver, + jdbcUrl, + dbUserName, + dbPassword); + ((PooledDataSource) ds) + .forceCloseAll(); // otherwise the MyBatis pool is not initialized correctly + } else { + LOGGER.warn("propertiesFile " + propertiesFileName + " is incomplete" + warningMessage); + LOGGER.warn("Using default Datasource for Test"); + ds = createDefaultDataSource(); + } + + } catch (IOException e) { + LOGGER.warn("createDataSourceFromProperties caught Exception " + e); + LOGGER.warn("Using default Datasource for Test"); + ds = createDefaultDataSource(); } - /** - * returns the Datasource used for Junit test. If the file {user.home}/taskanaUnitTest.properties is present, the - * Datasource is created according to the properties jdbcDriver, jdbcUrl, dbUserName and dbPassword. Assuming, the - * database has the name tskdb, a sample properties file for DB2 looks as follows: - * jdbcDriver=com.ibm.db2.jcc.DB2Driver jdbcUrl=jdbc:db2://localhost:50000/tskdb dbUserName=db2user - * dbPassword=db2password If any of these properties is missing, or the file doesn't exist, the default Datasource - * for h2 in-memory db is created. - * - * @return dataSource for unit test - */ - public static DataSource getDataSource() { - if (dataSource == null) { - String userHomeDirectroy = System.getProperty("user.home"); - String propertiesFileName = userHomeDirectroy + "/taskanaUnitTest.properties"; - File f = new File(propertiesFileName); - if (f.exists() && !f.isDirectory()) { - dataSource = createDataSourceFromProperties(propertiesFileName); - } else { - dataSource = createDefaultDataSource(); - } - } - return dataSource; + return ds; + } + + static String getSchemaNameFromPropertiesObject(String propertiesFileName) { + String schemaName = "TASKANA"; + try (InputStream input = new FileInputStream(propertiesFileName)) { + Properties prop = new Properties(); + prop.load(input); + boolean propertiesFileIsComplete = true; + String warningMessage = ""; + schemaName = prop.getProperty("schemaName"); + if (schemaName == null || schemaName.length() == 0) { + propertiesFileIsComplete = false; + warningMessage += ", schemaName property missing"; + } + + if (!propertiesFileIsComplete) { + LOGGER.warn("propertiesFile " + propertiesFileName + " is incomplete" + warningMessage); + LOGGER.warn("Using default Datasource for Test"); + schemaName = "TASKANA"; + } + + } catch (FileNotFoundException e) { + LOGGER.warn("getSchemaNameFromPropertiesObject caught Exception " + e); + LOGGER.warn("Using default schemaName for Test"); + } catch (IOException e) { + LOGGER.warn("createDataSourceFromProperties caught Exception " + e); + LOGGER.warn("Using default Datasource for Test"); } - /** - * create Default Datasource for in-memory database. - * - * @return the default datasource. - */ - private static DataSource createDefaultDataSource() { - // JdbcDataSource ds = new JdbcDataSource(); - // ds.setURL("jdbc:h2:mem:taskana;IGNORECASE=TRUE;LOCK_MODE=0"); - // ds.setPassword("sa"); - // ds.setUser("sa"); + return schemaName; + } - String jdbcDriver = "org.h2.Driver"; - String jdbcUrl = "jdbc:h2:mem:taskana;IGNORECASE=TRUE;LOCK_MODE=0"; - String dbUserName = "sa"; - String dbPassword = "sa"; - PooledDataSource ds = new PooledDataSource(Thread.currentThread().getContextClassLoader(), jdbcDriver, - jdbcUrl, dbUserName, dbPassword); - ds.setPoolTimeToWait(POOL_TIME_TO_WAIT); - ds.forceCloseAll(); // otherwise the MyBatis pool is not initialized correctly + /** + * create Default Datasource for in-memory database. + * + * @return the default datasource. + */ + private static DataSource createDefaultDataSource() { + // JdbcDataSource ds = new JdbcDataSource(); + // ds.setURL("jdbc:h2:mem:taskana;IGNORECASE=TRUE;LOCK_MODE=0"); + // ds.setPassword("sa"); + // ds.setUser("sa"); - return ds; - } - - /** - * returns the SchemaName used for Junit test. If the file {user.home}/taskanaUnitTest.properties is present, the - * SchemaName is created according to the property schemaName. - * a sample properties file for DB2 looks as follows: - * jdbcDriver=com.ibm.db2.jcc.DB2Driver jdbcUrl=jdbc:db2://localhost:50000/tskdb dbUserName=db2user - * dbPassword=db2password schemaName=TASKANA If any of these properties is missing, or the file doesn't exist, the default schemaName - * TASKANA is created used. - * - * @return String for unit test - */ - public static String getSchemaName() { - if (schemaName == null) { - String userHomeDirectroy = System.getProperty("user.home"); - String propertiesFileName = userHomeDirectroy + "/taskanaUnitTest.properties"; - File f = new File(propertiesFileName); - if (f.exists() && !f.isDirectory()) { - schemaName = getSchemaNameFromPropertiesObject(propertiesFileName); - } else { - schemaName = "TASKANA"; - } - } - return schemaName; - } - - /** - * create data source from properties file. - * - * @param propertiesFileName the name of the property file - * @return the parsed datasource. - */ - public static DataSource createDataSourceFromProperties(String propertiesFileName) { - DataSource ds; - try (InputStream input = new FileInputStream(propertiesFileName)) { - Properties prop = new Properties(); - prop.load(input); - boolean propertiesFileIsComplete = true; - String warningMessage = ""; - String jdbcDriver = prop.getProperty("jdbcDriver"); - if (jdbcDriver == null || jdbcDriver.length() == 0) { - propertiesFileIsComplete = false; - warningMessage += ", jdbcDriver property missing"; - } - String jdbcUrl = prop.getProperty("jdbcUrl"); - if (jdbcUrl == null || jdbcUrl.length() == 0) { - propertiesFileIsComplete = false; - warningMessage += ", jdbcUrl property missing"; - } - String dbUserName = prop.getProperty("dbUserName"); - if (dbUserName == null || dbUserName.length() == 0) { - propertiesFileIsComplete = false; - warningMessage += ", dbUserName property missing"; - } - String dbPassword = prop.getProperty("dbPassword"); - if (dbPassword == null || dbPassword.length() == 0) { - propertiesFileIsComplete = false; - warningMessage += ", dbPassword property missing"; - } - - if (propertiesFileIsComplete) { - ds = new PooledDataSource(Thread.currentThread().getContextClassLoader(), jdbcDriver, - jdbcUrl, dbUserName, dbPassword); - ((PooledDataSource) ds).forceCloseAll(); // otherwise the MyBatis pool is not initialized correctly - } else { - LOGGER.warn("propertiesFile " + propertiesFileName + " is incomplete" + warningMessage); - LOGGER.warn("Using default Datasource for Test"); - ds = createDefaultDataSource(); - } - - } catch (IOException e) { - LOGGER.warn("createDataSourceFromProperties caught Exception " + e); - LOGGER.warn("Using default Datasource for Test"); - ds = createDefaultDataSource(); - } - - return ds; - } - - static String getSchemaNameFromPropertiesObject(String propertiesFileName) { - String schemaName = "TASKANA"; - try (InputStream input = new FileInputStream(propertiesFileName)) { - Properties prop = new Properties(); - prop.load(input); - boolean propertiesFileIsComplete = true; - String warningMessage = ""; - schemaName = prop.getProperty("schemaName"); - if (schemaName == null || schemaName.length() == 0) { - propertiesFileIsComplete = false; - warningMessage += ", schemaName property missing"; - } - - if (!propertiesFileIsComplete) { - LOGGER.warn("propertiesFile " + propertiesFileName + " is incomplete" + warningMessage); - LOGGER.warn("Using default Datasource for Test"); - schemaName = "TASKANA"; - } - - } catch (FileNotFoundException e) { - LOGGER.warn("getSchemaNameFromPropertiesObject caught Exception " + e); - LOGGER.warn("Using default schemaName for Test"); - } catch (IOException e) { - LOGGER.warn("createDataSourceFromProperties caught Exception " + e); - LOGGER.warn("Using default Datasource for Test"); - } - - return schemaName; - } + String jdbcDriver = "org.h2.Driver"; + String jdbcUrl = "jdbc:h2:mem:taskana;IGNORECASE=TRUE;LOCK_MODE=0"; + String dbUserName = "sa"; + String dbPassword = "sa"; + PooledDataSource ds = + new PooledDataSource( + Thread.currentThread().getContextClassLoader(), + jdbcDriver, + jdbcUrl, + dbUserName, + dbPassword); + ds.setPoolTimeToWait(POOL_TIME_TO_WAIT); + ds.forceCloseAll(); // otherwise the MyBatis pool is not initialized correctly + return ds; + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/configuration/TaskanaEngineTestConfigurationTest.java b/lib/taskana-core/src/test/java/pro/taskana/impl/configuration/TaskanaEngineTestConfigurationTest.java index e1537a38a..0e526bdb4 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/configuration/TaskanaEngineTestConfigurationTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/configuration/TaskanaEngineTestConfigurationTest.java @@ -3,27 +3,23 @@ package pro.taskana.impl.configuration; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.sql.SQLException; - import javax.sql.DataSource; - import org.junit.jupiter.api.Test; import pro.taskana.TaskanaEngine; import pro.taskana.configuration.TaskanaEngineConfiguration; -/** - * Test of configuration. - */ +/** Test of configuration. */ class TaskanaEngineTestConfigurationTest { - @Test - void testCreateTaskanaEngine() throws SQLException { - DataSource ds = TaskanaEngineTestConfiguration.getDataSource(); - TaskanaEngineConfiguration taskEngineConfiguration = new TaskanaEngineConfiguration(ds, false, - TaskanaEngineTestConfiguration.getSchemaName()); + @Test + void testCreateTaskanaEngine() throws SQLException { + DataSource ds = TaskanaEngineTestConfiguration.getDataSource(); + TaskanaEngineConfiguration taskEngineConfiguration = + new TaskanaEngineConfiguration(ds, false, TaskanaEngineTestConfiguration.getSchemaName()); - TaskanaEngine te = taskEngineConfiguration.buildTaskanaEngine(); + TaskanaEngine te = taskEngineConfiguration.buildTaskanaEngine(); - assertNotNull(te); - } + assertNotNull(te); + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/integration/ClassificationServiceImplIntAutoCommitTest.java b/lib/taskana-core/src/test/java/pro/taskana/impl/integration/ClassificationServiceImplIntAutoCommitTest.java index 438d132c5..ae3a469f4 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/integration/ClassificationServiceImplIntAutoCommitTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/integration/ClassificationServiceImplIntAutoCommitTest.java @@ -11,9 +11,7 @@ import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneId; import java.util.List; - import javax.sql.DataSource; - import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -42,149 +40,161 @@ import pro.taskana.sampledata.SampleDataGenerator; */ class ClassificationServiceImplIntAutoCommitTest { - static int counter = 0; - private DataSource dataSource; - private ClassificationService classificationService; - private TaskanaEngineConfiguration taskanaEngineConfiguration; - private TaskanaEngine taskanaEngine; - private TaskanaEngineImpl taskanaEngineImpl; + static int counter = 0; + private DataSource dataSource; + private ClassificationService classificationService; + private TaskanaEngineConfiguration taskanaEngineConfiguration; + private TaskanaEngine taskanaEngine; + private TaskanaEngineImpl taskanaEngineImpl; - @BeforeAll - static void resetDb() { - DataSource ds = TaskanaEngineTestConfiguration.getDataSource(); - String schemaName = TaskanaEngineTestConfiguration.getSchemaName(); - new SampleDataGenerator(ds, schemaName).dropDb(); - } + @BeforeAll + static void resetDb() { + DataSource ds = TaskanaEngineTestConfiguration.getDataSource(); + String schemaName = TaskanaEngineTestConfiguration.getSchemaName(); + new SampleDataGenerator(ds, schemaName).dropDb(); + } - @BeforeEach - void setup() throws SQLException { - dataSource = TaskanaEngineTestConfiguration.getDataSource(); - String schemaName = TaskanaEngineTestConfiguration.getSchemaName(); - taskanaEngineConfiguration = new TaskanaEngineConfiguration(dataSource, false, false, - schemaName); - taskanaEngine = taskanaEngineConfiguration.buildTaskanaEngine(); - classificationService = taskanaEngine.getClassificationService(); - taskanaEngineImpl = (TaskanaEngineImpl) taskanaEngine; - taskanaEngineImpl.setConnectionManagementMode(ConnectionManagementMode.AUTOCOMMIT); - new SampleDataGenerator(dataSource, schemaName).clearDb(); - } + @BeforeEach + void setup() throws SQLException { + dataSource = TaskanaEngineTestConfiguration.getDataSource(); + String schemaName = TaskanaEngineTestConfiguration.getSchemaName(); + taskanaEngineConfiguration = + new TaskanaEngineConfiguration(dataSource, false, false, schemaName); + taskanaEngine = taskanaEngineConfiguration.buildTaskanaEngine(); + classificationService = taskanaEngine.getClassificationService(); + taskanaEngineImpl = (TaskanaEngineImpl) taskanaEngine; + taskanaEngineImpl.setConnectionManagementMode(ConnectionManagementMode.AUTOCOMMIT); + new SampleDataGenerator(dataSource, schemaName).clearDb(); + } - @Test - void testFindAllClassifications() - throws ClassificationAlreadyExistException, NotAuthorizedException, DomainNotFoundException, - InvalidArgumentException { - Classification classification0 = this.createDummyClassificationWithUniqueKey("", "TASK"); - classificationService.createClassification(classification0); - Classification classification1 = this.createDummyClassificationWithUniqueKey("", "TASK"); - classificationService.createClassification(classification1); - Classification classification2 = this.createDummyClassificationWithUniqueKey("", "TASK"); - classification2.setParentId(classification0.getId()); - classificationService.createClassification(classification2); + @Test + void testFindAllClassifications() + throws ClassificationAlreadyExistException, NotAuthorizedException, DomainNotFoundException, + InvalidArgumentException { + Classification classification0 = this.createDummyClassificationWithUniqueKey("", "TASK"); + classificationService.createClassification(classification0); + Classification classification1 = this.createDummyClassificationWithUniqueKey("", "TASK"); + classificationService.createClassification(classification1); + Classification classification2 = this.createDummyClassificationWithUniqueKey("", "TASK"); + classification2.setParentId(classification0.getId()); + classificationService.createClassification(classification2); - assertEquals(2 + 1, classificationService.createClassificationQuery().list().size()); - } + assertEquals(2 + 1, classificationService.createClassificationQuery().list().size()); + } - @Test - void testModifiedClassification() - throws ClassificationAlreadyExistException, ClassificationNotFoundException, NotAuthorizedException, - ConcurrencyException, DomainNotFoundException, InvalidArgumentException { - String description = "TEST SOMETHING"; - Classification classification = this.createDummyClassificationWithUniqueKey("DOMAIN_A", "TASK"); - classification.setDescription(""); - classification = classificationService.createClassification(classification); - classification.setDescription("TEST SOMETHING"); - classificationService.updateClassification(classification); + @Test + void testModifiedClassification() + throws ClassificationAlreadyExistException, ClassificationNotFoundException, + NotAuthorizedException, ConcurrencyException, DomainNotFoundException, + InvalidArgumentException { + String description = "TEST SOMETHING"; + Classification classification = this.createDummyClassificationWithUniqueKey("DOMAIN_A", "TASK"); + classification.setDescription(""); + classification = classificationService.createClassification(classification); + classification.setDescription("TEST SOMETHING"); + classificationService.updateClassification(classification); - classification = classificationService.getClassification(classification.getKey(), classification.getDomain()); - assertThat(description, equalTo(classification.getDescription())); - } + classification = + classificationService.getClassification( + classification.getKey(), classification.getDomain()); + assertThat(description, equalTo(classification.getDescription())); + } - @Test - void testInsertClassification() - throws NotAuthorizedException, ClassificationAlreadyExistException, InvalidArgumentException, - DomainNotFoundException { - Classification classification = this.createDummyClassificationWithUniqueKey("DOMAIN_A", "TASK"); - classification = classificationService.createClassification(classification); + @Test + void testInsertClassification() + throws NotAuthorizedException, ClassificationAlreadyExistException, InvalidArgumentException, + DomainNotFoundException { + Classification classification = this.createDummyClassificationWithUniqueKey("DOMAIN_A", "TASK"); + classification = classificationService.createClassification(classification); - List list = classificationService.createClassificationQuery() + List list = + classificationService + .createClassificationQuery() .validInDomainEquals(Boolean.TRUE) .createdWithin(today()) .list(); - assertEquals(1, list.size()); - } + assertEquals(1, list.size()); + } - @Test - void testUpdateClassification() - throws NotAuthorizedException, ClassificationAlreadyExistException, ClassificationNotFoundException, - ConcurrencyException, DomainNotFoundException, InvalidArgumentException { - Classification classification = this.createDummyClassificationWithUniqueKey("DOMAIN_A", "TASK"); - classification = classificationService.createClassification(classification); - classification.setDescription("description"); - classification = classificationService.updateClassification(classification); + @Test + void testUpdateClassification() + throws NotAuthorizedException, ClassificationAlreadyExistException, + ClassificationNotFoundException, ConcurrencyException, DomainNotFoundException, + InvalidArgumentException { + Classification classification = this.createDummyClassificationWithUniqueKey("DOMAIN_A", "TASK"); + classification = classificationService.createClassification(classification); + classification.setDescription("description"); + classification = classificationService.updateClassification(classification); - List list = classificationService.createClassificationQuery() - .validInDomainEquals(true) + List list = + classificationService.createClassificationQuery().validInDomainEquals(true).list(); + assertEquals(1, list.size()); + + classification = classificationService.updateClassification(classification); + list = classificationService.createClassificationQuery().list(); + assertEquals(2, list.size()); + + List allClassifications = + classificationService.createClassificationQuery().list(); + assertEquals(2, allClassifications.size()); + } + + @Test + void testDefaultSettings() + throws NotAuthorizedException, ClassificationAlreadyExistException, + ClassificationNotFoundException, ConcurrencyException, DomainNotFoundException, + InvalidArgumentException { + Classification classification = this.createDummyClassificationWithUniqueKey("DOMAIN_A", "TASK"); + classification = classificationService.createClassification(classification); + + Classification classification1 = + this.createDummyClassificationWithUniqueKey("DOMAIN_A", "TASK"); + classification1 = classificationService.createClassification(classification1); + + classification1.setParentId(classification.getId()); + classification1 = classificationService.updateClassification(classification1); + + List list = + classificationService.createClassificationQuery().parentIdIn("").list(); + assertEquals(3, list.size()); + list = classificationService.createClassificationQuery().list(); + assertEquals(4, list.size()); + + List listAll = classificationService.createClassificationQuery().list(); + list = classificationService.createClassificationQuery().list(); + assertEquals(listAll.size(), list.size()); + + list = classificationService.createClassificationQuery().validInDomainEquals(true).list(); + assertEquals(2, list.size()); + + list = classificationService.createClassificationQuery().createdWithin(today()).list(); + assertEquals(4, list.size()); + + list = + classificationService + .createClassificationQuery() + .domainIn("DOMAIN_C") + .validInDomainEquals(false) .list(); - assertEquals(1, list.size()); + assertEquals(0, list.size()); - classification = classificationService.updateClassification(classification); - list = classificationService.createClassificationQuery() - .list(); - assertEquals(2, list.size()); + list = classificationService.createClassificationQuery().list(); + assertEquals(4, list.size()); + } - List allClassifications = classificationService.createClassificationQuery().list(); - assertEquals(2, allClassifications.size()); - } + private TimeInterval today() { + Instant begin = + LocalDateTime.of(LocalDate.now(), LocalTime.MIN).atZone(ZoneId.systemDefault()).toInstant(); + Instant end = + LocalDateTime.of(LocalDate.now(), LocalTime.MAX).atZone(ZoneId.systemDefault()).toInstant(); + return new TimeInterval(begin, end); + } - @Test - void testDefaultSettings() - throws NotAuthorizedException, ClassificationAlreadyExistException, ClassificationNotFoundException, - ConcurrencyException, DomainNotFoundException, InvalidArgumentException { - Classification classification = this.createDummyClassificationWithUniqueKey("DOMAIN_A", "TASK"); - classification = classificationService.createClassification(classification); - - Classification classification1 = this.createDummyClassificationWithUniqueKey("DOMAIN_A", "TASK"); - classification1 = classificationService.createClassification(classification1); - - classification1.setParentId(classification.getId()); - classification1 = classificationService.updateClassification(classification1); - - List list = classificationService.createClassificationQuery() - .parentIdIn("") - .list(); - assertEquals(3, list.size()); - list = classificationService.createClassificationQuery() - .list(); - assertEquals(4, list.size()); - - List listAll = classificationService.createClassificationQuery().list(); - list = classificationService.createClassificationQuery().list(); - assertEquals(listAll.size(), list.size()); - - list = classificationService.createClassificationQuery().validInDomainEquals(true).list(); - assertEquals(2, list.size()); - - list = classificationService.createClassificationQuery().createdWithin(today()).list(); - assertEquals(4, list.size()); - - list = classificationService.createClassificationQuery().domainIn("DOMAIN_C").validInDomainEquals(false).list(); - assertEquals(0, list.size()); - - list = classificationService.createClassificationQuery() - .list(); - assertEquals(4, list.size()); - } - - private TimeInterval today() { - Instant begin = LocalDateTime.of(LocalDate.now(), LocalTime.MIN).atZone(ZoneId.systemDefault()).toInstant(); - Instant end = LocalDateTime.of(LocalDate.now(), LocalTime.MAX).atZone(ZoneId.systemDefault()).toInstant(); - return new TimeInterval(begin, end); - } - - private Classification createDummyClassificationWithUniqueKey(String domain, String type) { - Classification classification = classificationService.newClassification("TEST" + counter, domain, type); - counter++; - return classification; - } + private Classification createDummyClassificationWithUniqueKey(String domain, String type) { + Classification classification = + classificationService.newClassification("TEST" + counter, domain, type); + counter++; + return classification; + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/integration/ClassificationServiceImplIntExplicitTest.java b/lib/taskana-core/src/test/java/pro/taskana/impl/integration/ClassificationServiceImplIntExplicitTest.java index aa9c6103d..55ca538e2 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/integration/ClassificationServiceImplIntExplicitTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/integration/ClassificationServiceImplIntExplicitTest.java @@ -13,9 +13,7 @@ import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneId; import java.util.List; - import javax.sql.DataSource; - import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; @@ -46,221 +44,233 @@ import pro.taskana.sampledata.SampleDataGenerator; * * @author BBR */ - public class ClassificationServiceImplIntExplicitTest { - private static final String ID_PREFIX_CLASSIFICATION = "CLI"; - static int counter = 0; - private DataSource dataSource; - private ClassificationService classificationService; - private TaskanaEngineConfiguration taskanaEngineConfiguration; - private TaskanaEngine taskanaEngine; - private TaskanaEngineImpl taskanaEngineImpl; + private static final String ID_PREFIX_CLASSIFICATION = "CLI"; + static int counter = 0; + private DataSource dataSource; + private ClassificationService classificationService; + private TaskanaEngineConfiguration taskanaEngineConfiguration; + private TaskanaEngine taskanaEngine; + private TaskanaEngineImpl taskanaEngineImpl; - @BeforeAll - public static void resetDb() throws SQLException { - DataSource ds = TaskanaEngineTestConfiguration.getDataSource(); - String schemaName = TaskanaEngineTestConfiguration.getSchemaName(); - new SampleDataGenerator(ds, schemaName).dropDb(); - } + @BeforeAll + public static void resetDb() throws SQLException { + DataSource ds = TaskanaEngineTestConfiguration.getDataSource(); + String schemaName = TaskanaEngineTestConfiguration.getSchemaName(); + new SampleDataGenerator(ds, schemaName).dropDb(); + } - @BeforeEach - public void setup() throws SQLException { - dataSource = TaskanaEngineTestConfiguration.getDataSource(); - String schemaName = TaskanaEngineTestConfiguration.getSchemaName(); - taskanaEngineConfiguration = new TaskanaEngineConfiguration(dataSource, false, false, - schemaName); - taskanaEngine = taskanaEngineConfiguration.buildTaskanaEngine(); - classificationService = taskanaEngine.getClassificationService(); - taskanaEngineImpl = (TaskanaEngineImpl) taskanaEngine; - taskanaEngineImpl.setConnectionManagementMode(ConnectionManagementMode.EXPLICIT); - SampleDataGenerator sampleDataGenerator = new SampleDataGenerator(dataSource, schemaName); - sampleDataGenerator.clearDb(); - } + @BeforeEach + public void setup() throws SQLException { + dataSource = TaskanaEngineTestConfiguration.getDataSource(); + String schemaName = TaskanaEngineTestConfiguration.getSchemaName(); + taskanaEngineConfiguration = + new TaskanaEngineConfiguration(dataSource, false, false, schemaName); + taskanaEngine = taskanaEngineConfiguration.buildTaskanaEngine(); + classificationService = taskanaEngine.getClassificationService(); + taskanaEngineImpl = (TaskanaEngineImpl) taskanaEngine; + taskanaEngineImpl.setConnectionManagementMode(ConnectionManagementMode.EXPLICIT); + SampleDataGenerator sampleDataGenerator = new SampleDataGenerator(dataSource, schemaName); + sampleDataGenerator.clearDb(); + } - @AfterEach - public void cleanUp() throws SQLException { - taskanaEngineImpl.setConnection(null); - } + @AfterEach + public void cleanUp() throws SQLException { + taskanaEngineImpl.setConnection(null); + } - @Test - public void testInsertClassification() - throws SQLException, ClassificationNotFoundException, ClassificationAlreadyExistException, - NotAuthorizedException, DomainNotFoundException, InvalidArgumentException { - Connection connection = dataSource.getConnection(); - taskanaEngineImpl.setConnection(connection); + @Test + public void testInsertClassification() + throws SQLException, ClassificationNotFoundException, ClassificationAlreadyExistException, + NotAuthorizedException, DomainNotFoundException, InvalidArgumentException { + Connection connection = dataSource.getConnection(); + taskanaEngineImpl.setConnection(connection); - final String domain = "DOMAIN_A"; - final String key = "dummy-key"; - ClassificationImpl expectedClassification; - Classification actualClassification; + final String domain = "DOMAIN_A"; + final String key = "dummy-key"; + ClassificationImpl expectedClassification; + Classification actualClassification; - // new classification but master existing - expectedClassification = (ClassificationImpl) this.createNewClassificationWithUniqueKey("", "TASK"); - expectedClassification.setKey(key); - expectedClassification.setDomain("DOMAIN_B"); - classificationService.createClassification(expectedClassification); - connection.commit(); - actualClassification = classificationService.getClassification(key, "DOMAIN_B"); - assertThat(actualClassification, not(IsEqual.equalTo(null))); - assertThat(actualClassification.getCreated(), not(IsEqual.equalTo(null))); - assertThat(actualClassification.getId(), not(IsEqual.equalTo(null))); - assertThat(actualClassification.getKey(), IsEqual.equalTo(key)); - assertThat(actualClassification.getDomain(), IsEqual.equalTo("DOMAIN_B")); - assertThat(actualClassification.getId(), startsWith(ID_PREFIX_CLASSIFICATION)); - Classification masterResult = classificationService.getClassification(key, ""); - assertThat(masterResult, not(IsEqual.equalTo(null))); + // new classification but master existing + expectedClassification = + (ClassificationImpl) this.createNewClassificationWithUniqueKey("", "TASK"); + expectedClassification.setKey(key); + expectedClassification.setDomain("DOMAIN_B"); + classificationService.createClassification(expectedClassification); + connection.commit(); + actualClassification = classificationService.getClassification(key, "DOMAIN_B"); + assertThat(actualClassification, not(IsEqual.equalTo(null))); + assertThat(actualClassification.getCreated(), not(IsEqual.equalTo(null))); + assertThat(actualClassification.getId(), not(IsEqual.equalTo(null))); + assertThat(actualClassification.getKey(), IsEqual.equalTo(key)); + assertThat(actualClassification.getDomain(), IsEqual.equalTo("DOMAIN_B")); + assertThat(actualClassification.getId(), startsWith(ID_PREFIX_CLASSIFICATION)); + Classification masterResult = classificationService.getClassification(key, ""); + assertThat(masterResult, not(IsEqual.equalTo(null))); - // invalid serviceLevel - ClassificationImpl expectedClassificationCreated = (ClassificationImpl) this.createNewClassificationWithUniqueKey( - "", "TASK"); - expectedClassificationCreated.setDomain(domain); - expectedClassificationCreated.setKey(""); - expectedClassificationCreated.setServiceLevel("ASAP"); + // invalid serviceLevel + ClassificationImpl expectedClassificationCreated = + (ClassificationImpl) this.createNewClassificationWithUniqueKey("", "TASK"); + expectedClassificationCreated.setDomain(domain); + expectedClassificationCreated.setKey(""); + expectedClassificationCreated.setServiceLevel("ASAP"); - Assertions.assertThrows(InvalidArgumentException.class, () -> { - classificationService.createClassification(expectedClassificationCreated); - }, - "Should have thrown IllegalArgumentException, because ServiceLevel is invalid."); + Assertions.assertThrows( + InvalidArgumentException.class, + () -> { + classificationService.createClassification(expectedClassificationCreated); + }, + "Should have thrown IllegalArgumentException, because ServiceLevel is invalid."); - connection.commit(); - } + connection.commit(); + } - @Test - public void testFindAllClassifications() - throws SQLException, ClassificationAlreadyExistException, NotAuthorizedException, - DomainNotFoundException, InvalidArgumentException { - Connection connection = dataSource.getConnection(); - taskanaEngineImpl.setConnection(connection); - Classification classification0 = this.createNewClassificationWithUniqueKey("", "TASK"); - classificationService.createClassification(classification0); - Classification classification1 = this.createNewClassificationWithUniqueKey("", "TASK"); - classificationService.createClassification(classification1); - Classification classification2 = this.createNewClassificationWithUniqueKey("", "TASK"); - classification2.setParentId(classification0.getId()); - classificationService.createClassification(classification2); + @Test + public void testFindAllClassifications() + throws SQLException, ClassificationAlreadyExistException, NotAuthorizedException, + DomainNotFoundException, InvalidArgumentException { + Connection connection = dataSource.getConnection(); + taskanaEngineImpl.setConnection(connection); + Classification classification0 = this.createNewClassificationWithUniqueKey("", "TASK"); + classificationService.createClassification(classification0); + Classification classification1 = this.createNewClassificationWithUniqueKey("", "TASK"); + classificationService.createClassification(classification1); + Classification classification2 = this.createNewClassificationWithUniqueKey("", "TASK"); + classification2.setParentId(classification0.getId()); + classificationService.createClassification(classification2); - assertEquals(2 + 1, classificationService.createClassificationQuery().list().size()); - connection.commit(); - } + assertEquals(2 + 1, classificationService.createClassificationQuery().list().size()); + connection.commit(); + } - @Test - public void testModifiedClassification() - throws SQLException, ClassificationAlreadyExistException, ClassificationNotFoundException, - NotAuthorizedException, ConcurrencyException, DomainNotFoundException, InvalidArgumentException { + @Test + public void testModifiedClassification() + throws SQLException, ClassificationAlreadyExistException, ClassificationNotFoundException, + NotAuthorizedException, ConcurrencyException, DomainNotFoundException, + InvalidArgumentException { - Connection connection = dataSource.getConnection(); - taskanaEngineImpl.setConnection(connection); - Classification classification = this.createNewClassificationWithUniqueKey("DOMAIN_A", "TASK"); - connection.commit(); - classification = classificationService.createClassification(classification); + Connection connection = dataSource.getConnection(); + taskanaEngineImpl.setConnection(connection); + Classification classification = this.createNewClassificationWithUniqueKey("DOMAIN_A", "TASK"); + connection.commit(); + classification = classificationService.createClassification(classification); - String updatedDescription = "TEST SOMETHING"; - classification.setDescription(updatedDescription); - classification = classificationService.updateClassification(classification); - connection.commit(); + String updatedDescription = "TEST SOMETHING"; + classification.setDescription(updatedDescription); + classification = classificationService.updateClassification(classification); + connection.commit(); - classification = classificationService.getClassification(classification.getKey(), classification.getDomain()); - assertThat(classification.getDescription(), IsEqual.equalTo(updatedDescription)); - } + classification = + classificationService.getClassification( + classification.getKey(), classification.getDomain()); + assertThat(classification.getDescription(), IsEqual.equalTo(updatedDescription)); + } - @Test - public void testInsertAndClassificationQuery() - throws SQLException, ClassificationAlreadyExistException, NotAuthorizedException, - DomainNotFoundException, InvalidArgumentException { - Connection connection = dataSource.getConnection(); - taskanaEngineImpl.setConnection(connection); - Classification classification = this.createNewClassificationWithUniqueKey("DOMAIN_A", "TASK"); - classificationService.createClassification(classification); - List list = classificationService.createClassificationQuery() + @Test + public void testInsertAndClassificationQuery() + throws SQLException, ClassificationAlreadyExistException, NotAuthorizedException, + DomainNotFoundException, InvalidArgumentException { + Connection connection = dataSource.getConnection(); + taskanaEngineImpl.setConnection(connection); + Classification classification = this.createNewClassificationWithUniqueKey("DOMAIN_A", "TASK"); + classificationService.createClassification(classification); + List list = + classificationService + .createClassificationQuery() .validInDomainEquals(Boolean.TRUE) .createdWithin(today()) .list(); - assertEquals(1, list.size()); - } + assertEquals(1, list.size()); + } - @Test - public void testUpdateAndClassificationQuery() throws NotAuthorizedException, SQLException, - ClassificationAlreadyExistException, ClassificationNotFoundException, ConcurrencyException, - DomainNotFoundException, InvalidArgumentException { - Connection connection = dataSource.getConnection(); - taskanaEngineImpl.setConnection(connection); - Classification classification = this.createNewClassificationWithUniqueKey("DOMAIN_A", "TASK"); - classification.setDescription(""); - classification = classificationService.createClassification(classification); - classification.setDescription("description"); - classification = classificationService.updateClassification(classification); + @Test + public void testUpdateAndClassificationQuery() + throws NotAuthorizedException, SQLException, ClassificationAlreadyExistException, + ClassificationNotFoundException, ConcurrencyException, DomainNotFoundException, + InvalidArgumentException { + Connection connection = dataSource.getConnection(); + taskanaEngineImpl.setConnection(connection); + Classification classification = this.createNewClassificationWithUniqueKey("DOMAIN_A", "TASK"); + classification.setDescription(""); + classification = classificationService.createClassification(classification); + classification.setDescription("description"); + classification = classificationService.updateClassification(classification); - List list = classificationService.createClassificationQuery() + List list = classificationService.createClassificationQuery().list(); + assertEquals(2, list.size()); + list = classificationService.createClassificationQuery().validInDomainEquals(true).list(); + assertEquals(1, list.size()); + classification = + classificationService.getClassification( + classification.getKey(), classification.getDomain()); + assertThat(classification.getDescription(), IsEqual.equalTo("description")); + + classification = classificationService.updateClassification(classification); + list = classificationService.createClassificationQuery().list(); + assertEquals(2, list.size()); + + List allClassifications = + classificationService.createClassificationQuery().list(); + assertEquals(2, allClassifications.size()); + connection.commit(); + } + + @Test + public void testDefaultSettingsWithClassificationQuery() + throws NotAuthorizedException, SQLException, ClassificationAlreadyExistException, + ClassificationNotFoundException, InvalidArgumentException, ConcurrencyException, + DomainNotFoundException { + Connection connection = dataSource.getConnection(); + taskanaEngineImpl.setConnection(connection); + Classification classification = this.createNewClassificationWithUniqueKey("DOMAIN_A", "TASK"); + classification = classificationService.createClassification(classification); + + Classification classification1 = this.createNewClassificationWithUniqueKey("DOMAIN_A", "TASK"); + classification1 = classificationService.createClassification(classification1); + classification1.setParentId(classification.getId()); + classification1 = classificationService.updateClassification(classification1); + + List list = + classificationService.createClassificationQuery().parentIdIn("").list(); + assertEquals(3, list.size()); + list = classificationService.createClassificationQuery().list(); + assertEquals(4, list.size()); + connection.commit(); + + list = classificationService.createClassificationQuery().validInDomainEquals(true).list(); + assertEquals(2, list.size()); + list = classificationService.createClassificationQuery().createdWithin(today()).list(); + assertEquals(4, list.size()); + list = + classificationService + .createClassificationQuery() + .domainIn("DOMAIN_C") + .validInDomainEquals(false) .list(); - assertEquals(2, list.size()); - list = classificationService.createClassificationQuery().validInDomainEquals(true).list(); - assertEquals(1, list.size()); - classification = classificationService.getClassification(classification.getKey(), classification.getDomain()); - assertThat(classification.getDescription(), IsEqual.equalTo("description")); + assertEquals(0, list.size()); + list = classificationService.createClassificationQuery().keyIn(classification1.getKey()).list(); + assertEquals(2, list.size()); - classification = classificationService.updateClassification(classification); - list = classificationService.createClassificationQuery() - .list(); - assertEquals(2, list.size()); + list = + classificationService.createClassificationQuery().parentIdIn(classification.getId()).list(); + assertEquals(1, list.size()); + assertThat(list.get(0).getKey(), IsEqual.equalTo(classification1.getKey())); + connection.commit(); + } - List allClassifications = classificationService.createClassificationQuery().list(); - assertEquals(2, allClassifications.size()); - connection.commit(); - } - - @Test - public void testDefaultSettingsWithClassificationQuery() throws NotAuthorizedException, SQLException, - ClassificationAlreadyExistException, ClassificationNotFoundException, InvalidArgumentException, - ConcurrencyException, DomainNotFoundException { - Connection connection = dataSource.getConnection(); - taskanaEngineImpl.setConnection(connection); - Classification classification = this.createNewClassificationWithUniqueKey("DOMAIN_A", "TASK"); - classification = classificationService.createClassification(classification); - - Classification classification1 = this.createNewClassificationWithUniqueKey("DOMAIN_A", "TASK"); - classification1 = classificationService.createClassification(classification1); - classification1.setParentId(classification.getId()); - classification1 = classificationService.updateClassification(classification1); - - List list = classificationService.createClassificationQuery() - .parentIdIn("") - .list(); - assertEquals(3, list.size()); - list = classificationService.createClassificationQuery() - .list(); - assertEquals(4, list.size()); - connection.commit(); - - list = classificationService.createClassificationQuery().validInDomainEquals(true).list(); - assertEquals(2, list.size()); - list = classificationService.createClassificationQuery().createdWithin(today()).list(); - assertEquals(4, list.size()); - list = classificationService.createClassificationQuery().domainIn("DOMAIN_C").validInDomainEquals(false).list(); - assertEquals(0, list.size()); - list = classificationService.createClassificationQuery() - .keyIn(classification1.getKey()) - .list(); - assertEquals(2, list.size()); - - list = classificationService.createClassificationQuery() - .parentIdIn(classification.getId()) - .list(); - assertEquals(1, list.size()); - assertThat(list.get(0).getKey(), IsEqual.equalTo(classification1.getKey())); - connection.commit(); - } - - private Classification createNewClassificationWithUniqueKey(String domain, String type) { - Classification classification = classificationService.newClassification("TEST" + counter, domain, type); - counter++; - return classification; - } - - private TimeInterval today() { - Instant begin = LocalDateTime.of(LocalDate.now(), LocalTime.MIN).atZone(ZoneId.systemDefault()).toInstant(); - Instant end = LocalDateTime.of(LocalDate.now(), LocalTime.MAX).atZone(ZoneId.systemDefault()).toInstant(); - return new TimeInterval(begin, end); - } + private Classification createNewClassificationWithUniqueKey(String domain, String type) { + Classification classification = + classificationService.newClassification("TEST" + counter, domain, type); + counter++; + return classification; + } + private TimeInterval today() { + Instant begin = + LocalDateTime.of(LocalDate.now(), LocalTime.MIN).atZone(ZoneId.systemDefault()).toInstant(); + Instant end = + LocalDateTime.of(LocalDate.now(), LocalTime.MAX).atZone(ZoneId.systemDefault()).toInstant(); + return new TimeInterval(begin, end); + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/integration/TaskServiceImplIntAutocommitTest.java b/lib/taskana-core/src/test/java/pro/taskana/impl/integration/TaskServiceImplIntAutocommitTest.java index 5d93a73d2..b676d4b99 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/integration/TaskServiceImplIntAutocommitTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/integration/TaskServiceImplIntAutocommitTest.java @@ -9,9 +9,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import java.sql.SQLException; import java.util.List; import java.util.UUID; - import javax.sql.DataSource; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -64,121 +62,129 @@ import pro.taskana.security.WithAccessId; @ExtendWith(JAASExtension.class) class TaskServiceImplIntAutocommitTest { - private DataSource dataSource; + private DataSource dataSource; - private TaskServiceImpl taskServiceImpl; + private TaskServiceImpl taskServiceImpl; - private TaskanaEngineConfiguration taskanaEngineConfiguration; + private TaskanaEngineConfiguration taskanaEngineConfiguration; - private TaskanaEngine taskanaEngine; + private TaskanaEngine taskanaEngine; - private TaskanaEngineImpl taskanaEngineImpl; + private TaskanaEngineImpl taskanaEngineImpl; - private ClassificationService classificationService; + private ClassificationService classificationService; - private WorkbasketService workbasketService; + private WorkbasketService workbasketService; - @BeforeEach - void setup() throws SQLException { - dataSource = TaskanaEngineTestConfiguration.getDataSource(); - String schemaName = TaskanaEngineTestConfiguration.getSchemaName(); - taskanaEngineConfiguration = new TaskanaEngineConfiguration(dataSource, false, false, - schemaName); + @BeforeEach + void setup() throws SQLException { + dataSource = TaskanaEngineTestConfiguration.getDataSource(); + String schemaName = TaskanaEngineTestConfiguration.getSchemaName(); + taskanaEngineConfiguration = + new TaskanaEngineConfiguration(dataSource, false, false, schemaName); - taskanaEngine = taskanaEngineConfiguration.buildTaskanaEngine(); - taskanaEngineImpl = (TaskanaEngineImpl) taskanaEngine; - taskanaEngineImpl.setConnectionManagementMode(ConnectionManagementMode.AUTOCOMMIT); - taskServiceImpl = (TaskServiceImpl) taskanaEngine.getTaskService(); - classificationService = taskanaEngine.getClassificationService(); - workbasketService = taskanaEngine.getWorkbasketService(); - SampleDataGenerator sampleDataGenerator = new SampleDataGenerator(dataSource, schemaName); - sampleDataGenerator.clearDb(); - } + taskanaEngine = taskanaEngineConfiguration.buildTaskanaEngine(); + taskanaEngineImpl = (TaskanaEngineImpl) taskanaEngine; + taskanaEngineImpl.setConnectionManagementMode(ConnectionManagementMode.AUTOCOMMIT); + taskServiceImpl = (TaskServiceImpl) taskanaEngine.getTaskService(); + classificationService = taskanaEngine.getClassificationService(); + workbasketService = taskanaEngine.getWorkbasketService(); + SampleDataGenerator sampleDataGenerator = new SampleDataGenerator(dataSource, schemaName); + sampleDataGenerator.clearDb(); + } - @Test - void testStart() throws TaskNotFoundException, - WorkbasketNotFoundException, NotAuthorizedException, ClassificationNotFoundException, - ClassificationAlreadyExistException, TaskAlreadyExistException, InvalidWorkbasketException, - InvalidArgumentException, WorkbasketAlreadyExistException, DomainNotFoundException { + @Test + void testStart() + throws TaskNotFoundException, WorkbasketNotFoundException, NotAuthorizedException, + ClassificationNotFoundException, ClassificationAlreadyExistException, + TaskAlreadyExistException, InvalidWorkbasketException, InvalidArgumentException, + WorkbasketAlreadyExistException, DomainNotFoundException { - Workbasket wb = workbasketService.newWorkbasket("workbasket", "DOMAIN_A"); - wb.setName("workbasket"); - wb.setType(WorkbasketType.GROUP); - taskanaEngine.getWorkbasketService().createWorkbasket(wb); + Workbasket wb = workbasketService.newWorkbasket("workbasket", "DOMAIN_A"); + wb.setName("workbasket"); + wb.setType(WorkbasketType.GROUP); + taskanaEngine.getWorkbasketService().createWorkbasket(wb); - Classification classification = classificationService.newClassification("TEST", "DOMAIN_A", "TASK"); - taskanaEngine.getClassificationService().createClassification(classification); + Classification classification = + classificationService.newClassification("TEST", "DOMAIN_A", "TASK"); + taskanaEngine.getClassificationService().createClassification(classification); - Task task = taskServiceImpl.newTask(wb.getId()); - task.setName("Unit Test Task"); + Task task = taskServiceImpl.newTask(wb.getId()); + task.setName("Unit Test Task"); - task.setClassificationKey(classification.getKey()); - task.setPrimaryObjRef(JunitHelper.createDefaultObjRef()); - task = taskServiceImpl.createTask(task); + task.setClassificationKey(classification.getKey()); + task.setPrimaryObjRef(JunitHelper.createDefaultObjRef()); + task = taskServiceImpl.createTask(task); - TaskanaEngine te2 = taskanaEngineConfiguration.buildTaskanaEngine(); - TaskServiceImpl taskServiceImpl2 = (TaskServiceImpl) te2.getTaskService(); - Task resultTask = taskServiceImpl2.getTask(task.getId()); - assertNotNull(resultTask); - } + TaskanaEngine te2 = taskanaEngineConfiguration.buildTaskanaEngine(); + TaskServiceImpl taskServiceImpl2 = (TaskServiceImpl) te2.getTaskService(); + Task resultTask = taskServiceImpl2.getTask(task.getId()); + assertNotNull(resultTask); + } - @Test - void testStartTransactionFail() - throws TaskNotFoundException, NotAuthorizedException, - WorkbasketNotFoundException, ClassificationNotFoundException, ClassificationAlreadyExistException, - TaskAlreadyExistException, InvalidWorkbasketException, InvalidArgumentException, - WorkbasketAlreadyExistException, DomainNotFoundException { + @Test + void testStartTransactionFail() + throws TaskNotFoundException, NotAuthorizedException, WorkbasketNotFoundException, + ClassificationNotFoundException, ClassificationAlreadyExistException, + TaskAlreadyExistException, InvalidWorkbasketException, InvalidArgumentException, + WorkbasketAlreadyExistException, DomainNotFoundException { - Workbasket wb = workbasketService.newWorkbasket("wb1k1", "DOMAIN_A"); - wb.setName("sdf"); - wb.setType(WorkbasketType.GROUP); - taskanaEngine.getWorkbasketService().createWorkbasket(wb); + Workbasket wb = workbasketService.newWorkbasket("wb1k1", "DOMAIN_A"); + wb.setName("sdf"); + wb.setType(WorkbasketType.GROUP); + taskanaEngine.getWorkbasketService().createWorkbasket(wb); - Classification classification = classificationService.newClassification("TEST", "DOMAIN_A", "TASK"); - classification = taskanaEngine.getClassificationService() - .createClassification(classification); - classification = taskanaEngine.getClassificationService() - .getClassification( - classification.getKey(), - classification.getDomain()); + Classification classification = + classificationService.newClassification("TEST", "DOMAIN_A", "TASK"); + classification = taskanaEngine.getClassificationService().createClassification(classification); + classification = + taskanaEngine + .getClassificationService() + .getClassification(classification.getKey(), classification.getDomain()); - TaskImpl task = (TaskImpl) taskServiceImpl.newTask(wb.getKey(), "DOMAIN_A"); - task.setName("Unit Test Task"); - task.setClassificationKey(classification.getKey()); - task.setPrimaryObjRef(JunitHelper.createDefaultObjRef()); - taskServiceImpl.createTask(task); - taskServiceImpl.getTask(task.getId()); + TaskImpl task = (TaskImpl) taskServiceImpl.newTask(wb.getKey(), "DOMAIN_A"); + task.setName("Unit Test Task"); + task.setClassificationKey(classification.getKey()); + task.setPrimaryObjRef(JunitHelper.createDefaultObjRef()); + taskServiceImpl.createTask(task); + taskServiceImpl.getTask(task.getId()); - TaskanaEngineImpl te2 = (TaskanaEngineImpl) taskanaEngineConfiguration.buildTaskanaEngine(); - TaskServiceImpl taskServiceImpl2 = (TaskServiceImpl) te2.getTaskService(); + TaskanaEngineImpl te2 = (TaskanaEngineImpl) taskanaEngineConfiguration.buildTaskanaEngine(); + TaskServiceImpl taskServiceImpl2 = (TaskServiceImpl) te2.getTaskService(); - Assertions.assertThrows(TaskNotFoundException.class, () -> taskServiceImpl2.getTask(wb.getId())); - } + Assertions.assertThrows( + TaskNotFoundException.class, () -> taskServiceImpl2.getTask(wb.getId())); + } - @Test - void should_ReturnList_when_BuilderIsUsed() throws NotAuthorizedException, - WorkbasketNotFoundException, ClassificationNotFoundException, ClassificationAlreadyExistException, - TaskAlreadyExistException, InvalidWorkbasketException, InvalidArgumentException, SystemException, - WorkbasketAlreadyExistException, DomainNotFoundException { - Workbasket wb = workbasketService.newWorkbasket("key", "DOMAIN_A"); - wb.setName("workbasket"); - wb.setType(WorkbasketType.GROUP); - taskanaEngine.getWorkbasketService().createWorkbasket(wb); - Classification classification = classificationService.newClassification("TEST", "DOMAIN_A", "TASK"); - taskanaEngine.getClassificationService().createClassification(classification); + @Test + void should_ReturnList_when_BuilderIsUsed() + throws NotAuthorizedException, WorkbasketNotFoundException, ClassificationNotFoundException, + ClassificationAlreadyExistException, TaskAlreadyExistException, + InvalidWorkbasketException, InvalidArgumentException, SystemException, + WorkbasketAlreadyExistException, DomainNotFoundException { + Workbasket wb = workbasketService.newWorkbasket("key", "DOMAIN_A"); + wb.setName("workbasket"); + wb.setType(WorkbasketType.GROUP); + taskanaEngine.getWorkbasketService().createWorkbasket(wb); + Classification classification = + classificationService.newClassification("TEST", "DOMAIN_A", "TASK"); + taskanaEngine.getClassificationService().createClassification(classification); - Task task = taskServiceImpl.newTask(wb.getKey(), wb.getDomain()); - task.setName("Unit Test Task"); - task.setClassificationKey(classification.getKey()); - task.setPrimaryObjRef(JunitHelper.createDefaultObjRef()); - taskServiceImpl.createTask(task); + Task task = taskServiceImpl.newTask(wb.getKey(), wb.getDomain()); + task.setName("Unit Test Task"); + task.setClassificationKey(classification.getKey()); + task.setPrimaryObjRef(JunitHelper.createDefaultObjRef()); + taskServiceImpl.createTask(task); - List results = taskServiceImpl.createTaskQuery() + List results = + taskServiceImpl + .createTaskQuery() .nameIn("bla", "test") .descriptionLike("test") .priorityIn(1, 2, 2) .stateIn(TaskState.CLAIMED) - .workbasketKeyDomainIn(new KeyDomain("asd", "novatec"), new KeyDomain("asdasdasd", "DOMAIN_A")) + .workbasketKeyDomainIn( + new KeyDomain("asd", "novatec"), new KeyDomain("asdasdasd", "DOMAIN_A")) .ownerIn("test", "test2", "bla") .customAttributeIn("16", "test") .classificationKeyIn("pId1", "pId2") @@ -189,205 +195,228 @@ class TaskServiceImplIntAutocommitTest { .primaryObjectReferenceValueIn("val1", "val2", "val3") .list(); - assertEquals(0, results.size()); - } + assertEquals(0, results.size()); + } - @Test - void shouldTransferTaskToOtherWorkbasket() - throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - ClassificationAlreadyExistException, TaskNotFoundException, InterruptedException, TaskAlreadyExistException, - InvalidWorkbasketException, InvalidArgumentException, WorkbasketAlreadyExistException, DomainNotFoundException, - InvalidStateException { - Workbasket sourceWB; - Workbasket destinationWB; - WorkbasketImpl wb; - ClassificationImpl classification; - TaskImpl task; - Task resultTask; - final int sleepTime = 100; + @Test + void shouldTransferTaskToOtherWorkbasket() + throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + ClassificationAlreadyExistException, TaskNotFoundException, InterruptedException, + TaskAlreadyExistException, InvalidWorkbasketException, InvalidArgumentException, + WorkbasketAlreadyExistException, DomainNotFoundException, InvalidStateException { + Workbasket sourceWB; + Workbasket destinationWB; + WorkbasketImpl wb; + ClassificationImpl classification; + TaskImpl task; + Task resultTask; + final int sleepTime = 100; - // Source Workbasket - wb = (WorkbasketImpl) workbasketService.newWorkbasket("key1", "DOMAIN_A"); - wb.setName("Basic-Workbasket"); - wb.setDescription("Just used as base WB for Task here"); - wb.setType(WorkbasketType.GROUP); - wb.setOwner("The Tester ID"); - sourceWB = workbasketService.createWorkbasket(wb); + // Source Workbasket + wb = (WorkbasketImpl) workbasketService.newWorkbasket("key1", "DOMAIN_A"); + wb.setName("Basic-Workbasket"); + wb.setDescription("Just used as base WB for Task here"); + wb.setType(WorkbasketType.GROUP); + wb.setOwner("The Tester ID"); + sourceWB = workbasketService.createWorkbasket(wb); - // Destination Workbasket - wb = (WorkbasketImpl) workbasketService.newWorkbasket("k1", "DOMAIN_A"); - wb.setName("Desination-WorkBasket"); + // Destination Workbasket + wb = (WorkbasketImpl) workbasketService.newWorkbasket("k1", "DOMAIN_A"); + wb.setName("Desination-WorkBasket"); - wb.setType(WorkbasketType.CLEARANCE); - wb.setDescription("Destination WB where Task should be transfered to"); - wb.setOwner("The Tester ID"); - destinationWB = workbasketService.createWorkbasket(wb); + wb.setType(WorkbasketType.CLEARANCE); + wb.setDescription("Destination WB where Task should be transfered to"); + wb.setOwner("The Tester ID"); + destinationWB = workbasketService.createWorkbasket(wb); - // Classification required for Task - classification = (ClassificationImpl) classificationService.newClassification("KEY", "DOMAIN_A", "TASK"); - classification.setCategory("EXTERNAL"); - classification.setName("Transfert-Task Classification"); - classificationService.createClassification(classification); + // Classification required for Task + classification = + (ClassificationImpl) classificationService.newClassification("KEY", "DOMAIN_A", "TASK"); + classification.setCategory("EXTERNAL"); + classification.setName("Transfert-Task Classification"); + classificationService.createClassification(classification); - // Task which should be transfered - task = (TaskImpl) taskServiceImpl.newTask(sourceWB.getId()); - task.setName("Task Name"); - task.setDescription("Task used for transfer Test"); - task.setRead(true); - task.setTransferred(false); - task.setModified(null); - task.setClassificationKey(classification.getKey()); - task.setPrimaryObjRef(JunitHelper.createDefaultObjRef()); - task = (TaskImpl) taskServiceImpl.createTask(task); - Thread.sleep(sleepTime); // Sleep for modification-timestamp + // Task which should be transfered + task = (TaskImpl) taskServiceImpl.newTask(sourceWB.getId()); + task.setName("Task Name"); + task.setDescription("Task used for transfer Test"); + task.setRead(true); + task.setTransferred(false); + task.setModified(null); + task.setClassificationKey(classification.getKey()); + task.setPrimaryObjRef(JunitHelper.createDefaultObjRef()); + task = (TaskImpl) taskServiceImpl.createTask(task); + Thread.sleep(sleepTime); // Sleep for modification-timestamp - resultTask = taskServiceImpl.transfer(task.getId(), destinationWB.getId()); - assertThat(resultTask.isRead(), equalTo(false)); - assertThat(resultTask.isTransferred(), equalTo(true)); - assertThat(resultTask.getWorkbasketSummary().getId(), equalTo(destinationWB.getId())); - assertThat(resultTask.getModified(), not(equalTo(null))); - assertThat(resultTask.getModified(), not(equalTo(task.getModified()))); - assertThat(resultTask.getCreated(), not(equalTo(null))); - assertThat(resultTask.getCreated(), equalTo(task.getCreated())); - } + resultTask = taskServiceImpl.transfer(task.getId(), destinationWB.getId()); + assertThat(resultTask.isRead(), equalTo(false)); + assertThat(resultTask.isTransferred(), equalTo(true)); + assertThat(resultTask.getWorkbasketSummary().getId(), equalTo(destinationWB.getId())); + assertThat(resultTask.getModified(), not(equalTo(null))); + assertThat(resultTask.getModified(), not(equalTo(task.getModified()))); + assertThat(resultTask.getCreated(), not(equalTo(null))); + assertThat(resultTask.getCreated(), equalTo(task.getCreated())); + } - @Test - void shouldNotTransferAnyTask() { + @Test + void shouldNotTransferAnyTask() { - Assertions.assertThrows(TaskNotFoundException.class, () -> - taskServiceImpl.transfer(UUID.randomUUID() + "_X", "1")); - } + Assertions.assertThrows( + TaskNotFoundException.class, () -> taskServiceImpl.transfer(UUID.randomUUID() + "_X", "1")); + } - @WithAccessId(userName = "User", groupNames = {"businessadmin"}) - @Test - void shouldNotTransferByFailingSecurity() throws WorkbasketNotFoundException, - ClassificationNotFoundException, NotAuthorizedException, ClassificationAlreadyExistException, SQLException, - TaskAlreadyExistException, InvalidWorkbasketException, InvalidArgumentException, - WorkbasketAlreadyExistException, DomainNotFoundException { - final String user = CurrentUserContext.getUserid(); + @WithAccessId( + userName = "User", + groupNames = {"businessadmin"}) + @Test + void shouldNotTransferByFailingSecurity() + throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + ClassificationAlreadyExistException, SQLException, TaskAlreadyExistException, + InvalidWorkbasketException, InvalidArgumentException, WorkbasketAlreadyExistException, + DomainNotFoundException { + final String user = CurrentUserContext.getUserid(); - // Set up Security for this Test - dataSource = TaskanaEngineTestConfiguration.getDataSource(); - taskanaEngineConfiguration = new TaskanaEngineConfiguration(dataSource, false, true, - TaskanaEngineTestConfiguration.getSchemaName()); - taskanaEngine = taskanaEngineConfiguration.buildTaskanaEngine(); - taskanaEngineImpl = (TaskanaEngineImpl) taskanaEngine; - taskanaEngineImpl.setConnectionManagementMode(ConnectionManagementMode.AUTOCOMMIT); - taskServiceImpl = (TaskServiceImpl) taskanaEngine.getTaskService(); - classificationService = taskanaEngine.getClassificationService(); - workbasketService = taskanaEngine.getWorkbasketService(); + // Set up Security for this Test + dataSource = TaskanaEngineTestConfiguration.getDataSource(); + taskanaEngineConfiguration = + new TaskanaEngineConfiguration( + dataSource, false, true, TaskanaEngineTestConfiguration.getSchemaName()); + taskanaEngine = taskanaEngineConfiguration.buildTaskanaEngine(); + taskanaEngineImpl = (TaskanaEngineImpl) taskanaEngine; + taskanaEngineImpl.setConnectionManagementMode(ConnectionManagementMode.AUTOCOMMIT); + taskServiceImpl = (TaskServiceImpl) taskanaEngine.getTaskService(); + classificationService = taskanaEngine.getClassificationService(); + workbasketService = taskanaEngine.getWorkbasketService(); - ClassificationImpl classification = (ClassificationImpl) classificationService.newClassification("KEY", - "DOMAIN_A", "TASK"); - classification.setCategory("EXTERNAL"); - classification.setName("Transfert-Task Classification"); - classificationService.createClassification(classification); + ClassificationImpl classification = + (ClassificationImpl) classificationService.newClassification("KEY", "DOMAIN_A", "TASK"); + classification.setCategory("EXTERNAL"); + classification.setName("Transfert-Task Classification"); + classificationService.createClassification(classification); - WorkbasketImpl wb = (WorkbasketImpl) workbasketService.newWorkbasket("k5", "DOMAIN_A"); - wb.setName("BASE WB"); - wb.setDescription("Normal base WB"); - wb.setOwner(user); - wb.setType(WorkbasketType.TOPIC); - WorkbasketImpl wbCreated = (WorkbasketImpl) workbasketService.createWorkbasket(wb); - createWorkbasketWithSecurity(wbCreated, wbCreated.getOwner(), true, true, true, true); + WorkbasketImpl wb = (WorkbasketImpl) workbasketService.newWorkbasket("k5", "DOMAIN_A"); + wb.setName("BASE WB"); + wb.setDescription("Normal base WB"); + wb.setOwner(user); + wb.setType(WorkbasketType.TOPIC); + WorkbasketImpl wbCreated = (WorkbasketImpl) workbasketService.createWorkbasket(wb); + createWorkbasketWithSecurity(wbCreated, wbCreated.getOwner(), true, true, true, true); - WorkbasketImpl wbNoAppend = (WorkbasketImpl) workbasketService.newWorkbasket("key77", "DOMAIN_A"); - wbNoAppend.setName("Test-Security-WorkBasket-APPEND"); - wbNoAppend.setDescription("Workbasket without permission APPEND on Task"); - wbNoAppend.setOwner(user); - wbNoAppend.setType(WorkbasketType.PERSONAL); + WorkbasketImpl wbNoAppend = + (WorkbasketImpl) workbasketService.newWorkbasket("key77", "DOMAIN_A"); + wbNoAppend.setName("Test-Security-WorkBasket-APPEND"); + wbNoAppend.setDescription("Workbasket without permission APPEND on Task"); + wbNoAppend.setOwner(user); + wbNoAppend.setType(WorkbasketType.PERSONAL); - WorkbasketImpl wbNoAppendCreated = (WorkbasketImpl) workbasketService.createWorkbasket(wbNoAppend); - createWorkbasketWithSecurity(wbNoAppendCreated, wbNoAppendCreated.getOwner(), true, true, false, true); + WorkbasketImpl wbNoAppendCreated = + (WorkbasketImpl) workbasketService.createWorkbasket(wbNoAppend); + createWorkbasketWithSecurity( + wbNoAppendCreated, wbNoAppendCreated.getOwner(), true, true, false, true); - WorkbasketImpl wbNoTransfer = (WorkbasketImpl) workbasketService.newWorkbasket("k99", "DOMAIN_B"); - wbNoTransfer.setName("Test-Security-WorkBasket-TRANSFER"); - wbNoTransfer.setDescription("Workbasket without permission TRANSFER on Task"); - wbNoTransfer.setOwner(user); - wbNoTransfer.setType(WorkbasketType.CLEARANCE); + WorkbasketImpl wbNoTransfer = + (WorkbasketImpl) workbasketService.newWorkbasket("k99", "DOMAIN_B"); + wbNoTransfer.setName("Test-Security-WorkBasket-TRANSFER"); + wbNoTransfer.setDescription("Workbasket without permission TRANSFER on Task"); + wbNoTransfer.setOwner(user); + wbNoTransfer.setType(WorkbasketType.CLEARANCE); - wbNoTransfer = (WorkbasketImpl) workbasketService.createWorkbasket(wbNoTransfer); - createWorkbasketWithSecurity(wbNoTransfer, wbNoTransfer.getOwner(), true, true, true, false); + wbNoTransfer = (WorkbasketImpl) workbasketService.createWorkbasket(wbNoTransfer); + createWorkbasketWithSecurity(wbNoTransfer, wbNoTransfer.getOwner(), true, true, true, false); - TaskImpl task = (TaskImpl) taskServiceImpl.newTask(wbCreated.getId()); - task.setName("Task Name"); - task.setDescription("Task used for transfer Test"); - task.setOwner(user); - task.setClassificationKey(classification.getKey()); - task.setPrimaryObjRef(JunitHelper.createDefaultObjRef()); - TaskImpl taskCreated = (TaskImpl) taskServiceImpl.createTask(task); + TaskImpl task = (TaskImpl) taskServiceImpl.newTask(wbCreated.getId()); + task.setName("Task Name"); + task.setDescription("Task used for transfer Test"); + task.setOwner(user); + task.setClassificationKey(classification.getKey()); + task.setPrimaryObjRef(JunitHelper.createDefaultObjRef()); + TaskImpl taskCreated = (TaskImpl) taskServiceImpl.createTask(task); - // Check failing with missing APPEND - NotAuthorizedException e = Assertions.assertThrows(NotAuthorizedException.class, () -> - taskServiceImpl.transfer(taskCreated.getId(), wbNoAppendCreated.getId()), + // Check failing with missing APPEND + NotAuthorizedException e = + Assertions.assertThrows( + NotAuthorizedException.class, + () -> taskServiceImpl.transfer(taskCreated.getId(), wbNoAppendCreated.getId()), "Transfer Task should be FAILD, because there are no APPEND-Rights on destination WB."); - Assertions.assertTrue(e.getMessage().contains("APPEND"), - "Transfer Task should be FAILD, because there are no APPEND-Rights on destination WB."); - assertThat(taskCreated.isTransferred(), equalTo(false)); - assertThat(taskCreated.getWorkbasketKey(), not(equalTo(wbNoAppendCreated.getKey()))); - assertThat(taskCreated.getWorkbasketKey(), equalTo(wbCreated.getKey())); + Assertions.assertTrue( + e.getMessage().contains("APPEND"), + "Transfer Task should be FAILD, because there are no APPEND-Rights on destination WB."); + assertThat(taskCreated.isTransferred(), equalTo(false)); + assertThat(taskCreated.getWorkbasketKey(), not(equalTo(wbNoAppendCreated.getKey()))); + assertThat(taskCreated.getWorkbasketKey(), equalTo(wbCreated.getKey())); - // Check failing with missing TRANSFER - taskCreated.setId(""); - taskCreated.getWorkbasketSummaryImpl().setId(wbNoTransfer.getId()); - taskCreated.setWorkbasketKey(null); - taskCreated.setExternalId(IdGenerator.generateWithPrefix("TST")); + // Check failing with missing TRANSFER + taskCreated.setId(""); + taskCreated.getWorkbasketSummaryImpl().setId(wbNoTransfer.getId()); + taskCreated.setWorkbasketKey(null); + taskCreated.setExternalId(IdGenerator.generateWithPrefix("TST")); - TaskImpl taskCreated2 = (TaskImpl) taskServiceImpl.createTask(taskCreated); + TaskImpl taskCreated2 = (TaskImpl) taskServiceImpl.createTask(taskCreated); - e = Assertions.assertThrows(NotAuthorizedException.class, () -> - taskServiceImpl.transfer(taskCreated2.getId(), wbCreated.getId()), + e = + Assertions.assertThrows( + NotAuthorizedException.class, + () -> taskServiceImpl.transfer(taskCreated2.getId(), wbCreated.getId()), "Transfer Task should be FAILED, because there are no TRANSFER-Rights on current WB."); - Assertions.assertTrue(e.getMessage().contains("TRANSFER"), - "Transfer Task should be FAILED, because there are no APPEND-Rights on current WB."); + Assertions.assertTrue( + e.getMessage().contains("TRANSFER"), + "Transfer Task should be FAILED, because there are no APPEND-Rights on current WB."); - assertThat(taskCreated2.isTransferred(), equalTo(false)); - assertThat(taskCreated2.getWorkbasketKey(), not(equalTo(wbNoAppendCreated.getKey()))); - } + assertThat(taskCreated2.isTransferred(), equalTo(false)); + assertThat(taskCreated2.getWorkbasketKey(), not(equalTo(wbNoAppendCreated.getKey()))); + } - @Test - void testWithPrimaryObjectRef() throws TaskNotFoundException, - WorkbasketNotFoundException, NotAuthorizedException, ClassificationNotFoundException, - ClassificationAlreadyExistException, TaskAlreadyExistException, InvalidWorkbasketException, - InvalidArgumentException, WorkbasketAlreadyExistException, DomainNotFoundException { - Workbasket wb = workbasketService.newWorkbasket("workbasket", "DOMAIN_A"); - wb.setName("workbasket"); - wb.setType(WorkbasketType.GROUP); - taskanaEngine.getWorkbasketService().createWorkbasket(wb); - Classification classification = classificationService.newClassification("TEST", "DOMAIN_A", "TASK"); - taskanaEngine.getClassificationService().createClassification(classification); + @Test + void testWithPrimaryObjectRef() + throws TaskNotFoundException, WorkbasketNotFoundException, NotAuthorizedException, + ClassificationNotFoundException, ClassificationAlreadyExistException, + TaskAlreadyExistException, InvalidWorkbasketException, InvalidArgumentException, + WorkbasketAlreadyExistException, DomainNotFoundException { + Workbasket wb = workbasketService.newWorkbasket("workbasket", "DOMAIN_A"); + wb.setName("workbasket"); + wb.setType(WorkbasketType.GROUP); + taskanaEngine.getWorkbasketService().createWorkbasket(wb); + Classification classification = + classificationService.newClassification("TEST", "DOMAIN_A", "TASK"); + taskanaEngine.getClassificationService().createClassification(classification); - Task task = taskServiceImpl.newTask(wb.getId()); - task.setName("Unit Test Task"); + Task task = taskServiceImpl.newTask(wb.getId()); + task.setName("Unit Test Task"); - task.setClassificationKey(classification.getKey()); + task.setClassificationKey(classification.getKey()); - ObjectReference objRef = new ObjectReference(); - objRef.setCompany("novatec"); - objRef.setSystem("linux"); - objRef.setSystemInstance("inst1"); - objRef.setType("fast"); - objRef.setValue("4711"); - task.setPrimaryObjRef(objRef); + ObjectReference objRef = new ObjectReference(); + objRef.setCompany("novatec"); + objRef.setSystem("linux"); + objRef.setSystemInstance("inst1"); + objRef.setType("fast"); + objRef.setValue("4711"); + task.setPrimaryObjRef(objRef); - task = taskServiceImpl.createTask(task); + task = taskServiceImpl.createTask(task); - Task task2 = taskServiceImpl.getTask(task.getId()); - // skanaEngineImpl.getSqlSession().commit(); // needed so that the change is visible in the other session + Task task2 = taskServiceImpl.getTask(task.getId()); + // skanaEngineImpl.getSqlSession().commit(); // needed so that the change is visible in the + // other session - assertNotNull(task2); - } - - private void createWorkbasketWithSecurity(Workbasket wb, String accessId, boolean permOpen, - boolean permRead, boolean permAppend, boolean permTransfer) - throws InvalidArgumentException, NotAuthorizedException, WorkbasketNotFoundException { - WorkbasketAccessItem accessItem = workbasketService.newWorkbasketAccessItem(wb.getId(), accessId); - accessItem.setPermOpen(permOpen); - accessItem.setPermRead(permRead); - accessItem.setPermAppend(permAppend); - accessItem.setPermTransfer(permTransfer); - workbasketService.createWorkbasketAccessItem(accessItem); - } + assertNotNull(task2); + } + private void createWorkbasketWithSecurity( + Workbasket wb, + String accessId, + boolean permOpen, + boolean permRead, + boolean permAppend, + boolean permTransfer) + throws InvalidArgumentException, NotAuthorizedException, WorkbasketNotFoundException { + WorkbasketAccessItem accessItem = + workbasketService.newWorkbasketAccessItem(wb.getId(), accessId); + accessItem.setPermOpen(permOpen); + accessItem.setPermRead(permRead); + accessItem.setPermAppend(permAppend); + accessItem.setPermTransfer(permTransfer); + workbasketService.createWorkbasketAccessItem(accessItem); + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/integration/TaskServiceImplIntExplicitTest.java b/lib/taskana-core/src/test/java/pro/taskana/impl/integration/TaskServiceImplIntExplicitTest.java index 11d02facc..6d1297015 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/integration/TaskServiceImplIntExplicitTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/integration/TaskServiceImplIntExplicitTest.java @@ -12,9 +12,7 @@ import java.sql.Connection; import java.sql.SQLException; import java.util.List; import java.util.UUID; - import javax.sql.DataSource; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -70,190 +68,210 @@ import pro.taskana.security.WithAccessId; @ExtendWith(JAASExtension.class) class TaskServiceImplIntExplicitTest { - private static DataSource dataSource; + private static DataSource dataSource; - private static TaskServiceImpl taskServiceImpl; + private static TaskServiceImpl taskServiceImpl; - private static TaskanaEngineConfiguration taskanaEngineConfiguration; + private static TaskanaEngineConfiguration taskanaEngineConfiguration; - private static TaskanaEngine taskanaEngine; + private static TaskanaEngine taskanaEngine; - private static TaskanaEngineImpl taskanaEngineImpl; + private static TaskanaEngineImpl taskanaEngineImpl; - private static ClassificationService classificationService; + private static ClassificationService classificationService; - private static WorkbasketService workbasketService; + private static WorkbasketService workbasketService; - @BeforeAll - static void setup() throws SQLException { - String userHomeDirectory = System.getProperty("user.home"); - String propertiesFileName = userHomeDirectory + "/taskanaUnitTest.properties"; + @BeforeAll + static void setup() throws SQLException { + String userHomeDirectory = System.getProperty("user.home"); + String propertiesFileName = userHomeDirectory + "/taskanaUnitTest.properties"; - dataSource = new File(propertiesFileName).exists() + dataSource = + new File(propertiesFileName).exists() ? TaskanaEngineTestConfiguration.createDataSourceFromProperties(propertiesFileName) : TaskanaEngineConfiguration.createDefaultDataSource(); - taskanaEngineConfiguration = new TaskanaEngineConfiguration(dataSource, false, - TaskanaEngineTestConfiguration.getSchemaName()); - taskanaEngine = taskanaEngineConfiguration.buildTaskanaEngine(); - taskServiceImpl = (TaskServiceImpl) taskanaEngine.getTaskService(); - taskanaEngineImpl = (TaskanaEngineImpl) taskanaEngine; - classificationService = taskanaEngine.getClassificationService(); - taskanaEngineImpl.setConnectionManagementMode(ConnectionManagementMode.EXPLICIT); - workbasketService = taskanaEngine.getWorkbasketService(); - DbSchemaCreator creator = new DbSchemaCreator(dataSource, dataSource.getConnection().getSchema()); - creator.run(); - } + taskanaEngineConfiguration = + new TaskanaEngineConfiguration( + dataSource, false, TaskanaEngineTestConfiguration.getSchemaName()); + taskanaEngine = taskanaEngineConfiguration.buildTaskanaEngine(); + taskServiceImpl = (TaskServiceImpl) taskanaEngine.getTaskService(); + taskanaEngineImpl = (TaskanaEngineImpl) taskanaEngine; + classificationService = taskanaEngine.getClassificationService(); + taskanaEngineImpl.setConnectionManagementMode(ConnectionManagementMode.EXPLICIT); + workbasketService = taskanaEngine.getWorkbasketService(); + DbSchemaCreator creator = + new DbSchemaCreator(dataSource, dataSource.getConnection().getSchema()); + creator.run(); + } - @BeforeEach - void resetDb() { - String schemaName = TaskanaEngineTestConfiguration.getSchemaName(); - SampleDataGenerator sampleDataGenerator = new SampleDataGenerator(dataSource, schemaName); - sampleDataGenerator.clearDb(); - } + @BeforeEach + void resetDb() { + String schemaName = TaskanaEngineTestConfiguration.getSchemaName(); + SampleDataGenerator sampleDataGenerator = new SampleDataGenerator(dataSource, schemaName); + sampleDataGenerator.clearDb(); + } - @WithAccessId(userName = "Elena", groupNames = {"businessadmin"}) - @Test - void testStartTransactionFail() - throws SQLException, TaskNotFoundException, NotAuthorizedException, WorkbasketNotFoundException, - ClassificationNotFoundException, ClassificationAlreadyExistException, - TaskAlreadyExistException, InvalidWorkbasketException, InvalidArgumentException, - WorkbasketAlreadyExistException, DomainNotFoundException { - Connection connection = dataSource.getConnection(); - taskanaEngineImpl.setConnection(connection); + @WithAccessId( + userName = "Elena", + groupNames = {"businessadmin"}) + @Test + void testStartTransactionFail() + throws SQLException, TaskNotFoundException, NotAuthorizedException, + WorkbasketNotFoundException, ClassificationNotFoundException, + ClassificationAlreadyExistException, TaskAlreadyExistException, + InvalidWorkbasketException, InvalidArgumentException, WorkbasketAlreadyExistException, + DomainNotFoundException { + Connection connection = dataSource.getConnection(); + taskanaEngineImpl.setConnection(connection); - WorkbasketImpl workbasket = (WorkbasketImpl) workbasketService.newWorkbasket("k1", "DOMAIN_A"); - workbasket.setName("workbasket"); - workbasket.setId("1"); // set id manually for authorization tests + WorkbasketImpl workbasket = (WorkbasketImpl) workbasketService.newWorkbasket("k1", "DOMAIN_A"); + workbasket.setName("workbasket"); + workbasket.setId("1"); // set id manually for authorization tests - workbasket.setType(WorkbasketType.GROUP); - Classification classification = classificationService.newClassification("TEST", "DOMAIN_A", "TASK"); - taskanaEngineImpl.getWorkbasketService().createWorkbasket(workbasket); + workbasket.setType(WorkbasketType.GROUP); + Classification classification = + classificationService.newClassification("TEST", "DOMAIN_A", "TASK"); + taskanaEngineImpl.getWorkbasketService().createWorkbasket(workbasket); - WorkbasketAccessItem accessItem = workbasketService.newWorkbasketAccessItem("1", "Elena"); - accessItem.setPermAppend(true); - accessItem.setPermRead(true); - accessItem.setPermOpen(true); - workbasketService.createWorkbasketAccessItem(accessItem); + WorkbasketAccessItem accessItem = workbasketService.newWorkbasketAccessItem("1", "Elena"); + accessItem.setPermAppend(true); + accessItem.setPermRead(true); + accessItem.setPermOpen(true); + workbasketService.createWorkbasketAccessItem(accessItem); - taskanaEngineImpl.getClassificationService().createClassification(classification); - connection.commit(); - Task task = taskServiceImpl.newTask(workbasket.getId()); - task.setName("Unit Test Task"); - task.setClassificationKey(classification.getKey()); - task.setPrimaryObjRef(JunitHelper.createDefaultObjRef()); - task = taskServiceImpl.createTask(task); - connection.commit(); - taskServiceImpl.getTask(task.getId()); + taskanaEngineImpl.getClassificationService().createClassification(classification); + connection.commit(); + Task task = taskServiceImpl.newTask(workbasket.getId()); + task.setName("Unit Test Task"); + task.setClassificationKey(classification.getKey()); + task.setPrimaryObjRef(JunitHelper.createDefaultObjRef()); + task = taskServiceImpl.createTask(task); + connection.commit(); + taskServiceImpl.getTask(task.getId()); - TaskanaEngineImpl te2 = (TaskanaEngineImpl) taskanaEngineConfiguration.buildTaskanaEngine(); - TaskServiceImpl taskServiceImpl2 = (TaskServiceImpl) te2.getTaskService(); - Assertions.assertThrows(TaskNotFoundException.class, () -> - taskServiceImpl2.getTask(workbasket.getId())); - connection.commit(); - } + TaskanaEngineImpl te2 = (TaskanaEngineImpl) taskanaEngineConfiguration.buildTaskanaEngine(); + TaskServiceImpl taskServiceImpl2 = (TaskServiceImpl) te2.getTaskService(); + Assertions.assertThrows( + TaskNotFoundException.class, () -> taskServiceImpl2.getTask(workbasket.getId())); + connection.commit(); + } - @WithAccessId(userName = "Elena", groupNames = {"businessadmin"}) - @Test - void testCreateTask() - throws SQLException, TaskNotFoundException, NotAuthorizedException, - WorkbasketNotFoundException, ClassificationNotFoundException, ClassificationAlreadyExistException, - TaskAlreadyExistException, InvalidWorkbasketException, InvalidArgumentException, - WorkbasketAlreadyExistException, DomainNotFoundException { - Connection connection = dataSource.getConnection(); - taskanaEngineImpl.setConnection(connection); + @WithAccessId( + userName = "Elena", + groupNames = {"businessadmin"}) + @Test + void testCreateTask() + throws SQLException, TaskNotFoundException, NotAuthorizedException, + WorkbasketNotFoundException, ClassificationNotFoundException, + ClassificationAlreadyExistException, TaskAlreadyExistException, + InvalidWorkbasketException, InvalidArgumentException, WorkbasketAlreadyExistException, + DomainNotFoundException { + Connection connection = dataSource.getConnection(); + taskanaEngineImpl.setConnection(connection); - Task task = this.generateDummyTask(); - connection.commit(); + Task task = this.generateDummyTask(); + connection.commit(); - WorkbasketAccessItem accessItem = workbasketService.newWorkbasketAccessItem("1", "Elena"); - accessItem.setPermAppend(true); - accessItem.setPermRead(true); - accessItem.setPermOpen(true); - workbasketService.createWorkbasketAccessItem(accessItem); + WorkbasketAccessItem accessItem = workbasketService.newWorkbasketAccessItem("1", "Elena"); + accessItem.setPermAppend(true); + accessItem.setPermRead(true); + accessItem.setPermOpen(true); + workbasketService.createWorkbasketAccessItem(accessItem); - task.setPrimaryObjRef(JunitHelper.createDefaultObjRef()); - task = taskServiceImpl.createTask(task); - connection.commit(); // needed so that the change is visible in the other session + task.setPrimaryObjRef(JunitHelper.createDefaultObjRef()); + task = taskServiceImpl.createTask(task); + connection.commit(); // needed so that the change is visible in the other session - TaskanaEngine te2 = taskanaEngineConfiguration.buildTaskanaEngine(); - TaskServiceImpl taskServiceImpl2 = (TaskServiceImpl) te2.getTaskService(); - Task resultTask = taskServiceImpl2.getTask(task.getId()); - assertNotNull(resultTask); - connection.commit(); - } + TaskanaEngine te2 = taskanaEngineConfiguration.buildTaskanaEngine(); + TaskServiceImpl taskServiceImpl2 = (TaskServiceImpl) te2.getTaskService(); + Task resultTask = taskServiceImpl2.getTask(task.getId()); + assertNotNull(resultTask); + connection.commit(); + } - @WithAccessId(userName = "Elena", groupNames = {"businessadmin"}) - @Test - void createTaskShouldThrowWorkbasketNotFoundException() - throws NotAuthorizedException, SQLException, - ClassificationAlreadyExistException, InvalidWorkbasketException, - InvalidArgumentException, WorkbasketAlreadyExistException, DomainNotFoundException { - Connection connection = dataSource.getConnection(); - taskanaEngineImpl.setConnection(connection); - Task test = this.generateDummyTask(); - ((WorkbasketSummaryImpl) (test.getWorkbasketSummary())).setId("2"); + @WithAccessId( + userName = "Elena", + groupNames = {"businessadmin"}) + @Test + void createTaskShouldThrowWorkbasketNotFoundException() + throws NotAuthorizedException, SQLException, ClassificationAlreadyExistException, + InvalidWorkbasketException, InvalidArgumentException, WorkbasketAlreadyExistException, + DomainNotFoundException { + Connection connection = dataSource.getConnection(); + taskanaEngineImpl.setConnection(connection); + Task test = this.generateDummyTask(); + ((WorkbasketSummaryImpl) (test.getWorkbasketSummary())).setId("2"); - Assertions.assertThrows(WorkbasketNotFoundException.class, () -> - taskServiceImpl.createTask(test)); - } + Assertions.assertThrows( + WorkbasketNotFoundException.class, () -> taskServiceImpl.createTask(test)); + } - @WithAccessId(userName = "Elena", groupNames = {"businessadmin"}) - @Test - void createManualTaskShouldThrowClassificationNotFoundException() - throws NotAuthorizedException, WorkbasketNotFoundException, SQLException, - ClassificationAlreadyExistException, InvalidWorkbasketException, - InvalidArgumentException, WorkbasketAlreadyExistException, DomainNotFoundException { - Connection connection = dataSource.getConnection(); - taskanaEngineImpl.setConnection(connection); + @WithAccessId( + userName = "Elena", + groupNames = {"businessadmin"}) + @Test + void createManualTaskShouldThrowClassificationNotFoundException() + throws NotAuthorizedException, WorkbasketNotFoundException, SQLException, + ClassificationAlreadyExistException, InvalidWorkbasketException, InvalidArgumentException, + WorkbasketAlreadyExistException, DomainNotFoundException { + Connection connection = dataSource.getConnection(); + taskanaEngineImpl.setConnection(connection); - Workbasket wb = workbasketService.newWorkbasket("WB NR.1", "DOMAIN_A"); - wb.setName("dummy-WB"); - wb.setType(WorkbasketType.PERSONAL); - wb = workbasketService.createWorkbasket(wb); - this.createWorkbasketWithSecurity(wb, CurrentUserContext.getUserid(), true, true, - true, false); - Classification classification = classificationService.newClassification( + Workbasket wb = workbasketService.newWorkbasket("WB NR.1", "DOMAIN_A"); + wb.setName("dummy-WB"); + wb.setType(WorkbasketType.PERSONAL); + wb = workbasketService.createWorkbasket(wb); + this.createWorkbasketWithSecurity(wb, CurrentUserContext.getUserid(), true, true, true, false); + Classification classification = + classificationService.newClassification( UUID.randomUUID().toString(), wb.getDomain(), "t1"); // not persisted, - // not found. - classification.setName("not persisted - so not found."); + // not found. + classification.setName("not persisted - so not found."); - Task task = this.generateDummyTask(); - ((TaskImpl) task).setWorkbasketSummary(wb.asSummary()); - task.setClassificationKey(classification.getKey()); + Task task = this.generateDummyTask(); + ((TaskImpl) task).setWorkbasketSummary(wb.asSummary()); + task.setClassificationKey(classification.getKey()); - Assertions.assertThrows(ClassificationNotFoundException.class, () -> - taskServiceImpl.createTask(task)); - } + Assertions.assertThrows( + ClassificationNotFoundException.class, () -> taskServiceImpl.createTask(task)); + } - @WithAccessId(userName = "Elena", groupNames = {"DummyGroup", "businessadmin"}) - @Test - void should_ReturnList_when_BuilderIsUsed() throws SQLException, NotAuthorizedException, - WorkbasketNotFoundException, ClassificationNotFoundException, ClassificationAlreadyExistException, - TaskAlreadyExistException, InvalidWorkbasketException, InvalidArgumentException, SystemException, - WorkbasketAlreadyExistException, DomainNotFoundException { - Connection connection = dataSource.getConnection(); - taskanaEngineImpl.setConnection(connection); - WorkbasketImpl workbasket = (WorkbasketImpl) workbasketService.newWorkbasket("k1", "DOMAIN_A"); - workbasket.setName("workbasket"); - Classification classification = classificationService.newClassification("TEST", "DOMAIN_A", "TASK"); - classificationService.createClassification(classification); - workbasket.setId("1"); // set id manually for authorization tests - workbasket.setType(WorkbasketType.GROUP); - workbasket = (WorkbasketImpl) workbasketService.createWorkbasket(workbasket); + @WithAccessId( + userName = "Elena", + groupNames = {"DummyGroup", "businessadmin"}) + @Test + void should_ReturnList_when_BuilderIsUsed() + throws SQLException, NotAuthorizedException, WorkbasketNotFoundException, + ClassificationNotFoundException, ClassificationAlreadyExistException, + TaskAlreadyExistException, InvalidWorkbasketException, InvalidArgumentException, + SystemException, WorkbasketAlreadyExistException, DomainNotFoundException { + Connection connection = dataSource.getConnection(); + taskanaEngineImpl.setConnection(connection); + WorkbasketImpl workbasket = (WorkbasketImpl) workbasketService.newWorkbasket("k1", "DOMAIN_A"); + workbasket.setName("workbasket"); + Classification classification = + classificationService.newClassification("TEST", "DOMAIN_A", "TASK"); + classificationService.createClassification(classification); + workbasket.setId("1"); // set id manually for authorization tests + workbasket.setType(WorkbasketType.GROUP); + workbasket = (WorkbasketImpl) workbasketService.createWorkbasket(workbasket); - WorkbasketAccessItem accessItem = workbasketService.newWorkbasketAccessItem("1", "Elena"); - accessItem.setPermAppend(true); - accessItem.setPermRead(true); - accessItem.setPermOpen(true); - workbasketService.createWorkbasketAccessItem(accessItem); + WorkbasketAccessItem accessItem = workbasketService.newWorkbasketAccessItem("1", "Elena"); + accessItem.setPermAppend(true); + accessItem.setPermRead(true); + accessItem.setPermOpen(true); + workbasketService.createWorkbasketAccessItem(accessItem); - Task task = taskServiceImpl.newTask(workbasket.getId()); - task.setName("Unit Test Task"); - task.setClassificationKey(classification.getKey()); - task.setPrimaryObjRef(JunitHelper.createDefaultObjRef()); - taskServiceImpl.createTask(task); + Task task = taskServiceImpl.newTask(workbasket.getId()); + task.setName("Unit Test Task"); + task.setClassificationKey(classification.getKey()); + task.setPrimaryObjRef(JunitHelper.createDefaultObjRef()); + taskServiceImpl.createTask(task); - List results = taskServiceImpl.createTaskQuery() + List results = + taskServiceImpl + .createTaskQuery() .nameIn("bla", "test") .descriptionLike("test") .priorityIn(1, 2, 2) @@ -269,206 +287,231 @@ class TaskServiceImplIntExplicitTest { .primaryObjectReferenceValueIn("val1", "val2", "val3") .list(); - assertEquals(0, results.size()); - connection.commit(); - } + assertEquals(0, results.size()); + connection.commit(); + } - @WithAccessId(userName = "Elena", groupNames = {"businessadmin"}) - @Test - void shouldTransferTaskToOtherWorkbasket() - throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - ClassificationAlreadyExistException, TaskNotFoundException, InterruptedException, TaskAlreadyExistException, - SQLException, InvalidWorkbasketException, InvalidArgumentException, WorkbasketAlreadyExistException, - DomainNotFoundException, InvalidStateException { - Workbasket sourceWB; - Workbasket destinationWB; - WorkbasketImpl wb; - ClassificationImpl classification; - TaskImpl task; - Task resultTask; - final int sleepTime = 100; - final String user = CurrentUserContext.getUserid(); - Connection connection = dataSource.getConnection(); - taskanaEngineImpl.setConnection(connection); + @WithAccessId( + userName = "Elena", + groupNames = {"businessadmin"}) + @Test + void shouldTransferTaskToOtherWorkbasket() + throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + ClassificationAlreadyExistException, TaskNotFoundException, InterruptedException, + TaskAlreadyExistException, SQLException, InvalidWorkbasketException, + InvalidArgumentException, WorkbasketAlreadyExistException, DomainNotFoundException, + InvalidStateException { + Workbasket sourceWB; + Workbasket destinationWB; + WorkbasketImpl wb; + ClassificationImpl classification; + TaskImpl task; + Task resultTask; + final int sleepTime = 100; + final String user = CurrentUserContext.getUserid(); + Connection connection = dataSource.getConnection(); + taskanaEngineImpl.setConnection(connection); - // Source Workbasket - wb = (WorkbasketImpl) workbasketService.newWorkbasket("sourceWbKey", "DOMAIN_A"); - wb.setName("Basic-Workbasket"); - wb.setDescription("Just used as base WB for Task here"); - wb.setOwner(user); - wb.setType(WorkbasketType.PERSONAL); - sourceWB = workbasketService.createWorkbasket(wb); + // Source Workbasket + wb = (WorkbasketImpl) workbasketService.newWorkbasket("sourceWbKey", "DOMAIN_A"); + wb.setName("Basic-Workbasket"); + wb.setDescription("Just used as base WB for Task here"); + wb.setOwner(user); + wb.setType(WorkbasketType.PERSONAL); + sourceWB = workbasketService.createWorkbasket(wb); - createWorkbasketWithSecurity(wb, wb.getOwner(), false, false, false, false); - createWorkbasketWithSecurity(sourceWB, sourceWB.getOwner(), true, true, true, true); + createWorkbasketWithSecurity(wb, wb.getOwner(), false, false, false, false); + createWorkbasketWithSecurity(sourceWB, sourceWB.getOwner(), true, true, true, true); - // Destination Workbasket - wb = (WorkbasketImpl) workbasketService.newWorkbasket("wb2Key", "DOMAIN_A"); - wb.setName("Desination-WorkBasket"); - wb.setDescription("Destination WB where Task should be transfered to"); - wb.setOwner(user); - wb.setType(WorkbasketType.TOPIC); + // Destination Workbasket + wb = (WorkbasketImpl) workbasketService.newWorkbasket("wb2Key", "DOMAIN_A"); + wb.setName("Desination-WorkBasket"); + wb.setDescription("Destination WB where Task should be transfered to"); + wb.setOwner(user); + wb.setType(WorkbasketType.TOPIC); - destinationWB = workbasketService.createWorkbasket(wb); - createWorkbasketWithSecurity(destinationWB, destinationWB.getOwner(), false, true, true, true); + destinationWB = workbasketService.createWorkbasket(wb); + createWorkbasketWithSecurity(destinationWB, destinationWB.getOwner(), false, true, true, true); - // Classification required for Task - classification = (ClassificationImpl) classificationService.newClassification("KEY", "DOMAIN_A", "TASK"); - classification.setCategory("EXTERNAL"); - classification.setName("Transfert-Task Classification"); - classificationService.createClassification(classification); + // Classification required for Task + classification = + (ClassificationImpl) classificationService.newClassification("KEY", "DOMAIN_A", "TASK"); + classification.setCategory("EXTERNAL"); + classification.setName("Transfert-Task Classification"); + classificationService.createClassification(classification); - // Task which should be transfered - task = (TaskImpl) taskServiceImpl.newTask(sourceWB.getId()); - task.setName("Task Name"); - task.setDescription("Task used for transfer Test"); - task.setRead(true); - task.setTransferred(false); - task.setModified(null); - task.setClassificationKey("KEY"); - task.setOwner(user); - task.setPrimaryObjRef(JunitHelper.createDefaultObjRef()); - task = (TaskImpl) taskServiceImpl.createTask(task); - Thread.sleep(sleepTime); // Sleep for modification-timestamp - connection.commit(); + // Task which should be transfered + task = (TaskImpl) taskServiceImpl.newTask(sourceWB.getId()); + task.setName("Task Name"); + task.setDescription("Task used for transfer Test"); + task.setRead(true); + task.setTransferred(false); + task.setModified(null); + task.setClassificationKey("KEY"); + task.setOwner(user); + task.setPrimaryObjRef(JunitHelper.createDefaultObjRef()); + task = (TaskImpl) taskServiceImpl.createTask(task); + Thread.sleep(sleepTime); // Sleep for modification-timestamp + connection.commit(); - resultTask = taskServiceImpl.transfer(task.getId(), destinationWB.getId()); - connection.commit(); - assertThat(resultTask.isRead(), equalTo(false)); - assertThat(resultTask.isTransferred(), equalTo(true)); - assertThat(resultTask.getWorkbasketKey(), equalTo(destinationWB.getKey())); - assertThat(resultTask.getModified(), not(equalTo(null))); - assertThat(resultTask.getModified(), not(equalTo(task.getModified()))); - assertThat(resultTask.getCreated(), not(equalTo(null))); - assertThat(resultTask.getCreated(), equalTo(task.getCreated())); - } + resultTask = taskServiceImpl.transfer(task.getId(), destinationWB.getId()); + connection.commit(); + assertThat(resultTask.isRead(), equalTo(false)); + assertThat(resultTask.isTransferred(), equalTo(true)); + assertThat(resultTask.getWorkbasketKey(), equalTo(destinationWB.getKey())); + assertThat(resultTask.getModified(), not(equalTo(null))); + assertThat(resultTask.getModified(), not(equalTo(task.getModified()))); + assertThat(resultTask.getCreated(), not(equalTo(null))); + assertThat(resultTask.getCreated(), equalTo(task.getCreated())); + } - @Test - void shouldNotTransferAnyTask() - throws SQLException { - Connection connection = dataSource.getConnection(); - taskanaEngineImpl.setConnection(connection); + @Test + void shouldNotTransferAnyTask() throws SQLException { + Connection connection = dataSource.getConnection(); + taskanaEngineImpl.setConnection(connection); - Assertions.assertThrows(TaskNotFoundException.class, () -> - taskServiceImpl.transfer(UUID.randomUUID() + "_X", "1")); - } + Assertions.assertThrows( + TaskNotFoundException.class, () -> taskServiceImpl.transfer(UUID.randomUUID() + "_X", "1")); + } - @WithAccessId(userName = "User", groupNames = {"businessadmin"}) - @Test - void shouldNotTransferByFailingSecurity() throws WorkbasketNotFoundException, - ClassificationNotFoundException, NotAuthorizedException, ClassificationAlreadyExistException, SQLException, - TaskAlreadyExistException, InvalidWorkbasketException, InvalidArgumentException, - WorkbasketAlreadyExistException, DomainNotFoundException { - final String user = "User"; + @WithAccessId( + userName = "User", + groupNames = {"businessadmin"}) + @Test + void shouldNotTransferByFailingSecurity() + throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + ClassificationAlreadyExistException, SQLException, TaskAlreadyExistException, + InvalidWorkbasketException, InvalidArgumentException, WorkbasketAlreadyExistException, + DomainNotFoundException { + final String user = "User"; - // Set up Security for this Test - dataSource = TaskanaEngineTestConfiguration.getDataSource(); - taskanaEngineConfiguration = new TaskanaEngineConfiguration(dataSource, false, true, - TaskanaEngineTestConfiguration.getSchemaName()); - taskanaEngine = taskanaEngineConfiguration.buildTaskanaEngine(); - taskanaEngineImpl = (TaskanaEngineImpl) taskanaEngine; - taskanaEngineImpl.setConnectionManagementMode(ConnectionManagementMode.AUTOCOMMIT); - taskServiceImpl = (TaskServiceImpl) taskanaEngine.getTaskService(); - classificationService = taskanaEngine.getClassificationService(); - workbasketService = taskanaEngine.getWorkbasketService(); + // Set up Security for this Test + dataSource = TaskanaEngineTestConfiguration.getDataSource(); + taskanaEngineConfiguration = + new TaskanaEngineConfiguration( + dataSource, false, true, TaskanaEngineTestConfiguration.getSchemaName()); + taskanaEngine = taskanaEngineConfiguration.buildTaskanaEngine(); + taskanaEngineImpl = (TaskanaEngineImpl) taskanaEngine; + taskanaEngineImpl.setConnectionManagementMode(ConnectionManagementMode.AUTOCOMMIT); + taskServiceImpl = (TaskServiceImpl) taskanaEngine.getTaskService(); + classificationService = taskanaEngine.getClassificationService(); + workbasketService = taskanaEngine.getWorkbasketService(); - ClassificationImpl classification = (ClassificationImpl) classificationService.newClassification( - "KEY", "DOMAIN_A", "TASK"); - classification.setCategory("EXTERNAL"); - classification.setName("Transfert-Task Classification"); - classificationService.createClassification(classification); + ClassificationImpl classification = + (ClassificationImpl) classificationService.newClassification("KEY", "DOMAIN_A", "TASK"); + classification.setCategory("EXTERNAL"); + classification.setName("Transfert-Task Classification"); + classificationService.createClassification(classification); - WorkbasketImpl wb = (WorkbasketImpl) workbasketService.newWorkbasket("wbKey1", "DOMAIN_A"); - wb.setName("BASE WB"); - wb.setDescription("Normal base WB"); - wb.setOwner(user); - wb.setType(WorkbasketType.GROUP); - WorkbasketImpl wbCreated = (WorkbasketImpl) workbasketService.createWorkbasket(wb); - createWorkbasketWithSecurity(wbCreated, wbCreated.getOwner(), true, true, true, true); + WorkbasketImpl wb = (WorkbasketImpl) workbasketService.newWorkbasket("wbKey1", "DOMAIN_A"); + wb.setName("BASE WB"); + wb.setDescription("Normal base WB"); + wb.setOwner(user); + wb.setType(WorkbasketType.GROUP); + WorkbasketImpl wbCreated = (WorkbasketImpl) workbasketService.createWorkbasket(wb); + createWorkbasketWithSecurity(wbCreated, wbCreated.getOwner(), true, true, true, true); - WorkbasketImpl wbNoAppend = (WorkbasketImpl) workbasketService.newWorkbasket("keyNoAppend", "DOMAIN_B"); - wbNoAppend.setName("Test-Security-WorkBasket-APPEND"); - wbNoAppend.setDescription("Workbasket without permission APPEND on Task"); - wbNoAppend.setOwner(user); + WorkbasketImpl wbNoAppend = + (WorkbasketImpl) workbasketService.newWorkbasket("keyNoAppend", "DOMAIN_B"); + wbNoAppend.setName("Test-Security-WorkBasket-APPEND"); + wbNoAppend.setDescription("Workbasket without permission APPEND on Task"); + wbNoAppend.setOwner(user); - wbNoAppend.setType(WorkbasketType.CLEARANCE); - WorkbasketImpl wbNoAppendCreated = (WorkbasketImpl) workbasketService.createWorkbasket(wbNoAppend); - createWorkbasketWithSecurity(wbNoAppendCreated, wbNoAppendCreated.getOwner(), true, true, false, true); + wbNoAppend.setType(WorkbasketType.CLEARANCE); + WorkbasketImpl wbNoAppendCreated = + (WorkbasketImpl) workbasketService.createWorkbasket(wbNoAppend); + createWorkbasketWithSecurity( + wbNoAppendCreated, wbNoAppendCreated.getOwner(), true, true, false, true); - WorkbasketImpl wbNoTransfer = (WorkbasketImpl) workbasketService.newWorkbasket("keyNoTransfer", "DOMAIN_A"); - wbNoTransfer.setName("Test-Security-WorkBasket-TRANSFER"); - wbNoTransfer.setDescription("Workbasket without permission TRANSFER on Task"); - wbNoTransfer.setOwner(user); - wbNoTransfer.setType(WorkbasketType.GROUP); - wbNoTransfer = (WorkbasketImpl) workbasketService.createWorkbasket(wbNoTransfer); - createWorkbasketWithSecurity(wbNoTransfer, wbNoTransfer.getOwner(), true, true, true, false); + WorkbasketImpl wbNoTransfer = + (WorkbasketImpl) workbasketService.newWorkbasket("keyNoTransfer", "DOMAIN_A"); + wbNoTransfer.setName("Test-Security-WorkBasket-TRANSFER"); + wbNoTransfer.setDescription("Workbasket without permission TRANSFER on Task"); + wbNoTransfer.setOwner(user); + wbNoTransfer.setType(WorkbasketType.GROUP); + wbNoTransfer = (WorkbasketImpl) workbasketService.createWorkbasket(wbNoTransfer); + createWorkbasketWithSecurity(wbNoTransfer, wbNoTransfer.getOwner(), true, true, true, false); - TaskImpl task = (TaskImpl) taskServiceImpl.newTask(wbCreated.getId()); - task.setName("Task Name"); - task.setDescription("Task used for transfer Test"); - task.setOwner(user); - task.setClassificationKey(classification.getKey()); - task.setPrimaryObjRef(JunitHelper.createDefaultObjRef()); - TaskImpl taskCreated = (TaskImpl) taskServiceImpl.createTask(task); + TaskImpl task = (TaskImpl) taskServiceImpl.newTask(wbCreated.getId()); + task.setName("Task Name"); + task.setDescription("Task used for transfer Test"); + task.setOwner(user); + task.setClassificationKey(classification.getKey()); + task.setPrimaryObjRef(JunitHelper.createDefaultObjRef()); + TaskImpl taskCreated = (TaskImpl) taskServiceImpl.createTask(task); - // Check failing with missing APPEND - NotAuthorizedException e = Assertions.assertThrows(NotAuthorizedException.class, + // Check failing with missing APPEND + NotAuthorizedException e = + Assertions.assertThrows( + NotAuthorizedException.class, () -> taskServiceImpl.transfer(taskCreated.getId(), wbNoAppendCreated.getId()), "Transfer Task should be FAILED, because there are no APPEND-Rights on destination WB."); - assertTrue(e.getMessage().contains("APPEND"), - "Transfer Task should be FAILED, because there are no APPEND-Rights on destination WB."); + assertTrue( + e.getMessage().contains("APPEND"), + "Transfer Task should be FAILED, because there are no APPEND-Rights on destination WB."); - assertThat(taskCreated.isTransferred(), equalTo(false)); - assertThat(taskCreated.getWorkbasketKey(), not(equalTo(wbNoAppendCreated.getKey()))); - assertThat(taskCreated.getWorkbasketKey(), equalTo(wbCreated.getKey())); + assertThat(taskCreated.isTransferred(), equalTo(false)); + assertThat(taskCreated.getWorkbasketKey(), not(equalTo(wbNoAppendCreated.getKey()))); + assertThat(taskCreated.getWorkbasketKey(), equalTo(wbCreated.getKey())); - // Check failing with missing TRANSFER - taskCreated.setId(""); - taskCreated.setWorkbasketKey(wbNoTransfer.getKey()); - taskCreated.getWorkbasketSummaryImpl().setId(wbNoTransfer.getId()); - taskCreated.setExternalId(IdGenerator.generateWithPrefix("TST")); - TaskImpl taskCreated2 = (TaskImpl) taskServiceImpl.createTask(taskCreated); - e = Assertions.assertThrows(NotAuthorizedException.class, + // Check failing with missing TRANSFER + taskCreated.setId(""); + taskCreated.setWorkbasketKey(wbNoTransfer.getKey()); + taskCreated.getWorkbasketSummaryImpl().setId(wbNoTransfer.getId()); + taskCreated.setExternalId(IdGenerator.generateWithPrefix("TST")); + TaskImpl taskCreated2 = (TaskImpl) taskServiceImpl.createTask(taskCreated); + e = + Assertions.assertThrows( + NotAuthorizedException.class, () -> taskServiceImpl.transfer(taskCreated2.getId(), wbCreated.getId()), "Transfer Task should be FAILED, because there are no TRANSFER-Rights on current WB."); - assertTrue(e.getMessage().contains("TRANSFER"), - "Transfer Task should be FAILED, because there are no APPEND-Rights on current WB."); - assertThat(taskCreated2.isTransferred(), equalTo(false)); - assertThat(taskCreated2.getWorkbasketKey(), not(equalTo(wbNoAppendCreated.getKey()))); - } + assertTrue( + e.getMessage().contains("TRANSFER"), + "Transfer Task should be FAILED, because there are no APPEND-Rights on current WB."); + assertThat(taskCreated2.isTransferred(), equalTo(false)); + assertThat(taskCreated2.getWorkbasketKey(), not(equalTo(wbNoAppendCreated.getKey()))); + } - private Task generateDummyTask() - throws ClassificationAlreadyExistException, InvalidWorkbasketException, NotAuthorizedException, - WorkbasketAlreadyExistException, DomainNotFoundException, InvalidArgumentException { - WorkbasketImpl workbasket = (WorkbasketImpl) workbasketService.newWorkbasket("wb", "DOMAIN_A"); - workbasket.setName("wb"); - workbasket.setId("1"); // set id manually for authorization tests - workbasket.setType(WorkbasketType.GROUP); - taskanaEngine.getWorkbasketService().createWorkbasket(workbasket); + @AfterEach + void cleanUp() throws SQLException { + taskanaEngineImpl.setConnection(null); + } - Classification classification = classificationService.newClassification("TEST", "DOMAIN_A", "TASK"); - taskanaEngine.getClassificationService().createClassification(classification); + private Task generateDummyTask() + throws ClassificationAlreadyExistException, InvalidWorkbasketException, + NotAuthorizedException, WorkbasketAlreadyExistException, DomainNotFoundException, + InvalidArgumentException { + WorkbasketImpl workbasket = (WorkbasketImpl) workbasketService.newWorkbasket("wb", "DOMAIN_A"); + workbasket.setName("wb"); + workbasket.setId("1"); // set id manually for authorization tests + workbasket.setType(WorkbasketType.GROUP); + taskanaEngine.getWorkbasketService().createWorkbasket(workbasket); - Task task = taskServiceImpl.newTask(workbasket.getId()); - task.setClassificationKey(classification.getKey()); - return task; - } + Classification classification = + classificationService.newClassification("TEST", "DOMAIN_A", "TASK"); + taskanaEngine.getClassificationService().createClassification(classification); - private void createWorkbasketWithSecurity(Workbasket wb, String accessId, boolean permOpen, - boolean permRead, boolean permAppend, boolean permTransfer) - throws InvalidArgumentException, NotAuthorizedException, WorkbasketNotFoundException { - WorkbasketAccessItem accessItem = workbasketService.newWorkbasketAccessItem(wb.getId(), accessId); - accessItem.setPermOpen(permOpen); - accessItem.setPermRead(permRead); - accessItem.setPermAppend(permAppend); - accessItem.setPermTransfer(permTransfer); - workbasketService.createWorkbasketAccessItem(accessItem); - } + Task task = taskServiceImpl.newTask(workbasket.getId()); + task.setClassificationKey(classification.getKey()); + return task; + } - @AfterEach - void cleanUp() throws SQLException { - taskanaEngineImpl.setConnection(null); - } + private void createWorkbasketWithSecurity( + Workbasket wb, + String accessId, + boolean permOpen, + boolean permRead, + boolean permAppend, + boolean permTransfer) + throws InvalidArgumentException, NotAuthorizedException, WorkbasketNotFoundException { + WorkbasketAccessItem accessItem = + workbasketService.newWorkbasketAccessItem(wb.getId(), accessId); + accessItem.setPermOpen(permOpen); + accessItem.setPermRead(permRead); + accessItem.setPermAppend(permAppend); + accessItem.setPermTransfer(permTransfer); + workbasketService.createWorkbasketAccessItem(accessItem); + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/integration/WorkbasketServiceImplIntAutocommitTest.java b/lib/taskana-core/src/test/java/pro/taskana/impl/integration/WorkbasketServiceImplIntAutocommitTest.java index 3e3d3693b..e553a1fd9 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/integration/WorkbasketServiceImplIntAutocommitTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/integration/WorkbasketServiceImplIntAutocommitTest.java @@ -13,9 +13,7 @@ import java.time.ZoneId; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import javax.sql.DataSource; - import org.apache.ibatis.session.SqlSession; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -55,185 +53,222 @@ import pro.taskana.security.WithAccessId; @ExtendWith(JAASExtension.class) class WorkbasketServiceImplIntAutocommitTest { - private static final int SLEEP_TIME = 100; - private TaskanaEngine taskanaEngine; - private WorkbasketService workBasketService; - private Instant now; + private static final int SLEEP_TIME = 100; + private TaskanaEngine taskanaEngine; + private WorkbasketService workBasketService; + private Instant now; - @BeforeAll - static void resetDb() { - DataSource ds = TaskanaEngineTestConfiguration.getDataSource(); - String schemaName = TaskanaEngineTestConfiguration.getSchemaName(); - new SampleDataGenerator(ds, schemaName).dropDb(); - } + @BeforeAll + static void resetDb() { + DataSource ds = TaskanaEngineTestConfiguration.getDataSource(); + String schemaName = TaskanaEngineTestConfiguration.getSchemaName(); + new SampleDataGenerator(ds, schemaName).dropDb(); + } - @BeforeEach - void setup() throws SQLException { - DataSource dataSource = TaskanaEngineTestConfiguration.getDataSource(); - String schemaName = TaskanaEngineTestConfiguration.getSchemaName(); - TaskanaEngineConfiguration taskanaEngineConfiguration = new TaskanaEngineConfiguration( - dataSource, false, - schemaName); - taskanaEngine = taskanaEngineConfiguration.buildTaskanaEngine(); - taskanaEngine.setConnectionManagementMode(ConnectionManagementMode.AUTOCOMMIT); - workBasketService = taskanaEngine.getWorkbasketService(); - SampleDataGenerator sampleDataGenerator = new SampleDataGenerator(dataSource, schemaName); - sampleDataGenerator.clearDb(); - now = Instant.now(); - } + @BeforeEach + void setup() throws SQLException { + DataSource dataSource = TaskanaEngineTestConfiguration.getDataSource(); + String schemaName = TaskanaEngineTestConfiguration.getSchemaName(); + TaskanaEngineConfiguration taskanaEngineConfiguration = + new TaskanaEngineConfiguration(dataSource, false, schemaName); + taskanaEngine = taskanaEngineConfiguration.buildTaskanaEngine(); + taskanaEngine.setConnectionManagementMode(ConnectionManagementMode.AUTOCOMMIT); + workBasketService = taskanaEngine.getWorkbasketService(); + SampleDataGenerator sampleDataGenerator = new SampleDataGenerator(dataSource, schemaName); + sampleDataGenerator.clearDb(); + now = Instant.now(); + } - @Test - void testGetWorkbasketFail() { - Assertions.assertThrows(WorkbasketNotFoundException.class, () -> - workBasketService.getWorkbasket("fail")); - } + @Test + void testGetWorkbasketFail() { + Assertions.assertThrows( + WorkbasketNotFoundException.class, () -> workBasketService.getWorkbasket("fail")); + } - @WithAccessId(userName = "Elena", groupNames = {"businessadmin"}) - @Test - void testUpdateWorkbasket() throws Exception { - String id0 = IdGenerator.generateWithPrefix("TWB"); - Workbasket workbasket0 = createTestWorkbasket(id0, "key0", "DOMAIN_A", "Superbasket", WorkbasketType.GROUP); - workbasket0 = workBasketService.createWorkbasket(workbasket0); - createWorkbasketWithSecurity(workbasket0, "Elena", true, true, false, false); + @WithAccessId( + userName = "Elena", + groupNames = {"businessadmin"}) + @Test + void testUpdateWorkbasket() throws Exception { + String id0 = IdGenerator.generateWithPrefix("TWB"); + Workbasket workbasket0 = + createTestWorkbasket(id0, "key0", "DOMAIN_A", "Superbasket", WorkbasketType.GROUP); + workbasket0 = workBasketService.createWorkbasket(workbasket0); + createWorkbasketWithSecurity(workbasket0, "Elena", true, true, false, false); - String id1 = IdGenerator.generateWithPrefix("TWB"); - Workbasket workbasket1 = createTestWorkbasket(id1, "key1", "DOMAIN_A", "Megabasket", WorkbasketType.GROUP); - workbasket1 = workBasketService.createWorkbasket(workbasket1); - createWorkbasketWithSecurity(workbasket1, "Elena", true, true, false, false); + String id1 = IdGenerator.generateWithPrefix("TWB"); + Workbasket workbasket1 = + createTestWorkbasket(id1, "key1", "DOMAIN_A", "Megabasket", WorkbasketType.GROUP); + workbasket1 = workBasketService.createWorkbasket(workbasket1); + createWorkbasketWithSecurity(workbasket1, "Elena", true, true, false, false); - String id2 = IdGenerator.generateWithPrefix("TWB"); - Workbasket workbasket2 = createTestWorkbasket(id2, "key2", "DOMAIN_A", "Hyperbasket", WorkbasketType.GROUP); - workbasket2 = workBasketService.createWorkbasket(workbasket2); - createWorkbasketWithSecurity(workbasket2, "Elena", true, true, false, false); - List distTargets = new ArrayList<>(Arrays.asList(workbasket0.getId(), workbasket1.getId())); - Thread.sleep(SLEEP_TIME); - workBasketService.setDistributionTargets(workbasket2.getId(), distTargets); + String id2 = IdGenerator.generateWithPrefix("TWB"); + Workbasket workbasket2 = + createTestWorkbasket(id2, "key2", "DOMAIN_A", "Hyperbasket", WorkbasketType.GROUP); + workbasket2 = workBasketService.createWorkbasket(workbasket2); + createWorkbasketWithSecurity(workbasket2, "Elena", true, true, false, false); + List distTargets = + new ArrayList<>(Arrays.asList(workbasket0.getId(), workbasket1.getId())); + Thread.sleep(SLEEP_TIME); + workBasketService.setDistributionTargets(workbasket2.getId(), distTargets); - String id3 = IdGenerator.generateWithPrefix("TWB"); - Workbasket workbasket3 = createTestWorkbasket(id3, "key3", "DOMAIN_A", "hm ... irgend ein basket", - WorkbasketType.GROUP); - workbasket3 = workBasketService.createWorkbasket(workbasket3); - createWorkbasketWithSecurity(workbasket3, "Elena", true, true, false, false); + String id3 = IdGenerator.generateWithPrefix("TWB"); + Workbasket workbasket3 = + createTestWorkbasket( + id3, "key3", "DOMAIN_A", "hm ... irgend ein basket", WorkbasketType.GROUP); + workbasket3 = workBasketService.createWorkbasket(workbasket3); + createWorkbasketWithSecurity(workbasket3, "Elena", true, true, false, false); - List newDistTargets = new ArrayList<>(Arrays.asList(workbasket3.getId())); - Thread.sleep(SLEEP_TIME); - workBasketService.setDistributionTargets(workbasket2.getId(), newDistTargets); + List newDistTargets = new ArrayList<>(Arrays.asList(workbasket3.getId())); + Thread.sleep(SLEEP_TIME); + workBasketService.setDistributionTargets(workbasket2.getId(), newDistTargets); - Workbasket foundBasket = workBasketService.getWorkbasket(workbasket2.getId()); + Workbasket foundBasket = workBasketService.getWorkbasket(workbasket2.getId()); - List distributionTargets = workBasketService.getDistributionTargets(foundBasket.getId()); + List distributionTargets = + workBasketService.getDistributionTargets(foundBasket.getId()); - assertEquals(1, distributionTargets.size()); - assertEquals(id3, distributionTargets.get(0).getId()); - assertNotEquals(workBasketService.getWorkbasket(id2).getCreated(), - workBasketService.getWorkbasket(id2).getModified()); - assertEquals(workBasketService.getWorkbasket(id1).getCreated(), - workBasketService.getWorkbasket(id1).getModified()); - assertEquals(workBasketService.getWorkbasket(id3).getCreated(), - workBasketService.getWorkbasket(id3).getModified()); - } + assertEquals(1, distributionTargets.size()); + assertEquals(id3, distributionTargets.get(0).getId()); + assertNotEquals( + workBasketService.getWorkbasket(id2).getCreated(), + workBasketService.getWorkbasket(id2).getModified()); + assertEquals( + workBasketService.getWorkbasket(id1).getCreated(), + workBasketService.getWorkbasket(id1).getModified()); + assertEquals( + workBasketService.getWorkbasket(id3).getCreated(), + workBasketService.getWorkbasket(id3).getModified()); + } - @WithAccessId(userName = "Elena", groupNames = {"businessadmin"}) - @Test - void testInsertWorkbasketAccessUser() throws NotAuthorizedException, InvalidArgumentException, - DomainNotFoundException, InvalidWorkbasketException, WorkbasketAlreadyExistException, - WorkbasketNotFoundException { + @WithAccessId( + userName = "Elena", + groupNames = {"businessadmin"}) + @Test + void testInsertWorkbasketAccessUser() + throws NotAuthorizedException, InvalidArgumentException, DomainNotFoundException, + InvalidWorkbasketException, WorkbasketAlreadyExistException, WorkbasketNotFoundException { - Workbasket wb = createTestWorkbasket("k100000000000000000000000000000000000000", "key1", "DOMAIN_A", "name", + Workbasket wb = + createTestWorkbasket( + "k100000000000000000000000000000000000000", + "key1", + "DOMAIN_A", + "name", WorkbasketType.PERSONAL); - workBasketService.createWorkbasket(wb); - WorkbasketAccessItem accessItem = workBasketService - .newWorkbasketAccessItem("k100000000000000000000000000000000000000", "Arthur Dent"); - accessItem.setPermOpen(true); - accessItem.setPermRead(true); - workBasketService.createWorkbasketAccessItem(accessItem); + workBasketService.createWorkbasket(wb); + WorkbasketAccessItem accessItem = + workBasketService.newWorkbasketAccessItem( + "k100000000000000000000000000000000000000", "Arthur Dent"); + accessItem.setPermOpen(true); + accessItem.setPermRead(true); + workBasketService.createWorkbasketAccessItem(accessItem); - assertEquals(1, - workBasketService.getWorkbasketAccessItems("k100000000000000000000000000000000000000").size()); + assertEquals( + 1, + workBasketService + .getWorkbasketAccessItems("k100000000000000000000000000000000000000") + .size()); + } + + @WithAccessId( + userName = "Elena", + groupNames = {"businessadmin"}) + @Test + void testUpdateWorkbasketAccessUser() + throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException, + DomainNotFoundException, InvalidWorkbasketException, WorkbasketAlreadyExistException { + WorkbasketImpl wb = (WorkbasketImpl) workBasketService.newWorkbasket("key", "DOMAIN_A"); + wb.setId("k200000000000000000000000000000000000000"); + wb.setName("name"); + wb.setDescription("Description of a Workbasket..."); + wb.setType(WorkbasketType.GROUP); + workBasketService.createWorkbasket(wb); + + WorkbasketAccessItem accessItem = + workBasketService.newWorkbasketAccessItem( + "k200000000000000000000000000000000000000", "Zaphod Beeblebrox"); + accessItem.setPermOpen(true); + accessItem.setPermRead(true); + workBasketService.createWorkbasketAccessItem(accessItem); + + assertEquals( + 1, + workBasketService + .getWorkbasketAccessItems("k200000000000000000000000000000000000000") + .size()); + + accessItem.setPermAppend(true); + workBasketService.updateWorkbasketAccessItem(accessItem); + + if (TaskanaEngineConfiguration.shouldUseLowerCaseForAccessIds()) { + assertEquals("zaphod beeblebrox", accessItem.getAccessId()); + } else { + assertEquals("Zaphod Beeblebrox", accessItem.getAccessId()); } + } - @WithAccessId(userName = "Elena", groupNames = {"businessadmin"}) - @Test - void testUpdateWorkbasketAccessUser() - throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException, DomainNotFoundException, - InvalidWorkbasketException, WorkbasketAlreadyExistException { - WorkbasketImpl wb = (WorkbasketImpl) workBasketService.newWorkbasket("key", "DOMAIN_A"); - wb.setId("k200000000000000000000000000000000000000"); - wb.setName("name"); - wb.setDescription("Description of a Workbasket..."); - wb.setType(WorkbasketType.GROUP); - workBasketService.createWorkbasket(wb); + private void updateModifiedTimestamps( + Workbasket basket2, Workbasket basket3, Workbasket basket4, Workbasket basket1) + throws NoSuchFieldException, IllegalAccessException { + // created and modified timestamps are set by WorkbasketServiceImpl to 'now' when the workbasket + // is created + // in order to create timestamps distict from the current time, we must use the mapper directly + // to bypass + // WorkbasketServiceImpl + TaskanaEngineProxyForTest engineProxy = new TaskanaEngineProxyForTest(taskanaEngine); + SqlSession session = engineProxy.getSqlSession(); + WorkbasketMapper mapper = session.getMapper(WorkbasketMapper.class); - WorkbasketAccessItem accessItem = workBasketService.newWorkbasketAccessItem( - "k200000000000000000000000000000000000000", - "Zaphod Beeblebrox"); - accessItem.setPermOpen(true); - accessItem.setPermRead(true); - workBasketService.createWorkbasketAccessItem(accessItem); + WorkbasketImpl wb1 = (WorkbasketImpl) basket1; + WorkbasketImpl wb2 = (WorkbasketImpl) basket2; + WorkbasketImpl wb3 = (WorkbasketImpl) basket3; + WorkbasketImpl wb4 = (WorkbasketImpl) basket4; - assertEquals(1, - workBasketService.getWorkbasketAccessItems("k200000000000000000000000000000000000000").size()); + engineProxy.openConnection(); + wb1.setModified(now.minus(Duration.ofDays(10L))); + mapper.update(wb1); + wb2.setModified(now.minus(Duration.ofDays(15L))); + mapper.update(wb2); + wb3.setModified(now.minus(Duration.ofDays(20L))); + mapper.update(wb3); + wb4.setModified(now.minus(Duration.ofDays(30L))); + mapper.update(wb4); + engineProxy.returnConnection(); + } - accessItem.setPermAppend(true); - workBasketService.updateWorkbasketAccessItem(accessItem); + private void createWorkbasketWithSecurity( + Workbasket wb, + String accessId, + boolean permOpen, + boolean permRead, + boolean permAppend, + boolean permTransfer) + throws InvalidArgumentException, NotAuthorizedException, WorkbasketNotFoundException { + WorkbasketAccessItem accessItem = + workBasketService.newWorkbasketAccessItem(wb.getId(), accessId); + accessItem.setPermOpen(permOpen); + accessItem.setPermRead(permRead); + accessItem.setPermAppend(permAppend); + accessItem.setPermTransfer(permTransfer); + workBasketService.createWorkbasketAccessItem(accessItem); + } - if (TaskanaEngineConfiguration.shouldUseLowerCaseForAccessIds()) { - assertEquals("zaphod beeblebrox", accessItem.getAccessId()); - } else { - assertEquals("Zaphod Beeblebrox", accessItem.getAccessId()); - } - } - - private void updateModifiedTimestamps(Workbasket basket2, Workbasket basket3, Workbasket basket4, - Workbasket basket1) throws NoSuchFieldException, IllegalAccessException { - // created and modified timestamps are set by WorkbasketServiceImpl to 'now' when the workbasket is created - // in order to create timestamps distict from the current time, we must use the mapper directly to bypass - // WorkbasketServiceImpl - TaskanaEngineProxyForTest engineProxy = new TaskanaEngineProxyForTest(taskanaEngine); - SqlSession session = engineProxy.getSqlSession(); - WorkbasketMapper mapper = session.getMapper(WorkbasketMapper.class); - - WorkbasketImpl wb1 = (WorkbasketImpl) basket1; - WorkbasketImpl wb2 = (WorkbasketImpl) basket2; - WorkbasketImpl wb3 = (WorkbasketImpl) basket3; - WorkbasketImpl wb4 = (WorkbasketImpl) basket4; - - engineProxy.openConnection(); - wb1.setModified(now.minus(Duration.ofDays(10L))); - mapper.update(wb1); - wb2.setModified(now.minus(Duration.ofDays(15L))); - mapper.update(wb2); - wb3.setModified(now.minus(Duration.ofDays(20L))); - mapper.update(wb3); - wb4.setModified(now.minus(Duration.ofDays(30L))); - mapper.update(wb4); - engineProxy.returnConnection(); - } - - private void createWorkbasketWithSecurity(Workbasket wb, String accessId, boolean permOpen, - boolean permRead, boolean permAppend, boolean permTransfer) - throws InvalidArgumentException, NotAuthorizedException, WorkbasketNotFoundException { - WorkbasketAccessItem accessItem = workBasketService.newWorkbasketAccessItem(wb.getId(), accessId); - accessItem.setPermOpen(permOpen); - accessItem.setPermRead(permRead); - accessItem.setPermAppend(permAppend); - accessItem.setPermTransfer(permTransfer); - workBasketService.createWorkbasketAccessItem(accessItem); - } - - private Workbasket createTestWorkbasket(String id, String key, String domain, String name, WorkbasketType type) { - WorkbasketImpl wb = (WorkbasketImpl) workBasketService.newWorkbasket(key, domain); - wb.setId(id); - wb.setName(name); - wb.setDescription("Description of a Workbasket..."); - wb.setType(type); - return wb; - } - - private TimeInterval today() { - Instant begin = LocalDateTime.of(LocalDate.now(), LocalTime.MIN).atZone(ZoneId.systemDefault()).toInstant(); - Instant end = LocalDateTime.of(LocalDate.now(), LocalTime.MAX).atZone(ZoneId.systemDefault()).toInstant(); - return new TimeInterval(begin, end); - } + private Workbasket createTestWorkbasket( + String id, String key, String domain, String name, WorkbasketType type) { + WorkbasketImpl wb = (WorkbasketImpl) workBasketService.newWorkbasket(key, domain); + wb.setId(id); + wb.setName(name); + wb.setDescription("Description of a Workbasket..."); + wb.setType(type); + return wb; + } + private TimeInterval today() { + Instant begin = + LocalDateTime.of(LocalDate.now(), LocalTime.MIN).atZone(ZoneId.systemDefault()).toInstant(); + Instant end = + LocalDateTime.of(LocalDate.now(), LocalTime.MAX).atZone(ZoneId.systemDefault()).toInstant(); + return new TimeInterval(begin, end); + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/integration/WorkbasketServiceImplIntExplicitTest.java b/lib/taskana-core/src/test/java/pro/taskana/impl/integration/WorkbasketServiceImplIntExplicitTest.java index 89b8e2701..e4b58f31c 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/integration/WorkbasketServiceImplIntExplicitTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/integration/WorkbasketServiceImplIntExplicitTest.java @@ -8,9 +8,7 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import javax.sql.DataSource; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; @@ -47,151 +45,172 @@ import pro.taskana.security.WithAccessId; @ExtendWith(JAASExtension.class) class WorkbasketServiceImplIntExplicitTest { - private static final int SLEEP_TIME = 100; - static int counter = 0; - private DataSource dataSource; - private TaskanaEngineConfiguration taskanaEngineConfiguration; - private TaskanaEngine taskanaEngine; - private TaskanaEngineImpl taskanaEngineImpl; - private WorkbasketService workBasketService; + private static final int SLEEP_TIME = 100; + static int counter = 0; + private DataSource dataSource; + private TaskanaEngineConfiguration taskanaEngineConfiguration; + private TaskanaEngine taskanaEngine; + private TaskanaEngineImpl taskanaEngineImpl; + private WorkbasketService workBasketService; - @BeforeAll - static void resetDb() { - DataSource ds = TaskanaEngineTestConfiguration.getDataSource(); - String schemaName = TaskanaEngineTestConfiguration.getSchemaName(); - new SampleDataGenerator(ds, schemaName).dropDb(); - } + @BeforeAll + static void resetDb() { + DataSource ds = TaskanaEngineTestConfiguration.getDataSource(); + String schemaName = TaskanaEngineTestConfiguration.getSchemaName(); + new SampleDataGenerator(ds, schemaName).dropDb(); + } - @BeforeEach - void setup() throws SQLException { - dataSource = TaskanaEngineTestConfiguration.getDataSource(); - String schemaName = TaskanaEngineTestConfiguration.getSchemaName(); - taskanaEngineConfiguration = new TaskanaEngineConfiguration(dataSource, false, - schemaName); - taskanaEngine = taskanaEngineConfiguration.buildTaskanaEngine(); - taskanaEngineImpl = (TaskanaEngineImpl) taskanaEngine; - taskanaEngineImpl.setConnectionManagementMode(ConnectionManagementMode.EXPLICIT); - SampleDataGenerator sampleDataGenerator = new SampleDataGenerator(dataSource, schemaName); - sampleDataGenerator.clearDb(); - } + @BeforeEach + void setup() throws SQLException { + dataSource = TaskanaEngineTestConfiguration.getDataSource(); + String schemaName = TaskanaEngineTestConfiguration.getSchemaName(); + taskanaEngineConfiguration = new TaskanaEngineConfiguration(dataSource, false, schemaName); + taskanaEngine = taskanaEngineConfiguration.buildTaskanaEngine(); + taskanaEngineImpl = (TaskanaEngineImpl) taskanaEngine; + taskanaEngineImpl.setConnectionManagementMode(ConnectionManagementMode.EXPLICIT); + SampleDataGenerator sampleDataGenerator = new SampleDataGenerator(dataSource, schemaName); + sampleDataGenerator.clearDb(); + } - @WithAccessId(userName = "Elena", groupNames = {"businessadmin"}) - @Test - void testUpdateWorkbasket() throws Exception { - Connection connection = dataSource.getConnection(); - taskanaEngineImpl.setConnection(connection); - workBasketService = taskanaEngine.getWorkbasketService(); - String id0 = IdGenerator.generateWithPrefix("TWB"); - Workbasket workbasket0 = createTestWorkbasket(id0, "key0", "DOMAIN_A", "Superbasket", WorkbasketType.GROUP); - workbasket0 = workBasketService.createWorkbasket(workbasket0); - createWorkbasketWithSecurity(workbasket0, "Elena", true, true, false, false); + @WithAccessId( + userName = "Elena", + groupNames = {"businessadmin"}) + @Test + void testUpdateWorkbasket() throws Exception { + Connection connection = dataSource.getConnection(); + taskanaEngineImpl.setConnection(connection); + workBasketService = taskanaEngine.getWorkbasketService(); + String id0 = IdGenerator.generateWithPrefix("TWB"); + Workbasket workbasket0 = + createTestWorkbasket(id0, "key0", "DOMAIN_A", "Superbasket", WorkbasketType.GROUP); + workbasket0 = workBasketService.createWorkbasket(workbasket0); + createWorkbasketWithSecurity(workbasket0, "Elena", true, true, false, false); - String id1 = IdGenerator.generateWithPrefix("TWB"); - Workbasket workbasket1 = createTestWorkbasket(id1, "key1", "DOMAIN_A", "Megabasket", WorkbasketType.GROUP); - workbasket1 = workBasketService.createWorkbasket(workbasket1); - createWorkbasketWithSecurity(workbasket1, "Elena", true, true, false, false); + String id1 = IdGenerator.generateWithPrefix("TWB"); + Workbasket workbasket1 = + createTestWorkbasket(id1, "key1", "DOMAIN_A", "Megabasket", WorkbasketType.GROUP); + workbasket1 = workBasketService.createWorkbasket(workbasket1); + createWorkbasketWithSecurity(workbasket1, "Elena", true, true, false, false); - String id2 = IdGenerator.generateWithPrefix("TWB"); - Workbasket workbasket2 = createTestWorkbasket(id2, "key2", "DOMAIN_A", "Hyperbasket", WorkbasketType.GROUP); - workbasket2 = workBasketService.createWorkbasket(workbasket2); - createWorkbasketWithSecurity(workbasket2, "Elena", true, true, false, false); + String id2 = IdGenerator.generateWithPrefix("TWB"); + Workbasket workbasket2 = + createTestWorkbasket(id2, "key2", "DOMAIN_A", "Hyperbasket", WorkbasketType.GROUP); + workbasket2 = workBasketService.createWorkbasket(workbasket2); + createWorkbasketWithSecurity(workbasket2, "Elena", true, true, false, false); - List distTargets = new ArrayList<>(Arrays.asList(workbasket0.getId(), workbasket1.getId())); - Thread.sleep(SLEEP_TIME); - workBasketService.setDistributionTargets(workbasket2.getId(), distTargets); + List distTargets = + new ArrayList<>(Arrays.asList(workbasket0.getId(), workbasket1.getId())); + Thread.sleep(SLEEP_TIME); + workBasketService.setDistributionTargets(workbasket2.getId(), distTargets); - String id3 = IdGenerator.generateWithPrefix("TWB"); - Workbasket workbasket3 = createTestWorkbasket(id3, "key3", "DOMAIN_A", "hm ... irgend ein basket", - WorkbasketType.GROUP); - workbasket3 = workBasketService.createWorkbasket(workbasket3); - createWorkbasketWithSecurity(workbasket3, "Elena", true, true, false, false); + String id3 = IdGenerator.generateWithPrefix("TWB"); + Workbasket workbasket3 = + createTestWorkbasket( + id3, "key3", "DOMAIN_A", "hm ... irgend ein basket", WorkbasketType.GROUP); + workbasket3 = workBasketService.createWorkbasket(workbasket3); + createWorkbasketWithSecurity(workbasket3, "Elena", true, true, false, false); - List newDistTargets = new ArrayList<>(Arrays.asList(workbasket3.getId())); - Thread.sleep(SLEEP_TIME); - workBasketService.setDistributionTargets(workbasket2.getId(), newDistTargets); + List newDistTargets = new ArrayList<>(Arrays.asList(workbasket3.getId())); + Thread.sleep(SLEEP_TIME); + workBasketService.setDistributionTargets(workbasket2.getId(), newDistTargets); - Workbasket foundBasket = workBasketService.getWorkbasket(workbasket2.getId()); + Workbasket foundBasket = workBasketService.getWorkbasket(workbasket2.getId()); - List distributionTargets = workBasketService.getDistributionTargets(foundBasket.getId()); - assertEquals(1, distributionTargets.size()); - assertEquals(workbasket3.getId(), distributionTargets.get(0).getId()); - assertNotEquals(workBasketService.getWorkbasket(id2).getCreated(), - workBasketService.getWorkbasket(id2).getModified()); - assertEquals(workBasketService.getWorkbasket(id1).getCreated(), - workBasketService.getWorkbasket(id1).getModified()); - assertEquals(workBasketService.getWorkbasket(id3).getCreated(), - workBasketService.getWorkbasket(id3).getModified()); - connection.commit(); - } + List distributionTargets = + workBasketService.getDistributionTargets(foundBasket.getId()); + assertEquals(1, distributionTargets.size()); + assertEquals(workbasket3.getId(), distributionTargets.get(0).getId()); + assertNotEquals( + workBasketService.getWorkbasket(id2).getCreated(), + workBasketService.getWorkbasket(id2).getModified()); + assertEquals( + workBasketService.getWorkbasket(id1).getCreated(), + workBasketService.getWorkbasket(id1).getModified()); + assertEquals( + workBasketService.getWorkbasket(id3).getCreated(), + workBasketService.getWorkbasket(id3).getModified()); + connection.commit(); + } - @WithAccessId(userName = "Elena", groupNames = {"businessadmin"}) - @Test - void testInsertWorkbasketAccessUser() - throws NotAuthorizedException, SQLException, InvalidArgumentException, WorkbasketNotFoundException, - DomainNotFoundException, InvalidWorkbasketException, WorkbasketAlreadyExistException { - Connection connection = dataSource.getConnection(); - taskanaEngineImpl.setConnection(connection); - workBasketService = taskanaEngine.getWorkbasketService(); - Workbasket wb = createTestWorkbasket("id1", "key1", "DOMAIN_A", "name", WorkbasketType.CLEARANCE); - workBasketService.createWorkbasket(wb); - WorkbasketAccessItem accessItem = workBasketService.newWorkbasketAccessItem( - "id1", - "Arthur Dent"); - accessItem.setPermOpen(true); - accessItem.setPermRead(true); - workBasketService.createWorkbasketAccessItem(accessItem); + @WithAccessId( + userName = "Elena", + groupNames = {"businessadmin"}) + @Test + void testInsertWorkbasketAccessUser() + throws NotAuthorizedException, SQLException, InvalidArgumentException, + WorkbasketNotFoundException, DomainNotFoundException, InvalidWorkbasketException, + WorkbasketAlreadyExistException { + Connection connection = dataSource.getConnection(); + taskanaEngineImpl.setConnection(connection); + workBasketService = taskanaEngine.getWorkbasketService(); + Workbasket wb = + createTestWorkbasket("id1", "key1", "DOMAIN_A", "name", WorkbasketType.CLEARANCE); + workBasketService.createWorkbasket(wb); + WorkbasketAccessItem accessItem = + workBasketService.newWorkbasketAccessItem("id1", "Arthur Dent"); + accessItem.setPermOpen(true); + accessItem.setPermRead(true); + workBasketService.createWorkbasketAccessItem(accessItem); - assertEquals(1, workBasketService.getWorkbasketAccessItems("id1").size()); - connection.commit(); - } + assertEquals(1, workBasketService.getWorkbasketAccessItems("id1").size()); + connection.commit(); + } - @WithAccessId(userName = "Elena", groupNames = {"businessadmin"}) - @Test - void testUpdateWorkbasketAccessUser() - throws NotAuthorizedException, SQLException, InvalidArgumentException, WorkbasketNotFoundException, - DomainNotFoundException, InvalidWorkbasketException, WorkbasketAlreadyExistException { - Connection connection = dataSource.getConnection(); - taskanaEngineImpl.setConnection(connection); - workBasketService = taskanaEngine.getWorkbasketService(); + @WithAccessId( + userName = "Elena", + groupNames = {"businessadmin"}) + @Test + void testUpdateWorkbasketAccessUser() + throws NotAuthorizedException, SQLException, InvalidArgumentException, + WorkbasketNotFoundException, DomainNotFoundException, InvalidWorkbasketException, + WorkbasketAlreadyExistException { + Connection connection = dataSource.getConnection(); + taskanaEngineImpl.setConnection(connection); + workBasketService = taskanaEngine.getWorkbasketService(); - Workbasket wb = createTestWorkbasket("key2", "kkey2", "DOMAIN_A", "name", WorkbasketType.CLEARANCE); - workBasketService.createWorkbasket(wb); - WorkbasketAccessItem accessItem = workBasketService.newWorkbasketAccessItem( - "key2", - "Zaphod Beeblebrox"); - accessItem.setPermOpen(true); - accessItem.setPermRead(true); - workBasketService.createWorkbasketAccessItem(accessItem); + Workbasket wb = + createTestWorkbasket("key2", "kkey2", "DOMAIN_A", "name", WorkbasketType.CLEARANCE); + workBasketService.createWorkbasket(wb); + WorkbasketAccessItem accessItem = + workBasketService.newWorkbasketAccessItem("key2", "Zaphod Beeblebrox"); + accessItem.setPermOpen(true); + accessItem.setPermRead(true); + workBasketService.createWorkbasketAccessItem(accessItem); - assertEquals(1, workBasketService.getWorkbasketAccessItems("key2").size()); - assertEquals("zaphod beeblebrox", accessItem.getAccessId()); - connection.commit(); - } + assertEquals(1, workBasketService.getWorkbasketAccessItems("key2").size()); + assertEquals("zaphod beeblebrox", accessItem.getAccessId()); + connection.commit(); + } - private void createWorkbasketWithSecurity(Workbasket wb, String accessId, boolean permOpen, - boolean permRead, boolean permAppend, boolean permTransfer) - throws InvalidArgumentException, NotAuthorizedException, WorkbasketNotFoundException { - WorkbasketAccessItem accessItem = workBasketService.newWorkbasketAccessItem( - wb.getId(), accessId); - accessItem.setPermOpen(permOpen); - accessItem.setPermRead(permRead); - accessItem.setPermAppend(permAppend); - accessItem.setPermTransfer(permTransfer); - workBasketService.createWorkbasketAccessItem(accessItem); - } + @AfterEach + void cleanUp() throws SQLException { + taskanaEngineImpl.setConnection(null); + } - private Workbasket createTestWorkbasket(String id, String key, String domain, String name, WorkbasketType type) { - WorkbasketImpl wb = (WorkbasketImpl) workBasketService.newWorkbasket(key, domain); - wb.setId(id); - wb.setName(name); - wb.setDescription("Description of a Workbasket..."); - wb.setType(type); - return wb; - } - - @AfterEach - void cleanUp() throws SQLException { - taskanaEngineImpl.setConnection(null); - } + private void createWorkbasketWithSecurity( + Workbasket wb, + String accessId, + boolean permOpen, + boolean permRead, + boolean permAppend, + boolean permTransfer) + throws InvalidArgumentException, NotAuthorizedException, WorkbasketNotFoundException { + WorkbasketAccessItem accessItem = + workBasketService.newWorkbasketAccessItem(wb.getId(), accessId); + accessItem.setPermOpen(permOpen); + accessItem.setPermRead(permRead); + accessItem.setPermAppend(permAppend); + accessItem.setPermTransfer(permTransfer); + workBasketService.createWorkbasketAccessItem(accessItem); + } + private Workbasket createTestWorkbasket( + String id, String key, String domain, String name, WorkbasketType type) { + WorkbasketImpl wb = (WorkbasketImpl) workBasketService.newWorkbasket(key, domain); + wb.setId(id); + wb.setName(name); + wb.setDescription("Description of a Workbasket..."); + wb.setType(type); + return wb; + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/impl/report/structure/ReportTest.java b/lib/taskana-core/src/test/java/pro/taskana/impl/report/structure/ReportTest.java index 5ced758d5..2f3d6b347 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/impl/report/structure/ReportTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/impl/report/structure/ReportTest.java @@ -9,191 +9,182 @@ import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import pro.taskana.impl.report.header.TimeIntervalColumnHeader; import pro.taskana.impl.report.item.MonitorQueryItem; -/** - * Tests for {@link Report}. - */ +/** Tests for {@link Report}. */ class ReportTest { - private static final List HEADERS = IntStream.range(0, 4) - .mapToObj(TimeIntervalColumnHeader::new) - .collect(Collectors.toList()); - private Report report; - private MonitorQueryItem item; + private static final List HEADERS = + IntStream.range(0, 4).mapToObj(TimeIntervalColumnHeader::new).collect(Collectors.toList()); + private Report report; + private MonitorQueryItem item; - @BeforeEach - void before() { - this.report = new Report(HEADERS, new String[] {"rowDesc"}) { + @BeforeEach + void before() { + this.report = + new Report( + HEADERS, new String[] {"rowDesc"}) {}; + item = new MonitorQueryItem(); + item.setKey("key"); + item.setAgeInDays(0); + item.setNumberOfTasks(3); + } + + @Test + void testEmptyReport() { + // then + assertEquals(0, report.getRows().size()); + Row sumRow = report.getSumRow(); + assertArrayEquals(new int[] {0, 0, 0, 0}, sumRow.getCells()); + assertEquals(0, sumRow.getTotalValue()); + } + + @Test + void testInsertSingleItem() { + // when + report.addItem(item); + + // then + assertEquals(1, report.getRows().size()); + Row row = report.getRow("key"); + assertArrayEquals(new int[] {item.getValue(), 0, 0, 0}, row.getCells()); + assertEquals(item.getValue(), row.getTotalValue()); + } + + @Test + void testInsertSameItemMultipleTimes() { + // when + report.addItem(item); + report.addItem(item); + + // then + assertEquals(1, report.getRows().size()); + Row row = report.getRow("key"); + assertArrayEquals(new int[] {2 * item.getValue(), 0, 0, 0}, row.getCells()); + assertEquals(2 * item.getValue(), row.getTotalValue()); + } + + @Test + void testInsertSameItemMultipleTimes2() { + // given + MonitorQueryItem item = new MonitorQueryItem(); + item.setKey("key"); + item.setAgeInDays(0); + item.setNumberOfTasks(3); + + // when + report.addItems(Arrays.asList(item, item)); + + // then + assertEquals(1, report.getRows().size()); + Row row = report.getRow("key"); + assertArrayEquals(new int[] {2 * item.getValue(), 0, 0, 0}, row.getCells()); + assertEquals(2 * item.getValue(), row.getTotalValue()); + } + + @Test + void testInsertSameItemMultipleTimesWithPreProcessor() { + // given + int overrideValue = 5; + QueryItemPreprocessor preprocessor = + (item) -> { + item.setNumberOfTasks(overrideValue); + return item; }; + // when + report.addItems(Arrays.asList(item, item), preprocessor); - item = new MonitorQueryItem(); - item.setKey("key"); - item.setAgeInDays(0); - item.setNumberOfTasks(3); - } + // then + assertEquals(1, report.getRows().size()); + Row row = report.getRow("key"); + assertArrayEquals(new int[] {2 * overrideValue, 0, 0, 0}, row.getCells()); + assertEquals(2 * overrideValue, row.getTotalValue()); + } - @Test - void testEmptyReport() { - //then - assertEquals(0, report.getRows().size()); - Row sumRow = report.getSumRow(); - assertArrayEquals(new int[] {0, 0, 0, 0}, sumRow.getCells()); - assertEquals(0, sumRow.getTotalValue()); - } + @Test + void testInsertItemWithNoColumnHeaders() { + // given + report = + new Report( + Collections.emptyList(), new String[] {"rowDesc"}) {}; - @Test - void testInsertSingleItem() { - //when - report.addItem(item); + // when + report.addItem(item); - //then - assertEquals(1, report.getRows().size()); - Row row = report.getRow("key"); - assertArrayEquals(new int[] {item.getValue(), 0, 0, 0}, row.getCells()); - assertEquals(item.getValue(), row.getTotalValue()); + // then + assertEquals(1, report.getRows().size()); + assertArrayEquals(new int[0], report.getRow("key").getCells()); + assertEquals(item.getValue(), report.getRow("key").getTotalValue()); + } - } + @Test + void testInsertItemWhichIsNotInHeaderScopes() { + // given + item.setAgeInDays(-2); + // when + report.addItem(item); - @Test - void testInsertSameItemMultipleTimes() { - //when - report.addItem(item); - report.addItem(item); + // then + assertEquals(0, report.getRows().size()); + Row sumRow = report.getSumRow(); + assertArrayEquals(new int[] {0, 0, 0, 0}, sumRow.getCells()); + assertEquals(0, sumRow.getTotalValue()); + } - //then - assertEquals(1, report.getRows().size()); - Row row = report.getRow("key"); - assertArrayEquals(new int[] {2 * item.getValue(), 0, 0, 0}, row.getCells()); - assertEquals(2 * item.getValue(), row.getTotalValue()); + @Test + void testInsertItemWhichIsInMultipleHeaderScopes() { + // given + List headers = new ArrayList<>(HEADERS); + headers.add(new TimeIntervalColumnHeader(0, 3)); + report = + new Report( + headers, new String[] {"rowDesc"}) {}; - } + item.setAgeInDays(2); - @Test - void testInsertSameItemMultipleTimes2() { - //given - MonitorQueryItem item = new MonitorQueryItem(); - item.setKey("key"); - item.setAgeInDays(0); - item.setNumberOfTasks(3); + // when + report.addItem(item); - //when - report.addItems(Arrays.asList(item, item)); + // then + assertEquals(1, report.getRows().size()); - //then - assertEquals(1, report.getRows().size()); - Row row = report.getRow("key"); - assertArrayEquals(new int[] {2 * item.getValue(), 0, 0, 0}, row.getCells()); - assertEquals(2 * item.getValue(), row.getTotalValue()); + Row row = report.getRow("key"); + assertArrayEquals(new int[] {0, 0, item.getValue(), 0, item.getValue()}, row.getCells()); + assertEquals(2 * item.getValue(), row.getTotalValue()); - } + Row sumRow = report.getSumRow(); + assertArrayEquals(new int[] {0, 0, item.getValue(), 0, item.getValue()}, sumRow.getCells()); + assertEquals(2 * item.getValue(), sumRow.getTotalValue()); + } - @Test - void testInsertSameItemMultipleTimesWithPreProcessor() { - //given - int overrideValue = 5; - QueryItemPreprocessor preprocessor = (item) -> { - item.setNumberOfTasks(overrideValue); - return item; + @Test + void testInsertItemWithPreProcessor() { + // given + int overrideValue = 5; + QueryItemPreprocessor preprocessor = + item -> { + item.setNumberOfTasks(overrideValue); + return item; }; - //when - report.addItems(Arrays.asList(item, item), preprocessor); + item.setAgeInDays(1); - //then - assertEquals(1, report.getRows().size()); - Row row = report.getRow("key"); - assertArrayEquals(new int[] {2 * overrideValue, 0, 0, 0}, row.getCells()); - assertEquals(2 * overrideValue, row.getTotalValue()); + // when + report.addItem(item, preprocessor); - } + // then + assertEquals(1, report.getRows().size()); - @Test - void testInsertItemWithNoColumnHeaders() { - //given - report = new Report(Collections.emptyList(), - new String[] {"rowDesc"}) { - - }; - - //when - report.addItem(item); - - //then - assertEquals(1, report.getRows().size()); - assertArrayEquals(new int[0], report.getRow("key").getCells()); - assertEquals(item.getValue(), report.getRow("key").getTotalValue()); - } - - @Test - void testInsertItemWhichIsNotInHeaderScopes() { - //given - item.setAgeInDays(-2); - //when - report.addItem(item); - - //then - assertEquals(0, report.getRows().size()); - Row sumRow = report.getSumRow(); - assertArrayEquals(new int[] {0, 0, 0, 0}, sumRow.getCells()); - assertEquals(0, sumRow.getTotalValue()); - } - - @Test - void testInsertItemWhichIsInMultipleHeaderScopes() { - //given - List headers = new ArrayList<>(HEADERS); - headers.add(new TimeIntervalColumnHeader(0, 3)); - report = new Report(headers, new String[] {"rowDesc"}) { - - }; - item.setAgeInDays(2); - - //when - report.addItem(item); - - //then - assertEquals(1, report.getRows().size()); - - Row row = report.getRow("key"); - assertArrayEquals(new int[] {0, 0, item.getValue(), 0, item.getValue()}, row.getCells()); - assertEquals(2 * item.getValue(), row.getTotalValue()); - - Row sumRow = report.getSumRow(); - assertArrayEquals(new int[] {0, 0, item.getValue(), 0, item.getValue()}, sumRow.getCells()); - assertEquals(2 * item.getValue(), sumRow.getTotalValue()); - - } - - @Test - void testInsertItemWithPreProcessor() { - //given - int overrideValue = 5; - QueryItemPreprocessor preprocessor = item -> { - item.setNumberOfTasks(overrideValue); - return item; - }; - item.setAgeInDays(1); - - //when - report.addItem(item, preprocessor); - - //then - assertEquals(1, report.getRows().size()); - - Row row = report.getRow(item.getKey()); - assertArrayEquals(new int[] {0, overrideValue, 0, 0}, row.getCells()); - assertEquals(overrideValue, row.getTotalValue()); - - Row sumRow = report.getSumRow(); - assertArrayEquals(new int[] {0, overrideValue, 0, 0}, sumRow.getCells()); - assertEquals(overrideValue, sumRow.getTotalValue()); - - } + Row row = report.getRow(item.getKey()); + assertArrayEquals(new int[] {0, overrideValue, 0, 0}, row.getCells()); + assertEquals(overrideValue, row.getTotalValue()); + Row sumRow = report.getSumRow(); + assertArrayEquals(new int[] {0, overrideValue, 0, 0}, sumRow.getCells()); + assertEquals(overrideValue, sumRow.getTotalValue()); + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/mappings/TaskTestMapper.java b/lib/taskana-core/src/test/java/pro/taskana/mappings/TaskTestMapper.java index 8e81eb405..80173eee7 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/mappings/TaskTestMapper.java +++ b/lib/taskana-core/src/test/java/pro/taskana/mappings/TaskTestMapper.java @@ -2,7 +2,6 @@ package pro.taskana.mappings; import java.util.List; import java.util.Map; - import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; @@ -12,22 +11,26 @@ import org.apache.ibatis.type.ClobTypeHandler; import pro.taskana.impl.TaskImpl; import pro.taskana.impl.persistence.MapTypeHandler; -/** - * This class contains specific mybatis mappings for task tests. - */ +/** This class contains specific mybatis mappings for task tests. */ public interface TaskTestMapper { - @Select("select CUSTOM_ATTRIBUTES from TASK where id = #{taskId}") - @Results(value = { - @Result(property = "customAttributes", column = "CUSTOM_ATTRIBUTES", - javaType = String.class, typeHandler = ClobTypeHandler.class) - }) - String getCustomAttributesAsString(@Param("taskId") String taskId); + @Select("select CUSTOM_ATTRIBUTES from TASK where id = #{taskId}") + @Results( + value = { + @Result( + property = "customAttributes", + column = "CUSTOM_ATTRIBUTES", + javaType = String.class, + typeHandler = ClobTypeHandler.class) + }) + String getCustomAttributesAsString(@Param("taskId") String taskId); - @Select("SELECT ID, CREATED, CLAIMED, COMPLETED, MODIFIED, PLANNED, DUE, NAME, CREATOR, DESCRIPTION, NOTE, PRIORITY, STATE, CLASSIFICATION_CATEGORY, CLASSIFICATION_KEY, CLASSIFICATION_ID, WORKBASKET_ID, WORKBASKET_KEY, DOMAIN, BUSINESS_PROCESS_ID, PARENT_BUSINESS_PROCESS_ID, OWNER, POR_COMPANY, POR_SYSTEM, POR_INSTANCE, POR_TYPE, POR_VALUE, IS_READ, IS_TRANSFERRED, CUSTOM_ATTRIBUTES, CUSTOM_1, CUSTOM_2, CUSTOM_3, CUSTOM_4, CUSTOM_5, CUSTOM_6, CUSTOM_7, CUSTOM_8, CUSTOM_9, CUSTOM_10 " - + "FROM TASK " - + "WHERE CUSTOM_ATTRIBUTES like #{searchText}") - @Results(value = { + @Select( + "SELECT ID, CREATED, CLAIMED, COMPLETED, MODIFIED, PLANNED, DUE, NAME, CREATOR, DESCRIPTION, NOTE, PRIORITY, STATE, CLASSIFICATION_CATEGORY, CLASSIFICATION_KEY, CLASSIFICATION_ID, WORKBASKET_ID, WORKBASKET_KEY, DOMAIN, BUSINESS_PROCESS_ID, PARENT_BUSINESS_PROCESS_ID, OWNER, POR_COMPANY, POR_SYSTEM, POR_INSTANCE, POR_TYPE, POR_VALUE, IS_READ, IS_TRANSFERRED, CUSTOM_ATTRIBUTES, CUSTOM_1, CUSTOM_2, CUSTOM_3, CUSTOM_4, CUSTOM_5, CUSTOM_6, CUSTOM_7, CUSTOM_8, CUSTOM_9, CUSTOM_10 " + + "FROM TASK " + + "WHERE CUSTOM_ATTRIBUTES like #{searchText}") + @Results( + value = { @Result(property = "id", column = "ID"), @Result(property = "created", column = "CREATED"), @Result(property = "claimed", column = "CLAIMED"), @@ -41,7 +44,9 @@ public interface TaskTestMapper { @Result(property = "note", column = "NOTE"), @Result(property = "priority", column = "PRIORITY"), @Result(property = "state", column = "STATE"), - @Result(property = "classificationSummaryImpl.category", column = "CLASSIFICATION_CATEGORY"), + @Result( + property = "classificationSummaryImpl.category", + column = "CLASSIFICATION_CATEGORY"), @Result(property = "classificationSummaryImpl.id", column = "CLASSIFICATION_ID"), @Result(property = "classificationSummaryImpl.key", column = "CLASSIFICATION_KEY"), @Result(property = "domain", column = "DOMAIN"), @@ -55,8 +60,11 @@ public interface TaskTestMapper { @Result(property = "primaryObjRef.value", column = "POR_VALUE"), @Result(property = "isRead", column = "IS_READ"), @Result(property = "isTransferred", column = "IS_TRANSFERRED"), - @Result(property = "customAttributes", column = "CUSTOM_ATTRIBUTES", - javaType = Map.class, typeHandler = MapTypeHandler.class), + @Result( + property = "customAttributes", + column = "CUSTOM_ATTRIBUTES", + javaType = Map.class, + typeHandler = MapTypeHandler.class), @Result(property = "custom1", column = "CUSTOM_1"), @Result(property = "custom2", column = "CUSTOM_2"), @Result(property = "custom3", column = "CUSTOM_3"), @@ -67,7 +75,6 @@ public interface TaskTestMapper { @Result(property = "custom8", column = "CUSTOM_8"), @Result(property = "custom9", column = "CUSTOM_9"), @Result(property = "custom10", column = "CUSTOM_10") - }) - List selectTasksByCustomAttributeLike(@Param("searchText") String searchText); - + }) + List selectTasksByCustomAttributeLike(@Param("searchText") String searchText); } diff --git a/lib/taskana-core/src/test/java/pro/taskana/sampledata/SampleDataGeneratorTest.java b/lib/taskana-core/src/test/java/pro/taskana/sampledata/SampleDataGeneratorTest.java index 814d4c414..db10b1c1c 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/sampledata/SampleDataGeneratorTest.java +++ b/lib/taskana-core/src/test/java/pro/taskana/sampledata/SampleDataGeneratorTest.java @@ -6,32 +6,29 @@ import org.junit.jupiter.api.Test; import pro.taskana.configuration.DbSchemaCreator; -/** - * Test SampleDataGenerator. - */ +/** Test SampleDataGenerator. */ class SampleDataGeneratorTest { - private static final String JDBC_URL = "jdbc:h2:mem:taskana;IGNORECASE=TRUE;LOCK_MODE=0;INIT=CREATE SCHEMA IF NOT EXISTS TASKANA"; + private static final String JDBC_URL = + "jdbc:h2:mem:taskana;IGNORECASE=TRUE;LOCK_MODE=0;INIT=CREATE SCHEMA IF NOT EXISTS TASKANA"; - @Test - void getScriptsValidSql() { - PooledDataSource pooledDataSource = new PooledDataSource("org.h2.Driver", - JDBC_URL, "sa", "sa"); - Assertions.assertDoesNotThrow(() -> new DbSchemaCreator(pooledDataSource, "TASKANA").run()); - Assertions.assertDoesNotThrow(() -> new SampleDataGenerator(pooledDataSource, "TASKANA").generateSampleData()); - pooledDataSource.forceCloseAll(); - } + @Test + void getScriptsValidSql() { + PooledDataSource pooledDataSource = new PooledDataSource("org.h2.Driver", JDBC_URL, "sa", "sa"); + Assertions.assertDoesNotThrow(() -> new DbSchemaCreator(pooledDataSource, "TASKANA").run()); + Assertions.assertDoesNotThrow( + () -> new SampleDataGenerator(pooledDataSource, "TASKANA").generateSampleData()); + pooledDataSource.forceCloseAll(); + } - @Test - void tableExists() { - PooledDataSource pooledDataSource = new PooledDataSource("org.h2.Driver", - JDBC_URL, "sa", "sa"); - Assertions.assertDoesNotThrow(() -> new DbSchemaCreator(pooledDataSource, "TASKANA").run()); - - SampleDataGenerator sampleDataGenerator = new SampleDataGenerator(pooledDataSource, "TASKANA"); - Assertions.assertTrue(sampleDataGenerator.tableExists("TASK")); - Assertions.assertFalse(sampleDataGenerator.tableExists("TASKRANDOM")); - pooledDataSource.forceCloseAll(); - } + @Test + void tableExists() { + PooledDataSource pooledDataSource = new PooledDataSource("org.h2.Driver", JDBC_URL, "sa", "sa"); + Assertions.assertDoesNotThrow(() -> new DbSchemaCreator(pooledDataSource, "TASKANA").run()); + SampleDataGenerator sampleDataGenerator = new SampleDataGenerator(pooledDataSource, "TASKANA"); + Assertions.assertTrue(sampleDataGenerator.tableExists("TASK")); + Assertions.assertFalse(sampleDataGenerator.tableExists("TASKRANDOM")); + pooledDataSource.forceCloseAll(); + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/security/JAASExtension.java b/lib/taskana-core/src/test/java/pro/taskana/security/JAASExtension.java index 5c9f04e98..25725ee93 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/security/JAASExtension.java +++ b/lib/taskana-core/src/test/java/pro/taskana/security/JAASExtension.java @@ -5,52 +5,51 @@ import java.security.Principal; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.List; - import javax.security.auth.Subject; - import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.InvocationInterceptor; import org.junit.jupiter.api.extension.ReflectiveInvocationContext; import org.junit.platform.commons.JUnitException; -/** - * Runner for integration tests that enables JAAS subject. - */ +/** Runner for integration tests that enables JAAS subject. */ public class JAASExtension implements InvocationInterceptor { - @Override - public void interceptTestMethod(Invocation invocation, - ReflectiveInvocationContext invocationContext, - ExtensionContext extensionContext) throws Throwable { + @Override + public void interceptTestMethod( + Invocation invocation, + ReflectiveInvocationContext invocationContext, + ExtensionContext extensionContext) + throws Throwable { - //check for access - Subject subject = new Subject(); - List principalList = new ArrayList<>(); + // check for access + Subject subject = new Subject(); + List principalList = new ArrayList<>(); - WithAccessId withAccessId = invocationContext.getExecutable().getAnnotation(WithAccessId.class); - if (withAccessId != null) { - if (withAccessId.userName() != null) { - principalList.add(new UserPrincipal(withAccessId.userName())); - } - for (String groupName : withAccessId.groupNames()) { - if (groupName != null) { - principalList.add(new GroupPrincipal(groupName)); - } - } + WithAccessId withAccessId = invocationContext.getExecutable().getAnnotation(WithAccessId.class); + if (withAccessId != null) { + if (withAccessId.userName() != null) { + principalList.add(new UserPrincipal(withAccessId.userName())); + } + for (String groupName : withAccessId.groupNames()) { + if (groupName != null) { + principalList.add(new GroupPrincipal(groupName)); } - subject.getPrincipals().addAll(principalList); - Subject.doAs(subject, (PrivilegedExceptionAction) () -> { - - try { - invocation.proceed(); - } catch (Exception | Error e) { - throw e; - } catch (Throwable e) { - throw new JUnitException("Execution of test failed: " + invocationContext.getExecutable().getName(), e); - } - return null; - }); - + } } - + subject.getPrincipals().addAll(principalList); + Subject.doAs( + subject, + (PrivilegedExceptionAction) + () -> { + try { + invocation.proceed(); + } catch (Exception | Error e) { + throw e; + } catch (Throwable e) { + throw new JUnitException( + "Execution of test failed: " + invocationContext.getExecutable().getName(), e); + } + return null; + }); + } } diff --git a/lib/taskana-core/src/test/java/pro/taskana/security/WithAccessId.java b/lib/taskana-core/src/test/java/pro/taskana/security/WithAccessId.java index fbd641c93..0326fce23 100644 --- a/lib/taskana-core/src/test/java/pro/taskana/security/WithAccessId.java +++ b/lib/taskana-core/src/test/java/pro/taskana/security/WithAccessId.java @@ -7,14 +7,14 @@ import java.lang.annotation.Target; /** * Specify user id for JUnit JAASRunner. - * @author bbr * + * @author bbr */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface WithAccessId { - String userName(); + String userName(); - String[] groupNames() default {}; + String[] groupNames() default {}; } diff --git a/lib/taskana-data/src/main/java/pro/taskana/sampledata/SQLReplacer.java b/lib/taskana-data/src/main/java/pro/taskana/sampledata/SQLReplacer.java index 7e9982adb..50f9883a4 100644 --- a/lib/taskana-data/src/main/java/pro/taskana/sampledata/SQLReplacer.java +++ b/lib/taskana-data/src/main/java/pro/taskana/sampledata/SQLReplacer.java @@ -10,80 +10,80 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; -/** - * This class replaces boolean values with int values if the database is db2. - */ +/** This class replaces boolean values with int values if the database is db2. */ final class SQLReplacer { - static final String RELATIVE_DATE_REGEX = "RELATIVE_DATE\\((-?\\d+)\\)"; - static final Pattern RELATIVE_DATE_PATTERN = Pattern.compile(RELATIVE_DATE_REGEX); - static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); + static final String RELATIVE_DATE_REGEX = "RELATIVE_DATE\\((-?\\d+)\\)"; + static final Pattern RELATIVE_DATE_PATTERN = Pattern.compile(RELATIVE_DATE_REGEX); + static final DateTimeFormatter DATE_TIME_FORMATTER = + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); - private SQLReplacer() { - } + private SQLReplacer() {} - static String getScriptAsSql(String dbProductName, LocalDateTime now, String scriptPath) { - return parseAndReplace(getScriptBufferedStream(scriptPath), now, dbProductName); - } + static String getScriptAsSql(String dbProductName, LocalDateTime now, String scriptPath) { + return parseAndReplace(getScriptBufferedStream(scriptPath), now, dbProductName); + } - private static String replaceBooleanWithInteger(String sql) { - return sql.replaceAll("(?i)true", "1").replaceAll("(?i)false", "0"); - } + static boolean isPostgreSQL(String databaseProductName) { + return "PostgreSQL".equals(databaseProductName); + } - private static String parseAndReplace(BufferedReader bufferedReader, LocalDateTime now, String dbProductname) { - boolean isDb2 = isDb2(dbProductname); - String sql = bufferedReader.lines().collect(Collectors.joining(System.lineSeparator())); - if (isDb2) { - sql = replaceBooleanWithInteger(sql); - } - return replaceDatePlaceholder(now, sql); - } + static boolean isDb2(String dbProductName) { + return dbProductName != null && dbProductName.contains("DB2"); + } - static boolean isPostgreSQL(String databaseProductName) { - return "PostgreSQL".equals(databaseProductName); + /** + * This method resolves the custom sql function defined through this regex: {@value + * RELATIVE_DATE_REGEX}. Its parameter is a digit representing the relative offset of a given + * starting point date. + * + *

Yes, this can be done as an actual sql function, but that'd lead to a little more complexity + * (and thus we'd have to maintain the code for db compatibility ...) Since we're already + * replacing the boolean attributes of sql files this addition is not a huge computational cost. + * + * @param now anchor for relative date conversion. + * @param sql sql statement which may contain the above declared custom function. + * @return sql statement with the given function resolved, if the 'sql' parameter contained any. + */ + static String replaceDatePlaceholder(LocalDateTime now, String sql) { + Matcher m = RELATIVE_DATE_PATTERN.matcher(sql); + StringBuffer sb = new StringBuffer(sql.length()); + while (m.find()) { + long daysToShift = Long.parseLong(m.group(1)); + String daysAsStringDate = formatToSqlDate(now, daysToShift); + m.appendReplacement(sb, daysAsStringDate); } + m.appendTail(sb); + return sb.toString(); + } - static boolean isDb2(String dbProductName) { - return dbProductName != null && dbProductName.contains("DB2"); - } + static BufferedReader getScriptBufferedStream(String script) { + return Optional.ofNullable(SampleDataGenerator.class.getResourceAsStream(script)) + .map( + inputStream -> + new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) + .orElse(null); + } - /** - * This method resolves the custom sql function defined through this regex: {@value RELATIVE_DATE_REGEX}. Its - * parameter is a digit representing the relative offset of a given starting point date. - *

- * Yes, this can be done as an actual sql function, but that'd lead to a little more complexity (and thus we'd have - * to maintain the code for db compatibility ...) Since we're already replacing the boolean attributes of sql files - * this addition is not a huge computational cost. - * - * @param now - * anchor for relative date conversion. - * @param sql - * sql statement which may contain the above declared custom function. - * @return sql statement with the given function resolved, if the 'sql' parameter contained any. - */ - static String replaceDatePlaceholder(LocalDateTime now, String sql) { - Matcher m = RELATIVE_DATE_PATTERN.matcher(sql); - StringBuffer sb = new StringBuffer(sql.length()); - while (m.find()) { - long daysToShift = Long.parseLong(m.group(1)); - String daysAsStringDate = formatToSqlDate(now, daysToShift); - m.appendReplacement(sb, daysAsStringDate); - } - m.appendTail(sb); - return sb.toString(); - } + static String getSanitizedTableName(String table) { + return table.replaceAll("[^a-zA-Z0-9_]", "__"); + } - private static String formatToSqlDate(LocalDateTime now, long days) { - return "'" + now.plusDays(days).format(DATE_TIME_FORMATTER) + "'"; - } + private static String replaceBooleanWithInteger(String sql) { + return sql.replaceAll("(?i)true", "1").replaceAll("(?i)false", "0"); + } - static BufferedReader getScriptBufferedStream(String script) { - return Optional.ofNullable(SampleDataGenerator.class.getResourceAsStream(script)).map( - inputStream -> new BufferedReader( - new InputStreamReader(inputStream, StandardCharsets.UTF_8))).orElse(null); + private static String parseAndReplace( + BufferedReader bufferedReader, LocalDateTime now, String dbProductname) { + boolean isDb2 = isDb2(dbProductname); + String sql = bufferedReader.lines().collect(Collectors.joining(System.lineSeparator())); + if (isDb2) { + sql = replaceBooleanWithInteger(sql); } + return replaceDatePlaceholder(now, sql); + } - static String getSanitizedTableName(String table) { - return table.replaceAll("[^a-zA-Z0-9_]", "__"); - } + private static String formatToSqlDate(LocalDateTime now, long days) { + return "'" + now.plusDays(days).format(DATE_TIME_FORMATTER) + "'"; + } } diff --git a/lib/taskana-data/src/main/java/pro/taskana/sampledata/SampleDataGenerator.java b/lib/taskana-data/src/main/java/pro/taskana/sampledata/SampleDataGenerator.java index c9954c66a..918ed87ee 100644 --- a/lib/taskana-data/src/main/java/pro/taskana/sampledata/SampleDataGenerator.java +++ b/lib/taskana-data/src/main/java/pro/taskana/sampledata/SampleDataGenerator.java @@ -13,154 +13,150 @@ import java.util.List; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; - import javax.sql.DataSource; - import org.apache.ibatis.jdbc.RuntimeSqlException; import org.apache.ibatis.jdbc.ScriptRunner; import org.apache.ibatis.jdbc.SqlRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * This class generates sample data for manual testing purposes. - */ +/** This class generates sample data for manual testing purposes. */ public class SampleDataGenerator { - private static final Logger LOGGER = LoggerFactory.getLogger(SampleDataGenerator.class); + private static final Logger LOGGER = LoggerFactory.getLogger(SampleDataGenerator.class); - private static final String CACHED_TEST = "TEST"; - private static final String CACHED_SAMPLE = "SAMPLE"; - private static final String CACHED_EVENTSAMPLE = "EVENTSAMPLE"; - private static final String CACHED_MONITOR = "MONITOR"; - private static final String CACHED_CLEARDB = "CLEARDB"; - private static final String CACHED_DROPDB = "DROPDB"; + private static final String CACHED_TEST = "TEST"; + private static final String CACHED_SAMPLE = "SAMPLE"; + private static final String CACHED_EVENTSAMPLE = "EVENTSAMPLE"; + private static final String CACHED_MONITOR = "MONITOR"; + private static final String CACHED_CLEARDB = "CLEARDB"; + private static final String CACHED_DROPDB = "DROPDB"; + private static HashMap> cachedScripts = new HashMap<>(); + private final DataSource dataSource; + private final LocalDateTime now; + /** + * This value cannot be automatically obtained by connection.getSchema(), because setting not yet + * existing schema will result into an SQL Exception. + */ + private final String schema; - private final DataSource dataSource; - private final LocalDateTime now; + public SampleDataGenerator(DataSource dataSource, String schema) { + this(dataSource, schema, LocalDateTime.now()); + } - /** - * This value cannot be automatically obtained by connection.getSchema(), - * because setting not yet existing schema will result into an SQL Exception. - */ - private final String schema; + public SampleDataGenerator(DataSource dataSource, String schema, LocalDateTime now) { + this.dataSource = dataSource; + this.schema = schema; + this.now = now; + } - private static HashMap> cachedScripts = new HashMap<>(); - - public SampleDataGenerator(DataSource dataSource, String schema) { - this(dataSource, schema, LocalDateTime.now()); - } - - public SampleDataGenerator(DataSource dataSource, String schema, LocalDateTime now) { - this.dataSource = dataSource; - this.schema = schema; - this.now = now; - } - - public void generateSampleData() { - runScripts((runner) -> { - clearDb(); - Stream scripts; - String cacheKey; - //dbtable constants? - if (tableExists("HISTORY_EVENTS")) { - scripts = SampleDataProvider.getScriptsWithEvents(); - cacheKey = CACHED_EVENTSAMPLE; - } else { - scripts = SampleDataProvider.getDefaultScripts(); - cacheKey = CACHED_SAMPLE; - } - executeAndCacheScripts(scripts, cacheKey); + public void generateSampleData() { + runScripts( + (runner) -> { + clearDb(); + Stream scripts; + String cacheKey; + // dbtable constants? + if (tableExists("HISTORY_EVENTS")) { + scripts = SampleDataProvider.getScriptsWithEvents(); + cacheKey = CACHED_EVENTSAMPLE; + } else { + scripts = SampleDataProvider.getDefaultScripts(); + cacheKey = CACHED_SAMPLE; + } + executeAndCacheScripts(scripts, cacheKey); }); - } + } - public void generateTestData() { - Stream scripts = SampleDataProvider.getTestDataScripts(); - executeAndCacheScripts(scripts, CACHED_TEST); - } + public void generateTestData() { + Stream scripts = SampleDataProvider.getTestDataScripts(); + executeAndCacheScripts(scripts, CACHED_TEST); + } - public void generateMonitorData() { - Stream scripts = SampleDataProvider.getMonitorDataScripts(); - executeAndCacheScripts(scripts, CACHED_MONITOR); - } + public void generateMonitorData() { + Stream scripts = SampleDataProvider.getMonitorDataScripts(); + executeAndCacheScripts(scripts, CACHED_MONITOR); + } - public void clearDb() { - Stream scripts = SampleDataProvider.getScriptsToClearDatabase(); - executeAndCacheScripts(scripts, CACHED_CLEARDB); - } + public void clearDb() { + Stream scripts = SampleDataProvider.getScriptsToClearDatabase(); + executeAndCacheScripts(scripts, CACHED_CLEARDB); + } - public void dropDb() { - Stream scripts = SampleDataProvider.getScriptsToDropDatabase(); - executeAndCacheScripts(scripts, CACHED_DROPDB); - } + public void dropDb() { + Stream scripts = SampleDataProvider.getScriptsToDropDatabase(); + executeAndCacheScripts(scripts, CACHED_DROPDB); + } - private List parseScripts(Stream scripts) { - try (Connection connection = dataSource.getConnection()) { - String dbProductName = connection.getMetaData().getDatabaseProductName(); - return scripts.map(script -> SQLReplacer.getScriptAsSql(dbProductName, now, script)) - .collect(Collectors.toList()); - } catch (SQLException e) { - throw new RuntimeSqlException("Connection to database failed.", e); + boolean tableExists(String table) { + try (Connection connection = dataSource.getConnection()) { + connection.setSchema(schema); + SqlRunner runner = new SqlRunner(connection); + String tableSafe = SQLReplacer.getSanitizedTableName(table); + String query = "SELECT 1 FROM " + tableSafe + " LIMIT 1;"; + runner.run(query); + return true; + } catch (Exception e) { + return false; + } + } + + private List parseScripts(Stream scripts) { + try (Connection connection = dataSource.getConnection()) { + String dbProductName = connection.getMetaData().getDatabaseProductName(); + return scripts + .map(script -> SQLReplacer.getScriptAsSql(dbProductName, now, script)) + .collect(Collectors.toList()); + } catch (SQLException e) { + throw new RuntimeSqlException("Connection to database failed.", e); + } + } + + private void runScripts(Consumer consumer) { + try (Connection connection = dataSource.getConnection()) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace(connection.getMetaData().toString()); + } + + StringWriter outWriter = new StringWriter(); + StringWriter errorWriter = new StringWriter(); + + ScriptRunner runner = getScriptRunner(connection, outWriter, errorWriter); + consumer.accept(runner); + runner.closeConnection(); + + if (LOGGER.isTraceEnabled()) { + LOGGER.trace(outWriter.toString()); + String trimmedErrorString = errorWriter.toString().trim(); + if (!trimmedErrorString.isEmpty()) { + LOGGER.error(trimmedErrorString); } + } + } catch (SQLException e) { + throw new RuntimeSqlException("Failed to execute script.", e); } + } - boolean tableExists(String table) { - try (Connection connection = dataSource.getConnection()) { - connection.setSchema(schema); - SqlRunner runner = new SqlRunner(connection); - String tableSafe = SQLReplacer.getSanitizedTableName(table); - String query = "SELECT 1 FROM " + tableSafe + " LIMIT 1;"; - runner.run(query); - return true; - } catch (Exception e) { - return false; - } - } + private void executeAndCacheScripts(Stream scripts, String cacheKey) { + runScripts( + runner -> + cachedScripts.computeIfAbsent(cacheKey, key -> parseScripts(scripts)).stream() + .map(s -> s.getBytes(StandardCharsets.UTF_8)) + .map(ByteArrayInputStream::new) + .map(s -> new InputStreamReader(s, StandardCharsets.UTF_8)) + .forEach(runner::runScript)); + } - private void runScripts(Consumer consumer) { - try (Connection connection = dataSource.getConnection()) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace(connection.getMetaData().toString()); - } + private ScriptRunner getScriptRunner( + Connection connection, StringWriter outWriter, StringWriter errorWriter) throws SQLException { - StringWriter outWriter = new StringWriter(); - StringWriter errorWriter = new StringWriter(); - - ScriptRunner runner = getScriptRunner(connection, outWriter, errorWriter); - consumer.accept(runner); - runner.closeConnection(); - - if (LOGGER.isTraceEnabled()) { - LOGGER.trace(outWriter.toString()); - String trimmedErrorString = errorWriter.toString().trim(); - if (!trimmedErrorString.isEmpty()) { - LOGGER.error(trimmedErrorString); - } - } - } catch (SQLException e) { - throw new RuntimeSqlException("Failed to execute script.", e); - } - } - - private void executeAndCacheScripts(Stream scripts, String cacheKey) { - runScripts(runner -> cachedScripts.computeIfAbsent(cacheKey, key -> parseScripts(scripts)).stream() - .map(s -> s.getBytes(StandardCharsets.UTF_8)) - .map(ByteArrayInputStream::new) - .map(s -> new InputStreamReader(s, StandardCharsets.UTF_8)) - .forEach(runner::runScript)); - } - - private ScriptRunner getScriptRunner(Connection connection, StringWriter outWriter, - StringWriter errorWriter) throws SQLException { - - PrintWriter logWriter = new PrintWriter(outWriter); - PrintWriter errorLogWriter = new PrintWriter(errorWriter); - ScriptRunner runner = new ScriptRunner(connection); - - connection.setSchema(schema); - runner.setLogWriter(logWriter); - runner.setErrorLogWriter(errorLogWriter); - return runner; - } + PrintWriter logWriter = new PrintWriter(outWriter); + PrintWriter errorLogWriter = new PrintWriter(errorWriter); + ScriptRunner runner = new ScriptRunner(connection); + connection.setSchema(schema); + runner.setLogWriter(logWriter); + runner.setErrorLogWriter(errorLogWriter); + return runner; + } } diff --git a/lib/taskana-data/src/main/java/pro/taskana/sampledata/SampleDataProvider.java b/lib/taskana-data/src/main/java/pro/taskana/sampledata/SampleDataProvider.java index cebecb8a4..04a1da1c1 100644 --- a/lib/taskana-data/src/main/java/pro/taskana/sampledata/SampleDataProvider.java +++ b/lib/taskana-data/src/main/java/pro/taskana/sampledata/SampleDataProvider.java @@ -2,69 +2,68 @@ package pro.taskana.sampledata; import java.util.stream.Stream; -/** - * Provides a sample data set. - */ +/** Provides a sample data set. */ public final class SampleDataProvider { - private static final String DB_CLEAR_TABLES_SCRIPT = "/sql/clear/clear-db.sql"; - private static final String DB_DROP_TABLES_SCRIPT = "/sql/clear/drop-tables.sql"; + static final String TEST_TASK = "/sql/test-data/task.sql"; + static final String TEST_WORKBASKET = "/sql/test-data/workbasket.sql"; + static final String TEST_DISTRIBUTION_TARGETS = "/sql/test-data/distribution-targets.sql"; + static final String TEST_WORKBASKET_ACCESS_LIST = "/sql/test-data/workbasket-access-list.sql"; + static final String TEST_CLASSIFICATION = "/sql/test-data/classification.sql"; + static final String TEST_OBJECT_REFERENCE = "/sql/test-data/object-reference.sql"; + static final String TEST_ATTACHMENT = "/sql/test-data/attachment.sql"; + static final String MONITOR_SAMPLE_DATA = "/sql/monitor-data/monitor-sample-data.sql"; + private static final String DB_CLEAR_TABLES_SCRIPT = "/sql/clear/clear-db.sql"; + private static final String DB_DROP_TABLES_SCRIPT = "/sql/clear/drop-tables.sql"; + private static final String CLEAR_HISTORY_EVENTS = "/sql/clear/clear-history-events.sql"; + private static final String HISTORY_EVENT = "/sql/sample-data/history-event.sql"; + private static final String SAMPLE_TASK = "/sql/sample-data/task.sql"; + private static final String SAMPLE_WORKBASKET = "/sql/sample-data/workbasket.sql"; + private static final String SAMPLE_DISTRIBUTION_TARGETS = + "/sql/sample-data/distribution-targets.sql"; + private static final String SAMPLE_WORKBASKET_ACCESS_LIST = + "/sql/sample-data/workbasket-access-list.sql"; + private static final String SAMPLE_CLASSIFICATION = "/sql/sample-data/classification.sql"; + private static final String SAMPLE_OBJECT_REFERENCE = "/sql/sample-data/object-reference.sql"; + private static final String SAMPLE_ATTACHMENT = "/sql/sample-data/attachment.sql"; - private static final String CLEAR_HISTORY_EVENTS = "/sql/clear/clear-history-events.sql"; - private static final String HISTORY_EVENT = "/sql/sample-data/history-event.sql"; + private SampleDataProvider() {} - private static final String SAMPLE_TASK = "/sql/sample-data/task.sql"; - private static final String SAMPLE_WORKBASKET = "/sql/sample-data/workbasket.sql"; - private static final String SAMPLE_DISTRIBUTION_TARGETS = "/sql/sample-data/distribution-targets.sql"; - private static final String SAMPLE_WORKBASKET_ACCESS_LIST = "/sql/sample-data/workbasket-access-list.sql"; - private static final String SAMPLE_CLASSIFICATION = "/sql/sample-data/classification.sql"; - private static final String SAMPLE_OBJECT_REFERENCE = "/sql/sample-data/object-reference.sql"; - private static final String SAMPLE_ATTACHMENT = "/sql/sample-data/attachment.sql"; + static Stream getDefaultScripts() { + return Stream.of( + SAMPLE_WORKBASKET, + SAMPLE_DISTRIBUTION_TARGETS, + SAMPLE_CLASSIFICATION, + SAMPLE_TASK, + SAMPLE_ATTACHMENT, + SAMPLE_WORKBASKET_ACCESS_LIST, + SAMPLE_OBJECT_REFERENCE); + } - static final String TEST_TASK = "/sql/test-data/task.sql"; - static final String TEST_WORKBASKET = "/sql/test-data/workbasket.sql"; - static final String TEST_DISTRIBUTION_TARGETS = "/sql/test-data/distribution-targets.sql"; - static final String TEST_WORKBASKET_ACCESS_LIST = "/sql/test-data/workbasket-access-list.sql"; - static final String TEST_CLASSIFICATION = "/sql/test-data/classification.sql"; - static final String TEST_OBJECT_REFERENCE = "/sql/test-data/object-reference.sql"; - static final String TEST_ATTACHMENT = "/sql/test-data/attachment.sql"; + static Stream getScriptsWithEvents() { + return Stream.concat(getDefaultScripts(), Stream.of(CLEAR_HISTORY_EVENTS, HISTORY_EVENT)); + } - static final String MONITOR_SAMPLE_DATA = "/sql/monitor-data/monitor-sample-data.sql"; + static Stream getScriptsToClearDatabase() { + return Stream.concat(getDefaultScripts(), Stream.of(DB_CLEAR_TABLES_SCRIPT)); + } - private SampleDataProvider() { - } + static Stream getScriptsToDropDatabase() { + return Stream.concat(getDefaultScripts(), Stream.of(DB_DROP_TABLES_SCRIPT)); + } - static Stream getDefaultScripts() { - return Stream.of( - SAMPLE_WORKBASKET, SAMPLE_DISTRIBUTION_TARGETS, SAMPLE_CLASSIFICATION, SAMPLE_TASK, SAMPLE_ATTACHMENT, - SAMPLE_WORKBASKET_ACCESS_LIST, - SAMPLE_OBJECT_REFERENCE); - } + static Stream getTestDataScripts() { + return Stream.of( + TEST_CLASSIFICATION, + TEST_WORKBASKET, + TEST_TASK, + TEST_WORKBASKET_ACCESS_LIST, + TEST_DISTRIBUTION_TARGETS, + TEST_OBJECT_REFERENCE, + TEST_ATTACHMENT); + } - static Stream getScriptsWithEvents() { - return Stream.concat(getDefaultScripts(), Stream.of(CLEAR_HISTORY_EVENTS, HISTORY_EVENT)); - } - - static Stream getScriptsToClearDatabase() { - return Stream.concat(getDefaultScripts(), Stream.of(DB_CLEAR_TABLES_SCRIPT)); - } - - static Stream getScriptsToDropDatabase() { - return Stream.concat(getDefaultScripts(), Stream.of(DB_DROP_TABLES_SCRIPT)); - } - - static Stream getTestDataScripts() { - return Stream.of( - TEST_CLASSIFICATION, - TEST_WORKBASKET, - TEST_TASK, - TEST_WORKBASKET_ACCESS_LIST, - TEST_DISTRIBUTION_TARGETS, - TEST_OBJECT_REFERENCE, - TEST_ATTACHMENT); - } - - static Stream getMonitorDataScripts() { - return Stream.of(MONITOR_SAMPLE_DATA); - } + static Stream getMonitorDataScripts() { + return Stream.of(MONITOR_SAMPLE_DATA); + } } diff --git a/lib/taskana-data/src/test/java/pro/taskana/sampledata/SQLReplacerTest.java b/lib/taskana-data/src/test/java/pro/taskana/sampledata/SQLReplacerTest.java index 37ef1759f..b10fc548e 100644 --- a/lib/taskana-data/src/test/java/pro/taskana/sampledata/SQLReplacerTest.java +++ b/lib/taskana-data/src/test/java/pro/taskana/sampledata/SQLReplacerTest.java @@ -6,63 +6,57 @@ import static pro.taskana.sampledata.SQLReplacer.RELATIVE_DATE_PATTERN; import java.time.LocalDateTime; import java.util.regex.Matcher; - import org.hamcrest.CoreMatchers; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -/** - * Test SampleDataGenerator. - */ +/** Test SampleDataGenerator. */ class SQLReplacerTest { - @Test - void replaceRelativeTimeFunctionSameDate() { - LocalDateTime now = LocalDateTime.now(); - String dateFormatted = now.format(DATE_TIME_FORMATTER); - String sqlStringReplaced = SQLReplacer.replaceDatePlaceholder(now, - "... RELATIVE_DATE(0) ..."); - assertThat(sqlStringReplaced, CoreMatchers.containsString(dateFormatted)); - } + @Test + void replaceRelativeTimeFunctionSameDate() { + LocalDateTime now = LocalDateTime.now(); + String dateFormatted = now.format(DATE_TIME_FORMATTER); + String sqlStringReplaced = SQLReplacer.replaceDatePlaceholder(now, "... RELATIVE_DATE(0) ..."); + assertThat(sqlStringReplaced, CoreMatchers.containsString(dateFormatted)); + } - @Test - void testDateRegex() { + @Test + void testDateRegex() { - Assertions.assertTrue(RELATIVE_DATE_PATTERN.matcher("RELATIVE_DATE(123)").matches()); + Assertions.assertTrue(RELATIVE_DATE_PATTERN.matcher("RELATIVE_DATE(123)").matches()); - Assertions.assertTrue(RELATIVE_DATE_PATTERN.matcher("... RELATIVE_DATE(5) ...").find()); - Assertions.assertTrue(RELATIVE_DATE_PATTERN.matcher("... RELATIVE_DATE(0) ...").find()); - Assertions.assertTrue(RELATIVE_DATE_PATTERN.matcher("... RELATIVE_DATE(-123) ...").find()); + Assertions.assertTrue(RELATIVE_DATE_PATTERN.matcher("... RELATIVE_DATE(5) ...").find()); + Assertions.assertTrue(RELATIVE_DATE_PATTERN.matcher("... RELATIVE_DATE(0) ...").find()); + Assertions.assertTrue(RELATIVE_DATE_PATTERN.matcher("... RELATIVE_DATE(-123) ...").find()); - Assertions.assertFalse(RELATIVE_DATE_PATTERN.matcher("... RELATIVE_DATE() ...").find()); - Assertions.assertFalse(RELATIVE_DATE_PATTERN.matcher("... RELATIVE_DATE(ABCDE) ...").find()); - Assertions.assertFalse(RELATIVE_DATE_PATTERN.matcher("... RELATIVE_NO(5) ...").find()); - Assertions.assertFalse(RELATIVE_DATE_PATTERN.matcher("...").find()); - } + Assertions.assertFalse(RELATIVE_DATE_PATTERN.matcher("... RELATIVE_DATE() ...").find()); + Assertions.assertFalse(RELATIVE_DATE_PATTERN.matcher("... RELATIVE_DATE(ABCDE) ...").find()); + Assertions.assertFalse(RELATIVE_DATE_PATTERN.matcher("... RELATIVE_NO(5) ...").find()); + Assertions.assertFalse(RELATIVE_DATE_PATTERN.matcher("...").find()); + } - @Test - void testDateRegexExtractGroup() { - Matcher matcher = RELATIVE_DATE_PATTERN.matcher("RELATIVE_DATE(123)"); - Assertions.assertTrue(matcher.find()); - Assertions.assertEquals("123", matcher.group(1)); - } + @Test + void testDateRegexExtractGroup() { + Matcher matcher = RELATIVE_DATE_PATTERN.matcher("RELATIVE_DATE(123)"); + Assertions.assertTrue(matcher.find()); + Assertions.assertEquals("123", matcher.group(1)); + } - @Test - void replaceRelativeTimeFunctionPosDate() { - LocalDateTime now = LocalDateTime.now(); - String dateFormatted = now.plusDays(5).format(DATE_TIME_FORMATTER); - String sqlStringReplaced = SQLReplacer.replaceDatePlaceholder(now, - "... RELATIVE_DATE(5) ..."); - assertThat(sqlStringReplaced, CoreMatchers.containsString(dateFormatted)); - } - - @Test - void replaceRelativeTimeFunctionNegDate() { - LocalDateTime now = LocalDateTime.now(); - String dateFormatted = now.plusDays(-10).format(DATE_TIME_FORMATTER); - String sqlStringReplaced = SQLReplacer.replaceDatePlaceholder(now, - "... RELATIVE_DATE(-10) ..."); - assertThat(sqlStringReplaced, CoreMatchers.containsString(dateFormatted)); - } + @Test + void replaceRelativeTimeFunctionPosDate() { + LocalDateTime now = LocalDateTime.now(); + String dateFormatted = now.plusDays(5).format(DATE_TIME_FORMATTER); + String sqlStringReplaced = SQLReplacer.replaceDatePlaceholder(now, "... RELATIVE_DATE(5) ..."); + assertThat(sqlStringReplaced, CoreMatchers.containsString(dateFormatted)); + } + @Test + void replaceRelativeTimeFunctionNegDate() { + LocalDateTime now = LocalDateTime.now(); + String dateFormatted = now.plusDays(-10).format(DATE_TIME_FORMATTER); + String sqlStringReplaced = + SQLReplacer.replaceDatePlaceholder(now, "... RELATIVE_DATE(-10) ..."); + assertThat(sqlStringReplaced, CoreMatchers.containsString(dateFormatted)); + } } diff --git a/lib/taskana-data/src/test/java/pro/taskana/sampledata/SampleDataProviderTest.java b/lib/taskana-data/src/test/java/pro/taskana/sampledata/SampleDataProviderTest.java index 0d8242f87..95094af08 100644 --- a/lib/taskana-data/src/test/java/pro/taskana/sampledata/SampleDataProviderTest.java +++ b/lib/taskana-data/src/test/java/pro/taskana/sampledata/SampleDataProviderTest.java @@ -3,28 +3,25 @@ package pro.taskana.sampledata; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -/** - * Test SampleDataGenerator. - */ +/** Test SampleDataGenerator. */ class SampleDataProviderTest { - @Test - void getScriptsNotNull() { - Assertions.assertNotNull(SampleDataProvider.getDefaultScripts()); - Assertions.assertNotNull(SampleDataProvider.getScriptsWithEvents()); - } + @Test + void getScriptsNotNull() { + Assertions.assertNotNull(SampleDataProvider.getDefaultScripts()); + Assertions.assertNotNull(SampleDataProvider.getScriptsWithEvents()); + } - @Test - void getScriptsNotEmpty() { - Assertions.assertTrue(SampleDataProvider.getDefaultScripts().count() > 0); - Assertions.assertTrue(SampleDataProvider.getScriptsWithEvents().count() > 0); - } - - @Test - void getScriptsFileExists() { - SampleDataProvider.getDefaultScripts() - .map(SQLReplacer::getScriptBufferedStream) - .forEach(Assertions::assertNotNull); - } + @Test + void getScriptsNotEmpty() { + Assertions.assertTrue(SampleDataProvider.getDefaultScripts().count() > 0); + Assertions.assertTrue(SampleDataProvider.getScriptsWithEvents().count() > 0); + } + @Test + void getScriptsFileExists() { + SampleDataProvider.getDefaultScripts() + .map(SQLReplacer::getScriptBufferedStream) + .forEach(Assertions::assertNotNull); + } } diff --git a/lib/taskana-spring-example/src/main/java/pro/taskana/ExampleBootstrap.java b/lib/taskana-spring-example/src/main/java/pro/taskana/ExampleBootstrap.java index 3074fe674..44c8c3ad1 100644 --- a/lib/taskana-spring-example/src/main/java/pro/taskana/ExampleBootstrap.java +++ b/lib/taskana-spring-example/src/main/java/pro/taskana/ExampleBootstrap.java @@ -1,7 +1,6 @@ package pro.taskana; import javax.annotation.PostConstruct; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; @@ -19,52 +18,49 @@ import pro.taskana.exceptions.TaskNotFoundException; import pro.taskana.exceptions.WorkbasketAlreadyExistException; import pro.taskana.exceptions.WorkbasketNotFoundException; -/** - * TODO. - */ +/** TODO. */ @Component @Transactional public class ExampleBootstrap { - @Autowired - private TaskService taskService; + @Autowired private TaskService taskService; - @Autowired - private TaskanaEngine taskanaEngine; + @Autowired private TaskanaEngine taskanaEngine; - @PostConstruct - public void test() throws TaskNotFoundException, NotAuthorizedException, WorkbasketNotFoundException, - ClassificationNotFoundException, InvalidStateException, InvalidOwnerException, TaskAlreadyExistException, - InvalidArgumentException, DomainNotFoundException, InvalidWorkbasketException, WorkbasketAlreadyExistException, - ClassificationAlreadyExistException { - System.out.println("---------------------------> Start App"); + @PostConstruct + public void test() + throws TaskNotFoundException, NotAuthorizedException, WorkbasketNotFoundException, + ClassificationNotFoundException, InvalidStateException, InvalidOwnerException, + TaskAlreadyExistException, InvalidArgumentException, DomainNotFoundException, + InvalidWorkbasketException, WorkbasketAlreadyExistException, + ClassificationAlreadyExistException { + System.out.println("---------------------------> Start App"); - Workbasket wb = taskanaEngine.getWorkbasketService().newWorkbasket("workbasket", "DOMAIN_A"); - wb.setName("workbasket"); - wb.setType(WorkbasketType.GROUP); - taskanaEngine.getWorkbasketService().createWorkbasket(wb); - Classification classification = taskanaEngine.getClassificationService().newClassification("TEST", - "DOMAIN_A", - "TASK"); - taskanaEngine.getClassificationService().createClassification(classification); - - Task task = taskanaEngine.getTaskService().newTask(wb.getId()); - task.setName("Spring example task"); - task.setClassificationKey(classification.getKey()); - ObjectReference objRef = new ObjectReference(); - objRef.setCompany("aCompany"); - objRef.setSystem("aSystem"); - objRef.setSystemInstance("anInstance"); - objRef.setType("aType"); - objRef.setValue("aValue"); - task.setPrimaryObjRef(objRef); - task = taskService.createTask(task); - System.out.println("---------------------------> Task started: " + task.getId()); - taskService.claim(task.getId()); - System.out.println( - "---------------------------> Task claimed: " + taskService.getTask(task.getId()).getOwner()); - taskService.forceCompleteTask(task.getId()); - System.out.println("---------------------------> Task completed"); - } + Workbasket wb = taskanaEngine.getWorkbasketService().newWorkbasket("workbasket", "DOMAIN_A"); + wb.setName("workbasket"); + wb.setType(WorkbasketType.GROUP); + taskanaEngine.getWorkbasketService().createWorkbasket(wb); + Classification classification = + taskanaEngine.getClassificationService().newClassification("TEST", "DOMAIN_A", "TASK"); + taskanaEngine.getClassificationService().createClassification(classification); + Task task = taskanaEngine.getTaskService().newTask(wb.getId()); + task.setName("Spring example task"); + task.setClassificationKey(classification.getKey()); + ObjectReference objRef = new ObjectReference(); + objRef.setCompany("aCompany"); + objRef.setSystem("aSystem"); + objRef.setSystemInstance("anInstance"); + objRef.setType("aType"); + objRef.setValue("aValue"); + task.setPrimaryObjRef(objRef); + task = taskService.createTask(task); + System.out.println("---------------------------> Task started: " + task.getId()); + taskService.claim(task.getId()); + System.out.println( + "---------------------------> Task claimed: " + + taskService.getTask(task.getId()).getOwner()); + taskService.forceCompleteTask(task.getId()); + System.out.println("---------------------------> Task completed"); + } } diff --git a/lib/taskana-spring-example/src/main/java/pro/taskana/TaskanaConfig.java b/lib/taskana-spring-example/src/main/java/pro/taskana/TaskanaConfig.java index 6457b69dd..99584cef4 100644 --- a/lib/taskana-spring-example/src/main/java/pro/taskana/TaskanaConfig.java +++ b/lib/taskana-spring-example/src/main/java/pro/taskana/TaskanaConfig.java @@ -1,9 +1,7 @@ package pro.taskana; import java.sql.SQLException; - import javax.sql.DataSource; - import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -17,82 +15,76 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; import pro.taskana.configuration.SpringTaskanaEngineConfiguration; -/** - * Class to set /load configuration for Taskana Library. - * - */ +/** Class to set /load configuration for Taskana Library. */ @Configuration @EnableTransactionManagement() public class TaskanaConfig { - @Value("${taskana.schemaName:TASKANA}") - private String schemaName; + @Value("${taskana.schemaName:TASKANA}") + private String schemaName; - /** - * TODO. - */ - @Profile("inmemorydb") - @Configuration - @PropertySource("classpath:customdb.properties") - static class InmemoryDBProperties { - } + @Bean + @Primary + @ConfigurationProperties(prefix = "customdb.datasource") + public DataSourceProperties dataSourceProperties() { + return new DataSourceProperties(); + } - @Bean - @Primary - @ConfigurationProperties(prefix = "customdb.datasource") - public DataSourceProperties dataSourceProperties() { - return new DataSourceProperties(); - } + @Bean + @Primary + public DataSource dataSource(DataSourceProperties properties) { + DataSource dataSource = properties.initializeDataSourceBuilder().build(); + // if TaskanaEngineImpl runs with SpringManagedTransactionFactory, then + // there is no need to wrap the dataSource into TransactionAwareDataSourceProxy ... + // return new TransactionAwareDataSourceProxy(dataSource); + return dataSource; + } - @Bean - @Primary - public DataSource dataSource(DataSourceProperties properties) { - DataSource dataSource = properties. - initializeDataSourceBuilder().build(); - // if TaskanaEngineImpl runs with SpringManagedTransactionFactory, then - // there is no need to wrap the dataSource into TransactionAwareDataSourceProxy ... - // return new TransactionAwareDataSourceProxy(dataSource); - return dataSource; - } + @Bean + public DataSourceTransactionManager transactionManager(DataSource dataSource) { + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(); + transactionManager.setDataSource(dataSource); + return transactionManager; + } - @Bean - public DataSourceTransactionManager transactionManager(DataSource dataSource) { - DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(); - transactionManager.setDataSource(dataSource); - return transactionManager; - } + @Bean + public SpringTaskanaEngineConfiguration taskanaEngineConfiguration(DataSource dataSource) + throws SQLException { + SpringTaskanaEngineConfiguration taskanaEngineConfiguration = + new SpringTaskanaEngineConfiguration(dataSource, true, false, schemaName); + return taskanaEngineConfiguration; + } - @Bean - public SpringTaskanaEngineConfiguration taskanaEngineConfiguration(DataSource dataSource) throws SQLException { - SpringTaskanaEngineConfiguration taskanaEngineConfiguration = new SpringTaskanaEngineConfiguration(dataSource, - true, false, schemaName); - return taskanaEngineConfiguration; - } + @Bean + public TaskanaEngine taskanaEngine(SpringTaskanaEngineConfiguration taskanaEngineConfiguration) { + TaskanaEngine taskanaEngine = taskanaEngineConfiguration.buildTaskanaEngine(); + // taskanaEngine.setConnectionManagementMode(TaskanaEngine.ConnectionManagementMode.EXPLICIT); + return taskanaEngine; + } - @Bean - public TaskanaEngine taskanaEngine(SpringTaskanaEngineConfiguration taskanaEngineConfiguration) { - TaskanaEngine taskanaEngine = taskanaEngineConfiguration.buildTaskanaEngine(); - // taskanaEngine.setConnectionManagementMode(TaskanaEngine.ConnectionManagementMode.EXPLICIT); - return taskanaEngine; - } + @Bean + public WorkbasketService workbasketService(TaskanaEngine taskanaEngine) { + return taskanaEngine.getWorkbasketService(); + } - @Bean - public WorkbasketService workbasketService(TaskanaEngine taskanaEngine) { - return taskanaEngine.getWorkbasketService(); - } + @Bean + public TaskService taskService(TaskanaEngine taskanaEngine) { + return taskanaEngine.getTaskService(); + } - @Bean - public TaskService taskService(TaskanaEngine taskanaEngine) { - return taskanaEngine.getTaskService(); - } + @Bean + public ClassificationService classificationService(TaskanaEngine taskanaEngine) { + return taskanaEngine.getClassificationService(); + } - @Bean - public ClassificationService classificationService(TaskanaEngine taskanaEngine) { - return taskanaEngine.getClassificationService(); - } + @Bean + public ExampleBootstrap exampleBootstrap() { + return new ExampleBootstrap(); + } - @Bean - public ExampleBootstrap exampleBootstrap() { - return new ExampleBootstrap(); - } + /** TODO. */ + @Profile("inmemorydb") + @Configuration + @PropertySource("classpath:customdb.properties") + static class InmemoryDBProperties {} } diff --git a/lib/taskana-spring-example/src/main/java/pro/taskana/TaskanaConfigTestApplication.java b/lib/taskana-spring-example/src/main/java/pro/taskana/TaskanaConfigTestApplication.java index 486b23bdb..0fd66c482 100644 --- a/lib/taskana-spring-example/src/main/java/pro/taskana/TaskanaConfigTestApplication.java +++ b/lib/taskana-spring-example/src/main/java/pro/taskana/TaskanaConfigTestApplication.java @@ -4,16 +4,13 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.Import; -/** - * Class to start an Application to test Taskana. - * - */ +/** Class to start an Application to test Taskana. */ @SpringBootApplication @Import(TaskanaConfig.class) @SuppressWarnings("checkstyle:hideutilityclassconstructor") public class TaskanaConfigTestApplication { - public static void main(String[] args) { - new SpringApplicationBuilder(TaskanaConfigTestApplication.class).run(args); - } + public static void main(String[] args) { + new SpringApplicationBuilder(TaskanaConfigTestApplication.class).run(args); + } } diff --git a/lib/taskana-spring-example/src/main/java/pro/taskana/TaskanaTestController.java b/lib/taskana-spring-example/src/main/java/pro/taskana/TaskanaTestController.java index 675d1bd07..b14edcec3 100644 --- a/lib/taskana-spring-example/src/main/java/pro/taskana/TaskanaTestController.java +++ b/lib/taskana-spring-example/src/main/java/pro/taskana/TaskanaTestController.java @@ -15,114 +15,112 @@ import pro.taskana.exceptions.WorkbasketAlreadyExistException; import pro.taskana.impl.WorkbasketImpl; import pro.taskana.impl.util.IdGenerator; -/** - * Rest Controller. - */ +/** Rest Controller. */ @RestController public class TaskanaTestController { - @Autowired - private JdbcTemplate jdbcTemplate; + @Autowired private JdbcTemplate jdbcTemplate; - @Autowired - private TaskanaEngine taskanaEngine; + @Autowired private TaskanaEngine taskanaEngine; - @Transactional(rollbackFor = Exception.class) - @RequestMapping("/schema") - public @ResponseBody String schema() { - String schema = jdbcTemplate.queryForObject("SELECT SCHEMA()", String.class); - System.err.println("current schema: " + schema); - return schema; + @Transactional(rollbackFor = Exception.class) + @RequestMapping("/schema") + public @ResponseBody String schema() { + String schema = jdbcTemplate.queryForObject("SELECT SCHEMA()", String.class); + System.err.println("current schema: " + schema); + return schema; + } + + @Transactional(readOnly = true, rollbackFor = Exception.class) + @RequestMapping("/workbaskets") + public @ResponseBody Integer workbaskets() { + return getWorkbaskets(); + } + + @Transactional(readOnly = true, rollbackFor = Exception.class) + @RequestMapping("/customdb-tests") + public @ResponseBody Integer customdbTests() { + return getCustomdbTests(); + } + + @Transactional(rollbackFor = Exception.class) + @RequestMapping("/transaction") + public @ResponseBody String transaction( + @RequestParam(value = "rollback", defaultValue = "false") String rollback) + throws InvalidWorkbasketException, NotAuthorizedException, WorkbasketAlreadyExistException, + DomainNotFoundException { + taskanaEngine.getWorkbasketService().createWorkbasket(createWorkBasket("key", "workbasket")); + + int workbaskets = getWorkbaskets(); + if (Boolean.valueOf(rollback)) { + throw new RuntimeException("workbaskets: " + workbaskets); + } else { + return "workbaskets: " + workbaskets; } + } - @Transactional(readOnly = true, rollbackFor = Exception.class) - @RequestMapping("/workbaskets") - public @ResponseBody Integer workbaskets() { - return getWorkbaskets(); + @Transactional(rollbackFor = Exception.class) + @RequestMapping("/transaction-many") + public @ResponseBody String transactionMany( + @RequestParam(value = "rollback", defaultValue = "false") String rollback) + throws InvalidWorkbasketException, NotAuthorizedException, WorkbasketAlreadyExistException, + DomainNotFoundException { + taskanaEngine.getWorkbasketService().createWorkbasket(createWorkBasket("key1", "workbasket1")); + taskanaEngine.getWorkbasketService().createWorkbasket(createWorkBasket("key2", "workbasket2")); + taskanaEngine.getWorkbasketService().createWorkbasket(createWorkBasket("key3", "workbasket3")); + + if (Boolean.valueOf(rollback)) { + throw new RuntimeException("workbaskets: " + getWorkbaskets()); + } else { + return "workbaskets: " + getWorkbaskets(); } + } - @Transactional(readOnly = true, rollbackFor = Exception.class) - @RequestMapping("/customdb-tests") - public @ResponseBody Integer customdbTests() { - return getCustomdbTests(); + @Transactional(rollbackFor = Exception.class) + @RequestMapping("/customdb") + public @ResponseBody String transactionCustomdb( + @RequestParam(value = "rollback", defaultValue = "false") String rollback) + throws InvalidWorkbasketException, NotAuthorizedException, WorkbasketAlreadyExistException, + DomainNotFoundException { + taskanaEngine.getWorkbasketService().createWorkbasket(createWorkBasket("key1", "workbasket1")); + taskanaEngine.getWorkbasketService().createWorkbasket(createWorkBasket("key2", "workbasket2")); + + jdbcTemplate.execute("INSERT INTO CUSTOMDB.TEST VALUES ('1', 'test')"); + jdbcTemplate.execute("INSERT INTO CUSTOMDB.TEST VALUES ('2', 'test2')"); + + if (Boolean.valueOf(rollback)) { + throw new RuntimeException( + "workbaskets: " + getWorkbaskets() + ", tests: " + getCustomdbTests()); + } else { + return "workbaskets: " + getWorkbaskets() + ", tests: " + getCustomdbTests(); } + } - @Transactional(rollbackFor = Exception.class) - @RequestMapping("/transaction") - public @ResponseBody String transaction(@RequestParam(value = "rollback", defaultValue = "false") String rollback) - throws InvalidWorkbasketException, NotAuthorizedException, - WorkbasketAlreadyExistException, DomainNotFoundException { - taskanaEngine.getWorkbasketService().createWorkbasket(createWorkBasket("key", "workbasket")); + @Transactional(rollbackFor = Exception.class) + @RequestMapping("/cleanup") + public @ResponseBody String cleanup() { + jdbcTemplate.execute("DELETE FROM WORKBASKET"); + jdbcTemplate.execute("DELETE FROM CUSTOMDB.TEST"); + System.err.println("cleaned workbasket and test tables"); + return "cleaned workbasket and test tables"; + } - int workbaskets = getWorkbaskets(); - if (Boolean.valueOf(rollback)) { - throw new RuntimeException("workbaskets: " + workbaskets); - } else { - return "workbaskets: " + workbaskets; - } - } + private int getWorkbaskets() { + // return taskanaEngine.getWorkbasketService().getWorkbaskets().size(); + return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM WORKBASKET", Integer.class); + } - @Transactional(rollbackFor = Exception.class) - @RequestMapping("/transaction-many") - public @ResponseBody String transactionMany( - @RequestParam(value = "rollback", defaultValue = "false") String rollback) - throws InvalidWorkbasketException, NotAuthorizedException, - WorkbasketAlreadyExistException, DomainNotFoundException { - taskanaEngine.getWorkbasketService().createWorkbasket(createWorkBasket("key1", "workbasket1")); - taskanaEngine.getWorkbasketService().createWorkbasket(createWorkBasket("key2", "workbasket2")); - taskanaEngine.getWorkbasketService().createWorkbasket(createWorkBasket("key3", "workbasket3")); + private int getCustomdbTests() { + return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM CUSTOMDB.TEST", Integer.class); + } - if (Boolean.valueOf(rollback)) { - throw new RuntimeException("workbaskets: " + getWorkbaskets()); - } else { - return "workbaskets: " + getWorkbaskets(); - } - } - - @Transactional(rollbackFor = Exception.class) - @RequestMapping("/customdb") - public @ResponseBody String transactionCustomdb( - @RequestParam(value = "rollback", defaultValue = "false") String rollback) - throws InvalidWorkbasketException, NotAuthorizedException, - WorkbasketAlreadyExistException, DomainNotFoundException { - taskanaEngine.getWorkbasketService().createWorkbasket(createWorkBasket("key1", "workbasket1")); - taskanaEngine.getWorkbasketService().createWorkbasket(createWorkBasket("key2", "workbasket2")); - - jdbcTemplate.execute("INSERT INTO CUSTOMDB.TEST VALUES ('1', 'test')"); - jdbcTemplate.execute("INSERT INTO CUSTOMDB.TEST VALUES ('2', 'test2')"); - - if (Boolean.valueOf(rollback)) { - throw new RuntimeException("workbaskets: " + getWorkbaskets() + ", tests: " + getCustomdbTests()); - } else { - return "workbaskets: " + getWorkbaskets() + ", tests: " + getCustomdbTests(); - } - } - - @Transactional(rollbackFor = Exception.class) - @RequestMapping("/cleanup") - public @ResponseBody String cleanup() { - jdbcTemplate.execute("DELETE FROM WORKBASKET"); - jdbcTemplate.execute("DELETE FROM CUSTOMDB.TEST"); - System.err.println("cleaned workbasket and test tables"); - return "cleaned workbasket and test tables"; - } - - private int getWorkbaskets() { - // return taskanaEngine.getWorkbasketService().getWorkbaskets().size(); - return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM WORKBASKET", Integer.class); - } - - private int getCustomdbTests() { - return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM CUSTOMDB.TEST", Integer.class); - } - - private Workbasket createWorkBasket(String key, String name) { - WorkbasketImpl workbasket = (WorkbasketImpl) taskanaEngine.getWorkbasketService().newWorkbasket(key, - "DOMAIN_A"); - String id1 = IdGenerator.generateWithPrefix("TWB"); - workbasket.setId(id1); - workbasket.setName(name); - workbasket.setType(WorkbasketType.GROUP); - return workbasket; - } + private Workbasket createWorkBasket(String key, String name) { + WorkbasketImpl workbasket = + (WorkbasketImpl) taskanaEngine.getWorkbasketService().newWorkbasket(key, "DOMAIN_A"); + String id1 = IdGenerator.generateWithPrefix("TWB"); + workbasket.setId(id1); + workbasket.setName(name); + workbasket.setType(WorkbasketType.GROUP); + return workbasket; + } } diff --git a/lib/taskana-spring-example/src/test/java/pro/taskana/TaskanaTransactionIntTest.java b/lib/taskana-spring-example/src/test/java/pro/taskana/TaskanaTransactionIntTest.java index 4ead65a20..0c3b28fa3 100644 --- a/lib/taskana-spring-example/src/test/java/pro/taskana/TaskanaTransactionIntTest.java +++ b/lib/taskana-spring-example/src/test/java/pro/taskana/TaskanaTransactionIntTest.java @@ -11,9 +11,7 @@ import static org.junit.Assert.assertThat; import java.sql.Connection; import java.sql.SQLException; import java.util.List; - import javax.sql.DataSource; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -40,260 +38,264 @@ import pro.taskana.jobs.TaskCleanupJob; import pro.taskana.jobs.WorkbasketCleanupJob; import pro.taskana.transaction.TaskanaTransactionProvider; -/** - * - */ +/** */ @ExtendWith(SpringExtension.class) -@SpringBootTest(classes = TaskanaConfigTestApplication.class, +@SpringBootTest( + classes = TaskanaConfigTestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles({"inmemorydb", "dev"}) @Import({TransactionalJobsConfiguration.class}) class TaskanaTransactionIntTest { - private static final int POOL_TIME_TO_WAIT = 50; - @Autowired - TaskanaTransactionProvider springTransactionProvider; - @Autowired - private TestRestTemplate restTemplate; - @Autowired - private DataSource dataSource; - @Autowired - private JdbcTemplate jdbcTemplate; - @Autowired - private TaskanaEngine taskanaEngine; + private static final int POOL_TIME_TO_WAIT = 50; + @Autowired TaskanaTransactionProvider springTransactionProvider; + @Autowired private TestRestTemplate restTemplate; + @Autowired private DataSource dataSource; + @Autowired private JdbcTemplate jdbcTemplate; + @Autowired private TaskanaEngine taskanaEngine; - private static ObjectReference createDefaultObjRef() { - ObjectReference objRef = new ObjectReference(); - objRef.setCompany("company"); - objRef.setSystem("system"); - objRef.setSystemInstance("instance"); - objRef.setType("type"); - objRef.setValue("value"); - return objRef; - } + @BeforeEach + void before() { + JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); + jdbcTemplate.execute("DELETE FROM TASK"); + jdbcTemplate.execute("DELETE FROM WORKBASKET"); + jdbcTemplate.execute("DELETE FROM CUSTOMDB.TEST"); + } - @BeforeEach - void before() { - JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); - jdbcTemplate.execute("DELETE FROM TASK"); - jdbcTemplate.execute("DELETE FROM WORKBASKET"); - jdbcTemplate.execute("DELETE FROM CUSTOMDB.TEST"); - } + @Test + void testTaskanaSchema() { + ResponseEntity responseEntity = restTemplate.getForEntity("/schema", String.class); + assertThat(responseEntity.getBody(), is("TASKANA")); + } - @Test - void testTaskanaSchema() { - ResponseEntity responseEntity = restTemplate.getForEntity("/schema", String.class); - assertThat(responseEntity.getBody(), is("TASKANA")); - } + @Test + void testTransaction() { + assertBefore(0, 0); - @Test - void testTransaction() { - assertBefore(0, 0); + ResponseEntity responseEntity = restTemplate.getForEntity("/transaction", String.class); + System.err.println("response: " + responseEntity.getBody()); + assertThat(responseEntity.getBody(), containsString("workbaskets: 1")); - ResponseEntity responseEntity = restTemplate.getForEntity("/transaction", String.class); - System.err.println("response: " + responseEntity.getBody()); - assertThat(responseEntity.getBody(), containsString("workbaskets: 1")); + assertAfter(1, 0); + } - assertAfter(1, 0); - } + @Test + void testTransactionRollback() { + assertBefore(0, 0); - @Test - void testTransactionRollback() { - assertBefore(0, 0); + ResponseEntity responseEntity = + restTemplate.getForEntity("/transaction?rollback={rollback}", String.class, "true"); + System.err.println("result: " + responseEntity.getBody()); + assertThat(responseEntity.getBody(), containsString("workbaskets: 1")); - ResponseEntity responseEntity = restTemplate.getForEntity("/transaction?rollback={rollback}", - String.class, "true"); - System.err.println("result: " + responseEntity.getBody()); - assertThat(responseEntity.getBody(), containsString("workbaskets: 1")); + assertAfter(0, 0); + } - assertAfter(0, 0); - } + @Test + void testTransactionCombined() { + assertBefore(0, 0); - @Test - void testTransactionCombined() { - assertBefore(0, 0); + ResponseEntity responseEntity = + restTemplate.getForEntity("/transaction-many", String.class); + System.err.println("response: " + responseEntity.getBody()); + assertThat(responseEntity.getBody(), containsString("workbaskets: 3")); - ResponseEntity responseEntity = restTemplate.getForEntity("/transaction-many", String.class); - System.err.println("response: " + responseEntity.getBody()); - assertThat(responseEntity.getBody(), containsString("workbaskets: 3")); + assertAfter(3, 0); + } - assertAfter(3, 0); - } + @Test + void testTransactionCombinedRollback() { + assertBefore(0, 0); - @Test - void testTransactionCombinedRollback() { - assertBefore(0, 0); + ResponseEntity responseEntity = + restTemplate.getForEntity("/transaction-many?rollback={rollback}", String.class, "true"); + System.err.println("result: " + responseEntity.getBody()); + assertThat(responseEntity.getBody(), containsString("workbaskets: 3")); - ResponseEntity responseEntity = restTemplate.getForEntity("/transaction-many?rollback={rollback}", - String.class, "true"); - System.err.println("result: " + responseEntity.getBody()); - assertThat(responseEntity.getBody(), containsString("workbaskets: 3")); + assertAfter(0, 0); + } - assertAfter(0, 0); - } + @Test + void testTransactionCustomdb() { + assertBefore(0, 0); - @Test - void testTransactionCustomdb() { - assertBefore(0, 0); + ResponseEntity responseEntity = restTemplate.getForEntity("/customdb", String.class); + System.err.println("response: " + responseEntity.getBody()); + assertThat(responseEntity.getBody(), containsString("workbaskets: 2")); + assertThat(responseEntity.getBody(), containsString("tests: 2")); - ResponseEntity responseEntity = restTemplate.getForEntity("/customdb", String.class); - System.err.println("response: " + responseEntity.getBody()); - assertThat(responseEntity.getBody(), containsString("workbaskets: 2")); - assertThat(responseEntity.getBody(), containsString("tests: 2")); + assertAfter(2, 2); + } - assertAfter(2, 2); + @Test + void testTransactionCustomdbRollback() { + assertBefore(0, 0); - } + ResponseEntity responseEntity = + restTemplate.getForEntity("/customdb?rollback={rollback}", String.class, "true"); + System.err.println("response: " + responseEntity.getBody()); + assertThat(responseEntity.getBody(), containsString("workbaskets: 2")); + assertThat(responseEntity.getBody(), containsString("tests: 2")); - @Test - void testTransactionCustomdbRollback() { - assertBefore(0, 0); + assertAfter(0, 0); + } - ResponseEntity responseEntity = restTemplate.getForEntity("/customdb?rollback={rollback}", - String.class, "true"); - System.err.println("response: " + responseEntity.getBody()); - assertThat(responseEntity.getBody(), containsString("workbaskets: 2")); - assertThat(responseEntity.getBody(), containsString("tests: 2")); + @Test + void testTransactionCustomDbWithSchemaSetToTaskana() + throws SQLException, NotAuthorizedException, WorkbasketNotFoundException, + DomainNotFoundException, InvalidWorkbasketException, WorkbasketAlreadyExistException { - assertAfter(0, 0); - } + TaskanaEngineImpl taskanaEngineImpl = (TaskanaEngineImpl) taskanaEngine; + Connection connection = dataSource.getConnection(); - @Test - void testTransactionCustomDbWithSchemaSetToTaskana() - throws SQLException, NotAuthorizedException, WorkbasketNotFoundException, DomainNotFoundException, - InvalidWorkbasketException, WorkbasketAlreadyExistException { - - TaskanaEngineImpl taskanaEngineImpl = (TaskanaEngineImpl) taskanaEngine; - Connection connection = dataSource.getConnection(); - - assertNotEquals(connection.getSchema(), "PUBLIC"); - jdbcTemplate.execute("INSERT INTO CUSTOMDB.TEST VALUES ('1', 'test')"); - jdbcTemplate.execute("INSERT INTO CUSTOMDB.TEST VALUES ('2', 'test2')"); - int result = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM CUSTOMDB.TEST", Integer.class); - assertEquals(2, result); - Workbasket wbCreated = taskanaEngine.getWorkbasketService() + assertNotEquals(connection.getSchema(), "PUBLIC"); + jdbcTemplate.execute("INSERT INTO CUSTOMDB.TEST VALUES ('1', 'test')"); + jdbcTemplate.execute("INSERT INTO CUSTOMDB.TEST VALUES ('2', 'test2')"); + int result = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM CUSTOMDB.TEST", Integer.class); + assertEquals(2, result); + Workbasket wbCreated = + taskanaEngine + .getWorkbasketService() .createWorkbasket(createWorkBasket("key1", "workbasket1")); - Workbasket wb = taskanaEngineImpl.getWorkbasketService().getWorkbasket(wbCreated.getId()); - assertNotNull(wb); - result = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM CUSTOMDB.TEST", Integer.class); - assertEquals(2, result); + Workbasket wb = taskanaEngineImpl.getWorkbasketService().getWorkbasket(wbCreated.getId()); + assertNotNull(wb); + result = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM CUSTOMDB.TEST", Integer.class); + assertEquals(2, result); + } + + @Test + void testWorkbasketCleanupJobTransaction() { + try { + + WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); + workbasketService.createWorkbasket(createWorkBasket("key1", "wb1")); + workbasketService.createWorkbasket(createWorkBasket("key2", "wb2")); + workbasketService.createWorkbasket(createWorkBasket("key3", "wb3")); + TaskService taskService = taskanaEngine.getTaskService(); + ClassificationService classificationService = taskanaEngine.getClassificationService(); + classificationService.newClassification("TEST", "DOMAIN_A", "TASK"); + taskService.createTask(createTask("key1", "TEST")); + taskService.createTask(createTask("key2", "TEST")); + taskService.createTask(createTask("key3", "TEST")); + + assertEquals(workbasketService.createWorkbasketQuery().count(), 3); + assertEquals(taskService.createTaskQuery().count(), 3); + + List tasks = + taskService + .createTaskQuery() + .workbasketKeyDomainIn(new KeyDomain("key1", "DOMAIN_A")) + .list(); + taskService.claim(tasks.get(0).getTaskId()); + taskService.completeTask(tasks.get(0).getTaskId()); + tasks = + taskService + .createTaskQuery() + .workbasketKeyDomainIn(new KeyDomain("key2", "DOMAIN_A")) + .list(); + taskService.claim(tasks.get(0).getTaskId()); + taskService.completeTask(tasks.get(0).getTaskId()); + workbasketService.deleteWorkbasket( + workbasketService.getWorkbasket("key1", "DOMAIN_A").getId()); + workbasketService.deleteWorkbasket( + workbasketService.getWorkbasket("key2", "DOMAIN_A").getId()); + + // Clean two tasks, key1 and key2. + TaskCleanupJob taskCleanupJob = + new TaskCleanupJob(taskanaEngine, springTransactionProvider, null); + taskCleanupJob.run(); + + tasks = + taskService + .createTaskQuery() + .workbasketKeyDomainIn(new KeyDomain("key3", "DOMAIN_A")) + .list(); + taskService.claim(tasks.get(0).getTaskId()); + taskService.completeTask(tasks.get(0).getTaskId()); + + try { + workbasketService.deleteWorkbasket( + workbasketService.getWorkbasket("key3", "DOMAIN_A").getId()); + } catch (TaskanaException ex) { + assertEquals(ex.getMessage().contains("contains non-completed tasks"), true); + } + + WorkbasketCleanupJob job = + new WorkbasketCleanupJob(taskanaEngine, springTransactionProvider, null); + job.run(); + + assertNull(workbasketService.getWorkbasket("key1", "DOMAIN_A")); + assertNull(workbasketService.getWorkbasket("key2", "DOMAIN_A")); + + } catch (TaskanaException e) { + e.printStackTrace(); } + } - @Test - void testWorkbasketCleanupJobTransaction() { - try { + private static ObjectReference createDefaultObjRef() { + ObjectReference objRef = new ObjectReference(); + objRef.setCompany("company"); + objRef.setSystem("system"); + objRef.setSystemInstance("instance"); + objRef.setType("type"); + objRef.setValue("value"); + return objRef; + } - WorkbasketService workbasketService = taskanaEngine.getWorkbasketService(); - workbasketService.createWorkbasket(createWorkBasket("key1", "wb1")); - workbasketService.createWorkbasket(createWorkBasket("key2", "wb2")); - workbasketService.createWorkbasket(createWorkBasket("key3", "wb3")); - TaskService taskService = taskanaEngine.getTaskService(); - ClassificationService classificationService = taskanaEngine.getClassificationService(); - classificationService.newClassification("TEST", "DOMAIN_A", "TASK"); - taskService.createTask(createTask("key1", "TEST")); - taskService.createTask(createTask("key2", "TEST")); - taskService.createTask(createTask("key3", "TEST")); + private void assertBefore(int workbaskets, int tests) { + assertWorkbaskets("before", workbaskets); + assertCustomdbTests("before", tests); + } - assertEquals(workbasketService.createWorkbasketQuery() - .count(), 3); - assertEquals(taskService.createTaskQuery() - .count(), 3); + private void assertAfter(int workbaskets, int tests) { + assertWorkbaskets("after", workbaskets); + assertCustomdbTests("after", tests); + } - List tasks = taskService.createTaskQuery() - .workbasketKeyDomainIn(new KeyDomain("key1", "DOMAIN_A")) - .list(); - taskService.claim(tasks.get(0).getTaskId()); - taskService.completeTask(tasks.get(0).getTaskId()); - tasks = taskService.createTaskQuery() - .workbasketKeyDomainIn(new KeyDomain("key2", "DOMAIN_A")) - .list(); - taskService.claim(tasks.get(0).getTaskId()); - taskService.completeTask(tasks.get(0).getTaskId()); - workbasketService.deleteWorkbasket(workbasketService.getWorkbasket("key1", "DOMAIN_A").getId()); - workbasketService.deleteWorkbasket(workbasketService.getWorkbasket("key2", "DOMAIN_A").getId()); + private void assertWorkbaskets(String assertion, int value) { + int workbaskets = getWorkbaskets(); + System.err.println(assertion + " workbaskets: " + workbaskets); + assertThat(workbaskets, is(value)); + } - // Clean two tasks, key1 and key2. - TaskCleanupJob taskCleanupJob = new TaskCleanupJob(taskanaEngine, springTransactionProvider, null); - taskCleanupJob.run(); + private void assertCustomdbTests(String assertion, int value) { + int tests = getCustomdbTests(); + System.err.println(assertion + " tests: " + tests); + assertThat(tests, is(value)); + } - tasks = taskService.createTaskQuery() - .workbasketKeyDomainIn(new KeyDomain("key3", "DOMAIN_A")) - .list(); - taskService.claim(tasks.get(0).getTaskId()); - taskService.completeTask(tasks.get(0).getTaskId()); - - try { - workbasketService.deleteWorkbasket(workbasketService.getWorkbasket("key3", "DOMAIN_A").getId()); - } catch (TaskanaException ex) { - assertEquals(ex.getMessage().contains("contains non-completed tasks"), true); - } - - WorkbasketCleanupJob job = new WorkbasketCleanupJob(taskanaEngine, springTransactionProvider, null); - job.run(); - - assertNull(workbasketService.getWorkbasket("key1", "DOMAIN_A")); - assertNull(workbasketService.getWorkbasket("key2", "DOMAIN_A")); - - } catch (TaskanaException e) { - e.printStackTrace(); - } + private int getWorkbaskets() { + ResponseEntity workbaskets = restTemplate.getForEntity("/workbaskets", Integer.class); + if (workbaskets.getStatusCode().is2xxSuccessful()) { + return workbaskets.getBody(); + } else { + throw new RuntimeException("error get workbaskets: " + workbaskets.getBody()); } + } - private void assertBefore(int workbaskets, int tests) { - assertWorkbaskets("before", workbaskets); - assertCustomdbTests("before", tests); + private int getCustomdbTests() { + ResponseEntity tests = restTemplate.getForEntity("/customdb-tests", Integer.class); + if (tests.getStatusCode().is2xxSuccessful()) { + return tests.getBody(); + } else { + throw new RuntimeException("error get customdb.tests: " + tests.getBody()); } + } - private void assertAfter(int workbaskets, int tests) { - assertWorkbaskets("after", workbaskets); - assertCustomdbTests("after", tests); - } + private Workbasket createWorkBasket(String key, String name) { + WorkbasketImpl workbasket = + (WorkbasketImpl) taskanaEngine.getWorkbasketService().newWorkbasket(key, "DOMAIN_A"); + String id1 = IdGenerator.generateWithPrefix("TWB"); + workbasket.setId(id1); + workbasket.setName(name); + workbasket.setType(WorkbasketType.GROUP); + return workbasket; + } - private void assertWorkbaskets(String assertion, int value) { - int workbaskets = getWorkbaskets(); - System.err.println(assertion + " workbaskets: " + workbaskets); - assertThat(workbaskets, is(value)); - } - - private void assertCustomdbTests(String assertion, int value) { - int tests = getCustomdbTests(); - System.err.println(assertion + " tests: " + tests); - assertThat(tests, is(value)); - } - - private int getWorkbaskets() { - ResponseEntity workbaskets = restTemplate.getForEntity("/workbaskets", Integer.class); - if (workbaskets.getStatusCode().is2xxSuccessful()) { - return workbaskets.getBody(); - } else { - throw new RuntimeException("error get workbaskets: " + workbaskets.getBody()); - } - } - - private int getCustomdbTests() { - ResponseEntity tests = restTemplate.getForEntity("/customdb-tests", Integer.class); - if (tests.getStatusCode().is2xxSuccessful()) { - return tests.getBody(); - } else { - throw new RuntimeException("error get customdb.tests: " + tests.getBody()); - } - } - - private Workbasket createWorkBasket(String key, String name) { - WorkbasketImpl workbasket = (WorkbasketImpl) taskanaEngine.getWorkbasketService().newWorkbasket(key, - "DOMAIN_A"); - String id1 = IdGenerator.generateWithPrefix("TWB"); - workbasket.setId(id1); - workbasket.setName(name); - workbasket.setType(WorkbasketType.GROUP); - return workbasket; - } - - private Task createTask(String key, String classificationKey) { - TaskImpl task = (TaskImpl) taskanaEngine.getTaskService().newTask(key, - "DOMAIN_A"); - task.setClassificationKey(classificationKey); - task.setPrimaryObjRef(createDefaultObjRef()); - return task; - } + private Task createTask(String key, String classificationKey) { + TaskImpl task = (TaskImpl) taskanaEngine.getTaskService().newTask(key, "DOMAIN_A"); + task.setClassificationKey(classificationKey); + task.setPrimaryObjRef(createDefaultObjRef()); + return task; + } } diff --git a/lib/taskana-spring-example/src/test/java/pro/taskana/TransactionalJobsConfiguration.java b/lib/taskana-spring-example/src/test/java/pro/taskana/TransactionalJobsConfiguration.java index 9bc7b952c..c164bbbaf 100644 --- a/lib/taskana-spring-example/src/test/java/pro/taskana/TransactionalJobsConfiguration.java +++ b/lib/taskana-spring-example/src/test/java/pro/taskana/TransactionalJobsConfiguration.java @@ -5,15 +5,12 @@ import org.springframework.context.annotation.Configuration; import pro.taskana.transaction.TaskanaTransactionProvider; -/** - * Configuration class for Spring sample application. - */ +/** Configuration class for Spring sample application. */ @Configuration public class TransactionalJobsConfiguration { - @Bean - public TaskanaTransactionProvider springTransactionProvider() { - return new pro.taskana.transaction.SpringTransactionProvider(); - } - + @Bean + public TaskanaTransactionProvider springTransactionProvider() { + return new pro.taskana.transaction.SpringTransactionProvider(); + } } diff --git a/lib/taskana-spring/src/main/java/pro/taskana/SpringTaskanaEngineImpl.java b/lib/taskana-spring/src/main/java/pro/taskana/SpringTaskanaEngineImpl.java index 5ff5c6652..c5d2162ae 100644 --- a/lib/taskana-spring/src/main/java/pro/taskana/SpringTaskanaEngineImpl.java +++ b/lib/taskana-spring/src/main/java/pro/taskana/SpringTaskanaEngineImpl.java @@ -1,24 +1,21 @@ package pro.taskana; import javax.annotation.PostConstruct; - import org.mybatis.spring.transaction.SpringManagedTransactionFactory; import pro.taskana.configuration.SpringTaskanaEngineConfiguration; import pro.taskana.impl.TaskanaEngineImpl; -/** - * This class configures the TaskanaEngine for spring. - */ +/** This class configures the TaskanaEngine for spring. */ public class SpringTaskanaEngineImpl extends TaskanaEngineImpl { - public SpringTaskanaEngineImpl(SpringTaskanaEngineConfiguration taskanaEngineConfiguration) { - super(taskanaEngineConfiguration); - } + public SpringTaskanaEngineImpl(SpringTaskanaEngineConfiguration taskanaEngineConfiguration) { + super(taskanaEngineConfiguration); + } - @PostConstruct - public void init() { - this.transactionFactory = new SpringManagedTransactionFactory(); - this.sessionManager = createSqlSessionManager(); - } + @PostConstruct + public void init() { + this.transactionFactory = new SpringManagedTransactionFactory(); + this.sessionManager = createSqlSessionManager(); + } } diff --git a/lib/taskana-spring/src/main/java/pro/taskana/configuration/SpringTaskanaEngineConfiguration.java b/lib/taskana-spring/src/main/java/pro/taskana/configuration/SpringTaskanaEngineConfiguration.java index 53a98a9db..ed97ba853 100644 --- a/lib/taskana-spring/src/main/java/pro/taskana/configuration/SpringTaskanaEngineConfiguration.java +++ b/lib/taskana-spring/src/main/java/pro/taskana/configuration/SpringTaskanaEngineConfiguration.java @@ -1,40 +1,52 @@ package pro.taskana.configuration; import java.sql.SQLException; - import javax.sql.DataSource; import pro.taskana.SpringTaskanaEngineImpl; import pro.taskana.TaskanaEngine; -/** - * This class configures the TaskanaEngineConfiguration for spring. - */ +/** This class configures the TaskanaEngineConfiguration for spring. */ public class SpringTaskanaEngineConfiguration extends TaskanaEngineConfiguration { - public SpringTaskanaEngineConfiguration(DataSource dataSource, boolean useManagedTransactions, - boolean securityEnabled, String schemaName) throws SQLException { - super(dataSource, useManagedTransactions, securityEnabled, schemaName); - } + public SpringTaskanaEngineConfiguration( + DataSource dataSource, + boolean useManagedTransactions, + boolean securityEnabled, + String schemaName) + throws SQLException { + super(dataSource, useManagedTransactions, securityEnabled, schemaName); + } - public SpringTaskanaEngineConfiguration(DataSource dataSource, boolean useManagedTransactions, - boolean securityEnabled, String propertiesFileName, String propertiesSeparator, String schemaName) throws SQLException { - super(dataSource, useManagedTransactions, securityEnabled, propertiesFileName, propertiesSeparator, schemaName); - } + public SpringTaskanaEngineConfiguration( + DataSource dataSource, + boolean useManagedTransactions, + boolean securityEnabled, + String propertiesFileName, + String propertiesSeparator, + String schemaName) + throws SQLException { + super( + dataSource, + useManagedTransactions, + securityEnabled, + propertiesFileName, + propertiesSeparator, + schemaName); + } - /** - * This method creates the Spring-based TaskanaEngine without an sqlSessionFactory. - * - * @return the TaskanaEngine - */ - @Override - public TaskanaEngine buildTaskanaEngine() { - this.useManagedTransactions = true; - return new SpringTaskanaEngineImpl(this); - } - - public void setDataSource(DataSource dataSource) { - this.dataSource = dataSource; - } + /** + * This method creates the Spring-based TaskanaEngine without an sqlSessionFactory. + * + * @return the TaskanaEngine + */ + @Override + public TaskanaEngine buildTaskanaEngine() { + this.useManagedTransactions = true; + return new SpringTaskanaEngineImpl(this); + } + public void setDataSource(DataSource dataSource) { + this.dataSource = dataSource; + } } diff --git a/lib/taskana-spring/src/main/java/pro/taskana/transaction/SpringTransactionProvider.java b/lib/taskana-spring/src/main/java/pro/taskana/transaction/SpringTransactionProvider.java index 857c6f6de..524decedd 100644 --- a/lib/taskana-spring/src/main/java/pro/taskana/transaction/SpringTransactionProvider.java +++ b/lib/taskana-spring/src/main/java/pro/taskana/transaction/SpringTransactionProvider.java @@ -3,17 +3,13 @@ package pro.taskana.transaction; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; -/** - * TODO. - */ +/** TODO. */ @Component public class SpringTransactionProvider implements TaskanaTransactionProvider { - @Override - @Transactional(rollbackFor = Exception.class) - public Object executeInTransaction( - TaskanaCallable action) { - return action.call(); - } - + @Override + @Transactional(rollbackFor = Exception.class) + public Object executeInTransaction(TaskanaCallable action) { + return action.call(); + } } diff --git a/lib/taskana-spring/src/test/java/pro/taskana/TaskanaComponent.java b/lib/taskana-spring/src/test/java/pro/taskana/TaskanaComponent.java index 92ee994d5..f3a6c5490 100644 --- a/lib/taskana-spring/src/test/java/pro/taskana/TaskanaComponent.java +++ b/lib/taskana-spring/src/test/java/pro/taskana/TaskanaComponent.java @@ -10,34 +10,31 @@ import pro.taskana.exceptions.NotAuthorizedException; import pro.taskana.exceptions.TaskAlreadyExistException; import pro.taskana.exceptions.WorkbasketNotFoundException; -/** - * TODO. - */ +/** TODO. */ @Component @Transactional public class TaskanaComponent { - @Autowired - TaskService taskService; + @Autowired TaskService taskService; - public TaskService getTaskService() { - return taskService; - } + public TaskService getTaskService() { + return taskService; + } - public void triggerRollback() throws NotAuthorizedException, WorkbasketNotFoundException, - ClassificationNotFoundException, TaskAlreadyExistException, InvalidArgumentException { - Task task = taskService.newTask("1"); - task.setName("Unit Test Task"); - ObjectReference objRef = new ObjectReference(); - objRef.setCompany("aCompany"); - objRef.setSystem("aSystem"); - objRef.setSystemInstance("anInstance"); - objRef.setType("aType"); - objRef.setValue("aValue"); - task.setPrimaryObjRef(objRef); - - task = taskService.createTask(task); - throw new RuntimeException(); - } + public void triggerRollback() + throws NotAuthorizedException, WorkbasketNotFoundException, ClassificationNotFoundException, + TaskAlreadyExistException, InvalidArgumentException { + Task task = taskService.newTask("1"); + task.setName("Unit Test Task"); + ObjectReference objRef = new ObjectReference(); + objRef.setCompany("aCompany"); + objRef.setSystem("aSystem"); + objRef.setSystemInstance("anInstance"); + objRef.setType("aType"); + objRef.setValue("aValue"); + task.setPrimaryObjRef(objRef); + task = taskService.createTask(task); + throw new RuntimeException(); + } } diff --git a/lib/taskana-spring/src/test/java/pro/taskana/TransactionTest.java b/lib/taskana-spring/src/test/java/pro/taskana/TransactionTest.java index 0e9613864..d8026db63 100644 --- a/lib/taskana-spring/src/test/java/pro/taskana/TransactionTest.java +++ b/lib/taskana-spring/src/test/java/pro/taskana/TransactionTest.java @@ -4,7 +4,6 @@ import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; - import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; @@ -21,9 +20,7 @@ import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; -/** - * TODO. - */ +/** TODO. */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @ContextConfiguration("classpath:test-applicationContext.xml") @@ -31,59 +28,56 @@ import org.springframework.test.context.junit4.SpringRunner; @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) public class TransactionTest { - @Autowired - TaskService taskService; + @Autowired TaskService taskService; + @LocalServerPort int port; + @Autowired private TestRestTemplate restTemplate; - @Autowired - private TestRestTemplate restTemplate; + @Before + public void init() throws SQLException, ClassNotFoundException { + Class.forName("org.h2.Driver"); + try (Connection conn = + DriverManager.getConnection( + "jdbc:h2:mem:task-engine;IGNORECASE=TRUE;LOCK_MODE=0", "SA", "SA")) { + conn.createStatement().executeUpdate("DELETE FROM TASK WHERE 1=1"); + conn.commit(); + } + } - @LocalServerPort - int port; + @Test + @Ignore + public void testCommit() throws SQLException { + restTemplate.getForEntity("http://127.0.0.1:" + port + "/test", String.class); - @Before - public void init() throws SQLException, ClassNotFoundException { - Class.forName("org.h2.Driver"); - try (Connection conn = DriverManager.getConnection("jdbc:h2:mem:task-engine;IGNORECASE=TRUE;LOCK_MODE=0", "SA", - "SA")) { - conn.createStatement().executeUpdate("DELETE FROM TASK WHERE 1=1"); - conn.commit(); - } + int resultCount = 0; + try (Connection conn = + DriverManager.getConnection( + "jdbc:h2:mem:task-engine;IGNORECASE=TRUE;LOCK_MODE=0", "SA", "SA")) { + ResultSet rs = conn.createStatement().executeQuery("SELECT ID FROM TASK"); + + while (rs.next()) { + resultCount++; + } } - @Test - @Ignore - public void testCommit() throws SQLException { - restTemplate.getForEntity("http://127.0.0.1:" + port + "/test", String.class); + Assert.assertEquals(1, resultCount); + } - int resultCount = 0; - try (Connection conn = DriverManager.getConnection("jdbc:h2:mem:task-engine;IGNORECASE=TRUE;LOCK_MODE=0", "SA", - "SA")) { - ResultSet rs = conn.createStatement().executeQuery("SELECT ID FROM TASK"); + @Test + @Ignore + public void testRollback() throws SQLException { + restTemplate.postForEntity("http://127.0.0.1:" + port + "/test", null, String.class); - while (rs.next()) { - resultCount++; - } - } + int resultCount = 0; + try (Connection conn = + DriverManager.getConnection( + "jdbc:h2:mem:task-engine;IGNORECASE=TRUE;LOCK_MODE=0", "SA", "SA")) { + ResultSet rs = conn.createStatement().executeQuery("SELECT ID FROM TASK"); - Assert.assertEquals(1, resultCount); - } - - @Test - @Ignore - public void testRollback() throws SQLException { - restTemplate.postForEntity("http://127.0.0.1:" + port + "/test", null, String.class); - - int resultCount = 0; - try (Connection conn = DriverManager.getConnection("jdbc:h2:mem:task-engine;IGNORECASE=TRUE;LOCK_MODE=0", "SA", - "SA")) { - ResultSet rs = conn.createStatement().executeQuery("SELECT ID FROM TASK"); - - while (rs.next()) { - resultCount++; - } - } - - Assert.assertEquals(0, resultCount); + while (rs.next()) { + resultCount++; + } } + Assert.assertEquals(0, resultCount); + } } diff --git a/rest/taskana-rest-spring-example-boot/src/main/java/pro/taskana/rest/ExampleRestApplication.java b/rest/taskana-rest-spring-example-boot/src/main/java/pro/taskana/rest/ExampleRestApplication.java index 7a7801d9c..f139ec553 100644 --- a/rest/taskana-rest-spring-example-boot/src/main/java/pro/taskana/rest/ExampleRestApplication.java +++ b/rest/taskana-rest-spring-example-boot/src/main/java/pro/taskana/rest/ExampleRestApplication.java @@ -1,10 +1,8 @@ package pro.taskana.rest; import java.sql.SQLException; - import javax.annotation.PostConstruct; import javax.sql.DataSource; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; @@ -23,52 +21,53 @@ import pro.taskana.ldap.LdapClient; import pro.taskana.ldap.LdapConfiguration; import pro.taskana.sampledata.SampleDataGenerator; -/** - * Example Application showing the implementation of taskana-rest-spring. - */ +/** Example Application showing the implementation of taskana-rest-spring. */ @SpringBootApplication @EnableScheduling @ComponentScan(basePackages = "pro.taskana") -@Import({TransactionalJobsConfiguration.class, LdapConfiguration.class, RestConfiguration.class, WebMvcConfig.class}) +@Import({ + TransactionalJobsConfiguration.class, + LdapConfiguration.class, + RestConfiguration.class, + WebMvcConfig.class +}) public class ExampleRestApplication { - @Value("${taskana.schemaName:TASKANA}") - public String schemaName; + @Value("${taskana.schemaName:TASKANA}") + public String schemaName; - @Value("${generateSampleData:true}") - public boolean generateSampleData; + @Value("${generateSampleData:true}") + public boolean generateSampleData; - @Autowired - private SampleDataGenerator sampleDataGenerator; + @Autowired private SampleDataGenerator sampleDataGenerator; - @Autowired - private LdapClient ldapClient; + @Autowired private LdapClient ldapClient; - @Autowired private LdapCacheTestImpl ldapCacheTest; + @Autowired private LdapCacheTestImpl ldapCacheTest; - public static void main(String[] args) { - SpringApplication.run(ExampleRestApplication.class, args); + public static void main(String[] args) { + SpringApplication.run(ExampleRestApplication.class, args); + } + + @Bean + public PlatformTransactionManager txManager(DataSource dataSource) { + return new DataSourceTransactionManager(dataSource); + } + + @Bean + @DependsOn("getTaskanaEngine") // generate sample data after schema was inserted + public SampleDataGenerator generateSampleData(DataSource dataSource) { + sampleDataGenerator = new SampleDataGenerator(dataSource, schemaName); + return sampleDataGenerator; + } + + @PostConstruct + private void init() throws SQLException { + if (!ldapClient.useLdap()) { + AccessIdController.setLdapCache(ldapCacheTest); } - - @Bean - public PlatformTransactionManager txManager(DataSource dataSource) { - return new DataSourceTransactionManager(dataSource); - } - - @Bean - @DependsOn("getTaskanaEngine") // generate sample data after schema was inserted - public SampleDataGenerator generateSampleData(DataSource dataSource) { - sampleDataGenerator = new SampleDataGenerator(dataSource, schemaName); - return sampleDataGenerator; - } - - @PostConstruct - private void init() throws SQLException { - if (!ldapClient.useLdap()) { - AccessIdController.setLdapCache(ldapCacheTest); - } - if (generateSampleData) { - sampleDataGenerator.generateSampleData(); - } + if (generateSampleData) { + sampleDataGenerator.generateSampleData(); } + } } diff --git a/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/jobs/JobScheduler.java b/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/jobs/JobScheduler.java index 1d9197358..d86b2742e 100644 --- a/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/jobs/JobScheduler.java +++ b/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/jobs/JobScheduler.java @@ -5,10 +5,8 @@ import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.List; - import javax.annotation.PostConstruct; import javax.security.auth.Subject; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -20,76 +18,73 @@ import pro.taskana.TaskanaRole; import pro.taskana.security.UserPrincipal; import pro.taskana.transaction.TaskanaTransactionProvider; -/** - * This class invokes the JobRunner periodically to schedule long running jobs. - */ +/** This class invokes the JobRunner periodically to schedule long running jobs. */ @Component public class JobScheduler { - private static final Logger LOGGER = LoggerFactory.getLogger(JobScheduler.class); + private static final Logger LOGGER = LoggerFactory.getLogger(JobScheduler.class); + @Autowired TaskanaTransactionProvider springTransactionProvider; + @Autowired private TaskanaEngine taskanaEngine; - @Autowired - private TaskanaEngine taskanaEngine; + @PostConstruct + public void scheduleCleanupJob() { + LOGGER.debug("Entry to scheduleCleanupJob."); + TaskCleanupJob.initializeSchedule(taskanaEngine); + WorkbasketCleanupJob.initializeSchedule(taskanaEngine); + LOGGER.debug("Exit from scheduleCleanupJob."); + } - @Autowired - TaskanaTransactionProvider springTransactionProvider; - - @PostConstruct - public void scheduleCleanupJob() { - LOGGER.debug("Entry to scheduleCleanupJob."); - TaskCleanupJob.initializeSchedule(taskanaEngine); - WorkbasketCleanupJob.initializeSchedule(taskanaEngine); - LOGGER.debug("Exit from scheduleCleanupJob."); + @Scheduled(cron = "${taskana.jobscheduler.async.cron}") + public void triggerJobs() { + LOGGER.info("AsyncJobs started."); + try { + runAsyncJobsAsAdmin(); + LOGGER.info("AsyncJobs completed."); + } catch (PrivilegedActionException e) { + LOGGER.info("AsyncJobs failed.", e); } + } - @Scheduled(cron = "${taskana.jobscheduler.async.cron}") - public void triggerJobs() { - LOGGER.info("AsyncJobs started."); - try { - runAsyncJobsAsAdmin(); - LOGGER.info("AsyncJobs completed."); - } catch (PrivilegedActionException e) { - LOGGER.info("AsyncJobs failed.", e); - } + /* + * Creates an admin subject and runs the job using the subject. + */ + private void runAsyncJobsAsAdmin() throws PrivilegedActionException { + Subject.doAs( + getAdminSubject(), + new PrivilegedExceptionAction() { + + @Override + public Object run() throws Exception { + + try { + JobRunner runner = new JobRunner(taskanaEngine); + runner.registerTransactionProvider(springTransactionProvider); + LOGGER.info("Running Jobs"); + runner.runJobs(); + return "Successful"; + } catch (Throwable e) { + throw new Exception(e); + } + } + }); + } + + private Subject getAdminSubject() { + Subject subject = new Subject(); + List principalList = new ArrayList<>(); + try { + principalList.add( + new UserPrincipal( + taskanaEngine + .getConfiguration() + .getRoleMap() + .get(TaskanaRole.ADMIN) + .iterator() + .next())); + } catch (Throwable t) { + LOGGER.warn("Could not determine a configured admin user.", t); } - - /* - * Creates an admin subject and runs the job using the subject. - */ - private void runAsyncJobsAsAdmin() throws PrivilegedActionException { - Subject.doAs(getAdminSubject(), - new PrivilegedExceptionAction() { - - @Override - public Object run() throws Exception { - - try { - JobRunner runner = new JobRunner(taskanaEngine); - runner.registerTransactionProvider(springTransactionProvider); - LOGGER.info("Running Jobs"); - runner.runJobs(); - return "Successful"; - } catch (Throwable e) { - throw new Exception(e); - } - - } - - }); - } - - private Subject getAdminSubject() { - Subject subject = new Subject(); - List principalList = new ArrayList<>(); - try { - principalList - .add(new UserPrincipal( - taskanaEngine.getConfiguration().getRoleMap().get(TaskanaRole.ADMIN).iterator().next())); - } catch (Throwable t) { - LOGGER.warn("Could not determine a configured admin user.", t); - } - subject.getPrincipals().addAll(principalList); - return subject; - } - + subject.getPrincipals().addAll(principalList); + return subject; + } } diff --git a/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/jobs/TransactionalJobsConfiguration.java b/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/jobs/TransactionalJobsConfiguration.java index 68e94cada..99269ecf1 100644 --- a/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/jobs/TransactionalJobsConfiguration.java +++ b/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/jobs/TransactionalJobsConfiguration.java @@ -5,15 +5,12 @@ import org.springframework.context.annotation.Configuration; import pro.taskana.transaction.TaskanaTransactionProvider; -/** - * Configuration class for Spring sample application. - */ +/** Configuration class for Spring sample application. */ @Configuration public class TransactionalJobsConfiguration { - @Bean - public TaskanaTransactionProvider springTransactionProvider() { - return new pro.taskana.transaction.SpringTransactionProvider(); - } - + @Bean + public TaskanaTransactionProvider springTransactionProvider() { + return new pro.taskana.transaction.SpringTransactionProvider(); + } } diff --git a/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/ldap/LdapCacheTestImpl.java b/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/ldap/LdapCacheTestImpl.java index d90ad6dc3..79f88618a 100644 --- a/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/ldap/LdapCacheTestImpl.java +++ b/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/ldap/LdapCacheTestImpl.java @@ -6,7 +6,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; - import org.springframework.stereotype.Component; import pro.taskana.rest.resource.AccessIdResource; @@ -19,377 +18,389 @@ import pro.taskana.rest.resource.AccessIdResource; @Component public class LdapCacheTestImpl implements LdapCache { - /** - * Dictionary is a {@link Map} collection that contains {@link AccessIdResource} as key (user) - * and {@link List} as value (groups of which the user is a member) . - */ - private static Map> users; - private static List accessIds = new ArrayList<>(Arrays.asList( - new AccessIdResource("Martin, Rojas Miguel Angel", "user_1_1"), - new AccessIdResource("Zorgati, Mustapha", "user_2_1"), - new AccessIdResource("Behrendt, Maximilian", "max"), - new AccessIdResource("Bert, Ali", "teamlead_5"), - new AccessIdResource("Hagen, Holger", "teamlead_3"), - new AccessIdResource("Breier, Bernd", "user_2_2"), - new AccessIdResource("Fielmalz, Anke", "user017"), - new AccessIdResource("Mente, Maximilian", "max_mente"), - new AccessIdResource("Theke, Bernd", "user_2_3"), - new AccessIdResource("Ferrante, Elena", "elena"), - new AccessIdResource("Mueller, Simone", "simone"), - new AccessIdResource("Sirup, Aaron", "user001"), - new AccessIdResource("Nacho, recuerda", "user_1_2"), - new AccessIdResource("Lass, Ada", "user003"), - new AccessIdResource("Tion, Addi", "user004"), - new AccessIdResource("Lette, Adi", "user005"), - new AccessIdResource("Admin", "teamlead_2"), - new AccessIdResource("Native, Alter", "user006"), - new AccessIdResource("Herum, Albert", "user007"), - new AccessIdResource("Meyer, Dominik", "teamlead_1"), - new AccessIdResource("Mente, Ali", "user009"), - new AccessIdResource("Nach, Alma", "user011"), - new AccessIdResource("Gehzauch, Anders", "user012"), - new AccessIdResource("Theke, Andi", "user013"), - new AccessIdResource("Kreuz, Andreas", "user014"), - new AccessIdResource("Tiefsee, Anka", "user016"), - new AccessIdResource("Fassen, Ann", "user018"), - new AccessIdResource("Probe, Ann", "user019"), - new AccessIdResource("Bolika, Anna", "user020"), - new AccessIdResource("Ecke, Anna", "user021"), - new AccessIdResource("Hosi, Anna", "user022"), - new AccessIdResource("Kronis-Tisch, Anna", "user023"), - new AccessIdResource("Logie, Anna", "user024"), - new AccessIdResource("Luehse, Anna", "user025"), - new AccessIdResource("Nass, Anna", "user026"), - new AccessIdResource("Thalb, Anna", "user027"), - new AccessIdResource("Tomie, Anna", "user028"), - new AccessIdResource("Donnich, Anne", "user029"), - new AccessIdResource("Kaffek, Anne", "user030"), - new AccessIdResource("Thek, Anne", "user031"), - new AccessIdResource("Matoer, Anni", "user032"), - new AccessIdResource("Ragentor, Ansgar", "user033"), - new AccessIdResource("Stoteles, Ari", "user034"), - new AccessIdResource("Thmetik, Ari", "user035"), - new AccessIdResource("Nuehm, Arno", "user036"), - new AccessIdResource("Schocke, Artie", "user037"), - new AccessIdResource("Stoppel, Bart", "user038"), - new AccessIdResource("Beitung, Bea", "user039"), - new AccessIdResource("Ildich, Bea", "user040"), - new AccessIdResource("Vista, Bella", "user041"), - new AccessIdResource("Utzer, Ben", "user042"), - new AccessIdResource("Zien, Ben", "user043"), - new AccessIdResource("Stein, Bernd", "user044"), - new AccessIdResource("Deramen, Bill", "user045"), - new AccessIdResource("Honig, Bine", "user046"), - new AccessIdResource("Densatz, Bo", "user047"), - new AccessIdResource("Densee, Bo", "user048"), - new AccessIdResource("Lerwagen, Bo", "user049"), - new AccessIdResource("Tail, Bob", "user050"), - new AccessIdResource("Ketta, Bruce", "user051"), - new AccessIdResource("Terrie, Bud", "user052"), - new AccessIdResource("Biener-Haken, Cara", "user053"), - new AccessIdResource("Ass, Caro", "user054"), - new AccessIdResource("Kaffee, Caro", "user055"), - new AccessIdResource("Linger, Caro", "user056"), - new AccessIdResource("tenSaft, Caro", "user057"), - new AccessIdResource("Antheme, Chris", "user058"), - new AccessIdResource("Baum, Chris", "user059"), - new AccessIdResource("Tall, Chris", "user060"), - new AccessIdResource("Reiniger, Claas", "user061"), - new AccessIdResource("Grube, Claire", "user062"), - new AccessIdResource("Fall, Clara", "user063"), - new AccessIdResource("Korn, Clara", "user064"), - new AccessIdResource("Lenriff, Cora", "user065"), - new AccessIdResource("Schiert, Cora", "user066"), - new AccessIdResource("Hose, Cord", "user067"), - new AccessIdResource("Onbleu, Cord", "user068"), - new AccessIdResource("Umkleide, Damon", "user069"), - new AccessIdResource("Affier, Dean", "user070"), - new AccessIdResource("Orm, Dean", "user071"), - new AccessIdResource("Platz, Dennis", "user072"), - new AccessIdResource("Milch, Dick", "user073"), - new AccessIdResource("Mow, Dina", "user074"), - new AccessIdResource("Keil, Donna", "user075"), - new AccessIdResource("Littchen, Donna", "user076"), - new AccessIdResource("Wetter, Donna", "user077"), - new AccessIdResource("Was, Ed", "user078"), - new AccessIdResource("Khar, Ede", "user079"), - new AccessIdResource("Nut, Ella", "user080"), - new AccessIdResource("Stisch, Ella", "user081"), - new AccessIdResource("Diel, Emma", "user082"), - new AccessIdResource("Herdamit, Emma", "user083"), - new AccessIdResource("Mitter-Uhe, Emma", "user084"), - new AccessIdResource("Tatt, Erich", "user085"), - new AccessIdResource("Drigend, Ernie", "user086"), - new AccessIdResource("Poly, Esther", "user087"), - new AccessIdResource("Trautz, Eugen", "user088"), - new AccessIdResource("Quiert, Eva", "user089"), - new AccessIdResource("Inurlaub, Fatma", "user090"), - new AccessIdResource("Land, Finn", "user091"), - new AccessIdResource("Sternis, Finn", "user092"), - new AccessIdResource("Furt, Frank", "user093"), - new AccessIdResource("Reich, Frank", "user094"), - new AccessIdResource("Iskaner, Franz", "user095"), - new AccessIdResource("Nerr, Franziska", "user096"), - new AccessIdResource("Zafen, Friedrich", "user097"), - new AccessIdResource("Pomm, Fritz", "user098"), - new AccessIdResource("deWegs, Gera", "user099"), - new AccessIdResource("Staebe, Gitta", "user100"), - new AccessIdResource("Zend, Glenn", "user101"), - new AccessIdResource("Fisch, Grete", "user102"), - new AccessIdResource("Zucker, Gus", "user103"), - new AccessIdResource("Muhn, Hanni", "user104"), - new AccessIdResource("Fermesse, Hanno", "user105"), - new AccessIdResource("Aplast, Hans", "user106"), - new AccessIdResource("Eart, Hans", "user107"), - new AccessIdResource("Back, Hardy", "user108"), - new AccessIdResource("Beau, Harry", "user109"), - new AccessIdResource("Kraut, Heide", "user110"), - new AccessIdResource("Witzka, Heide", "user111"), - new AccessIdResource("Buchen, Hein", "user112"), - new AccessIdResource("Lichkeit, Hein", "user113"), - new AccessIdResource("Suchung, Hein", "user114"), - new AccessIdResource("Ellmann, Heinz", "user115"), - new AccessIdResource("Ketchup, Heinz", "user116"), - new AccessIdResource("Zeim, Hilde", "user117"), - new AccessIdResource("Bilien, Immo", "user118"), - new AccessIdResource("Her, Inge", "user119"), - new AccessIdResource("Wahrsam, Inge", "user120"), - new AccessIdResource("Flamm, Ingo", "user121"), - new AccessIdResource("Enzien, Ingrid", "user122"), - new AccessIdResource("Rohsch, Inken", "user123"), - new AccessIdResource("Ihr, Insa", "user124"), - new AccessIdResource("Nerda, Iska", "user125"), - new AccessIdResource("Eitz, Jens", "user126"), - new AccessIdResource("Nastik, Jim", "user127"), - new AccessIdResource("Gurt, Jo", "user128"), - new AccessIdResource("Kurrth, Jo", "user129"), - new AccessIdResource("Kolade, Joe", "user130"), - new AccessIdResource("Iter, Johann", "user131"), - new AccessIdResource("Tick, Joyce", "user132"), - new AccessIdResource("Case, Justin", "user133"), - new AccessIdResource("Time, Justin", "user134"), - new AccessIdResource("Komp, Jutta", "user135"), - new AccessIdResource("Mauer, Kai", "user136"), - new AccessIdResource("Pirinja, Kai", "user137"), - new AccessIdResource("Serpfalz, Kai", "user138"), - new AccessIdResource("Auer, Karl", "user139"), - new AccessIdResource("Ielauge, Karl", "user140"), - new AccessIdResource("Ifornjen, Karl", "user141"), - new AccessIdResource("Radi, Karl", "user142"), - new AccessIdResource("Verti, Karl", "user143"), - new AccessIdResource("Sery, Karo", "user144"), - new AccessIdResource("Lisator, Katha", "user145"), - new AccessIdResource("Flo, Kati", "user146"), - new AccessIdResource("Schenn, Knut", "user147"), - new AccessIdResource("Achse, Kurt", "user148"), - new AccessIdResource("Zepause, Kurt", "user149"), - new AccessIdResource("Zerr, Kurt", "user150"), - new AccessIdResource("Reden, Lasse", "user151"), - new AccessIdResource("Metten, Lee", "user152"), - new AccessIdResource("Arm, Lene", "user153"), - new AccessIdResource("Thur, Linnea", "user154"), - new AccessIdResource("Bonn, Lisa", "user155"), - new AccessIdResource("Sembourg, Luc", "user156"), - new AccessIdResource("Rung, Lucky", "user157"), - new AccessIdResource("Zafen, Ludwig", "user158"), - new AccessIdResource("Hauden, Lukas", "user159"), - new AccessIdResource("Hose, Lutz", "user160"), - new AccessIdResource("Tablette, Lutz", "user161"), - new AccessIdResource("Fehr, Luzie", "user162"), - new AccessIdResource("Nalyse, Magda", "user163"), - new AccessIdResource("Ehfer, Maik", "user164"), - new AccessIdResource("Sehr, Malte", "user165"), - new AccessIdResource("Thon, Mara", "user166"), - new AccessIdResource("Quark, Marga", "user167"), - new AccessIdResource("Nade, Marie", "user168"), - new AccessIdResource("Niert, Marie", "user169"), - new AccessIdResource("Neese, Mario", "user170"), - new AccessIdResource("Nette, Marion", "user171"), - new AccessIdResource("Nesium, Mark", "user172"), - new AccessIdResource("Thalle, Mark", "user173"), - new AccessIdResource("Diven, Marle", "user174"), - new AccessIdResource("Fitz, Marle", "user175"), - new AccessIdResource("Pfahl, Marta", "user176"), - new AccessIdResource("Zorn, Martin", "user177"), - new AccessIdResource("Krissmes, Mary", "user178"), - new AccessIdResource("Jess, Matt", "user179"), - new AccessIdResource("Strammer, Max", "user180"), - new AccessIdResource("Mumm, Maxi", "user181"), - new AccessIdResource("Morphose, Meta", "user182"), - new AccessIdResource("Uh, Mia", "user183"), - new AccessIdResource("Rofon, Mike", "user184"), - new AccessIdResource("Rosoft, Mike", "user185"), - new AccessIdResource("Liter, Milli", "user186"), - new AccessIdResource("Thär, Milli", "user187"), - new AccessIdResource("Welle, Mirko", "user188"), - new AccessIdResource("Thorat, Mo", "user189"), - new AccessIdResource("Thor, Moni", "user190"), - new AccessIdResource("Kinolta, Monika", "user191"), - new AccessIdResource("Mundhaar, Monika", "user192"), - new AccessIdResource("Munter, Monika", "user193"), - new AccessIdResource("Zwerg, Nat", "user194"), - new AccessIdResource("Elmine, Nick", "user195"), - new AccessIdResource("Thien, Niko", "user196"), - new AccessIdResource("Pferd, Nils", "user197"), - new AccessIdResource("Lerweise, Norma", "user198"), - new AccessIdResource("Motor, Otto", "user199"), - new AccessIdResource("Totol, Otto", "user200"), - new AccessIdResource("Nerr, Paula", "user201"), - new AccessIdResource("Imeter, Peer", "user202"), - new AccessIdResource("Serkatze, Peer", "user203"), - new AccessIdResource("Gogisch, Peter", "user204"), - new AccessIdResource("Silje, Peter", "user205"), - new AccessIdResource("Harmonie, Phil", "user206"), - new AccessIdResource("Ihnen, Philip", "user207"), - new AccessIdResource("Uto, Pia", "user208"), - new AccessIdResource("Kothek, Pina", "user209"), - new AccessIdResource("Zar, Pit", "user210"), - new AccessIdResource("Zeih, Polly", "user211"), - new AccessIdResource("Tswan, Puh", "user212"), - new AccessIdResource("Zufall, Rainer", "user213"), - new AccessIdResource("Lien, Rita", "user214"), - new AccessIdResource("Held, Roman", "user215"), - new AccessIdResource("Haar, Ross", "user216"), - new AccessIdResource("Dick, Roy", "user217"), - new AccessIdResource("Enplaner, Ruth", "user218"), - new AccessIdResource("Kommen, Ryan", "user219"), - new AccessIdResource("Philo, Sophie", "user220"), - new AccessIdResource("Matisier, Stig", "user221"), - new AccessIdResource("Loniki, Tessa", "user222"), - new AccessIdResource("Tralisch, Thea", "user223"), - new AccessIdResource("Logie, Theo", "user224"), - new AccessIdResource("Ister, Thorn", "user225"), - new AccessIdResource("Buktu, Tim", "user226"), - new AccessIdResource("Ate, Tom", "user227"), - new AccessIdResource("Pie, Udo", "user228"), - new AccessIdResource("Aloe, Vera", "user229"), - new AccessIdResource("Hausver, Walter", "user230"), - new AccessIdResource("Schuh, Wanda", "user231"), - new AccessIdResource("Rahm, Wolf", "user232"), + /** + * Dictionary is a {@link Map} collection that contains {@link AccessIdResource} as key (user) and + * {@link List} as value (groups of which the user is a member) . + */ + private static Map> users; - new AccessIdResource("businessadmin", "cn=businessadmin,ou=groups,o=taskanatest"), - new AccessIdResource("UsersGroup", "cn=usersgroup,ou=groups,o=taskanatest"), - new AccessIdResource("DevelopersGroup", "cn=developersgroup,ou=groups,o=taskanatest"), - new AccessIdResource("businessadmin", "cn=customersgroup,ou=groups,o=taskanatest"), + private static List accessIds = + new ArrayList<>( + Arrays.asList( + new AccessIdResource("Martin, Rojas Miguel Angel", "user_1_1"), + new AccessIdResource("Zorgati, Mustapha", "user_2_1"), + new AccessIdResource("Behrendt, Maximilian", "max"), + new AccessIdResource("Bert, Ali", "teamlead_5"), + new AccessIdResource("Hagen, Holger", "teamlead_3"), + new AccessIdResource("Breier, Bernd", "user_2_2"), + new AccessIdResource("Fielmalz, Anke", "user017"), + new AccessIdResource("Mente, Maximilian", "max_mente"), + new AccessIdResource("Theke, Bernd", "user_2_3"), + new AccessIdResource("Ferrante, Elena", "elena"), + new AccessIdResource("Mueller, Simone", "simone"), + new AccessIdResource("Sirup, Aaron", "user001"), + new AccessIdResource("Nacho, recuerda", "user_1_2"), + new AccessIdResource("Lass, Ada", "user003"), + new AccessIdResource("Tion, Addi", "user004"), + new AccessIdResource("Lette, Adi", "user005"), + new AccessIdResource("Admin", "teamlead_2"), + new AccessIdResource("Native, Alter", "user006"), + new AccessIdResource("Herum, Albert", "user007"), + new AccessIdResource("Meyer, Dominik", "teamlead_1"), + new AccessIdResource("Mente, Ali", "user009"), + new AccessIdResource("Nach, Alma", "user011"), + new AccessIdResource("Gehzauch, Anders", "user012"), + new AccessIdResource("Theke, Andi", "user013"), + new AccessIdResource("Kreuz, Andreas", "user014"), + new AccessIdResource("Tiefsee, Anka", "user016"), + new AccessIdResource("Fassen, Ann", "user018"), + new AccessIdResource("Probe, Ann", "user019"), + new AccessIdResource("Bolika, Anna", "user020"), + new AccessIdResource("Ecke, Anna", "user021"), + new AccessIdResource("Hosi, Anna", "user022"), + new AccessIdResource("Kronis-Tisch, Anna", "user023"), + new AccessIdResource("Logie, Anna", "user024"), + new AccessIdResource("Luehse, Anna", "user025"), + new AccessIdResource("Nass, Anna", "user026"), + new AccessIdResource("Thalb, Anna", "user027"), + new AccessIdResource("Tomie, Anna", "user028"), + new AccessIdResource("Donnich, Anne", "user029"), + new AccessIdResource("Kaffek, Anne", "user030"), + new AccessIdResource("Thek, Anne", "user031"), + new AccessIdResource("Matoer, Anni", "user032"), + new AccessIdResource("Ragentor, Ansgar", "user033"), + new AccessIdResource("Stoteles, Ari", "user034"), + new AccessIdResource("Thmetik, Ari", "user035"), + new AccessIdResource("Nuehm, Arno", "user036"), + new AccessIdResource("Schocke, Artie", "user037"), + new AccessIdResource("Stoppel, Bart", "user038"), + new AccessIdResource("Beitung, Bea", "user039"), + new AccessIdResource("Ildich, Bea", "user040"), + new AccessIdResource("Vista, Bella", "user041"), + new AccessIdResource("Utzer, Ben", "user042"), + new AccessIdResource("Zien, Ben", "user043"), + new AccessIdResource("Stein, Bernd", "user044"), + new AccessIdResource("Deramen, Bill", "user045"), + new AccessIdResource("Honig, Bine", "user046"), + new AccessIdResource("Densatz, Bo", "user047"), + new AccessIdResource("Densee, Bo", "user048"), + new AccessIdResource("Lerwagen, Bo", "user049"), + new AccessIdResource("Tail, Bob", "user050"), + new AccessIdResource("Ketta, Bruce", "user051"), + new AccessIdResource("Terrie, Bud", "user052"), + new AccessIdResource("Biener-Haken, Cara", "user053"), + new AccessIdResource("Ass, Caro", "user054"), + new AccessIdResource("Kaffee, Caro", "user055"), + new AccessIdResource("Linger, Caro", "user056"), + new AccessIdResource("tenSaft, Caro", "user057"), + new AccessIdResource("Antheme, Chris", "user058"), + new AccessIdResource("Baum, Chris", "user059"), + new AccessIdResource("Tall, Chris", "user060"), + new AccessIdResource("Reiniger, Claas", "user061"), + new AccessIdResource("Grube, Claire", "user062"), + new AccessIdResource("Fall, Clara", "user063"), + new AccessIdResource("Korn, Clara", "user064"), + new AccessIdResource("Lenriff, Cora", "user065"), + new AccessIdResource("Schiert, Cora", "user066"), + new AccessIdResource("Hose, Cord", "user067"), + new AccessIdResource("Onbleu, Cord", "user068"), + new AccessIdResource("Umkleide, Damon", "user069"), + new AccessIdResource("Affier, Dean", "user070"), + new AccessIdResource("Orm, Dean", "user071"), + new AccessIdResource("Platz, Dennis", "user072"), + new AccessIdResource("Milch, Dick", "user073"), + new AccessIdResource("Mow, Dina", "user074"), + new AccessIdResource("Keil, Donna", "user075"), + new AccessIdResource("Littchen, Donna", "user076"), + new AccessIdResource("Wetter, Donna", "user077"), + new AccessIdResource("Was, Ed", "user078"), + new AccessIdResource("Khar, Ede", "user079"), + new AccessIdResource("Nut, Ella", "user080"), + new AccessIdResource("Stisch, Ella", "user081"), + new AccessIdResource("Diel, Emma", "user082"), + new AccessIdResource("Herdamit, Emma", "user083"), + new AccessIdResource("Mitter-Uhe, Emma", "user084"), + new AccessIdResource("Tatt, Erich", "user085"), + new AccessIdResource("Drigend, Ernie", "user086"), + new AccessIdResource("Poly, Esther", "user087"), + new AccessIdResource("Trautz, Eugen", "user088"), + new AccessIdResource("Quiert, Eva", "user089"), + new AccessIdResource("Inurlaub, Fatma", "user090"), + new AccessIdResource("Land, Finn", "user091"), + new AccessIdResource("Sternis, Finn", "user092"), + new AccessIdResource("Furt, Frank", "user093"), + new AccessIdResource("Reich, Frank", "user094"), + new AccessIdResource("Iskaner, Franz", "user095"), + new AccessIdResource("Nerr, Franziska", "user096"), + new AccessIdResource("Zafen, Friedrich", "user097"), + new AccessIdResource("Pomm, Fritz", "user098"), + new AccessIdResource("deWegs, Gera", "user099"), + new AccessIdResource("Staebe, Gitta", "user100"), + new AccessIdResource("Zend, Glenn", "user101"), + new AccessIdResource("Fisch, Grete", "user102"), + new AccessIdResource("Zucker, Gus", "user103"), + new AccessIdResource("Muhn, Hanni", "user104"), + new AccessIdResource("Fermesse, Hanno", "user105"), + new AccessIdResource("Aplast, Hans", "user106"), + new AccessIdResource("Eart, Hans", "user107"), + new AccessIdResource("Back, Hardy", "user108"), + new AccessIdResource("Beau, Harry", "user109"), + new AccessIdResource("Kraut, Heide", "user110"), + new AccessIdResource("Witzka, Heide", "user111"), + new AccessIdResource("Buchen, Hein", "user112"), + new AccessIdResource("Lichkeit, Hein", "user113"), + new AccessIdResource("Suchung, Hein", "user114"), + new AccessIdResource("Ellmann, Heinz", "user115"), + new AccessIdResource("Ketchup, Heinz", "user116"), + new AccessIdResource("Zeim, Hilde", "user117"), + new AccessIdResource("Bilien, Immo", "user118"), + new AccessIdResource("Her, Inge", "user119"), + new AccessIdResource("Wahrsam, Inge", "user120"), + new AccessIdResource("Flamm, Ingo", "user121"), + new AccessIdResource("Enzien, Ingrid", "user122"), + new AccessIdResource("Rohsch, Inken", "user123"), + new AccessIdResource("Ihr, Insa", "user124"), + new AccessIdResource("Nerda, Iska", "user125"), + new AccessIdResource("Eitz, Jens", "user126"), + new AccessIdResource("Nastik, Jim", "user127"), + new AccessIdResource("Gurt, Jo", "user128"), + new AccessIdResource("Kurrth, Jo", "user129"), + new AccessIdResource("Kolade, Joe", "user130"), + new AccessIdResource("Iter, Johann", "user131"), + new AccessIdResource("Tick, Joyce", "user132"), + new AccessIdResource("Case, Justin", "user133"), + new AccessIdResource("Time, Justin", "user134"), + new AccessIdResource("Komp, Jutta", "user135"), + new AccessIdResource("Mauer, Kai", "user136"), + new AccessIdResource("Pirinja, Kai", "user137"), + new AccessIdResource("Serpfalz, Kai", "user138"), + new AccessIdResource("Auer, Karl", "user139"), + new AccessIdResource("Ielauge, Karl", "user140"), + new AccessIdResource("Ifornjen, Karl", "user141"), + new AccessIdResource("Radi, Karl", "user142"), + new AccessIdResource("Verti, Karl", "user143"), + new AccessIdResource("Sery, Karo", "user144"), + new AccessIdResource("Lisator, Katha", "user145"), + new AccessIdResource("Flo, Kati", "user146"), + new AccessIdResource("Schenn, Knut", "user147"), + new AccessIdResource("Achse, Kurt", "user148"), + new AccessIdResource("Zepause, Kurt", "user149"), + new AccessIdResource("Zerr, Kurt", "user150"), + new AccessIdResource("Reden, Lasse", "user151"), + new AccessIdResource("Metten, Lee", "user152"), + new AccessIdResource("Arm, Lene", "user153"), + new AccessIdResource("Thur, Linnea", "user154"), + new AccessIdResource("Bonn, Lisa", "user155"), + new AccessIdResource("Sembourg, Luc", "user156"), + new AccessIdResource("Rung, Lucky", "user157"), + new AccessIdResource("Zafen, Ludwig", "user158"), + new AccessIdResource("Hauden, Lukas", "user159"), + new AccessIdResource("Hose, Lutz", "user160"), + new AccessIdResource("Tablette, Lutz", "user161"), + new AccessIdResource("Fehr, Luzie", "user162"), + new AccessIdResource("Nalyse, Magda", "user163"), + new AccessIdResource("Ehfer, Maik", "user164"), + new AccessIdResource("Sehr, Malte", "user165"), + new AccessIdResource("Thon, Mara", "user166"), + new AccessIdResource("Quark, Marga", "user167"), + new AccessIdResource("Nade, Marie", "user168"), + new AccessIdResource("Niert, Marie", "user169"), + new AccessIdResource("Neese, Mario", "user170"), + new AccessIdResource("Nette, Marion", "user171"), + new AccessIdResource("Nesium, Mark", "user172"), + new AccessIdResource("Thalle, Mark", "user173"), + new AccessIdResource("Diven, Marle", "user174"), + new AccessIdResource("Fitz, Marle", "user175"), + new AccessIdResource("Pfahl, Marta", "user176"), + new AccessIdResource("Zorn, Martin", "user177"), + new AccessIdResource("Krissmes, Mary", "user178"), + new AccessIdResource("Jess, Matt", "user179"), + new AccessIdResource("Strammer, Max", "user180"), + new AccessIdResource("Mumm, Maxi", "user181"), + new AccessIdResource("Morphose, Meta", "user182"), + new AccessIdResource("Uh, Mia", "user183"), + new AccessIdResource("Rofon, Mike", "user184"), + new AccessIdResource("Rosoft, Mike", "user185"), + new AccessIdResource("Liter, Milli", "user186"), + new AccessIdResource("Thär, Milli", "user187"), + new AccessIdResource("Welle, Mirko", "user188"), + new AccessIdResource("Thorat, Mo", "user189"), + new AccessIdResource("Thor, Moni", "user190"), + new AccessIdResource("Kinolta, Monika", "user191"), + new AccessIdResource("Mundhaar, Monika", "user192"), + new AccessIdResource("Munter, Monika", "user193"), + new AccessIdResource("Zwerg, Nat", "user194"), + new AccessIdResource("Elmine, Nick", "user195"), + new AccessIdResource("Thien, Niko", "user196"), + new AccessIdResource("Pferd, Nils", "user197"), + new AccessIdResource("Lerweise, Norma", "user198"), + new AccessIdResource("Motor, Otto", "user199"), + new AccessIdResource("Totol, Otto", "user200"), + new AccessIdResource("Nerr, Paula", "user201"), + new AccessIdResource("Imeter, Peer", "user202"), + new AccessIdResource("Serkatze, Peer", "user203"), + new AccessIdResource("Gogisch, Peter", "user204"), + new AccessIdResource("Silje, Peter", "user205"), + new AccessIdResource("Harmonie, Phil", "user206"), + new AccessIdResource("Ihnen, Philip", "user207"), + new AccessIdResource("Uto, Pia", "user208"), + new AccessIdResource("Kothek, Pina", "user209"), + new AccessIdResource("Zar, Pit", "user210"), + new AccessIdResource("Zeih, Polly", "user211"), + new AccessIdResource("Tswan, Puh", "user212"), + new AccessIdResource("Zufall, Rainer", "user213"), + new AccessIdResource("Lien, Rita", "user214"), + new AccessIdResource("Held, Roman", "user215"), + new AccessIdResource("Haar, Ross", "user216"), + new AccessIdResource("Dick, Roy", "user217"), + new AccessIdResource("Enplaner, Ruth", "user218"), + new AccessIdResource("Kommen, Ryan", "user219"), + new AccessIdResource("Philo, Sophie", "user220"), + new AccessIdResource("Matisier, Stig", "user221"), + new AccessIdResource("Loniki, Tessa", "user222"), + new AccessIdResource("Tralisch, Thea", "user223"), + new AccessIdResource("Logie, Theo", "user224"), + new AccessIdResource("Ister, Thorn", "user225"), + new AccessIdResource("Buktu, Tim", "user226"), + new AccessIdResource("Ate, Tom", "user227"), + new AccessIdResource("Pie, Udo", "user228"), + new AccessIdResource("Aloe, Vera", "user229"), + new AccessIdResource("Hausver, Walter", "user230"), + new AccessIdResource("Schuh, Wanda", "user231"), + new AccessIdResource("Rahm, Wolf", "user232"), + new AccessIdResource("businessadmin", "cn=businessadmin,ou=groups,o=taskanatest"), + new AccessIdResource("UsersGroup", "cn=usersgroup,ou=groups,o=taskanatest"), + new AccessIdResource("DevelopersGroup", "cn=developersgroup,ou=groups,o=taskanatest"), + new AccessIdResource("businessadmin", "cn=customersgroup,ou=groups,o=taskanatest"), + new AccessIdResource("user_domain_A", "cn=user_domain_a,ou=groups,o=taskanatest"), + new AccessIdResource("monitor", "cn=monitor,ou=groups,o=taskanatest"), + new AccessIdResource("user_domain_C", "cn=user_domain_c,ou=groups,o=taskanatest"), + new AccessIdResource("user_domain_D", "cn=user_domain_d,ou=groups,o=taskanatest"), + new AccessIdResource("admin", "cn=admin,ou=groups,o=taskanatest"), + new AccessIdResource( + "manager_domain_B", "cn=manager_domain_b,ou=groups,o=taskanatest"), + new AccessIdResource( + "manager_domain_C", "cn=manager_domain_c,ou=groups,o=taskanatest"), + new AccessIdResource( + "manager_domain_D", "cn=manager_domain_d,ou=groups,o=taskanatest"), + new AccessIdResource("teamlead_2", "cn=teamlead_2" + ",ou=groups,o=taskanatest"), + new AccessIdResource("teamlead_4", "cn=teamlead_4" + ",ou=groups,o=taskanatest"), + new AccessIdResource("team_3", "cn=team_3" + ",ou=groups,o=taskanatest"), + new AccessIdResource("team_4", "cn=team_4" + ",ou=groups,o=taskanatest"))); - new AccessIdResource("user_domain_A", "cn=user_domain_a,ou=groups,o=taskanatest"), - new AccessIdResource("monitor", "cn=monitor,ou=groups,o=taskanatest"), - new AccessIdResource("user_domain_C", "cn=user_domain_c,ou=groups,o=taskanatest"), - new AccessIdResource("user_domain_D", "cn=user_domain_d,ou=groups,o=taskanatest"), + @Override + public List findMatchingAccessId( + String searchFor, int maxNumberOfReturnedAccessIds) { + return findAcessIdResource(searchFor, maxNumberOfReturnedAccessIds, false); + } - new AccessIdResource("admin", "cn=admin,ou=groups,o=taskanatest"), - new AccessIdResource("manager_domain_B", "cn=manager_domain_b,ou=groups,o=taskanatest"), - new AccessIdResource("manager_domain_C", "cn=manager_domain_c,ou=groups,o=taskanatest"), - new AccessIdResource("manager_domain_D", "cn=manager_domain_d,ou=groups,o=taskanatest"), - - new AccessIdResource("teamlead_2", "cn=teamlead_2" + ",ou=groups,o=taskanatest"), - new AccessIdResource("teamlead_4", "cn=teamlead_4" + ",ou=groups,o=taskanatest"), - new AccessIdResource("team_3", "cn=team_3" + ",ou=groups,o=taskanatest"), - new AccessIdResource("team_4", "cn=team_4" + ",ou=groups,o=taskanatest"))); - - @Override - public List findMatchingAccessId(String searchFor, int maxNumberOfReturnedAccessIds) { - return findAcessIdResource(searchFor, maxNumberOfReturnedAccessIds, false); + @Override + public List findGroupsOfUser( + String searchFor, int maxNumberOfReturnedAccessIds) { + if (users == null) { + addUsersToGroups(); } + return findAcessIdResource(searchFor, maxNumberOfReturnedAccessIds, true); + } - @Override - public List findGroupsOfUser(String searchFor, int maxNumberOfReturnedAccessIds) { - if (users == null) { - addUsersToGroups(); - } - return findAcessIdResource(searchFor, maxNumberOfReturnedAccessIds, true); - } + @Override + public List validateAccessId(String accessId) { + return accessIds.stream() + .filter(t -> (t.getAccessId().equalsIgnoreCase(accessId.toLowerCase()))) + .collect(Collectors.toList()); + } - @Override - public List validateAccessId(String accessId) { - return accessIds.stream() - .filter(t -> (t.getAccessId().equalsIgnoreCase(accessId.toLowerCase()))) - .collect(Collectors.toList()); - } - - private List findAcessIdResource(String searchFor, int maxNumberOfReturnedAccessIds, - boolean groupMember) { - List usersAndGroups = accessIds.stream() - .filter(t -> (t.getName().toLowerCase().contains(searchFor.toLowerCase()) - || t.getAccessId().toLowerCase().contains(searchFor.toLowerCase()))) + private List findAcessIdResource( + String searchFor, int maxNumberOfReturnedAccessIds, boolean groupMember) { + List usersAndGroups = + accessIds.stream() + .filter( + t -> + (t.getName().toLowerCase().contains(searchFor.toLowerCase()) + || t.getAccessId().toLowerCase().contains(searchFor.toLowerCase()))) .collect(Collectors.toList()); - List usersAndGroupsAux = new ArrayList<>(usersAndGroups); - if (groupMember) { - usersAndGroupsAux.forEach(item -> { - if (users.get(item) != null) { - usersAndGroups.addAll(users.get(item)); - } - }); - } - - usersAndGroups.sort((AccessIdResource a, AccessIdResource b) -> { - return a.getAccessId().compareToIgnoreCase(b.getAccessId()); - }); - - List result = usersAndGroups.subList(0, - Math.min(usersAndGroups.size(), maxNumberOfReturnedAccessIds)); - - return result; + List usersAndGroupsAux = new ArrayList<>(usersAndGroups); + if (groupMember) { + usersAndGroupsAux.forEach( + item -> { + if (users.get(item) != null) { + usersAndGroups.addAll(users.get(item)); + } + }); } - private void addUsersToGroups() { - List groups = new ArrayList<>(); - users = new HashMap<>(); - - accessIds.forEach(item -> { - if (!item.getAccessId().contains("ou=groups")) { - users.put(item, new ArrayList<>()); - } else { - groups.add(item); - } + usersAndGroups.sort( + (AccessIdResource a, AccessIdResource b) -> { + return a.getAccessId().compareToIgnoreCase(b.getAccessId()); }); - int groupNumber = 0; - List group0 = new ArrayList<>(), group1 = new ArrayList<>(), group2 = new ArrayList<>(), group3 = new ArrayList<>(); + List result = + usersAndGroups.subList(0, Math.min(usersAndGroups.size(), maxNumberOfReturnedAccessIds)); - for (AccessIdResource group : groups) { - switch (groupNumber) { - case 0: - group0.add(group); - break; - case 1: - group1.add(group); - break; - case 2: - group2.add(group); - break; - case 3: - group3.add(group); - break; - default: - break; - } - groupNumber = (groupNumber + 1) % 4; - } + return result; + } - int countUser = 0; - for (AccessIdResource item : accessIds) { - if (!item.getAccessId().contains("ou=groups")) { - switch (countUser) { - case 0: - users.put(item, group0); - break; - case 1: - users.put(item, group1); - break; - case 2: - users.put(item, group2); - break; - case 3: - users.put(item, group3); - break; - default: - break; - } - } - countUser = (countUser + 1) % 4; - } + private void addUsersToGroups() { + List groups = new ArrayList<>(); + users = new HashMap<>(); + + accessIds.forEach( + item -> { + if (!item.getAccessId().contains("ou=groups")) { + users.put(item, new ArrayList<>()); + } else { + groups.add(item); + } + }); + + int groupNumber = 0; + List group0 = new ArrayList<>(), + group1 = new ArrayList<>(), + group2 = new ArrayList<>(), + group3 = new ArrayList<>(); + + for (AccessIdResource group : groups) { + switch (groupNumber) { + case 0: + group0.add(group); + break; + case 1: + group1.add(group); + break; + case 2: + group2.add(group); + break; + case 3: + group3.add(group); + break; + default: + break; + } + groupNumber = (groupNumber + 1) % 4; } + int countUser = 0; + for (AccessIdResource item : accessIds) { + if (!item.getAccessId().contains("ou=groups")) { + switch (countUser) { + case 0: + users.put(item, group0); + break; + case 1: + users.put(item, group1); + break; + case 2: + users.put(item, group2); + break; + case 3: + users.put(item, group3); + break; + default: + break; + } + } + countUser = (countUser + 1) % 4; + } + } } diff --git a/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/WebMvcConfig.java b/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/WebMvcConfig.java index 3f5e1dea6..63d0cb8eb 100644 --- a/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/WebMvcConfig.java +++ b/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/WebMvcConfig.java @@ -1,9 +1,9 @@ package pro.taskana.rest; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import java.util.List; - import javax.annotation.PostConstruct; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; @@ -11,48 +11,43 @@ import org.springframework.http.converter.json.MappingJackson2HttpMessageConvert import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -/** - * The Web MVC Configuration. - * - */ +/** The Web MVC Configuration. */ @Configuration @EnableWebMvc public class WebMvcConfig implements WebMvcConfigurer { - private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { - "classpath:/META-INF/resources/", "classpath:/resources/", - "classpath:/static/", "classpath:/public/"}; + private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { + "classpath:/META-INF/resources/", "classpath:/resources/", + "classpath:/static/", "classpath:/public/" + }; - @Autowired - private ObjectMapper objectMapper; + @Autowired private ObjectMapper objectMapper; - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - if (!registry.hasMappingForPattern("/webjars/**")) { - registry.addResourceHandler("/webjars/**").addResourceLocations( - "classpath:/META-INF/resources/webjars/"); - } - if (!registry.hasMappingForPattern("/**")) { - registry.addResourceHandler("/**").addResourceLocations( - CLASSPATH_RESOURCE_LOCATIONS); - } + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + if (!registry.hasMappingForPattern("/webjars/**")) { + registry + .addResourceHandler("/webjars/**") + .addResourceLocations("classpath:/META-INF/resources/webjars/"); } - - @Override - public void extendMessageConverters(List> converters) { - for (HttpMessageConverter converter : converters) { - if (converter instanceof MappingJackson2HttpMessageConverter) { - MappingJackson2HttpMessageConverter jacksonConverter = (MappingJackson2HttpMessageConverter) converter; - jacksonConverter.setPrettyPrint(true); - } - } + if (!registry.hasMappingForPattern("/**")) { + registry.addResourceHandler("/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS); } + } - @PostConstruct - public void enableObjectIndent() { - objectMapper.enable(SerializationFeature.INDENT_OUTPUT); + @Override + public void extendMessageConverters(List> converters) { + for (HttpMessageConverter converter : converters) { + if (converter instanceof MappingJackson2HttpMessageConverter) { + MappingJackson2HttpMessageConverter jacksonConverter = + (MappingJackson2HttpMessageConverter) converter; + jacksonConverter.setPrettyPrint(true); + } } + } + + @PostConstruct + public void enableObjectIndent() { + objectMapper.enable(SerializationFeature.INDENT_OUTPUT); + } } diff --git a/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/controllers/LoginController.java b/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/controllers/LoginController.java index 8ce1edbde..d17d12247 100644 --- a/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/controllers/LoginController.java +++ b/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/controllers/LoginController.java @@ -7,18 +7,16 @@ import org.springframework.stereotype.Controller; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -/** - * The login controller. - */ +/** The login controller. */ @Controller public class LoginController implements WebMvcConfigurer { - private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class); + private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class); - @Override - public void addViewControllers(ViewControllerRegistry registry) { - LOGGER.debug("Entry to addViewControllers()"); - registry.addViewController("/login").setViewName("login"); - registry.setOrder(Ordered.HIGHEST_PRECEDENCE); - LOGGER.debug("Exit from addViewControllers()"); - } + @Override + public void addViewControllers(ViewControllerRegistry registry) { + LOGGER.debug("Entry to addViewControllers()"); + registry.addViewController("/login").setViewName("login"); + registry.setOrder(Ordered.HIGHEST_PRECEDENCE); + LOGGER.debug("Exit from addViewControllers()"); + } } diff --git a/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/controllers/ViewController.java b/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/controllers/ViewController.java index 170c4f7cc..4fefc9d30 100644 --- a/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/controllers/ViewController.java +++ b/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/controllers/ViewController.java @@ -3,14 +3,12 @@ package pro.taskana.rest.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; -/** - * The view controller. - */ +/** The view controller. */ @Controller public class ViewController { - @RequestMapping({"", "taskana/**"}) - public String index() { - return "forward:/index.html"; - } + @RequestMapping({"", "taskana/**"}) + public String index() { + return "forward:/index.html"; + } } diff --git a/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/models/User.java b/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/models/User.java index 533af5fb4..56a9846fd 100644 --- a/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/models/User.java +++ b/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/models/User.java @@ -1,31 +1,28 @@ package pro.taskana.rest.models; -/** - * model for a user. - * - */ +/** model for a user. */ public class User { - private String username; - private String password; + private String username; + private String password; - public String getUsername() { - return username; - } + public String getUsername() { + return username; + } - public void setUsername(String username) { - this.username = username; - } + public void setUsername(String username) { + this.username = username; + } - public String getPassword() { - return password; - } + public String getPassword() { + return password; + } - public void setPassword(String password) { - this.password = password; - } + public void setPassword(String password) { + this.password = password; + } - @Override - public String toString() { - return "User [" + "username= " + this.username + "]"; - } + @Override + public String toString() { + return "User [" + "username= " + this.username + "]"; + } } diff --git a/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/security/SampleLoginModule.java b/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/security/SampleLoginModule.java index 66516bf5d..bc4e9be1e 100644 --- a/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/security/SampleLoginModule.java +++ b/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/security/SampleLoginModule.java @@ -2,14 +2,12 @@ package pro.taskana.rest.security; import java.util.List; import java.util.Map; - import javax.security.auth.Subject; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.spi.LoginModule; - import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import pro.taskana.ldap.LdapCacheTestImpl; @@ -17,68 +15,69 @@ import pro.taskana.rest.resource.AccessIdResource; import pro.taskana.security.GroupPrincipal; import pro.taskana.security.UserPrincipal; -/** - * TODO. - */ +/** TODO. */ public class SampleLoginModule extends UsernamePasswordAuthenticationFilter implements LoginModule { - private NameCallback nameCallback; + private NameCallback nameCallback; - private PasswordCallback passwordCallback; + private PasswordCallback passwordCallback; - private Subject subject; + private Subject subject; - @Override - public boolean abort() { - return true; + @Override + public boolean abort() { + return true; + } + + @Override + public boolean commit() { + addUserPrincipalToSubject(); + addGroupSubjectsDerivedFromUsername(); + return true; + } + + @Override + public void initialize( + Subject subject, + CallbackHandler callbackHandler, + Map sharedState, + Map options) { + + this.subject = subject; + + try { + nameCallback = new NameCallback("prompt"); + passwordCallback = new PasswordCallback("prompt", false); + + callbackHandler.handle(new Callback[] {nameCallback, passwordCallback}); + } catch (Exception e) { + throw new RuntimeException(e); } + } - @Override - public boolean commit() { - addUserPrincipalToSubject(); - addGroupSubjectsDerivedFromUsername(); - return true; - } + @Override + public boolean login() { + return nameCallback.getName().equals(new String(passwordCallback.getPassword())); + } - private void addGroupSubjectsDerivedFromUsername() { - LdapCacheTestImpl ldapCacheTest = new LdapCacheTestImpl(); - String username = nameCallback.getName().toLowerCase(); - List groups = ldapCacheTest.findGroupsOfUser(username, Integer.MAX_VALUE); - groups.forEach((AccessIdResource group) -> { - if (group.getAccessId().contains("ou=groups")) { - subject.getPrincipals().add(new GroupPrincipal(group.getName())); - } + @Override + public boolean logout() { + return true; + } + + private void addGroupSubjectsDerivedFromUsername() { + LdapCacheTestImpl ldapCacheTest = new LdapCacheTestImpl(); + String username = nameCallback.getName().toLowerCase(); + List groups = ldapCacheTest.findGroupsOfUser(username, Integer.MAX_VALUE); + groups.forEach( + (AccessIdResource group) -> { + if (group.getAccessId().contains("ou=groups")) { + subject.getPrincipals().add(new GroupPrincipal(group.getName())); + } }); - } - - private void addUserPrincipalToSubject() { - subject.getPrincipals().add(new UserPrincipal(nameCallback.getName())); - } - - @Override - public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, - Map options) { - - this.subject = subject; - - try { - nameCallback = new NameCallback("prompt"); - passwordCallback = new PasswordCallback("prompt", false); - - callbackHandler.handle(new Callback[] {nameCallback, passwordCallback}); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - @Override - public boolean login() { - return nameCallback.getName().equals(new String(passwordCallback.getPassword())); - } - - @Override - public boolean logout() { - return true; - } + } + private void addUserPrincipalToSubject() { + subject.getPrincipals().add(new UserPrincipal(nameCallback.getName())); + } } diff --git a/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/security/SampleRoleGranter.java b/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/security/SampleRoleGranter.java index 6afba562c..28547e228 100644 --- a/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/security/SampleRoleGranter.java +++ b/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/security/SampleRoleGranter.java @@ -3,16 +3,13 @@ package pro.taskana.rest.security; import java.security.Principal; import java.util.Collections; import java.util.Set; - import org.springframework.security.authentication.jaas.AuthorityGranter; -/** - * TODO. - */ +/** TODO. */ public class SampleRoleGranter implements AuthorityGranter { - @Override - public Set grant(Principal principal) { - return Collections.singleton(principal.getName()); - } + @Override + public Set grant(Principal principal) { + return Collections.singleton(principal.getName()); + } } diff --git a/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/security/WebSecurityConfig.java b/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/security/WebSecurityConfig.java index 54e188cda..bb0371838 100644 --- a/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/security/WebSecurityConfig.java +++ b/rest/taskana-rest-spring-example-common/src/main/java/pro/taskana/rest/security/WebSecurityConfig.java @@ -22,105 +22,101 @@ import org.springframework.web.filter.CorsFilter; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -/** - * Default basic configuration for taskana web example. - */ +/** Default basic configuration for taskana web example. */ @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { - @Value("${devMode:false}") - private boolean devMode; + @Value("${devMode:false}") + private boolean devMode; - @Override - protected void configure(HttpSecurity http) throws Exception { + @Bean + public JaasAuthenticationProvider jaasAuthProvider() { + JaasAuthenticationProvider authenticationProvider = new JaasAuthenticationProvider(); + authenticationProvider.setAuthorityGranters(new AuthorityGranter[] {new SampleRoleGranter()}); + authenticationProvider.setCallbackHandlers( + new JaasAuthenticationCallbackHandler[] { + new JaasNameCallbackHandler(), new JaasPasswordCallbackHandler() + }); + authenticationProvider.setLoginContextName("taskana"); + authenticationProvider.setLoginConfig(new ClassPathResource("pss_jaas.config")); + return authenticationProvider; + } - http.authorizeRequests() - .antMatchers( - "/css/**", - "/img/**") - .permitAll() - .and() - .csrf() - .disable() - .httpBasic() - .and() - .authenticationProvider(jaasAuthProvider()) - .authorizeRequests() - .antMatchers(HttpMethod.GET, "/docs/**") - .permitAll() - .and() - .addFilter(new JaasApiIntegrationFilter()); + @Bean + public WebMvcConfigurer corsConfigurer() { + return new WebMvcConfigurer() { - if (devMode) { - http.headers() - .frameOptions() - .sameOrigin() - .and() - .authorizeRequests() - .antMatchers("/h2-console/**") - .permitAll(); - } else { - AddLoginPageConfiguration(http); - } + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**").allowedOrigins("*"); + } + }; + } + @Bean + public FilterRegistrationBean corsFilter() { + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + CorsConfiguration config = new CorsConfiguration(); + config.setAllowCredentials(true); + config.addAllowedOrigin("*"); + config.addAllowedHeader("*"); + config.addAllowedMethod("*"); + config.addAllowedMethod("POST"); + source.registerCorsConfiguration("/**", config); + FilterRegistrationBean bean = new FilterRegistrationBean<>(new CorsFilter(source)); + bean.setOrder(0); + return bean; + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + + http.authorizeRequests() + .antMatchers("/css/**", "/img/**") + .permitAll() + .and() + .csrf() + .disable() + .httpBasic() + .and() + .authenticationProvider(jaasAuthProvider()) + .authorizeRequests() + .antMatchers(HttpMethod.GET, "/docs/**") + .permitAll() + .and() + .addFilter(new JaasApiIntegrationFilter()); + + if (devMode) { + http.headers() + .frameOptions() + .sameOrigin() + .and() + .authorizeRequests() + .antMatchers("/h2-console/**") + .permitAll(); + } else { + AddLoginPageConfiguration(http); } + } - @Bean - public JaasAuthenticationProvider jaasAuthProvider() { - JaasAuthenticationProvider authenticationProvider = new JaasAuthenticationProvider(); - authenticationProvider.setAuthorityGranters(new AuthorityGranter[] {new SampleRoleGranter()}); - authenticationProvider.setCallbackHandlers(new JaasAuthenticationCallbackHandler[] { - new JaasNameCallbackHandler(), new JaasPasswordCallbackHandler()}); - authenticationProvider.setLoginContextName("taskana"); - authenticationProvider.setLoginConfig(new ClassPathResource("pss_jaas.config")); - return authenticationProvider; - } - - @Bean - public WebMvcConfigurer corsConfigurer() { - return new WebMvcConfigurer() { - - @Override - public void addCorsMappings(CorsRegistry registry) { - registry.addMapping("/**").allowedOrigins("*"); - } - }; - } - - @Bean - public FilterRegistrationBean corsFilter() { - UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); - CorsConfiguration config = new CorsConfiguration(); - config.setAllowCredentials(true); - config.addAllowedOrigin("*"); - config.addAllowedHeader("*"); - config.addAllowedMethod("*"); - config.addAllowedMethod("POST"); - source.registerCorsConfiguration("/**", config); - FilterRegistrationBean bean = new FilterRegistrationBean<>(new CorsFilter(source)); - bean.setOrder(0); - return bean; - } - - private void AddLoginPageConfiguration(HttpSecurity http) throws Exception { - http - .authorizeRequests() - .anyRequest() - .fullyAuthenticated() - .and() - .formLogin() - .loginPage("/login") - .failureUrl("/login?error") - .defaultSuccessUrl("/") - .permitAll() - .and() - .logout() - .invalidateHttpSession(true) - .clearAuthentication(true) - .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) - .logoutSuccessUrl("/login?logout") - .deleteCookies("JSESSIONID") - .permitAll(); - } + private void AddLoginPageConfiguration(HttpSecurity http) throws Exception { + http.authorizeRequests() + .anyRequest() + .fullyAuthenticated() + .and() + .formLogin() + .loginPage("/login") + .failureUrl("/login?error") + .defaultSuccessUrl("/") + .permitAll() + .and() + .logout() + .invalidateHttpSession(true) + .clearAuthentication(true) + .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) + .logoutSuccessUrl("/login?logout") + .deleteCookies("JSESSIONID") + .permitAll(); + } } diff --git a/rest/taskana-rest-spring-example-common/src/test/java/pro/taskana/RestHelper.java b/rest/taskana-rest-spring-example-common/src/test/java/pro/taskana/RestHelper.java index 623d1fdab..555902e39 100644 --- a/rest/taskana-rest-spring-example-common/src/test/java/pro/taskana/RestHelper.java +++ b/rest/taskana-rest-spring-example-common/src/test/java/pro/taskana/RestHelper.java @@ -1,4 +1,8 @@ package pro.taskana; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.hateoas.hal.Jackson2HalModule; @@ -10,66 +14,58 @@ import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; - -/** - * Helps to simplify rest api testing. - */ +/** Helps to simplify rest api testing. */ @Component public class RestHelper { - @Autowired - Environment environment; + public static RestTemplate template = getRestTemplate(); + @Autowired Environment environment; - public static RestTemplate template = getRestTemplate(); + public String toUrl(String relativeUrl, Object... uriVariables) { + return UriComponentsBuilder.fromPath(relativeUrl) + .scheme("http") + .host("127.0.0.1") + .port(environment.getProperty("local.server.port")) + .build(uriVariables) + .toString(); + } - public String toUrl(String relativeUrl, Object... uriVariables) { - return UriComponentsBuilder.fromPath(relativeUrl) - .scheme("http") - .host("127.0.0.1") - .port(environment.getProperty("local.server.port")) - .build(uriVariables) - .toString(); - } + public HttpEntity defaultRequest() { + return new HttpEntity<>(getHeaders()); + } - public HttpEntity defaultRequest() { - return new HttpEntity<>(getHeaders()); - } + public HttpHeaders getHeaders() { + HttpHeaders headers = new HttpHeaders(); + headers.add("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x"); + headers.add("Content-Type", "application/json"); + return headers; + } - public HttpHeaders getHeaders() { - HttpHeaders headers = new HttpHeaders(); - headers.add("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x"); - headers.add("Content-Type", "application/json"); - return headers; - } + public HttpHeaders getHeadersAdmin() { + HttpHeaders headers = new HttpHeaders(); + headers.add("Authorization", "Basic YWRtaW46YWRtaW4="); // admin:admin + headers.add("Content-Type", "application/hal+json"); + return headers; + } - public HttpHeaders getHeadersAdmin() { - HttpHeaders headers = new HttpHeaders(); - headers.add("Authorization", "Basic YWRtaW46YWRtaW4="); // admin:admin - headers.add("Content-Type", "application/hal+json"); - return headers; - } + /** + * Return a REST template which is capable of dealing with responses in HAL format. + * + * @return RestTemplate + */ + public static RestTemplate getRestTemplate() { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + mapper.registerModule(new Jackson2HalModule()); - /** - * Return a REST template which is capable of dealing with responses in HAL format. - * - * @return RestTemplate - */ - public static RestTemplate getRestTemplate() { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); - mapper.registerModule(new Jackson2HalModule()); + MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); + converter.setSupportedMediaTypes(MediaType.parseMediaTypes("application/hal+json")); + converter.setObjectMapper(mapper); - MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); - converter.setSupportedMediaTypes(MediaType.parseMediaTypes("application/hal+json")); - converter.setObjectMapper(mapper); - - RestTemplate template = new RestTemplate(); - //important to add first to ensure priority - template.getMessageConverters().add(0, converter); - return template; - } + RestTemplate template = new RestTemplate(); + // important to add first to ensure priority + template.getMessageConverters().add(0, converter); + return template; + } } diff --git a/rest/taskana-rest-spring-example-common/src/test/java/pro/taskana/jobs/AsyncUpdateJobIntTest.java b/rest/taskana-rest-spring-example-common/src/test/java/pro/taskana/jobs/AsyncUpdateJobIntTest.java index ffb3990c3..2589f1815 100644 --- a/rest/taskana-rest-spring-example-common/src/test/java/pro/taskana/jobs/AsyncUpdateJobIntTest.java +++ b/rest/taskana-rest-spring-example-common/src/test/java/pro/taskana/jobs/AsyncUpdateJobIntTest.java @@ -3,11 +3,11 @@ package pro.taskana.jobs; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; +import com.fasterxml.jackson.databind.ObjectMapper; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -22,8 +22,6 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.web.client.RestTemplate; -import com.fasterxml.jackson.databind.ObjectMapper; - import pro.taskana.Classification; import pro.taskana.RestHelper; import pro.taskana.Task; @@ -35,123 +33,134 @@ import pro.taskana.rest.resource.ClassificationResourceAssembler; import pro.taskana.rest.resource.TaskResource; import pro.taskana.rest.resource.TaskResourceAssembler; -/** - * Test async updates. - */ +/** Test async updates. */ @ActiveProfiles({"test"}) @ExtendWith(SpringExtension.class) -@SpringBootTest(classes = RestConfiguration.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@SpringBootTest( + classes = RestConfiguration.class, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class AsyncUpdateJobIntTest { - private static final String CLASSIFICATION_ID = "CLI:100000000000000000000000000000000003"; + private static final String CLASSIFICATION_ID = "CLI:100000000000000000000000000000000003"; + static RestTemplate template; + @Autowired ClassificationResourceAssembler classificationResourceAssembler; + @Autowired TaskResourceAssembler taskResourceAssembler; + @Autowired JobScheduler jobScheduler; + @Autowired RestHelper restHelper; - @Autowired - ClassificationResourceAssembler classificationResourceAssembler; + @BeforeAll + static void init() { + template = RestHelper.getRestTemplate(); + } - @Autowired - TaskResourceAssembler taskResourceAssembler; + @Test + void testUpdateClassificationPrioServiceLevel() throws Exception { - @Autowired - JobScheduler jobScheduler; + // 1st step: get old classification : + Instant before = Instant.now(); + ObjectMapper mapper = new ObjectMapper(); - @Autowired RestHelper restHelper; - - static RestTemplate template; - - @BeforeAll - static void init() { - template = RestHelper.getRestTemplate(); - } - - @Test - void testUpdateClassificationPrioServiceLevel() - throws Exception { - - // 1st step: get old classification : - Instant before = Instant.now(); - ObjectMapper mapper = new ObjectMapper(); - - ResponseEntity response = template.exchange( + ResponseEntity response = + template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS_ID, CLASSIFICATION_ID), HttpMethod.GET, new HttpEntity(restHelper.getHeaders()), - ParameterizedTypeReference.forType(ClassificationResource.class) - ); + ParameterizedTypeReference.forType(ClassificationResource.class)); - assertNotNull(response.getBody()); - ClassificationResource classification = response.getBody(); - assertNotNull(classification.getLink(Link.REL_SELF)); + assertNotNull(response.getBody()); + ClassificationResource classification = response.getBody(); + assertNotNull(classification.getLink(Link.REL_SELF)); - // 2nd step: modify classification and trigger update - classification.removeLinks(); - classification.setServiceLevel("P5D"); - classification.setPriority(1000); + // 2nd step: modify classification and trigger update + classification.removeLinks(); + classification.setServiceLevel("P5D"); + classification.setPriority(1000); - template.put( - restHelper.toUrl(Mapping.URL_CLASSIFICATIONS_ID, CLASSIFICATION_ID), - new HttpEntity<>(mapper.writeValueAsString(classification), restHelper.getHeaders()) - ); + template.put( + restHelper.toUrl(Mapping.URL_CLASSIFICATIONS_ID, CLASSIFICATION_ID), + new HttpEntity<>(mapper.writeValueAsString(classification), restHelper.getHeaders())); - //trigger jobs twice to refresh all entries. first entry on the first call and follow up on the seconds call - jobScheduler.triggerJobs(); - jobScheduler.triggerJobs(); + // trigger jobs twice to refresh all entries. first entry on the first call and follow up on the + // seconds call + jobScheduler.triggerJobs(); + jobScheduler.triggerJobs(); - // verify the classification modified timestamp is after 'before' - ResponseEntity repeatedResponse = template.exchange( + // verify the classification modified timestamp is after 'before' + ResponseEntity repeatedResponse = + template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS_ID, CLASSIFICATION_ID), HttpMethod.GET, new HttpEntity(restHelper.getHeaders()), - ParameterizedTypeReference.forType(ClassificationResource.class) - ); + ParameterizedTypeReference.forType(ClassificationResource.class)); - assertNotNull(repeatedResponse.getBody()); + assertNotNull(repeatedResponse.getBody()); - ClassificationResource modifiedClassificationResource = repeatedResponse.getBody(); - Classification modifiedClassification = classificationResourceAssembler.toModel(modifiedClassificationResource); + ClassificationResource modifiedClassificationResource = repeatedResponse.getBody(); + Classification modifiedClassification = + classificationResourceAssembler.toModel(modifiedClassificationResource); - assertFalse(before.isAfter(modifiedClassification.getModified())); + assertFalse(before.isAfter(modifiedClassification.getModified())); - List affectedTasks = new ArrayList<>( - Arrays.asList("TKI:000000000000000000000000000000000003", "TKI:000000000000000000000000000000000004", - "TKI:000000000000000000000000000000000005", "TKI:000000000000000000000000000000000006", - "TKI:000000000000000000000000000000000007", "TKI:000000000000000000000000000000000008", - "TKI:000000000000000000000000000000000009", "TKI:000000000000000000000000000000000010", - "TKI:000000000000000000000000000000000011", "TKI:000000000000000000000000000000000012", - "TKI:000000000000000000000000000000000013", "TKI:000000000000000000000000000000000014", - "TKI:000000000000000000000000000000000015", "TKI:000000000000000000000000000000000016", - "TKI:000000000000000000000000000000000017", "TKI:000000000000000000000000000000000018", - "TKI:000000000000000000000000000000000019", "TKI:000000000000000000000000000000000020", - "TKI:000000000000000000000000000000000021", "TKI:000000000000000000000000000000000022", - "TKI:000000000000000000000000000000000023", "TKI:000000000000000000000000000000000024", - "TKI:000000000000000000000000000000000025", "TKI:000000000000000000000000000000000026", - "TKI:000000000000000000000000000000000027", "TKI:000000000000000000000000000000000028", - "TKI:000000000000000000000000000000000029", "TKI:000000000000000000000000000000000030", - "TKI:000000000000000000000000000000000031", "TKI:000000000000000000000000000000000032", - "TKI:000000000000000000000000000000000033", "TKI:000000000000000000000000000000000034", - "TKI:000000000000000000000000000000000035", "TKI:000000000000000000000000000000000100", - "TKI:000000000000000000000000000000000101", "TKI:000000000000000000000000000000000102", + List affectedTasks = + new ArrayList<>( + Arrays.asList( + "TKI:000000000000000000000000000000000003", + "TKI:000000000000000000000000000000000004", + "TKI:000000000000000000000000000000000005", + "TKI:000000000000000000000000000000000006", + "TKI:000000000000000000000000000000000007", + "TKI:000000000000000000000000000000000008", + "TKI:000000000000000000000000000000000009", + "TKI:000000000000000000000000000000000010", + "TKI:000000000000000000000000000000000011", + "TKI:000000000000000000000000000000000012", + "TKI:000000000000000000000000000000000013", + "TKI:000000000000000000000000000000000014", + "TKI:000000000000000000000000000000000015", + "TKI:000000000000000000000000000000000016", + "TKI:000000000000000000000000000000000017", + "TKI:000000000000000000000000000000000018", + "TKI:000000000000000000000000000000000019", + "TKI:000000000000000000000000000000000020", + "TKI:000000000000000000000000000000000021", + "TKI:000000000000000000000000000000000022", + "TKI:000000000000000000000000000000000023", + "TKI:000000000000000000000000000000000024", + "TKI:000000000000000000000000000000000025", + "TKI:000000000000000000000000000000000026", + "TKI:000000000000000000000000000000000027", + "TKI:000000000000000000000000000000000028", + "TKI:000000000000000000000000000000000029", + "TKI:000000000000000000000000000000000030", + "TKI:000000000000000000000000000000000031", + "TKI:000000000000000000000000000000000032", + "TKI:000000000000000000000000000000000033", + "TKI:000000000000000000000000000000000034", + "TKI:000000000000000000000000000000000035", + "TKI:000000000000000000000000000000000100", + "TKI:000000000000000000000000000000000101", + "TKI:000000000000000000000000000000000102", "TKI:000000000000000000000000000000000103")); - for (String taskId : affectedTasks) { - verifyTaskIsModifiedAfterOrEquals(taskId, before); - } - + for (String taskId : affectedTasks) { + verifyTaskIsModifiedAfterOrEquals(taskId, before); } + } - private void verifyTaskIsModifiedAfterOrEquals(String taskId, Instant before) - throws InvalidArgumentException { + private void verifyTaskIsModifiedAfterOrEquals(String taskId, Instant before) + throws InvalidArgumentException { - ResponseEntity taskResponse = template.exchange( + ResponseEntity taskResponse = + template.exchange( restHelper.toUrl(Mapping.URL_TASKS_ID, taskId), HttpMethod.GET, new HttpEntity<>(restHelper.getHeadersAdmin()), ParameterizedTypeReference.forType(TaskResource.class)); - TaskResource taskResource = taskResponse.getBody(); - Task task = taskResourceAssembler.toModel(taskResource); - - Instant modified = task.getModified(); - boolean isAfterOrEquals = before.isAfter(modified) || before.equals(modified); - assertFalse("Task " + task.getId() + " has not been refreshed.", isAfterOrEquals); - } + TaskResource taskResource = taskResponse.getBody(); + Task task = taskResourceAssembler.toModel(taskResource); + Instant modified = task.getModified(); + boolean isAfterOrEquals = before.isAfter(modified) || before.equals(modified); + assertFalse("Task " + task.getId() + " has not been refreshed.", isAfterOrEquals); + } } diff --git a/rest/taskana-rest-spring-example-common/src/test/java/pro/taskana/ldap/LdapTest.java b/rest/taskana-rest-spring-example-common/src/test/java/pro/taskana/ldap/LdapTest.java index 277c7b8e0..7ee2dfe25 100644 --- a/rest/taskana-rest-spring-example-common/src/test/java/pro/taskana/ldap/LdapTest.java +++ b/rest/taskana-rest-spring-example-common/src/test/java/pro/taskana/ldap/LdapTest.java @@ -3,7 +3,6 @@ package pro.taskana.ldap; import static org.junit.Assert.assertEquals; import java.util.List; - import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; @@ -16,24 +15,22 @@ import pro.taskana.impl.util.LoggerUtils; import pro.taskana.rest.RestConfiguration; import pro.taskana.rest.resource.AccessIdResource; -/** - * Test Ldap attachment. - * - */ +/** Test Ldap attachment. */ @ActiveProfiles({"test"}) @ExtendWith(SpringExtension.class) -@SpringBootTest(classes = RestConfiguration.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@SpringBootTest( + classes = RestConfiguration.class, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class LdapTest { - @Autowired - private LdapClient ldapClient; + @Autowired private LdapClient ldapClient; - @Test - void testFindUsers() throws InvalidArgumentException { - if (ldapClient.useLdap()) { - List usersAndGroups = ldapClient.searchUsersAndGroups("ser0"); - System.out.println("#### found " + LoggerUtils.listToString(usersAndGroups)); - assertEquals(50, usersAndGroups.size()); - } + @Test + void testFindUsers() throws InvalidArgumentException { + if (ldapClient.useLdap()) { + List usersAndGroups = ldapClient.searchUsersAndGroups("ser0"); + System.out.println("#### found " + LoggerUtils.listToString(usersAndGroups)); + assertEquals(50, usersAndGroups.size()); } + } } diff --git a/rest/taskana-rest-spring-example-common/src/test/java/pro/taskana/rest/AccessIdValidationControllerIntTest.java b/rest/taskana-rest-spring-example-common/src/test/java/pro/taskana/rest/AccessIdValidationControllerIntTest.java index c96ad88c0..eb161b683 100644 --- a/rest/taskana-rest-spring-example-common/src/test/java/pro/taskana/rest/AccessIdValidationControllerIntTest.java +++ b/rest/taskana-rest-spring-example-common/src/test/java/pro/taskana/rest/AccessIdValidationControllerIntTest.java @@ -7,7 +7,6 @@ import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -27,59 +26,56 @@ import pro.taskana.RestHelper; import pro.taskana.ldap.LdapCacheTestImpl; import pro.taskana.rest.resource.AccessIdResource; -/** - * Test AccessIdValidation. - */ - +/** Test AccessIdValidation. */ @ActiveProfiles({"test"}) @ExtendWith(SpringExtension.class) -@SpringBootTest(classes = RestConfiguration.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@SpringBootTest( + classes = RestConfiguration.class, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class AccessIdValidationControllerIntTest { - @Autowired RestHelper restHelper; + static RestTemplate template; + @Autowired RestHelper restHelper; - static RestTemplate template; + @BeforeAll + static void init() { + template = RestHelper.getRestTemplate(); + } - @BeforeAll - static void init() { - template = RestHelper.getRestTemplate(); - } - - @Test - void testGetMatches() { - AccessIdController.setLdapCache(new LdapCacheTestImpl()); - HttpEntity request = new HttpEntity(restHelper.getHeaders()); - ResponseEntity> response = template.exchange( + @Test + void testGetMatches() { + AccessIdController.setLdapCache(new LdapCacheTestImpl()); + HttpEntity request = new HttpEntity(restHelper.getHeaders()); + ResponseEntity> response = + template.exchange( restHelper.toUrl(Mapping.URL_ACCESSID) + "?search-for=ali", HttpMethod.GET, request, - new ParameterizedTypeReference>() { + new ParameterizedTypeReference>() {}); - }); - List body = response.getBody(); - assertNotNull(body); - assertTrue(3 == body.size()); - List expectedIds = new ArrayList<>(Arrays.asList("Tralisch, Thea", "Bert, Ali", "Mente, Ali")); - for (AccessIdResource accessId : body) { - assertTrue(expectedIds.contains(accessId.getName())); - } + List body = response.getBody(); + assertNotNull(body); + assertTrue(3 == body.size()); + List expectedIds = + new ArrayList<>(Arrays.asList("Tralisch, Thea", "Bert, Ali", "Mente, Ali")); + for (AccessIdResource accessId : body) { + assertTrue(expectedIds.contains(accessId.getName())); } + } - @Test - void testBadRequestWhenSearchForIsTooShort() { - AccessIdController.setLdapCache(new LdapCacheTestImpl()); - HttpEntity request = new HttpEntity(restHelper.getHeaders()); - try { - template.exchange( - restHelper.toUrl(Mapping.URL_ACCESSID) + "?search-for=al", - HttpMethod.GET, - request, - ParameterizedTypeReference.forType(List.class)); - } catch (HttpClientErrorException e) { - assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); - assertTrue(e.getResponseBodyAsString().contains("Minimum searchFor length =")); - } - + @Test + void testBadRequestWhenSearchForIsTooShort() { + AccessIdController.setLdapCache(new LdapCacheTestImpl()); + HttpEntity request = new HttpEntity(restHelper.getHeaders()); + try { + template.exchange( + restHelper.toUrl(Mapping.URL_ACCESSID) + "?search-for=al", + HttpMethod.GET, + request, + ParameterizedTypeReference.forType(List.class)); + } catch (HttpClientErrorException e) { + assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); + assertTrue(e.getResponseBodyAsString().contains("Minimum searchFor length =")); } - + } } diff --git a/rest/taskana-rest-spring-example-common/src/test/java/pro/taskana/rest/ExampleRestApplication.java b/rest/taskana-rest-spring-example-common/src/test/java/pro/taskana/rest/ExampleRestApplication.java index 7a7801d9c..f139ec553 100644 --- a/rest/taskana-rest-spring-example-common/src/test/java/pro/taskana/rest/ExampleRestApplication.java +++ b/rest/taskana-rest-spring-example-common/src/test/java/pro/taskana/rest/ExampleRestApplication.java @@ -1,10 +1,8 @@ package pro.taskana.rest; import java.sql.SQLException; - import javax.annotation.PostConstruct; import javax.sql.DataSource; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; @@ -23,52 +21,53 @@ import pro.taskana.ldap.LdapClient; import pro.taskana.ldap.LdapConfiguration; import pro.taskana.sampledata.SampleDataGenerator; -/** - * Example Application showing the implementation of taskana-rest-spring. - */ +/** Example Application showing the implementation of taskana-rest-spring. */ @SpringBootApplication @EnableScheduling @ComponentScan(basePackages = "pro.taskana") -@Import({TransactionalJobsConfiguration.class, LdapConfiguration.class, RestConfiguration.class, WebMvcConfig.class}) +@Import({ + TransactionalJobsConfiguration.class, + LdapConfiguration.class, + RestConfiguration.class, + WebMvcConfig.class +}) public class ExampleRestApplication { - @Value("${taskana.schemaName:TASKANA}") - public String schemaName; + @Value("${taskana.schemaName:TASKANA}") + public String schemaName; - @Value("${generateSampleData:true}") - public boolean generateSampleData; + @Value("${generateSampleData:true}") + public boolean generateSampleData; - @Autowired - private SampleDataGenerator sampleDataGenerator; + @Autowired private SampleDataGenerator sampleDataGenerator; - @Autowired - private LdapClient ldapClient; + @Autowired private LdapClient ldapClient; - @Autowired private LdapCacheTestImpl ldapCacheTest; + @Autowired private LdapCacheTestImpl ldapCacheTest; - public static void main(String[] args) { - SpringApplication.run(ExampleRestApplication.class, args); + public static void main(String[] args) { + SpringApplication.run(ExampleRestApplication.class, args); + } + + @Bean + public PlatformTransactionManager txManager(DataSource dataSource) { + return new DataSourceTransactionManager(dataSource); + } + + @Bean + @DependsOn("getTaskanaEngine") // generate sample data after schema was inserted + public SampleDataGenerator generateSampleData(DataSource dataSource) { + sampleDataGenerator = new SampleDataGenerator(dataSource, schemaName); + return sampleDataGenerator; + } + + @PostConstruct + private void init() throws SQLException { + if (!ldapClient.useLdap()) { + AccessIdController.setLdapCache(ldapCacheTest); } - - @Bean - public PlatformTransactionManager txManager(DataSource dataSource) { - return new DataSourceTransactionManager(dataSource); - } - - @Bean - @DependsOn("getTaskanaEngine") // generate sample data after schema was inserted - public SampleDataGenerator generateSampleData(DataSource dataSource) { - sampleDataGenerator = new SampleDataGenerator(dataSource, schemaName); - return sampleDataGenerator; - } - - @PostConstruct - private void init() throws SQLException { - if (!ldapClient.useLdap()) { - AccessIdController.setLdapCache(ldapCacheTest); - } - if (generateSampleData) { - sampleDataGenerator.generateSampleData(); - } + if (generateSampleData) { + sampleDataGenerator.generateSampleData(); } + } } diff --git a/rest/taskana-rest-spring-example-wildfly/src/main/java/pro/taskana/TaskanaWildFlyApplication.java b/rest/taskana-rest-spring-example-wildfly/src/main/java/pro/taskana/TaskanaWildFlyApplication.java index 05011a501..552572b7d 100644 --- a/rest/taskana-rest-spring-example-wildfly/src/main/java/pro/taskana/TaskanaWildFlyApplication.java +++ b/rest/taskana-rest-spring-example-wildfly/src/main/java/pro/taskana/TaskanaWildFlyApplication.java @@ -3,12 +3,10 @@ package pro.taskana; import java.io.InputStream; import java.sql.SQLException; import java.util.Properties; - import javax.annotation.PostConstruct; import javax.naming.Context; import javax.naming.InitialContext; import javax.sql.DataSource; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -36,80 +34,87 @@ import pro.taskana.rest.WebMvcConfig; import pro.taskana.sampledata.SampleDataGenerator; /** - * Example Application showing the implementation of taskana-rest-spring for jboss application server. + * Example Application showing the implementation of taskana-rest-spring for jboss application + * server. */ @SpringBootApplication @EnableScheduling -@Import({TransactionalJobsConfiguration.class, LdapConfiguration.class, RestConfiguration.class, WebMvcConfig.class}) +@Import({ + TransactionalJobsConfiguration.class, + LdapConfiguration.class, + RestConfiguration.class, + WebMvcConfig.class +}) public class TaskanaWildFlyApplication extends SpringBootServletInitializer { - private static final Logger LOGGER = LoggerFactory.getLogger(TaskanaWildFlyApplication.class); - @Value("${taskana.schemaName:TASKANA}") - public String schemaName; + private static final Logger LOGGER = LoggerFactory.getLogger(TaskanaWildFlyApplication.class); - @Value("${generateSampleData:true}") - public boolean generateSampleData; + @Value("${taskana.schemaName:TASKANA}") + public String schemaName; - @Autowired - private SampleDataGenerator sampleDataGenerator; + @Value("${generateSampleData:true}") + public boolean generateSampleData; - @Autowired - private LdapClient ldapClient; + @Autowired private SampleDataGenerator sampleDataGenerator; - @Autowired private LdapCacheTestImpl ldapCacheTest; + @Autowired private LdapClient ldapClient; - public static void main(String[] args) { - SpringApplication.run(TaskanaWildFlyApplication.class, args); + @Autowired private LdapCacheTestImpl ldapCacheTest; + + public static void main(String[] args) { + SpringApplication.run(TaskanaWildFlyApplication.class, args); + } + + @Bean + @Primary + @ConfigurationProperties(prefix = "datasource") + public DataSourceProperties dataSourceProperties() { + DataSourceProperties props = new DataSourceProperties(); + props.setUrl( + "jdbc:h2:mem:taskana;IGNORECASE=TRUE;LOCK_MODE=0;INIT=CREATE SCHEMA IF NOT EXISTS " + + schemaName); + return props; + } + + @Bean + public DataSource dataSource(DataSourceProperties dsProperties) { + // First try to load Properties and get Datasource via jndi lookup + Context ctx; + DataSource dataSource; + ClassLoader classloader = Thread.currentThread().getContextClassLoader(); + try (InputStream propertyStream = classloader.getResourceAsStream("application.properties")) { + Properties properties = new Properties(); + ctx = new InitialContext(); + properties.load(propertyStream); + dataSource = (DataSource) ctx.lookup(properties.getProperty("datasource.jndi")); + return dataSource; + } catch (Exception e) { + LOGGER.error( + "Caught exception {} when attempting to start Taskana with Datasource from Jndi. Using default H2 datasource. ", + e); + return dsProperties.initializeDataSourceBuilder().build(); } + } - @Bean - @Primary - @ConfigurationProperties(prefix = "datasource") - public DataSourceProperties dataSourceProperties() { - DataSourceProperties props = new DataSourceProperties(); - props.setUrl("jdbc:h2:mem:taskana;IGNORECASE=TRUE;LOCK_MODE=0;INIT=CREATE SCHEMA IF NOT EXISTS " + schemaName); - return props; - } + @Bean + public PlatformTransactionManager txManager(DataSource dataSource) { + return new DataSourceTransactionManager(dataSource); + } - @Bean - public DataSource dataSource(DataSourceProperties dsProperties) { - // First try to load Properties and get Datasource via jndi lookup - Context ctx; - DataSource dataSource; - ClassLoader classloader = Thread.currentThread().getContextClassLoader(); - try (InputStream propertyStream = classloader.getResourceAsStream("application.properties")) { - Properties properties = new Properties(); - ctx = new InitialContext(); - properties.load(propertyStream); - dataSource = (DataSource) ctx.lookup(properties.getProperty("datasource.jndi")); - return dataSource; - } catch (Exception e) { - LOGGER.error( - "Caught exception {} when attempting to start Taskana with Datasource from Jndi. Using default H2 datasource. ", - e); - return dsProperties.initializeDataSourceBuilder().build(); - } - } + @Bean + @DependsOn("getTaskanaEngine") // generate sample data after schema was inserted + public SampleDataGenerator generateSampleData(DataSource dataSource) { + sampleDataGenerator = new SampleDataGenerator(dataSource, schemaName); + return sampleDataGenerator; + } - @Bean - public PlatformTransactionManager txManager(DataSource dataSource) { - return new DataSourceTransactionManager(dataSource); + @PostConstruct + private void init() throws SQLException { + if (!ldapClient.useLdap()) { + AccessIdController.setLdapCache(ldapCacheTest); } - - @Bean - @DependsOn("getTaskanaEngine") // generate sample data after schema was inserted - public SampleDataGenerator generateSampleData(DataSource dataSource) { - sampleDataGenerator = new SampleDataGenerator(dataSource, schemaName); - return sampleDataGenerator; - } - - @PostConstruct - private void init() throws SQLException { - if (!ldapClient.useLdap()) { - AccessIdController.setLdapCache(ldapCacheTest); - } - if (generateSampleData) { - sampleDataGenerator.generateSampleData(); - } + if (generateSampleData) { + sampleDataGenerator.generateSampleData(); } + } } diff --git a/rest/taskana-rest-spring-example-wildfly/src/main/java/pro/taskana/wildfly/security/ElytronToJaasFilter.java b/rest/taskana-rest-spring-example-wildfly/src/main/java/pro/taskana/wildfly/security/ElytronToJaasFilter.java index b825b2201..04f625153 100644 --- a/rest/taskana-rest-spring-example-wildfly/src/main/java/pro/taskana/wildfly/security/ElytronToJaasFilter.java +++ b/rest/taskana-rest-spring-example-wildfly/src/main/java/pro/taskana/wildfly/security/ElytronToJaasFilter.java @@ -2,13 +2,11 @@ package pro.taskana.wildfly.security; import java.io.IOException; import java.security.AccessController; - import javax.security.auth.Subject; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; - import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.filter.GenericFilterBean; @@ -18,65 +16,60 @@ import org.wildfly.security.authz.Roles; import pro.taskana.security.GroupPrincipal; -/** - * Simple Filter to map all Elytron Roles to JAAS-Principals. - */ +/** Simple Filter to map all Elytron Roles to JAAS-Principals. */ public class ElytronToJaasFilter extends GenericFilterBean { - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) - throws IOException, ServletException { - SecurityIdentity securityIdentity = getSecurityIdentity(); - if (securityIdentity != null) { - Roles roles = securityIdentity.getRoles(); - Subject subject = obtainSubject(request); - if (subject != null) { - if (subject.getPrincipals().size() == 0) { - subject.getPrincipals().add(securityIdentity.getPrincipal()); - } - if (subject.getPrincipals(GroupPrincipal.class).size() == 0) { - roles.forEach(role -> subject.getPrincipals().add(new GroupPrincipal(role))); - } - } + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + SecurityIdentity securityIdentity = getSecurityIdentity(); + if (securityIdentity != null) { + Roles roles = securityIdentity.getRoles(); + Subject subject = obtainSubject(request); + if (subject != null) { + if (subject.getPrincipals().size() == 0) { + subject.getPrincipals().add(securityIdentity.getPrincipal()); } - chain.doFilter(request, response); + if (subject.getPrincipals(GroupPrincipal.class).size() == 0) { + roles.forEach(role -> subject.getPrincipals().add(new GroupPrincipal(role))); + } + } + } + chain.doFilter(request, response); + } + + /** + * Obtains the Subject to run as or null if no Subject is + * available. + * + *

The default implementation attempts to obtain the Subject from the + * SecurityContext's Authentication. If it is of type + * JaasAuthenticationToken and is authenticated, the Subject is returned from + * it. Otherwise, null is returned. + * + * @param request the current ServletRequest + * @return the Subject to run as or null if no Subject is available. + */ + protected Subject obtainSubject(ServletRequest request) { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (logger.isDebugEnabled()) { + logger.debug("Attempting to obtainSubject using authentication : " + authentication); + } + if (authentication == null) { + return null; + } + if (!authentication.isAuthenticated()) { + return null; } - private SecurityIdentity getSecurityIdentity() { - SecurityDomain current = SecurityDomain.getCurrent(); - if (current != null) { - return current.getCurrentSecurityIdentity(); - } - return null; - } - - /** - *

- * Obtains the Subject to run as or null if no Subject is available. - *

- *

- * The default implementation attempts to obtain the Subject from the SecurityContext's - * Authentication. If it is of type JaasAuthenticationToken and is authenticated, the - * Subject is returned from it. Otherwise, null is returned. - *

- * - * @param request - * the current ServletRequest - * @return the Subject to run as or null if no Subject is available. - */ - protected Subject obtainSubject(ServletRequest request) { - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - if (logger.isDebugEnabled()) { - logger.debug("Attempting to obtainSubject using authentication : " + authentication); - } - if (authentication == null) { - return null; - } - if (!authentication.isAuthenticated()) { - return null; - } - - return Subject.getSubject(AccessController.getContext()); - + return Subject.getSubject(AccessController.getContext()); + } + + private SecurityIdentity getSecurityIdentity() { + SecurityDomain current = SecurityDomain.getCurrent(); + if (current != null) { + return current.getCurrentSecurityIdentity(); } + return null; + } } diff --git a/rest/taskana-rest-spring-example-wildfly/src/main/java/pro/taskana/wildfly/security/LoginErrorController.java b/rest/taskana-rest-spring-example-wildfly/src/main/java/pro/taskana/wildfly/security/LoginErrorController.java index 9b03b020f..669763e44 100644 --- a/rest/taskana-rest-spring-example-wildfly/src/main/java/pro/taskana/wildfly/security/LoginErrorController.java +++ b/rest/taskana-rest-spring-example-wildfly/src/main/java/pro/taskana/wildfly/security/LoginErrorController.java @@ -6,16 +6,14 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.view.RedirectView; -/** - * The loginError controller. - */ +/** The loginError controller. */ @Controller public class LoginErrorController { - @PostMapping - @GetMapping - @RequestMapping("/loginerror") - public RedirectView loginError() { - return new RedirectView("/login?error", true); - } + @PostMapping + @GetMapping + @RequestMapping("/loginerror") + public RedirectView loginError() { + return new RedirectView("/login?error", true); + } } diff --git a/rest/taskana-rest-spring-example-wildfly/src/main/java/pro/taskana/wildfly/security/WildflyWebSecurityConfig.java b/rest/taskana-rest-spring-example-wildfly/src/main/java/pro/taskana/wildfly/security/WildflyWebSecurityConfig.java index a35896a16..c9bec1194 100644 --- a/rest/taskana-rest-spring-example-wildfly/src/main/java/pro/taskana/wildfly/security/WildflyWebSecurityConfig.java +++ b/rest/taskana-rest-spring-example-wildfly/src/main/java/pro/taskana/wildfly/security/WildflyWebSecurityConfig.java @@ -3,7 +3,6 @@ package pro.taskana.wildfly.security; import java.util.ArrayList; import java.util.Collection; import java.util.List; - import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -31,164 +30,164 @@ import org.wildfly.security.authz.Roles; import pro.taskana.rest.security.WebSecurityConfig; /** - * Default basic configuration for taskana web example running on Wildfly / JBoss with Elytron or JAAS Security. + * Default basic configuration for taskana web example running on Wildfly / JBoss with Elytron or + * JAAS Security. */ @Configuration @EnableWebSecurity @Order(1) public class WildflyWebSecurityConfig extends WebSecurityConfig { - @Value("${devMode:false}") - private boolean devMode; + @Value("${devMode:false}") + private boolean devMode; - @Override - protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests() - .antMatchers( - "/css/**", - "/img/**") - .permitAll() - .and() - .csrf() - .disable() - .httpBasic() - .and() - .authenticationProvider(preauthAuthProvider()) - .authorizeRequests() - .antMatchers(HttpMethod.GET, "/docs/**") - .permitAll() - .and() - .addFilter(preAuthFilter()) - .addFilterAfter(new ElytronToJaasFilter(), JaasApiIntegrationFilter.class) - .addFilter(jaasApiIntegrationFilter()); + @Bean + public J2eePreAuthenticatedProcessingFilter preAuthFilter() throws Exception { + J2eePreAuthenticatedProcessingFilter filter = new J2eePreAuthenticatedProcessingFilter(); + filter.setAuthenticationManager(preAuthManager()); + return filter; + } - if (devMode) { - http.headers() - .frameOptions() - .sameOrigin() - .and() - .authorizeRequests() - .antMatchers("/h2-console/**") - .permitAll(); - } else { - addLoginPageConfiguration(http); - } - } + @Bean + public AuthenticationManager preAuthManager() { + return new AuthenticationManager() { - private JaasApiIntegrationFilter jaasApiIntegrationFilter() { - JaasApiIntegrationFilter filter = new JaasApiIntegrationFilter(); - filter.setCreateEmptySubject(true); - return filter; - } + @Override + public Authentication authenticate(Authentication authentication) + throws AuthenticationException { + return preauthAuthProvider().authenticate(authentication); + } + }; + } - @Bean - public J2eePreAuthenticatedProcessingFilter preAuthFilter() throws Exception { - J2eePreAuthenticatedProcessingFilter filter = new J2eePreAuthenticatedProcessingFilter(); - filter.setAuthenticationManager(preAuthManager()); - return filter; - } + @Bean + public PreAuthenticatedAuthenticationProvider preauthAuthProvider() { + PreAuthenticatedAuthenticationProvider preauthAuthProvider = + new PreAuthenticatedAuthenticationProvider(); + preauthAuthProvider.setPreAuthenticatedUserDetailsService(authenticationUserDetailsService()); + return preauthAuthProvider; + } - @Bean - public AuthenticationManager preAuthManager() { - return new AuthenticationManager() { + @Bean + public AuthenticationUserDetailsService + authenticationUserDetailsService() { + return new AuthenticationUserDetailsService() { - @Override - public Authentication authenticate(Authentication authentication) throws AuthenticationException { - return preauthAuthProvider().authenticate(authentication); + @Override + public UserDetails loadUserDetails(PreAuthenticatedAuthenticationToken token) + throws UsernameNotFoundException { + return new UserDetails() { + + private static final long serialVersionUID = 1L; + + @Override + public boolean isEnabled() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public String getUsername() { + return token.getName(); + } + + @Override + public String getPassword() { + return (String) token.getCredentials(); + } + + @Override + public Collection getAuthorities() { + List authorities = new ArrayList<>(); + SecurityIdentity securityIdentity = getSecurityIdentity(); + if (securityIdentity != null) { + Roles roles = securityIdentity.getRoles(); + roles.forEach(role -> authorities.add(new SimpleGrantedAuthority(role))); } - }; - } + return authorities; + } - @Bean - public PreAuthenticatedAuthenticationProvider preauthAuthProvider() { - PreAuthenticatedAuthenticationProvider preauthAuthProvider = new PreAuthenticatedAuthenticationProvider(); - preauthAuthProvider.setPreAuthenticatedUserDetailsService( - authenticationUserDetailsService()); - return preauthAuthProvider; - } - - @Bean - public AuthenticationUserDetailsService authenticationUserDetailsService() { - return new AuthenticationUserDetailsService() { - - @Override - public UserDetails loadUserDetails(PreAuthenticatedAuthenticationToken token) - throws UsernameNotFoundException { - return new UserDetails() { - - private static final long serialVersionUID = 1L; - - @Override - public boolean isEnabled() { - return true; - } - - @Override - public boolean isCredentialsNonExpired() { - return true; - } - - @Override - public boolean isAccountNonLocked() { - return true; - } - - @Override - public boolean isAccountNonExpired() { - return true; - } - - @Override - public String getUsername() { - return token.getName(); - } - - @Override - public String getPassword() { - return (String) token.getCredentials(); - } - - @Override - public Collection getAuthorities() { - List authorities = new ArrayList<>(); - SecurityIdentity securityIdentity = getSecurityIdentity(); - if (securityIdentity != null) { - Roles roles = securityIdentity.getRoles(); - roles.forEach(role -> authorities.add(new SimpleGrantedAuthority(role))); - } - return authorities; - } - - private SecurityIdentity getSecurityIdentity() { - SecurityDomain current = SecurityDomain.getCurrent(); - if (current != null) { - return current.getCurrentSecurityIdentity(); - } - return null; - } - }; + private SecurityIdentity getSecurityIdentity() { + SecurityDomain current = SecurityDomain.getCurrent(); + if (current != null) { + return current.getCurrentSecurityIdentity(); } + return null; + } }; - } + } + }; + } - private void addLoginPageConfiguration(HttpSecurity http) throws Exception { - http - .authorizeRequests() - .anyRequest() - .fullyAuthenticated() - .and() - .formLogin() - .loginPage("/login") - .failureUrl("/login?error") - .defaultSuccessUrl("/") - .permitAll() - .and() - .logout() - .invalidateHttpSession(true) - .clearAuthentication(true) - .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) - .logoutSuccessUrl("/login?logout") - .deleteCookies("JSESSIONID") - .permitAll(); + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers("/css/**", "/img/**") + .permitAll() + .and() + .csrf() + .disable() + .httpBasic() + .and() + .authenticationProvider(preauthAuthProvider()) + .authorizeRequests() + .antMatchers(HttpMethod.GET, "/docs/**") + .permitAll() + .and() + .addFilter(preAuthFilter()) + .addFilterAfter(new ElytronToJaasFilter(), JaasApiIntegrationFilter.class) + .addFilter(jaasApiIntegrationFilter()); + + if (devMode) { + http.headers() + .frameOptions() + .sameOrigin() + .and() + .authorizeRequests() + .antMatchers("/h2-console/**") + .permitAll(); + } else { + addLoginPageConfiguration(http); } + } + + private JaasApiIntegrationFilter jaasApiIntegrationFilter() { + JaasApiIntegrationFilter filter = new JaasApiIntegrationFilter(); + filter.setCreateEmptySubject(true); + return filter; + } + + private void addLoginPageConfiguration(HttpSecurity http) throws Exception { + http.authorizeRequests() + .anyRequest() + .fullyAuthenticated() + .and() + .formLogin() + .loginPage("/login") + .failureUrl("/login?error") + .defaultSuccessUrl("/") + .permitAll() + .and() + .logout() + .invalidateHttpSession(true) + .clearAuthentication(true) + .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) + .logoutSuccessUrl("/login?logout") + .deleteCookies("JSESSIONID") + .permitAll(); + } } diff --git a/rest/taskana-rest-spring-example-wildfly/src/test/java/pro/taskana/TaskanaWildflyTest.java b/rest/taskana-rest-spring-example-wildfly/src/test/java/pro/taskana/TaskanaWildflyTest.java index c4e011d62..3e964b223 100644 --- a/rest/taskana-rest-spring-example-wildfly/src/test/java/pro/taskana/TaskanaWildflyTest.java +++ b/rest/taskana-rest-spring-example-wildfly/src/test/java/pro/taskana/TaskanaWildflyTest.java @@ -2,9 +2,10 @@ package pro.taskana; import static org.junit.Assert.assertEquals; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.util.Collections; - import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; @@ -25,58 +26,60 @@ import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.client.RestTemplate; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; - import pro.taskana.rest.resource.TaskanaUserInfoResource; /** - * This test class is configured to run with postgres DB if you want to run it with h2 it is needed. to change data - * source configuration at project-defaults.yml. + * This test class is configured to run with postgres DB if you want to run it with h2 it is needed. + * to change data source configuration at project-defaults.yml. */ @RunWith(Arquillian.class) public class TaskanaWildflyTest { - @Deployment(testable = false) - public static Archive createTestArchive() { + @Deployment(testable = false) + public static Archive createTestArchive() { - File[] files = Maven.resolver() + File[] files = + Maven.resolver() .loadPomFromFile("pom.xml") .importRuntimeDependencies() .resolve() .withTransitivity() .asFile(); - return ShrinkWrap.create(WebArchive.class, "taskana.war") - .addPackages(true, "pro.taskana") - .addAsResource("taskana.properties") - .addAsResource("application.properties") - .addAsResource("project-defaults.yml") - .addAsLibraries(files); - } + return ShrinkWrap.create(WebArchive.class, "taskana.war") + .addPackages(true, "pro.taskana") + .addAsResource("taskana.properties") + .addAsResource("application.properties") + .addAsResource("project-defaults.yml") + .addAsLibraries(files); + } - @Test - @RunAsClient - public void shouldGetStatusOK() { + @Test + @RunAsClient + public void shouldGetStatusOK() { - HttpHeaders headers = new HttpHeaders(); - HttpEntity request = new HttpEntity(headers); - ResponseEntity response = getRestTemplate().exchange( - "http://127.0.0.1:" + "8090" + "/api/v1/current-user-info", HttpMethod.GET, request, - ParameterizedTypeReference.forType(TaskanaUserInfoResource.class)); - assertEquals(HttpStatus.OK, response.getStatusCode()); + HttpHeaders headers = new HttpHeaders(); + HttpEntity request = new HttpEntity(headers); + ResponseEntity response = + getRestTemplate() + .exchange( + "http://127.0.0.1:" + "8090" + "/api/v1/current-user-info", + HttpMethod.GET, + request, + ParameterizedTypeReference.forType(TaskanaUserInfoResource.class)); + assertEquals(HttpStatus.OK, response.getStatusCode()); + } - } + private RestTemplate getRestTemplate() { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - private RestTemplate getRestTemplate() { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); + converter.setSupportedMediaTypes(MediaType.parseMediaTypes("application/json")); + converter.setObjectMapper(mapper); - MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); - converter.setSupportedMediaTypes(MediaType.parseMediaTypes("application/json")); - converter.setObjectMapper(mapper); - - RestTemplate template = new RestTemplate(Collections.> singletonList(converter)); - return template; - } + RestTemplate template = + new RestTemplate(Collections.>singletonList(converter)); + return template; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/ldap/AccessId.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/ldap/AccessId.java index df2c2be5c..5707b65df 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/ldap/AccessId.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/ldap/AccessId.java @@ -7,28 +7,27 @@ package pro.taskana.ldap; */ public class AccessId { - private String accessId; - private String name; + private String accessId; + private String name; - public String getAccessId() { - return accessId; - } + public String getAccessId() { + return accessId; + } - public void setAccessId(String accessId) { - this.accessId = accessId; - } + public void setAccessId(String accessId) { + this.accessId = accessId; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } - - @Override - public String toString() { - return "AccessId [" + "accessId=" + this.accessId + ", name=" + this.name + "]"; - } + public void setName(String name) { + this.name = name; + } + @Override + public String toString() { + return "AccessId [" + "accessId=" + this.accessId + ", name=" + this.name + "]"; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/ldap/LdapCache.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/ldap/LdapCache.java index b9aa43fc4..d7b237adf 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/ldap/LdapCache.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/ldap/LdapCache.java @@ -11,29 +11,31 @@ import pro.taskana.rest.resource.AccessIdResource; */ public interface LdapCache { - /** - * find access ids for users and groups that match specified search criteria. - * - * @param searchFor - * the search string. The search is performed over names and ids of users and groups. - * @param maxNumberOfReturnedAccessIds - * the maximum number of results to return. - * @return a List of access ids for users and group where the name or id contains the search string. - */ - List findMatchingAccessId(String searchFor, int maxNumberOfReturnedAccessIds); + /** + * find access ids for users and groups that match specified search criteria. + * + * @param searchFor the search string. The search is performed over names and ids of users and + * groups. + * @param maxNumberOfReturnedAccessIds the maximum number of results to return. + * @return a List of access ids for users and group where the name or id contains the search + * string. + */ + List findMatchingAccessId(String searchFor, int maxNumberOfReturnedAccessIds); - /** - * Find the groups belong to a user. - * @param searchFor the search string. The search is performed over names and ids of group . - * @param maxNumberOfReturnedAccessIds the maximum number of results to return. - * @return a List of access ids for groups of users. - */ - List findGroupsOfUser(String searchFor, int maxNumberOfReturnedAccessIds); + /** + * Find the groups belong to a user. + * + * @param searchFor the search string. The search is performed over names and ids of group . + * @param maxNumberOfReturnedAccessIds the maximum number of results to return. + * @return a List of access ids for groups of users. + */ + List findGroupsOfUser(String searchFor, int maxNumberOfReturnedAccessIds); - /** - * Validate a access id. - * @param accessId the search string. - * @return the corresponding access ids. - */ - List validateAccessId(String accessId); + /** + * Validate a access id. + * + * @param accessId the search string. + * @return the corresponding access ids. + */ + List validateAccessId(String accessId); } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/ldap/LdapClient.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/ldap/LdapClient.java index 923753d26..9d9ca82c8 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/ldap/LdapClient.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/ldap/LdapClient.java @@ -1,10 +1,8 @@ package pro.taskana.ldap; import java.util.List; - import javax.annotation.PostConstruct; import javax.naming.directory.SearchControls; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -31,314 +29,339 @@ import pro.taskana.rest.resource.AccessIdResource; @Component public class LdapClient { - public static final String TASKANA_USE_LDAP_PROP_NAME = "taskana.ldap.useLdap"; - private static final Logger LOGGER = LoggerFactory.getLogger(LdapClient.class); - private static final String CN = "cn"; - private boolean active = false; - @Autowired - private Environment env; - @Autowired(required = false) - private LdapTemplate ldapTemplate; - private String userSearchBase; - private String userSearchFilterName; - private String userSearchFilterValue; - private String userFirstnameAttribute; - private String userLastnameAttribute; - private String userIdAttribute; - private String groupSearchBase; - private String groupSearchFilterName; - private String groupSearchFilterValue; - private String groupNameAttribute; - private String groupsOfUser; - private int minSearchForLength; - private int maxNumberOfReturnedAccessIds; - private String message; + public static final String TASKANA_USE_LDAP_PROP_NAME = "taskana.ldap.useLdap"; + private static final Logger LOGGER = LoggerFactory.getLogger(LdapClient.class); + private static final String CN = "cn"; + private boolean active = false; + @Autowired private Environment env; - @PostConstruct - private void init() { - LOGGER.debug("Entry to init()"); - String strMinSearchForLength = getMinSearchForLengthAsString(); - if (strMinSearchForLength == null || strMinSearchForLength.isEmpty()) { - minSearchForLength = 3; - } else { - minSearchForLength = Integer.parseInt(strMinSearchForLength); - } + @Autowired(required = false) + private LdapTemplate ldapTemplate; - String strMaxNumberOfReturnedAccessIds = getMaxNumberOfReturnedAccessIdsAsString(); - if (strMaxNumberOfReturnedAccessIds == null || strMaxNumberOfReturnedAccessIds.isEmpty()) { - maxNumberOfReturnedAccessIds = 50; - } else { - maxNumberOfReturnedAccessIds = Integer.parseInt(strMaxNumberOfReturnedAccessIds); - } + private String userSearchBase; + private String userSearchFilterName; + private String userSearchFilterValue; + private String userFirstnameAttribute; + private String userLastnameAttribute; + private String userIdAttribute; + private String groupSearchBase; + private String groupSearchFilterName; + private String groupSearchFilterValue; + private String groupNameAttribute; + private String groupsOfUser; + private int minSearchForLength; + private int maxNumberOfReturnedAccessIds; + private String message; - if (useLdap()) { - userSearchBase = getUserSearchBase(); - userSearchFilterName = getUserSearchFilterName(); - userSearchFilterValue = getUserSearchFilterValue(); - userFirstnameAttribute = getUserFirstnameAttribute(); - userLastnameAttribute = getUserLastnameAttribute(); - userIdAttribute = getUserIdAttribute(); - groupSearchBase = getGroupSearchBase(); - groupSearchFilterName = getGroupSearchFilterName(); - groupSearchFilterValue = getGroupSearchFilterValue(); - groupNameAttribute = getGroupNameAttribute(); - groupsOfUser = getGroupsOfUser(); - - ldapTemplate.setDefaultCountLimit(maxNumberOfReturnedAccessIds); - - final String emptyMessage = "taskana.ldap.useLdap is set to true, but"; - message = emptyMessage; - if (userSearchBase == null) { - message += " taskana.ldap.userSearchBase is not configured."; - } - if (userSearchFilterName == null) { - message += " taskana.ldap.userSearchFilterName is not configured."; - } - if (userSearchFilterValue == null) { - message += " taskana.ldap.userSearchFilterValue is not configured."; - } - if (userFirstnameAttribute == null) { - message += " taskana.ldap.userFirstnameAttribute is not configured."; - } - if (userLastnameAttribute == null) { - message += " taskana.ldap.userLastnameAttribute is not configured."; - } - if (userIdAttribute == null) { - message += " taskana.ldap.userIdAttribute is not configured."; - } - if (groupSearchBase == null) { - message += " taskana.ldap.groupSearchBase is not configured."; - } - if (groupSearchFilterName == null) { - message += " taskana.ldap.groupSearchFilterName is not configured."; - } - if (groupSearchFilterValue == null) { - message += " taskana.ldap.groupSearchFilterValue is not configured."; - } - if (groupNameAttribute == null) { - message += " taskana.ldap.groupNameAttribute is not configured."; - } - if (groupsOfUser == null) { - message += " taskana.ldap.groupsOfUser is not configured."; - } - if (!message.equals(emptyMessage)) { - throw new SystemException(message); - } - active = true; - } - LOGGER.debug("Exit from init()"); + public List searchUsersAndGroups(final String name) + throws InvalidArgumentException { + LOGGER.debug("entry to searchUsersAndGroups(name = {})", name); + if (!active) { + throw new SystemException( + "LdapClient was called but is not active due to missing configuration: " + message); } + testMinSearchForLength(name); - public List searchUsersAndGroups(final String name) throws InvalidArgumentException { - LOGGER.debug("entry to searchUsersAndGroups(name = {})", name); - if (!active) { - throw new SystemException( - "LdapClient was called but is not active due to missing configuration: " + message); - } - testMinSearchForLength(name); - - List users = searchUsersByName(name); - users.addAll(searchGroupsByName(name)); - users.sort((AccessIdResource a, AccessIdResource b) -> { - return a.getAccessId().compareToIgnoreCase(b.getAccessId()); + List users = searchUsersByName(name); + users.addAll(searchGroupsByName(name)); + users.sort( + (AccessIdResource a, AccessIdResource b) -> { + return a.getAccessId().compareToIgnoreCase(b.getAccessId()); }); - List result = users.subList(0, Math.min(users.size(), maxNumberOfReturnedAccessIds)); - LOGGER.debug("exit from searchUsersAndGroups(name = {}). Returning {} users and groups: {}", name, users.size(), - LoggerUtils.listToString(result)); + List result = + users.subList(0, Math.min(users.size(), maxNumberOfReturnedAccessIds)); + LOGGER.debug( + "exit from searchUsersAndGroups(name = {}). Returning {} users and groups: {}", + name, + users.size(), + LoggerUtils.listToString(result)); - return result; + return result; + } + + public List searchUsersByName(final String name) + throws InvalidArgumentException { + LOGGER.debug("entry to searchUsersByName(name = {}).", name); + if (!active) { + throw new SystemException( + "LdapClient was called but is not active due to missing configuration: " + message); + } + testMinSearchForLength(name); + + final AndFilter andFilter = new AndFilter(); + andFilter.and(new EqualsFilter(getUserSearchFilterName(), getUserSearchFilterValue())); + final OrFilter orFilter = new OrFilter(); + + orFilter.or(new WhitespaceWildcardsFilter(getUserFirstnameAttribute(), name)); + orFilter.or(new WhitespaceWildcardsFilter(getUserLastnameAttribute(), name)); + orFilter.or(new WhitespaceWildcardsFilter(getUserIdAttribute(), name)); + andFilter.and(orFilter); + + String[] userAttributesToReturn = { + getUserFirstnameAttribute(), getUserLastnameAttribute(), getUserIdAttribute() + }; + + final List accessIds = + ldapTemplate.search( + getUserSearchBase(), + andFilter.encode(), + SearchControls.SUBTREE_SCOPE, + userAttributesToReturn, + new UserContextMapper()); + LOGGER.debug( + "exit from searchUsersByName. Retrieved the following users: {}.", + LoggerUtils.listToString(accessIds)); + return accessIds; + } + + public List searchGroupsByName(final String name) + throws InvalidArgumentException { + LOGGER.debug("entry to searchGroupsByName(name = {}).", name); + if (!active) { + throw new SystemException( + "LdapClient was called but is not active due to missing configuration: " + message); + } + testMinSearchForLength(name); + + final AndFilter andFilter = new AndFilter(); + andFilter.and(new EqualsFilter(getGroupSearchFilterName(), getGroupSearchFilterValue())); + final OrFilter orFilter = new OrFilter(); + orFilter.or(new WhitespaceWildcardsFilter(getGroupNameAttribute(), name)); + if (!CN.equals(groupNameAttribute)) { + orFilter.or(new WhitespaceWildcardsFilter(CN, name)); + } + andFilter.and(orFilter); + + String[] groupAttributesToReturn; + if (CN.equals(groupNameAttribute)) { + groupAttributesToReturn = new String[] {CN}; + } else { + groupAttributesToReturn = new String[] {getGroupNameAttribute(), CN}; } - public List searchUsersByName(final String name) throws InvalidArgumentException { - LOGGER.debug("entry to searchUsersByName(name = {}).", name); - if (!active) { - throw new SystemException( - "LdapClient was called but is not active due to missing configuration: " + message); - } - testMinSearchForLength(name); + final List accessIds = + ldapTemplate.search( + getGroupSearchBase(), + andFilter.encode(), + SearchControls.SUBTREE_SCOPE, + groupAttributesToReturn, + new GroupContextMapper()); + LOGGER.debug( + "Exit from searchGroupsByName. Retrieved the following groups: {}", + LoggerUtils.listToString(accessIds)); + return accessIds; + } - final AndFilter andFilter = new AndFilter(); - andFilter.and(new EqualsFilter(getUserSearchFilterName(), getUserSearchFilterValue())); - final OrFilter orFilter = new OrFilter(); + public List searchGroupsofUsersIsMember(final String name) + throws InvalidArgumentException { + LOGGER.debug("entry to searchGroupsofUsersIsMember(name = {}).", name); + if (!active) { + throw new SystemException( + "LdapClient was called but is not active due to missing configuration: " + message); + } + testMinSearchForLength(name); - orFilter.or(new WhitespaceWildcardsFilter(getUserFirstnameAttribute(), name)); - orFilter.or(new WhitespaceWildcardsFilter(getUserLastnameAttribute(), name)); - orFilter.or(new WhitespaceWildcardsFilter(getUserIdAttribute(), name)); - andFilter.and(orFilter); + final AndFilter andFilter = new AndFilter(); + andFilter.and(new WhitespaceWildcardsFilter(getGroupNameAttribute(), "")); + andFilter.and(new EqualsFilter(getGroupsOfUser(), name)); - String[] userAttributesToReturn = {getUserFirstnameAttribute(), getUserLastnameAttribute(), - getUserIdAttribute()}; + String[] userAttributesToReturn = {getUserIdAttribute(), getGroupNameAttribute()}; - final List accessIds = ldapTemplate.search(getUserSearchBase(), andFilter.encode(), - SearchControls.SUBTREE_SCOPE, userAttributesToReturn, new UserContextMapper()); - LOGGER.debug("exit from searchUsersByName. Retrieved the following users: {}.", - LoggerUtils.listToString(accessIds)); - return accessIds; + final List accessIds = + ldapTemplate.search( + getGroupSearchBase(), + andFilter.encode(), + SearchControls.SUBTREE_SCOPE, + userAttributesToReturn, + new GroupContextMapper()); + LOGGER.debug( + "exit from searchGroupsofUsersIsMember. Retrieved the following users: {}.", + LoggerUtils.listToString(accessIds)); + return accessIds; + } + public boolean useLdap() { + String useLdap = env.getProperty(TASKANA_USE_LDAP_PROP_NAME); + if (useLdap == null || useLdap.isEmpty()) { + return false; + } else { + return Boolean.parseBoolean(useLdap); + } + } + + public String getUserSearchBase() { + return env.getProperty("taskana.ldap.userSearchBase"); + } + + public String getUserSearchFilterName() { + return env.getProperty("taskana.ldap.userSearchFilterName"); + } + + public String getUserSearchFilterValue() { + return env.getProperty("taskana.ldap.userSearchFilterValue"); + } + + public String getUserFirstnameAttribute() { + return env.getProperty("taskana.ldap.userFirstnameAttribute"); + } + + public String getUserLastnameAttribute() { + return env.getProperty("taskana.ldap.userLastnameAttribute"); + } + + public String getUserIdAttribute() { + return env.getProperty("taskana.ldap.userIdAttribute"); + } + + public String getGroupSearchBase() { + return env.getProperty("taskana.ldap.groupSearchBase"); + } + + public String getGroupSearchFilterName() { + return env.getProperty("taskana.ldap.groupSearchFilterName"); + } + + public String getGroupSearchFilterValue() { + return env.getProperty("taskana.ldap.groupSearchFilterValue"); + } + + public String getGroupNameAttribute() { + return env.getProperty("taskana.ldap.groupNameAttribute"); + } + + public String getMinSearchForLengthAsString() { + return env.getProperty("taskana.ldap.minSearchForLength"); + } + + public int getMinSearchForLength() { + return minSearchForLength; + } + + public String getMaxNumberOfReturnedAccessIdsAsString() { + return env.getProperty("taskana.ldap.maxNumberOfReturnedAccessIds"); + } + + public int getMaxNumberOfReturnedAccessIds() { + return maxNumberOfReturnedAccessIds; + } + + public String getGroupsOfUser() { + return env.getProperty("taskana.ldap.groupsOfUser"); + } + + public boolean isGroup(String accessId) { + return accessId.contains(getGroupSearchBase()); + } + + @PostConstruct + private void init() { + LOGGER.debug("Entry to init()"); + String strMinSearchForLength = getMinSearchForLengthAsString(); + if (strMinSearchForLength == null || strMinSearchForLength.isEmpty()) { + minSearchForLength = 3; + } else { + minSearchForLength = Integer.parseInt(strMinSearchForLength); } - public List searchGroupsByName(final String name) throws InvalidArgumentException { - LOGGER.debug("entry to searchGroupsByName(name = {}).", name); - if (!active) { - throw new SystemException( - "LdapClient was called but is not active due to missing configuration: " + message); - } - testMinSearchForLength(name); - - final AndFilter andFilter = new AndFilter(); - andFilter.and(new EqualsFilter(getGroupSearchFilterName(), getGroupSearchFilterValue())); - final OrFilter orFilter = new OrFilter(); - orFilter.or(new WhitespaceWildcardsFilter(getGroupNameAttribute(), name)); - if (!CN.equals(groupNameAttribute)) { - orFilter.or(new WhitespaceWildcardsFilter(CN, name)); - } - andFilter.and(orFilter); - - String[] groupAttributesToReturn; - if (CN.equals(groupNameAttribute)) { - groupAttributesToReturn = new String[] {CN}; - } else { - groupAttributesToReturn = new String[] {getGroupNameAttribute(), CN}; - } - - final List accessIds = ldapTemplate.search(getGroupSearchBase(), andFilter.encode(), - SearchControls.SUBTREE_SCOPE, groupAttributesToReturn, new GroupContextMapper()); - LOGGER.debug("Exit from searchGroupsByName. Retrieved the following groups: {}", - LoggerUtils.listToString(accessIds)); - return accessIds; - + String strMaxNumberOfReturnedAccessIds = getMaxNumberOfReturnedAccessIdsAsString(); + if (strMaxNumberOfReturnedAccessIds == null || strMaxNumberOfReturnedAccessIds.isEmpty()) { + maxNumberOfReturnedAccessIds = 50; + } else { + maxNumberOfReturnedAccessIds = Integer.parseInt(strMaxNumberOfReturnedAccessIds); } - public List searchGroupsofUsersIsMember(final String name) throws InvalidArgumentException { - LOGGER.debug("entry to searchGroupsofUsersIsMember(name = {}).", name); - if (!active) { - throw new SystemException( - "LdapClient was called but is not active due to missing configuration: " + message); - } - testMinSearchForLength(name); + if (useLdap()) { + userSearchBase = getUserSearchBase(); + userSearchFilterName = getUserSearchFilterName(); + userSearchFilterValue = getUserSearchFilterValue(); + userFirstnameAttribute = getUserFirstnameAttribute(); + userLastnameAttribute = getUserLastnameAttribute(); + userIdAttribute = getUserIdAttribute(); + groupSearchBase = getGroupSearchBase(); + groupSearchFilterName = getGroupSearchFilterName(); + groupSearchFilterValue = getGroupSearchFilterValue(); + groupNameAttribute = getGroupNameAttribute(); + groupsOfUser = getGroupsOfUser(); - final AndFilter andFilter = new AndFilter(); - andFilter.and(new WhitespaceWildcardsFilter(getGroupNameAttribute(), "")); - andFilter.and(new EqualsFilter(getGroupsOfUser(), name)); - - String[] userAttributesToReturn = {getUserIdAttribute(), getGroupNameAttribute()}; - - final List accessIds = ldapTemplate.search(getGroupSearchBase(), andFilter.encode(), - SearchControls.SUBTREE_SCOPE, userAttributesToReturn, new GroupContextMapper()); - LOGGER.debug("exit from searchGroupsofUsersIsMember. Retrieved the following users: {}.", - LoggerUtils.listToString(accessIds)); - return accessIds; + ldapTemplate.setDefaultCountLimit(maxNumberOfReturnedAccessIds); + final String emptyMessage = "taskana.ldap.useLdap is set to true, but"; + message = emptyMessage; + if (userSearchBase == null) { + message += " taskana.ldap.userSearchBase is not configured."; + } + if (userSearchFilterName == null) { + message += " taskana.ldap.userSearchFilterName is not configured."; + } + if (userSearchFilterValue == null) { + message += " taskana.ldap.userSearchFilterValue is not configured."; + } + if (userFirstnameAttribute == null) { + message += " taskana.ldap.userFirstnameAttribute is not configured."; + } + if (userLastnameAttribute == null) { + message += " taskana.ldap.userLastnameAttribute is not configured."; + } + if (userIdAttribute == null) { + message += " taskana.ldap.userIdAttribute is not configured."; + } + if (groupSearchBase == null) { + message += " taskana.ldap.groupSearchBase is not configured."; + } + if (groupSearchFilterName == null) { + message += " taskana.ldap.groupSearchFilterName is not configured."; + } + if (groupSearchFilterValue == null) { + message += " taskana.ldap.groupSearchFilterValue is not configured."; + } + if (groupNameAttribute == null) { + message += " taskana.ldap.groupNameAttribute is not configured."; + } + if (groupsOfUser == null) { + message += " taskana.ldap.groupsOfUser is not configured."; + } + if (!message.equals(emptyMessage)) { + throw new SystemException(message); + } + active = true; } + LOGGER.debug("Exit from init()"); + } - private void testMinSearchForLength(final String name) throws InvalidArgumentException { - if (name == null || name.length() < minSearchForLength) { - throw new InvalidArgumentException("searchFor string " + name + " is too short. Minimum Length = " - + getMinSearchForLength()); - } + private void testMinSearchForLength(final String name) throws InvalidArgumentException { + if (name == null || name.length() < minSearchForLength) { + throw new InvalidArgumentException( + "searchFor string " + + name + + " is too short. Minimum Length = " + + getMinSearchForLength()); } + } - public boolean useLdap() { - String useLdap = env.getProperty(TASKANA_USE_LDAP_PROP_NAME); - if (useLdap == null || useLdap.isEmpty()) { - return false; - } else { - return Boolean.parseBoolean(useLdap); - } + /** Context Mapper for user entries. */ + private class UserContextMapper extends AbstractContextMapper { + + @Override + public AccessIdResource doMapFromContext(final DirContextOperations context) { + final AccessIdResource accessId = new AccessIdResource(); + accessId.setAccessId(context.getStringAttribute(getUserIdAttribute())); + String firstName = context.getStringAttribute(getUserFirstnameAttribute()); + String lastName = context.getStringAttribute(getUserLastnameAttribute()); + accessId.setName(lastName + ", " + firstName); + return accessId; } + } - public String getUserSearchBase() { - return env.getProperty("taskana.ldap.userSearchBase"); - } - - public String getUserSearchFilterName() { - return env.getProperty("taskana.ldap.userSearchFilterName"); - } - - public String getUserSearchFilterValue() { - return env.getProperty("taskana.ldap.userSearchFilterValue"); - } - - public String getUserFirstnameAttribute() { - return env.getProperty("taskana.ldap.userFirstnameAttribute"); - } - - public String getUserLastnameAttribute() { - return env.getProperty("taskana.ldap.userLastnameAttribute"); - } - - public String getUserIdAttribute() { - return env.getProperty("taskana.ldap.userIdAttribute"); - } - - public String getGroupSearchBase() { - return env.getProperty("taskana.ldap.groupSearchBase"); - } - - public String getGroupSearchFilterName() { - return env.getProperty("taskana.ldap.groupSearchFilterName"); - } - - public String getGroupSearchFilterValue() { - return env.getProperty("taskana.ldap.groupSearchFilterValue"); - } - - public String getGroupNameAttribute() { - return env.getProperty("taskana.ldap.groupNameAttribute"); - } - - public String getMinSearchForLengthAsString() { - return env.getProperty("taskana.ldap.minSearchForLength"); - } - - public int getMinSearchForLength() { - return minSearchForLength; - } - - public String getMaxNumberOfReturnedAccessIdsAsString() { - return env.getProperty("taskana.ldap.maxNumberOfReturnedAccessIds"); - } - - public int getMaxNumberOfReturnedAccessIds() { - return maxNumberOfReturnedAccessIds; - } - - public String getGroupsOfUser() { - return env.getProperty("taskana.ldap.groupsOfUser"); - } - - public boolean isGroup(String accessId) { - return accessId.contains(getGroupSearchBase()); - } - - /** - * Context Mapper for user entries. - */ - private class UserContextMapper extends AbstractContextMapper { - - @Override - public AccessIdResource doMapFromContext(final DirContextOperations context) { - final AccessIdResource accessId = new AccessIdResource(); - accessId.setAccessId(context.getStringAttribute(getUserIdAttribute())); - String firstName = context.getStringAttribute(getUserFirstnameAttribute()); - String lastName = context.getStringAttribute(getUserLastnameAttribute()); - accessId.setName(lastName + ", " + firstName); - return accessId; - } - } - - /** - * Context Mapper for user entries. - */ - private class GroupContextMapper extends AbstractContextMapper { - - @Override - public AccessIdResource doMapFromContext(final DirContextOperations context) { - final AccessIdResource accessId = new AccessIdResource(); - accessId.setAccessId(context.getNameInNamespace()); // fully qualified dn - accessId.setName(context.getStringAttribute(getGroupNameAttribute())); - return accessId; - } + /** Context Mapper for user entries. */ + private class GroupContextMapper extends AbstractContextMapper { + + @Override + public AccessIdResource doMapFromContext(final DirContextOperations context) { + final AccessIdResource accessId = new AccessIdResource(); + accessId.setAccessId(context.getNameInNamespace()); // fully qualified dn + accessId.setName(context.getStringAttribute(getGroupNameAttribute())); + return accessId; } + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/ldap/LdapConfiguration.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/ldap/LdapConfiguration.java index 931c3f312..8069ab780 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/ldap/LdapConfiguration.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/ldap/LdapConfiguration.java @@ -11,59 +11,54 @@ import org.springframework.core.type.AnnotatedTypeMetadata; import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.core.support.LdapContextSource; -/** - * Configuration for Ldap access. - */ +/** Configuration for Ldap access. */ @Configuration public class LdapConfiguration { - @Autowired - private Environment env; + @Autowired private Environment env; - @Bean - public LdapContextSource contextSource() { + @Bean + public LdapContextSource contextSource() { - LdapContextSource contextSource = new LdapContextSource(); - boolean useLdap; - String useLdapConfigValue = env.getProperty("taskana.ldap.useLdap"); - if (useLdapConfigValue == null || useLdapConfigValue.isEmpty()) { - useLdap = false; - } else { - useLdap = Boolean.parseBoolean(useLdapConfigValue); - } - if (useLdap) { - contextSource.setUrl(env.getRequiredProperty("taskana.ldap.serverUrl")); - contextSource.setBase(env.getRequiredProperty("taskana.ldap.baseDn")); - contextSource.setUserDn(env.getRequiredProperty("taskana.ldap.bindDn")); - contextSource.setPassword(env.getRequiredProperty("taskana.ldap.bindPassword")); - } else { - contextSource.setUrl("ldap://localhost:9999"); - contextSource.setBase("o=taskana"); - contextSource.setUserDn("user"); - contextSource.setPassword("secret"); - } - return contextSource; + LdapContextSource contextSource = new LdapContextSource(); + boolean useLdap; + String useLdapConfigValue = env.getProperty("taskana.ldap.useLdap"); + if (useLdapConfigValue == null || useLdapConfigValue.isEmpty()) { + useLdap = false; + } else { + useLdap = Boolean.parseBoolean(useLdapConfigValue); } - - @Bean(name = "ldapTemplate") - @Conditional(WithLdapCondition.class) - public LdapTemplate getActiveLdapTemplate() { - return new LdapTemplate(contextSource()); + if (useLdap) { + contextSource.setUrl(env.getRequiredProperty("taskana.ldap.serverUrl")); + contextSource.setBase(env.getRequiredProperty("taskana.ldap.baseDn")); + contextSource.setUserDn(env.getRequiredProperty("taskana.ldap.bindDn")); + contextSource.setPassword(env.getRequiredProperty("taskana.ldap.bindPassword")); + } else { + contextSource.setUrl("ldap://localhost:9999"); + contextSource.setBase("o=taskana"); + contextSource.setUserDn("user"); + contextSource.setPassword("secret"); } + return contextSource; + } - /** - * Helper class to control conditional provision of LdapTemplate. - */ - public static class WithLdapCondition implements Condition { + @Bean(name = "ldapTemplate") + @Conditional(WithLdapCondition.class) + public LdapTemplate getActiveLdapTemplate() { + return new LdapTemplate(contextSource()); + } - @Override - public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { - String useLdap = context.getEnvironment().getProperty(LdapClient.TASKANA_USE_LDAP_PROP_NAME); - if (useLdap == null || useLdap.isEmpty()) { - return false; - } else { - return Boolean.parseBoolean(useLdap); - } - } + /** Helper class to control conditional provision of LdapTemplate. */ + public static class WithLdapCondition implements Condition { + + @Override + public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { + String useLdap = context.getEnvironment().getProperty(LdapClient.TASKANA_USE_LDAP_PROP_NAME); + if (useLdap == null || useLdap.isEmpty()) { + return false; + } else { + return Boolean.parseBoolean(useLdap); + } } + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/AbstractPagingController.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/AbstractPagingController.java index 4a4432ecb..8857bf95d 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/AbstractPagingController.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/AbstractPagingController.java @@ -3,117 +3,115 @@ package pro.taskana.rest; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import org.springframework.util.MultiValueMap; import pro.taskana.BaseQuery; import pro.taskana.exceptions.InvalidArgumentException; import pro.taskana.rest.resource.PagedResources.PageMetadata; -/** - * Abstract superclass for taskana REST controller with pageable resources. - */ +/** Abstract superclass for taskana REST controller with pageable resources. */ public abstract class AbstractPagingController { - private static final String PAGING_PAGE = "page"; - private static final String PAGING_PAGE_SIZE = "page-size"; + private static final String PAGING_PAGE = "page"; + private static final String PAGING_PAGE_SIZE = "page-size"; - protected String[] extractCommaSeparatedFields(List list) { - List values = new ArrayList<>(); - if (list != null) { - list.forEach(item -> values.addAll(Arrays.asList(item.split(",")))); - } - return values.toArray(new String[0]); + protected String[] extractCommaSeparatedFields(List list) { + List values = new ArrayList<>(); + if (list != null) { + list.forEach(item -> values.addAll(Arrays.asList(item.split(",")))); } + return values.toArray(new String[0]); + } - protected void validateNoInvalidParameterIsLeft(MultiValueMap params) - throws InvalidArgumentException { - if (!params.isEmpty()) { - throw new InvalidArgumentException("Invalid parameter specified: " + params.keySet()); - } + protected void validateNoInvalidParameterIsLeft(MultiValueMap params) + throws InvalidArgumentException { + if (!params.isEmpty()) { + throw new InvalidArgumentException("Invalid parameter specified: " + params.keySet()); } + } - protected PageMetadata getPageMetadata(MultiValueMap params, BaseQuery query) - throws InvalidArgumentException { - PageMetadata pageMetadata = null; - if (hasPagingInformationInParams(params)) { - // paging - long totalElements = query.count(); - pageMetadata = initPageMetadata(params, totalElements); - validateNoInvalidParameterIsLeft(params); - } else { - // not paging - validateNoInvalidParameterIsLeft(params); - } - return pageMetadata; + protected PageMetadata getPageMetadata( + MultiValueMap params, BaseQuery query) throws InvalidArgumentException { + PageMetadata pageMetadata = null; + if (hasPagingInformationInParams(params)) { + // paging + long totalElements = query.count(); + pageMetadata = initPageMetadata(params, totalElements); + validateNoInvalidParameterIsLeft(params); + } else { + // not paging + validateNoInvalidParameterIsLeft(params); } + return pageMetadata; + } - protected List getQueryList(BaseQuery query, PageMetadata pageMetadata) { - List resultList; - if (pageMetadata != null) { - resultList = query.listPage((int) pageMetadata.getNumber(), (int) pageMetadata.getSize()); - } else { - resultList = query.list(); - } - return resultList; + protected List getQueryList(BaseQuery query, PageMetadata pageMetadata) { + List resultList; + if (pageMetadata != null) { + resultList = query.listPage((int) pageMetadata.getNumber(), (int) pageMetadata.getSize()); + } else { + resultList = query.list(); } + return resultList; + } - private boolean hasPagingInformationInParams(MultiValueMap params) { - return params.getFirst(PAGING_PAGE) != null; + protected PageMetadata initPageMetadata(MultiValueMap param, long totalElements) + throws InvalidArgumentException { + long pageSize = getPageSize(param); + long page = getPage(param); + + PageMetadata pageMetadata = + new PageMetadata(pageSize, page, totalElements >= 0 ? totalElements : Integer.MAX_VALUE); + if (pageMetadata.getNumber() > pageMetadata.getTotalPages()) { + // unfortunately no setter for number + pageMetadata = new PageMetadata(pageSize, pageMetadata.getTotalPages(), totalElements); } + return pageMetadata; + } - protected PageMetadata initPageMetadata(MultiValueMap param, long totalElements) - throws InvalidArgumentException { - long pageSize = getPageSize(param); - long page = getPage(param); - - PageMetadata pageMetadata = new PageMetadata(pageSize, page, - totalElements >= 0 ? totalElements : Integer.MAX_VALUE); - if (pageMetadata.getNumber() > pageMetadata.getTotalPages()) { - // unfortunately no setter for number - pageMetadata = new PageMetadata(pageSize, pageMetadata.getTotalPages(), totalElements); - } - return pageMetadata; + // This method is deprecated please remove it after updating taskana-simple-history reference to + // it. + // TODO: @Deprecated + protected PageMetadata initPageMetadata( + String pagesizeParam, String pageParam, long totalElements) throws InvalidArgumentException { + long pageSize; + long page; + try { + pageSize = Long.parseLong(pagesizeParam); + page = Long.parseLong(pageParam); + } catch (NumberFormatException e) { + throw new InvalidArgumentException( + "page and pageSize must be a integer value.", e.getCause()); } - - // This method is deprecated please remove it after updating taskana-simple-history reference to it. - //TODO: @Deprecated - protected PageMetadata initPageMetadata(String pagesizeParam, String pageParam, long totalElements) - throws InvalidArgumentException { - long pageSize; - long page; - try { - pageSize = Long.parseLong(pagesizeParam); - page = Long.parseLong(pageParam); - } catch (NumberFormatException e) { - throw new InvalidArgumentException("page and pageSize must be a integer value.", e.getCause()); - } - PageMetadata pageMetadata = new PageMetadata(pageSize, page, totalElements); - if (pageMetadata.getNumber() > pageMetadata.getTotalPages()) { - // unfortunately no setter for number - pageMetadata = new PageMetadata(pageSize, pageMetadata.getTotalPages(), totalElements); - } - return pageMetadata; + PageMetadata pageMetadata = new PageMetadata(pageSize, page, totalElements); + if (pageMetadata.getNumber() > pageMetadata.getTotalPages()) { + // unfortunately no setter for number + pageMetadata = new PageMetadata(pageSize, pageMetadata.getTotalPages(), totalElements); } + return pageMetadata; + } - private long getPage(MultiValueMap params) throws InvalidArgumentException { - String param = params.getFirst(PAGING_PAGE); - params.remove(PAGING_PAGE); - try { - return Long.parseLong(param != null ? param : "1"); - } catch (NumberFormatException e) { - throw new InvalidArgumentException("page must be a integer value.", e.getCause()); - } + private boolean hasPagingInformationInParams(MultiValueMap params) { + return params.getFirst(PAGING_PAGE) != null; + } + + private long getPage(MultiValueMap params) throws InvalidArgumentException { + String param = params.getFirst(PAGING_PAGE); + params.remove(PAGING_PAGE); + try { + return Long.parseLong(param != null ? param : "1"); + } catch (NumberFormatException e) { + throw new InvalidArgumentException("page must be a integer value.", e.getCause()); } + } - private long getPageSize(MultiValueMap params) throws InvalidArgumentException { - String param = params.getFirst(PAGING_PAGE_SIZE); - params.remove(PAGING_PAGE_SIZE); - try { - return param != null ? Long.parseLong(param) : Integer.MAX_VALUE; - } catch (NumberFormatException e) { - throw new InvalidArgumentException("page-size must be a integer value.", e.getCause()); - } + private long getPageSize(MultiValueMap params) throws InvalidArgumentException { + String param = params.getFirst(PAGING_PAGE_SIZE); + params.remove(PAGING_PAGE_SIZE); + try { + return param != null ? Long.parseLong(param) : Integer.MAX_VALUE; + } catch (NumberFormatException e) { + throw new InvalidArgumentException("page-size must be a integer value.", e.getCause()); } - + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/AccessIdController.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/AccessIdController.java index 23bf747f3..5db55c618 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/AccessIdController.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/AccessIdController.java @@ -1,7 +1,6 @@ package pro.taskana.rest; import java.util.List; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -26,88 +25,89 @@ import pro.taskana.rest.resource.AccessIdResource; @EnableHypermediaSupport(type = HypermediaType.HAL) public class AccessIdController { - private static final Logger LOGGER = LoggerFactory.getLogger(AccessIdController.class); + private static final Logger LOGGER = LoggerFactory.getLogger(AccessIdController.class); + private static LdapCache ldapCache; + @Autowired LdapClient ldapClient; - @Autowired - LdapClient ldapClient; - - private static LdapCache ldapCache; - - @GetMapping(path = Mapping.URL_ACCESSID) - public ResponseEntity> validateAccessIds( - @RequestParam("search-for") String searchFor) throws InvalidArgumentException { - LOGGER.debug("Entry to validateAccessIds(search-for= {})", searchFor); - if (searchFor.length() < ldapClient.getMinSearchForLength()) { - throw new InvalidArgumentException( - "searchFor string '" + searchFor + "' is too short. Minimum searchFor length = " - + ldapClient.getMinSearchForLength()); - } - ResponseEntity> response; - if (ldapClient.useLdap()) { - List accessIdUsers = ldapClient.searchUsersAndGroups(searchFor); - response = ResponseEntity.ok(accessIdUsers); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from validateAccessIds(), returning {}", response); - } - - return response; - } else if (ldapCache != null) { - response = ResponseEntity.ok( - ldapCache.findMatchingAccessId(searchFor, ldapClient.getMaxNumberOfReturnedAccessIds())); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from validateAccessIds(), returning {}", response); - } - - return response; - } else { - response = ResponseEntity.notFound().build(); - LOGGER.debug("Exit from validateAccessIds(), returning {}", response); - return response; - } + @GetMapping(path = Mapping.URL_ACCESSID) + public ResponseEntity> validateAccessIds( + @RequestParam("search-for") String searchFor) throws InvalidArgumentException { + LOGGER.debug("Entry to validateAccessIds(search-for= {})", searchFor); + if (searchFor.length() < ldapClient.getMinSearchForLength()) { + throw new InvalidArgumentException( + "searchFor string '" + + searchFor + + "' is too short. Minimum searchFor length = " + + ldapClient.getMinSearchForLength()); } + ResponseEntity> response; + if (ldapClient.useLdap()) { + List accessIdUsers = ldapClient.searchUsersAndGroups(searchFor); + response = ResponseEntity.ok(accessIdUsers); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from validateAccessIds(), returning {}", response); + } - @GetMapping(path = Mapping.URL_ACCESSID_GROUPS) - public ResponseEntity> getGroupsByAccessId( - @RequestParam("access-id") String accessId) throws InvalidArgumentException { - LOGGER.debug("Entry to getGroupsByAccessId(access-id= {})", accessId); - if (ldapClient.useLdap() || ldapCache != null) { - if (!validateAccessId(accessId)) { - throw new InvalidArgumentException("The accessId is invalid"); - } - } - List accessIdUsers; - ResponseEntity> response; - if (ldapClient.useLdap()) { - accessIdUsers = ldapClient.searchUsersAndGroups(accessId); - accessIdUsers.addAll(ldapClient.searchGroupsofUsersIsMember(accessId)); - response = ResponseEntity.ok(accessIdUsers); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from getGroupsByAccessId(), returning {}", response); - } + return response; + } else if (ldapCache != null) { + response = + ResponseEntity.ok( + ldapCache.findMatchingAccessId( + searchFor, ldapClient.getMaxNumberOfReturnedAccessIds())); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from validateAccessIds(), returning {}", response); + } - return response; - } else if (ldapCache != null) { - accessIdUsers = ldapCache.findGroupsOfUser(accessId, ldapClient.getMaxNumberOfReturnedAccessIds()); - response = ResponseEntity.ok(accessIdUsers); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from getGroupsByAccessId(), returning {}", response); - } - - return response; - } else { - response = ResponseEntity.notFound().build(); - LOGGER.debug("Exit from getGroupsByAccessId(), returning {}", response); - return response; - } + return response; + } else { + response = ResponseEntity.notFound().build(); + LOGGER.debug("Exit from validateAccessIds(), returning {}", response); + return response; } + } - public static void setLdapCache(LdapCache cache) { - ldapCache = cache; + @GetMapping(path = Mapping.URL_ACCESSID_GROUPS) + public ResponseEntity> getGroupsByAccessId( + @RequestParam("access-id") String accessId) throws InvalidArgumentException { + LOGGER.debug("Entry to getGroupsByAccessId(access-id= {})", accessId); + if (ldapClient.useLdap() || ldapCache != null) { + if (!validateAccessId(accessId)) { + throw new InvalidArgumentException("The accessId is invalid"); + } } + List accessIdUsers; + ResponseEntity> response; + if (ldapClient.useLdap()) { + accessIdUsers = ldapClient.searchUsersAndGroups(accessId); + accessIdUsers.addAll(ldapClient.searchGroupsofUsersIsMember(accessId)); + response = ResponseEntity.ok(accessIdUsers); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from getGroupsByAccessId(), returning {}", response); + } - private boolean validateAccessId(String accessId) throws InvalidArgumentException { - return (ldapClient.useLdap() && ldapClient.searchUsersAndGroups(accessId).size() == 1) || (!ldapClient.useLdap() - && ldapCache.validateAccessId(accessId).size() == 1); + return response; + } else if (ldapCache != null) { + accessIdUsers = + ldapCache.findGroupsOfUser(accessId, ldapClient.getMaxNumberOfReturnedAccessIds()); + response = ResponseEntity.ok(accessIdUsers); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from getGroupsByAccessId(), returning {}", response); + } + + return response; + } else { + response = ResponseEntity.notFound().build(); + LOGGER.debug("Exit from getGroupsByAccessId(), returning {}", response); + return response; } + } + public static void setLdapCache(LdapCache cache) { + ldapCache = cache; + } + + private boolean validateAccessId(String accessId) throws InvalidArgumentException { + return (ldapClient.useLdap() && ldapClient.searchUsersAndGroups(accessId).size() == 1) + || (!ldapClient.useLdap() && ldapCache.validateAccessId(accessId).size() == 1); + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/AttachmentController.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/AttachmentController.java index 5f40bcb25..0124445f2 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/AttachmentController.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/AttachmentController.java @@ -1,8 +1,4 @@ package pro.taskana.rest; -/** - * Controller for all {@link pro.taskana.Attachment} related endpoints. - */ -public class AttachmentController { - -} +/** Controller for all {@link pro.taskana.Attachment} related endpoints. */ +public class AttachmentController {} diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/ClassificationController.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/ClassificationController.java index 1202fc3f5..adeb1a1a4 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/ClassificationController.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/ClassificationController.java @@ -1,7 +1,6 @@ package pro.taskana.rest; import java.util.List; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.hateoas.config.EnableHypermediaSupport; @@ -37,283 +36,289 @@ import pro.taskana.rest.resource.ClassificationSummaryListResource; import pro.taskana.rest.resource.ClassificationSummaryResourceAssembler; import pro.taskana.rest.resource.PagedResources.PageMetadata; -/** - * Controller for all {@link Classification} related endpoints. - */ +/** Controller for all {@link Classification} related endpoints. */ @RestController @EnableHypermediaSupport(type = HypermediaType.HAL) public class ClassificationController extends AbstractPagingController { - private static final Logger LOGGER = LoggerFactory.getLogger(ClassificationController.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ClassificationController.class); - private static final String LIKE = "%"; + private static final String LIKE = "%"; - private static final String NAME = "name"; + private static final String NAME = "name"; - private static final String NAME_LIKE = "name-like"; + private static final String NAME_LIKE = "name-like"; - private static final String KEY = "key"; + private static final String KEY = "key"; - private static final String DOMAIN = "domain"; + private static final String DOMAIN = "domain"; - private static final String CATEGORY = "category"; + private static final String CATEGORY = "category"; - private static final String TYPE = "type"; + private static final String TYPE = "type"; - private static final String CUSTOM_1_LIKE = "custom-1-like"; + private static final String CUSTOM_1_LIKE = "custom-1-like"; - private static final String CUSTOM_2_LIKE = "custom-2-like"; + private static final String CUSTOM_2_LIKE = "custom-2-like"; - private static final String CUSTOM_3_LIKE = "custom-3-like"; + private static final String CUSTOM_3_LIKE = "custom-3-like"; - private static final String CUSTOM_4_LIKE = "custom-4-like"; + private static final String CUSTOM_4_LIKE = "custom-4-like"; - private static final String CUSTOM_5_LIKE = "custom-5-like"; + private static final String CUSTOM_5_LIKE = "custom-5-like"; - private static final String CUSTOM_6_LIKE = "custom-6-like"; + private static final String CUSTOM_6_LIKE = "custom-6-like"; - private static final String CUSTOM_7_LIKE = "custom-7-like"; + private static final String CUSTOM_7_LIKE = "custom-7-like"; - private static final String CUSTOM_8_LIKE = "custom-8-like"; + private static final String CUSTOM_8_LIKE = "custom-8-like"; - private static final String SORT_BY = "sort-by"; + private static final String SORT_BY = "sort-by"; - private static final String SORT_DIRECTION = "order"; + private static final String SORT_DIRECTION = "order"; - private ClassificationService classificationService; + private ClassificationService classificationService; - private ClassificationResourceAssembler classificationResourceAssembler; + private ClassificationResourceAssembler classificationResourceAssembler; - private ClassificationSummaryResourceAssembler classificationSummaryResourceAssembler; + private ClassificationSummaryResourceAssembler classificationSummaryResourceAssembler; - ClassificationController( - ClassificationService classificationService, - ClassificationResourceAssembler classificationResourceAssembler, - ClassificationSummaryResourceAssembler classificationSummaryResourceAssembler) { - this.classificationService = classificationService; - this.classificationResourceAssembler = classificationResourceAssembler; - this.classificationSummaryResourceAssembler = classificationSummaryResourceAssembler; + ClassificationController( + ClassificationService classificationService, + ClassificationResourceAssembler classificationResourceAssembler, + ClassificationSummaryResourceAssembler classificationSummaryResourceAssembler) { + this.classificationService = classificationService; + this.classificationResourceAssembler = classificationResourceAssembler; + this.classificationSummaryResourceAssembler = classificationSummaryResourceAssembler; + } + + @GetMapping(path = Mapping.URL_CLASSIFICATIONS) + @Transactional(readOnly = true, rollbackFor = Exception.class) + public ResponseEntity getClassifications( + @RequestParam MultiValueMap params) throws InvalidArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Entry to getClassifications(params= {})", params); } - @GetMapping(path = Mapping.URL_CLASSIFICATIONS) - @Transactional(readOnly = true, rollbackFor = Exception.class) - public ResponseEntity getClassifications( - @RequestParam MultiValueMap params) throws InvalidArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Entry to getClassifications(params= {})", params); - } + ClassificationQuery query = classificationService.createClassificationQuery(); + query = applySortingParams(query, params); + query = applyFilterParams(query, params); - ClassificationQuery query = classificationService.createClassificationQuery(); - query = applySortingParams(query, params); - query = applyFilterParams(query, params); + PageMetadata pageMetadata = getPageMetadata(params, query); + List classificationSummaries = getQueryList(query, pageMetadata); - PageMetadata pageMetadata = getPageMetadata(params, query); - List classificationSummaries = getQueryList(query, pageMetadata); - - ResponseEntity response = ResponseEntity.ok( + ResponseEntity response = + ResponseEntity.ok( classificationSummaryResourceAssembler.toResources( - classificationSummaries, - pageMetadata)); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from getClassifications(), returning {}", response); - } - - return response; + classificationSummaries, pageMetadata)); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from getClassifications(), returning {}", response); } - @GetMapping(path = Mapping.URL_CLASSIFICATIONS_ID) - @Transactional(readOnly = true, rollbackFor = Exception.class) - public ResponseEntity getClassification(@PathVariable String classificationId) - throws ClassificationNotFoundException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Entry to getClassification(classificationId= {})", classificationId); - } + return response; + } - Classification classification = classificationService.getClassification(classificationId); - ResponseEntity response = ResponseEntity.ok( - classificationResourceAssembler.toResource(classification)); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from getClassification(), returning {}", response); - } - - return response; + @GetMapping(path = Mapping.URL_CLASSIFICATIONS_ID) + @Transactional(readOnly = true, rollbackFor = Exception.class) + public ResponseEntity getClassification( + @PathVariable String classificationId) throws ClassificationNotFoundException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Entry to getClassification(classificationId= {})", classificationId); } - @PostMapping(path = Mapping.URL_CLASSIFICATIONS) - @Transactional(rollbackFor = Exception.class) - public ResponseEntity createClassification( - @RequestBody ClassificationResource resource) - throws NotAuthorizedException, ClassificationAlreadyExistException, - DomainNotFoundException, InvalidArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Entry to createClassification(resource= {})", resource); - } - Classification classification = classificationResourceAssembler.toModel(resource); - classification = classificationService.createClassification(classification); + Classification classification = classificationService.getClassification(classificationId); + ResponseEntity response = + ResponseEntity.ok(classificationResourceAssembler.toResource(classification)); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from getClassification(), returning {}", response); + } - ResponseEntity response = ResponseEntity.status(HttpStatus.CREATED) + return response; + } + + @PostMapping(path = Mapping.URL_CLASSIFICATIONS) + @Transactional(rollbackFor = Exception.class) + public ResponseEntity createClassification( + @RequestBody ClassificationResource resource) + throws NotAuthorizedException, ClassificationAlreadyExistException, DomainNotFoundException, + InvalidArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Entry to createClassification(resource= {})", resource); + } + Classification classification = classificationResourceAssembler.toModel(resource); + classification = classificationService.createClassification(classification); + + ResponseEntity response = + ResponseEntity.status(HttpStatus.CREATED) .body(classificationResourceAssembler.toResource(classification)); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from createClassification(), returning {}", response); - } - - return response; + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from createClassification(), returning {}", response); } - @PutMapping(path = Mapping.URL_CLASSIFICATIONS_ID) - @Transactional(rollbackFor = Exception.class) - public ResponseEntity updateClassification( - @PathVariable(value = "classificationId") String classificationId, @RequestBody ClassificationResource resource) - throws NotAuthorizedException, ClassificationNotFoundException, ConcurrencyException, - InvalidArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Entry to updateClassification(classificationId= {}, resource= {})", classificationId, - resource); - } + return response; + } - ResponseEntity result; - if (classificationId.equals(resource.classificationId)) { - Classification classification = classificationResourceAssembler.toModel(resource); - classification = classificationService.updateClassification(classification); - result = ResponseEntity.ok(classificationResourceAssembler.toResource(classification)); - } else { - throw new InvalidArgumentException( - "ClassificationId ('" + classificationId - + "') of the URI is not identical with the classificationId ('" - + resource.getClassificationId() + "') of the object in the payload."); - } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from updateClassification(), returning {}", result); - } - - return result; + @PutMapping(path = Mapping.URL_CLASSIFICATIONS_ID) + @Transactional(rollbackFor = Exception.class) + public ResponseEntity updateClassification( + @PathVariable(value = "classificationId") String classificationId, + @RequestBody ClassificationResource resource) + throws NotAuthorizedException, ClassificationNotFoundException, ConcurrencyException, + InvalidArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "Entry to updateClassification(classificationId= {}, resource= {})", + classificationId, + resource); } - @DeleteMapping(path = Mapping.URL_CLASSIFICATIONS_ID) - @Transactional(readOnly = true, rollbackFor = Exception.class) - public ResponseEntity deleteClassification(@PathVariable String classificationId) - throws ClassificationNotFoundException, ClassificationInUseException, NotAuthorizedException { - LOGGER.debug("Entry to deleteClassification(classificationId= {})", classificationId); - classificationService.deleteClassification(classificationId); - ResponseEntity response = ResponseEntity.noContent().build(); - LOGGER.debug("Exit from deleteClassification(), returning {}", response); - return response; + ResponseEntity result; + if (classificationId.equals(resource.classificationId)) { + Classification classification = classificationResourceAssembler.toModel(resource); + classification = classificationService.updateClassification(classification); + result = ResponseEntity.ok(classificationResourceAssembler.toResource(classification)); + } else { + throw new InvalidArgumentException( + "ClassificationId ('" + + classificationId + + "') of the URI is not identical with the classificationId ('" + + resource.getClassificationId() + + "') of the object in the payload."); + } + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from updateClassification(), returning {}", result); } - private ClassificationQuery applySortingParams(ClassificationQuery query, MultiValueMap params) - throws IllegalArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Entry to applySortingParams(query= {}, params= {})", query, params); - } + return result; + } - // sorting - String sortBy = params.getFirst(SORT_BY); - if (sortBy != null) { - SortDirection sortDirection; - if (params.getFirst(SORT_DIRECTION) != null && "desc".equals(params.getFirst(SORT_DIRECTION))) { - sortDirection = SortDirection.DESCENDING; - } else { - sortDirection = SortDirection.ASCENDING; - } - switch (sortBy) { - case (CATEGORY): - query = query.orderByCategory(sortDirection); - break; - case (DOMAIN): - query = query.orderByDomain(sortDirection); - break; - case (KEY): - query = query.orderByKey(sortDirection); - break; - case (NAME): - query = query.orderByName(sortDirection); - break; - default: - throw new IllegalArgumentException("Unknown order '" + sortBy + "'"); - } - } - params.remove(SORT_BY); - params.remove(SORT_DIRECTION); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from applySortingParams(), returning {}", query); - } + @DeleteMapping(path = Mapping.URL_CLASSIFICATIONS_ID) + @Transactional(readOnly = true, rollbackFor = Exception.class) + public ResponseEntity deleteClassification(@PathVariable String classificationId) + throws ClassificationNotFoundException, ClassificationInUseException, NotAuthorizedException { + LOGGER.debug("Entry to deleteClassification(classificationId= {})", classificationId); + classificationService.deleteClassification(classificationId); + ResponseEntity response = ResponseEntity.noContent().build(); + LOGGER.debug("Exit from deleteClassification(), returning {}", response); + return response; + } - return query; + private ClassificationQuery applySortingParams( + ClassificationQuery query, MultiValueMap params) + throws IllegalArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Entry to applySortingParams(query= {}, params= {})", query, params); } - private ClassificationQuery applyFilterParams(ClassificationQuery query, - MultiValueMap params) throws InvalidArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Entry to applyFilterParams(query= {}, params= {})", query, params); - } - - if (params.containsKey(NAME)) { - String[] names = extractCommaSeparatedFields(params.get(NAME)); - query.nameIn(names); - params.remove(NAME); - } - if (params.containsKey(NAME_LIKE)) { - query.nameLike(LIKE + params.get(NAME_LIKE).get(0) + LIKE); - params.remove(NAME_LIKE); - } - if (params.containsKey(KEY)) { - String[] names = extractCommaSeparatedFields(params.get(KEY)); - query.keyIn(names); - params.remove(KEY); - } - if (params.containsKey(CATEGORY)) { - String[] names = extractCommaSeparatedFields(params.get(CATEGORY)); - query.categoryIn(names); - params.remove(CATEGORY); - } - if (params.containsKey(DOMAIN)) { - String[] names = extractCommaSeparatedFields(params.get(DOMAIN)); - query.domainIn(names); - params.remove(DOMAIN); - } - if (params.containsKey(TYPE)) { - String[] names = extractCommaSeparatedFields(params.get(TYPE)); - query.typeIn(names); - params.remove(TYPE); - } - if (params.containsKey(CUSTOM_1_LIKE)) { - query.customAttributeLike("1", LIKE + params.get(CUSTOM_1_LIKE).get(0) + LIKE); - params.remove(CUSTOM_1_LIKE); - } - if (params.containsKey(CUSTOM_2_LIKE)) { - query.customAttributeLike("2", LIKE + params.get(CUSTOM_2_LIKE).get(0) + LIKE); - params.remove(CUSTOM_2_LIKE); - } - if (params.containsKey(CUSTOM_3_LIKE)) { - query.customAttributeLike("3", LIKE + params.get(CUSTOM_3_LIKE).get(0) + LIKE); - params.remove(CUSTOM_3_LIKE); - } - if (params.containsKey(CUSTOM_4_LIKE)) { - query.customAttributeLike("4", LIKE + params.get(CUSTOM_4_LIKE).get(0) + LIKE); - params.remove(CUSTOM_4_LIKE); - } - if (params.containsKey(CUSTOM_5_LIKE)) { - query.customAttributeLike("5", LIKE + params.get(CUSTOM_5_LIKE).get(0) + LIKE); - params.remove(CUSTOM_5_LIKE); - } - if (params.containsKey(CUSTOM_6_LIKE)) { - query.customAttributeLike("6", LIKE + params.get(CUSTOM_6_LIKE).get(0) + LIKE); - params.remove(CUSTOM_6_LIKE); - } - if (params.containsKey(CUSTOM_7_LIKE)) { - query.customAttributeLike("7", LIKE + params.get(CUSTOM_7_LIKE).get(0) + LIKE); - params.remove(CUSTOM_7_LIKE); - } - if (params.containsKey(CUSTOM_8_LIKE)) { - query.customAttributeLike("8", LIKE + params.get(CUSTOM_8_LIKE).get(0) + LIKE); - params.remove(CUSTOM_8_LIKE); - } - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from applyFilterParams(), returning {}", query); - } - - return query; + // sorting + String sortBy = params.getFirst(SORT_BY); + if (sortBy != null) { + SortDirection sortDirection; + if (params.getFirst(SORT_DIRECTION) != null + && "desc".equals(params.getFirst(SORT_DIRECTION))) { + sortDirection = SortDirection.DESCENDING; + } else { + sortDirection = SortDirection.ASCENDING; + } + switch (sortBy) { + case (CATEGORY): + query = query.orderByCategory(sortDirection); + break; + case (DOMAIN): + query = query.orderByDomain(sortDirection); + break; + case (KEY): + query = query.orderByKey(sortDirection); + break; + case (NAME): + query = query.orderByName(sortDirection); + break; + default: + throw new IllegalArgumentException("Unknown order '" + sortBy + "'"); + } + } + params.remove(SORT_BY); + params.remove(SORT_DIRECTION); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from applySortingParams(), returning {}", query); } + return query; + } + + private ClassificationQuery applyFilterParams( + ClassificationQuery query, MultiValueMap params) + throws InvalidArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Entry to applyFilterParams(query= {}, params= {})", query, params); + } + + if (params.containsKey(NAME)) { + String[] names = extractCommaSeparatedFields(params.get(NAME)); + query.nameIn(names); + params.remove(NAME); + } + if (params.containsKey(NAME_LIKE)) { + query.nameLike(LIKE + params.get(NAME_LIKE).get(0) + LIKE); + params.remove(NAME_LIKE); + } + if (params.containsKey(KEY)) { + String[] names = extractCommaSeparatedFields(params.get(KEY)); + query.keyIn(names); + params.remove(KEY); + } + if (params.containsKey(CATEGORY)) { + String[] names = extractCommaSeparatedFields(params.get(CATEGORY)); + query.categoryIn(names); + params.remove(CATEGORY); + } + if (params.containsKey(DOMAIN)) { + String[] names = extractCommaSeparatedFields(params.get(DOMAIN)); + query.domainIn(names); + params.remove(DOMAIN); + } + if (params.containsKey(TYPE)) { + String[] names = extractCommaSeparatedFields(params.get(TYPE)); + query.typeIn(names); + params.remove(TYPE); + } + if (params.containsKey(CUSTOM_1_LIKE)) { + query.customAttributeLike("1", LIKE + params.get(CUSTOM_1_LIKE).get(0) + LIKE); + params.remove(CUSTOM_1_LIKE); + } + if (params.containsKey(CUSTOM_2_LIKE)) { + query.customAttributeLike("2", LIKE + params.get(CUSTOM_2_LIKE).get(0) + LIKE); + params.remove(CUSTOM_2_LIKE); + } + if (params.containsKey(CUSTOM_3_LIKE)) { + query.customAttributeLike("3", LIKE + params.get(CUSTOM_3_LIKE).get(0) + LIKE); + params.remove(CUSTOM_3_LIKE); + } + if (params.containsKey(CUSTOM_4_LIKE)) { + query.customAttributeLike("4", LIKE + params.get(CUSTOM_4_LIKE).get(0) + LIKE); + params.remove(CUSTOM_4_LIKE); + } + if (params.containsKey(CUSTOM_5_LIKE)) { + query.customAttributeLike("5", LIKE + params.get(CUSTOM_5_LIKE).get(0) + LIKE); + params.remove(CUSTOM_5_LIKE); + } + if (params.containsKey(CUSTOM_6_LIKE)) { + query.customAttributeLike("6", LIKE + params.get(CUSTOM_6_LIKE).get(0) + LIKE); + params.remove(CUSTOM_6_LIKE); + } + if (params.containsKey(CUSTOM_7_LIKE)) { + query.customAttributeLike("7", LIKE + params.get(CUSTOM_7_LIKE).get(0) + LIKE); + params.remove(CUSTOM_7_LIKE); + } + if (params.containsKey(CUSTOM_8_LIKE)) { + query.customAttributeLike("8", LIKE + params.get(CUSTOM_8_LIKE).get(0) + LIKE); + params.remove(CUSTOM_8_LIKE); + } + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from applyFilterParams(), returning {}", query); + } + + return query; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/ClassificationDefinitionController.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/ClassificationDefinitionController.java index d86b7ec93..dfa346e3c 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/ClassificationDefinitionController.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/ClassificationDefinitionController.java @@ -1,5 +1,8 @@ package pro.taskana.rest; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; @@ -8,7 +11,6 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DuplicateKeyException; @@ -21,10 +23,6 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; - import pro.taskana.Classification; import pro.taskana.ClassificationQuery; import pro.taskana.ClassificationService; @@ -39,212 +37,221 @@ import pro.taskana.impl.util.LoggerUtils; import pro.taskana.rest.resource.ClassificationResource; import pro.taskana.rest.resource.ClassificationResourceAssembler; -/** - * Controller for Importing / Exporting classifications. - */ +/** Controller for Importing / Exporting classifications. */ @RestController @EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL) public class ClassificationDefinitionController { - private static final Logger LOGGER = LoggerFactory.getLogger(ClassificationDefinitionController.class); + private static final Logger LOGGER = + LoggerFactory.getLogger(ClassificationDefinitionController.class); - private ClassificationService classificationService; + private ClassificationService classificationService; - private ClassificationResourceAssembler classificationResourceAssembler; + private ClassificationResourceAssembler classificationResourceAssembler; - ClassificationDefinitionController( - ClassificationService classificationService, - ClassificationResourceAssembler classificationResourceAssembler) { - this.classificationService = classificationService; - this.classificationResourceAssembler = classificationResourceAssembler; + ClassificationDefinitionController( + ClassificationService classificationService, + ClassificationResourceAssembler classificationResourceAssembler) { + this.classificationService = classificationService; + this.classificationResourceAssembler = classificationResourceAssembler; + } + + @GetMapping(path = Mapping.URL_CLASSIFICATIONDEFINITION) + @Transactional(readOnly = true, rollbackFor = Exception.class) + public ResponseEntity> exportClassifications( + @RequestParam(required = false) String domain) throws ClassificationNotFoundException { + LOGGER.debug("Entry to exportClassifications(domain= {})", domain); + ClassificationQuery query = classificationService.createClassificationQuery(); + + List summaries = + domain != null ? query.domainIn(domain).list() : query.list(); + List export = new ArrayList<>(); + + for (ClassificationSummary summary : summaries) { + Classification classification = + classificationService.getClassification(summary.getKey(), summary.getDomain()); + + export.add(classificationResourceAssembler.toDefinition(classification)); } - @GetMapping(path = Mapping.URL_CLASSIFICATIONDEFINITION) - @Transactional(readOnly = true, rollbackFor = Exception.class) - public ResponseEntity> exportClassifications( - @RequestParam(required = false) String domain) - throws ClassificationNotFoundException { - LOGGER.debug("Entry to exportClassifications(domain= {})", domain); - ClassificationQuery query = classificationService.createClassificationQuery(); + ResponseEntity> response = ResponseEntity.ok(export); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from exportClassifications(), returning {}", response); + } - List summaries = domain != null ? query.domainIn(domain).list() : query.list(); - List export = new ArrayList<>(); + return response; + } - for (ClassificationSummary summary : summaries) { - Classification classification = classificationService.getClassification(summary.getKey(), - summary.getDomain()); + @PostMapping(path = Mapping.URL_CLASSIFICATIONDEFINITION) + @Transactional(rollbackFor = Exception.class) + public ResponseEntity importClassifications(@RequestParam("file") MultipartFile file) + throws InvalidArgumentException, NotAuthorizedException, ConcurrencyException, + ClassificationNotFoundException, ClassificationAlreadyExistException, + DomainNotFoundException, IOException { + LOGGER.debug("Entry to importClassifications()"); + Map systemIds = getSystemIds(); + List classificationsResources = + extractClassificationResourcesFromFile(file); + checkForDuplicates(classificationsResources); - export.add(classificationResourceAssembler.toDefinition(classification)); + Map childrenInFile = + mapChildrenToParentKeys(classificationsResources, systemIds); + insertOrUpdateClassificationsWithoutParent(classificationsResources, systemIds); + updateParentChildrenRelations(childrenInFile); + ResponseEntity response = ResponseEntity.noContent().build(); + LOGGER.debug("Exit from importClassifications(), returning {}", response); + return response; + } + + private Map getSystemIds() { + Map systemIds = + classificationService.createClassificationQuery().list().stream() + .collect( + Collectors.toMap( + i -> i.getKey() + "|" + i.getDomain(), ClassificationSummary::getId)); + return systemIds; + } + + private List extractClassificationResourcesFromFile(MultipartFile file) + throws IOException { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + List classificationsDefinitions = + mapper.readValue( + file.getInputStream(), new TypeReference>() {}); + + return classificationsDefinitions; + } + + private void checkForDuplicates(List classificationList) { + List identifiers = new ArrayList<>(); + Set duplicates = new HashSet<>(); + for (ClassificationResource classification : classificationList) { + String identifier = classification.key + "|" + classification.domain; + if (identifiers.contains(identifier)) { + duplicates.add(identifier); + } else { + identifiers.add(identifier); + } + } + if (!duplicates.isEmpty()) { + throw new DuplicateKeyException( + "The 'key|domain'-identifier is not unique for the value(s): " + duplicates.toString()); + } + } + + private Map mapChildrenToParentKeys( + List classificationResources, Map systemIds) { + LOGGER.debug("Entry to mapChildrenToParentKeys()"); + Map childrenInFile = new HashMap<>(); + Set newKeysWithDomain = new HashSet<>(); + classificationResources.forEach( + cl -> newKeysWithDomain.add(cl.getKey() + "|" + cl.getDomain())); + + for (ClassificationResource cl : classificationResources) { + cl.parentId = cl.parentId == null ? "" : cl.parentId; + cl.parentKey = cl.parentKey == null ? "" : cl.parentKey; + + if (!cl.getParentId().equals("") && cl.getParentKey().equals("")) { + for (ClassificationResource parent : classificationResources) { + if (cl.getParentId().equals(parent.getClassificationId())) { + cl.setParentKey(parent.getKey()); + } } + } - ResponseEntity> response = ResponseEntity.ok(export); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from exportClassifications(), returning {}", response); + String parentKeyAndDomain = cl.parentKey + "|" + cl.domain; + if (!cl.getParentKey().isEmpty() && !cl.getParentKey().equals("")) { + if (newKeysWithDomain.contains(parentKeyAndDomain) + || systemIds.containsKey(parentKeyAndDomain)) { + childrenInFile.put(classificationResourceAssembler.toModel(cl), cl.getParentKey()); } - - return response; + } + } + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "Exit from mapChildrenToParentKeys(), returning {}", + LoggerUtils.mapToString(childrenInFile)); } - @PostMapping(path = Mapping.URL_CLASSIFICATIONDEFINITION) - @Transactional(rollbackFor = Exception.class) - public ResponseEntity importClassifications( - @RequestParam("file") MultipartFile file) - throws InvalidArgumentException, NotAuthorizedException, ConcurrencyException, ClassificationNotFoundException, - ClassificationAlreadyExistException, DomainNotFoundException, IOException { - LOGGER.debug("Entry to importClassifications()"); - Map systemIds = getSystemIds(); - List classificationsResources = extractClassificationResourcesFromFile(file); - checkForDuplicates(classificationsResources); + return childrenInFile; + } - Map childrenInFile = mapChildrenToParentKeys(classificationsResources, systemIds); - insertOrUpdateClassificationsWithoutParent(classificationsResources, systemIds); - updateParentChildrenRelations(childrenInFile); - ResponseEntity response = ResponseEntity.noContent().build(); - LOGGER.debug("Exit from importClassifications(), returning {}", response); - return response; + private void insertOrUpdateClassificationsWithoutParent( + List classificationResources, Map systemIds) + throws ClassificationNotFoundException, NotAuthorizedException, InvalidArgumentException, + ClassificationAlreadyExistException, DomainNotFoundException, ConcurrencyException { + LOGGER.debug("Entry to insertOrUpdateClassificationsWithoutParent()"); + + for (ClassificationResource classificationResource : classificationResources) { + classificationResource.setParentKey(null); + classificationResource.setParentId(null); + classificationResource.setClassificationId(null); + + String systemId = + systemIds.get(classificationResource.key + "|" + classificationResource.domain); + if (systemId != null) { + updateExistingClassification(classificationResource, systemId); + } else { + classificationService.createClassification( + classificationResourceAssembler.toModel(classificationResource)); + } } + LOGGER.debug("Exit from insertOrUpdateClassificationsWithoutParent()"); + } - private Map getSystemIds() { - Map systemIds = classificationService.createClassificationQuery() - .list() - .stream() - .collect(Collectors.toMap(i -> i.getKey() + "|" + i.getDomain(), ClassificationSummary::getId)); - return systemIds; + private void updateParentChildrenRelations(Map childrenInFile) + throws ClassificationNotFoundException, NotAuthorizedException, ConcurrencyException, + InvalidArgumentException { + LOGGER.debug("Entry to updateParentChildrenRelations()"); + + for (Map.Entry entry : childrenInFile.entrySet()) { + Classification childRes = entry.getKey(); + String parentKey = entry.getValue(); + String classificationKey = childRes.getKey(); + String classificationDomain = childRes.getDomain(); + + Classification child = + classificationService.getClassification(classificationKey, classificationDomain); + String parentId = + (parentKey == null) + ? "" + : classificationService.getClassification(parentKey, classificationDomain).getId(); + + child.setParentKey(parentKey); + child.setParentId(parentId); + + classificationService.updateClassification(child); } + LOGGER.debug("Exit from updateParentChildrenRelations()"); + } - private List extractClassificationResourcesFromFile(MultipartFile file) - throws IOException { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - List classificationsDefinitions = mapper.readValue(file.getInputStream(), - new TypeReference>() { - - }); - return classificationsDefinitions; + private void updateExistingClassification(ClassificationResource cl, String systemId) + throws ClassificationNotFoundException, NotAuthorizedException, ConcurrencyException, + InvalidArgumentException { + LOGGER.debug("Entry to updateExistingClassification()"); + Classification currentClassification = classificationService.getClassification(systemId); + if (cl.getType() != null && !cl.getType().equals(currentClassification.getType())) { + throw new InvalidArgumentException("Can not change the type of a classification."); } - - private void checkForDuplicates(List classificationList) { - List identifiers = new ArrayList<>(); - Set duplicates = new HashSet<>(); - for (ClassificationResource classification : classificationList) { - String identifier = classification.key + "|" + classification.domain; - if (identifiers.contains(identifier)) { - duplicates.add(identifier); - } else { - identifiers.add(identifier); - } - } - if (!duplicates.isEmpty()) { - throw new DuplicateKeyException( - "The 'key|domain'-identifier is not unique for the value(s): " + duplicates.toString()); - } - } - - private Map mapChildrenToParentKeys(List classificationResources, - Map systemIds) { - LOGGER.debug("Entry to mapChildrenToParentKeys()"); - Map childrenInFile = new HashMap<>(); - Set newKeysWithDomain = new HashSet<>(); - classificationResources.forEach(cl -> newKeysWithDomain.add(cl.getKey() + "|" + cl.getDomain())); - - for (ClassificationResource cl : classificationResources) { - cl.parentId = cl.parentId == null ? "" : cl.parentId; - cl.parentKey = cl.parentKey == null ? "" : cl.parentKey; - - if (!cl.getParentId().equals("") && cl.getParentKey().equals("")) { - for (ClassificationResource parent : classificationResources) { - if (cl.getParentId().equals(parent.getClassificationId())) { - cl.setParentKey(parent.getKey()); - } - } - } - - String parentKeyAndDomain = cl.parentKey + "|" + cl.domain; - if (!cl.getParentKey().isEmpty() && !cl.getParentKey().equals("")) { - if (newKeysWithDomain.contains(parentKeyAndDomain) || systemIds.containsKey(parentKeyAndDomain)) { - childrenInFile.put(classificationResourceAssembler.toModel(cl), cl.getParentKey()); - } - } - } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from mapChildrenToParentKeys(), returning {}", LoggerUtils.mapToString(childrenInFile)); - } - - return childrenInFile; - } - - private void insertOrUpdateClassificationsWithoutParent(List classificationResources, - Map systemIds) - throws ClassificationNotFoundException, NotAuthorizedException, InvalidArgumentException, - ClassificationAlreadyExistException, DomainNotFoundException, ConcurrencyException { - LOGGER.debug("Entry to insertOrUpdateClassificationsWithoutParent()"); - - for (ClassificationResource classificationResource : classificationResources) { - classificationResource.setParentKey(null); - classificationResource.setParentId(null); - classificationResource.setClassificationId(null); - - String systemId = systemIds.get(classificationResource.key + "|" + classificationResource.domain); - if (systemId != null) { - updateExistingClassification(classificationResource, systemId); - } else { - classificationService.createClassification( - classificationResourceAssembler.toModel(classificationResource)); - } - } - LOGGER.debug("Exit from insertOrUpdateClassificationsWithoutParent()"); - } - - private void updateParentChildrenRelations(Map childrenInFile) - throws ClassificationNotFoundException, NotAuthorizedException, ConcurrencyException, - InvalidArgumentException { - LOGGER.debug("Entry to updateParentChildrenRelations()"); - - for (Map.Entry entry : childrenInFile.entrySet()) { - Classification childRes = entry.getKey(); - String parentKey = entry.getValue(); - String classificationKey = childRes.getKey(); - String classificationDomain = childRes.getDomain(); - - Classification child = classificationService.getClassification(classificationKey, classificationDomain); - String parentId = (parentKey == null) ? "" - : classificationService.getClassification(parentKey, classificationDomain).getId(); - - child.setParentKey(parentKey); - child.setParentId(parentId); - - classificationService.updateClassification(child); - } - LOGGER.debug("Exit from updateParentChildrenRelations()"); - } - - private void updateExistingClassification(ClassificationResource cl, - String systemId) throws ClassificationNotFoundException, NotAuthorizedException, - ConcurrencyException, InvalidArgumentException { - LOGGER.debug("Entry to updateExistingClassification()"); - Classification currentClassification = classificationService.getClassification(systemId); - if (cl.getType() != null && !cl.getType().equals(currentClassification.getType())) { - throw new InvalidArgumentException("Can not change the type of a classification."); - } - currentClassification.setCategory(cl.category); - currentClassification.setIsValidInDomain(cl.isValidInDomain); - currentClassification.setName(cl.name); - currentClassification.setParentId(cl.parentId); - currentClassification.setParentKey(cl.parentKey); - currentClassification.setDescription(cl.description); - currentClassification.setPriority(cl.priority); - currentClassification.setServiceLevel(cl.serviceLevel); - currentClassification.setApplicationEntryPoint(cl.applicationEntryPoint); - currentClassification.setCustom1(cl.custom1); - currentClassification.setCustom2(cl.custom2); - currentClassification.setCustom3(cl.custom3); - currentClassification.setCustom4(cl.custom4); - currentClassification.setCustom5(cl.custom5); - currentClassification.setCustom6(cl.custom6); - currentClassification.setCustom7(cl.custom7); - currentClassification.setCustom8(cl.custom8); - classificationService.updateClassification(currentClassification); - LOGGER.debug("Exit from updateExistingClassification()"); - } - + currentClassification.setCategory(cl.category); + currentClassification.setIsValidInDomain(cl.isValidInDomain); + currentClassification.setName(cl.name); + currentClassification.setParentId(cl.parentId); + currentClassification.setParentKey(cl.parentKey); + currentClassification.setDescription(cl.description); + currentClassification.setPriority(cl.priority); + currentClassification.setServiceLevel(cl.serviceLevel); + currentClassification.setApplicationEntryPoint(cl.applicationEntryPoint); + currentClassification.setCustom1(cl.custom1); + currentClassification.setCustom2(cl.custom2); + currentClassification.setCustom3(cl.custom3); + currentClassification.setCustom4(cl.custom4); + currentClassification.setCustom5(cl.custom5); + currentClassification.setCustom6(cl.custom6); + currentClassification.setCustom7(cl.custom7); + currentClassification.setCustom8(cl.custom8); + classificationService.updateClassification(currentClassification); + LOGGER.debug("Exit from updateExistingClassification()"); + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/Mapping.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/Mapping.java index 05dbfb207..0899b5479 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/Mapping.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/Mapping.java @@ -1,53 +1,45 @@ package pro.taskana.rest; -/** - * Collection of Url to Controller mappings. - */ +/** Collection of Url to Controller mappings. */ public final class Mapping { - private static final String PRE = "/api/v1/"; - - public static final String URL_ACCESSID = PRE + "access-ids"; - public static final String URL_ACCESSID_GROUPS = URL_ACCESSID + "/groups"; - - public static final String URL_CLASSIFICATIONS = PRE + "classifications"; - public static final String URL_CLASSIFICATIONS_ID = URL_CLASSIFICATIONS + "/{classificationId}"; - - public static final String URL_CLASSIFICATIONDEFINITION = PRE + "classification-definitions"; - - public static final String URL_MONITOR = PRE + "monitor"; - public static final String URL_MONITOR_TASKSSTATUS = URL_MONITOR + "/tasks-status-report"; - public static final String URL_MONITOR_TASKSWORKBASKET = URL_MONITOR + "/tasks-workbasket-report"; - public static final String URL_MONITOR_TASKSWORKBASKETPLANNED = - URL_MONITOR + "/tasks-workbasket-planned-date-report"; - public static final String URL_MONITOR_TASKSCLASSIFICATION = URL_MONITOR + "/tasks-classification-report"; - public static final String URL_MONITOR_TIMESTAMP = URL_MONITOR + "/timestamp-report"; - - public static final String URL_DOMAIN = PRE + "domains"; - public static final String URL_CLASSIFICATIONCATEGORIES = PRE + "classification-categories"; - public static final String URL_CLASSIFICATIONTYPES = PRE + "classification-types"; - public static final String URL_CURRENTUSER = PRE + "current-user-info"; - public static final String URL_HISTORYENABLED = PRE + "history-provider-enabled"; - public static final String URL_VERSION = PRE + "version"; - - public static final String URL_TASKS = PRE + "tasks"; - public static final String URL_TASKS_ID = URL_TASKS + "/{taskId}"; - public static final String URL_TASKS_ID_CLAIM = URL_TASKS_ID + "/claim"; - public static final String URL_TASKS_ID_COMPLETE = URL_TASKS_ID + "/complete"; - public static final String URL_TASKS_ID_TRANSFER_WORKBASKETID = URL_TASKS_ID + "/transfer/{workbasketId}"; - - public static final String URL_WORKBASKETACCESSITEMS = PRE + "workbasket-access-items"; - - public static final String URL_WORKBASKET = PRE + "workbaskets"; - public static final String URL_WORKBASKET_ID = URL_WORKBASKET + "/{workbasketId}"; - public static final String URL_WORKBASKET_ID_ACCESSITEMS = URL_WORKBASKET_ID + "/workbasketAccessItems"; - public static final String URL_WORKBASKET_ID_DISTRIBUTION = URL_WORKBASKET_ID + "/distribution-targets"; - //TODO @Deprecated - public static final String URL_WORKBASKET_DISTRIBUTION_ID = URL_WORKBASKET + "/distribution-targets/{workbasketId}"; - - public static final String URL_WORKBASKETDEFIITIONS = PRE + "workbasket-definitions"; - - private Mapping() { - } + public static final String URL_ACCESSID = PRE + "access-ids"; + public static final String URL_ACCESSID_GROUPS = URL_ACCESSID + "/groups"; + public static final String URL_CLASSIFICATIONS = PRE + "classifications"; + public static final String URL_CLASSIFICATIONS_ID = URL_CLASSIFICATIONS + "/{classificationId}"; + public static final String URL_CLASSIFICATIONDEFINITION = PRE + "classification-definitions"; + public static final String URL_MONITOR = PRE + "monitor"; + public static final String URL_MONITOR_TASKSSTATUS = URL_MONITOR + "/tasks-status-report"; + public static final String URL_MONITOR_TASKSWORKBASKET = URL_MONITOR + "/tasks-workbasket-report"; + public static final String URL_MONITOR_TASKSWORKBASKETPLANNED = + URL_MONITOR + "/tasks-workbasket-planned-date-report"; + public static final String URL_MONITOR_TASKSCLASSIFICATION = + URL_MONITOR + "/tasks-classification-report"; + public static final String URL_MONITOR_TIMESTAMP = URL_MONITOR + "/timestamp-report"; + public static final String URL_DOMAIN = PRE + "domains"; + public static final String URL_CLASSIFICATIONCATEGORIES = PRE + "classification-categories"; + public static final String URL_CLASSIFICATIONTYPES = PRE + "classification-types"; + public static final String URL_CURRENTUSER = PRE + "current-user-info"; + public static final String URL_HISTORYENABLED = PRE + "history-provider-enabled"; + public static final String URL_VERSION = PRE + "version"; + public static final String URL_TASKS = PRE + "tasks"; + public static final String URL_TASKS_ID = URL_TASKS + "/{taskId}"; + public static final String URL_TASKS_ID_CLAIM = URL_TASKS_ID + "/claim"; + public static final String URL_TASKS_ID_COMPLETE = URL_TASKS_ID + "/complete"; + public static final String URL_TASKS_ID_TRANSFER_WORKBASKETID = + URL_TASKS_ID + "/transfer/{workbasketId}"; + public static final String URL_WORKBASKETACCESSITEMS = PRE + "workbasket-access-items"; + public static final String URL_WORKBASKET = PRE + "workbaskets"; + public static final String URL_WORKBASKET_ID = URL_WORKBASKET + "/{workbasketId}"; + public static final String URL_WORKBASKET_ID_ACCESSITEMS = + URL_WORKBASKET_ID + "/workbasketAccessItems"; + public static final String URL_WORKBASKET_ID_DISTRIBUTION = + URL_WORKBASKET_ID + "/distribution-targets"; + // TODO @Deprecated + public static final String URL_WORKBASKET_DISTRIBUTION_ID = + URL_WORKBASKET + "/distribution-targets/{workbasketId}"; + public static final String URL_WORKBASKETDEFIITIONS = PRE + "workbasket-definitions"; + private static final String PRE = "/api/v1/"; + private Mapping() {} } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/MonitorController.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/MonitorController.java index 6cc6d2e77..9c0167767 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/MonitorController.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/MonitorController.java @@ -5,7 +5,6 @@ import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.hateoas.config.EnableHypermediaSupport; @@ -24,135 +23,149 @@ import pro.taskana.impl.report.header.TimeIntervalColumnHeader; import pro.taskana.rest.resource.ReportResource; import pro.taskana.rest.resource.ReportResourceAssembler; -/** - * Controller for all monitoring endpoints. - */ +/** Controller for all monitoring endpoints. */ @RestController @EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL) public class MonitorController { - private static final Logger LOGGER = LoggerFactory.getLogger(MonitorController.class); + private static final Logger LOGGER = LoggerFactory.getLogger(MonitorController.class); - private TaskMonitorService taskMonitorService; + private TaskMonitorService taskMonitorService; - private ReportResourceAssembler reportResourceAssembler; + private ReportResourceAssembler reportResourceAssembler; - MonitorController(TaskMonitorService taskMonitorService, ReportResourceAssembler reportResourceAssembler) { - this.taskMonitorService = taskMonitorService; - this.reportResourceAssembler = reportResourceAssembler; + MonitorController( + TaskMonitorService taskMonitorService, ReportResourceAssembler reportResourceAssembler) { + this.taskMonitorService = taskMonitorService; + this.reportResourceAssembler = reportResourceAssembler; + } + + @GetMapping(path = Mapping.URL_MONITOR_TASKSSTATUS) + @Transactional(readOnly = true, rollbackFor = Exception.class) + public ResponseEntity getTasksStatusReport( + @RequestParam(required = false) List domains, + @RequestParam(required = false) List states) + throws NotAuthorizedException, InvalidArgumentException { + LOGGER.debug("Entry to getTasksStatusReport()"); + ResponseEntity response = + ResponseEntity.ok( + reportResourceAssembler.toResource( + taskMonitorService + .createTaskStatusReportBuilder() + .stateIn(states) + .domainIn(domains) + .buildReport(), + domains, + states)); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from getTasksStatusReport(), returning {}", response); } - @GetMapping(path = Mapping.URL_MONITOR_TASKSSTATUS) - @Transactional(readOnly = true, rollbackFor = Exception.class) - public ResponseEntity getTasksStatusReport(@RequestParam(required = false) List domains, - @RequestParam(required = false) List states) throws NotAuthorizedException, - InvalidArgumentException { - LOGGER.debug("Entry to getTasksStatusReport()"); - ResponseEntity response = ResponseEntity.ok(reportResourceAssembler.toResource( - taskMonitorService.createTaskStatusReportBuilder().stateIn(states).domainIn(domains).buildReport(), - domains, states)); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from getTasksStatusReport(), returning {}", response); - } + return response; + } - return response; - } + @GetMapping(path = Mapping.URL_MONITOR_TASKSWORKBASKET) + @Transactional(readOnly = true, rollbackFor = Exception.class) + public ResponseEntity getTasksWorkbasketReport( + @RequestParam(value = "states") List states) + throws NotAuthorizedException, InvalidArgumentException { + LOGGER.debug("Entry to getTasksWorkbasketReport()"); - @GetMapping(path = Mapping.URL_MONITOR_TASKSWORKBASKET) - @Transactional(readOnly = true, rollbackFor = Exception.class) - public ResponseEntity getTasksWorkbasketReport( - @RequestParam(value = "states") List states) - throws NotAuthorizedException, InvalidArgumentException { - LOGGER.debug("Entry to getTasksWorkbasketReport()"); - - ReportResource report = reportResourceAssembler.toResource( - taskMonitorService.createWorkbasketReportBuilder() + ReportResource report = + reportResourceAssembler.toResource( + taskMonitorService + .createWorkbasketReportBuilder() .withColumnHeaders(getRangeTimeInterval()) .buildReport(), states); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from getTasksWorkbasketReport(), returning {}", report); - } - - return ResponseEntity.status(HttpStatus.OK) - .body(report); - + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from getTasksWorkbasketReport(), returning {}", report); } - @GetMapping(path = Mapping.URL_MONITOR_TASKSWORKBASKETPLANNED) - @Transactional(readOnly = true, rollbackFor = Exception.class) - public ResponseEntity getTasksWorkbasketPlannedDateReport( - @RequestParam(value = "daysInPast") int daysInPast, - @RequestParam(value = "states") List states) - throws NotAuthorizedException, InvalidArgumentException { - LOGGER.debug("Entry to getTasksWorkbasketPlannedDateReport()"); + return ResponseEntity.status(HttpStatus.OK).body(report); + } - ReportResource report = reportResourceAssembler.toResource( - taskMonitorService.createWorkbasketReportBuilder() + @GetMapping(path = Mapping.URL_MONITOR_TASKSWORKBASKETPLANNED) + @Transactional(readOnly = true, rollbackFor = Exception.class) + public ResponseEntity getTasksWorkbasketPlannedDateReport( + @RequestParam(value = "daysInPast") int daysInPast, + @RequestParam(value = "states") List states) + throws NotAuthorizedException, InvalidArgumentException { + LOGGER.debug("Entry to getTasksWorkbasketPlannedDateReport()"); + + ReportResource report = + reportResourceAssembler.toResource( + taskMonitorService + .createWorkbasketReportBuilder() .stateIn(states) .withColumnHeaders(getDateTimeInterval(daysInPast)) .buildPlannedDateBasedReport(), - daysInPast, states); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from getTasksWorkbasketPlannedDateReport(), returning {}", report); - } - - return ResponseEntity.status(HttpStatus.OK) - .body(report); - + daysInPast, + states); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from getTasksWorkbasketPlannedDateReport(), returning {}", report); } - @GetMapping(path = Mapping.URL_MONITOR_TASKSCLASSIFICATION) - @Transactional(readOnly = true, rollbackFor = Exception.class) - public ResponseEntity getTasksClassificationReport() - throws NotAuthorizedException, InvalidArgumentException { - LOGGER.debug("Entry to getTasksClassificationReport()"); + return ResponseEntity.status(HttpStatus.OK).body(report); + } - ReportResource report = reportResourceAssembler.toResource( - taskMonitorService.createClassificationReportBuilder() + @GetMapping(path = Mapping.URL_MONITOR_TASKSCLASSIFICATION) + @Transactional(readOnly = true, rollbackFor = Exception.class) + public ResponseEntity getTasksClassificationReport() + throws NotAuthorizedException, InvalidArgumentException { + LOGGER.debug("Entry to getTasksClassificationReport()"); + + ReportResource report = + reportResourceAssembler.toResource( + taskMonitorService + .createClassificationReportBuilder() .withColumnHeaders(getRangeTimeInterval()) .buildReport()); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from getTasksClassificationReport(), returning {}", report); - } - - return ResponseEntity.status(HttpStatus.OK) - .body(report); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from getTasksClassificationReport(), returning {}", report); } - @GetMapping(path = Mapping.URL_MONITOR_TIMESTAMP) - @Transactional(readOnly = true, rollbackFor = Exception.class) - public ResponseEntity getDailyEntryExitReport() - throws NotAuthorizedException, InvalidArgumentException { - List columnHeaders = IntStream.range(-14, 0) + return ResponseEntity.status(HttpStatus.OK).body(report); + } + + @GetMapping(path = Mapping.URL_MONITOR_TIMESTAMP) + @Transactional(readOnly = true, rollbackFor = Exception.class) + public ResponseEntity getDailyEntryExitReport() + throws NotAuthorizedException, InvalidArgumentException { + List columnHeaders = + IntStream.range(-14, 0) .mapToObj(TimeIntervalColumnHeader.Date::new) .collect(Collectors.toList()); - return ResponseEntity.status(HttpStatus.OK) - .body(reportResourceAssembler.toResource( - taskMonitorService.createTimestampReportBuilder() + return ResponseEntity.status(HttpStatus.OK) + .body( + reportResourceAssembler.toResource( + taskMonitorService + .createTimestampReportBuilder() .withColumnHeaders(columnHeaders) .buildReport())); - } + } - private List getRangeTimeInterval() { - return Stream.concat(Stream.concat( - Stream.of(new TimeIntervalColumnHeader.Range(Integer.MIN_VALUE, -10), - new TimeIntervalColumnHeader.Range(-10, -5)), - Stream.of(-4, -3, -2, -1, 0, 1, 2, 3, 4) - .map(TimeIntervalColumnHeader.Range::new)), - Stream.of(new TimeIntervalColumnHeader.Range(5, 10), + private List getRangeTimeInterval() { + return Stream.concat( + Stream.concat( + Stream.of( + new TimeIntervalColumnHeader.Range(Integer.MIN_VALUE, -10), + new TimeIntervalColumnHeader.Range(-10, -5)), + Stream.of(-4, -3, -2, -1, 0, 1, 2, 3, 4).map(TimeIntervalColumnHeader.Range::new)), + Stream.of( + new TimeIntervalColumnHeader.Range(5, 10), new TimeIntervalColumnHeader.Range(10, Integer.MAX_VALUE))) - .collect(Collectors.toList()); - } + .collect(Collectors.toList()); + } - private List getDateTimeInterval(int daysInPast) { + private List getDateTimeInterval(int daysInPast) { - List columnHeaders = new ArrayList<>(); - for (int i = 0; i <= daysInPast; i++) { - columnHeaders.add(new TimeIntervalColumnHeader.Date(i - daysInPast)); - } - return columnHeaders; + List columnHeaders = new ArrayList<>(); + for (int i = 0; i <= daysInPast; i++) { + columnHeaders.add(new TimeIntervalColumnHeader.Date(i - daysInPast)); } + return columnHeaders; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/RestConfiguration.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/RestConfiguration.java index 37a2da4c1..e5ab393fe 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/RestConfiguration.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/RestConfiguration.java @@ -1,9 +1,8 @@ package pro.taskana.rest; +import com.fasterxml.jackson.databind.cfg.HandlerInstantiator; import java.sql.SQLException; - import javax.sql.DataSource; - import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.ApplicationContext; @@ -14,8 +13,6 @@ import org.springframework.context.annotation.Scope; import org.springframework.http.converter.json.SpringHandlerInstantiator; import org.springframework.transaction.annotation.EnableTransactionManagement; -import com.fasterxml.jackson.databind.cfg.HandlerInstantiator; - import pro.taskana.ClassificationService; import pro.taskana.TaskMonitorService; import pro.taskana.TaskService; @@ -25,58 +22,56 @@ import pro.taskana.configuration.SpringTaskanaEngineConfiguration; import pro.taskana.configuration.TaskanaEngineConfiguration; import pro.taskana.ldap.LdapClient; -/** - * Configuration for REST service. - */ +/** Configuration for REST service. */ @Configuration @ComponentScan @EnableTransactionManagement public class RestConfiguration { - @Value("${taskana.schemaName:TASKANA}") - private String schemaName; + @Value("${taskana.schemaName:TASKANA}") + private String schemaName; - @Bean - public ClassificationService getClassificationService(TaskanaEngine taskanaEngine) { - return taskanaEngine.getClassificationService(); - } + @Bean + public ClassificationService getClassificationService(TaskanaEngine taskanaEngine) { + return taskanaEngine.getClassificationService(); + } - @Bean - public TaskService getTaskService(TaskanaEngine taskanaEngine) { - return taskanaEngine.getTaskService(); - } + @Bean + public TaskService getTaskService(TaskanaEngine taskanaEngine) { + return taskanaEngine.getTaskService(); + } - @Bean - public TaskMonitorService getTaskMonitorService(TaskanaEngine taskanaEngine) { - return taskanaEngine.getTaskMonitorService(); - } + @Bean + public TaskMonitorService getTaskMonitorService(TaskanaEngine taskanaEngine) { + return taskanaEngine.getTaskMonitorService(); + } - @Bean - public WorkbasketService getWorkbasketService(TaskanaEngine taskanaEngine) { - return taskanaEngine.getWorkbasketService(); - } + @Bean + public WorkbasketService getWorkbasketService(TaskanaEngine taskanaEngine) { + return taskanaEngine.getWorkbasketService(); + } - @Bean - @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) - public TaskanaEngine getTaskanaEngine(TaskanaEngineConfiguration taskanaEngineConfiguration) { - return taskanaEngineConfiguration.buildTaskanaEngine(); - } + @Bean + @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) + public TaskanaEngine getTaskanaEngine(TaskanaEngineConfiguration taskanaEngineConfiguration) { + return taskanaEngineConfiguration.buildTaskanaEngine(); + } - @Bean - @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) - public TaskanaEngineConfiguration taskanaEngineConfiguration(DataSource dataSource) throws SQLException { - return new SpringTaskanaEngineConfiguration(dataSource, true, true, schemaName); - } + @Bean + @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) + public TaskanaEngineConfiguration taskanaEngineConfiguration(DataSource dataSource) + throws SQLException { + return new SpringTaskanaEngineConfiguration(dataSource, true, true, schemaName); + } - @Bean - public LdapClient ldapClient() { - return new LdapClient(); - } - - // Needed for injection into jackson deserializer. - @Bean - public HandlerInstantiator handlerInstantiator(ApplicationContext context) { - return new SpringHandlerInstantiator(context.getAutowireCapableBeanFactory()); - } + @Bean + public LdapClient ldapClient() { + return new LdapClient(); + } + // Needed for injection into jackson deserializer. + @Bean + public HandlerInstantiator handlerInstantiator(ApplicationContext context) { + return new SpringHandlerInstantiator(context.getAutowireCapableBeanFactory()); + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/TaskController.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/TaskController.java index 27db829d9..192390200 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/TaskController.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/TaskController.java @@ -2,7 +2,6 @@ package pro.taskana.rest; import java.util.ArrayList; import java.util.List; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.hateoas.config.EnableHypermediaSupport; @@ -44,386 +43,398 @@ import pro.taskana.rest.resource.TaskResourceAssembler; import pro.taskana.rest.resource.TaskSummaryListResource; import pro.taskana.rest.resource.TaskSummaryResourceAssembler; -/** - * Controller for all {@link Task} related endpoints. - */ +/** Controller for all {@link Task} related endpoints. */ @RestController @EnableHypermediaSupport(type = HypermediaType.HAL) public class TaskController extends AbstractPagingController { - private static final Logger LOGGER = LoggerFactory.getLogger(TaskController.class); + private static final Logger LOGGER = LoggerFactory.getLogger(TaskController.class); - private static final String LIKE = "%"; - private static final String STATE = "state"; - private static final String STATE_VALUE_CLAIMED = "CLAIMED"; - private static final String STATE_VALUE_COMPLETED = "COMPLETED"; - private static final String STATE_VALUE_READY = "READY"; - private static final String PRIORITY = "priority"; - private static final String NAME = "name"; - private static final String NAME_LIKE = "name-like"; - private static final String OWNER = "owner"; - private static final String OWNER_LIKE = "owner-like"; - private static final String DOMAIN = "domain"; - private static final String WORKBASKET_ID = "workbasket-id"; - private static final String WORKBASKET_KEY = "workbasket-key"; - private static final String CLASSIFICATION_KEY = "classification.key"; - private static final String POR_VALUE = "por.value"; - private static final String POR_TYPE = "por.type"; - private static final String POR_SYSTEM_INSTANCE = "por.instance"; - private static final String POR_SYSTEM = "por.system"; - private static final String POR_COMPANY = "por.company"; - private static final String DUE = "due"; - private static final String PLANNED = "planned"; + private static final String LIKE = "%"; + private static final String STATE = "state"; + private static final String STATE_VALUE_CLAIMED = "CLAIMED"; + private static final String STATE_VALUE_COMPLETED = "COMPLETED"; + private static final String STATE_VALUE_READY = "READY"; + private static final String PRIORITY = "priority"; + private static final String NAME = "name"; + private static final String NAME_LIKE = "name-like"; + private static final String OWNER = "owner"; + private static final String OWNER_LIKE = "owner-like"; + private static final String DOMAIN = "domain"; + private static final String WORKBASKET_ID = "workbasket-id"; + private static final String WORKBASKET_KEY = "workbasket-key"; + private static final String CLASSIFICATION_KEY = "classification.key"; + private static final String POR_VALUE = "por.value"; + private static final String POR_TYPE = "por.type"; + private static final String POR_SYSTEM_INSTANCE = "por.instance"; + private static final String POR_SYSTEM = "por.system"; + private static final String POR_COMPANY = "por.company"; + private static final String DUE = "due"; + private static final String PLANNED = "planned"; - private static final String SORT_BY = "sort-by"; - private static final String SORT_DIRECTION = "order"; + private static final String SORT_BY = "sort-by"; + private static final String SORT_DIRECTION = "order"; - private TaskService taskService; + private TaskService taskService; - private TaskResourceAssembler taskResourceAssembler; + private TaskResourceAssembler taskResourceAssembler; - private TaskSummaryResourceAssembler taskSummaryResourceAssembler; + private TaskSummaryResourceAssembler taskSummaryResourceAssembler; - TaskController( - TaskService taskService, - TaskResourceAssembler taskResourceAssembler, - TaskSummaryResourceAssembler taskSummaryResourceAssembler) { - this.taskService = taskService; - this.taskResourceAssembler = taskResourceAssembler; - this.taskSummaryResourceAssembler = taskSummaryResourceAssembler; + TaskController( + TaskService taskService, + TaskResourceAssembler taskResourceAssembler, + TaskSummaryResourceAssembler taskSummaryResourceAssembler) { + this.taskService = taskService; + this.taskResourceAssembler = taskResourceAssembler; + this.taskSummaryResourceAssembler = taskSummaryResourceAssembler; + } + + @GetMapping(path = Mapping.URL_TASKS) + @Transactional(readOnly = true, rollbackFor = Exception.class) + public ResponseEntity getTasks( + @RequestParam MultiValueMap params) throws InvalidArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Entry to getTasks(params= {})", params); } - @GetMapping(path = Mapping.URL_TASKS) - @Transactional(readOnly = true, rollbackFor = Exception.class) - public ResponseEntity getTasks( - @RequestParam MultiValueMap params) throws InvalidArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Entry to getTasks(params= {})", params); - } + TaskQuery query = taskService.createTaskQuery(); + query = applyFilterParams(query, params); + query = applySortingParams(query, params); - TaskQuery query = taskService.createTaskQuery(); - query = applyFilterParams(query, params); - query = applySortingParams(query, params); + PageMetadata pageMetadata = getPageMetadata(params, query); + List taskSummaries = getQueryList(query, pageMetadata); - PageMetadata pageMetadata = getPageMetadata(params, query); - List taskSummaries = getQueryList(query, pageMetadata); - - TaskSummaryListResource pagedResources = taskSummaryResourceAssembler.toResources(taskSummaries, - pageMetadata); - ResponseEntity response = ResponseEntity.ok(pagedResources); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from getTasks(), returning {}", response); - } - - return response; + TaskSummaryListResource pagedResources = + taskSummaryResourceAssembler.toResources(taskSummaries, pageMetadata); + ResponseEntity response = ResponseEntity.ok(pagedResources); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from getTasks(), returning {}", response); } - @GetMapping(path = Mapping.URL_TASKS_ID) - @Transactional(readOnly = true, rollbackFor = Exception.class) - public ResponseEntity getTask(@PathVariable String taskId) - throws TaskNotFoundException, NotAuthorizedException { - LOGGER.debug("Entry to getTask(taskId= {})", taskId); - Task task = taskService.getTask(taskId); - ResponseEntity result = ResponseEntity.ok(taskResourceAssembler.toResource(task)); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from getTask(), returning {}", result); - } + return response; + } - return result; + @GetMapping(path = Mapping.URL_TASKS_ID) + @Transactional(readOnly = true, rollbackFor = Exception.class) + public ResponseEntity getTask(@PathVariable String taskId) + throws TaskNotFoundException, NotAuthorizedException { + LOGGER.debug("Entry to getTask(taskId= {})", taskId); + Task task = taskService.getTask(taskId); + ResponseEntity result = ResponseEntity.ok(taskResourceAssembler.toResource(task)); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from getTask(), returning {}", result); } - @PostMapping(path = Mapping.URL_TASKS_ID_CLAIM) - @Transactional(rollbackFor = Exception.class) - public ResponseEntity claimTask(@PathVariable String taskId, @RequestBody String userName) - throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, NotAuthorizedException { - LOGGER.debug("Entry to claimTask(taskId= {}, userName= {})", taskId, userName); - // TODO verify user - taskService.claim(taskId); - Task updatedTask = taskService.getTask(taskId); - ResponseEntity result = ResponseEntity.ok(taskResourceAssembler.toResource(updatedTask)); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from claimTask(), returning {}", result); - } + return result; + } - return result; + @PostMapping(path = Mapping.URL_TASKS_ID_CLAIM) + @Transactional(rollbackFor = Exception.class) + public ResponseEntity claimTask( + @PathVariable String taskId, @RequestBody String userName) + throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, + NotAuthorizedException { + LOGGER.debug("Entry to claimTask(taskId= {}, userName= {})", taskId, userName); + // TODO verify user + taskService.claim(taskId); + Task updatedTask = taskService.getTask(taskId); + ResponseEntity result = + ResponseEntity.ok(taskResourceAssembler.toResource(updatedTask)); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from claimTask(), returning {}", result); } - @PostMapping(path = Mapping.URL_TASKS_ID_COMPLETE) - @Transactional(rollbackFor = Exception.class) - public ResponseEntity completeTask(@PathVariable String taskId) - throws TaskNotFoundException, InvalidOwnerException, InvalidStateException, NotAuthorizedException { - LOGGER.debug("Entry to completeTask(taskId= {})", taskId); - taskService.forceCompleteTask(taskId); - Task updatedTask = taskService.getTask(taskId); - ResponseEntity result = ResponseEntity.ok(taskResourceAssembler.toResource(updatedTask)); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from completeTask(), returning {}", result); - } + return result; + } - return result; + @PostMapping(path = Mapping.URL_TASKS_ID_COMPLETE) + @Transactional(rollbackFor = Exception.class) + public ResponseEntity completeTask(@PathVariable String taskId) + throws TaskNotFoundException, InvalidOwnerException, InvalidStateException, + NotAuthorizedException { + LOGGER.debug("Entry to completeTask(taskId= {})", taskId); + taskService.forceCompleteTask(taskId); + Task updatedTask = taskService.getTask(taskId); + ResponseEntity result = + ResponseEntity.ok(taskResourceAssembler.toResource(updatedTask)); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from completeTask(), returning {}", result); } - @DeleteMapping(path = Mapping.URL_TASKS_ID) - @Transactional(rollbackFor = Exception.class) - public ResponseEntity deleteTask(@PathVariable String taskId) - throws TaskNotFoundException, InvalidStateException, NotAuthorizedException { - LOGGER.debug("Entry to deleteTask(taskId= {})", taskId); - taskService.forceDeleteTask(taskId); - ResponseEntity result = ResponseEntity.noContent().build(); - LOGGER.debug("Exit from deleteTask(), returning {}", result); - return result; + return result; + } + + @DeleteMapping(path = Mapping.URL_TASKS_ID) + @Transactional(rollbackFor = Exception.class) + public ResponseEntity deleteTask(@PathVariable String taskId) + throws TaskNotFoundException, InvalidStateException, NotAuthorizedException { + LOGGER.debug("Entry to deleteTask(taskId= {})", taskId); + taskService.forceDeleteTask(taskId); + ResponseEntity result = ResponseEntity.noContent().build(); + LOGGER.debug("Exit from deleteTask(), returning {}", result); + return result; + } + + @PostMapping(path = Mapping.URL_TASKS) + @Transactional(rollbackFor = Exception.class) + public ResponseEntity createTask(@RequestBody TaskResource taskResource) + throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, + TaskAlreadyExistException, InvalidArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Entry to createTask(params= {})", taskResource); } - @PostMapping(path = Mapping.URL_TASKS) - @Transactional(rollbackFor = Exception.class) - public ResponseEntity createTask(@RequestBody TaskResource taskResource) - throws WorkbasketNotFoundException, ClassificationNotFoundException, NotAuthorizedException, - TaskAlreadyExistException, InvalidArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Entry to createTask(params= {})", taskResource); - } + Task fromResource = taskResourceAssembler.toModel(taskResource); + Task createdTask = taskService.createTask(fromResource); - Task fromResource = taskResourceAssembler.toModel(taskResource); - Task createdTask = taskService.createTask(fromResource); - - ResponseEntity result = ResponseEntity.status(HttpStatus.CREATED) + ResponseEntity result = + ResponseEntity.status(HttpStatus.CREATED) .body(taskResourceAssembler.toResource(createdTask)); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from createTask(), returning {}", result); - } - - return result; + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from createTask(), returning {}", result); } - @RequestMapping(path = Mapping.URL_TASKS_ID_TRANSFER_WORKBASKETID) - @Transactional(rollbackFor = Exception.class) - public ResponseEntity transferTask(@PathVariable String taskId, @PathVariable String workbasketId) - throws TaskNotFoundException, WorkbasketNotFoundException, NotAuthorizedException, InvalidStateException { - LOGGER.debug("Entry to transferTask(taskId= {}, workbasketId= {})", taskId, workbasketId); - Task updatedTask = taskService.transfer(taskId, workbasketId); - ResponseEntity result = ResponseEntity.ok(taskResourceAssembler.toResource(updatedTask)); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from transferTask(), returning {}", result); - } + return result; + } - return result; + @RequestMapping(path = Mapping.URL_TASKS_ID_TRANSFER_WORKBASKETID) + @Transactional(rollbackFor = Exception.class) + public ResponseEntity transferTask( + @PathVariable String taskId, @PathVariable String workbasketId) + throws TaskNotFoundException, WorkbasketNotFoundException, NotAuthorizedException, + InvalidStateException { + LOGGER.debug("Entry to transferTask(taskId= {}, workbasketId= {})", taskId, workbasketId); + Task updatedTask = taskService.transfer(taskId, workbasketId); + ResponseEntity result = + ResponseEntity.ok(taskResourceAssembler.toResource(updatedTask)); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from transferTask(), returning {}", result); } - @PutMapping(path = Mapping.URL_TASKS_ID) - @Transactional(rollbackFor = Exception.class) - public ResponseEntity updateTask( - @PathVariable(value = "taskId") String taskId, - @RequestBody TaskResource taskResource) - throws TaskNotFoundException, ClassificationNotFoundException, InvalidArgumentException, ConcurrencyException, - NotAuthorizedException, AttachmentPersistenceException { - LOGGER.debug("Entry to updateTask(taskId= {}, taskResource= {})", taskId, taskResource); - ResponseEntity result; - if (taskId.equals(taskResource.getTaskId())) { - Task task = taskResourceAssembler.toModel(taskResource); - task = taskService.updateTask(task); - result = ResponseEntity.ok(taskResourceAssembler.toResource(task)); - } else { - throw new InvalidArgumentException( - "TaskId ('" + taskId - + "') is not identical with the taskId of to object in the payload which should be updated. ID=('" - + taskResource.getTaskId() + "')"); - } + return result; + } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from updateTask(), returning {}", result); - } - - return result; + @PutMapping(path = Mapping.URL_TASKS_ID) + @Transactional(rollbackFor = Exception.class) + public ResponseEntity updateTask( + @PathVariable(value = "taskId") String taskId, @RequestBody TaskResource taskResource) + throws TaskNotFoundException, ClassificationNotFoundException, InvalidArgumentException, + ConcurrencyException, NotAuthorizedException, AttachmentPersistenceException { + LOGGER.debug("Entry to updateTask(taskId= {}, taskResource= {})", taskId, taskResource); + ResponseEntity result; + if (taskId.equals(taskResource.getTaskId())) { + Task task = taskResourceAssembler.toModel(taskResource); + task = taskService.updateTask(task); + result = ResponseEntity.ok(taskResourceAssembler.toResource(task)); + } else { + throw new InvalidArgumentException( + "TaskId ('" + + taskId + + "') is not identical with the taskId of to object in the payload which should be updated. ID=('" + + taskResource.getTaskId() + + "')"); } - private TaskQuery applyFilterParams(TaskQuery taskQuery, MultiValueMap params) - throws InvalidArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Entry to applyFilterParams(taskQuery= {}, params= {})", taskQuery, params); - } - - // apply filters - if (params.containsKey(NAME)) { - String[] names = extractCommaSeparatedFields(params.get(NAME)); - taskQuery.nameIn(names); - params.remove(NAME); - } - if (params.containsKey(NAME_LIKE)) { - taskQuery.nameLike(LIKE + params.get(NAME_LIKE).get(0) + LIKE); - params.remove(NAME_LIKE); - } - if (params.containsKey(PRIORITY)) { - String[] prioritiesInString = extractCommaSeparatedFields(params.get(PRIORITY)); - int[] priorities = extractPriorities(prioritiesInString); - taskQuery.priorityIn(priorities); - params.remove(PRIORITY); - } - if (params.containsKey(STATE)) { - TaskState[] states = extractStates(params); - taskQuery.stateIn(states); - params.remove(STATE); - } - if (params.containsKey(CLASSIFICATION_KEY)) { - String[] classificationKeys = extractCommaSeparatedFields(params.get(CLASSIFICATION_KEY)); - taskQuery.classificationKeyIn(classificationKeys); - params.remove(CLASSIFICATION_KEY); - } - if (params.containsKey(WORKBASKET_ID)) { - String[] workbaskets = extractCommaSeparatedFields(params.get(WORKBASKET_ID)); - taskQuery.workbasketIdIn(workbaskets); - params.remove(WORKBASKET_ID); - } - if (params.containsKey(WORKBASKET_KEY)) { - String[] domains = null; - if (params.get(DOMAIN) != null) { - domains = extractCommaSeparatedFields(params.get(DOMAIN)); - } - if (domains == null || domains.length != 1) { - throw new InvalidArgumentException("workbasket-key requires excactly one domain as second parameter."); - } - String[] workbasketKeys = extractCommaSeparatedFields(params.get(WORKBASKET_KEY)); - KeyDomain[] keyDomains = new KeyDomain[workbasketKeys.length]; - for (int i = 0; i < workbasketKeys.length; i++) { - keyDomains[i] = new KeyDomain(workbasketKeys[i], domains[0]); - } - taskQuery.workbasketKeyDomainIn(keyDomains); - params.remove(WORKBASKET_KEY); - params.remove(DOMAIN); - } - if (params.containsKey(OWNER)) { - String[] owners = extractCommaSeparatedFields(params.get(OWNER)); - taskQuery.ownerIn(owners); - params.remove(OWNER); - } - if (params.containsKey(OWNER_LIKE)) { - taskQuery.ownerLike(LIKE + params.get(OWNER_LIKE).get(0) + LIKE); - params.remove(OWNER_LIKE); - } - if (params.containsKey(POR_COMPANY)) { - String[] companies = extractCommaSeparatedFields(params.get(POR_COMPANY)); - taskQuery.primaryObjectReferenceCompanyIn(companies); - params.remove(POR_COMPANY); - } - if (params.containsKey(POR_SYSTEM)) { - String[] systems = extractCommaSeparatedFields(params.get(POR_SYSTEM)); - taskQuery.primaryObjectReferenceSystemIn(systems); - params.remove(POR_SYSTEM); - } - if (params.containsKey(POR_SYSTEM_INSTANCE)) { - String[] systemInstances = extractCommaSeparatedFields(params.get(POR_SYSTEM_INSTANCE)); - taskQuery.primaryObjectReferenceSystemInstanceIn(systemInstances); - params.remove(POR_SYSTEM_INSTANCE); - } - if (params.containsKey(POR_TYPE)) { - taskQuery.primaryObjectReferenceTypeLike(LIKE + params.get(POR_TYPE).get(0) + LIKE); - params.remove(POR_TYPE); - } - if (params.containsKey(POR_VALUE)) { - taskQuery.primaryObjectReferenceValueLike(LIKE + params.get(POR_VALUE).get(0) + LIKE); - params.remove(POR_VALUE); - } - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from applyFilterParams(), returning {}", taskQuery); - } - - return taskQuery; + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from updateTask(), returning {}", result); } - private TaskQuery applySortingParams(TaskQuery taskQuery, MultiValueMap params) - throws InvalidArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Entry to applySortingParams(taskQuery= {}, params= {})", taskQuery, params); - } + return result; + } - // sorting - String sortBy = params.getFirst(SORT_BY); - if (sortBy != null) { - SortDirection sortDirection; - if (params.getFirst(SORT_DIRECTION) != null && "desc".equals(params.getFirst(SORT_DIRECTION))) { - sortDirection = SortDirection.DESCENDING; - } else { - sortDirection = SortDirection.ASCENDING; - } - switch (sortBy) { - case (CLASSIFICATION_KEY): - taskQuery = taskQuery.orderByClassificationKey(sortDirection); - break; - case (POR_TYPE): - taskQuery = taskQuery.orderByPrimaryObjectReferenceType(sortDirection); - break; - case (POR_VALUE): - taskQuery = taskQuery.orderByPrimaryObjectReferenceValue(sortDirection); - break; - case (STATE): - taskQuery = taskQuery.orderByState(sortDirection); - break; - case (NAME): - taskQuery = taskQuery.orderByName(sortDirection); - break; - case (DUE): - taskQuery = taskQuery.orderByDue(sortDirection); - break; - case (PLANNED): - taskQuery = taskQuery.orderByPlanned(sortDirection); - break; - case (PRIORITY): - taskQuery = taskQuery.orderByPriority(sortDirection); - break; - default: - throw new InvalidArgumentException("Unknown filter attribute: " + sortBy); - } - } - params.remove(SORT_BY); - params.remove(SORT_DIRECTION); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from applySortingParams(), returning {}", taskQuery); - } - - return taskQuery; + private TaskQuery applyFilterParams(TaskQuery taskQuery, MultiValueMap params) + throws InvalidArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Entry to applyFilterParams(taskQuery= {}, params= {})", taskQuery, params); } - private int[] extractPriorities(String[] prioritiesInString) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Entry to extractPriorities(prioritiesInString= {})", (Object[]) prioritiesInString); - } - - int[] priorities = new int[prioritiesInString.length]; - for (int i = 0; i < prioritiesInString.length; i++) { - priorities[i] = Integer.parseInt(prioritiesInString[i]); - } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from extractPriorities(), returning {}", priorities); - } - - return priorities; + // apply filters + if (params.containsKey(NAME)) { + String[] names = extractCommaSeparatedFields(params.get(NAME)); + taskQuery.nameIn(names); + params.remove(NAME); + } + if (params.containsKey(NAME_LIKE)) { + taskQuery.nameLike(LIKE + params.get(NAME_LIKE).get(0) + LIKE); + params.remove(NAME_LIKE); + } + if (params.containsKey(PRIORITY)) { + String[] prioritiesInString = extractCommaSeparatedFields(params.get(PRIORITY)); + int[] priorities = extractPriorities(prioritiesInString); + taskQuery.priorityIn(priorities); + params.remove(PRIORITY); + } + if (params.containsKey(STATE)) { + TaskState[] states = extractStates(params); + taskQuery.stateIn(states); + params.remove(STATE); + } + if (params.containsKey(CLASSIFICATION_KEY)) { + String[] classificationKeys = extractCommaSeparatedFields(params.get(CLASSIFICATION_KEY)); + taskQuery.classificationKeyIn(classificationKeys); + params.remove(CLASSIFICATION_KEY); + } + if (params.containsKey(WORKBASKET_ID)) { + String[] workbaskets = extractCommaSeparatedFields(params.get(WORKBASKET_ID)); + taskQuery.workbasketIdIn(workbaskets); + params.remove(WORKBASKET_ID); + } + if (params.containsKey(WORKBASKET_KEY)) { + String[] domains = null; + if (params.get(DOMAIN) != null) { + domains = extractCommaSeparatedFields(params.get(DOMAIN)); + } + if (domains == null || domains.length != 1) { + throw new InvalidArgumentException( + "workbasket-key requires excactly one domain as second parameter."); + } + String[] workbasketKeys = extractCommaSeparatedFields(params.get(WORKBASKET_KEY)); + KeyDomain[] keyDomains = new KeyDomain[workbasketKeys.length]; + for (int i = 0; i < workbasketKeys.length; i++) { + keyDomains[i] = new KeyDomain(workbasketKeys[i], domains[0]); + } + taskQuery.workbasketKeyDomainIn(keyDomains); + params.remove(WORKBASKET_KEY); + params.remove(DOMAIN); + } + if (params.containsKey(OWNER)) { + String[] owners = extractCommaSeparatedFields(params.get(OWNER)); + taskQuery.ownerIn(owners); + params.remove(OWNER); + } + if (params.containsKey(OWNER_LIKE)) { + taskQuery.ownerLike(LIKE + params.get(OWNER_LIKE).get(0) + LIKE); + params.remove(OWNER_LIKE); + } + if (params.containsKey(POR_COMPANY)) { + String[] companies = extractCommaSeparatedFields(params.get(POR_COMPANY)); + taskQuery.primaryObjectReferenceCompanyIn(companies); + params.remove(POR_COMPANY); + } + if (params.containsKey(POR_SYSTEM)) { + String[] systems = extractCommaSeparatedFields(params.get(POR_SYSTEM)); + taskQuery.primaryObjectReferenceSystemIn(systems); + params.remove(POR_SYSTEM); + } + if (params.containsKey(POR_SYSTEM_INSTANCE)) { + String[] systemInstances = extractCommaSeparatedFields(params.get(POR_SYSTEM_INSTANCE)); + taskQuery.primaryObjectReferenceSystemInstanceIn(systemInstances); + params.remove(POR_SYSTEM_INSTANCE); + } + if (params.containsKey(POR_TYPE)) { + taskQuery.primaryObjectReferenceTypeLike(LIKE + params.get(POR_TYPE).get(0) + LIKE); + params.remove(POR_TYPE); + } + if (params.containsKey(POR_VALUE)) { + taskQuery.primaryObjectReferenceValueLike(LIKE + params.get(POR_VALUE).get(0) + LIKE); + params.remove(POR_VALUE); } - private TaskState[] extractStates(MultiValueMap params) throws InvalidArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Entry to extractStates(params= {})", params); - } - - List states = new ArrayList<>(); - for (String item : params.get(STATE)) { - for (String state : item.split(",")) { - switch (state) { - case STATE_VALUE_READY: - states.add(TaskState.READY); - break; - case STATE_VALUE_COMPLETED: - states.add(TaskState.COMPLETED); - break; - case STATE_VALUE_CLAIMED: - states.add(TaskState.CLAIMED); - break; - default: - throw new InvalidArgumentException("Unknown status '" + state + "'"); - } - } - } - - LOGGER.debug("Exit from extractStates()"); - return states.toArray(new TaskState[0]); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from applyFilterParams(), returning {}", taskQuery); } + + return taskQuery; + } + + private TaskQuery applySortingParams(TaskQuery taskQuery, MultiValueMap params) + throws InvalidArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Entry to applySortingParams(taskQuery= {}, params= {})", taskQuery, params); + } + + // sorting + String sortBy = params.getFirst(SORT_BY); + if (sortBy != null) { + SortDirection sortDirection; + if (params.getFirst(SORT_DIRECTION) != null + && "desc".equals(params.getFirst(SORT_DIRECTION))) { + sortDirection = SortDirection.DESCENDING; + } else { + sortDirection = SortDirection.ASCENDING; + } + switch (sortBy) { + case (CLASSIFICATION_KEY): + taskQuery = taskQuery.orderByClassificationKey(sortDirection); + break; + case (POR_TYPE): + taskQuery = taskQuery.orderByPrimaryObjectReferenceType(sortDirection); + break; + case (POR_VALUE): + taskQuery = taskQuery.orderByPrimaryObjectReferenceValue(sortDirection); + break; + case (STATE): + taskQuery = taskQuery.orderByState(sortDirection); + break; + case (NAME): + taskQuery = taskQuery.orderByName(sortDirection); + break; + case (DUE): + taskQuery = taskQuery.orderByDue(sortDirection); + break; + case (PLANNED): + taskQuery = taskQuery.orderByPlanned(sortDirection); + break; + case (PRIORITY): + taskQuery = taskQuery.orderByPriority(sortDirection); + break; + default: + throw new InvalidArgumentException("Unknown filter attribute: " + sortBy); + } + } + params.remove(SORT_BY); + params.remove(SORT_DIRECTION); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from applySortingParams(), returning {}", taskQuery); + } + + return taskQuery; + } + + private int[] extractPriorities(String[] prioritiesInString) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "Entry to extractPriorities(prioritiesInString= {})", (Object[]) prioritiesInString); + } + + int[] priorities = new int[prioritiesInString.length]; + for (int i = 0; i < prioritiesInString.length; i++) { + priorities[i] = Integer.parseInt(prioritiesInString[i]); + } + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from extractPriorities(), returning {}", priorities); + } + + return priorities; + } + + private TaskState[] extractStates(MultiValueMap params) + throws InvalidArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Entry to extractStates(params= {})", params); + } + + List states = new ArrayList<>(); + for (String item : params.get(STATE)) { + for (String state : item.split(",")) { + switch (state) { + case STATE_VALUE_READY: + states.add(TaskState.READY); + break; + case STATE_VALUE_COMPLETED: + states.add(TaskState.COMPLETED); + break; + case STATE_VALUE_CLAIMED: + states.add(TaskState.CLAIMED); + break; + default: + throw new InvalidArgumentException("Unknown status '" + state + "'"); + } + } + } + + LOGGER.debug("Exit from extractStates()"); + return states.toArray(new TaskState[0]); + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/TaskanaEngineController.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/TaskanaEngineController.java index e5ffee294..78c88b5b6 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/TaskanaEngineController.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/TaskanaEngineController.java @@ -1,7 +1,6 @@ package pro.taskana.rest; import java.util.List; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -17,101 +16,103 @@ import pro.taskana.rest.resource.TaskanaUserInfoResource; import pro.taskana.rest.resource.VersionResource; import pro.taskana.security.CurrentUserContext; -/** - * Controller for TaskanaEngine related tasks. - */ +/** Controller for TaskanaEngine related tasks. */ @RestController @EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL) public class TaskanaEngineController { - private static final Logger LOGGER = LoggerFactory.getLogger(TaskanaEngineController.class); + private static final Logger LOGGER = LoggerFactory.getLogger(TaskanaEngineController.class); - private TaskanaEngineConfiguration taskanaEngineConfiguration; + private TaskanaEngineConfiguration taskanaEngineConfiguration; - private TaskanaEngine taskanaEngine; - @Value("${version:Local build}") - private String version; + private TaskanaEngine taskanaEngine; - TaskanaEngineController(TaskanaEngineConfiguration taskanaEngineConfiguration, TaskanaEngine taskanaEngine) { - this.taskanaEngineConfiguration = taskanaEngineConfiguration; - this.taskanaEngine = taskanaEngine; + @Value("${version:Local build}") + private String version; + + TaskanaEngineController( + TaskanaEngineConfiguration taskanaEngineConfiguration, TaskanaEngine taskanaEngine) { + this.taskanaEngineConfiguration = taskanaEngineConfiguration; + this.taskanaEngine = taskanaEngine; + } + + @GetMapping(path = Mapping.URL_DOMAIN) + public ResponseEntity> getDomains() { + ResponseEntity> response = + ResponseEntity.ok(taskanaEngineConfiguration.getDomains()); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from getDomains(), returning {}", response); + } + return response; + } + + @GetMapping(path = Mapping.URL_CLASSIFICATIONCATEGORIES) + public ResponseEntity> getClassificationCategories(String type) { + LOGGER.debug("Entry to getClassificationCategories(type = {})", type); + ResponseEntity> response; + if (type != null) { + response = + ResponseEntity.ok(taskanaEngineConfiguration.getClassificationCategoriesByType(type)); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from getClassificationCategories(), returning {}", response); + } + return response; + } + response = ResponseEntity.ok(taskanaEngineConfiguration.getAllClassificationCategories()); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from getClassificationCategories(), returning {}", response); + } + return response; + } + + @GetMapping(path = Mapping.URL_CLASSIFICATIONTYPES) + public ResponseEntity> getClassificationTypes() { + ResponseEntity> response = + ResponseEntity.ok(taskanaEngineConfiguration.getClassificationTypes()); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from getClassificationTypes(), returning {}", response); + } + return response; + } + + @GetMapping(path = Mapping.URL_CURRENTUSER) + public ResponseEntity getCurrentUserInfo() { + LOGGER.debug("Entry to getCurrentUserInfo()"); + TaskanaUserInfoResource resource = new TaskanaUserInfoResource(); + resource.setUserId(CurrentUserContext.getUserid()); + resource.setGroupIds(CurrentUserContext.getGroupIds()); + for (TaskanaRole role : taskanaEngineConfiguration.getRoleMap().keySet()) { + if (taskanaEngine.isUserInRole(role)) { + resource.getRoles().add(role); + } + } + ResponseEntity response = ResponseEntity.ok(resource); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from getCurrentUserInfo(), returning {}", response); } - @GetMapping(path = Mapping.URL_DOMAIN) - public ResponseEntity> getDomains() { - ResponseEntity> response = ResponseEntity.ok(taskanaEngineConfiguration.getDomains()); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from getDomains(), returning {}", response); - } - return response; - } + return response; + } - @GetMapping(path = Mapping.URL_CLASSIFICATIONCATEGORIES) - public ResponseEntity> getClassificationCategories(String type) { - LOGGER.debug("Entry to getClassificationCategories(type = {})", type); - ResponseEntity> response; - if (type != null) { - response = ResponseEntity.ok(taskanaEngineConfiguration.getClassificationCategoriesByType(type)); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from getClassificationCategories(), returning {}", response); - } - return response; - } - response = ResponseEntity.ok(taskanaEngineConfiguration.getAllClassificationCategories()); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from getClassificationCategories(), returning {}", response); - } - return response; - } + @GetMapping(path = Mapping.URL_HISTORYENABLED) + public ResponseEntity getIsHistoryProviderEnabled() { + ResponseEntity response = ResponseEntity.ok(taskanaEngine.isHistoryEnabled()); + LOGGER.debug("Exit from getIsHistoryProviderEnabled(), returning {}", response); + return response; + } - @GetMapping(path = Mapping.URL_CLASSIFICATIONTYPES) - public ResponseEntity> getClassificationTypes() { - ResponseEntity> response = ResponseEntity.ok( - taskanaEngineConfiguration.getClassificationTypes()); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from getClassificationTypes(), returning {}", response); - } - return response; - } - - @GetMapping(path = Mapping.URL_CURRENTUSER) - public ResponseEntity getCurrentUserInfo() { - LOGGER.debug("Entry to getCurrentUserInfo()"); - TaskanaUserInfoResource resource = new TaskanaUserInfoResource(); - resource.setUserId(CurrentUserContext.getUserid()); - resource.setGroupIds(CurrentUserContext.getGroupIds()); - for (TaskanaRole role : taskanaEngineConfiguration.getRoleMap().keySet()) { - if (taskanaEngine.isUserInRole(role)) { - resource.getRoles().add(role); - } - } - ResponseEntity response = ResponseEntity.ok(resource); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from getCurrentUserInfo(), returning {}", response); - } - - return response; - } - - @GetMapping(path = Mapping.URL_HISTORYENABLED) - public ResponseEntity getIsHistoryProviderEnabled() { - ResponseEntity response = ResponseEntity.ok(taskanaEngine.isHistoryEnabled()); - LOGGER.debug("Exit from getIsHistoryProviderEnabled(), returning {}", response); - return response; - } - - /** - * Get the current application version. - * - * @return The current version. - */ - @GetMapping(path = Mapping.URL_VERSION) - public ResponseEntity currentVersion() { - LOGGER.debug("Entry to currentVersion()"); - VersionResource resource = new VersionResource(); - resource.setVersion(TaskanaEngineConfiguration.class.getPackage().getImplementationVersion()); - ResponseEntity response = ResponseEntity.ok(resource); - LOGGER.debug("Exit from currentVersion(), returning {}", response); - return response; - } + /** + * Get the current application version. + * + * @return The current version. + */ + @GetMapping(path = Mapping.URL_VERSION) + public ResponseEntity currentVersion() { + LOGGER.debug("Entry to currentVersion()"); + VersionResource resource = new VersionResource(); + resource.setVersion(TaskanaEngineConfiguration.class.getPackage().getImplementationVersion()); + ResponseEntity response = ResponseEntity.ok(resource); + LOGGER.debug("Exit from currentVersion(), returning {}", response); + return response; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/TaskanaErrorData.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/TaskanaErrorData.java index 105b3ef19..a11530ba3 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/TaskanaErrorData.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/TaskanaErrorData.java @@ -1,7 +1,6 @@ package pro.taskana.rest; import java.util.Date; - import org.springframework.http.HttpStatus; import org.springframework.web.context.request.WebRequest; @@ -12,53 +11,63 @@ import org.springframework.web.context.request.WebRequest; */ public class TaskanaErrorData { - private Date timestamp; - private int status; - private String error; - private String exception; - private String message; - private String path; + private Date timestamp; + private int status; + private String error; + private String exception; + private String message; + private String path; - TaskanaErrorData(HttpStatus stat, Exception ex, WebRequest req) { - this.timestamp = new Date(); - this.status = stat.value(); - this.error = stat.name(); - this.exception = ex.getClass().getName(); - this.message = ex.getMessage(); - this.path = req.getDescription(false); - if (this.path != null && this.path.startsWith("uri=")) { - this.path = this.path.substring(4); - } + TaskanaErrorData(HttpStatus stat, Exception ex, WebRequest req) { + this.timestamp = new Date(); + this.status = stat.value(); + this.error = stat.name(); + this.exception = ex.getClass().getName(); + this.message = ex.getMessage(); + this.path = req.getDescription(false); + if (this.path != null && this.path.startsWith("uri=")) { + this.path = this.path.substring(4); } + } - public Date getTimestamp() { - return timestamp; - } + public Date getTimestamp() { + return timestamp; + } - public int getStatus() { - return status; - } + public int getStatus() { + return status; + } - public String getError() { - return error; - } + public String getError() { + return error; + } - public String getException() { - return exception; - } + public String getException() { + return exception; + } - public String getMessage() { - return message; - } + public String getMessage() { + return message; + } - public String getPath() { - return path; - } - - @Override - public String toString() { - return "TaskanaErrorData [timestamp=" + timestamp + ", status=" + status + ", error=" + error + ", exception=" - + exception + ", message=" + message + ", path=" + path + "]"; - } + public String getPath() { + return path; + } + @Override + public String toString() { + return "TaskanaErrorData [timestamp=" + + timestamp + + ", status=" + + status + + ", error=" + + error + + ", exception=" + + exception + + ", message=" + + message + + ", path=" + + path + + "]"; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/TaskanaRestExceptionHandler.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/TaskanaRestExceptionHandler.java index eabff2a80..406edaf62 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/TaskanaRestExceptionHandler.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/TaskanaRestExceptionHandler.java @@ -38,110 +38,118 @@ import pro.taskana.exceptions.WorkbasketNotFoundException; @ControllerAdvice public class TaskanaRestExceptionHandler extends ResponseEntityExceptionHandler { - private static final Logger LOGGER = LoggerFactory.getLogger(TaskanaRestExceptionHandler.class); + private static final Logger LOGGER = LoggerFactory.getLogger(TaskanaRestExceptionHandler.class); - @ExceptionHandler(InvalidArgumentException.class) - protected ResponseEntity handleInvalidArgument(InvalidArgumentException ex, WebRequest req) { - return buildResponse(ex, req, HttpStatus.BAD_REQUEST); - } + @ExceptionHandler(InvalidArgumentException.class) + protected ResponseEntity handleInvalidArgument( + InvalidArgumentException ex, WebRequest req) { + return buildResponse(ex, req, HttpStatus.BAD_REQUEST); + } - @ExceptionHandler(NotAuthorizedException.class) - protected ResponseEntity handleNotAuthorized(NotAuthorizedException ex, WebRequest req) { - return buildResponse(ex, req, HttpStatus.FORBIDDEN); - } + @ExceptionHandler(NotAuthorizedException.class) + protected ResponseEntity handleNotAuthorized(NotAuthorizedException ex, WebRequest req) { + return buildResponse(ex, req, HttpStatus.FORBIDDEN); + } - @ExceptionHandler(TaskNotFoundException.class) - protected ResponseEntity handleTaskNotFound(TaskNotFoundException ex, WebRequest req) { - return buildResponse(ex, req, HttpStatus.NOT_FOUND); - } + @ExceptionHandler(TaskNotFoundException.class) + protected ResponseEntity handleTaskNotFound(TaskNotFoundException ex, WebRequest req) { + return buildResponse(ex, req, HttpStatus.NOT_FOUND); + } - @ExceptionHandler(TaskAlreadyExistException.class) - protected ResponseEntity handleTaskAlreadyExist(TaskAlreadyExistException ex, - WebRequest req) { - return buildResponse(ex, req, HttpStatus.CONFLICT); - } + @ExceptionHandler(TaskAlreadyExistException.class) + protected ResponseEntity handleTaskAlreadyExist( + TaskAlreadyExistException ex, WebRequest req) { + return buildResponse(ex, req, HttpStatus.CONFLICT); + } - @ExceptionHandler(NotAuthorizedToQueryWorkbasketException.class) - protected ResponseEntity handleNotAuthorizedToQueryWorkbasket(NotAuthorizedToQueryWorkbasketException ex, - WebRequest req) { - return buildResponse(ex, req, HttpStatus.FORBIDDEN); - } + @ExceptionHandler(NotAuthorizedToQueryWorkbasketException.class) + protected ResponseEntity handleNotAuthorizedToQueryWorkbasket( + NotAuthorizedToQueryWorkbasketException ex, WebRequest req) { + return buildResponse(ex, req, HttpStatus.FORBIDDEN); + } - @ExceptionHandler(InvalidStateException.class) - protected ResponseEntity handleInvalidState(InvalidStateException ex, WebRequest req) { - return buildResponse(ex, req, HttpStatus.CONFLICT); - } + @ExceptionHandler(InvalidStateException.class) + protected ResponseEntity handleInvalidState(InvalidStateException ex, WebRequest req) { + return buildResponse(ex, req, HttpStatus.CONFLICT); + } - @ExceptionHandler(InvalidOwnerException.class) - protected ResponseEntity handleInvalidOwner(InvalidOwnerException ex, WebRequest req) { - return buildResponse(ex, req, HttpStatus.CONFLICT); - } + @ExceptionHandler(InvalidOwnerException.class) + protected ResponseEntity handleInvalidOwner(InvalidOwnerException ex, WebRequest req) { + return buildResponse(ex, req, HttpStatus.CONFLICT); + } - @ExceptionHandler(ClassificationNotFoundException.class) - protected ResponseEntity handleClassificationNotFound(ClassificationNotFoundException ex, WebRequest req) { - return buildResponse(ex, req, HttpStatus.NOT_FOUND); - } + @ExceptionHandler(ClassificationNotFoundException.class) + protected ResponseEntity handleClassificationNotFound( + ClassificationNotFoundException ex, WebRequest req) { + return buildResponse(ex, req, HttpStatus.NOT_FOUND); + } - @ExceptionHandler(ClassificationAlreadyExistException.class) - protected ResponseEntity handleClassificationAlreadyExist(ClassificationAlreadyExistException ex, - WebRequest req) { - return buildResponse(ex, req, HttpStatus.CONFLICT); - } + @ExceptionHandler(ClassificationAlreadyExistException.class) + protected ResponseEntity handleClassificationAlreadyExist( + ClassificationAlreadyExistException ex, WebRequest req) { + return buildResponse(ex, req, HttpStatus.CONFLICT); + } - @ExceptionHandler(DuplicateKeyException.class) - protected ResponseEntity handleDuplicateKey(DuplicateKeyException ex, WebRequest req) { - return buildResponse(ex, req, HttpStatus.CONFLICT); - } + @ExceptionHandler(DuplicateKeyException.class) + protected ResponseEntity handleDuplicateKey(DuplicateKeyException ex, WebRequest req) { + return buildResponse(ex, req, HttpStatus.CONFLICT); + } - @ExceptionHandler(ConcurrencyException.class) - protected ResponseEntity handleConcurrencyException(ConcurrencyException ex, WebRequest req) { - return buildResponse(ex, req, HttpStatus.LOCKED); - } + @ExceptionHandler(ConcurrencyException.class) + protected ResponseEntity handleConcurrencyException( + ConcurrencyException ex, WebRequest req) { + return buildResponse(ex, req, HttpStatus.LOCKED); + } - @ExceptionHandler(WorkbasketInUseException.class) - protected ResponseEntity handleWorkbasketInUse(WorkbasketInUseException ex, WebRequest req) { - return buildResponse(ex, req, HttpStatus.LOCKED); - } + @ExceptionHandler(WorkbasketInUseException.class) + protected ResponseEntity handleWorkbasketInUse( + WorkbasketInUseException ex, WebRequest req) { + return buildResponse(ex, req, HttpStatus.LOCKED); + } - @ExceptionHandler(WorkbasketAlreadyExistException.class) - protected ResponseEntity handleWorkbasketAlreadyExist(WorkbasketAlreadyExistException ex, WebRequest req) { - return buildResponse(ex, req, HttpStatus.CONFLICT); - } + @ExceptionHandler(WorkbasketAlreadyExistException.class) + protected ResponseEntity handleWorkbasketAlreadyExist( + WorkbasketAlreadyExistException ex, WebRequest req) { + return buildResponse(ex, req, HttpStatus.CONFLICT); + } - @ExceptionHandler(WorkbasketNotFoundException.class) - protected ResponseEntity handleWorkbasketNotFound(WorkbasketNotFoundException ex, WebRequest req) { - return buildResponse(ex, req, HttpStatus.NOT_FOUND); - } + @ExceptionHandler(WorkbasketNotFoundException.class) + protected ResponseEntity handleWorkbasketNotFound( + WorkbasketNotFoundException ex, WebRequest req) { + return buildResponse(ex, req, HttpStatus.NOT_FOUND); + } - @ExceptionHandler(InvalidWorkbasketException.class) - protected ResponseEntity handleInvalidWorkbasket(InvalidWorkbasketException ex, WebRequest req) { - return buildResponse(ex, req, HttpStatus.BAD_REQUEST); - } + @ExceptionHandler(InvalidWorkbasketException.class) + protected ResponseEntity handleInvalidWorkbasket( + InvalidWorkbasketException ex, WebRequest req) { + return buildResponse(ex, req, HttpStatus.BAD_REQUEST); + } - @ExceptionHandler(DomainNotFoundException.class) - protected ResponseEntity handleDomainNotFound(DomainNotFoundException ex, WebRequest req) { - return buildResponse(ex, req, HttpStatus.BAD_REQUEST); - } + @ExceptionHandler(DomainNotFoundException.class) + protected ResponseEntity handleDomainNotFound( + DomainNotFoundException ex, WebRequest req) { + return buildResponse(ex, req, HttpStatus.BAD_REQUEST); + } - @ExceptionHandler(MaxUploadSizeExceededException.class) - protected ResponseEntity handleMaxUploadSizeExceededException(MaxUploadSizeExceededException ex, - WebRequest req) { - return buildResponse(ex, req, HttpStatus.PAYLOAD_TOO_LARGE); - } + @ExceptionHandler(MaxUploadSizeExceededException.class) + protected ResponseEntity handleMaxUploadSizeExceededException( + MaxUploadSizeExceededException ex, WebRequest req) { + return buildResponse(ex, req, HttpStatus.PAYLOAD_TOO_LARGE); + } - @ExceptionHandler(Exception.class) - protected ResponseEntity handleGeneralException(Exception ex, WebRequest req) { - return buildResponse(ex, req, HttpStatus.BAD_REQUEST); - } + @ExceptionHandler(Exception.class) + protected ResponseEntity handleGeneralException(Exception ex, WebRequest req) { + return buildResponse(ex, req, HttpStatus.BAD_REQUEST); + } - private ResponseEntity buildResponse(Exception ex, WebRequest req, HttpStatus status) { - TaskanaErrorData errorData = new TaskanaErrorData(status, ex, req); - logError(ex, errorData); - return ResponseEntity.status(status).body(errorData); - } - - private void logError(Exception ex, TaskanaErrorData errorData) { - LOGGER.error("Error occurred during processing of rest request:\n {}" + errorData.toString(), ex); - } + private ResponseEntity buildResponse(Exception ex, WebRequest req, HttpStatus status) { + TaskanaErrorData errorData = new TaskanaErrorData(status, ex, req); + logError(ex, errorData); + return ResponseEntity.status(status).body(errorData); + } + private void logError(Exception ex, TaskanaErrorData errorData) { + LOGGER.error( + "Error occurred during processing of rest request:\n {}" + errorData.toString(), ex); + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/WorkbasketAccessItemController.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/WorkbasketAccessItemController.java index b1047420c..9964140bc 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/WorkbasketAccessItemController.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/WorkbasketAccessItemController.java @@ -3,7 +3,6 @@ package pro.taskana.rest; import java.util.ArrayList; import java.util.Collections; import java.util.List; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -26,199 +25,189 @@ import pro.taskana.rest.resource.PagedResources.PageMetadata; import pro.taskana.rest.resource.WorkbasketAccessItemPaginatedListResource; import pro.taskana.rest.resource.WorkbasketAccessItemResourceAssembler; -/** - * Controller for Workbasket access. - */ +/** Controller for Workbasket access. */ @RestController @EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL) public class WorkbasketAccessItemController extends AbstractPagingController { - private static final Logger LOGGER = LoggerFactory.getLogger(WorkbasketAccessItemController.class); + private static final Logger LOGGER = + LoggerFactory.getLogger(WorkbasketAccessItemController.class); - private static final String LIKE = "%"; - private static final String WORKBASKET_KEY = "workbasket-key"; - private static final String WORKBASKET_KEY_LIKE = "workbasket-key-like"; - private static final String ACCESS_ID = "access-id"; - private static final String ACCESS_ID_LIKE = "access-id-like"; - private static final String ACCESS_IDS = "access-ids"; + private static final String LIKE = "%"; + private static final String WORKBASKET_KEY = "workbasket-key"; + private static final String WORKBASKET_KEY_LIKE = "workbasket-key-like"; + private static final String ACCESS_ID = "access-id"; + private static final String ACCESS_ID_LIKE = "access-id-like"; + private static final String ACCESS_IDS = "access-ids"; - private static final String SORT_BY = "sort-by"; - private static final String SORT_DIRECTION = "order"; + private static final String SORT_BY = "sort-by"; + private static final String SORT_DIRECTION = "order"; - @Autowired - LdapClient ldapClient; + @Autowired LdapClient ldapClient; - @Autowired - private WorkbasketService workbasketService; + @Autowired private WorkbasketService workbasketService; - @Autowired - private WorkbasketAccessItemResourceAssembler workbasketAccessItemResourceAssembler; + @Autowired private WorkbasketAccessItemResourceAssembler workbasketAccessItemResourceAssembler; - /** - * This GET method return all workbasketAccessItems that correspond the given data. - * - * @param params - * filter, order and access ids. - * @return all WorkbasketAccesItemResource. - * @throws NotAuthorizedException - * if the user is not authorized. - * @throws InvalidArgumentException - * if some argument is invalid. - */ - @GetMapping(path = Mapping.URL_WORKBASKETACCESSITEMS) - public ResponseEntity getWorkbasketAccessItems( - @RequestParam MultiValueMap params) - throws NotAuthorizedException, InvalidArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Entry to getWorkbasketAccessItems(params= {})", params); - } - - WorkbasketAccessItemQuery query = workbasketService.createWorkbasketAccessItemQuery(); - query = getAccessIds(query, params); - query = applyFilterParams(query, params); - query = applySortingParams(query, params); - - PageMetadata pageMetadata = getPageMetadata(params, query); - List workbasketAccessItems = getQueryList(query, pageMetadata); - - WorkbasketAccessItemPaginatedListResource pagedResources = workbasketAccessItemResourceAssembler.toResources( - workbasketAccessItems, - pageMetadata); - - ResponseEntity response = ResponseEntity.ok(pagedResources); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from getWorkbasketAccessItems(), returning {}", response); - } - - return response; + /** + * This GET method return all workbasketAccessItems that correspond the given data. + * + * @param params filter, order and access ids. + * @return all WorkbasketAccesItemResource. + * @throws NotAuthorizedException if the user is not authorized. + * @throws InvalidArgumentException if some argument is invalid. + */ + @GetMapping(path = Mapping.URL_WORKBASKETACCESSITEMS) + public ResponseEntity getWorkbasketAccessItems( + @RequestParam MultiValueMap params) + throws NotAuthorizedException, InvalidArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Entry to getWorkbasketAccessItems(params= {})", params); } - /** - * This DELETE method delete all workbasketAccessItems that correspond the given accessId. - * - * @param accessId - * which need remove his workbasketAccessItems. - * @return ResponseEntity if the user is not authorized. - * @throws NotAuthorizedException - * if the user is not authorized. - * @throws InvalidArgumentException - * if some argument is invalid. - */ - @DeleteMapping(path = Mapping.URL_WORKBASKETACCESSITEMS) - public ResponseEntity removeWorkbasketAccessItems( - @RequestParam("access-id") String accessId) - throws NotAuthorizedException, InvalidArgumentException { - LOGGER.debug("Entry to removeWorkbasketAccessItems(access-id= {})", accessId); - if (!ldapClient.isGroup(accessId)) { - List workbasketAccessItemList = workbasketService.createWorkbasketAccessItemQuery() - .accessIdIn(accessId) - .list(); + WorkbasketAccessItemQuery query = workbasketService.createWorkbasketAccessItemQuery(); + query = getAccessIds(query, params); + query = applyFilterParams(query, params); + query = applySortingParams(query, params); - if (workbasketAccessItemList != null && !workbasketAccessItemList.isEmpty()) { - workbasketService.deleteWorkbasketAccessItemsForAccessId(accessId); - } - } else { - throw new InvalidArgumentException( - accessId + " corresponding to a group, not a user. You just can remove access items for a user"); - } + PageMetadata pageMetadata = getPageMetadata(params, query); + List workbasketAccessItems = getQueryList(query, pageMetadata); - ResponseEntity response = ResponseEntity.noContent().build(); - LOGGER.debug("Exit from removeWorkbasketAccessItems(), returning {}", response); - return response; + WorkbasketAccessItemPaginatedListResource pagedResources = + workbasketAccessItemResourceAssembler.toResources(workbasketAccessItems, pageMetadata); + + ResponseEntity response = + ResponseEntity.ok(pagedResources); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from getWorkbasketAccessItems(), returning {}", response); } - private WorkbasketAccessItemQuery getAccessIds(WorkbasketAccessItemQuery query, - MultiValueMap params) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Entry to getAccessIds(query= {}, params= {})", params); - } + return response; + } - if (params.containsKey(ACCESS_IDS)) { - String[] accessIds = extractVerticalBarSeparatedFields(params.get(ACCESS_IDS)); - query.accessIdIn(accessIds); - params.remove(ACCESS_IDS); - } + /** + * This DELETE method delete all workbasketAccessItems that correspond the given accessId. + * + * @param accessId which need remove his workbasketAccessItems. + * @return ResponseEntity if the user is not authorized. + * @throws NotAuthorizedException if the user is not authorized. + * @throws InvalidArgumentException if some argument is invalid. + */ + @DeleteMapping(path = Mapping.URL_WORKBASKETACCESSITEMS) + public ResponseEntity removeWorkbasketAccessItems( + @RequestParam("access-id") String accessId) + throws NotAuthorizedException, InvalidArgumentException { + LOGGER.debug("Entry to removeWorkbasketAccessItems(access-id= {})", accessId); + if (!ldapClient.isGroup(accessId)) { + List workbasketAccessItemList = + workbasketService.createWorkbasketAccessItemQuery().accessIdIn(accessId).list(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from getAccessIds(), returning {}", query); - } - - return query; + if (workbasketAccessItemList != null && !workbasketAccessItemList.isEmpty()) { + workbasketService.deleteWorkbasketAccessItemsForAccessId(accessId); + } + } else { + throw new InvalidArgumentException( + accessId + + " corresponding to a group, not a user. You just can remove access items for a user"); } - private WorkbasketAccessItemQuery applyFilterParams(WorkbasketAccessItemQuery query, - MultiValueMap params) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Entry to applyFilterParams(query= {}, params= {})", params); - } + ResponseEntity response = ResponseEntity.noContent().build(); + LOGGER.debug("Exit from removeWorkbasketAccessItems(), returning {}", response); + return response; + } - if (params.containsKey(WORKBASKET_KEY)) { - String[] keys = extractCommaSeparatedFields(params.get(WORKBASKET_KEY)); - query.workbasketKeyIn(keys); - params.remove(WORKBASKET_KEY); - } - if (params.containsKey(WORKBASKET_KEY_LIKE)) { - query.workbasketKeyLike(LIKE + params.get(WORKBASKET_KEY_LIKE).get(0) + LIKE); - params.remove(WORKBASKET_KEY_LIKE); - } - if (params.containsKey(ACCESS_ID)) { - String[] accessId = extractCommaSeparatedFields(params.get(ACCESS_ID)); - query.accessIdIn(accessId); - params.remove(ACCESS_ID); - } - if (params.containsKey(ACCESS_ID_LIKE)) { - query.accessIdLike(LIKE + params.get(ACCESS_ID_LIKE).get(0) + LIKE); - params.remove(ACCESS_ID_LIKE); - } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from applyFilterParams(), returning {}", query); - } - - return query; + private WorkbasketAccessItemQuery getAccessIds( + WorkbasketAccessItemQuery query, MultiValueMap params) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Entry to getAccessIds(query= {}, params= {})", params); } - private WorkbasketAccessItemQuery applySortingParams(WorkbasketAccessItemQuery query, - MultiValueMap params) - throws IllegalArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Entry to applySortingParams(query= {}, params= {})", params); - } - - // sorting - String sortBy = params.getFirst(SORT_BY); - if (sortBy != null) { - BaseQuery.SortDirection sortDirection; - if (params.getFirst(SORT_DIRECTION) != null && "desc".equals(params.getFirst(SORT_DIRECTION))) { - sortDirection = BaseQuery.SortDirection.DESCENDING; - } else { - sortDirection = BaseQuery.SortDirection.ASCENDING; - } - switch (sortBy) { - case (WORKBASKET_KEY): - query = query.orderByWorkbasketKey(sortDirection); - break; - case (ACCESS_ID): - query = query.orderByAccessId(sortDirection); - break; - default: - throw new IllegalArgumentException("Unknown order '" + sortBy + "'"); - } - } - params.remove(SORT_BY); - params.remove(SORT_DIRECTION); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from applySortingParams(), returning {}", query); - } - - return query; + if (params.containsKey(ACCESS_IDS)) { + String[] accessIds = extractVerticalBarSeparatedFields(params.get(ACCESS_IDS)); + query.accessIdIn(accessIds); + params.remove(ACCESS_IDS); } - private String[] extractVerticalBarSeparatedFields(List searchFor) { - List values = new ArrayList<>(); - if (searchFor != null) { - searchFor.forEach(item -> Collections.addAll(values, item.split("\\|"))); - } - return values.toArray(new String[0]); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from getAccessIds(), returning {}", query); } + return query; + } + + private WorkbasketAccessItemQuery applyFilterParams( + WorkbasketAccessItemQuery query, MultiValueMap params) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Entry to applyFilterParams(query= {}, params= {})", params); + } + + if (params.containsKey(WORKBASKET_KEY)) { + String[] keys = extractCommaSeparatedFields(params.get(WORKBASKET_KEY)); + query.workbasketKeyIn(keys); + params.remove(WORKBASKET_KEY); + } + if (params.containsKey(WORKBASKET_KEY_LIKE)) { + query.workbasketKeyLike(LIKE + params.get(WORKBASKET_KEY_LIKE).get(0) + LIKE); + params.remove(WORKBASKET_KEY_LIKE); + } + if (params.containsKey(ACCESS_ID)) { + String[] accessId = extractCommaSeparatedFields(params.get(ACCESS_ID)); + query.accessIdIn(accessId); + params.remove(ACCESS_ID); + } + if (params.containsKey(ACCESS_ID_LIKE)) { + query.accessIdLike(LIKE + params.get(ACCESS_ID_LIKE).get(0) + LIKE); + params.remove(ACCESS_ID_LIKE); + } + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from applyFilterParams(), returning {}", query); + } + + return query; + } + + private WorkbasketAccessItemQuery applySortingParams( + WorkbasketAccessItemQuery query, MultiValueMap params) + throws IllegalArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Entry to applySortingParams(query= {}, params= {})", params); + } + + // sorting + String sortBy = params.getFirst(SORT_BY); + if (sortBy != null) { + BaseQuery.SortDirection sortDirection; + if (params.getFirst(SORT_DIRECTION) != null + && "desc".equals(params.getFirst(SORT_DIRECTION))) { + sortDirection = BaseQuery.SortDirection.DESCENDING; + } else { + sortDirection = BaseQuery.SortDirection.ASCENDING; + } + switch (sortBy) { + case (WORKBASKET_KEY): + query = query.orderByWorkbasketKey(sortDirection); + break; + case (ACCESS_ID): + query = query.orderByAccessId(sortDirection); + break; + default: + throw new IllegalArgumentException("Unknown order '" + sortBy + "'"); + } + } + params.remove(SORT_BY); + params.remove(SORT_DIRECTION); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from applySortingParams(), returning {}", query); + } + + return query; + } + + private String[] extractVerticalBarSeparatedFields(List searchFor) { + List values = new ArrayList<>(); + if (searchFor != null) { + searchFor.forEach(item -> Collections.addAll(values, item.split("\\|"))); + } + return values.toArray(new String[0]); + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/WorkbasketController.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/WorkbasketController.java index 2f4621e1d..86d6b11e9 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/WorkbasketController.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/WorkbasketController.java @@ -3,7 +3,6 @@ package pro.taskana.rest; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.hateoas.Resources; @@ -50,423 +49,443 @@ import pro.taskana.rest.resource.WorkbasketResourceAssembler; import pro.taskana.rest.resource.WorkbasketSummaryListResource; import pro.taskana.rest.resource.WorkbasketSummaryResourceAssembler; -/** - * Controller for all {@link Workbasket} related endpoints. - */ - +/** Controller for all {@link Workbasket} related endpoints. */ @RestController @EnableHypermediaSupport(type = HypermediaType.HAL) public class WorkbasketController extends AbstractPagingController { - private static final Logger LOGGER = LoggerFactory.getLogger(WorkbasketController.class); + private static final Logger LOGGER = LoggerFactory.getLogger(WorkbasketController.class); - private static final String LIKE = "%"; - private static final String NAME = "name"; - private static final String NAME_LIKE = "name-like"; - private static final String KEY = "key"; - private static final String KEY_LIKE = "key-like"; - private static final String OWNER = "owner"; - private static final String OWNER_LIKE = "owner-like"; - private static final String DESCRIPTION_LIKE = "description-like"; - private static final String DOMAIN = "domain"; - private static final String REQUIRED_PERMISSION = "required-permission"; - private static final String TYPE = "type"; - private static final String DESCRIPTION = "description"; + private static final String LIKE = "%"; + private static final String NAME = "name"; + private static final String NAME_LIKE = "name-like"; + private static final String KEY = "key"; + private static final String KEY_LIKE = "key-like"; + private static final String OWNER = "owner"; + private static final String OWNER_LIKE = "owner-like"; + private static final String DESCRIPTION_LIKE = "description-like"; + private static final String DOMAIN = "domain"; + private static final String REQUIRED_PERMISSION = "required-permission"; + private static final String TYPE = "type"; + private static final String DESCRIPTION = "description"; - private static final String SORT_BY = "sort-by"; - private static final String SORT_DIRECTION = "order"; + private static final String SORT_BY = "sort-by"; + private static final String SORT_DIRECTION = "order"; - private WorkbasketService workbasketService; + private WorkbasketService workbasketService; - private WorkbasketResourceAssembler workbasketResourceAssembler; + private WorkbasketResourceAssembler workbasketResourceAssembler; - private WorkbasketSummaryResourceAssembler workbasketSummaryResourceAssembler; + private WorkbasketSummaryResourceAssembler workbasketSummaryResourceAssembler; - private DistributionTargetResourceAssembler distributionTargetResourceAssembler; + private DistributionTargetResourceAssembler distributionTargetResourceAssembler; - private WorkbasketAccessItemResourceAssembler workbasketAccessItemResourceAssembler; + private WorkbasketAccessItemResourceAssembler workbasketAccessItemResourceAssembler; - WorkbasketController(WorkbasketService workbasketService, - WorkbasketResourceAssembler workbasketResourceAssembler, - WorkbasketSummaryResourceAssembler workbasketSummaryResourceAssembler, - DistributionTargetResourceAssembler distributionTargetResourceAssembler, - WorkbasketAccessItemResourceAssembler workbasketAccessItemResourceAssembler) { - this.workbasketService = workbasketService; - this.workbasketResourceAssembler = workbasketResourceAssembler; - this.workbasketSummaryResourceAssembler = workbasketSummaryResourceAssembler; - this.distributionTargetResourceAssembler = distributionTargetResourceAssembler; - this.workbasketAccessItemResourceAssembler = workbasketAccessItemResourceAssembler; + WorkbasketController( + WorkbasketService workbasketService, + WorkbasketResourceAssembler workbasketResourceAssembler, + WorkbasketSummaryResourceAssembler workbasketSummaryResourceAssembler, + DistributionTargetResourceAssembler distributionTargetResourceAssembler, + WorkbasketAccessItemResourceAssembler workbasketAccessItemResourceAssembler) { + this.workbasketService = workbasketService; + this.workbasketResourceAssembler = workbasketResourceAssembler; + this.workbasketSummaryResourceAssembler = workbasketSummaryResourceAssembler; + this.distributionTargetResourceAssembler = distributionTargetResourceAssembler; + this.workbasketAccessItemResourceAssembler = workbasketAccessItemResourceAssembler; + } + + @GetMapping(path = Mapping.URL_WORKBASKET) + @Transactional(readOnly = true, rollbackFor = Exception.class) + public ResponseEntity getWorkbaskets( + @RequestParam MultiValueMap params) throws InvalidArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Entry to getWorkbaskets(params= {})", params); } - @GetMapping(path = Mapping.URL_WORKBASKET) - @Transactional(readOnly = true, rollbackFor = Exception.class) - public ResponseEntity getWorkbaskets( - @RequestParam MultiValueMap params) throws InvalidArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Entry to getWorkbaskets(params= {})", params); - } + WorkbasketQuery query = workbasketService.createWorkbasketQuery(); + query = applySortingParams(query, params); + query = applyFilterParams(query, params); - WorkbasketQuery query = workbasketService.createWorkbasketQuery(); - query = applySortingParams(query, params); - query = applyFilterParams(query, params); + PageMetadata pageMetadata = getPageMetadata(params, query); + List workbasketSummaries = getQueryList(query, pageMetadata); + WorkbasketSummaryListResource pagedResources = + workbasketSummaryResourceAssembler.toResources(workbasketSummaries, pageMetadata); - PageMetadata pageMetadata = getPageMetadata(params, query); - List workbasketSummaries = getQueryList(query, pageMetadata); - WorkbasketSummaryListResource pagedResources = workbasketSummaryResourceAssembler.toResources( - workbasketSummaries, - pageMetadata); - - ResponseEntity response = ResponseEntity.ok(pagedResources); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from getWorkbaskets(), returning {}", response); - } - - return response; + ResponseEntity response = ResponseEntity.ok(pagedResources); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from getWorkbaskets(), returning {}", response); } - @GetMapping(path = Mapping.URL_WORKBASKET_ID) - @Transactional(readOnly = true, rollbackFor = Exception.class) - public ResponseEntity getWorkbasket(@PathVariable(value = "workbasketId") String workbasketId) - throws WorkbasketNotFoundException, NotAuthorizedException { - LOGGER.debug("Entry to getWorkbasket(workbasketId= {})", workbasketId); - ResponseEntity result; - Workbasket workbasket = workbasketService.getWorkbasket(workbasketId); - result = ResponseEntity.ok(workbasketResourceAssembler.toResource(workbasket)); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from getWorkbasket(), returning {}", result); - } + return response; + } - return result; + @GetMapping(path = Mapping.URL_WORKBASKET_ID) + @Transactional(readOnly = true, rollbackFor = Exception.class) + public ResponseEntity getWorkbasket( + @PathVariable(value = "workbasketId") String workbasketId) + throws WorkbasketNotFoundException, NotAuthorizedException { + LOGGER.debug("Entry to getWorkbasket(workbasketId= {})", workbasketId); + ResponseEntity result; + Workbasket workbasket = workbasketService.getWorkbasket(workbasketId); + result = ResponseEntity.ok(workbasketResourceAssembler.toResource(workbasket)); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from getWorkbasket(), returning {}", result); } - @DeleteMapping(path = Mapping.URL_WORKBASKET_ID) - @Transactional(rollbackFor = Exception.class, noRollbackFor = WorkbasketNotFoundException.class) - public ResponseEntity markWorkbasketForDeletion(@PathVariable(value = "workbasketId") String workbasketId) - throws NotAuthorizedException, InvalidArgumentException, - WorkbasketNotFoundException, WorkbasketInUseException { - LOGGER.debug("Entry to markWorkbasketForDeletion(workbasketId= {})", workbasketId); - ResponseEntity response = ResponseEntity.accepted().body(workbasketService.deleteWorkbasket(workbasketId)); - LOGGER.debug("Exit from markWorkbasketForDeletion(), returning {}", - response); - return response; + return result; + } + + @DeleteMapping(path = Mapping.URL_WORKBASKET_ID) + @Transactional(rollbackFor = Exception.class, noRollbackFor = WorkbasketNotFoundException.class) + public ResponseEntity markWorkbasketForDeletion( + @PathVariable(value = "workbasketId") String workbasketId) + throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException, + WorkbasketInUseException { + LOGGER.debug("Entry to markWorkbasketForDeletion(workbasketId= {})", workbasketId); + ResponseEntity response = + ResponseEntity.accepted().body(workbasketService.deleteWorkbasket(workbasketId)); + LOGGER.debug("Exit from markWorkbasketForDeletion(), returning {}", response); + return response; + } + + @PostMapping(path = Mapping.URL_WORKBASKET) + @Transactional(rollbackFor = Exception.class) + public ResponseEntity createWorkbasket( + @RequestBody WorkbasketResource workbasketResource) + throws InvalidWorkbasketException, NotAuthorizedException, WorkbasketAlreadyExistException, + WorkbasketNotFoundException, DomainNotFoundException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Entry to createWorkbasket(workbasketResource= {})", workbasketResource); } - @PostMapping(path = Mapping.URL_WORKBASKET) - @Transactional(rollbackFor = Exception.class) - public ResponseEntity createWorkbasket(@RequestBody WorkbasketResource workbasketResource) - throws InvalidWorkbasketException, NotAuthorizedException, WorkbasketAlreadyExistException, - WorkbasketNotFoundException, DomainNotFoundException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Entry to createWorkbasket(workbasketResource= {})", workbasketResource); - } - - Workbasket workbasket = workbasketResourceAssembler.toModel(workbasketResource); - workbasket = workbasketService.createWorkbasket(workbasket); - ResponseEntity response = ResponseEntity.status(HttpStatus.CREATED) + Workbasket workbasket = workbasketResourceAssembler.toModel(workbasketResource); + workbasket = workbasketService.createWorkbasket(workbasket); + ResponseEntity response = + ResponseEntity.status(HttpStatus.CREATED) .body(workbasketResourceAssembler.toResource(workbasket)); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from createWorkbasket(), returning {}", response); - } - - return response; + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from createWorkbasket(), returning {}", response); } - @PutMapping(path = Mapping.URL_WORKBASKET_ID) - @Transactional(rollbackFor = Exception.class) - public ResponseEntity updateWorkbasket( - @PathVariable(value = "workbasketId") String workbasketId, - @RequestBody WorkbasketResource workbasketResource) - throws InvalidWorkbasketException, WorkbasketNotFoundException, NotAuthorizedException { - LOGGER.debug("Entry to updateWorkbasket(workbasketId= {})", workbasketId); - ResponseEntity result; - if (workbasketId.equals(workbasketResource.workbasketId)) { - Workbasket workbasket = workbasketResourceAssembler.toModel(workbasketResource); - workbasket = workbasketService.updateWorkbasket(workbasket); - result = ResponseEntity.ok(workbasketResourceAssembler.toResource(workbasket)); - } else { - throw new InvalidWorkbasketException( - "Target-WB-ID('" + workbasketId - + "') is not identical with the WB-ID of to object which should be updated. ID=('" - + workbasketResource.getId() + "')"); - } + return response; + } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from updateWorkbasket(), returning {}", result); - } - - return result; + @PutMapping(path = Mapping.URL_WORKBASKET_ID) + @Transactional(rollbackFor = Exception.class) + public ResponseEntity updateWorkbasket( + @PathVariable(value = "workbasketId") String workbasketId, + @RequestBody WorkbasketResource workbasketResource) + throws InvalidWorkbasketException, WorkbasketNotFoundException, NotAuthorizedException { + LOGGER.debug("Entry to updateWorkbasket(workbasketId= {})", workbasketId); + ResponseEntity result; + if (workbasketId.equals(workbasketResource.workbasketId)) { + Workbasket workbasket = workbasketResourceAssembler.toModel(workbasketResource); + workbasket = workbasketService.updateWorkbasket(workbasket); + result = ResponseEntity.ok(workbasketResourceAssembler.toResource(workbasket)); + } else { + throw new InvalidWorkbasketException( + "Target-WB-ID('" + + workbasketId + + "') is not identical with the WB-ID of to object which should be updated. ID=('" + + workbasketResource.getId() + + "')"); } - @GetMapping(path = Mapping.URL_WORKBASKET_ID_ACCESSITEMS) - @Transactional(readOnly = true, rollbackFor = Exception.class) - public ResponseEntity getWorkbasketAccessItems( - @PathVariable(value = "workbasketId") String workbasketId) - throws NotAuthorizedException, WorkbasketNotFoundException { - LOGGER.debug("Entry to getWorkbasketAccessItems(workbasketId= {})", workbasketId); - ResponseEntity result; - - List accessItems = workbasketService.getWorkbasketAccessItems(workbasketId); - result = ResponseEntity.ok(workbasketAccessItemResourceAssembler.toResources(workbasketId, accessItems)); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from getWorkbasketAccessItems(), returning {}", result); - } - - return result; + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from updateWorkbasket(), returning {}", result); } - @PutMapping(path = Mapping.URL_WORKBASKET_ID_ACCESSITEMS) - @Transactional(rollbackFor = Exception.class) - public ResponseEntity setWorkbasketAccessItems( - @PathVariable(value = "workbasketId") String workbasketId, - @RequestBody List workbasketAccessResourceItems) - throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException { - LOGGER.debug("Entry to setWorkbasketAccessItems(workbasketId= {})", workbasketId); - if (workbasketAccessResourceItems == null) { - throw new InvalidArgumentException("Can´t create something with NULL body-value."); - } + return result; + } - List wbAccessItems = new ArrayList<>(); - workbasketAccessResourceItems.forEach( - item -> wbAccessItems.add(workbasketAccessItemResourceAssembler.toModel(item))); - workbasketService.setWorkbasketAccessItems(workbasketId, wbAccessItems); - List updatedWbAccessItems = workbasketService.getWorkbasketAccessItems(workbasketId); + @GetMapping(path = Mapping.URL_WORKBASKET_ID_ACCESSITEMS) + @Transactional(readOnly = true, rollbackFor = Exception.class) + public ResponseEntity getWorkbasketAccessItems( + @PathVariable(value = "workbasketId") String workbasketId) + throws NotAuthorizedException, WorkbasketNotFoundException { + LOGGER.debug("Entry to getWorkbasketAccessItems(workbasketId= {})", workbasketId); + ResponseEntity result; - ResponseEntity response = ResponseEntity.ok( + List accessItems = + workbasketService.getWorkbasketAccessItems(workbasketId); + result = + ResponseEntity.ok( + workbasketAccessItemResourceAssembler.toResources(workbasketId, accessItems)); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from getWorkbasketAccessItems(), returning {}", result); + } + + return result; + } + + @PutMapping(path = Mapping.URL_WORKBASKET_ID_ACCESSITEMS) + @Transactional(rollbackFor = Exception.class) + public ResponseEntity setWorkbasketAccessItems( + @PathVariable(value = "workbasketId") String workbasketId, + @RequestBody List workbasketAccessResourceItems) + throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException { + LOGGER.debug("Entry to setWorkbasketAccessItems(workbasketId= {})", workbasketId); + if (workbasketAccessResourceItems == null) { + throw new InvalidArgumentException("Can´t create something with NULL body-value."); + } + + List wbAccessItems = new ArrayList<>(); + workbasketAccessResourceItems.forEach( + item -> wbAccessItems.add(workbasketAccessItemResourceAssembler.toModel(item))); + workbasketService.setWorkbasketAccessItems(workbasketId, wbAccessItems); + List updatedWbAccessItems = + workbasketService.getWorkbasketAccessItems(workbasketId); + + ResponseEntity response = + ResponseEntity.ok( workbasketAccessItemResourceAssembler.toResources(workbasketId, updatedWbAccessItems)); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from setWorkbasketAccessItems(), returning {}", response); - } - - return response; + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from setWorkbasketAccessItems(), returning {}", response); } - @GetMapping(path = Mapping.URL_WORKBASKET_ID_DISTRIBUTION) - @Transactional(readOnly = true, rollbackFor = Exception.class) - public ResponseEntity getDistributionTargets( - @PathVariable(value = "workbasketId") String workbasketId) - throws WorkbasketNotFoundException, NotAuthorizedException { + return response; + } - LOGGER.debug("Entry to getDistributionTargets(workbasketId= {})", workbasketId); - List distributionTargets = workbasketService.getDistributionTargets(workbasketId); - DistributionTargetListResource distributionTargetListResource = distributionTargetResourceAssembler - .toResources(workbasketId, distributionTargets); - ResponseEntity result = ResponseEntity.ok(distributionTargetListResource); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from getDistributionTargets(), returning {}", result); - } + @GetMapping(path = Mapping.URL_WORKBASKET_ID_DISTRIBUTION) + @Transactional(readOnly = true, rollbackFor = Exception.class) + public ResponseEntity getDistributionTargets( + @PathVariable(value = "workbasketId") String workbasketId) + throws WorkbasketNotFoundException, NotAuthorizedException { - return result; + LOGGER.debug("Entry to getDistributionTargets(workbasketId= {})", workbasketId); + List distributionTargets = + workbasketService.getDistributionTargets(workbasketId); + DistributionTargetListResource distributionTargetListResource = + distributionTargetResourceAssembler.toResources(workbasketId, distributionTargets); + ResponseEntity result = + ResponseEntity.ok(distributionTargetListResource); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from getDistributionTargets(), returning {}", result); } - @PutMapping(path = Mapping.URL_WORKBASKET_ID_DISTRIBUTION) - @Transactional(rollbackFor = Exception.class) - public ResponseEntity setDistributionTargetsForWorkbasketId( - @PathVariable(value = "workbasketId") String sourceWorkbasketId, - @RequestBody List targetWorkbasketIds) throws WorkbasketNotFoundException, NotAuthorizedException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Entry to getTasksStatusReport(workbasketId= {}, targetWorkbasketIds´= {})", - sourceWorkbasketId, - LoggerUtils.listToString(targetWorkbasketIds)); - } + return result; + } - workbasketService.setDistributionTargets(sourceWorkbasketId, targetWorkbasketIds); - - List distributionTargets = workbasketService.getDistributionTargets(sourceWorkbasketId); - ResponseEntity response = ResponseEntity.ok( - distributionTargetResourceAssembler.toResources(sourceWorkbasketId, distributionTargets)); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from getTasksStatusReport(), returning {}", response); - } - - return response; + @PutMapping(path = Mapping.URL_WORKBASKET_ID_DISTRIBUTION) + @Transactional(rollbackFor = Exception.class) + public ResponseEntity setDistributionTargetsForWorkbasketId( + @PathVariable(value = "workbasketId") String sourceWorkbasketId, + @RequestBody List targetWorkbasketIds) + throws WorkbasketNotFoundException, NotAuthorizedException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "Entry to getTasksStatusReport(workbasketId= {}, targetWorkbasketIds´= {})", + sourceWorkbasketId, + LoggerUtils.listToString(targetWorkbasketIds)); } - // TODO - schema inconsistent with PUT and GET - @DeleteMapping(path = Mapping.URL_WORKBASKET_DISTRIBUTION_ID) - @Transactional(rollbackFor = Exception.class) - public ResponseEntity> removeDistributionTargetForWorkbasketId( - @PathVariable(value = "workbasketId") String targetWorkbasketId) - throws WorkbasketNotFoundException, NotAuthorizedException { - LOGGER.debug("Entry to removeDistributionTargetForWorkbasketId(workbasketId= {})", targetWorkbasketId); - List sourceWorkbaskets = workbasketService.getDistributionSources(targetWorkbasketId); - for (WorkbasketSummary source : sourceWorkbaskets) { - workbasketService.removeDistributionTarget(source.getId(), targetWorkbasketId); - } + workbasketService.setDistributionTargets(sourceWorkbasketId, targetWorkbasketIds); - ResponseEntity> response = ResponseEntity.noContent().build(); - LOGGER.debug("Exit from removeDistributionTargetForWorkbasketId(), returning {}", response); - return response; + List distributionTargets = + workbasketService.getDistributionTargets(sourceWorkbasketId); + ResponseEntity response = + ResponseEntity.ok( + distributionTargetResourceAssembler.toResources( + sourceWorkbasketId, distributionTargets)); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from getTasksStatusReport(), returning {}", response); } - private WorkbasketQuery applySortingParams(WorkbasketQuery query, MultiValueMap params) - throws IllegalArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Entry to applySortingParams(query= {}, params={})", query, params); - } + return response; + } - // sorting - String sortBy = params.getFirst(SORT_BY); - if (sortBy != null) { - SortDirection sortDirection; - if (params.getFirst(SORT_DIRECTION) != null && "desc".equals(params.getFirst(SORT_DIRECTION))) { - sortDirection = SortDirection.DESCENDING; - } else { - sortDirection = SortDirection.ASCENDING; - } - switch (sortBy) { - case (NAME): - query = query.orderByName(sortDirection); - break; - case (KEY): - query = query.orderByKey(sortDirection); - break; - case (OWNER): - query = query.orderByOwner(sortDirection); - break; - case (TYPE): - query = query.orderByType(sortDirection); - break; - case (DESCRIPTION): - query = query.orderByDescription(sortDirection); - break; - default: - throw new IllegalArgumentException("Unknown order '" + sortBy + "'"); - } - } - params.remove(SORT_BY); - params.remove(SORT_DIRECTION); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from applySortingParams(), returning {}", query); - } - - return query; + // TODO - schema inconsistent with PUT and GET + @DeleteMapping(path = Mapping.URL_WORKBASKET_DISTRIBUTION_ID) + @Transactional(rollbackFor = Exception.class) + public ResponseEntity> + removeDistributionTargetForWorkbasketId( + @PathVariable(value = "workbasketId") String targetWorkbasketId) + throws WorkbasketNotFoundException, NotAuthorizedException { + LOGGER.debug( + "Entry to removeDistributionTargetForWorkbasketId(workbasketId= {})", targetWorkbasketId); + List sourceWorkbaskets = + workbasketService.getDistributionSources(targetWorkbasketId); + for (WorkbasketSummary source : sourceWorkbaskets) { + workbasketService.removeDistributionTarget(source.getId(), targetWorkbasketId); } - private WorkbasketQuery applyFilterParams(WorkbasketQuery query, - MultiValueMap params) throws InvalidArgumentException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Entry to applyFilterParams(query= {}, params= {})", query, params); - } + ResponseEntity> response = + ResponseEntity.noContent().build(); + LOGGER.debug("Exit from removeDistributionTargetForWorkbasketId(), returning {}", response); + return response; + } - if (params.containsKey(NAME)) { - String[] names = extractCommaSeparatedFields(params.get(NAME)); - query.nameIn(names); - params.remove(NAME); - } - if (params.containsKey(NAME_LIKE)) { - query.nameLike(LIKE + params.get(NAME_LIKE).get(0) + LIKE); - params.remove(NAME_LIKE); - } - if (params.containsKey(KEY)) { - String[] names = extractCommaSeparatedFields(params.get(KEY)); - query.keyIn(names); - params.remove(KEY); - } - if (params.containsKey(KEY_LIKE)) { - query.keyLike(LIKE + params.get(KEY_LIKE).get(0) + LIKE); - params.remove(KEY_LIKE); - } - if (params.containsKey(OWNER)) { - String[] names = extractCommaSeparatedFields(params.get(OWNER)); - query.ownerIn(names); - params.remove(OWNER); - } - if (params.containsKey(OWNER_LIKE)) { - query.ownerLike(LIKE + params.get(OWNER_LIKE).get(0) + LIKE); - params.remove(OWNER_LIKE); - } - if (params.containsKey(DESCRIPTION_LIKE)) { - query.descriptionLike(LIKE + params.get(DESCRIPTION_LIKE).get(0) + LIKE); - params.remove(DESCRIPTION_LIKE); - } - if (params.containsKey(DOMAIN)) { - query.domainIn(extractCommaSeparatedFields(params.get(DOMAIN))); - params.remove(DOMAIN); - } - if (params.containsKey(TYPE)) { - switch (params.getFirst(TYPE)) { - case "PERSONAL": - query.typeIn(WorkbasketType.PERSONAL); - break; - case "GROUP": - query.typeIn(WorkbasketType.GROUP); - break; - case "CLEARANCE": - query.typeIn(WorkbasketType.CLEARANCE); - break; - case "TOPIC": - query.typeIn(WorkbasketType.TOPIC); - break; - default: - throw new InvalidArgumentException("Unknown Workbasket type '" + params.getFirst(TYPE) + "'"); - } - params.remove(TYPE); - } - if (params.containsKey(REQUIRED_PERMISSION)) { - for (String authorization : Arrays.asList(params.getFirst(REQUIRED_PERMISSION).split(","))) { - switch (authorization.trim()) { - case "READ": - query.callerHasPermission(WorkbasketPermission.READ); - break; - case "OPEN": - query.callerHasPermission(WorkbasketPermission.OPEN); - break; - case "APPEND": - query.callerHasPermission(WorkbasketPermission.APPEND); - break; - case "TRANSFER": - query.callerHasPermission(WorkbasketPermission.TRANSFER); - break; - case "DISTRIBUTE": - query.callerHasPermission(WorkbasketPermission.DISTRIBUTE); - break; - case "CUSTOM_1": - query.callerHasPermission(WorkbasketPermission.CUSTOM_1); - break; - case "CUSTOM_2": - query.callerHasPermission(WorkbasketPermission.CUSTOM_2); - break; - case "CUSTOM_3": - query.callerHasPermission(WorkbasketPermission.CUSTOM_3); - break; - case "CUSTOM_4": - query.callerHasPermission(WorkbasketPermission.CUSTOM_4); - break; - case "CUSTOM_5": - query.callerHasPermission(WorkbasketPermission.CUSTOM_5); - break; - case "CUSTOM_6": - query.callerHasPermission(WorkbasketPermission.CUSTOM_6); - break; - case "CUSTOM_7": - query.callerHasPermission(WorkbasketPermission.CUSTOM_7); - break; - case "CUSTOM_8": - query.callerHasPermission(WorkbasketPermission.CUSTOM_8); - break; - case "CUSTOM_9": - query.callerHasPermission(WorkbasketPermission.CUSTOM_9); - break; - case "CUSTOM_10": - query.callerHasPermission(WorkbasketPermission.CUSTOM_10); - break; - case "CUSTOM_11": - query.callerHasPermission(WorkbasketPermission.CUSTOM_11); - break; - case "CUSTOM_12": - query.callerHasPermission(WorkbasketPermission.CUSTOM_12); - break; - default: - throw new InvalidArgumentException("Unknown authorization '" + authorization + "'"); - } - } - params.remove(REQUIRED_PERMISSION); - } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from applyFilterParams(), returning {}", query); - } - - return query; + private WorkbasketQuery applySortingParams( + WorkbasketQuery query, MultiValueMap params) throws IllegalArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Entry to applySortingParams(query= {}, params={})", query, params); } + // sorting + String sortBy = params.getFirst(SORT_BY); + if (sortBy != null) { + SortDirection sortDirection; + if (params.getFirst(SORT_DIRECTION) != null + && "desc".equals(params.getFirst(SORT_DIRECTION))) { + sortDirection = SortDirection.DESCENDING; + } else { + sortDirection = SortDirection.ASCENDING; + } + switch (sortBy) { + case (NAME): + query = query.orderByName(sortDirection); + break; + case (KEY): + query = query.orderByKey(sortDirection); + break; + case (OWNER): + query = query.orderByOwner(sortDirection); + break; + case (TYPE): + query = query.orderByType(sortDirection); + break; + case (DESCRIPTION): + query = query.orderByDescription(sortDirection); + break; + default: + throw new IllegalArgumentException("Unknown order '" + sortBy + "'"); + } + } + params.remove(SORT_BY); + params.remove(SORT_DIRECTION); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from applySortingParams(), returning {}", query); + } + + return query; + } + + private WorkbasketQuery applyFilterParams( + WorkbasketQuery query, MultiValueMap params) throws InvalidArgumentException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Entry to applyFilterParams(query= {}, params= {})", query, params); + } + + if (params.containsKey(NAME)) { + String[] names = extractCommaSeparatedFields(params.get(NAME)); + query.nameIn(names); + params.remove(NAME); + } + if (params.containsKey(NAME_LIKE)) { + query.nameLike(LIKE + params.get(NAME_LIKE).get(0) + LIKE); + params.remove(NAME_LIKE); + } + if (params.containsKey(KEY)) { + String[] names = extractCommaSeparatedFields(params.get(KEY)); + query.keyIn(names); + params.remove(KEY); + } + if (params.containsKey(KEY_LIKE)) { + query.keyLike(LIKE + params.get(KEY_LIKE).get(0) + LIKE); + params.remove(KEY_LIKE); + } + if (params.containsKey(OWNER)) { + String[] names = extractCommaSeparatedFields(params.get(OWNER)); + query.ownerIn(names); + params.remove(OWNER); + } + if (params.containsKey(OWNER_LIKE)) { + query.ownerLike(LIKE + params.get(OWNER_LIKE).get(0) + LIKE); + params.remove(OWNER_LIKE); + } + if (params.containsKey(DESCRIPTION_LIKE)) { + query.descriptionLike(LIKE + params.get(DESCRIPTION_LIKE).get(0) + LIKE); + params.remove(DESCRIPTION_LIKE); + } + if (params.containsKey(DOMAIN)) { + query.domainIn(extractCommaSeparatedFields(params.get(DOMAIN))); + params.remove(DOMAIN); + } + if (params.containsKey(TYPE)) { + switch (params.getFirst(TYPE)) { + case "PERSONAL": + query.typeIn(WorkbasketType.PERSONAL); + break; + case "GROUP": + query.typeIn(WorkbasketType.GROUP); + break; + case "CLEARANCE": + query.typeIn(WorkbasketType.CLEARANCE); + break; + case "TOPIC": + query.typeIn(WorkbasketType.TOPIC); + break; + default: + throw new InvalidArgumentException( + "Unknown Workbasket type '" + params.getFirst(TYPE) + "'"); + } + params.remove(TYPE); + } + if (params.containsKey(REQUIRED_PERMISSION)) { + for (String authorization : Arrays.asList(params.getFirst(REQUIRED_PERMISSION).split(","))) { + switch (authorization.trim()) { + case "READ": + query.callerHasPermission(WorkbasketPermission.READ); + break; + case "OPEN": + query.callerHasPermission(WorkbasketPermission.OPEN); + break; + case "APPEND": + query.callerHasPermission(WorkbasketPermission.APPEND); + break; + case "TRANSFER": + query.callerHasPermission(WorkbasketPermission.TRANSFER); + break; + case "DISTRIBUTE": + query.callerHasPermission(WorkbasketPermission.DISTRIBUTE); + break; + case "CUSTOM_1": + query.callerHasPermission(WorkbasketPermission.CUSTOM_1); + break; + case "CUSTOM_2": + query.callerHasPermission(WorkbasketPermission.CUSTOM_2); + break; + case "CUSTOM_3": + query.callerHasPermission(WorkbasketPermission.CUSTOM_3); + break; + case "CUSTOM_4": + query.callerHasPermission(WorkbasketPermission.CUSTOM_4); + break; + case "CUSTOM_5": + query.callerHasPermission(WorkbasketPermission.CUSTOM_5); + break; + case "CUSTOM_6": + query.callerHasPermission(WorkbasketPermission.CUSTOM_6); + break; + case "CUSTOM_7": + query.callerHasPermission(WorkbasketPermission.CUSTOM_7); + break; + case "CUSTOM_8": + query.callerHasPermission(WorkbasketPermission.CUSTOM_8); + break; + case "CUSTOM_9": + query.callerHasPermission(WorkbasketPermission.CUSTOM_9); + break; + case "CUSTOM_10": + query.callerHasPermission(WorkbasketPermission.CUSTOM_10); + break; + case "CUSTOM_11": + query.callerHasPermission(WorkbasketPermission.CUSTOM_11); + break; + case "CUSTOM_12": + query.callerHasPermission(WorkbasketPermission.CUSTOM_12); + break; + default: + throw new InvalidArgumentException("Unknown authorization '" + authorization + "'"); + } + } + params.remove(REQUIRED_PERMISSION); + } + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from applyFilterParams(), returning {}", query); + } + + return query; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/WorkbasketDefinitionController.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/WorkbasketDefinitionController.java index c5aa10433..e372dcdba 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/WorkbasketDefinitionController.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/WorkbasketDefinitionController.java @@ -1,5 +1,9 @@ package pro.taskana.rest; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; @@ -8,7 +12,6 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DuplicateKeyException; @@ -21,11 +24,6 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; - import pro.taskana.Workbasket; import pro.taskana.WorkbasketAccessItem; import pro.taskana.WorkbasketQuery; @@ -41,179 +39,174 @@ import pro.taskana.rest.resource.WorkbasketDefinitionResource; import pro.taskana.rest.resource.WorkbasketDefinitionResourceAssembler; import pro.taskana.rest.resource.WorkbasketResource; -/** - * Controller for all {@link WorkbasketDefinitionResource} related endpoints. - */ - +/** Controller for all {@link WorkbasketDefinitionResource} related endpoints. */ @RestController @EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL) public class WorkbasketDefinitionController { - private static final Logger LOGGER = LoggerFactory.getLogger(WorkbasketDefinitionController.class); + private static final Logger LOGGER = + LoggerFactory.getLogger(WorkbasketDefinitionController.class); - private WorkbasketService workbasketService; + private WorkbasketService workbasketService; - private WorkbasketDefinitionResourceAssembler workbasketDefinitionAssembler; + private WorkbasketDefinitionResourceAssembler workbasketDefinitionAssembler; - WorkbasketDefinitionController( - WorkbasketService workbasketService, - WorkbasketDefinitionResourceAssembler workbasketDefinitionAssembler) { - this.workbasketService = workbasketService; - this.workbasketDefinitionAssembler = workbasketDefinitionAssembler; + WorkbasketDefinitionController( + WorkbasketService workbasketService, + WorkbasketDefinitionResourceAssembler workbasketDefinitionAssembler) { + this.workbasketService = workbasketService; + this.workbasketDefinitionAssembler = workbasketDefinitionAssembler; + } + + @GetMapping(path = Mapping.URL_WORKBASKETDEFIITIONS) + @Transactional(readOnly = true, rollbackFor = Exception.class) + public ResponseEntity> exportWorkbaskets( + @RequestParam(required = false) String domain) + throws NotAuthorizedException, WorkbasketNotFoundException { + LOGGER.debug("Entry to exportWorkbaskets(domain= {})", domain); + WorkbasketQuery workbasketQuery = workbasketService.createWorkbasketQuery(); + List workbasketSummaryList = + domain != null ? workbasketQuery.domainIn(domain).list() : workbasketQuery.list(); + List basketExports = new ArrayList<>(); + for (WorkbasketSummary summary : workbasketSummaryList) { + Workbasket workbasket = workbasketService.getWorkbasket(summary.getId()); + basketExports.add(workbasketDefinitionAssembler.toResource(workbasket)); } - @GetMapping(path = Mapping.URL_WORKBASKETDEFIITIONS) - @Transactional(readOnly = true, rollbackFor = Exception.class) - public ResponseEntity> exportWorkbaskets( - @RequestParam(required = false) String domain) - throws NotAuthorizedException, WorkbasketNotFoundException { - LOGGER.debug("Entry to exportWorkbaskets(domain= {})", domain); - WorkbasketQuery workbasketQuery = workbasketService.createWorkbasketQuery(); - List workbasketSummaryList = domain != null - ? workbasketQuery.domainIn(domain).list() - : workbasketQuery.list(); - List basketExports = new ArrayList<>(); - for (WorkbasketSummary summary : workbasketSummaryList) { - Workbasket workbasket = workbasketService.getWorkbasket(summary.getId()); - basketExports.add(workbasketDefinitionAssembler.toResource(workbasket)); - } - - ResponseEntity> response = ResponseEntity.ok(basketExports); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exit from exportWorkbaskets(), returning {}", response); - } - - return response; + ResponseEntity> response = ResponseEntity.ok(basketExports); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Exit from exportWorkbaskets(), returning {}", response); } - /** - * This method imports a list of {@link WorkbasketDefinitionResource}. This does not exactly match the REST - * norm, but we want to have an option to import all settings at once. When a logical equal (key and domain are - * equal) workbasket already exists an update will be executed. Otherwise a new workbasket will be created. - * - * @param file - * the list of workbasket definitions which will be imported to the current system. - * @return Return answer is determined by the status code: 200 - all good 400 - list state error (referring to non - * existing id's) 401 - not authorized - * @throws IOException - * if multipart file cannot be parsed. - * @throws NotAuthorizedException - * if the user is not authorized. - * @throws DomainNotFoundException - * if domain information is incorrect. - * @throws InvalidWorkbasketException - * if workbasket has invalid information. - * @throws WorkbasketAlreadyExistException - * if workbasket already exists when trying to create a new one. - * @throws WorkbasketNotFoundException - * if do not exists a workbasket in the system with the used id. - * @throws InvalidArgumentException - * if authorization information in workbaskets definitions is incorrect. - */ - @PostMapping(path = Mapping.URL_WORKBASKETDEFIITIONS) - @Transactional(rollbackFor = Exception.class) - public ResponseEntity importWorkbaskets(@RequestParam("file") MultipartFile file) - throws IOException, NotAuthorizedException, DomainNotFoundException, InvalidWorkbasketException, - WorkbasketAlreadyExistException, WorkbasketNotFoundException, InvalidArgumentException { - LOGGER.debug("Entry to importWorkbaskets()"); - ObjectMapper mapper = new ObjectMapper(); - mapper.enable(SerializationFeature.INDENT_OUTPUT); - mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); - List definitions = mapper.readValue(file.getInputStream(), - new TypeReference>() { + return response; + } - }); + /** + * This method imports a list of {@link WorkbasketDefinitionResource}. This does not + * exactly match the REST norm, but we want to have an option to import all settings at once. When + * a logical equal (key and domain are equal) workbasket already exists an update will be + * executed. Otherwise a new workbasket will be created. + * + * @param file the list of workbasket definitions which will be imported to the current system. + * @return Return answer is determined by the status code: 200 - all good 400 - list state error + * (referring to non existing id's) 401 - not authorized + * @throws IOException if multipart file cannot be parsed. + * @throws NotAuthorizedException if the user is not authorized. + * @throws DomainNotFoundException if domain information is incorrect. + * @throws InvalidWorkbasketException if workbasket has invalid information. + * @throws WorkbasketAlreadyExistException if workbasket already exists when trying to create a + * new one. + * @throws WorkbasketNotFoundException if do not exists a workbasket in the system with the used + * id. + * @throws InvalidArgumentException if authorization information in workbaskets definitions is + * incorrect. + */ + @PostMapping(path = Mapping.URL_WORKBASKETDEFIITIONS) + @Transactional(rollbackFor = Exception.class) + public ResponseEntity importWorkbaskets(@RequestParam("file") MultipartFile file) + throws IOException, NotAuthorizedException, DomainNotFoundException, + InvalidWorkbasketException, WorkbasketAlreadyExistException, WorkbasketNotFoundException, + InvalidArgumentException { + LOGGER.debug("Entry to importWorkbaskets()"); + ObjectMapper mapper = new ObjectMapper(); + mapper.enable(SerializationFeature.INDENT_OUTPUT); + mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + List definitions = + mapper.readValue( + file.getInputStream(), new TypeReference>() {}); - // key: logical ID - // value: system ID (in database) - Map systemIds = workbasketService.createWorkbasketQuery() - .list() - .stream() + // key: logical ID + // value: system ID (in database) + Map systemIds = + workbasketService.createWorkbasketQuery().list().stream() .collect(Collectors.toMap(this::logicalId, WorkbasketSummary::getId)); - checkForDuplicates(definitions); + checkForDuplicates(definitions); - // key: old system ID - // value: system ID - Map idConversion = new HashMap<>(); + // key: old system ID + // value: system ID + Map idConversion = new HashMap<>(); - // STEP 1: update or create workbaskets from the import - for (WorkbasketDefinitionResource definition : definitions) { - Workbasket importedWb = workbasketDefinitionAssembler.toModel(definition.getWorkbasket()); - Workbasket workbasket; - if (systemIds.containsKey(logicalId(importedWb))) { - workbasket = workbasketService.updateWorkbasket(importedWb); - } else { - Workbasket wbWithoutId = removeId(importedWb); - workbasket = workbasketService.createWorkbasket(wbWithoutId); - } + // STEP 1: update or create workbaskets from the import + for (WorkbasketDefinitionResource definition : definitions) { + Workbasket importedWb = workbasketDefinitionAssembler.toModel(definition.getWorkbasket()); + Workbasket workbasket; + if (systemIds.containsKey(logicalId(importedWb))) { + workbasket = workbasketService.updateWorkbasket(importedWb); + } else { + Workbasket wbWithoutId = removeId(importedWb); + workbasket = workbasketService.createWorkbasket(wbWithoutId); + } - // Since we would have a n² runtime when doing a lookup and updating the access items we decided to - // simply delete all existing accessItems and create new ones. - for (WorkbasketAccessItem accessItem : workbasketService.getWorkbasketAccessItems(workbasket.getId())) { - workbasketService.deleteWorkbasketAccessItem(accessItem.getId()); - } - for (WorkbasketAccessItem authorization : definition.getAuthorizations()) { - workbasketService.createWorkbasketAccessItem(authorization); - } - idConversion.put(importedWb.getId(), workbasket.getId()); + // Since we would have a n² runtime when doing a lookup and updating the access items we + // decided to + // simply delete all existing accessItems and create new ones. + for (WorkbasketAccessItem accessItem : + workbasketService.getWorkbasketAccessItems(workbasket.getId())) { + workbasketService.deleteWorkbasketAccessItem(accessItem.getId()); + } + for (WorkbasketAccessItem authorization : definition.getAuthorizations()) { + workbasketService.createWorkbasketAccessItem(authorization); + } + idConversion.put(importedWb.getId(), workbasket.getId()); + } + + // STEP 2: update distribution targets + // This can not be done in step 1 because the system IDs are only known after step 1 + for (WorkbasketDefinitionResource definition : definitions) { + List distributionTargets = new ArrayList<>(); + for (String oldId : definition.getDistributionTargets()) { + if (idConversion.containsKey(oldId)) { + distributionTargets.add(idConversion.get(oldId)); + } else { + throw new InvalidWorkbasketException( + String.format( + "invalid import state: Workbasket '%s' does not exist in the given import list", + oldId)); } + } - // STEP 2: update distribution targets - // This can not be done in step 1 because the system IDs are only known after step 1 - for (WorkbasketDefinitionResource definition : definitions) { - List distributionTargets = new ArrayList<>(); - for (String oldId : definition.getDistributionTargets()) { - if (idConversion.containsKey(oldId)) { - distributionTargets.add(idConversion.get(oldId)); - } else { - throw new InvalidWorkbasketException( - String.format( - "invalid import state: Workbasket '%s' does not exist in the given import list", - oldId)); - } - } - - workbasketService.setDistributionTargets( - // no verification necessary since the workbasket was already imported in step 1. - idConversion.get(definition.getWorkbasket().getWorkbasketId()), distributionTargets); - } - ResponseEntity response = ResponseEntity.noContent().build(); - LOGGER.debug("Exit from importWorkbaskets(), returning {}", response); - return response; + workbasketService.setDistributionTargets( + // no verification necessary since the workbasket was already imported in step 1. + idConversion.get(definition.getWorkbasket().getWorkbasketId()), distributionTargets); } + ResponseEntity response = ResponseEntity.noContent().build(); + LOGGER.debug("Exit from importWorkbaskets(), returning {}", response); + return response; + } - private Workbasket removeId(Workbasket importedWb) { - WorkbasketResource wbRes = new WorkbasketResource(importedWb); - wbRes.setWorkbasketId(null); - return workbasketDefinitionAssembler.toModel(wbRes); - } + private Workbasket removeId(Workbasket importedWb) { + WorkbasketResource wbRes = new WorkbasketResource(importedWb); + wbRes.setWorkbasketId(null); + return workbasketDefinitionAssembler.toModel(wbRes); + } - private void checkForDuplicates(List definitions) { - List identifiers = new ArrayList<>(); - Set duplicates = new HashSet<>(); - for (WorkbasketDefinitionResource definition : definitions) { - String identifier = logicalId(workbasketDefinitionAssembler.toModel(definition.getWorkbasket())); - if (identifiers.contains(identifier)) { - duplicates.add(identifier); - } else { - identifiers.add(identifier); - } - } - if (!duplicates.isEmpty()) { - throw new DuplicateKeyException( - "The 'key|domain'-identifier is not unique for the value(s): " + duplicates.toString()); - } + private void checkForDuplicates(List definitions) { + List identifiers = new ArrayList<>(); + Set duplicates = new HashSet<>(); + for (WorkbasketDefinitionResource definition : definitions) { + String identifier = + logicalId(workbasketDefinitionAssembler.toModel(definition.getWorkbasket())); + if (identifiers.contains(identifier)) { + duplicates.add(identifier); + } else { + identifiers.add(identifier); + } } + if (!duplicates.isEmpty()) { + throw new DuplicateKeyException( + "The 'key|domain'-identifier is not unique for the value(s): " + duplicates.toString()); + } + } - private String logicalId(WorkbasketSummary workbasket) { - return logicalId(workbasket.getKey(), workbasket.getDomain()); - } + private String logicalId(WorkbasketSummary workbasket) { + return logicalId(workbasket.getKey(), workbasket.getDomain()); + } - private String logicalId(Workbasket workbasket) { - return logicalId(workbasket.getKey(), workbasket.getDomain()); - } + private String logicalId(Workbasket workbasket) { + return logicalId(workbasket.getKey(), workbasket.getDomain()); + } - private String logicalId(String key, String domain) { - return key + "|" + domain; - } + private String logicalId(String key, String domain) { + return key + "|" + domain; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/AbstractRessourcesAssembler.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/AbstractRessourcesAssembler.java index ee86012b6..74c2e0497 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/AbstractRessourcesAssembler.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/AbstractRessourcesAssembler.java @@ -1,9 +1,7 @@ package pro.taskana.rest.resource; import java.util.Map; - import javax.servlet.http.HttpServletRequest; - import org.springframework.hateoas.Link; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; @@ -11,53 +9,54 @@ import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import org.springframework.web.util.UriComponentsBuilder; /** - * Abstract resources assembler for taskana REST controller with pageable resources. This method is deprecated, it can - * be removed after fixing taskana-simple-history references + * Abstract resources assembler for taskana REST controller with pageable resources. This method is + * deprecated, it can be removed after fixing taskana-simple-history references */ -//TODO: @Deprecated +// TODO: @Deprecated public abstract class AbstractRessourcesAssembler { + UriComponentsBuilder original = getBuilderForOriginalUri(); + + public AbstractRessourcesAssembler() {} + + protected static UriComponentsBuilder getBuilderForOriginalUri() { + HttpServletRequest request = + ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); + UriComponentsBuilder baseUri = + ServletUriComponentsBuilder.fromServletMapping(request).path(request.getRequestURI()); + + for (Map.Entry entry : request.getParameterMap().entrySet()) { + String[] var4 = entry.getValue(); + for (String value : var4) { + baseUri.queryParam(entry.getKey(), value); + } + } + + return baseUri; + } + + protected PagedResources addPageLinks( + PagedResources pagedResources, PagedResources.PageMetadata pageMetadata) { UriComponentsBuilder original = getBuilderForOriginalUri(); - - public AbstractRessourcesAssembler() { + pagedResources.add( + (new Link(original.replaceQueryParam("page", 1).toUriString())).withRel("first")); + pagedResources.add( + (new Link(original.replaceQueryParam("page", pageMetadata.getTotalPages()).toUriString())) + .withRel("last")); + if (pageMetadata.getNumber() > 1L) { + pagedResources.add( + (new Link( + original.replaceQueryParam("page", pageMetadata.getNumber() - 1L).toUriString())) + .withRel("prev")); } - protected static UriComponentsBuilder getBuilderForOriginalUri() { - HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) - .getRequest(); - UriComponentsBuilder baseUri = ServletUriComponentsBuilder.fromServletMapping(request) - .path(request.getRequestURI()); - - for (Map.Entry entry : request.getParameterMap().entrySet()) { - String[] var4 = entry.getValue(); - for (String value : var4) { - baseUri.queryParam(entry.getKey(), value); - } - } - - return baseUri; + if (pageMetadata.getNumber() < pageMetadata.getTotalPages()) { + pagedResources.add( + (new Link( + original.replaceQueryParam("page", pageMetadata.getNumber() + 1L).toUriString())) + .withRel("next")); } - protected PagedResources addPageLinks(PagedResources pagedResources, - PagedResources.PageMetadata pageMetadata) { - UriComponentsBuilder original = getBuilderForOriginalUri(); - pagedResources.add( - (new Link(original.replaceQueryParam("page", 1).toUriString())).withRel("first")); - pagedResources.add((new Link( - original.replaceQueryParam("page", pageMetadata.getTotalPages()).toUriString())).withRel( - "last")); - if (pageMetadata.getNumber() > 1L) { - pagedResources.add((new Link( - original.replaceQueryParam("page", pageMetadata.getNumber() - 1L) - .toUriString())).withRel("prev")); - } - - if (pageMetadata.getNumber() < pageMetadata.getTotalPages()) { - pagedResources.add((new Link( - original.replaceQueryParam("page", pageMetadata.getNumber() + 1L) - .toUriString())).withRel("next")); - } - - return pagedResources; - } + return pagedResources; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/AccessIdResource.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/AccessIdResource.java index 3cb17c4dc..f35b8d038 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/AccessIdResource.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/AccessIdResource.java @@ -7,37 +7,34 @@ package pro.taskana.rest.resource; */ public class AccessIdResource { - private String name; - private String accessId; + private String name; + private String accessId; - public AccessIdResource() { + public AccessIdResource() {} - } + public AccessIdResource(String name, String accessId) { + this.accessId = accessId; + this.name = name; + } - public AccessIdResource(String name, String accessId) { - this.accessId = accessId; - this.name = name; - } + public String getAccessId() { + return accessId; + } - public String getAccessId() { - return accessId; - } + public void setAccessId(String accessId) { + this.accessId = accessId; + } - public void setAccessId(String accessId) { - this.accessId = accessId; - } + public String getName() { + return name; + } - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public String toString() { - return "AccessIdResource [" + "name=" + this.name + ", accessId=" + this.accessId + "]"; - } + public void setName(String name) { + this.name = name; + } + @Override + public String toString() { + return "AccessIdResource [" + "name=" + this.name + ", accessId=" + this.accessId + "]"; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/AttachmentResource.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/AttachmentResource.java index 341675485..5cfdabd94 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/AttachmentResource.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/AttachmentResource.java @@ -2,126 +2,131 @@ package pro.taskana.rest.resource; import java.util.HashMap; import java.util.Map; - import org.springframework.hateoas.ResourceSupport; import pro.taskana.Attachment; import pro.taskana.ObjectReference; -/** - * Resource class for {@link pro.taskana.Attachment}. - */ +/** Resource class for {@link pro.taskana.Attachment}. */ public class AttachmentResource extends ResourceSupport { - private String attachmentId; - private String taskId; - private String created; - private String modified; - private ClassificationSummaryResource classificationSummaryResource; - private ObjectReference objectReference; - private String channel; - private String received; + private String attachmentId; + private String taskId; + private String created; + private String modified; + private ClassificationSummaryResource classificationSummaryResource; + private ObjectReference objectReference; + private String channel; + private String received; + private Map customAttributes = new HashMap(); - public AttachmentResource() { - } + public AttachmentResource() {} - public AttachmentResource(Attachment attachment) { - this.attachmentId = attachment.getId(); - this.taskId = attachment.getTaskId(); - this.created = attachment.getCreated() != null ? attachment.getCreated().toString() : null; - this.modified = attachment.getModified() != null ? attachment.getModified().toString() : null; - this.classificationSummaryResource = new ClassificationSummaryResource(attachment.getClassificationSummary()); - this.objectReference = attachment.getObjectReference(); - this.channel = attachment.getChannel(); - this.received = attachment.getReceived() != null ? attachment.getReceived().toString() : null; - this.customAttributes = attachment.getCustomAttributes(); - } + public AttachmentResource(Attachment attachment) { + this.attachmentId = attachment.getId(); + this.taskId = attachment.getTaskId(); + this.created = attachment.getCreated() != null ? attachment.getCreated().toString() : null; + this.modified = attachment.getModified() != null ? attachment.getModified().toString() : null; + this.classificationSummaryResource = + new ClassificationSummaryResource(attachment.getClassificationSummary()); + this.objectReference = attachment.getObjectReference(); + this.channel = attachment.getChannel(); + this.received = attachment.getReceived() != null ? attachment.getReceived().toString() : null; + this.customAttributes = attachment.getCustomAttributes(); + } - public String getCreated() { - return created; - } + public String getCreated() { + return created; + } - public void setCreated(String created) { - this.created = created; - } + public void setCreated(String created) { + this.created = created; + } - public String getModified() { - return modified; - } + public String getModified() { + return modified; + } - public void setModified(String modified) { - this.modified = modified; - } + public void setModified(String modified) { + this.modified = modified; + } - public String getReceived() { - return received; - } + public String getReceived() { + return received; + } - public void setReceived(String received) { - this.received = received; - } + public void setReceived(String received) { + this.received = received; + } - private Map customAttributes = new HashMap(); + public String getAttachmentId() { + return attachmentId; + } - public String getAttachmentId() { - return attachmentId; - } + public void setAttachmentId(String attachmentId) { + this.attachmentId = attachmentId; + } - public void setAttachmentId(String attachmentId) { - this.attachmentId = attachmentId; - } + public String getTaskId() { + return taskId; + } - public String getTaskId() { - return taskId; - } + public void setTaskId(String taskId) { + this.taskId = taskId; + } - public void setTaskId(String taskId) { - this.taskId = taskId; - } + public ClassificationSummaryResource getClassificationSummary() { + return classificationSummaryResource; + } - public ClassificationSummaryResource getClassificationSummary() { - return classificationSummaryResource; - } + public void setClassificationSummary( + ClassificationSummaryResource classificationSummaryResource) { + this.classificationSummaryResource = classificationSummaryResource; + } - public void setClassificationSummary(ClassificationSummaryResource classificationSummaryResource) { - this.classificationSummaryResource = classificationSummaryResource; - } + public ObjectReference getObjectReference() { + return objectReference; + } - public ObjectReference getObjectReference() { - return objectReference; - } + public void setObjectReference(ObjectReference objectReference) { + this.objectReference = objectReference; + } - public void setObjectReference(ObjectReference objectReference) { - this.objectReference = objectReference; - } + public String getChannel() { + return channel; + } - public String getChannel() { - return channel; - } + public void setChannel(String channel) { + this.channel = channel; + } - public void setChannel(String channel) { - this.channel = channel; - } + public Map getCustomAttributes() { + return customAttributes; + } - public Map getCustomAttributes() { - return customAttributes; - } + public void setCustomAttributes(Map customAttributes) { + this.customAttributes = customAttributes; + } - public void setCustomAttributes(Map customAttributes) { - this.customAttributes = customAttributes; - } - - @Override - public String toString() { - return "AttachmentResource [" - + "attachmentId= " + this.attachmentId - + "taskId= " + this.taskId - + "created= " + this.created - + "modified= " + this.modified - + "classificationSummaryResource= " + this.classificationSummaryResource - + "objectReference= " + this.objectReference - + "channel= " + this.channel - + "received= " + this.received - + "]"; - } + @Override + public String toString() { + return "AttachmentResource [" + + "attachmentId= " + + this.attachmentId + + "taskId= " + + this.taskId + + "created= " + + this.created + + "modified= " + + this.modified + + "classificationSummaryResource= " + + this.classificationSummaryResource + + "objectReference= " + + this.objectReference + + "channel= " + + this.channel + + "received= " + + this.received + + "]"; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/AttachmentResourceAssembler.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/AttachmentResourceAssembler.java index 44ce786b4..c235e28a5 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/AttachmentResourceAssembler.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/AttachmentResourceAssembler.java @@ -4,7 +4,6 @@ import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import java.util.List; import java.util.stream.Collectors; - import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.mvc.ResourceAssemblerSupport; @@ -15,37 +14,37 @@ import pro.taskana.TaskService; import pro.taskana.impl.AttachmentImpl; import pro.taskana.rest.AttachmentController; -/** - * Resource assembler for {@link AttachmentResource}. - */ +/** Resource assembler for {@link AttachmentResource}. */ @Component -public class AttachmentResourceAssembler extends ResourceAssemblerSupport { +public class AttachmentResourceAssembler + extends ResourceAssemblerSupport { - @Autowired - private TaskService taskService; + @Autowired private TaskService taskService; - @Autowired - private ClassificationSummaryResourceAssembler classificationAssembler; + @Autowired private ClassificationSummaryResourceAssembler classificationAssembler; - public AttachmentResourceAssembler() { - super(AttachmentController.class, AttachmentResource.class); - } + public AttachmentResourceAssembler() { + super(AttachmentController.class, AttachmentResource.class); + } - @Override - public AttachmentResource toResource(Attachment attachment) { - AttachmentResource resource = new AttachmentResource(attachment); - resource.add(linkTo(AttachmentController.class).slash(attachment.getId()).withSelfRel()); - return resource; - } + @Override + public AttachmentResource toResource(Attachment attachment) { + AttachmentResource resource = new AttachmentResource(attachment); + resource.add(linkTo(AttachmentController.class).slash(attachment.getId()).withSelfRel()); + return resource; + } - public List toModel(List resources) { - return resources.stream().map(attachmentResource -> { - AttachmentImpl attachment = (AttachmentImpl) taskService.newAttachment(); - BeanUtils.copyProperties(attachmentResource, attachment); - attachment.setId(attachmentResource.getAttachmentId()); - attachment.setClassificationSummary( - classificationAssembler.toModel(attachmentResource.getClassificationSummary())); - return attachment; - }).collect(Collectors.toList()); - } + public List toModel(List resources) { + return resources.stream() + .map( + attachmentResource -> { + AttachmentImpl attachment = (AttachmentImpl) taskService.newAttachment(); + BeanUtils.copyProperties(attachmentResource, attachment); + attachment.setId(attachmentResource.getAttachmentId()); + attachment.setClassificationSummary( + classificationAssembler.toModel(attachmentResource.getClassificationSummary())); + return attachment; + }) + .collect(Collectors.toList()); + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/AttachmentSummaryResource.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/AttachmentSummaryResource.java index 0333d28e3..61e8a285e 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/AttachmentSummaryResource.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/AttachmentSummaryResource.java @@ -5,110 +5,119 @@ import org.springframework.hateoas.ResourceSupport; import pro.taskana.AttachmentSummary; import pro.taskana.ObjectReference; -/** - * Resource class for {@link pro.taskana.AttachmentSummary}. - */ +/** Resource class for {@link pro.taskana.AttachmentSummary}. */ public class AttachmentSummaryResource extends ResourceSupport { - private String attachmentId; - private String taskId; - private String created; - private String modified; - private ClassificationSummaryResource classificationSummaryResource; - private ObjectReference objectReference; - private String channel; - private String received; + private String attachmentId; + private String taskId; + private String created; + private String modified; + private ClassificationSummaryResource classificationSummaryResource; + private ObjectReference objectReference; + private String channel; + private String received; - AttachmentSummaryResource() { - } + AttachmentSummaryResource() {} - public AttachmentSummaryResource(AttachmentSummary attachmentSummary) { - this.attachmentId = attachmentSummary.getId(); - this.taskId = attachmentSummary.getTaskId(); - this.created = attachmentSummary.getCreated() != null ? attachmentSummary.getCreated().toString() : null; - this.modified = attachmentSummary.getModified() != null ? attachmentSummary.getModified().toString() : null; - this.classificationSummaryResource = new ClassificationSummaryResource( - attachmentSummary.getClassificationSummary()); - this.objectReference = attachmentSummary.getObjectReference(); - this.channel = attachmentSummary.getChannel(); - this.received = attachmentSummary.getReceived() != null ? attachmentSummary.getReceived().toString() : null; - } + public AttachmentSummaryResource(AttachmentSummary attachmentSummary) { + this.attachmentId = attachmentSummary.getId(); + this.taskId = attachmentSummary.getTaskId(); + this.created = + attachmentSummary.getCreated() != null ? attachmentSummary.getCreated().toString() : null; + this.modified = + attachmentSummary.getModified() != null ? attachmentSummary.getModified().toString() : null; + this.classificationSummaryResource = + new ClassificationSummaryResource(attachmentSummary.getClassificationSummary()); + this.objectReference = attachmentSummary.getObjectReference(); + this.channel = attachmentSummary.getChannel(); + this.received = + attachmentSummary.getReceived() != null ? attachmentSummary.getReceived().toString() : null; + } - public String getAttachmentId() { - return attachmentId; - } + public String getAttachmentId() { + return attachmentId; + } - public void setAttachmentId(String attachmentId) { - this.attachmentId = attachmentId; - } + public void setAttachmentId(String attachmentId) { + this.attachmentId = attachmentId; + } - public String getTaskId() { - return taskId; - } + public String getTaskId() { + return taskId; + } - public void setTaskId(String taskId) { - this.taskId = taskId; - } + public void setTaskId(String taskId) { + this.taskId = taskId; + } - public String getCreated() { - return created; - } + public String getCreated() { + return created; + } - public void setCreated(String created) { - this.created = created; - } + public void setCreated(String created) { + this.created = created; + } - public String getModified() { - return modified; - } + public String getModified() { + return modified; + } - public void setModified(String modified) { - this.modified = modified; - } + public void setModified(String modified) { + this.modified = modified; + } - public ClassificationSummaryResource getClassificationSummary() { - return classificationSummaryResource; - } + public ClassificationSummaryResource getClassificationSummary() { + return classificationSummaryResource; + } - public void setClassificationSummary(ClassificationSummaryResource classificationSummaryResource) { - this.classificationSummaryResource = classificationSummaryResource; - } + public void setClassificationSummary( + ClassificationSummaryResource classificationSummaryResource) { + this.classificationSummaryResource = classificationSummaryResource; + } - public ObjectReference getObjectReference() { - return objectReference; - } + public ObjectReference getObjectReference() { + return objectReference; + } - public void setObjectReference(ObjectReference objectReference) { - this.objectReference = objectReference; - } + public void setObjectReference(ObjectReference objectReference) { + this.objectReference = objectReference; + } - public String getChannel() { - return channel; - } + public String getChannel() { + return channel; + } - public void setChannel(String channel) { - this.channel = channel; - } + public void setChannel(String channel) { + this.channel = channel; + } - public String getReceived() { - return received; - } + public String getReceived() { + return received; + } - public void setReceived(String received) { - this.received = received; - } + public void setReceived(String received) { + this.received = received; + } - @Override - public String toString() { - return "AttachmentSummaryResource [" - + "attachmentId= " + this.attachmentId - + "taskId= " + this.taskId - + "created= " + this.created - + "modified= " + this.modified - + "classificationSummaryResource= " + this.classificationSummaryResource - + "objectReference= " + this.objectReference - + "channel= " + this.channel - + "received= " + this.received - + "]"; - } + @Override + public String toString() { + return "AttachmentSummaryResource [" + + "attachmentId= " + + this.attachmentId + + "taskId= " + + this.taskId + + "created= " + + this.created + + "modified= " + + this.modified + + "classificationSummaryResource= " + + this.classificationSummaryResource + + "objectReference= " + + this.objectReference + + "channel= " + + this.channel + + "received= " + + this.received + + "]"; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/AttachmentSummaryResourceAssembler.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/AttachmentSummaryResourceAssembler.java index 17a516ab6..92430a5c4 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/AttachmentSummaryResourceAssembler.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/AttachmentSummaryResourceAssembler.java @@ -1,32 +1,28 @@ package pro.taskana.rest.resource; import java.util.List; - import org.springframework.hateoas.mvc.ResourceAssemblerSupport; import org.springframework.stereotype.Component; import pro.taskana.AttachmentSummary; import pro.taskana.rest.AttachmentController; -/** - * Resource assembler for {@link AttachmentSummaryResource}. - */ +/** Resource assembler for {@link AttachmentSummaryResource}. */ @Component public class AttachmentSummaryResourceAssembler extends ResourceAssemblerSupport { - public AttachmentSummaryResourceAssembler() { - super(AttachmentController.class, AttachmentSummaryResource.class); - } + public AttachmentSummaryResourceAssembler() { + super(AttachmentController.class, AttachmentSummaryResource.class); + } - @Override - public AttachmentSummaryResource toResource(AttachmentSummary attachmentSummary) { - return new AttachmentSummaryResource(attachmentSummary); - } + @Override + public AttachmentSummaryResource toResource(AttachmentSummary attachmentSummary) { + return new AttachmentSummaryResource(attachmentSummary); + } - public List toResources( - List attachmentSummaries) { - List resources = super.toResources(attachmentSummaries); - return resources; - } + public List toResources(List attachmentSummaries) { + List resources = super.toResources(attachmentSummaries); + return resources; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ClassificationResource.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ClassificationResource.java index f44149a7b..7f259a464 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ClassificationResource.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ClassificationResource.java @@ -1,264 +1,299 @@ package pro.taskana.rest.resource; import javax.validation.constraints.NotNull; - import org.springframework.hateoas.ResourceSupport; import pro.taskana.Classification; -/** - * Resource class for {@link pro.taskana.Classification}. - */ +/** Resource class for {@link pro.taskana.Classification}. */ public class ClassificationResource extends ResourceSupport { - @NotNull - public String classificationId; - @NotNull - public String key; - public String parentId; - public String parentKey; - public String category; - public String type; - public String domain; - public Boolean isValidInDomain; - public String created; // ISO-8601 - public String modified; // ISO-8601 - public String name; - public String description; - public int priority; - public String serviceLevel; // PddDThhHmmM - public String applicationEntryPoint; - public String custom1; - public String custom2; - public String custom3; - public String custom4; - public String custom5; - public String custom6; - public String custom7; - public String custom8; + @NotNull public String classificationId; + @NotNull public String key; + public String parentId; + public String parentKey; + public String category; + public String type; + public String domain; + public Boolean isValidInDomain; + public String created; // ISO-8601 + public String modified; // ISO-8601 + public String name; + public String description; + public int priority; + public String serviceLevel; // PddDThhHmmM + public String applicationEntryPoint; + public String custom1; + public String custom2; + public String custom3; + public String custom4; + public String custom5; + public String custom6; + public String custom7; + public String custom8; - public ClassificationResource() { - } + public ClassificationResource() {} - public ClassificationResource(Classification classification) { - this.classificationId = classification.getId(); - this.key = classification.getKey(); - this.parentId = classification.getParentId(); - this.parentKey = classification.getParentKey(); - this.category = classification.getCategory(); - this.type = classification.getType(); - this.domain = classification.getDomain(); - this.isValidInDomain = classification.getIsValidInDomain(); - this.created = classification.getCreated() != null ? classification.getCreated().toString() : null; - this.modified = classification.getModified() != null ? classification.getModified().toString() : null; - this.name = classification.getName(); - this.description = classification.getDescription(); - this.priority = classification.getPriority(); - this.serviceLevel = classification.getServiceLevel(); - this.applicationEntryPoint = classification.getApplicationEntryPoint(); - this.custom1 = classification.getCustom1(); - this.custom2 = classification.getCustom2(); - this.custom3 = classification.getCustom3(); - this.custom4 = classification.getCustom4(); - this.custom5 = classification.getCustom5(); - this.custom6 = classification.getCustom6(); - this.custom7 = classification.getCustom7(); - this.custom8 = classification.getCustom8(); - } + public ClassificationResource(Classification classification) { + this.classificationId = classification.getId(); + this.key = classification.getKey(); + this.parentId = classification.getParentId(); + this.parentKey = classification.getParentKey(); + this.category = classification.getCategory(); + this.type = classification.getType(); + this.domain = classification.getDomain(); + this.isValidInDomain = classification.getIsValidInDomain(); + this.created = + classification.getCreated() != null ? classification.getCreated().toString() : null; + this.modified = + classification.getModified() != null ? classification.getModified().toString() : null; + this.name = classification.getName(); + this.description = classification.getDescription(); + this.priority = classification.getPriority(); + this.serviceLevel = classification.getServiceLevel(); + this.applicationEntryPoint = classification.getApplicationEntryPoint(); + this.custom1 = classification.getCustom1(); + this.custom2 = classification.getCustom2(); + this.custom3 = classification.getCustom3(); + this.custom4 = classification.getCustom4(); + this.custom5 = classification.getCustom5(); + this.custom6 = classification.getCustom6(); + this.custom7 = classification.getCustom7(); + this.custom8 = classification.getCustom8(); + } - public String getClassificationId() { - return classificationId; - } + public String getClassificationId() { + return classificationId; + } - public void setClassificationId(String classificationId) { - this.classificationId = classificationId; - } + public void setClassificationId(String classificationId) { + this.classificationId = classificationId; + } - public String getKey() { - return key; - } + public String getKey() { + return key; + } - public void setKey(String key) { - this.key = key; - } + public void setKey(String key) { + this.key = key; + } - public String getParentId() { - return parentId; - } + public String getParentId() { + return parentId; + } - public void setParentId(String parentId) { - this.parentId = parentId; - } + public void setParentId(String parentId) { + this.parentId = parentId; + } - public String getParentKey() { - return parentKey; - } + public String getParentKey() { + return parentKey; + } - public void setParentKey(String parentKey) { - this.parentKey = parentKey; - } + public void setParentKey(String parentKey) { + this.parentKey = parentKey; + } - public String getCategory() { - return category; - } + public String getCategory() { + return category; + } - public void setCategory(String category) { - this.category = category; - } + public void setCategory(String category) { + this.category = category; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public String getDomain() { - return domain; - } + public String getDomain() { + return domain; + } - public void setDomain(String domain) { - this.domain = domain; - } + public void setDomain(String domain) { + this.domain = domain; + } - public Boolean getIsValidInDomain() { - return isValidInDomain; - } + public Boolean getIsValidInDomain() { + return isValidInDomain; + } - public void setIsValidInDomain(Boolean validInDomain) { - isValidInDomain = validInDomain; - } + public void setIsValidInDomain(Boolean validInDomain) { + isValidInDomain = validInDomain; + } - public String getCreated() { - return created; - } + public String getCreated() { + return created; + } - public void setCreated(String created) { - this.created = created; - } + public void setCreated(String created) { + this.created = created; + } - public String getModified() { - return modified; - } + public String getModified() { + return modified; + } - public void setModified(String modified) { - this.modified = modified; - } + public void setModified(String modified) { + this.modified = modified; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public int getPriority() { - return priority; - } + public int getPriority() { + return priority; + } - public void setPriority(int priority) { - this.priority = priority; - } + public void setPriority(int priority) { + this.priority = priority; + } - public String getServiceLevel() { - return serviceLevel; - } + public String getServiceLevel() { + return serviceLevel; + } - public void setServiceLevel(String serviceLevel) { - this.serviceLevel = serviceLevel; - } + public void setServiceLevel(String serviceLevel) { + this.serviceLevel = serviceLevel; + } - public String getApplicationEntryPoint() { - return applicationEntryPoint; - } + public String getApplicationEntryPoint() { + return applicationEntryPoint; + } - public void setApplicationEntryPoint(String applicationEntryPoint) { - this.applicationEntryPoint = applicationEntryPoint; - } + public void setApplicationEntryPoint(String applicationEntryPoint) { + this.applicationEntryPoint = applicationEntryPoint; + } - public String getCustom1() { - return custom1; - } + public String getCustom1() { + return custom1; + } - public void setCustom1(String custom1) { - this.custom1 = custom1; - } + public void setCustom1(String custom1) { + this.custom1 = custom1; + } - public String getCustom2() { - return custom2; - } + public String getCustom2() { + return custom2; + } - public void setCustom2(String custom2) { - this.custom2 = custom2; - } + public void setCustom2(String custom2) { + this.custom2 = custom2; + } - public String getCustom3() { - return custom3; - } + public String getCustom3() { + return custom3; + } - public void setCustom3(String custom3) { - this.custom3 = custom3; - } + public void setCustom3(String custom3) { + this.custom3 = custom3; + } - public String getCustom4() { - return custom4; - } + public String getCustom4() { + return custom4; + } - public void setCustom4(String custom4) { - this.custom4 = custom4; - } + public void setCustom4(String custom4) { + this.custom4 = custom4; + } - public String getCustom5() { - return custom5; - } + public String getCustom5() { + return custom5; + } - public void setCustom5(String custom5) { - this.custom5 = custom5; - } + public void setCustom5(String custom5) { + this.custom5 = custom5; + } - public String getCustom6() { - return custom6; - } + public String getCustom6() { + return custom6; + } - public void setCustom6(String custom6) { - this.custom6 = custom6; - } + public void setCustom6(String custom6) { + this.custom6 = custom6; + } - public String getCustom7() { - return custom7; - } + public String getCustom7() { + return custom7; + } - public void setCustom7(String custom7) { - this.custom7 = custom7; - } + public void setCustom7(String custom7) { + this.custom7 = custom7; + } - public String getCustom8() { - return custom8; - } + public String getCustom8() { + return custom8; + } - public void setCustom8(String custom8) { - this.custom8 = custom8; - } - - @Override - public String toString() { - return "ClassificationResource [classificationId=" + classificationId + ", key=" + key + ", parentId=" - + parentId + ", parentKey=" + parentKey + ", category=" + category + ", type=" + type + ", domain=" + domain - + ", isValidInDomain=" + isValidInDomain + ", created=" + created + ", modified=" + modified + ", name=" - + name + ", description=" + description + ", priority=" + priority + ", serviceLevel=" + serviceLevel - + ", applicationEntryPoint=" + applicationEntryPoint + ", custom1=" + custom1 + ", custom2=" + custom2 - + ", custom3=" + custom3 + ", custom4=" + custom4 + ", custom5=" + custom5 + ", custom6=" + custom6 - + ", custom7=" + custom7 + ", custom8=" + custom8 + "]"; - } + public void setCustom8(String custom8) { + this.custom8 = custom8; + } + @Override + public String toString() { + return "ClassificationResource [classificationId=" + + classificationId + + ", key=" + + key + + ", parentId=" + + parentId + + ", parentKey=" + + parentKey + + ", category=" + + category + + ", type=" + + type + + ", domain=" + + domain + + ", isValidInDomain=" + + isValidInDomain + + ", created=" + + created + + ", modified=" + + modified + + ", name=" + + name + + ", description=" + + description + + ", priority=" + + priority + + ", serviceLevel=" + + serviceLevel + + ", applicationEntryPoint=" + + applicationEntryPoint + + ", custom1=" + + custom1 + + ", custom2=" + + custom2 + + ", custom3=" + + custom3 + + ", custom4=" + + custom4 + + ", custom5=" + + custom5 + + ", custom6=" + + custom6 + + ", custom7=" + + custom7 + + ", custom8=" + + custom8 + + "]"; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ClassificationResourceAssembler.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ClassificationResourceAssembler.java index 17ec22949..77030317a 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ClassificationResourceAssembler.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ClassificationResourceAssembler.java @@ -3,7 +3,6 @@ package pro.taskana.rest.resource; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import java.time.Instant; - import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.mvc.ResourceAssemblerSupport; @@ -15,43 +14,49 @@ import pro.taskana.impl.ClassificationImpl; import pro.taskana.rest.ClassificationController; /** - * Transforms {@link Classification} to its resource counterpart {@link ClassificationResource} and vice versa. + * Transforms {@link Classification} to its resource counterpart {@link ClassificationResource} and + * vice versa. */ @Component -public class ClassificationResourceAssembler extends ResourceAssemblerSupport { +public class ClassificationResourceAssembler + extends ResourceAssemblerSupport { - @Autowired - ClassificationService classificationService; + @Autowired ClassificationService classificationService; - public ClassificationResourceAssembler() { - super(ClassificationController.class, ClassificationResource.class); + public ClassificationResourceAssembler() { + super(ClassificationController.class, ClassificationResource.class); + } + + public ClassificationResource toResource(Classification classification) { + ClassificationResource resource = new ClassificationResource(classification); + resource.add( + linkTo(ClassificationController.class).slash(classification.getId()).withSelfRel()); + return resource; + } + + public ClassificationResource toDefinition(Classification classification) { + ClassificationResource resource = new ClassificationResource(classification); + resource.add( + linkTo(ClassificationController.class).slash(classification.getId()).withSelfRel()); + return resource; + } + + public Classification toModel(ClassificationResource classificationResource) { + ClassificationImpl classification = + (ClassificationImpl) + classificationService.newClassification( + classificationResource.domain, + classificationResource.key, + classificationResource.type); + BeanUtils.copyProperties(classificationResource, classification); + + classification.setId(classificationResource.getClassificationId()); + if (classificationResource.getCreated() != null) { + classification.setCreated(Instant.parse(classificationResource.getCreated())); } - - public ClassificationResource toResource(Classification classification) { - ClassificationResource resource = new ClassificationResource(classification); - resource.add(linkTo(ClassificationController.class).slash(classification.getId()).withSelfRel()); - return resource; + if (classificationResource.getModified() != null) { + classification.setModified(Instant.parse(classificationResource.getModified())); } - - public ClassificationResource toDefinition(Classification classification) { - ClassificationResource resource = new ClassificationResource(classification); - resource.add(linkTo(ClassificationController.class).slash(classification.getId()).withSelfRel()); - return resource; - } - - public Classification toModel(ClassificationResource classificationResource) { - ClassificationImpl classification = (ClassificationImpl) classificationService.newClassification( - classificationResource.domain, classificationResource.key, classificationResource.type); - BeanUtils.copyProperties(classificationResource, classification); - - classification.setId(classificationResource.getClassificationId()); - if (classificationResource.getCreated() != null) { - classification.setCreated(Instant.parse(classificationResource.getCreated())); - } - if (classificationResource.getModified() != null) { - classification.setModified(Instant.parse(classificationResource.getModified())); - } - return classification; - } - + return classification; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ClassificationSummaryListResource.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ClassificationSummaryListResource.java index a23246f3c..985384541 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ClassificationSummaryListResource.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ClassificationSummaryListResource.java @@ -1,32 +1,31 @@ package pro.taskana.rest.resource; +import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Collection; - import org.springframework.hateoas.Link; -import com.fasterxml.jackson.annotation.JsonProperty; +/** Resource class for {@link ClassificationSummaryResource} with Pagination. */ +public class ClassificationSummaryListResource + extends PagedResources { -/** - * Resource class for {@link ClassificationSummaryResource} with Pagination. - */ -public class ClassificationSummaryListResource extends PagedResources { + public ClassificationSummaryListResource() { + super(); + } - public ClassificationSummaryListResource() { - super(); - } + public ClassificationSummaryListResource( + Collection content, + PageMetadata metadata, + Iterable links) { + super(content, metadata, links); + } - public ClassificationSummaryListResource(Collection content, PageMetadata metadata, - Iterable links) { - super(content, metadata, links); - } + public ClassificationSummaryListResource( + Collection content, PageMetadata metadata, Link... links) { + super(content, metadata, links); + } - public ClassificationSummaryListResource(Collection content, PageMetadata metadata, - Link... links) { - super(content, metadata, links); - } - - @JsonProperty("classifications") - public Collection getContent() { - return super.getContent(); - } + @JsonProperty("classifications") + public Collection getContent() { + return super.getContent(); + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ClassificationSummaryResource.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ClassificationSummaryResource.java index 8a799c45e..40cd2d2b0 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ClassificationSummaryResource.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ClassificationSummaryResource.java @@ -4,200 +4,204 @@ import org.springframework.hateoas.ResourceSupport; import pro.taskana.ClassificationSummary; -/** - * Resource class for {@link pro.taskana.ClassificationSummary}. - */ +/** Resource class for {@link pro.taskana.ClassificationSummary}. */ public class ClassificationSummaryResource extends ResourceSupport { - public String classificationId; - public String key; - public String parentId; - public String parentKey; - public String category; - public String type; - public String domain; - public String name; - public int priority; - public String custom1; - public String custom2; - public String custom3; - public String custom4; - public String custom5; - public String custom6; - public String custom7; - public String custom8; + public String classificationId; + public String key; + public String parentId; + public String parentKey; + public String category; + public String type; + public String domain; + public String name; + public int priority; + public String custom1; + public String custom2; + public String custom3; + public String custom4; + public String custom5; + public String custom6; + public String custom7; + public String custom8; - public ClassificationSummaryResource() { - } + public ClassificationSummaryResource() {} - public ClassificationSummaryResource(ClassificationSummary classification) { - classificationId = classification.getId(); - key = classification.getKey(); - parentId = classification.getParentId(); - parentKey = classification.getParentKey(); - category = classification.getCategory(); - type = classification.getType(); - domain = classification.getDomain(); - name = classification.getName(); - priority = classification.getPriority(); - custom1 = classification.getCustom1(); - custom2 = classification.getCustom2(); - custom3 = classification.getCustom3(); - custom4 = classification.getCustom4(); - custom5 = classification.getCustom5(); - custom6 = classification.getCustom6(); - custom7 = classification.getCustom7(); - custom8 = classification.getCustom8(); - } + public ClassificationSummaryResource(ClassificationSummary classification) { + classificationId = classification.getId(); + key = classification.getKey(); + parentId = classification.getParentId(); + parentKey = classification.getParentKey(); + category = classification.getCategory(); + type = classification.getType(); + domain = classification.getDomain(); + name = classification.getName(); + priority = classification.getPriority(); + custom1 = classification.getCustom1(); + custom2 = classification.getCustom2(); + custom3 = classification.getCustom3(); + custom4 = classification.getCustom4(); + custom5 = classification.getCustom5(); + custom6 = classification.getCustom6(); + custom7 = classification.getCustom7(); + custom8 = classification.getCustom8(); + } - public String getClassificationId() { - return classificationId; - } + public String getClassificationId() { + return classificationId; + } - public void setClassificationId(String classificationId) { - this.classificationId = classificationId; - } + public void setClassificationId(String classificationId) { + this.classificationId = classificationId; + } - public String getKey() { - return key; - } + public String getKey() { + return key; + } - public void setKey(String key) { - this.key = key; - } + public void setKey(String key) { + this.key = key; + } - public String getParentId() { - return parentId; - } + public String getParentId() { + return parentId; + } - public void setParentId(String parentId) { - this.parentId = parentId; - } + public void setParentId(String parentId) { + this.parentId = parentId; + } - public String getParentKey() { - return parentKey; - } + public String getParentKey() { + return parentKey; + } - public void setParentKey(String parentKey) { - this.parentKey = parentKey; - } + public void setParentKey(String parentKey) { + this.parentKey = parentKey; + } - public String getCategory() { - return category; - } + public String getCategory() { + return category; + } - public void setCategory(String category) { - this.category = category; - } + public void setCategory(String category) { + this.category = category; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public String getDomain() { - return domain; - } + public String getDomain() { + return domain; + } - public void setDomain(String domain) { - this.domain = domain; - } + public void setDomain(String domain) { + this.domain = domain; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public int getPriority() { - return priority; - } + public int getPriority() { + return priority; + } - public void setPriority(int priority) { - this.priority = priority; - } + public void setPriority(int priority) { + this.priority = priority; + } - public String getCustom1() { - return custom1; - } + public String getCustom1() { + return custom1; + } - public void setCustom1(String custom1) { - this.custom1 = custom1; - } + public void setCustom1(String custom1) { + this.custom1 = custom1; + } - public String getCustom2() { - return custom2; - } + public String getCustom2() { + return custom2; + } - public void setCustom2(String custom2) { - this.custom2 = custom2; - } + public void setCustom2(String custom2) { + this.custom2 = custom2; + } - public String getCustom3() { - return custom3; - } + public String getCustom3() { + return custom3; + } - public void setCustom3(String custom3) { - this.custom3 = custom3; - } + public void setCustom3(String custom3) { + this.custom3 = custom3; + } - public String getCustom4() { - return custom4; - } + public String getCustom4() { + return custom4; + } - public void setCustom4(String custom4) { - this.custom4 = custom4; - } + public void setCustom4(String custom4) { + this.custom4 = custom4; + } - public String getCustom5() { - return custom5; - } + public String getCustom5() { + return custom5; + } - public void setCustom5(String custom5) { - this.custom5 = custom5; - } + public void setCustom5(String custom5) { + this.custom5 = custom5; + } - public String getCustom6() { - return custom6; - } + public String getCustom6() { + return custom6; + } - public void setCustom6(String custom6) { - this.custom6 = custom6; - } + public void setCustom6(String custom6) { + this.custom6 = custom6; + } - public String getCustom7() { - return custom7; - } + public String getCustom7() { + return custom7; + } - public void setCustom7(String custom7) { - this.custom7 = custom7; - } + public void setCustom7(String custom7) { + this.custom7 = custom7; + } - public String getCustom8() { - return custom8; - } + public String getCustom8() { + return custom8; + } - public void setCustom8(String custom8) { - this.custom8 = custom8; - } - - @Override - public String toString() { - return "ClassificationSummaryResource [" - + "classificationId= " + this.classificationId - + "key= " + this.key - + "parentId= " + this.parentId - + "parentKey= " + this.parentKey - + "type= " + this.type - + "domain= " + this.domain - + "name= " + this.name - + "priority= " + this.priority - + "]"; - } + public void setCustom8(String custom8) { + this.custom8 = custom8; + } + @Override + public String toString() { + return "ClassificationSummaryResource [" + + "classificationId= " + + this.classificationId + + "key= " + + this.key + + "parentId= " + + this.parentId + + "parentKey= " + + this.parentKey + + "type= " + + this.type + + "domain= " + + this.domain + + "name= " + + this.name + + "priority= " + + this.priority + + "]"; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ClassificationSummaryResourceAssembler.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ClassificationSummaryResourceAssembler.java index fa101aaa6..df7bc2eb0 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ClassificationSummaryResourceAssembler.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ClassificationSummaryResourceAssembler.java @@ -1,7 +1,6 @@ package pro.taskana.rest.resource; import java.util.Collection; - import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.mvc.ResourceAssemblerSupport; @@ -15,38 +14,35 @@ import pro.taskana.rest.Mapping; import pro.taskana.rest.resource.PagedResources.PageMetadata; import pro.taskana.rest.resource.links.PageLinks; -/** - * Resource assembler for {@link ClassificationSummaryResource}. - */ +/** Resource assembler for {@link ClassificationSummaryResource}. */ @Component public class ClassificationSummaryResourceAssembler extends ResourceAssemblerSupport { - @Autowired - private ClassificationService classificationService; + @Autowired private ClassificationService classificationService; - public ClassificationSummaryResourceAssembler() { - super(ClassificationController.class, ClassificationSummaryResource.class); - } + public ClassificationSummaryResourceAssembler() { + super(ClassificationController.class, ClassificationSummaryResource.class); + } - @Override - public ClassificationSummaryResource toResource(ClassificationSummary classificationSummary) { - return new ClassificationSummaryResource(classificationSummary); - } + @Override + public ClassificationSummaryResource toResource(ClassificationSummary classificationSummary) { + return new ClassificationSummaryResource(classificationSummary); + } - public ClassificationSummary toModel(ClassificationSummaryResource resource) { - ClassificationImpl classification = (ClassificationImpl) classificationService - .newClassification( - resource.getKey(), resource.getDomain(), - resource.getType()); - classification.setId(resource.getClassificationId()); - BeanUtils.copyProperties(resource, classification); - return classification.asSummary(); - } + public ClassificationSummary toModel(ClassificationSummaryResource resource) { + ClassificationImpl classification = + (ClassificationImpl) + classificationService.newClassification( + resource.getKey(), resource.getDomain(), resource.getType()); + classification.setId(resource.getClassificationId()); + BeanUtils.copyProperties(resource, classification); + return classification.asSummary(); + } - @PageLinks(Mapping.URL_CLASSIFICATIONS) - public ClassificationSummaryListResource toResources(Collection entities, - PageMetadata pageMetadata) { - return new ClassificationSummaryListResource(toResources(entities), pageMetadata); - } + @PageLinks(Mapping.URL_CLASSIFICATIONS) + public ClassificationSummaryListResource toResources( + Collection entities, PageMetadata pageMetadata) { + return new ClassificationSummaryListResource(toResources(entities), pageMetadata); + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/DistributionTargetListResource.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/DistributionTargetListResource.java index b384bf2d6..d89204e80 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/DistributionTargetListResource.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/DistributionTargetListResource.java @@ -1,34 +1,31 @@ package pro.taskana.rest.resource; -import java.util.Collection; - -import org.springframework.hateoas.Link; - import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Collection; +import org.springframework.hateoas.Link; -/** - * Resource class for {@link DistributionTargetResource} with Pagination. - */ +/** Resource class for {@link DistributionTargetResource} with Pagination. */ public class DistributionTargetListResource extends PagedResources { - public DistributionTargetListResource() { - super(); - } + public DistributionTargetListResource() { + super(); + } - public DistributionTargetListResource(Collection content, Link... links) { - super(content, null, links); - } + public DistributionTargetListResource( + Collection content, Link... links) { + super(content, null, links); + } - @Override - @JsonProperty("distributionTargets") - public Collection getContent() { - return super.getContent(); - } + @Override + @JsonProperty("distributionTargets") + public Collection getContent() { + return super.getContent(); + } - @Override - @JsonIgnore - public PageMetadata getMetadata() { - return super.getMetadata(); - } + @Override + @JsonIgnore + public PageMetadata getMetadata() { + return super.getMetadata(); + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/DistributionTargetResource.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/DistributionTargetResource.java index c094372c3..624363e67 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/DistributionTargetResource.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/DistributionTargetResource.java @@ -4,16 +4,13 @@ import org.springframework.hateoas.core.Relation; import pro.taskana.WorkbasketSummary; -/** - * Resource class for a distribution target based on {@link pro.taskana.WorkbasketSummary}. - */ +/** Resource class for a distribution target based on {@link pro.taskana.WorkbasketSummary}. */ @Relation(collectionRelation = "distributionTargets") public class DistributionTargetResource extends WorkbasketSummaryResource { - DistributionTargetResource() { - } + DistributionTargetResource() {} - DistributionTargetResource(WorkbasketSummary workbasketSummary) { - super(workbasketSummary); - } + DistributionTargetResource(WorkbasketSummary workbasketSummary) { + super(workbasketSummary); + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/DistributionTargetResourceAssembler.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/DistributionTargetResourceAssembler.java index d742720b3..4a6c963d7 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/DistributionTargetResourceAssembler.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/DistributionTargetResourceAssembler.java @@ -4,7 +4,6 @@ import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import java.util.List; - import org.springframework.hateoas.mvc.ResourceAssemblerSupport; import org.springframework.stereotype.Component; @@ -14,33 +13,34 @@ import pro.taskana.exceptions.WorkbasketNotFoundException; import pro.taskana.rest.WorkbasketController; /** - * Transforms WorkbasketSummary to its resource counterpart DistributionTargerResource and vice versa. + * Transforms WorkbasketSummary to its resource counterpart DistributionTargerResource and vice + * versa. */ @Component -public class DistributionTargetResourceAssembler extends - ResourceAssemblerSupport { +public class DistributionTargetResourceAssembler + extends ResourceAssemblerSupport { - public DistributionTargetResourceAssembler() { - super(WorkbasketController.class, DistributionTargetResource.class); - } + public DistributionTargetResourceAssembler() { + super(WorkbasketController.class, DistributionTargetResource.class); + } - public DistributionTargetResource toResource(WorkbasketSummary summary) { - return new DistributionTargetResource(summary); - } + public DistributionTargetResource toResource(WorkbasketSummary summary) { + return new DistributionTargetResource(summary); + } - public DistributionTargetListResource toResources(String workbasketId, - List distributionTargets) throws WorkbasketNotFoundException, NotAuthorizedException { + public DistributionTargetListResource toResources( + String workbasketId, List distributionTargets) + throws WorkbasketNotFoundException, NotAuthorizedException { - DistributionTargetListResource distributionTargetListResource = new DistributionTargetListResource( - toResources(distributionTargets)); - distributionTargetListResource - .add(linkTo(methodOn(WorkbasketController.class).getDistributionTargets(workbasketId)) - .withSelfRel()); - distributionTargetListResource - .add(linkTo(methodOn(WorkbasketController.class).getWorkbasket(workbasketId)) - .withRel("workbasket")); - - return distributionTargetListResource; - } + DistributionTargetListResource distributionTargetListResource = + new DistributionTargetListResource(toResources(distributionTargets)); + distributionTargetListResource.add( + linkTo(methodOn(WorkbasketController.class).getDistributionTargets(workbasketId)) + .withSelfRel()); + distributionTargetListResource.add( + linkTo(methodOn(WorkbasketController.class).getWorkbasket(workbasketId)) + .withRel("workbasket")); + return distributionTargetListResource; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/PagedResources.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/PagedResources.java index 119d8cafb..f8ab042b7 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/PagedResources.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/PagedResources.java @@ -1,228 +1,207 @@ package pro.taskana.rest.resource; +import com.fasterxml.jackson.annotation.JsonProperty; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; - import javax.xml.bind.annotation.XmlAttribute; - import org.springframework.hateoas.Link; import org.springframework.hateoas.ResourceSupport; import org.springframework.util.Assert; -import com.fasterxml.jackson.annotation.JsonProperty; - /** * Base Class for Resources with pagination. * - * @param - * The Class of the paginatied content + * @param The Class of the paginatied content */ public class PagedResources extends ResourceSupport { - private Collection content; + private Collection content; - private PageMetadata metadata; + private PageMetadata metadata; + + /** Default constructor to allow instantiation by reflection. */ + protected PagedResources() { + this(new ArrayList(), null); + } + + /** + * Creates a new {@link PagedResources} from the given content, {@link PageMetadata} and {@link + * Link}s (optional). + * + * @param content must not be {@literal null}. + * @param metadata the metadata + * @param links the links + */ + public PagedResources(Collection content, PageMetadata metadata, Link... links) { + this(content, metadata, Arrays.asList(links)); + } + + /** + * Creates a new {@link PagedResources} from the given content {@link PageMetadata} and {@link + * Link}s. + * + * @param content must not be {@literal null}. + * @param metadata the metadata + * @param links the links + */ + public PagedResources(Collection content, PageMetadata metadata, Iterable links) { + super(); + this.content = content; + this.metadata = metadata; + this.add(links); + } + + /** + * Returns the pagination metadata. + * + * @return the metadata + */ + @JsonProperty("page") + public PageMetadata getMetadata() { + return metadata; + } + + /** + * Returns the content. + * + * @return the content + */ + @JsonProperty("content") + public Collection getContent() { + return Collections.unmodifiableCollection(content); + }; + + /** Class for Page Metadata. */ + public static class PageMetadata { + + @XmlAttribute @JsonProperty private long size; + @XmlAttribute @JsonProperty private long totalElements; + @XmlAttribute @JsonProperty private long totalPages; + @XmlAttribute @JsonProperty private long number; + + protected PageMetadata() {} /** - * Default constructor to allow instantiation by reflection. - */ - protected PagedResources() { - this(new ArrayList(), null); - } - - /** - * Creates a new {@link PagedResources} from the given content, {@link PageMetadata} and {@link Link}s (optional). + * Creates a new {@link PageMetadata} from the given size, number, total elements and total + * pages. * - * @param content - * must not be {@literal null}. - * @param metadata - * the metadata - * @param links - * the links + * @param size the size + * @param number zero-indexed, must be less than totalPages + * @param totalElements number of elements + * @param totalPages the total pages */ - public PagedResources(Collection content, PageMetadata metadata, Link... links) { - this(content, metadata, Arrays.asList(links)); + public PageMetadata(long size, long number, long totalElements, long totalPages) { + Assert.isTrue(size > -1, "Size must not be negative!"); + Assert.isTrue(number > -1, "Number must not be negative!"); + Assert.isTrue(totalElements > -1, "Total elements must not be negative!"); + Assert.isTrue(totalPages > -1, "Total pages must not be negative!"); + + this.size = size; + this.number = number; + this.totalElements = totalElements; + this.totalPages = totalPages; } /** - * Creates a new {@link PagedResources} from the given content {@link PageMetadata} and {@link Link}s. + * Creates a new {@link PageMetadata} from the given size, number and total elements. * - * @param content - * must not be {@literal null}. - * @param metadata - * the metadata - * @param links - * the links + * @param size the size of the page + * @param number the number of the page + * @param totalElements the total number of elements available */ - public PagedResources(Collection content, PageMetadata metadata, Iterable links) { - super(); - this.content = content; - this.metadata = metadata; - this.add(links); + public PageMetadata(long size, long number, long totalElements) { + this( + size, + number, + totalElements, + size == 0 ? 0 : (long) Math.ceil((double) totalElements / (double) size)); } /** - * Returns the pagination metadata. + * Returns the requested size of the page. * - * @return the metadata + * @return the size a positive long. */ - @JsonProperty("page") - public PageMetadata getMetadata() { - return metadata; + public long getSize() { + return size; } /** - * Returns the content. + * Returns the total number of elements available. * - * @return the content + * @return the totalElements a positive long. */ - @JsonProperty("content") - public Collection getContent() { - return Collections.unmodifiableCollection(content); - }; + public long getTotalElements() { + return totalElements; + } /** - * Class for Page Metadata. + * Returns how many pages are available in total. + * + * @return the totalPages a positive long. */ - public static class PageMetadata { - - @XmlAttribute - @JsonProperty - private long size; - @XmlAttribute - @JsonProperty - private long totalElements; - @XmlAttribute - @JsonProperty - private long totalPages; - @XmlAttribute - @JsonProperty - private long number; - - protected PageMetadata() { - - } - - /** - * Creates a new {@link PageMetadata} from the given size, number, total elements and total pages. - * - * @param size - * the size - * @param number - * zero-indexed, must be less than totalPages - * @param totalElements - * number of elements - * @param totalPages - * the total pages - */ - public PageMetadata(long size, long number, long totalElements, long totalPages) { - Assert.isTrue(size > -1, "Size must not be negative!"); - Assert.isTrue(number > -1, "Number must not be negative!"); - Assert.isTrue(totalElements > -1, "Total elements must not be negative!"); - Assert.isTrue(totalPages > -1, "Total pages must not be negative!"); - - this.size = size; - this.number = number; - this.totalElements = totalElements; - this.totalPages = totalPages; - } - - /** - * Creates a new {@link PageMetadata} from the given size, number and total elements. - * - * @param size - * the size of the page - * @param number - * the number of the page - * @param totalElements - * the total number of elements available - */ - public PageMetadata(long size, long number, long totalElements) { - this(size, number, totalElements, size == 0 ? 0 : (long) Math.ceil((double) totalElements / (double) size)); - } - - /** - * Returns the requested size of the page. - * - * @return the size a positive long. - */ - public long getSize() { - return size; - } - - /** - * Returns the total number of elements available. - * - * @return the totalElements a positive long. - */ - public long getTotalElements() { - return totalElements; - } - - /** - * Returns how many pages are available in total. - * - * @return the totalPages a positive long. - */ - public long getTotalPages() { - return totalPages; - } - - /** - * Returns the number of the current page. - * - * @return the number a positive long. - */ - public long getNumber() { - return number; - } - - /* - * (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return String.format("Metadata { number: %d, total pages: %d, total elements: %d, size: %d }", number, - totalPages, totalElements, size); - } - - /* - * (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - - if (this == obj) { - return true; - } - - if (obj == null || !obj.getClass().equals(getClass())) { - return false; - } - - PageMetadata that = (PageMetadata) obj; - - return this.number == that.number && this.size == that.size && this.totalElements == that.totalElements - && this.totalPages == that.totalPages; - } - - /* - * (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - - int result = 17; - result += 31 * (int) (this.number ^ this.number >>> 32); - result += 31 * (int) (this.size ^ this.size >>> 32); - result += 31 * (int) (this.totalElements ^ this.totalElements >>> 32); - result += 31 * (int) (this.totalPages ^ this.totalPages >>> 32); - return result; - } + public long getTotalPages() { + return totalPages; } + + /** + * Returns the number of the current page. + * + * @return the number a positive long. + */ + public long getNumber() { + return number; + } + + /* + * (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + + int result = 17; + result += 31 * (int) (this.number ^ this.number >>> 32); + result += 31 * (int) (this.size ^ this.size >>> 32); + result += 31 * (int) (this.totalElements ^ this.totalElements >>> 32); + result += 31 * (int) (this.totalPages ^ this.totalPages >>> 32); + return result; + } + + /* + * (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + + if (this == obj) { + return true; + } + + if (obj == null || !obj.getClass().equals(getClass())) { + return false; + } + + PageMetadata that = (PageMetadata) obj; + + return this.number == that.number + && this.size == that.size + && this.totalElements == that.totalElements + && this.totalPages == that.totalPages; + } + + /* + * (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return String.format( + "Metadata { number: %d, total pages: %d, total elements: %d, size: %d }", + number, totalPages, totalElements, size); + } + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ReportResource.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ReportResource.java index ae5acba67..4beb0e47c 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ReportResource.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ReportResource.java @@ -2,132 +2,127 @@ package pro.taskana.rest.resource; import java.util.Arrays; import java.util.List; - import org.springframework.hateoas.ResourceSupport; -/** - * Resource class for {@link pro.taskana.impl.report.structure.Report}. - */ +/** Resource class for {@link pro.taskana.impl.report.structure.Report}. */ public class ReportResource extends ResourceSupport { - private MetaInformation meta; + private MetaInformation meta; - private List rows; + private List rows; - private List sumRow; + private List sumRow; - public ReportResource(MetaInformation meta, List rows, List sumRow) { - this.meta = meta; - this.rows = rows; - this.sumRow = sumRow; + public ReportResource(MetaInformation meta, List rows, List sumRow) { + this.meta = meta; + this.rows = rows; + this.sumRow = sumRow; + } + + public MetaInformation getMeta() { + return meta; + } + + public List getRows() { + return rows; + } + + public List getSumRow() { + return sumRow; + } + + /** Resource class for {@link pro.taskana.impl.report.row.SingleRow}. */ + public static class RowResource { + + private int[] cells; + private int total; + private int depth; + private String[] desc; + private boolean display; + + public RowResource(int[] cells, int total, int depth, String[] desc, boolean display) { + this.cells = cells; + this.total = total; + this.depth = depth; + this.desc = desc; + this.display = display; } - public MetaInformation getMeta() { - return meta; + @SuppressWarnings("unused") + public int[] getCells() { + return cells; } - public List getRows() { - return rows; + @SuppressWarnings("unused") + public int getTotal() { + return total; } - public List getSumRow() { - return sumRow; + @SuppressWarnings("unused") + public int getDepth() { + return depth; } - /** - * Resource class for {@link pro.taskana.impl.report.row.SingleRow}. - */ - public static class RowResource { - - private int[] cells; - private int total; - private int depth; - private String[] desc; - private boolean display; - - public RowResource(int[] cells, int total, int depth, String[] desc, boolean display) { - this.cells = cells; - this.total = total; - this.depth = depth; - this.desc = desc; - this.display = display; - } - - @SuppressWarnings("unused") - public int[] getCells() { - return cells; - } - - @SuppressWarnings("unused") - public int getTotal() { - return total; - } - - @SuppressWarnings("unused") - public int getDepth() { - return depth; - } - - @SuppressWarnings("unused") - public String[] getDesc() { - return desc; - } - - @SuppressWarnings("unused") - public boolean isDisplay() { - return display; - } - - @Override - public String toString() { - return String.format("RowResourde [cells=%s, total=%d, depth=%d, desc=%s", - Arrays.toString(cells), total, depth, Arrays.toString(desc)); - } + @SuppressWarnings("unused") + public String[] getDesc() { + return desc; } - /** - * Meta Information about this ReportResource. - */ - public static class MetaInformation { - - private static final String TOTAL_DESC = "Total"; - - private String name; - private String date; - private String[] header; - private String[] rowDesc; - - public MetaInformation(String name, String date, String[] header, String[] rowDesc) { - this.name = name; - this.date = date; - this.header = header; - this.rowDesc = rowDesc; - } - - public String getTotalDesc() { - return TOTAL_DESC; - } - - public String getName() { - return name; - } - - public String getDate() { - return date; - } - - public String[] getHeader() { - return header; - } - - public String[] getRowDesc() { - return rowDesc; - } - - @Override - public String toString() { - return String.format("MetaInformation [name= %s, date= %s, header= %s, rowDesc= %s]", - name, date, Arrays.toString(header), Arrays.toString(rowDesc)); - } + @SuppressWarnings("unused") + public boolean isDisplay() { + return display; } + + @Override + public String toString() { + return String.format( + "RowResourde [cells=%s, total=%d, depth=%d, desc=%s", + Arrays.toString(cells), total, depth, Arrays.toString(desc)); + } + } + + /** Meta Information about this ReportResource. */ + public static class MetaInformation { + + private static final String TOTAL_DESC = "Total"; + + private String name; + private String date; + private String[] header; + private String[] rowDesc; + + public MetaInformation(String name, String date, String[] header, String[] rowDesc) { + this.name = name; + this.date = date; + this.header = header; + this.rowDesc = rowDesc; + } + + public String getTotalDesc() { + return TOTAL_DESC; + } + + public String getName() { + return name; + } + + public String getDate() { + return date; + } + + public String[] getHeader() { + return header; + } + + public String[] getRowDesc() { + return rowDesc; + } + + @Override + public String toString() { + return String.format( + "MetaInformation [name= %s, date= %s, header= %s, rowDesc= %s]", + name, date, Arrays.toString(header), Arrays.toString(rowDesc)); + } + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ReportResourceAssembler.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ReportResourceAssembler.java index 1af4c121e..81d045c27 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ReportResourceAssembler.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/ReportResourceAssembler.java @@ -10,7 +10,6 @@ import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; - import org.springframework.stereotype.Component; import pro.taskana.TaskState; @@ -28,115 +27,125 @@ import pro.taskana.report.TimestampReport; import pro.taskana.report.WorkbasketReport; import pro.taskana.rest.MonitorController; -/** - * Transforms any {@link Report} into its {@link ReportResource}. - */ +/** Transforms any {@link Report} into its {@link ReportResource}. */ @Component public class ReportResourceAssembler { - public ReportResource toResource(TaskStatusReport report, List domains, List states) - throws NotAuthorizedException, InvalidArgumentException { - ReportResource resource = toReportResource(report); - resource.add( - linkTo(methodOn(MonitorController.class).getTasksStatusReport(domains, states)) - .withSelfRel().expand()); - return resource; - } + public ReportResource toResource( + TaskStatusReport report, List domains, List states) + throws NotAuthorizedException, InvalidArgumentException { + ReportResource resource = toReportResource(report); + resource.add( + linkTo(methodOn(MonitorController.class).getTasksStatusReport(domains, states)) + .withSelfRel() + .expand()); + return resource; + } - public ReportResource toResource(ClassificationReport report) - throws NotAuthorizedException, InvalidArgumentException { - ReportResource resource = toReportResource(report); - resource.add( - linkTo(methodOn(MonitorController.class).getTasksClassificationReport()) - .withSelfRel().expand()); - return resource; - } + public ReportResource toResource(ClassificationReport report) + throws NotAuthorizedException, InvalidArgumentException { + ReportResource resource = toReportResource(report); + resource.add( + linkTo(methodOn(MonitorController.class).getTasksClassificationReport()) + .withSelfRel() + .expand()); + return resource; + } - public ReportResource toResource(WorkbasketReport report, List states) - throws NotAuthorizedException, InvalidArgumentException { - ReportResource resource = toReportResource(report); - resource.add( - linkTo(methodOn(MonitorController.class).getTasksWorkbasketReport(states)) - .withSelfRel().expand()); - return resource; - } + public ReportResource toResource(WorkbasketReport report, List states) + throws NotAuthorizedException, InvalidArgumentException { + ReportResource resource = toReportResource(report); + resource.add( + linkTo(methodOn(MonitorController.class).getTasksWorkbasketReport(states)) + .withSelfRel() + .expand()); + return resource; + } - public ReportResource toResource(WorkbasketReport report, int daysInPast, List states) - throws NotAuthorizedException, InvalidArgumentException { - ReportResource resource = toReportResource(report); - resource.add( - linkTo(methodOn(MonitorController.class).getTasksWorkbasketPlannedDateReport(daysInPast, states)) - .withSelfRel().expand()); - return resource; - } + public ReportResource toResource(WorkbasketReport report, int daysInPast, List states) + throws NotAuthorizedException, InvalidArgumentException { + ReportResource resource = toReportResource(report); + resource.add( + linkTo( + methodOn(MonitorController.class) + .getTasksWorkbasketPlannedDateReport(daysInPast, states)) + .withSelfRel() + .expand()); + return resource; + } - public ReportResource toResource(TimestampReport report) - throws NotAuthorizedException, InvalidArgumentException { - ReportResource resource = toReportResource(report); - resource.add(linkTo(methodOn(MonitorController.class).getDailyEntryExitReport()).withSelfRel().expand()); - return resource; - } + public ReportResource toResource(TimestampReport report) + throws NotAuthorizedException, InvalidArgumentException { + ReportResource resource = toReportResource(report); + resource.add( + linkTo(methodOn(MonitorController.class).getDailyEntryExitReport()).withSelfRel().expand()); + return resource; + } - > ReportResource toReportResource(Report report) { - return toReportResource(report, Instant.now()); - } + > ReportResource toReportResource( + Report report) { + return toReportResource(report, Instant.now()); + } - > ReportResource toReportResource( - Report report, Instant time) { - String[] header = report.getColumnHeaders() - .stream() - .map(H::getDisplayName) - .toArray(String[]::new); - ReportResource.MetaInformation meta = new ReportResource.MetaInformation( - report.getClass().getSimpleName(), - time.toString(), - header, - report.getRowDesc()); + > ReportResource toReportResource( + Report report, Instant time) { + String[] header = + report.getColumnHeaders().stream().map(H::getDisplayName).toArray(String[]::new); + ReportResource.MetaInformation meta = + new ReportResource.MetaInformation( + report.getClass().getSimpleName(), time.toString(), header, report.getRowDesc()); - // iterate over each Row and transform it to a RowResource while keeping the domain key. - List rows = report.getRows() - .entrySet() - .stream() + // iterate over each Row and transform it to a RowResource while keeping the domain key. + List rows = + report.getRows().entrySet().stream() .sorted(Comparator.comparing(e -> e.getKey().toLowerCase())) - .map(i -> transformRow(i.getValue(), i.getKey(), new String[report.getRowDesc().length], 0)) + .map( + i -> + transformRow( + i.getValue(), i.getKey(), new String[report.getRowDesc().length], 0)) .flatMap(Collection::stream) .collect(Collectors.toList()); - List sumRow = transformRow(report.getSumRow(), meta.getTotalDesc(), - new String[report.getRowDesc().length], 0); + List sumRow = + transformRow( + report.getSumRow(), meta.getTotalDesc(), new String[report.getRowDesc().length], 0); - return new ReportResource(meta, rows, sumRow); - } + return new ReportResource(meta, rows, sumRow); + } - private List transformRow(Row row, String currentDesc, - String[] desc, int depth) { - // This is a very dirty solution.. Personally I'd prefer to use a visitor-like pattern here. - // The issue with that: Addition of the visitor code within taskana-core - and having clean code is not - // a reason to append code somewhere where it doesn't belong. - if (row.getClass() == SingleRow.class) { - return Collections.singletonList(transformSingleRow((SingleRow) row, currentDesc, desc, depth)); - } - return transformFoldableRow((FoldableRow) row, currentDesc, desc, depth); + private List transformRow( + Row row, String currentDesc, String[] desc, int depth) { + // This is a very dirty solution.. Personally I'd prefer to use a visitor-like pattern here. + // The issue with that: Addition of the visitor code within taskana-core - and having clean code + // is not + // a reason to append code somewhere where it doesn't belong. + if (row.getClass() == SingleRow.class) { + return Collections.singletonList( + transformSingleRow((SingleRow) row, currentDesc, desc, depth)); } + return transformFoldableRow((FoldableRow) row, currentDesc, desc, depth); + } - private ReportResource.RowResource transformSingleRow(SingleRow row, String currentDesc, - String[] previousRowDesc, int depth) { - String[] rowDesc = new String[previousRowDesc.length]; - System.arraycopy(previousRowDesc, 0, rowDesc, 0, depth); - rowDesc[depth] = currentDesc; - return new ReportResource.RowResource(row.getCells(), row.getTotalValue(), depth, rowDesc, depth == 0); - } + private ReportResource.RowResource transformSingleRow( + SingleRow row, String currentDesc, String[] previousRowDesc, int depth) { + String[] rowDesc = new String[previousRowDesc.length]; + System.arraycopy(previousRowDesc, 0, rowDesc, 0, depth); + rowDesc[depth] = currentDesc; + return new ReportResource.RowResource( + row.getCells(), row.getTotalValue(), depth, rowDesc, depth == 0); + } - private List transformFoldableRow(FoldableRow row, - String currentDesc, String[] previousRowDesc, int depth) { - ReportResource.RowResource baseRow = transformSingleRow(row, currentDesc, previousRowDesc, depth); - List rowList = new LinkedList<>(); - rowList.add(baseRow); - row.getFoldableRowKeySet().stream() - .sorted(String.CASE_INSENSITIVE_ORDER) - .map(s -> transformRow(row.getFoldableRow(s), s, baseRow.getDesc(), depth + 1)) - .flatMap(Collection::stream) - .forEachOrdered(rowList::add); - return rowList; - } + private List transformFoldableRow( + FoldableRow row, String currentDesc, String[] previousRowDesc, int depth) { + ReportResource.RowResource baseRow = + transformSingleRow(row, currentDesc, previousRowDesc, depth); + List rowList = new LinkedList<>(); + rowList.add(baseRow); + row.getFoldableRowKeySet().stream() + .sorted(String.CASE_INSENSITIVE_ORDER) + .map(s -> transformRow(row.getFoldableRow(s), s, baseRow.getDesc(), depth + 1)) + .flatMap(Collection::stream) + .forEachOrdered(rowList::add); + return rowList; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/TaskResource.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/TaskResource.java index b8422ee51..2b7455aa7 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/TaskResource.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/TaskResource.java @@ -4,7 +4,6 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; - import org.springframework.hateoas.ResourceSupport; import pro.taskana.ObjectReference; @@ -12,493 +11,501 @@ import pro.taskana.Task; import pro.taskana.TaskState; import pro.taskana.exceptions.InvalidArgumentException; -/** - * Resource class for {@link pro.taskana.Task}. - */ +/** Resource class for {@link pro.taskana.Task}. */ public class TaskResource extends ResourceSupport { - private String taskId; - private String externalId; - private String created; // ISO-8601 - private String claimed; // ISO-8601 - private String completed; // ISO-8601 - private String modified; // ISO-8601 - private String planned; // ISO-8601 - private String due; // ISO-8601 - private String name; - private String creator; - private String description; - private String note; - private int priority; - private TaskState state; - private ClassificationSummaryResource classificationSummaryResource; - private WorkbasketSummaryResource workbasketSummaryResource; - private String businessProcessId; - private String parentBusinessProcessId; - private String owner; - private ObjectReference primaryObjRef; - private boolean isRead; - private boolean isTransferred; - // All objects have to be serializable - private List customAttributes = Collections.emptyList(); - private List callbackInfo = Collections.emptyList(); - private List attachments = new ArrayList<>(); - private String custom1; - private String custom2; - private String custom3; - private String custom4; - private String custom5; - private String custom6; - private String custom7; - private String custom8; - private String custom9; - private String custom10; - private String custom11; - private String custom12; - private String custom13; - private String custom14; - private String custom15; - private String custom16; + private String taskId; + private String externalId; + private String created; // ISO-8601 + private String claimed; // ISO-8601 + private String completed; // ISO-8601 + private String modified; // ISO-8601 + private String planned; // ISO-8601 + private String due; // ISO-8601 + private String name; + private String creator; + private String description; + private String note; + private int priority; + private TaskState state; + private ClassificationSummaryResource classificationSummaryResource; + private WorkbasketSummaryResource workbasketSummaryResource; + private String businessProcessId; + private String parentBusinessProcessId; + private String owner; + private ObjectReference primaryObjRef; + private boolean isRead; + private boolean isTransferred; + // All objects have to be serializable + private List customAttributes = Collections.emptyList(); + private List callbackInfo = Collections.emptyList(); + private List attachments = new ArrayList<>(); + private String custom1; + private String custom2; + private String custom3; + private String custom4; + private String custom5; + private String custom6; + private String custom7; + private String custom8; + private String custom9; + private String custom10; + private String custom11; + private String custom12; + private String custom13; + private String custom14; + private String custom15; + private String custom16; - public TaskResource() { - } + public TaskResource() {} - public TaskResource(Task task) throws InvalidArgumentException { + public TaskResource(Task task) throws InvalidArgumentException { - taskId = task.getId(); - externalId = task.getExternalId(); - created = task.getCreated() != null ? task.getCreated().toString() : null; - claimed = task.getClaimed() != null ? task.getClaimed().toString() : null; - completed = task.getCompleted() != null ? task.getCompleted().toString() : null; - modified = task.getModified() != null ? task.getModified().toString() : null; - planned = task.getPlanned() != null ? task.getPlanned().toString() : null; - due = task.getDue() != null ? task.getDue().toString() : null; - name = task.getName(); - creator = task.getCreator(); - description = task.getDescription(); - note = task.getNote(); - priority = task.getPriority(); - state = task.getState(); - classificationSummaryResource = new ClassificationSummaryResource(task.getClassificationSummary()); - workbasketSummaryResource = new WorkbasketSummaryResource(task.getWorkbasketSummary()); - businessProcessId = task.getBusinessProcessId(); - parentBusinessProcessId = task.getParentBusinessProcessId(); - owner = task.getOwner(); - primaryObjRef = task.getPrimaryObjRef(); - isRead = task.isRead(); - isTransferred = task.isTransferred(); - customAttributes = task.getCustomAttributes().entrySet().stream() + taskId = task.getId(); + externalId = task.getExternalId(); + created = task.getCreated() != null ? task.getCreated().toString() : null; + claimed = task.getClaimed() != null ? task.getClaimed().toString() : null; + completed = task.getCompleted() != null ? task.getCompleted().toString() : null; + modified = task.getModified() != null ? task.getModified().toString() : null; + planned = task.getPlanned() != null ? task.getPlanned().toString() : null; + due = task.getDue() != null ? task.getDue().toString() : null; + name = task.getName(); + creator = task.getCreator(); + description = task.getDescription(); + note = task.getNote(); + priority = task.getPriority(); + state = task.getState(); + classificationSummaryResource = + new ClassificationSummaryResource(task.getClassificationSummary()); + workbasketSummaryResource = new WorkbasketSummaryResource(task.getWorkbasketSummary()); + businessProcessId = task.getBusinessProcessId(); + parentBusinessProcessId = task.getParentBusinessProcessId(); + owner = task.getOwner(); + primaryObjRef = task.getPrimaryObjRef(); + isRead = task.isRead(); + isTransferred = task.isTransferred(); + customAttributes = + task.getCustomAttributes().entrySet().stream() .map(e -> new TaskResource.CustomAttribute(e.getKey(), e.getValue())) .collect(Collectors.toList()); - callbackInfo = task.getCallbackInfo().entrySet().stream() + callbackInfo = + task.getCallbackInfo().entrySet().stream() .map(e -> new TaskResource.CustomAttribute(e.getKey(), e.getValue())) .collect(Collectors.toList()); - attachments = - task.getAttachments() - .stream() - .map(AttachmentResource::new) - .collect(Collectors.toList()); - custom1 = task.getCustomAttribute("1"); - custom2 = task.getCustomAttribute("2"); - custom3 = task.getCustomAttribute("3"); - custom4 = task.getCustomAttribute("4"); - custom5 = task.getCustomAttribute("5"); - custom6 = task.getCustomAttribute("6"); - custom7 = task.getCustomAttribute("7"); - custom8 = task.getCustomAttribute("8"); - custom9 = task.getCustomAttribute("9"); - custom10 = task.getCustomAttribute("10"); - custom11 = task.getCustomAttribute("11"); - custom12 = task.getCustomAttribute("12"); - custom13 = task.getCustomAttribute("13"); - custom14 = task.getCustomAttribute("14"); - custom15 = task.getCustomAttribute("15"); - custom16 = task.getCustomAttribute("16"); + attachments = + task.getAttachments().stream().map(AttachmentResource::new).collect(Collectors.toList()); + custom1 = task.getCustomAttribute("1"); + custom2 = task.getCustomAttribute("2"); + custom3 = task.getCustomAttribute("3"); + custom4 = task.getCustomAttribute("4"); + custom5 = task.getCustomAttribute("5"); + custom6 = task.getCustomAttribute("6"); + custom7 = task.getCustomAttribute("7"); + custom8 = task.getCustomAttribute("8"); + custom9 = task.getCustomAttribute("9"); + custom10 = task.getCustomAttribute("10"); + custom11 = task.getCustomAttribute("11"); + custom12 = task.getCustomAttribute("12"); + custom13 = task.getCustomAttribute("13"); + custom14 = task.getCustomAttribute("14"); + custom15 = task.getCustomAttribute("15"); + custom16 = task.getCustomAttribute("16"); + } + + public String getTaskId() { + return taskId; + } + + public void setTaskId(String taskId) { + this.taskId = taskId; + } + + public String getExternalId() { + return externalId; + } + + public void setExternalId(String externalId) { + this.externalId = externalId; + } + + public String getCreated() { + return created; + } + + public void setCreated(String created) { + this.created = created; + } + + public String getClaimed() { + return claimed; + } + + public void setClaimed(String claimed) { + this.claimed = claimed; + } + + public String getCompleted() { + return completed; + } + + public void setCompleted(String completed) { + this.completed = completed; + } + + public String getModified() { + return modified; + } + + public void setModified(String modified) { + this.modified = modified; + } + + public String getPlanned() { + return planned; + } + + public void setPlanned(String planned) { + this.planned = planned; + } + + public String getDue() { + return due; + } + + public void setDue(String due) { + this.due = due; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCreator() { + return creator; + } + + public void setCreator(String creator) { + this.creator = creator; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getNote() { + return note; + } + + public void setNote(String note) { + this.note = note; + } + + public int getPriority() { + return priority; + } - } - - public String getTaskId() { - return taskId; - } - - public void setTaskId(String taskId) { - this.taskId = taskId; - } - - public String getExternalId() { - return externalId; - } - - public void setExternalId(String externalId) { - this.externalId = externalId; - } - - public String getCreated() { - return created; - } - - public void setCreated(String created) { - this.created = created; - } - - public String getClaimed() { - return claimed; - } - - public void setClaimed(String claimed) { - this.claimed = claimed; - } - - public String getCompleted() { - return completed; - } - - public void setCompleted(String completed) { - this.completed = completed; - } - - public String getModified() { - return modified; - } - - public void setModified(String modified) { - this.modified = modified; - } - - public String getPlanned() { - return planned; - } - - public void setPlanned(String planned) { - this.planned = planned; - } - - public String getDue() { - return due; - } - - public void setDue(String due) { - this.due = due; - } + public void setPriority(int priority) { + this.priority = priority; + } - public String getName() { - return name; - } + public TaskState getState() { + return state; + } - public void setName(String name) { - this.name = name; - } + public void setState(TaskState state) { + this.state = state; + } - public String getCreator() { - return creator; - } + public ClassificationSummaryResource getClassificationSummaryResource() { + return classificationSummaryResource; + } - public void setCreator(String creator) { - this.creator = creator; - } + public void setClassificationSummaryResource( + ClassificationSummaryResource classificationSummaryResource) { + this.classificationSummaryResource = classificationSummaryResource; + } - public String getDescription() { - return description; - } + public WorkbasketSummaryResource getWorkbasketSummaryResource() { + return workbasketSummaryResource; + } - public void setDescription(String description) { - this.description = description; - } + public void setWorkbasketSummaryResource(WorkbasketSummaryResource workbasketSummaryResource) { + this.workbasketSummaryResource = workbasketSummaryResource; + } - public String getNote() { - return note; - } + public String getBusinessProcessId() { + return businessProcessId; + } - public void setNote(String note) { - this.note = note; - } + public void setBusinessProcessId(String businessProcessId) { + this.businessProcessId = businessProcessId; + } - public int getPriority() { - return priority; - } + public String getParentBusinessProcessId() { + return parentBusinessProcessId; + } - public void setPriority(int priority) { - this.priority = priority; - } + public void setParentBusinessProcessId(String parentBusinessProcessId) { + this.parentBusinessProcessId = parentBusinessProcessId; + } - public TaskState getState() { - return state; - } + public String getOwner() { + return owner; + } - public void setState(TaskState state) { - this.state = state; - } + public void setOwner(String owner) { + this.owner = owner; + } - public ClassificationSummaryResource getClassificationSummaryResource() { - return classificationSummaryResource; - } + public ObjectReference getPrimaryObjRef() { + return primaryObjRef; + } - public void setClassificationSummaryResource(ClassificationSummaryResource classificationSummaryResource) { - this.classificationSummaryResource = classificationSummaryResource; - } + public void setPrimaryObjRef(ObjectReference primaryObjRef) { + this.primaryObjRef = primaryObjRef; + } - public WorkbasketSummaryResource getWorkbasketSummaryResource() { - return workbasketSummaryResource; - } + public boolean isRead() { + return isRead; + } - public void setWorkbasketSummaryResource(WorkbasketSummaryResource workbasketSummaryResource) { - this.workbasketSummaryResource = workbasketSummaryResource; - } + public void setRead(boolean isRead) { + this.isRead = isRead; + } - public String getBusinessProcessId() { - return businessProcessId; - } + public boolean isTransferred() { + return isTransferred; + } - public void setBusinessProcessId(String businessProcessId) { - this.businessProcessId = businessProcessId; - } - - public String getParentBusinessProcessId() { - return parentBusinessProcessId; - } + public void setTransferred(boolean isTransferred) { + this.isTransferred = isTransferred; + } - public void setParentBusinessProcessId(String parentBusinessProcessId) { - this.parentBusinessProcessId = parentBusinessProcessId; - } + public List getCustomAttributes() { + return customAttributes; + } - public String getOwner() { - return owner; - } + public void setCustomAttributes(List customAttributes) { + this.customAttributes = customAttributes; + } - public void setOwner(String owner) { - this.owner = owner; - } + public List getCallbackInfo() { + return callbackInfo; + } - public ObjectReference getPrimaryObjRef() { - return primaryObjRef; - } + public void setCallbackInfo(List callbackInfo) { + this.callbackInfo = callbackInfo; + } - public void setPrimaryObjRef(ObjectReference primaryObjRef) { - this.primaryObjRef = primaryObjRef; - } + public List getAttachments() { + return attachments; + } - public boolean isRead() { - return isRead; - } + public void setAttachments(List attachments) { + this.attachments = attachments; + } - public void setRead(boolean isRead) { - this.isRead = isRead; - } + public String getCustom1() { + return custom1; + } - public boolean isTransferred() { - return isTransferred; - } + public void setCustom1(String custom1) { + this.custom1 = custom1; + } - public void setTransferred(boolean isTransferred) { - this.isTransferred = isTransferred; - } + public String getCustom2() { + return custom2; + } - public List getCustomAttributes() { - return customAttributes; - } + public void setCustom2(String custom2) { + this.custom2 = custom2; + } - public void setCustomAttributes(List customAttributes) { - this.customAttributes = customAttributes; - } + public String getCustom3() { + return custom3; + } - public List getCallbackInfo() { - return callbackInfo; - } + public void setCustom3(String custom3) { + this.custom3 = custom3; + } - public void setCallbackInfo(List callbackInfo) { - this.callbackInfo = callbackInfo; - } + public String getCustom4() { + return custom4; + } - public List getAttachments() { - return attachments; - } - - public void setAttachments(List attachments) { - this.attachments = attachments; - } - - public String getCustom1() { - return custom1; - } - - public void setCustom1(String custom1) { - this.custom1 = custom1; - } - - public String getCustom2() { - return custom2; - } - - public void setCustom2(String custom2) { - this.custom2 = custom2; - } - - public String getCustom3() { - return custom3; - } - - public void setCustom3(String custom3) { - this.custom3 = custom3; - } - - public String getCustom4() { - return custom4; - } - - public void setCustom4(String custom4) { - this.custom4 = custom4; - } - - public String getCustom5() { - return custom5; - } - - public void setCustom5(String custom5) { - this.custom5 = custom5; - } - - public String getCustom6() { - return custom6; - } - - public void setCustom6(String custom6) { - this.custom6 = custom6; - } - - public String getCustom7() { - return custom7; - } - - public void setCustom7(String custom7) { - this.custom7 = custom7; - } - - public String getCustom8() { - return custom8; - } - - public void setCustom8(String custom8) { - this.custom8 = custom8; - } - - public String getCustom9() { - return custom9; - } - - public void setCustom9(String custom9) { - this.custom9 = custom9; - } - - public String getCustom10() { - return custom10; - } - - public void setCustom10(String custom10) { - this.custom10 = custom10; - } - - public String getCustom11() { - return custom11; - } - - public void setCustom11(String custom11) { - this.custom11 = custom11; - } - - public String getCustom12() { - return custom12; - } - - public void setCustom12(String custom12) { - this.custom12 = custom12; - } - - public String getCustom13() { - return custom13; - } - - public void setCustom13(String custom13) { - this.custom13 = custom13; - } - - public String getCustom14() { - return custom14; - } - - public void setCustom14(String custom14) { - this.custom14 = custom14; - } - - public String getCustom15() { - return custom15; - } - - public void setCustom15(String custom15) { - this.custom15 = custom15; - } - - public String getCustom16() { - return custom16; - } + public void setCustom4(String custom4) { + this.custom4 = custom4; + } - public void setCustom16(String custom16) { - this.custom16 = custom16; + public String getCustom5() { + return custom5; + } + + public void setCustom5(String custom5) { + this.custom5 = custom5; + } + + public String getCustom6() { + return custom6; + } + + public void setCustom6(String custom6) { + this.custom6 = custom6; + } + + public String getCustom7() { + return custom7; + } + + public void setCustom7(String custom7) { + this.custom7 = custom7; + } + + public String getCustom8() { + return custom8; + } + + public void setCustom8(String custom8) { + this.custom8 = custom8; + } + + public String getCustom9() { + return custom9; + } + + public void setCustom9(String custom9) { + this.custom9 = custom9; + } + + public String getCustom10() { + return custom10; + } + + public void setCustom10(String custom10) { + this.custom10 = custom10; + } + + public String getCustom11() { + return custom11; + } + + public void setCustom11(String custom11) { + this.custom11 = custom11; + } + + public String getCustom12() { + return custom12; + } + + public void setCustom12(String custom12) { + this.custom12 = custom12; + } + + public String getCustom13() { + return custom13; + } + + public void setCustom13(String custom13) { + this.custom13 = custom13; + } + + public String getCustom14() { + return custom14; + } + + public void setCustom14(String custom14) { + this.custom14 = custom14; + } + + public String getCustom15() { + return custom15; + } + + public void setCustom15(String custom15) { + this.custom15 = custom15; + } + + public String getCustom16() { + return custom16; + } + + public void setCustom16(String custom16) { + this.custom16 = custom16; + } + + @Override + public String toString() { + return "TaskResource [" + + "taskId= " + + this.taskId + + "externalId= " + + this.externalId + + "created= " + + this.created + + "modified= " + + this.modified + + "claimed= " + + this.claimed + + "completed= " + + this.completed + + "planned= " + + this.planned + + "due= " + + this.due + + "name= " + + this.name + + "creator= " + + this.creator + + "description= " + + this.description + + "priority= " + + this.priority + + "owner= " + + this.owner + + "]"; + } + + /** + * A CustomAttribute is a user customized attribute which is saved as a Map and can be retreived + * from either {@link pro.taskana.Task#getCustomAttributes()} or {@link + * pro.taskana.Task#getCallbackInfo()}. + */ + public static class CustomAttribute { + + private final String key; + private final String value; + + @SuppressWarnings("unused") + public CustomAttribute() { + this(null, null); + // necessary for jackson. + } + + public CustomAttribute(String key, String value) { + this.key = key; + this.value = value; + } + + public String getKey() { + return key; + } + + public String getValue() { + return value; } @Override public String toString() { - return "TaskResource [" - + "taskId= " + this.taskId - + "externalId= " + this.externalId - + "created= " + this.created - + "modified= " + this.modified - + "claimed= " + this.claimed - + "completed= " + this.completed - + "planned= " + this.planned - + "due= " + this.due - + "name= " + this.name - + "creator= " + this.creator - + "description= " + this.description - + "priority= " + this.priority - + "owner= " + this.owner - + "]"; - } - - /** - * A CustomAttribute is a user customized attribute which is saved as a Map and can be retreived from - * either {@link pro.taskana.Task#getCustomAttributes()} or {@link pro.taskana.Task#getCallbackInfo()}. - */ - public static class CustomAttribute { - - private final String key; - private final String value; - - @SuppressWarnings("unused") - public CustomAttribute() { - this(null, null); - //necessary for jackson. - } - - public CustomAttribute(String key, String value) { - this.key = key; - this.value = value; - } - - public String getKey() { - return key; - } - - public String getValue() { - return value; - } - - @Override - public String toString() { - return "CustomAttribute [" - + "key= " + this.key - + "value= " + this.value - + "]"; - } + return "CustomAttribute [" + "key= " + this.key + "value= " + this.value + "]"; } + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/TaskResourceAssembler.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/TaskResourceAssembler.java index 3c8a49765..825dcc968 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/TaskResourceAssembler.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/TaskResourceAssembler.java @@ -5,7 +5,6 @@ import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import java.time.Instant; import java.util.Objects; import java.util.stream.Collectors; - import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.mvc.ResourceAssemblerSupport; @@ -18,91 +17,91 @@ import pro.taskana.exceptions.SystemException; import pro.taskana.impl.TaskImpl; import pro.taskana.rest.TaskController; -/** - * Resource assembler for {@link TaskResource}. - */ +/** Resource assembler for {@link TaskResource}. */ @Component -public class TaskResourceAssembler - extends ResourceAssemblerSupport { +public class TaskResourceAssembler extends ResourceAssemblerSupport { - @Autowired - private TaskService taskService; + @Autowired private TaskService taskService; - @Autowired - private ClassificationSummaryResourceAssembler classificationAssembler; + @Autowired private ClassificationSummaryResourceAssembler classificationAssembler; - @Autowired - private WorkbasketSummaryResourceAssembler workbasketAssembler; + @Autowired private WorkbasketSummaryResourceAssembler workbasketAssembler; - @Autowired - private AttachmentResourceAssembler attachmentAssembler; + @Autowired private AttachmentResourceAssembler attachmentAssembler; - public TaskResourceAssembler() { - super(TaskController.class, TaskResource.class); + public TaskResourceAssembler() { + super(TaskController.class, TaskResource.class); + } + + @Override + public TaskResource toResource(Task task) { + TaskResource resource; + try { + resource = new TaskResource(task); + resource.add(linkTo(TaskController.class).slash(task.getId()).withSelfRel()); + } catch (InvalidArgumentException e) { + throw new SystemException("caught unexpected Exception.", e.getCause()); } + return resource; + } - @Override - public TaskResource toResource(Task task) { - TaskResource resource; - try { - resource = new TaskResource(task); - resource.add(linkTo(TaskController.class).slash(task.getId()).withSelfRel()); - } catch (InvalidArgumentException e) { - throw new SystemException("caught unexpected Exception.", e.getCause()); - } - return resource; + public Task toModel(TaskResource resource) throws InvalidArgumentException { + validateTaskResource(resource); + TaskImpl task = + (TaskImpl) taskService.newTask(resource.getWorkbasketSummaryResource().getWorkbasketId()); + task.setId(resource.getTaskId()); + task.setExternalId(resource.getExternalId()); + BeanUtils.copyProperties(resource, task); + if (resource.getCreated() != null) { + task.setCreated(Instant.parse(resource.getCreated())); } - - public Task toModel(TaskResource resource) throws InvalidArgumentException { - validateTaskResource(resource); - TaskImpl task = (TaskImpl) taskService.newTask(resource.getWorkbasketSummaryResource().getWorkbasketId()); - task.setId(resource.getTaskId()); - task.setExternalId(resource.getExternalId()); - BeanUtils.copyProperties(resource, task); - if (resource.getCreated() != null) { - task.setCreated(Instant.parse(resource.getCreated())); - } - if (resource.getModified() != null) { - task.setModified(Instant.parse(resource.getModified())); - } - if (resource.getClaimed() != null) { - task.setClaimed(Instant.parse(resource.getClaimed())); - } - if (resource.getCompleted() != null) { - task.setCompleted(Instant.parse(resource.getCompleted())); - } - if (resource.getDue() != null) { - task.setDue(Instant.parse(resource.getDue())); - } - if (resource.getPlanned() != null) { - task.setPlanned(Instant.parse(resource.getPlanned())); - } - task.setClassificationSummary(classificationAssembler.toModel(resource.getClassificationSummaryResource())); - task.setWorkbasketSummary(workbasketAssembler.toModel(resource.getWorkbasketSummaryResource())); - task.setAttachments(attachmentAssembler.toModel(resource.getAttachments())); - task.setCustomAttributes(resource.getCustomAttributes().stream() + if (resource.getModified() != null) { + task.setModified(Instant.parse(resource.getModified())); + } + if (resource.getClaimed() != null) { + task.setClaimed(Instant.parse(resource.getClaimed())); + } + if (resource.getCompleted() != null) { + task.setCompleted(Instant.parse(resource.getCompleted())); + } + if (resource.getDue() != null) { + task.setDue(Instant.parse(resource.getDue())); + } + if (resource.getPlanned() != null) { + task.setPlanned(Instant.parse(resource.getPlanned())); + } + task.setClassificationSummary( + classificationAssembler.toModel(resource.getClassificationSummaryResource())); + task.setWorkbasketSummary(workbasketAssembler.toModel(resource.getWorkbasketSummaryResource())); + task.setAttachments(attachmentAssembler.toModel(resource.getAttachments())); + task.setCustomAttributes( + resource.getCustomAttributes().stream() .filter(e -> Objects.nonNull(e.getKey()) && !e.getKey().isEmpty()) - .collect(Collectors.toMap(TaskResource.CustomAttribute::getKey, TaskResource.CustomAttribute::getValue))); - task.setCallbackInfo(resource.getCallbackInfo().stream() + .collect( + Collectors.toMap( + TaskResource.CustomAttribute::getKey, TaskResource.CustomAttribute::getValue))); + task.setCallbackInfo( + resource.getCallbackInfo().stream() .filter(e -> Objects.nonNull(e.getKey()) && !e.getKey().isEmpty()) - .collect(Collectors.toMap(TaskResource.CustomAttribute::getKey, TaskResource.CustomAttribute::getValue))); + .collect( + Collectors.toMap( + TaskResource.CustomAttribute::getKey, TaskResource.CustomAttribute::getValue))); - return task; + return task; + } + + private void validateTaskResource(TaskResource resource) throws InvalidArgumentException { + if (resource.getWorkbasketSummaryResource() == null + || resource.getWorkbasketSummaryResource().getWorkbasketId() == null + || resource.getWorkbasketSummaryResource().getWorkbasketId().isEmpty()) { + throw new InvalidArgumentException( + "TaskResource must have a workbasket summary with a valid workbasketId."); } - - private void validateTaskResource(TaskResource resource) throws InvalidArgumentException { - if (resource.getWorkbasketSummaryResource() == null - || resource.getWorkbasketSummaryResource().getWorkbasketId() == null - || resource.getWorkbasketSummaryResource().getWorkbasketId().isEmpty()) { - throw new InvalidArgumentException( - "TaskResource must have a workbasket summary with a valid workbasketId."); - } - if (resource.getClassificationSummaryResource() == null - || resource.getClassificationSummaryResource().getKey() == null - || resource.getClassificationSummaryResource().getKey().isEmpty()) { - throw new InvalidArgumentException( - "TaskResource must have a classification summary with a valid classification key."); - } + if (resource.getClassificationSummaryResource() == null + || resource.getClassificationSummaryResource().getKey() == null + || resource.getClassificationSummaryResource().getKey().isEmpty()) { + throw new InvalidArgumentException( + "TaskResource must have a classification summary with a valid classification key."); } - + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/TaskSummaryListResource.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/TaskSummaryListResource.java index c04c02e2b..5759f43c5 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/TaskSummaryListResource.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/TaskSummaryListResource.java @@ -1,33 +1,29 @@ package pro.taskana.rest.resource; +import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Collection; - import org.springframework.hateoas.Link; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * Resource class for {@link TaskSummaryResource} with Pagination. - */ +/** Resource class for {@link TaskSummaryResource} with Pagination. */ public class TaskSummaryListResource extends PagedResources { - public TaskSummaryListResource() { - super(); - } + public TaskSummaryListResource() { + super(); + } - public TaskSummaryListResource(Collection content, PageMetadata metadata, - Iterable links) { - super(content, metadata, links); - } + public TaskSummaryListResource( + Collection content, PageMetadata metadata, Iterable links) { + super(content, metadata, links); + } - public TaskSummaryListResource(Collection content, PageMetadata metadata, Link... links) { - super(content, metadata, links); - } - - @Override - @JsonProperty("tasks") - public Collection getContent() { - return super.getContent(); - } + public TaskSummaryListResource( + Collection content, PageMetadata metadata, Link... links) { + super(content, metadata, links); + } + @Override + @JsonProperty("tasks") + public Collection getContent() { + return super.getContent(); + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/TaskSummaryResource.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/TaskSummaryResource.java index de06199e5..089a17080 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/TaskSummaryResource.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/TaskSummaryResource.java @@ -3,7 +3,6 @@ package pro.taskana.rest.resource; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; - import org.springframework.hateoas.ResourceSupport; import org.springframework.hateoas.core.Relation; @@ -12,417 +11,429 @@ import pro.taskana.TaskState; import pro.taskana.TaskSummary; import pro.taskana.exceptions.InvalidArgumentException; -/** - * Resource class for {@link pro.taskana.WorkbasketSummary}. - */ +/** Resource class for {@link pro.taskana.WorkbasketSummary}. */ @Relation(collectionRelation = "tasks") public class TaskSummaryResource extends ResourceSupport { - private String taskId; - private String externalId; - private String created; // ISO-8601 - private String claimed; // ISO-8601 - private String completed; // ISO-8601 - private String modified; // ISO-8601 - private String planned; // ISO-8601 - private String due; // ISO-8601 - private String name; - private String creator; - private String note; - private int priority; - private TaskState state; - private ClassificationSummaryResource classificationSummaryResource; - private WorkbasketSummaryResource workbasketSummaryResource; - private String businessProcessId; - private String parentBusinessProcessId; - private String owner; - private ObjectReference primaryObjRef; - private boolean isRead; - private boolean isTransferred; - private List attachmentSummaryResources = new ArrayList<>(); - private String custom1; - private String custom2; - private String custom3; - private String custom4; - private String custom5; - private String custom6; - private String custom7; - private String custom8; - private String custom9; - private String custom10; - private String custom11; - private String custom12; - private String custom13; - private String custom14; - private String custom15; - private String custom16; + private String taskId; + private String externalId; + private String created; // ISO-8601 + private String claimed; // ISO-8601 + private String completed; // ISO-8601 + private String modified; // ISO-8601 + private String planned; // ISO-8601 + private String due; // ISO-8601 + private String name; + private String creator; + private String note; + private int priority; + private TaskState state; + private ClassificationSummaryResource classificationSummaryResource; + private WorkbasketSummaryResource workbasketSummaryResource; + private String businessProcessId; + private String parentBusinessProcessId; + private String owner; + private ObjectReference primaryObjRef; + private boolean isRead; + private boolean isTransferred; + private List attachmentSummaryResources = new ArrayList<>(); + private String custom1; + private String custom2; + private String custom3; + private String custom4; + private String custom5; + private String custom6; + private String custom7; + private String custom8; + private String custom9; + private String custom10; + private String custom11; + private String custom12; + private String custom13; + private String custom14; + private String custom15; + private String custom16; - TaskSummaryResource() { - } + TaskSummaryResource() {} - public TaskSummaryResource(TaskSummary taskSummary) throws InvalidArgumentException { - this.taskId = taskSummary.getTaskId(); - this.externalId = taskSummary.getExternalId(); - created = taskSummary.getCreated() != null ? taskSummary.getCreated().toString() : null; - claimed = taskSummary.getClaimed() != null ? taskSummary.getClaimed().toString() : null; - completed = taskSummary.getCompleted() != null ? taskSummary.getCompleted().toString() : null; - modified = taskSummary.getModified() != null ? taskSummary.getModified().toString() : null; - planned = taskSummary.getPlanned() != null ? taskSummary.getPlanned().toString() : null; - due = taskSummary.getDue() != null ? taskSummary.getDue().toString() : null; - this.name = taskSummary.getName(); - this.creator = taskSummary.getCreator(); - this.note = taskSummary.getNote(); - this.priority = taskSummary.getPriority(); - this.state = taskSummary.getState(); - this.classificationSummaryResource = new ClassificationSummaryResource(taskSummary.getClassificationSummary()); - this.workbasketSummaryResource = new WorkbasketSummaryResource(taskSummary.getWorkbasketSummary()); - this.businessProcessId = taskSummary.getBusinessProcessId(); - this.parentBusinessProcessId = taskSummary.getParentBusinessProcessId(); - this.owner = taskSummary.getOwner(); - this.primaryObjRef = taskSummary.getPrimaryObjRef(); - this.isRead = taskSummary.isRead(); - this.isTransferred = taskSummary.isTransferred(); - this.attachmentSummaryResources = taskSummary.getAttachmentSummaries() - .stream() + public TaskSummaryResource(TaskSummary taskSummary) throws InvalidArgumentException { + this.taskId = taskSummary.getTaskId(); + this.externalId = taskSummary.getExternalId(); + created = taskSummary.getCreated() != null ? taskSummary.getCreated().toString() : null; + claimed = taskSummary.getClaimed() != null ? taskSummary.getClaimed().toString() : null; + completed = taskSummary.getCompleted() != null ? taskSummary.getCompleted().toString() : null; + modified = taskSummary.getModified() != null ? taskSummary.getModified().toString() : null; + planned = taskSummary.getPlanned() != null ? taskSummary.getPlanned().toString() : null; + due = taskSummary.getDue() != null ? taskSummary.getDue().toString() : null; + this.name = taskSummary.getName(); + this.creator = taskSummary.getCreator(); + this.note = taskSummary.getNote(); + this.priority = taskSummary.getPriority(); + this.state = taskSummary.getState(); + this.classificationSummaryResource = + new ClassificationSummaryResource(taskSummary.getClassificationSummary()); + this.workbasketSummaryResource = + new WorkbasketSummaryResource(taskSummary.getWorkbasketSummary()); + this.businessProcessId = taskSummary.getBusinessProcessId(); + this.parentBusinessProcessId = taskSummary.getParentBusinessProcessId(); + this.owner = taskSummary.getOwner(); + this.primaryObjRef = taskSummary.getPrimaryObjRef(); + this.isRead = taskSummary.isRead(); + this.isTransferred = taskSummary.isTransferred(); + this.attachmentSummaryResources = + taskSummary.getAttachmentSummaries().stream() .map(AttachmentSummaryResource::new) .collect(Collectors.toList()); - this.custom1 = taskSummary.getCustomAttribute("1"); - this.custom2 = taskSummary.getCustomAttribute("2"); - this.custom3 = taskSummary.getCustomAttribute("3"); - this.custom4 = taskSummary.getCustomAttribute("4"); - this.custom5 = taskSummary.getCustomAttribute("5"); - this.custom6 = taskSummary.getCustomAttribute("6"); - this.custom7 = taskSummary.getCustomAttribute("7"); - this.custom8 = taskSummary.getCustomAttribute("8"); - this.custom9 = taskSummary.getCustomAttribute("9"); - this.custom10 = taskSummary.getCustomAttribute("10"); - this.custom11 = taskSummary.getCustomAttribute("11"); - this.custom12 = taskSummary.getCustomAttribute("12"); - this.custom13 = taskSummary.getCustomAttribute("13"); - this.custom14 = taskSummary.getCustomAttribute("14"); - this.custom15 = taskSummary.getCustomAttribute("15"); - this.custom16 = taskSummary.getCustomAttribute("16"); - } - - public String getTaskId() { - return taskId; - } - - public void setTaskId(String taskId) { - this.taskId = taskId; - } - - public String getExternalId() { - return externalId; - } - - public void setExternalId(String externalId) { - this.externalId = externalId; - } - - public String getCreated() { - return created; - } - - public void setCreated(String created) { - this.created = created; - } - - public String getClaimed() { - return claimed; - } - - public void setClaimed(String claimed) { - this.claimed = claimed; - } - - public String getCompleted() { - return completed; - } - - public void setCompleted(String completed) { - this.completed = completed; - } - - public String getModified() { - return modified; - } - - public void setModified(String modified) { - this.modified = modified; - } - - public String getPlanned() { - return planned; - } - - public void setPlanned(String planned) { - this.planned = planned; - } - - public String getDue() { - return due; - } - - public void setDue(String due) { - this.due = due; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getCreator() { - return creator; - } - - public void setCreator(String creator) { - this.creator = creator; - } - - public String getNote() { - return note; - } - - public void setNote(String note) { - this.note = note; - } - - public int getPriority() { - return priority; - } - - public void setPriority(int priority) { - this.priority = priority; - } + this.custom1 = taskSummary.getCustomAttribute("1"); + this.custom2 = taskSummary.getCustomAttribute("2"); + this.custom3 = taskSummary.getCustomAttribute("3"); + this.custom4 = taskSummary.getCustomAttribute("4"); + this.custom5 = taskSummary.getCustomAttribute("5"); + this.custom6 = taskSummary.getCustomAttribute("6"); + this.custom7 = taskSummary.getCustomAttribute("7"); + this.custom8 = taskSummary.getCustomAttribute("8"); + this.custom9 = taskSummary.getCustomAttribute("9"); + this.custom10 = taskSummary.getCustomAttribute("10"); + this.custom11 = taskSummary.getCustomAttribute("11"); + this.custom12 = taskSummary.getCustomAttribute("12"); + this.custom13 = taskSummary.getCustomAttribute("13"); + this.custom14 = taskSummary.getCustomAttribute("14"); + this.custom15 = taskSummary.getCustomAttribute("15"); + this.custom16 = taskSummary.getCustomAttribute("16"); + } + + public String getTaskId() { + return taskId; + } + + public void setTaskId(String taskId) { + this.taskId = taskId; + } + + public String getExternalId() { + return externalId; + } + + public void setExternalId(String externalId) { + this.externalId = externalId; + } + + public String getCreated() { + return created; + } + + public void setCreated(String created) { + this.created = created; + } + + public String getClaimed() { + return claimed; + } + + public void setClaimed(String claimed) { + this.claimed = claimed; + } + + public String getCompleted() { + return completed; + } + + public void setCompleted(String completed) { + this.completed = completed; + } + + public String getModified() { + return modified; + } + + public void setModified(String modified) { + this.modified = modified; + } + + public String getPlanned() { + return planned; + } + + public void setPlanned(String planned) { + this.planned = planned; + } + + public String getDue() { + return due; + } + + public void setDue(String due) { + this.due = due; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCreator() { + return creator; + } + + public void setCreator(String creator) { + this.creator = creator; + } + + public String getNote() { + return note; + } + + public void setNote(String note) { + this.note = note; + } + + public int getPriority() { + return priority; + } + + public void setPriority(int priority) { + this.priority = priority; + } + + public TaskState getState() { + return state; + } - public TaskState getState() { - return state; - } + public void setState(TaskState state) { + this.state = state; + } - public void setState(TaskState state) { - this.state = state; - } + public ClassificationSummaryResource getClassificationSummaryResource() { + return classificationSummaryResource; + } - public ClassificationSummaryResource getClassificationSummaryResource() { - return classificationSummaryResource; - } + public void setClassificationSummaryResource( + ClassificationSummaryResource classificationSummaryResource) { + this.classificationSummaryResource = classificationSummaryResource; + } - public void setClassificationSummaryResource(ClassificationSummaryResource classificationSummaryResource) { - this.classificationSummaryResource = classificationSummaryResource; - } + public WorkbasketSummaryResource getWorkbasketSummaryResource() { + return workbasketSummaryResource; + } - public WorkbasketSummaryResource getWorkbasketSummaryResource() { - return workbasketSummaryResource; - } + public void setWorkbasketSummaryResource(WorkbasketSummaryResource workbasketSummaryResource) { + this.workbasketSummaryResource = workbasketSummaryResource; + } - public void setWorkbasketSummaryResource(WorkbasketSummaryResource workbasketSummaryResource) { - this.workbasketSummaryResource = workbasketSummaryResource; - } + public String getBusinessProcessId() { + return businessProcessId; + } - public String getBusinessProcessId() { - return businessProcessId; - } + public void setBusinessProcessId(String businessProcessId) { + this.businessProcessId = businessProcessId; + } - public void setBusinessProcessId(String businessProcessId) { - this.businessProcessId = businessProcessId; - } + public String getParentBusinessProcessId() { + return parentBusinessProcessId; + } - public String getParentBusinessProcessId() { - return parentBusinessProcessId; - } + public void setParentBusinessProcessId(String parentBusinessProcessId) { + this.parentBusinessProcessId = parentBusinessProcessId; + } - public void setParentBusinessProcessId(String parentBusinessProcessId) { - this.parentBusinessProcessId = parentBusinessProcessId; - } + public String getOwner() { + return owner; + } - public String getOwner() { - return owner; - } + public void setOwner(String owner) { + this.owner = owner; + } - public void setOwner(String owner) { - this.owner = owner; - } + public ObjectReference getPrimaryObjRef() { + return primaryObjRef; + } - public ObjectReference getPrimaryObjRef() { - return primaryObjRef; - } + public void setPrimaryObjRef(ObjectReference primaryObjRef) { + this.primaryObjRef = primaryObjRef; + } - public void setPrimaryObjRef(ObjectReference primaryObjRef) { - this.primaryObjRef = primaryObjRef; - } + public boolean isRead() { + return isRead; + } - public boolean isRead() { - return isRead; - } + public void setRead(boolean isRead) { + this.isRead = isRead; + } - public void setRead(boolean isRead) { - this.isRead = isRead; - } + public boolean isTransferred() { + return isTransferred; + } - public boolean isTransferred() { - return isTransferred; - } + public void setTransferred(boolean isTransferred) { + this.isTransferred = isTransferred; + } - public void setTransferred(boolean isTransferred) { - this.isTransferred = isTransferred; - } + public List getAttachmentSummaries() { + return attachmentSummaryResources; + } - public List getAttachmentSummaries() { - return attachmentSummaryResources; - } + public void setAttachmentSummaries(List attachmentSummaryResources) { + this.attachmentSummaryResources = attachmentSummaryResources; + } - public void setAttachmentSummaries(List attachmentSummaryResources) { - this.attachmentSummaryResources = attachmentSummaryResources; - } + public String getCustom1() { + return custom1; + } - public String getCustom1() { - return custom1; - } + public void setCustom1(String custom1) { + this.custom1 = custom1; + } - public void setCustom1(String custom1) { - this.custom1 = custom1; - } + public String getCustom2() { + return custom2; + } - public String getCustom2() { - return custom2; - } + public void setCustom2(String custom2) { + this.custom2 = custom2; + } - public void setCustom2(String custom2) { - this.custom2 = custom2; - } + public String getCustom3() { + return custom3; + } - public String getCustom3() { - return custom3; - } + public void setCustom3(String custom3) { + this.custom3 = custom3; + } - public void setCustom3(String custom3) { - this.custom3 = custom3; - } + public String getCustom4() { + return custom4; + } - public String getCustom4() { - return custom4; - } - - public void setCustom4(String custom4) { - this.custom4 = custom4; - } - - public String getCustom5() { - return custom5; - } - - public void setCustom5(String custom5) { - this.custom5 = custom5; - } - - public String getCustom6() { - return custom6; - } - - public void setCustom6(String custom6) { - this.custom6 = custom6; - } - - public String getCustom7() { - return custom7; - } - - public void setCustom7(String custom7) { - this.custom7 = custom7; - } - - public String getCustom8() { - return custom8; - } - - public void setCustom8(String custom8) { - this.custom8 = custom8; - } - - public String getCustom9() { - return custom9; - } - - public void setCustom9(String custom9) { - this.custom9 = custom9; - } - - public String getCustom10() { - return custom10; - } - - public void setCustom10(String custom10) { - this.custom10 = custom10; - } - - public String getCustom11() { - return custom11; - } - - public void setCustom11(String custom11) { - this.custom11 = custom11; - } - - public String getCustom12() { - return custom12; - } - - public void setCustom12(String custom12) { - this.custom12 = custom12; - } - - public String getCustom13() { - return custom13; - } - - public void setCustom13(String custom13) { - this.custom13 = custom13; - } - - public String getCustom14() { - return custom14; - } - - public void setCustom14(String custom14) { - this.custom14 = custom14; - } - - public String getCustom15() { - return custom15; - } - - public void setCustom15(String custom15) { - this.custom15 = custom15; - } - - public String getCustom16() { - return custom16; - } - - public void setCustom16(String custom16) { - this.custom16 = custom16; - } - - @Override - public String toString() { - return "TaskSummaryResource [" - + "taskId= " + this.taskId - + "externalId= " + this.externalId - + "created= " + this.created - + "modified= " + this.modified - + "claimed= " + this.claimed - + "completed= " + this.completed - + "planned= " + this.planned - + "due= " + this.due - + "name= " + this.name - + "creator= " + this.creator - + "priority= " + this.priority - + "owner= " + this.owner - + "]"; - } + public void setCustom4(String custom4) { + this.custom4 = custom4; + } + + public String getCustom5() { + return custom5; + } + + public void setCustom5(String custom5) { + this.custom5 = custom5; + } + + public String getCustom6() { + return custom6; + } + + public void setCustom6(String custom6) { + this.custom6 = custom6; + } + + public String getCustom7() { + return custom7; + } + + public void setCustom7(String custom7) { + this.custom7 = custom7; + } + + public String getCustom8() { + return custom8; + } + + public void setCustom8(String custom8) { + this.custom8 = custom8; + } + + public String getCustom9() { + return custom9; + } + + public void setCustom9(String custom9) { + this.custom9 = custom9; + } + + public String getCustom10() { + return custom10; + } + + public void setCustom10(String custom10) { + this.custom10 = custom10; + } + + public String getCustom11() { + return custom11; + } + + public void setCustom11(String custom11) { + this.custom11 = custom11; + } + + public String getCustom12() { + return custom12; + } + + public void setCustom12(String custom12) { + this.custom12 = custom12; + } + + public String getCustom13() { + return custom13; + } + + public void setCustom13(String custom13) { + this.custom13 = custom13; + } + + public String getCustom14() { + return custom14; + } + + public void setCustom14(String custom14) { + this.custom14 = custom14; + } + + public String getCustom15() { + return custom15; + } + + public void setCustom15(String custom15) { + this.custom15 = custom15; + } + + public String getCustom16() { + return custom16; + } + + public void setCustom16(String custom16) { + this.custom16 = custom16; + } + + @Override + public String toString() { + return "TaskSummaryResource [" + + "taskId= " + + this.taskId + + "externalId= " + + this.externalId + + "created= " + + this.created + + "modified= " + + this.modified + + "claimed= " + + this.claimed + + "completed= " + + this.completed + + "planned= " + + this.planned + + "due= " + + this.due + + "name= " + + this.name + + "creator= " + + this.creator + + "priority= " + + this.priority + + "owner= " + + this.owner + + "]"; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/TaskSummaryResourceAssembler.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/TaskSummaryResourceAssembler.java index ab87c6177..950df0bcd 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/TaskSummaryResourceAssembler.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/TaskSummaryResourceAssembler.java @@ -1,7 +1,6 @@ package pro.taskana.rest.resource; import java.util.List; - import org.springframework.hateoas.mvc.ResourceAssemblerSupport; import org.springframework.stereotype.Component; @@ -13,31 +12,29 @@ import pro.taskana.rest.TaskController; import pro.taskana.rest.resource.PagedResources.PageMetadata; import pro.taskana.rest.resource.links.PageLinks; -/** - * Resource assembler for {@link TaskSummaryResource}. - */ +/** Resource assembler for {@link TaskSummaryResource}. */ @Component public class TaskSummaryResourceAssembler extends ResourceAssemblerSupport { - public TaskSummaryResourceAssembler() { - super(TaskController.class, TaskSummaryResource.class); - } + public TaskSummaryResourceAssembler() { + super(TaskController.class, TaskSummaryResource.class); + } - @Override - public TaskSummaryResource toResource(TaskSummary taskSummary) { - TaskSummaryResource resource; - try { - resource = new TaskSummaryResource(taskSummary); - return resource; - } catch (InvalidArgumentException e) { - throw new SystemException("caught unexpected Exception.", e.getCause()); - } - } - - @PageLinks(Mapping.URL_TASKS) - public TaskSummaryListResource toResources(List taskSummaries, PageMetadata pageMetadata) { - return new TaskSummaryListResource(toResources(taskSummaries), pageMetadata); + @Override + public TaskSummaryResource toResource(TaskSummary taskSummary) { + TaskSummaryResource resource; + try { + resource = new TaskSummaryResource(taskSummary); + return resource; + } catch (InvalidArgumentException e) { + throw new SystemException("caught unexpected Exception.", e.getCause()); } + } + @PageLinks(Mapping.URL_TASKS) + public TaskSummaryListResource toResources( + List taskSummaries, PageMetadata pageMetadata) { + return new TaskSummaryListResource(toResources(taskSummaries), pageMetadata); + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/TaskanaUserInfoResource.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/TaskanaUserInfoResource.java index 41bec1140..83e61691a 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/TaskanaUserInfoResource.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/TaskanaUserInfoResource.java @@ -2,51 +2,51 @@ package pro.taskana.rest.resource; import java.util.ArrayList; import java.util.List; - import org.springframework.hateoas.ResourceSupport; import pro.taskana.TaskanaRole; import pro.taskana.impl.util.LoggerUtils; -/** - * Resource class for user information. - */ +/** Resource class for user information. */ public class TaskanaUserInfoResource extends ResourceSupport { - private String userId; - private List groupIds = new ArrayList<>(); - private List roles = new ArrayList<>(); + private String userId; + private List groupIds = new ArrayList<>(); + private List roles = new ArrayList<>(); - public String getUserId() { - return userId; - } + public String getUserId() { + return userId; + } - public void setUserId(String userId) { - this.userId = userId; - } + public void setUserId(String userId) { + this.userId = userId; + } - public List getGroupIds() { - return groupIds; - } + public List getGroupIds() { + return groupIds; + } - public void setGroupIds(List groupIds) { - this.groupIds = groupIds; - } + public void setGroupIds(List groupIds) { + this.groupIds = groupIds; + } - public List getRoles() { - return roles; - } + public List getRoles() { + return roles; + } - public void setRoles(List roles) { - this.roles = roles; - } + public void setRoles(List roles) { + this.roles = roles; + } - @Override - public String toString() { - return "TaskanaUserInfoResource [" - + "userId= " + this.userId - + "groupIds= " + LoggerUtils.listToString(this.groupIds) - + "roles= " + LoggerUtils.listToString(this.roles) - + "]"; - } + @Override + public String toString() { + return "TaskanaUserInfoResource [" + + "userId= " + + this.userId + + "groupIds= " + + LoggerUtils.listToString(this.groupIds) + + "roles= " + + LoggerUtils.listToString(this.roles) + + "]"; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/VersionResource.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/VersionResource.java index a00012bda..bcc0a0b0a 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/VersionResource.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/VersionResource.java @@ -2,23 +2,21 @@ package pro.taskana.rest.resource; import org.springframework.hateoas.ResourceSupport; -/** -* Resource class for version information. -*/ -public class VersionResource extends ResourceSupport { +/** Resource class for version information. */ +public class VersionResource extends ResourceSupport { - private String version; + private String version; - public String getVersion() { - return version; - } + public String getVersion() { + return version; + } - public void setVersion(String version) { - this.version = version; - } + public void setVersion(String version) { + this.version = version; + } - @Override - public String toString() { - return "VersionResource [" + "version= " + this.version + "]"; - } + @Override + public String toString() { + return "VersionResource [" + "version= " + this.version + "]"; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketAccessItemListResource.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketAccessItemListResource.java index f3bfe9838..8ca840f33 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketAccessItemListResource.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketAccessItemListResource.java @@ -1,32 +1,29 @@ package pro.taskana.rest.resource; +import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.Collection; - import org.springframework.hateoas.Link; -import com.fasterxml.jackson.annotation.JsonIgnore; - -/** - * Resource class for {@link WorkbasketAccessItemResource} without Pagination. - */ +/** Resource class for {@link WorkbasketAccessItemResource} without Pagination. */ public class WorkbasketAccessItemListResource extends WorkbasketAccessItemPaginatedListResource { - public WorkbasketAccessItemListResource() { - super(); - } + public WorkbasketAccessItemListResource() { + super(); + } - public WorkbasketAccessItemListResource(Collection content, Link... links) { - super(content, null, links); - } + public WorkbasketAccessItemListResource( + Collection content, Link... links) { + super(content, null, links); + } - public WorkbasketAccessItemListResource(Collection content, Iterable links) { - super(content, null, links); - } - - @Override - @JsonIgnore - public PageMetadata getMetadata() { - return super.getMetadata(); - } + public WorkbasketAccessItemListResource( + Collection content, Iterable links) { + super(content, null, links); + } + @Override + @JsonIgnore + public PageMetadata getMetadata() { + return super.getMetadata(); + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketAccessItemPaginatedListResource.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketAccessItemPaginatedListResource.java index cfc2ab3c6..9acfd8a32 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketAccessItemPaginatedListResource.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketAccessItemPaginatedListResource.java @@ -1,36 +1,32 @@ package pro.taskana.rest.resource; +import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Collection; - import org.springframework.hateoas.Link; -import com.fasterxml.jackson.annotation.JsonProperty; +/** Resource class for {@link WorkbasketAccessItemResource} with Pagination. */ +public class WorkbasketAccessItemPaginatedListResource + extends PagedResources { -/** - * Resource class for {@link WorkbasketAccessItemResource} with Pagination. - */ -public class WorkbasketAccessItemPaginatedListResource extends PagedResources { + public WorkbasketAccessItemPaginatedListResource() { + super(); + } - public WorkbasketAccessItemPaginatedListResource() { - super(); - } + public WorkbasketAccessItemPaginatedListResource( + Collection content, PageMetadata metadata, Link... links) { + super(content, metadata, links); + } - public WorkbasketAccessItemPaginatedListResource(Collection content, - PageMetadata metadata, - Link... links) { - super(content, metadata, links); - } - - public WorkbasketAccessItemPaginatedListResource(Collection content, - PageMetadata metadata, - Iterable links) { - super(content, metadata, links); - } - - @Override - @JsonProperty("accessItems") - public Collection getContent() { - return super.getContent(); - } + public WorkbasketAccessItemPaginatedListResource( + Collection content, + PageMetadata metadata, + Iterable links) { + super(content, metadata, links); + } + @Override + @JsonProperty("accessItems") + public Collection getContent() { + return super.getContent(); + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketAccessItemResource.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketAccessItemResource.java index 29c191355..1033a8557 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketAccessItemResource.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketAccessItemResource.java @@ -1,261 +1,259 @@ package pro.taskana.rest.resource; import javax.validation.constraints.NotNull; - import org.springframework.hateoas.ResourceSupport; import org.springframework.hateoas.core.Relation; import pro.taskana.WorkbasketAccessItem; -/** - * Resource class for {@link pro.taskana.WorkbasketAccessItem}. - */ +/** Resource class for {@link pro.taskana.WorkbasketAccessItem}. */ @Relation(collectionRelation = "accessItems") public class WorkbasketAccessItemResource extends ResourceSupport { - public String accessItemId; + public String accessItemId; - @NotNull - public String workbasketId; + @NotNull public String workbasketId; - @NotNull - public String workbasketKey; + @NotNull public String workbasketKey; - @NotNull - public String accessId; + @NotNull public String accessId; - public String accessName; + public String accessName; - public boolean permRead; - public boolean permOpen; - public boolean permAppend; - public boolean permTransfer; - public boolean permDistribute; - public boolean permCustom1; - public boolean permCustom2; - public boolean permCustom3; - public boolean permCustom4; - public boolean permCustom5; - public boolean permCustom6; - public boolean permCustom7; - public boolean permCustom8; - public boolean permCustom9; - public boolean permCustom10; - public boolean permCustom11; - public boolean permCustom12; + public boolean permRead; + public boolean permOpen; + public boolean permAppend; + public boolean permTransfer; + public boolean permDistribute; + public boolean permCustom1; + public boolean permCustom2; + public boolean permCustom3; + public boolean permCustom4; + public boolean permCustom5; + public boolean permCustom6; + public boolean permCustom7; + public boolean permCustom8; + public boolean permCustom9; + public boolean permCustom10; + public boolean permCustom11; + public boolean permCustom12; - public WorkbasketAccessItemResource() { - } + public WorkbasketAccessItemResource() {} - public WorkbasketAccessItemResource(WorkbasketAccessItem workbasketAccessItem) { - this.accessItemId = workbasketAccessItem.getId(); - this.workbasketId = workbasketAccessItem.getWorkbasketId(); - this.workbasketKey = workbasketAccessItem.getWorkbasketKey(); - this.accessId = workbasketAccessItem.getAccessId(); - this.accessName = workbasketAccessItem.getAccessName(); - this.permRead = workbasketAccessItem.isPermRead(); - this.permOpen = workbasketAccessItem.isPermOpen(); - this.permAppend = workbasketAccessItem.isPermAppend(); - this.permTransfer = workbasketAccessItem.isPermTransfer(); - this.permDistribute = workbasketAccessItem.isPermDistribute(); - this.permCustom1 = workbasketAccessItem.isPermCustom1(); - this.permCustom2 = workbasketAccessItem.isPermCustom2(); - this.permCustom3 = workbasketAccessItem.isPermCustom3(); - this.permCustom4 = workbasketAccessItem.isPermCustom4(); - this.permCustom5 = workbasketAccessItem.isPermCustom5(); - this.permCustom6 = workbasketAccessItem.isPermCustom6(); - this.permCustom7 = workbasketAccessItem.isPermCustom7(); - this.permCustom8 = workbasketAccessItem.isPermCustom8(); - this.permCustom9 = workbasketAccessItem.isPermCustom9(); - this.permCustom10 = workbasketAccessItem.isPermCustom10(); - this.permCustom11 = workbasketAccessItem.isPermCustom11(); - this.permCustom12 = workbasketAccessItem.isPermCustom12(); - } + public WorkbasketAccessItemResource(WorkbasketAccessItem workbasketAccessItem) { + this.accessItemId = workbasketAccessItem.getId(); + this.workbasketId = workbasketAccessItem.getWorkbasketId(); + this.workbasketKey = workbasketAccessItem.getWorkbasketKey(); + this.accessId = workbasketAccessItem.getAccessId(); + this.accessName = workbasketAccessItem.getAccessName(); + this.permRead = workbasketAccessItem.isPermRead(); + this.permOpen = workbasketAccessItem.isPermOpen(); + this.permAppend = workbasketAccessItem.isPermAppend(); + this.permTransfer = workbasketAccessItem.isPermTransfer(); + this.permDistribute = workbasketAccessItem.isPermDistribute(); + this.permCustom1 = workbasketAccessItem.isPermCustom1(); + this.permCustom2 = workbasketAccessItem.isPermCustom2(); + this.permCustom3 = workbasketAccessItem.isPermCustom3(); + this.permCustom4 = workbasketAccessItem.isPermCustom4(); + this.permCustom5 = workbasketAccessItem.isPermCustom5(); + this.permCustom6 = workbasketAccessItem.isPermCustom6(); + this.permCustom7 = workbasketAccessItem.isPermCustom7(); + this.permCustom8 = workbasketAccessItem.isPermCustom8(); + this.permCustom9 = workbasketAccessItem.isPermCustom9(); + this.permCustom10 = workbasketAccessItem.isPermCustom10(); + this.permCustom11 = workbasketAccessItem.isPermCustom11(); + this.permCustom12 = workbasketAccessItem.isPermCustom12(); + } - public String getAccessItemId() { - return accessItemId; - } + public String getAccessItemId() { + return accessItemId; + } - public void setAccessItemId(String accessItemId) { - this.accessItemId = accessItemId; - } + public void setAccessItemId(String accessItemId) { + this.accessItemId = accessItemId; + } - public String getWorkbasketId() { - return workbasketId; - } + public String getWorkbasketId() { + return workbasketId; + } - public void setWorkbasketId(String workbasketId) { - this.workbasketId = workbasketId; - } + public void setWorkbasketId(String workbasketId) { + this.workbasketId = workbasketId; + } - public String getWorkbasketKey() { - return workbasketKey; - } + public String getWorkbasketKey() { + return workbasketKey; + } - public void setWorkbasketKey(String workbasketKey) { - this.workbasketKey = workbasketKey; - } + public void setWorkbasketKey(String workbasketKey) { + this.workbasketKey = workbasketKey; + } - public String getAccessId() { - return accessId; - } + public String getAccessId() { + return accessId; + } - public void setAccessId(String accessId) { - this.accessId = accessId; - } + public void setAccessId(String accessId) { + this.accessId = accessId; + } - public String getAccessName() { - return accessName; - } + public String getAccessName() { + return accessName; + } - public void setAccessName(String accessName) { - this.accessName = accessName; - } + public void setAccessName(String accessName) { + this.accessName = accessName; + } - public boolean isPermRead() { - return permRead; - } + public boolean isPermRead() { + return permRead; + } - public void setPermRead(boolean permRead) { - this.permRead = permRead; - } + public void setPermRead(boolean permRead) { + this.permRead = permRead; + } - public boolean isPermOpen() { - return permOpen; - } + public boolean isPermOpen() { + return permOpen; + } - public void setPermOpen(boolean permOpen) { - this.permOpen = permOpen; - } + public void setPermOpen(boolean permOpen) { + this.permOpen = permOpen; + } - public boolean isPermAppend() { - return permAppend; - } + public boolean isPermAppend() { + return permAppend; + } - public void setPermAppend(boolean permAppend) { - this.permAppend = permAppend; - } + public void setPermAppend(boolean permAppend) { + this.permAppend = permAppend; + } - public boolean isPermTransfer() { - return permTransfer; - } + public boolean isPermTransfer() { + return permTransfer; + } - public void setPermTransfer(boolean permTransfer) { - this.permTransfer = permTransfer; - } + public void setPermTransfer(boolean permTransfer) { + this.permTransfer = permTransfer; + } - public boolean isPermDistribute() { - return permDistribute; - } + public boolean isPermDistribute() { + return permDistribute; + } - public void setPermDistribute(boolean permDistribute) { - this.permDistribute = permDistribute; - } + public void setPermDistribute(boolean permDistribute) { + this.permDistribute = permDistribute; + } - public boolean isPermCustom1() { - return permCustom1; - } + public boolean isPermCustom1() { + return permCustom1; + } - public void setPermCustom1(boolean permCustom1) { - this.permCustom1 = permCustom1; - } + public void setPermCustom1(boolean permCustom1) { + this.permCustom1 = permCustom1; + } - public boolean isPermCustom2() { - return permCustom2; - } + public boolean isPermCustom2() { + return permCustom2; + } - public void setPermCustom2(boolean permCustom2) { - this.permCustom2 = permCustom2; - } + public void setPermCustom2(boolean permCustom2) { + this.permCustom2 = permCustom2; + } - public boolean isPermCustom3() { - return permCustom3; - } + public boolean isPermCustom3() { + return permCustom3; + } - public void setPermCustom3(boolean permCustom3) { - this.permCustom3 = permCustom3; - } + public void setPermCustom3(boolean permCustom3) { + this.permCustom3 = permCustom3; + } - public boolean isPermCustom4() { - return permCustom4; - } + public boolean isPermCustom4() { + return permCustom4; + } - public void setPermCustom4(boolean permCustom4) { - this.permCustom4 = permCustom4; - } + public void setPermCustom4(boolean permCustom4) { + this.permCustom4 = permCustom4; + } - public boolean isPermCustom5() { - return permCustom5; - } + public boolean isPermCustom5() { + return permCustom5; + } - public void setPermCustom5(boolean permCustom5) { - this.permCustom5 = permCustom5; - } + public void setPermCustom5(boolean permCustom5) { + this.permCustom5 = permCustom5; + } - public boolean isPermCustom6() { - return permCustom6; - } + public boolean isPermCustom6() { + return permCustom6; + } - public void setPermCustom6(boolean permCustom6) { - this.permCustom6 = permCustom6; - } + public void setPermCustom6(boolean permCustom6) { + this.permCustom6 = permCustom6; + } - public boolean isPermCustom7() { - return permCustom7; - } + public boolean isPermCustom7() { + return permCustom7; + } - public void setPermCustom7(boolean permCustom7) { - this.permCustom7 = permCustom7; - } + public void setPermCustom7(boolean permCustom7) { + this.permCustom7 = permCustom7; + } - public boolean isPermCustom8() { - return permCustom8; - } + public boolean isPermCustom8() { + return permCustom8; + } - public void setPermCustom8(boolean permCustom8) { - this.permCustom8 = permCustom8; - } + public void setPermCustom8(boolean permCustom8) { + this.permCustom8 = permCustom8; + } - public boolean isPermCustom9() { - return permCustom9; - } + public boolean isPermCustom9() { + return permCustom9; + } - public void setPermCustom9(boolean permCustom9) { - this.permCustom9 = permCustom9; - } + public void setPermCustom9(boolean permCustom9) { + this.permCustom9 = permCustom9; + } - public boolean isPermCustom10() { - return permCustom10; - } + public boolean isPermCustom10() { + return permCustom10; + } - public void setPermCustom10(boolean permCustom10) { - this.permCustom10 = permCustom10; - } + public void setPermCustom10(boolean permCustom10) { + this.permCustom10 = permCustom10; + } - public boolean isPermCustom11() { - return permCustom11; - } + public boolean isPermCustom11() { + return permCustom11; + } - public void setPermCustom11(boolean permCustom11) { - this.permCustom11 = permCustom11; - } + public void setPermCustom11(boolean permCustom11) { + this.permCustom11 = permCustom11; + } - public boolean isPermCustom12() { - return permCustom12; - } + public boolean isPermCustom12() { + return permCustom12; + } - public void setPermCustom12(boolean permCustom12) { - this.permCustom12 = permCustom12; - } + public void setPermCustom12(boolean permCustom12) { + this.permCustom12 = permCustom12; + } - @Override - public String toString() { - return "WorkbasketAccessItemResource [" - + "accessItemId= " + this.accessItemId - + "workbasketId= " + this.workbasketId - + "workbasketKey= " + this.workbasketKey - + "accessId= " + this.accessId - + "accessName= " + this.accessName - + "]"; - } + @Override + public String toString() { + return "WorkbasketAccessItemResource [" + + "accessItemId= " + + this.accessItemId + + "workbasketId= " + + this.workbasketId + + "workbasketKey= " + + this.workbasketKey + + "accessId= " + + this.accessId + + "accessName= " + + this.accessName + + "]"; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketAccessItemResourceAssembler.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketAccessItemResourceAssembler.java index 0d61794eb..abc5ac653 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketAccessItemResourceAssembler.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketAccessItemResourceAssembler.java @@ -4,7 +4,6 @@ import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import java.util.List; - import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.mvc.ResourceAssemblerSupport; @@ -21,51 +20,51 @@ import pro.taskana.rest.resource.PagedResources.PageMetadata; import pro.taskana.rest.resource.links.PageLinks; /** - * Transforms {@link WorkbasketAccessItem} to its resource counterpart {@link WorkbasketAccessItemResource} and vice - * versa. + * Transforms {@link WorkbasketAccessItem} to its resource counterpart {@link + * WorkbasketAccessItemResource} and vice versa. */ @Component -public class WorkbasketAccessItemResourceAssembler extends - ResourceAssemblerSupport { +public class WorkbasketAccessItemResourceAssembler + extends ResourceAssemblerSupport { - @Autowired - private WorkbasketService workbasketService; + @Autowired private WorkbasketService workbasketService; - public WorkbasketAccessItemResourceAssembler() { - super(WorkbasketController.class, WorkbasketAccessItemResource.class); - } + public WorkbasketAccessItemResourceAssembler() { + super(WorkbasketController.class, WorkbasketAccessItemResource.class); + } - public WorkbasketAccessItemResource toResource(WorkbasketAccessItem wbAccItem) { - return new WorkbasketAccessItemResource(wbAccItem); - } + public WorkbasketAccessItemResource toResource(WorkbasketAccessItem wbAccItem) { + return new WorkbasketAccessItemResource(wbAccItem); + } - public WorkbasketAccessItem toModel(WorkbasketAccessItemResource wbAccItemResource) { - WorkbasketAccessItemImpl wbAccItemModel = (WorkbasketAccessItemImpl) workbasketService.newWorkbasketAccessItem( - wbAccItemResource.workbasketId, wbAccItemResource.accessId); - BeanUtils.copyProperties(wbAccItemResource, wbAccItemModel); + public WorkbasketAccessItem toModel(WorkbasketAccessItemResource wbAccItemResource) { + WorkbasketAccessItemImpl wbAccItemModel = + (WorkbasketAccessItemImpl) + workbasketService.newWorkbasketAccessItem( + wbAccItemResource.workbasketId, wbAccItemResource.accessId); + BeanUtils.copyProperties(wbAccItemResource, wbAccItemModel); - wbAccItemModel.setId(wbAccItemResource.accessItemId); - return wbAccItemModel; - } + wbAccItemModel.setId(wbAccItemResource.accessItemId); + return wbAccItemModel; + } - @PageLinks(Mapping.URL_WORKBASKETACCESSITEMS) - public WorkbasketAccessItemPaginatedListResource toResources( - List entities, PageMetadata pageMetadata) { - return new WorkbasketAccessItemPaginatedListResource(toResources(entities), pageMetadata); - } - - public WorkbasketAccessItemListResource toResources( - String workbasketId, List entities) - throws NotAuthorizedException, WorkbasketNotFoundException { - WorkbasketAccessItemListResource accessItemListResource = new WorkbasketAccessItemListResource( - super.toResources(entities)); - accessItemListResource - .add(linkTo(methodOn(WorkbasketController.class).getWorkbasketAccessItems(workbasketId)) - .withSelfRel()); - accessItemListResource - .add(linkTo(methodOn(WorkbasketController.class).getWorkbasket(workbasketId)) - .withRel("workbasket")); - return accessItemListResource; - } + @PageLinks(Mapping.URL_WORKBASKETACCESSITEMS) + public WorkbasketAccessItemPaginatedListResource toResources( + List entities, PageMetadata pageMetadata) { + return new WorkbasketAccessItemPaginatedListResource(toResources(entities), pageMetadata); + } + public WorkbasketAccessItemListResource toResources( + String workbasketId, List entities) + throws NotAuthorizedException, WorkbasketNotFoundException { + WorkbasketAccessItemListResource accessItemListResource = + new WorkbasketAccessItemListResource(super.toResources(entities)); + accessItemListResource.add( + linkTo(methodOn(WorkbasketController.class).getWorkbasketAccessItems(workbasketId)) + .withSelfRel()); + accessItemListResource.add( + linkTo(methodOn(WorkbasketController.class).getWorkbasket(workbasketId)) + .withRel("workbasket")); + return accessItemListResource; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketDefinitionResource.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketDefinitionResource.java index dfaf1b463..09cb8d1ba 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketDefinitionResource.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketDefinitionResource.java @@ -6,57 +6,60 @@ import java.util.Set; import pro.taskana.impl.WorkbasketAccessItemImpl; import pro.taskana.impl.util.LoggerUtils; -/** - * this class represents a workbasket including its distro targets and authorisations. - */ +/** this class represents a workbasket including its distro targets and authorisations. */ public class WorkbasketDefinitionResource { - private Set distributionTargets; - private List authorizations; - private WorkbasketResourceWithoutLinks workbasket; + private Set distributionTargets; + private List authorizations; + private WorkbasketResourceWithoutLinks workbasket; - public WorkbasketDefinitionResource() { - // necessary for de-serializing - } + public WorkbasketDefinitionResource() { + // necessary for de-serializing + } - public WorkbasketDefinitionResource(WorkbasketResourceWithoutLinks workbasket, - Set distributionTargets, List authorizations) { - super(); - this.workbasket = workbasket; - this.distributionTargets = distributionTargets; - this.authorizations = authorizations; - } + public WorkbasketDefinitionResource( + WorkbasketResourceWithoutLinks workbasket, + Set distributionTargets, + List authorizations) { + super(); + this.workbasket = workbasket; + this.distributionTargets = distributionTargets; + this.authorizations = authorizations; + } - public Set getDistributionTargets() { - return distributionTargets; - } + public Set getDistributionTargets() { + return distributionTargets; + } - public void setDistributionTargets(Set distributionTargets) { - this.distributionTargets = distributionTargets; - } + public void setDistributionTargets(Set distributionTargets) { + this.distributionTargets = distributionTargets; + } - public List getAuthorizations() { - return authorizations; - } + public List getAuthorizations() { + return authorizations; + } - public void setAuthorizations(List authorizations) { - this.authorizations = authorizations; - } + public void setAuthorizations(List authorizations) { + this.authorizations = authorizations; + } - public WorkbasketResourceWithoutLinks getWorkbasket() { - return workbasket; - } + public WorkbasketResourceWithoutLinks getWorkbasket() { + return workbasket; + } - public void setWorkbasket(WorkbasketResourceWithoutLinks workbasket) { - this.workbasket = workbasket; - } + public void setWorkbasket(WorkbasketResourceWithoutLinks workbasket) { + this.workbasket = workbasket; + } - @Override - public String toString() { - return "WorkbasketDefinitionResource [" - + "distributionTargets= " + LoggerUtils.setToString(this.distributionTargets) - + "authorizations= " + LoggerUtils.listToString(this.authorizations) - + "workbasket= " + this.workbasket - + "]"; - } + @Override + public String toString() { + return "WorkbasketDefinitionResource [" + + "distributionTargets= " + + LoggerUtils.setToString(this.distributionTargets) + + "authorizations= " + + LoggerUtils.listToString(this.authorizations) + + "workbasket= " + + this.workbasket + + "]"; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketDefinitionResourceAssembler.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketDefinitionResourceAssembler.java index 3b62c57bf..b465371e2 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketDefinitionResourceAssembler.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketDefinitionResourceAssembler.java @@ -5,7 +5,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.stream.Collectors; - import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -20,54 +19,52 @@ import pro.taskana.impl.WorkbasketAccessItemImpl; import pro.taskana.impl.WorkbasketImpl; /** - * Transforms {@link Workbasket} into a {@link WorkbasketDefinitionResource} - * containing all additional information about that workbasket. + * Transforms {@link Workbasket} into a {@link WorkbasketDefinitionResource} containing all + * additional information about that workbasket. */ @Component public class WorkbasketDefinitionResourceAssembler { - @Autowired - private WorkbasketService workbasketService; + @Autowired private WorkbasketService workbasketService; - /** - * maps the distro targets to their id to remove overhead. - * - * @param workbasket - * {@link Workbasket} which will be converted - * @return a {@link WorkbasketDefinitionResource}, containing the {@code basket}, its distribution targets and its - * authorizations - * @throws NotAuthorizedException - * if the user is not authorized - * @throws WorkbasketNotFoundException - * if {@code basket} is an unknown workbasket - */ - public WorkbasketDefinitionResource toResource(Workbasket workbasket) - throws NotAuthorizedException, WorkbasketNotFoundException { + /** + * maps the distro targets to their id to remove overhead. + * + * @param workbasket {@link Workbasket} which will be converted + * @return a {@link WorkbasketDefinitionResource}, containing the {@code basket}, its distribution + * targets and its authorizations + * @throws NotAuthorizedException if the user is not authorized + * @throws WorkbasketNotFoundException if {@code basket} is an unknown workbasket + */ + public WorkbasketDefinitionResource toResource(Workbasket workbasket) + throws NotAuthorizedException, WorkbasketNotFoundException { - WorkbasketResourceWithoutLinks basket = new WorkbasketResourceWithoutLinks(workbasket); + WorkbasketResourceWithoutLinks basket = new WorkbasketResourceWithoutLinks(workbasket); - List authorizations = new ArrayList<>(); - for (WorkbasketAccessItem accessItem : workbasketService.getWorkbasketAccessItems(basket.getWorkbasketId())) { - authorizations.add((WorkbasketAccessItemImpl) accessItem); - } - Set distroTargets = workbasketService.getDistributionTargets(workbasket.getId()) - .stream() + List authorizations = new ArrayList<>(); + for (WorkbasketAccessItem accessItem : + workbasketService.getWorkbasketAccessItems(basket.getWorkbasketId())) { + authorizations.add((WorkbasketAccessItemImpl) accessItem); + } + Set distroTargets = + workbasketService.getDistributionTargets(workbasket.getId()).stream() .map(WorkbasketSummary::getId) .collect(Collectors.toSet()); - return new WorkbasketDefinitionResource(basket, distroTargets, authorizations); - } + return new WorkbasketDefinitionResource(basket, distroTargets, authorizations); + } - public Workbasket toModel(WorkbasketResource wbResource) { - WorkbasketImpl workbasket = (WorkbasketImpl) workbasketService.newWorkbasket(wbResource.key, wbResource.domain); - BeanUtils.copyProperties(wbResource, workbasket); + public Workbasket toModel(WorkbasketResource wbResource) { + WorkbasketImpl workbasket = + (WorkbasketImpl) workbasketService.newWorkbasket(wbResource.key, wbResource.domain); + BeanUtils.copyProperties(wbResource, workbasket); - workbasket.setId(wbResource.workbasketId); - if (wbResource.getModified() != null) { - workbasket.setModified(Instant.parse(wbResource.modified)); - } - if (wbResource.getCreated() != null) { - workbasket.setCreated(Instant.parse(wbResource.created)); - } - return workbasket; + workbasket.setId(wbResource.workbasketId); + if (wbResource.getModified() != null) { + workbasket.setModified(Instant.parse(wbResource.modified)); } + if (wbResource.getCreated() != null) { + workbasket.setCreated(Instant.parse(wbResource.created)); + } + return workbasket; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketResource.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketResource.java index a410c48ad..af4cab77c 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketResource.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketResource.java @@ -1,207 +1,205 @@ package pro.taskana.rest.resource; import javax.validation.constraints.NotNull; - import org.springframework.hateoas.ResourceSupport; import pro.taskana.Workbasket; import pro.taskana.WorkbasketType; -/** - * Resource class for {@link pro.taskana.Workbasket}. - */ +/** Resource class for {@link pro.taskana.Workbasket}. */ public class WorkbasketResource extends ResourceSupport { - public String workbasketId; - @NotNull - public String key; - @NotNull - public String name; - @NotNull - public String domain; - @NotNull - public WorkbasketType type; - public String created; // ISO-8601 - public String modified; // ISO-8601 - public String description; - public String owner; - public String custom1; - public String custom2; - public String custom3; - public String custom4; - public String orgLevel1; - public String orgLevel2; - public String orgLevel3; - public String orgLevel4; + public String workbasketId; + @NotNull public String key; + @NotNull public String name; + @NotNull public String domain; + @NotNull public WorkbasketType type; + public String created; // ISO-8601 + public String modified; // ISO-8601 + public String description; + public String owner; + public String custom1; + public String custom2; + public String custom3; + public String custom4; + public String orgLevel1; + public String orgLevel2; + public String orgLevel3; + public String orgLevel4; - public WorkbasketResource() { - } + public WorkbasketResource() {} - public WorkbasketResource(Workbasket workbasket) { - this.workbasketId = workbasket.getId(); - this.key = workbasket.getKey(); - this.name = workbasket.getName(); - this.domain = workbasket.getDomain(); - this.type = workbasket.getType(); - this.created = workbasket.getCreated() != null ? workbasket.getCreated().toString() : null; - this.modified = workbasket.getModified() != null ? workbasket.getModified().toString() : null; - this.description = workbasket.getDescription(); - this.owner = workbasket.getOwner(); - this.custom1 = workbasket.getCustom1(); - this.custom2 = workbasket.getCustom2(); - this.custom3 = workbasket.getCustom3(); - this.custom4 = workbasket.getCustom4(); - this.orgLevel1 = workbasket.getOrgLevel1(); - this.orgLevel2 = workbasket.getOrgLevel2(); - this.orgLevel3 = workbasket.getOrgLevel3(); - this.orgLevel4 = workbasket.getOrgLevel4(); - } + public WorkbasketResource(Workbasket workbasket) { + this.workbasketId = workbasket.getId(); + this.key = workbasket.getKey(); + this.name = workbasket.getName(); + this.domain = workbasket.getDomain(); + this.type = workbasket.getType(); + this.created = workbasket.getCreated() != null ? workbasket.getCreated().toString() : null; + this.modified = workbasket.getModified() != null ? workbasket.getModified().toString() : null; + this.description = workbasket.getDescription(); + this.owner = workbasket.getOwner(); + this.custom1 = workbasket.getCustom1(); + this.custom2 = workbasket.getCustom2(); + this.custom3 = workbasket.getCustom3(); + this.custom4 = workbasket.getCustom4(); + this.orgLevel1 = workbasket.getOrgLevel1(); + this.orgLevel2 = workbasket.getOrgLevel2(); + this.orgLevel3 = workbasket.getOrgLevel3(); + this.orgLevel4 = workbasket.getOrgLevel4(); + } - public String getWorkbasketId() { - return workbasketId; - } + public String getWorkbasketId() { + return workbasketId; + } - public void setWorkbasketId(String workbasketId) { - this.workbasketId = workbasketId; - } + public void setWorkbasketId(String workbasketId) { + this.workbasketId = workbasketId; + } - public String getKey() { - return key; - } + public String getKey() { + return key; + } - public void setKey(String key) { - this.key = key; - } + public void setKey(String key) { + this.key = key; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getDomain() { - return domain; - } + public String getDomain() { + return domain; + } - public void setDomain(String domain) { - this.domain = domain; - } + public void setDomain(String domain) { + this.domain = domain; + } - public WorkbasketType getType() { - return type; - } + public WorkbasketType getType() { + return type; + } - public void setType(WorkbasketType type) { - this.type = type; - } + public void setType(WorkbasketType type) { + this.type = type; + } - public String getCreated() { - return created; - } + public String getCreated() { + return created; + } - public void setCreated(String created) { - this.created = created; - } + public void setCreated(String created) { + this.created = created; + } - public String getModified() { - return modified; - } + public String getModified() { + return modified; + } - public void setModified(String modified) { - this.modified = modified; - } + public void setModified(String modified) { + this.modified = modified; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public String getOwner() { - return owner; - } + public String getOwner() { + return owner; + } - public void setOwner(String owner) { - this.owner = owner; - } + public void setOwner(String owner) { + this.owner = owner; + } - public String getCustom1() { - return custom1; - } + public String getCustom1() { + return custom1; + } - public void setCustom1(String custom1) { - this.custom1 = custom1; - } + public void setCustom1(String custom1) { + this.custom1 = custom1; + } - public String getCustom2() { - return custom2; - } + public String getCustom2() { + return custom2; + } - public void setCustom2(String custom2) { - this.custom2 = custom2; - } + public void setCustom2(String custom2) { + this.custom2 = custom2; + } - public String getCustom3() { - return custom3; - } + public String getCustom3() { + return custom3; + } - public void setCustom3(String custom3) { - this.custom3 = custom3; - } + public void setCustom3(String custom3) { + this.custom3 = custom3; + } - public String getCustom4() { - return custom4; - } + public String getCustom4() { + return custom4; + } - public void setCustom4(String custom4) { - this.custom4 = custom4; - } + public void setCustom4(String custom4) { + this.custom4 = custom4; + } - public String getOrgLevel1() { - return orgLevel1; - } + public String getOrgLevel1() { + return orgLevel1; + } - public void setOrgLevel1(String orgLevel1) { - this.orgLevel1 = orgLevel1; - } + public void setOrgLevel1(String orgLevel1) { + this.orgLevel1 = orgLevel1; + } - public String getOrgLevel2() { - return orgLevel2; - } + public String getOrgLevel2() { + return orgLevel2; + } - public void setOrgLevel2(String orgLevel2) { - this.orgLevel2 = orgLevel2; - } + public void setOrgLevel2(String orgLevel2) { + this.orgLevel2 = orgLevel2; + } - public String getOrgLevel3() { - return orgLevel3; - } + public String getOrgLevel3() { + return orgLevel3; + } - public void setOrgLevel3(String orgLevel3) { - this.orgLevel3 = orgLevel3; - } + public void setOrgLevel3(String orgLevel3) { + this.orgLevel3 = orgLevel3; + } - public String getOrgLevel4() { - return orgLevel4; - } + public String getOrgLevel4() { + return orgLevel4; + } - public void setOrgLevel4(String orgLevel4) { - this.orgLevel4 = orgLevel4; - } + public void setOrgLevel4(String orgLevel4) { + this.orgLevel4 = orgLevel4; + } - @Override - public String toString() { - return "WorkbasketResource [" - + "workbasketId= " + this.workbasketId - + "key= " + this.key - + "name= " + this.name - + "domain= " + this.domain - + "type= " + this.type - + "owner= " + this.owner - + "]"; - } + @Override + public String toString() { + return "WorkbasketResource [" + + "workbasketId= " + + this.workbasketId + + "key= " + + this.key + + "name= " + + this.name + + "domain= " + + this.domain + + "type= " + + this.type + + "owner= " + + this.owner + + "]"; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketResourceAssembler.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketResourceAssembler.java index 46d4267b7..e435207e0 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketResourceAssembler.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketResourceAssembler.java @@ -4,7 +4,6 @@ import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import java.time.Instant; - import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -17,43 +16,51 @@ import pro.taskana.impl.WorkbasketImpl; import pro.taskana.rest.WorkbasketController; /** - * Transforms {@link Workbasket} to its resource counterpart {@link WorkbasketResource} and vice versa. + * Transforms {@link Workbasket} to its resource counterpart {@link WorkbasketResource} and vice + * versa. */ @Component public class WorkbasketResourceAssembler { - @Autowired - private WorkbasketService workbasketService; + @Autowired private WorkbasketService workbasketService; - public WorkbasketResource toResource(Workbasket wb) throws NotAuthorizedException, WorkbasketNotFoundException { - WorkbasketResource resource = new WorkbasketResource(wb); - return addLinks(resource, wb); + public WorkbasketResource toResource(Workbasket wb) + throws NotAuthorizedException, WorkbasketNotFoundException { + WorkbasketResource resource = new WorkbasketResource(wb); + return addLinks(resource, wb); + } + + public Workbasket toModel(WorkbasketResource wbResource) { + WorkbasketImpl workbasket = + (WorkbasketImpl) workbasketService.newWorkbasket(wbResource.key, wbResource.domain); + BeanUtils.copyProperties(wbResource, workbasket); + + workbasket.setId(wbResource.workbasketId); + if (wbResource.modified != null) { + workbasket.setModified(Instant.parse(wbResource.modified)); } - - public Workbasket toModel(WorkbasketResource wbResource) { - WorkbasketImpl workbasket = (WorkbasketImpl) workbasketService.newWorkbasket(wbResource.key, wbResource.domain); - BeanUtils.copyProperties(wbResource, workbasket); - - workbasket.setId(wbResource.workbasketId); - if (wbResource.modified != null) { - workbasket.setModified(Instant.parse(wbResource.modified)); - } - if (wbResource.created != null) { - workbasket.setCreated(Instant.parse(wbResource.created)); - } - return workbasket; + if (wbResource.created != null) { + workbasket.setCreated(Instant.parse(wbResource.created)); } + return workbasket; + } - private WorkbasketResource addLinks(WorkbasketResource resource, Workbasket wb) - throws NotAuthorizedException, WorkbasketNotFoundException { - resource.add(linkTo(methodOn(WorkbasketController.class).getWorkbasket(wb.getId())).withSelfRel()); - resource.add(linkTo(methodOn(WorkbasketController.class).getDistributionTargets(wb.getId())) + private WorkbasketResource addLinks(WorkbasketResource resource, Workbasket wb) + throws NotAuthorizedException, WorkbasketNotFoundException { + resource.add( + linkTo(methodOn(WorkbasketController.class).getWorkbasket(wb.getId())).withSelfRel()); + resource.add( + linkTo(methodOn(WorkbasketController.class).getDistributionTargets(wb.getId())) .withRel("distributionTargets")); - resource.add(linkTo(methodOn(WorkbasketController.class).getWorkbasketAccessItems(wb.getId())) + resource.add( + linkTo(methodOn(WorkbasketController.class).getWorkbasketAccessItems(wb.getId())) .withRel("accessItems")); - resource.add(linkTo(WorkbasketController.class).withRel("allWorkbaskets")); - resource.add(linkTo(methodOn(WorkbasketController.class).removeDistributionTargetForWorkbasketId(wb.getId())) + resource.add(linkTo(WorkbasketController.class).withRel("allWorkbaskets")); + resource.add( + linkTo( + methodOn(WorkbasketController.class) + .removeDistributionTargetForWorkbasketId(wb.getId())) .withRel("removeDistributionTargets")); - return resource; - } + return resource; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketResourceWithoutLinks.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketResourceWithoutLinks.java index c95428bf6..88db34134 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketResourceWithoutLinks.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketResourceWithoutLinks.java @@ -4,16 +4,13 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import pro.taskana.Workbasket; -/** - * Resource class for {@link pro.taskana.Workbasket} but without links property. - */ +/** Resource class for {@link pro.taskana.Workbasket} but without links property. */ @JsonIgnoreProperties(value = {"links"}) public class WorkbasketResourceWithoutLinks extends WorkbasketResource { - WorkbasketResourceWithoutLinks() { - } + WorkbasketResourceWithoutLinks() {} - WorkbasketResourceWithoutLinks(Workbasket workbasket) { - super(workbasket); - } + WorkbasketResourceWithoutLinks(Workbasket workbasket) { + super(workbasket); + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketSummaryListResource.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketSummaryListResource.java index b570717df..ca2585d5c 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketSummaryListResource.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketSummaryListResource.java @@ -1,33 +1,29 @@ package pro.taskana.rest.resource; +import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Collection; - import org.springframework.hateoas.Link; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * Resource class for {@link WorkbasketSummaryResource} with Pagination. - */ +/** Resource class for {@link WorkbasketSummaryResource} with Pagination. */ public class WorkbasketSummaryListResource extends PagedResources { - public WorkbasketSummaryListResource() { - super(); - } + public WorkbasketSummaryListResource() { + super(); + } - public WorkbasketSummaryListResource(Collection content, PageMetadata metadata, - Link... links) { - super(content, metadata, links); - } + public WorkbasketSummaryListResource( + Collection content, PageMetadata metadata, Link... links) { + super(content, metadata, links); + } - public WorkbasketSummaryListResource(Collection content, PageMetadata metadata, - Iterable links) { - super(content, metadata, links); - } + public WorkbasketSummaryListResource( + Collection content, PageMetadata metadata, Iterable links) { + super(content, metadata, links); + } - @Override - @JsonProperty("workbaskets") - public Collection getContent() { - return super.getContent(); - } + @Override + @JsonProperty("workbaskets") + public Collection getContent() { + return super.getContent(); + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketSummaryResource.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketSummaryResource.java index 556f1991f..debc163fd 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketSummaryResource.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketSummaryResource.java @@ -1,204 +1,202 @@ package pro.taskana.rest.resource; import javax.validation.constraints.NotNull; - import org.springframework.hateoas.ResourceSupport; import org.springframework.hateoas.core.Relation; import pro.taskana.WorkbasketSummary; import pro.taskana.WorkbasketType; -/** - * Resource class for {@link pro.taskana.WorkbasketSummary}. - */ +/** Resource class for {@link pro.taskana.WorkbasketSummary}. */ @Relation(collectionRelation = "workbaskets") public class WorkbasketSummaryResource extends ResourceSupport { - private String workbasketId; + private String workbasketId; - @NotNull - private String key; + @NotNull private String key; - @NotNull - private String name; + @NotNull private String name; - @NotNull - private String domain; + @NotNull private String domain; - @NotNull - private WorkbasketType type; + @NotNull private WorkbasketType type; - private String description; - private String owner; - private String custom1; - private String custom2; - private String custom3; - private String custom4; - private String orgLevel1; - private String orgLevel2; - private String orgLevel3; - private String orgLevel4; - private boolean markedForDeletion; + private String description; + private String owner; + private String custom1; + private String custom2; + private String custom3; + private String custom4; + private String orgLevel1; + private String orgLevel2; + private String orgLevel3; + private String orgLevel4; + private boolean markedForDeletion; - public WorkbasketSummaryResource() { - } + public WorkbasketSummaryResource() {} - public WorkbasketSummaryResource(WorkbasketSummary workbasketSummary) { - this.workbasketId = workbasketSummary.getId(); - this.key = workbasketSummary.getKey(); - this.name = workbasketSummary.getName(); - this.domain = workbasketSummary.getDomain(); - this.type = workbasketSummary.getType(); - this.description = workbasketSummary.getDescription(); - this.owner = workbasketSummary.getOwner(); - this.markedForDeletion = workbasketSummary.isMarkedForDeletion(); - this.custom1 = workbasketSummary.getCustom1(); - this.custom2 = workbasketSummary.getCustom2(); - this.custom3 = workbasketSummary.getCustom3(); - this.custom4 = workbasketSummary.getCustom4(); - this.orgLevel1 = workbasketSummary.getOrgLevel1(); - this.orgLevel2 = workbasketSummary.getOrgLevel2(); - this.orgLevel3 = workbasketSummary.getOrgLevel3(); - this.orgLevel4 = workbasketSummary.getOrgLevel4(); - } + public WorkbasketSummaryResource(WorkbasketSummary workbasketSummary) { + this.workbasketId = workbasketSummary.getId(); + this.key = workbasketSummary.getKey(); + this.name = workbasketSummary.getName(); + this.domain = workbasketSummary.getDomain(); + this.type = workbasketSummary.getType(); + this.description = workbasketSummary.getDescription(); + this.owner = workbasketSummary.getOwner(); + this.markedForDeletion = workbasketSummary.isMarkedForDeletion(); + this.custom1 = workbasketSummary.getCustom1(); + this.custom2 = workbasketSummary.getCustom2(); + this.custom3 = workbasketSummary.getCustom3(); + this.custom4 = workbasketSummary.getCustom4(); + this.orgLevel1 = workbasketSummary.getOrgLevel1(); + this.orgLevel2 = workbasketSummary.getOrgLevel2(); + this.orgLevel3 = workbasketSummary.getOrgLevel3(); + this.orgLevel4 = workbasketSummary.getOrgLevel4(); + } - public String getWorkbasketId() { - return workbasketId; - } + public String getWorkbasketId() { + return workbasketId; + } - public void setWorkbasketId(String workbasketId) { - this.workbasketId = workbasketId; - } + public void setWorkbasketId(String workbasketId) { + this.workbasketId = workbasketId; + } - public String getKey() { - return key; - } + public String getKey() { + return key; + } - public void setKey(String key) { - this.key = key; - } + public void setKey(String key) { + this.key = key; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getDomain() { - return domain; - } + public String getDomain() { + return domain; + } - public void setDomain(String domain) { - this.domain = domain; - } + public void setDomain(String domain) { + this.domain = domain; + } - public WorkbasketType getType() { - return type; - } + public WorkbasketType getType() { + return type; + } - public void setType(WorkbasketType type) { - this.type = type; - } + public void setType(WorkbasketType type) { + this.type = type; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public String getOwner() { - return owner; - } + public String getOwner() { + return owner; + } - public void setOwner(String owner) { - this.owner = owner; - } + public void setOwner(String owner) { + this.owner = owner; + } - public String getCustom1() { - return custom1; - } + public String getCustom1() { + return custom1; + } - public void setCustom1(String custom1) { - this.custom1 = custom1; - } + public void setCustom1(String custom1) { + this.custom1 = custom1; + } - public String getCustom2() { - return custom2; - } + public String getCustom2() { + return custom2; + } - public void setCustom2(String custom2) { - this.custom2 = custom2; - } + public void setCustom2(String custom2) { + this.custom2 = custom2; + } - public String getCustom3() { - return custom3; - } + public String getCustom3() { + return custom3; + } - public void setCustom3(String custom3) { - this.custom3 = custom3; - } + public void setCustom3(String custom3) { + this.custom3 = custom3; + } - public String getCustom4() { - return custom4; - } + public String getCustom4() { + return custom4; + } - public void setCustom4(String custom4) { - this.custom4 = custom4; - } + public void setCustom4(String custom4) { + this.custom4 = custom4; + } - public String getOrgLevel1() { - return orgLevel1; - } + public String getOrgLevel1() { + return orgLevel1; + } - public void setOrgLevel1(String orgLevel1) { - this.orgLevel1 = orgLevel1; - } + public void setOrgLevel1(String orgLevel1) { + this.orgLevel1 = orgLevel1; + } - public String getOrgLevel2() { - return orgLevel2; - } + public String getOrgLevel2() { + return orgLevel2; + } - public void setOrgLevel2(String orgLevel2) { - this.orgLevel2 = orgLevel2; - } + public void setOrgLevel2(String orgLevel2) { + this.orgLevel2 = orgLevel2; + } - public String getOrgLevel3() { - return orgLevel3; - } + public String getOrgLevel3() { + return orgLevel3; + } - public void setOrgLevel3(String orgLevel3) { - this.orgLevel3 = orgLevel3; - } + public void setOrgLevel3(String orgLevel3) { + this.orgLevel3 = orgLevel3; + } - public String getOrgLevel4() { - return orgLevel4; - } + public String getOrgLevel4() { + return orgLevel4; + } - public void setOrgLevel4(String orgLevel4) { - this.orgLevel4 = orgLevel4; - } + public void setOrgLevel4(String orgLevel4) { + this.orgLevel4 = orgLevel4; + } - public boolean getMarkedForDeletion() { - return markedForDeletion; - } + public boolean getMarkedForDeletion() { + return markedForDeletion; + } - public void setMarkedForDeletion(boolean markedForDeletion) { - this.markedForDeletion = markedForDeletion; - } + public void setMarkedForDeletion(boolean markedForDeletion) { + this.markedForDeletion = markedForDeletion; + } - @Override - public String toString() { - return "WorkbasketSummaryResource [" - + "workbasketId= " + this.workbasketId - + "key= " + this.key - + "name= " + this.name - + "domain= " + this.domain - + "type= " + this.type - + "owner= " + this.owner - + "]"; - } + @Override + public String toString() { + return "WorkbasketSummaryResource [" + + "workbasketId= " + + this.workbasketId + + "key= " + + this.key + + "name= " + + this.name + + "domain= " + + this.domain + + "type= " + + this.type + + "owner= " + + this.owner + + "]"; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketSummaryResourceAssembler.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketSummaryResourceAssembler.java index 00b316953..6475f9843 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketSummaryResourceAssembler.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/WorkbasketSummaryResourceAssembler.java @@ -1,7 +1,6 @@ package pro.taskana.rest.resource; import java.util.List; - import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.mvc.ResourceAssemblerSupport; @@ -15,37 +14,33 @@ import pro.taskana.rest.WorkbasketController; import pro.taskana.rest.resource.PagedResources.PageMetadata; import pro.taskana.rest.resource.links.PageLinks; -/** - * @author HH - */ +/** @author HH */ @Component public class WorkbasketSummaryResourceAssembler extends ResourceAssemblerSupport { - @Autowired - private WorkbasketService workbasketService; + @Autowired private WorkbasketService workbasketService; - public WorkbasketSummaryResourceAssembler() { - super(WorkbasketController.class, WorkbasketSummaryResource.class); - } + public WorkbasketSummaryResourceAssembler() { + super(WorkbasketController.class, WorkbasketSummaryResource.class); + } - @Override - public WorkbasketSummaryResource toResource(WorkbasketSummary workbasketSummary) { - return new WorkbasketSummaryResource(workbasketSummary); - } + @Override + public WorkbasketSummaryResource toResource(WorkbasketSummary workbasketSummary) { + return new WorkbasketSummaryResource(workbasketSummary); + } - @PageLinks(Mapping.URL_WORKBASKET) - public WorkbasketSummaryListResource toResources(List entities, - PageMetadata pageMetadata) { - return new WorkbasketSummaryListResource(toResources(entities), pageMetadata); - } - - public WorkbasketSummary toModel(WorkbasketSummaryResource resource) { - WorkbasketImpl workbasket = (WorkbasketImpl) workbasketService - .newWorkbasket(resource.getKey(), resource.getDomain()); - workbasket.setId(resource.getWorkbasketId()); - BeanUtils.copyProperties(resource, workbasket); - return workbasket.asSummary(); - } + @PageLinks(Mapping.URL_WORKBASKET) + public WorkbasketSummaryListResource toResources( + List entities, PageMetadata pageMetadata) { + return new WorkbasketSummaryListResource(toResources(entities), pageMetadata); + } + public WorkbasketSummary toModel(WorkbasketSummaryResource resource) { + WorkbasketImpl workbasket = + (WorkbasketImpl) workbasketService.newWorkbasket(resource.getKey(), resource.getDomain()); + workbasket.setId(resource.getWorkbasketId()); + BeanUtils.copyProperties(resource, workbasket); + return workbasket.asSummary(); + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/links/PageLinks.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/links/PageLinks.java index b662692b7..c722b4e50 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/links/PageLinks.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/links/PageLinks.java @@ -5,12 +5,10 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * Annotation to generate HATEOAS Links for paged list resources. - */ +/** Annotation to generate HATEOAS Links for paged list resources. */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface PageLinks { - String value(); + String value(); } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/links/PageLinksAspect.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/links/PageLinksAspect.java index f813a9062..004485cea 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/links/PageLinksAspect.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/resource/links/PageLinksAspect.java @@ -5,9 +5,7 @@ import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import java.lang.reflect.Method; import java.util.List; import java.util.Map; - import javax.servlet.http.HttpServletRequest; - import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; @@ -28,44 +26,46 @@ import pro.taskana.rest.resource.PagedResources.PageMetadata; @Aspect public class PageLinksAspect { - @Around("@annotation(pro.taskana.rest.resource.links.PageLinks) && args(data, page, ..)") - public ResourceSupport addLinksToPageResource(ProceedingJoinPoint joinPoint, List data, PageMetadata page) - throws Throwable { - HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) - .getRequest(); - Method method = ((MethodSignature) joinPoint.getSignature()).getMethod(); - PageLinks pageLinks = method.getAnnotation(PageLinks.class); - String relativeUrl = pageLinks.value(); - UriComponentsBuilder original = originalUri(relativeUrl, request); - ResourceSupport resourceSupport = (ResourceSupport) joinPoint.proceed(); - resourceSupport.add(new Link(original.toUriString()).withSelfRel()); - if (page != null) { - resourceSupport.add(new Link(original.replaceQueryParam("page", 1).toUriString()).withRel(Link.REL_FIRST)); - resourceSupport.add(new Link(original.replaceQueryParam("page", page.getTotalPages()).toUriString()) - .withRel(Link.REL_LAST)); - if (page.getNumber() > 1) { - resourceSupport - .add(new Link(original.replaceQueryParam("page", page.getNumber() - 1).toUriString()) - .withRel(Link.REL_PREVIOUS)); - } - if (page.getNumber() < page.getTotalPages()) { - resourceSupport - .add(new Link(original.replaceQueryParam("page", page.getNumber() + 1).toUriString()) - .withRel(Link.REL_NEXT)); - } - } - return resourceSupport; + @Around("@annotation(pro.taskana.rest.resource.links.PageLinks) && args(data, page, ..)") + public ResourceSupport addLinksToPageResource( + ProceedingJoinPoint joinPoint, List data, PageMetadata page) throws Throwable { + HttpServletRequest request = + ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); + Method method = ((MethodSignature) joinPoint.getSignature()).getMethod(); + PageLinks pageLinks = method.getAnnotation(PageLinks.class); + String relativeUrl = pageLinks.value(); + UriComponentsBuilder original = originalUri(relativeUrl, request); + ResourceSupport resourceSupport = (ResourceSupport) joinPoint.proceed(); + resourceSupport.add(new Link(original.toUriString()).withSelfRel()); + if (page != null) { + resourceSupport.add( + new Link(original.replaceQueryParam("page", 1).toUriString()).withRel(Link.REL_FIRST)); + resourceSupport.add( + new Link(original.replaceQueryParam("page", page.getTotalPages()).toUriString()) + .withRel(Link.REL_LAST)); + if (page.getNumber() > 1) { + resourceSupport.add( + new Link(original.replaceQueryParam("page", page.getNumber() - 1).toUriString()) + .withRel(Link.REL_PREVIOUS)); + } + if (page.getNumber() < page.getTotalPages()) { + resourceSupport.add( + new Link(original.replaceQueryParam("page", page.getNumber() + 1).toUriString()) + .withRel(Link.REL_NEXT)); + } } + return resourceSupport; + } - private UriComponentsBuilder originalUri(String relativeUrl, HttpServletRequest request) { - //argument to linkTo does not matter as we just want to have the default baseUrl - UriComponentsBuilder baseUri = linkTo(PageLinksAspect.class).toUriComponentsBuilder(); - baseUri.path(relativeUrl); - for (Map.Entry entry : request.getParameterMap().entrySet()) { - for (String value : entry.getValue()) { - baseUri.queryParam(entry.getKey(), value); - } - } - return baseUri; + private UriComponentsBuilder originalUri(String relativeUrl, HttpServletRequest request) { + // argument to linkTo does not matter as we just want to have the default baseUrl + UriComponentsBuilder baseUri = linkTo(PageLinksAspect.class).toUriComponentsBuilder(); + baseUri.path(relativeUrl); + for (Map.Entry entry : request.getParameterMap().entrySet()) { + for (String value : entry.getValue()) { + baseUri.queryParam(entry.getKey(), value); + } } + return baseUri; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/serialization/DistributionTargetDeserializer.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/serialization/DistributionTargetDeserializer.java index 593ae396b..641273d4c 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/serialization/DistributionTargetDeserializer.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/serialization/DistributionTargetDeserializer.java @@ -1,60 +1,59 @@ package pro.taskana.rest.serialization; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.context.support.SpringBeanAutowiringSupport; - import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; import pro.taskana.Workbasket; import pro.taskana.WorkbasketService; import pro.taskana.exceptions.NotAuthorizedException; import pro.taskana.exceptions.WorkbasketNotFoundException; -/** - * This class deserializes the string list to real workbaskets. - */ +/** This class deserializes the string list to real workbaskets. */ public class DistributionTargetDeserializer extends StdDeserializer> { - private static final long serialVersionUID = 4226950057149602129L; + private static final long serialVersionUID = 4226950057149602129L; - private static final Logger LOGGER = LoggerFactory.getLogger(DistributionTargetDeserializer.class); + private static final Logger LOGGER = + LoggerFactory.getLogger(DistributionTargetDeserializer.class); - @Autowired - private WorkbasketService workbasketService; + @Autowired private WorkbasketService workbasketService; - public DistributionTargetDeserializer() { - this(null); - SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); - } - - public DistributionTargetDeserializer(Class vc) { - super(vc); - } - - @Override - public List deserialize(JsonParser jsonparser, DeserializationContext context) - throws IOException, JsonProcessingException { - List distributionTargets = new ArrayList(); - while (jsonparser.nextToken() != JsonToken.END_ARRAY) { - String id = jsonparser.getText(); - try { - distributionTargets.add(workbasketService.getWorkbasket(id)); - } catch (WorkbasketNotFoundException e) { - LOGGER.error("The workbasket with the id ' {} ' is not found in database.", id); - } catch (NotAuthorizedException e) { - LOGGER.error("The user misses some required permissions for the workbasket with ID ' {} '. Exception = {}.", id, e); - } - } - return distributionTargets; + public DistributionTargetDeserializer() { + this(null); + SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); + } + + public DistributionTargetDeserializer(Class vc) { + super(vc); + } + + @Override + public List deserialize(JsonParser jsonparser, DeserializationContext context) + throws IOException, JsonProcessingException { + List distributionTargets = new ArrayList(); + while (jsonparser.nextToken() != JsonToken.END_ARRAY) { + String id = jsonparser.getText(); + try { + distributionTargets.add(workbasketService.getWorkbasket(id)); + } catch (WorkbasketNotFoundException e) { + LOGGER.error("The workbasket with the id ' {} ' is not found in database.", id); + } catch (NotAuthorizedException e) { + LOGGER.error( + "The user misses some required permissions for the workbasket with ID ' {} '. Exception = {}.", + id, + e); + } } + return distributionTargets; + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/serialization/DistributionTargetSerializer.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/serialization/DistributionTargetSerializer.java index 11e8c7702..8dd3f6349 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/serialization/DistributionTargetSerializer.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/serialization/DistributionTargetSerializer.java @@ -1,38 +1,36 @@ package pro.taskana.rest.serialization; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.StdSerializer; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; import pro.taskana.Workbasket; -/** - * This class serializes the distribution targets to an string array with ids. - */ +/** This class serializes the distribution targets to an string array with ids. */ public class DistributionTargetSerializer extends StdSerializer> { - private static final long serialVersionUID = -4655804943794734821L; + private static final long serialVersionUID = -4655804943794734821L; - public DistributionTargetSerializer() { - this(null); - } - - public DistributionTargetSerializer(Class> t) { - super(t); - } - - @Override - public void serialize(List workbaskets, JsonGenerator gen, SerializerProvider provider) - throws IOException { - List ids = new ArrayList<>(); - - for (Workbasket item : workbaskets) { - ids.add(item.getId()); - } - gen.writeObject(ids); + public DistributionTargetSerializer() { + this(null); + } + + public DistributionTargetSerializer(Class> t) { + super(t); + } + + @Override + public void serialize( + List workbaskets, JsonGenerator gen, SerializerProvider provider) + throws IOException { + List ids = new ArrayList<>(); + + for (Workbasket item : workbaskets) { + ids.add(item.getId()); } + gen.writeObject(ids); + } } diff --git a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/serialization/WorkbasketMixIn.java b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/serialization/WorkbasketMixIn.java index 9d27ca56f..ff9688961 100644 --- a/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/serialization/WorkbasketMixIn.java +++ b/rest/taskana-rest-spring/src/main/java/pro/taskana/rest/serialization/WorkbasketMixIn.java @@ -1,20 +1,17 @@ package pro.taskana.rest.serialization; -import java.util.List; - import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import java.util.List; import pro.taskana.Workbasket; /** - * This class is used to override the distributiontargets with non standard - * serialization classes. + * This class is used to override the distributiontargets with non standard serialization classes. */ public abstract class WorkbasketMixIn { - @JsonSerialize(using = DistributionTargetSerializer.class) - @JsonDeserialize(using = DistributionTargetDeserializer.class) - abstract List getDistributionTargets(); - + @JsonSerialize(using = DistributionTargetSerializer.class) + @JsonDeserialize(using = DistributionTargetDeserializer.class) + abstract List getDistributionTargets(); } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/RestHelper.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/RestHelper.java index a6a19f382..555902e39 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/RestHelper.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/RestHelper.java @@ -1,5 +1,8 @@ package pro.taskana; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.hateoas.hal.Jackson2HalModule; @@ -11,66 +14,58 @@ import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; - -/** - * Helps to simplify rest api testing. - */ +/** Helps to simplify rest api testing. */ @Component public class RestHelper { - @Autowired - Environment environment; + public static RestTemplate template = getRestTemplate(); + @Autowired Environment environment; - public static RestTemplate template = getRestTemplate(); + public String toUrl(String relativeUrl, Object... uriVariables) { + return UriComponentsBuilder.fromPath(relativeUrl) + .scheme("http") + .host("127.0.0.1") + .port(environment.getProperty("local.server.port")) + .build(uriVariables) + .toString(); + } - public String toUrl(String relativeUrl, Object... uriVariables) { - return UriComponentsBuilder.fromPath(relativeUrl) - .scheme("http") - .host("127.0.0.1") - .port(environment.getProperty("local.server.port")) - .build(uriVariables) - .toString(); - } + public HttpEntity defaultRequest() { + return new HttpEntity<>(getHeaders()); + } - public HttpEntity defaultRequest() { - return new HttpEntity<>(getHeaders()); - } + public HttpHeaders getHeaders() { + HttpHeaders headers = new HttpHeaders(); + headers.add("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x"); + headers.add("Content-Type", "application/json"); + return headers; + } - public HttpHeaders getHeaders() { - HttpHeaders headers = new HttpHeaders(); - headers.add("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x"); - headers.add("Content-Type", "application/json"); - return headers; - } + public HttpHeaders getHeadersAdmin() { + HttpHeaders headers = new HttpHeaders(); + headers.add("Authorization", "Basic YWRtaW46YWRtaW4="); // admin:admin + headers.add("Content-Type", "application/hal+json"); + return headers; + } - public HttpHeaders getHeadersAdmin() { - HttpHeaders headers = new HttpHeaders(); - headers.add("Authorization", "Basic YWRtaW46YWRtaW4="); // admin:admin - headers.add("Content-Type", "application/hal+json"); - return headers; - } + /** + * Return a REST template which is capable of dealing with responses in HAL format. + * + * @return RestTemplate + */ + public static RestTemplate getRestTemplate() { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + mapper.registerModule(new Jackson2HalModule()); - /** - * Return a REST template which is capable of dealing with responses in HAL format. - * - * @return RestTemplate - */ - public static RestTemplate getRestTemplate() { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); - mapper.registerModule(new Jackson2HalModule()); + MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); + converter.setSupportedMediaTypes(MediaType.parseMediaTypes("application/hal+json")); + converter.setObjectMapper(mapper); - MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); - converter.setSupportedMediaTypes(MediaType.parseMediaTypes("application/hal+json")); - converter.setObjectMapper(mapper); - - RestTemplate template = new RestTemplate(); - //important to add first to ensure priority - template.getMessageConverters().add(0, converter); - return template; - } + RestTemplate template = new RestTemplate(); + // important to add first to ensure priority + template.getMessageConverters().add(0, converter); + return template; + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/TaskanaSpringBootTest.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/TaskanaSpringBootTest.java index 216fd80c7..f988efcdb 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/TaskanaSpringBootTest.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/TaskanaSpringBootTest.java @@ -5,7 +5,6 @@ import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; @@ -13,15 +12,13 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; import pro.taskana.rest.RestConfiguration; -/** - * Use this annotation to test with a spring context and a standardized configuration. - */ +/** Use this annotation to test with a spring context and a standardized configuration. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Inherited @ActiveProfiles({"test"}) @ExtendWith(SpringExtension.class) -@SpringBootTest(classes = RestConfiguration.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -public @interface TaskanaSpringBootTest { - -} +@SpringBootTest( + classes = RestConfiguration.class, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public @interface TaskanaSpringBootTest {} diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/AbstractPagingControllerRestDocumentation.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/AbstractPagingControllerRestDocumentation.java index 09ab2a001..e90fa0101 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/AbstractPagingControllerRestDocumentation.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/AbstractPagingControllerRestDocumentation.java @@ -5,7 +5,6 @@ import static org.springframework.restdocs.payload.PayloadDocumentation.response import static org.springframework.restdocs.payload.PayloadDocumentation.subsectionWithPath; import java.util.HashMap; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation; @@ -15,52 +14,61 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import pro.taskana.rest.Mapping; -/** - * Generate Rest Docu for AbstractPagingController. - */ +/** Generate Rest Docu for AbstractPagingController. */ class AbstractPagingControllerRestDocumentation extends BaseRestDocumentation { - private HashMap pagingFieldDescriptionsMap = new HashMap(); + private HashMap pagingFieldDescriptionsMap = new HashMap(); - private FieldDescriptor[] pagingFieldDescriptors; + private FieldDescriptor[] pagingFieldDescriptors; - @BeforeEach - void setUp() { + @BeforeEach + void setUp() { - pagingFieldDescriptionsMap.put("page", "Contains metainfo if there are multiple pages, else it is null"); - pagingFieldDescriptionsMap.put("page.size", "Number of items per page"); - pagingFieldDescriptionsMap.put("page.totalElements", "Total number of items"); - pagingFieldDescriptionsMap.put("page.totalPages", "Number of pages"); - pagingFieldDescriptionsMap.put("page.number", "Current page number"); - pagingFieldDescriptionsMap.put("_links.first.href", "Link to first page"); - pagingFieldDescriptionsMap.put("_links.last.href", "Link to last page"); - pagingFieldDescriptionsMap.put("_links.prev.href", "Link to previous page"); - pagingFieldDescriptionsMap.put("_links.next.href", "Link to next page"); + pagingFieldDescriptionsMap.put( + "page", "Contains metainfo if there are multiple pages, else it is null"); + pagingFieldDescriptionsMap.put("page.size", "Number of items per page"); + pagingFieldDescriptionsMap.put("page.totalElements", "Total number of items"); + pagingFieldDescriptionsMap.put("page.totalPages", "Number of pages"); + pagingFieldDescriptionsMap.put("page.number", "Current page number"); + pagingFieldDescriptionsMap.put("_links.first.href", "Link to first page"); + pagingFieldDescriptionsMap.put("_links.last.href", "Link to last page"); + pagingFieldDescriptionsMap.put("_links.prev.href", "Link to previous page"); + pagingFieldDescriptionsMap.put("_links.next.href", "Link to next page"); - pagingFieldDescriptors = new FieldDescriptor[] { - subsectionWithPath("classifications").ignored(), - fieldWithPath("_links").ignored(), - fieldWithPath("_links.self").ignored(), - fieldWithPath("_links.self.href").ignored(), - fieldWithPath("page").description(pagingFieldDescriptionsMap.get("page")), - fieldWithPath("page.size").description(pagingFieldDescriptionsMap.get("page.size")), - fieldWithPath("page.totalElements").description(pagingFieldDescriptionsMap.get("page.totalElements")), - fieldWithPath("page.totalPages").description(pagingFieldDescriptionsMap.get("page.totalPages")), - fieldWithPath("page.number").description(pagingFieldDescriptionsMap.get("page.number")), - fieldWithPath("_links.first.href").description(pagingFieldDescriptionsMap.get("_links.first.href")), - fieldWithPath("_links.last.href").description(pagingFieldDescriptionsMap.get("_links.last.href")), - fieldWithPath("_links.prev.href").description(pagingFieldDescriptionsMap.get("_links.prev.href")), - fieldWithPath("_links.next.href").description(pagingFieldDescriptionsMap.get("_links.next.href")) + pagingFieldDescriptors = + new FieldDescriptor[] { + subsectionWithPath("classifications").ignored(), + fieldWithPath("_links").ignored(), + fieldWithPath("_links.self").ignored(), + fieldWithPath("_links.self.href").ignored(), + fieldWithPath("page").description(pagingFieldDescriptionsMap.get("page")), + fieldWithPath("page.size").description(pagingFieldDescriptionsMap.get("page.size")), + fieldWithPath("page.totalElements") + .description(pagingFieldDescriptionsMap.get("page.totalElements")), + fieldWithPath("page.totalPages") + .description(pagingFieldDescriptionsMap.get("page.totalPages")), + fieldWithPath("page.number").description(pagingFieldDescriptionsMap.get("page.number")), + fieldWithPath("_links.first.href") + .description(pagingFieldDescriptionsMap.get("_links.first.href")), + fieldWithPath("_links.last.href") + .description(pagingFieldDescriptionsMap.get("_links.last.href")), + fieldWithPath("_links.prev.href") + .description(pagingFieldDescriptionsMap.get("_links.prev.href")), + fieldWithPath("_links.next.href") + .description(pagingFieldDescriptionsMap.get("_links.next.href")) }; - } + } - @Test - void commonSummaryResourceFieldsDocTest() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders - .get(restHelper.toUrl(Mapping.URL_CLASSIFICATIONS) + "?page=2&page-size=5") - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("CommonSummaryResourceFields", - responseFields(pagingFieldDescriptors))); - } + @Test + void commonSummaryResourceFieldsDocTest() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get( + restHelper.toUrl(Mapping.URL_CLASSIFICATIONS) + "?page=2&page-size=5") + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "CommonSummaryResourceFields", responseFields(pagingFieldDescriptors))); + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/BaseRestDocumentation.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/BaseRestDocumentation.java index 1f1573a42..3ff2e0378 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/BaseRestDocumentation.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/BaseRestDocumentation.java @@ -16,33 +16,22 @@ import org.springframework.web.context.WebApplicationContext; import pro.taskana.RestHelper; import pro.taskana.TaskanaSpringBootTest; -/** - * Base class for Rest Documentation tests. - */ - +/** Base class for Rest Documentation tests. */ @AutoConfigureMockMvc @AutoConfigureRestDocs @TaskanaSpringBootTest public abstract class BaseRestDocumentation { - @LocalServerPort - protected int port; + @LocalServerPort protected int port; - @Autowired - protected WebApplicationContext context; + @Autowired protected WebApplicationContext context; - @Autowired - protected MockMvc mockMvc; + @Autowired protected MockMvc mockMvc; - @Autowired - protected RestHelper restHelper; - - @BeforeEach - public void setUpMockMvc() { - document("{methodName}", - preprocessRequest(prettyPrint()), - preprocessResponse(prettyPrint())); - - } + @Autowired protected RestHelper restHelper; + @BeforeEach + public void setUpMockMvc() { + document("{methodName}", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint())); + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/ClassificationControllerRestDocumentation.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/ClassificationControllerRestDocumentation.java index 335b4741b..2df11e025 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/ClassificationControllerRestDocumentation.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/ClassificationControllerRestDocumentation.java @@ -11,7 +11,6 @@ import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation; @@ -22,266 +21,334 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import pro.taskana.rest.Mapping; -/** - * Generate REST Dokumentation for ClassificationController. - */ +/** Generate REST Dokumentation for ClassificationController. */ class ClassificationControllerRestDocumentation extends BaseRestDocumentation { - private HashMap classificationFieldDescriptionsMap = new HashMap(); + private HashMap classificationFieldDescriptionsMap = + new HashMap(); - private FieldDescriptor[] allClassificationsFieldDescriptors; - private FieldDescriptor[] classificationFieldDescriptors; - private FieldDescriptor[] classificationSubsetFieldDescriptors; - private FieldDescriptor[] createClassificationFieldDescriptors; + private FieldDescriptor[] allClassificationsFieldDescriptors; + private FieldDescriptor[] classificationFieldDescriptors; + private FieldDescriptor[] classificationSubsetFieldDescriptors; + private FieldDescriptor[] createClassificationFieldDescriptors; - @BeforeEach - void setUp() { + @BeforeEach + void setUp() { - classificationFieldDescriptionsMap.put("classificationId", "Unique Id"); - classificationFieldDescriptionsMap.put("key", - "The key of the classification. This is typically an externally known code or abbreviation of the classification"); - classificationFieldDescriptionsMap.put("parentId", - "The id of the parent classification. Empty string (\"\") if this is a root classification."); - classificationFieldDescriptionsMap.put("parentKey", - "The key of the parent classification. Empty string (\"\") if this is a root classification."); - classificationFieldDescriptionsMap.put("category", - "The category of the classification (MANUAL, EXTERNAL, AUTOMATIC, PROCESS)"); - classificationFieldDescriptionsMap.put("type", "The type of classification (TASK, DOCUMENT)"); - classificationFieldDescriptionsMap.put("domain", "The domain for which this classification is specified"); - classificationFieldDescriptionsMap.put("isValidInDomain", - "True, if this classification to objects in this domain"); - classificationFieldDescriptionsMap.put("created", "The creation timestamp of the classification in the system"); - classificationFieldDescriptionsMap.put("modified", "The timestamp of the last modification date"); - classificationFieldDescriptionsMap.put("name", "The name of the classification"); - classificationFieldDescriptionsMap.put("description", "The description of the classification"); - classificationFieldDescriptionsMap.put("priority", "The priority of the classification"); - classificationFieldDescriptionsMap.put("serviceLevel", - "The service level of the classification. This is stated according to ISO 8601"); - classificationFieldDescriptionsMap.put("applicationEntryPoint", - "The logical name of the entry point, the task list application should redirect to work on a task of this classification"); - classificationFieldDescriptionsMap.put("custom1", "A custom property with name \"1\""); - classificationFieldDescriptionsMap.put("custom2", "A custom property with name \"2\""); - classificationFieldDescriptionsMap.put("custom3", "A custom property with name \"3\""); - classificationFieldDescriptionsMap.put("custom4", "A custom property with name \"4\""); - classificationFieldDescriptionsMap.put("custom5", "A custom property with name \"5\""); - classificationFieldDescriptionsMap.put("custom6", "A custom property with name \"6\""); - classificationFieldDescriptionsMap.put("custom7", "A custom property with name \"7\""); - classificationFieldDescriptionsMap.put("custom8", "A custom property with name \"8\""); - classificationFieldDescriptionsMap.put("_links.getAllClassifications.href", "Link to all classifications"); - classificationFieldDescriptionsMap.put("_links.getAllClassifications.templated", ""); + classificationFieldDescriptionsMap.put("classificationId", "Unique Id"); + classificationFieldDescriptionsMap.put( + "key", + "The key of the classification. This is typically an externally known code or abbreviation of the classification"); + classificationFieldDescriptionsMap.put( + "parentId", + "The id of the parent classification. Empty string (\"\") if this is a root classification."); + classificationFieldDescriptionsMap.put( + "parentKey", + "The key of the parent classification. Empty string (\"\") if this is a root classification."); + classificationFieldDescriptionsMap.put( + "category", "The category of the classification (MANUAL, EXTERNAL, AUTOMATIC, PROCESS)"); + classificationFieldDescriptionsMap.put("type", "The type of classification (TASK, DOCUMENT)"); + classificationFieldDescriptionsMap.put( + "domain", "The domain for which this classification is specified"); + classificationFieldDescriptionsMap.put( + "isValidInDomain", "True, if this classification to objects in this domain"); + classificationFieldDescriptionsMap.put( + "created", "The creation timestamp of the classification in the system"); + classificationFieldDescriptionsMap.put( + "modified", "The timestamp of the last modification date"); + classificationFieldDescriptionsMap.put("name", "The name of the classification"); + classificationFieldDescriptionsMap.put("description", "The description of the classification"); + classificationFieldDescriptionsMap.put("priority", "The priority of the classification"); + classificationFieldDescriptionsMap.put( + "serviceLevel", + "The service level of the classification. This is stated according to ISO 8601"); + classificationFieldDescriptionsMap.put( + "applicationEntryPoint", + "The logical name of the entry point, the task list application should redirect to work on a task of this classification"); + classificationFieldDescriptionsMap.put("custom1", "A custom property with name \"1\""); + classificationFieldDescriptionsMap.put("custom2", "A custom property with name \"2\""); + classificationFieldDescriptionsMap.put("custom3", "A custom property with name \"3\""); + classificationFieldDescriptionsMap.put("custom4", "A custom property with name \"4\""); + classificationFieldDescriptionsMap.put("custom5", "A custom property with name \"5\""); + classificationFieldDescriptionsMap.put("custom6", "A custom property with name \"6\""); + classificationFieldDescriptionsMap.put("custom7", "A custom property with name \"7\""); + classificationFieldDescriptionsMap.put("custom8", "A custom property with name \"8\""); + classificationFieldDescriptionsMap.put( + "_links.getAllClassifications.href", "Link to all classifications"); + classificationFieldDescriptionsMap.put("_links.getAllClassifications.templated", ""); - allClassificationsFieldDescriptors = new FieldDescriptor[] { - - subsectionWithPath("classifications") - .description("An Array of <>"), - fieldWithPath("_links.self.href").ignored(), - fieldWithPath("page").ignored() + allClassificationsFieldDescriptors = + new FieldDescriptor[] { + subsectionWithPath("classifications") + .description("An Array of <>"), + fieldWithPath("_links.self.href").ignored(), + fieldWithPath("page").ignored() }; - classificationFieldDescriptors = new FieldDescriptor[] { - - fieldWithPath("classificationId").description(classificationFieldDescriptionsMap.get("classificationId")), - fieldWithPath("key").description(classificationFieldDescriptionsMap.get("key")), - fieldWithPath("parentId").description(classificationFieldDescriptionsMap.get("parentId")), - fieldWithPath("parentKey").description(classificationFieldDescriptionsMap.get("parentKey")), - fieldWithPath("category").description(classificationFieldDescriptionsMap.get("category")), - fieldWithPath("type").description(classificationFieldDescriptionsMap.get("type")), - fieldWithPath("domain").description(classificationFieldDescriptionsMap.get("domain")), - fieldWithPath("isValidInDomain").description(classificationFieldDescriptionsMap.get("isValidInDomain")), - fieldWithPath("created").description(classificationFieldDescriptionsMap.get("created")), - fieldWithPath("modified").description(classificationFieldDescriptionsMap.get("modified")), - fieldWithPath("name").description(classificationFieldDescriptionsMap.get("name")), - fieldWithPath("description").description(classificationFieldDescriptionsMap.get("description")), - fieldWithPath("priority").description(classificationFieldDescriptionsMap.get("priority")), - fieldWithPath("serviceLevel").description(classificationFieldDescriptionsMap.get("serviceLevel")), - fieldWithPath("applicationEntryPoint") - .description(classificationFieldDescriptionsMap.get("applicationEntryPoint")), - fieldWithPath("custom1").description(classificationFieldDescriptionsMap.get("custom1")), - fieldWithPath("custom2").description(classificationFieldDescriptionsMap.get("custom2")), - fieldWithPath("custom3").description(classificationFieldDescriptionsMap.get("custom3")), - fieldWithPath("custom4").description(classificationFieldDescriptionsMap.get("custom4")), - fieldWithPath("custom5").description(classificationFieldDescriptionsMap.get("custom5")), - fieldWithPath("custom6").description(classificationFieldDescriptionsMap.get("custom6")), - fieldWithPath("custom7").description(classificationFieldDescriptionsMap.get("custom7")), - fieldWithPath("custom8").description(classificationFieldDescriptionsMap.get("custom8")), - fieldWithPath("_links.self.href").ignored() + classificationFieldDescriptors = + new FieldDescriptor[] { + fieldWithPath("classificationId") + .description(classificationFieldDescriptionsMap.get("classificationId")), + fieldWithPath("key").description(classificationFieldDescriptionsMap.get("key")), + fieldWithPath("parentId").description(classificationFieldDescriptionsMap.get("parentId")), + fieldWithPath("parentKey") + .description(classificationFieldDescriptionsMap.get("parentKey")), + fieldWithPath("category").description(classificationFieldDescriptionsMap.get("category")), + fieldWithPath("type").description(classificationFieldDescriptionsMap.get("type")), + fieldWithPath("domain").description(classificationFieldDescriptionsMap.get("domain")), + fieldWithPath("isValidInDomain") + .description(classificationFieldDescriptionsMap.get("isValidInDomain")), + fieldWithPath("created").description(classificationFieldDescriptionsMap.get("created")), + fieldWithPath("modified").description(classificationFieldDescriptionsMap.get("modified")), + fieldWithPath("name").description(classificationFieldDescriptionsMap.get("name")), + fieldWithPath("description") + .description(classificationFieldDescriptionsMap.get("description")), + fieldWithPath("priority").description(classificationFieldDescriptionsMap.get("priority")), + fieldWithPath("serviceLevel") + .description(classificationFieldDescriptionsMap.get("serviceLevel")), + fieldWithPath("applicationEntryPoint") + .description(classificationFieldDescriptionsMap.get("applicationEntryPoint")), + fieldWithPath("custom1").description(classificationFieldDescriptionsMap.get("custom1")), + fieldWithPath("custom2").description(classificationFieldDescriptionsMap.get("custom2")), + fieldWithPath("custom3").description(classificationFieldDescriptionsMap.get("custom3")), + fieldWithPath("custom4").description(classificationFieldDescriptionsMap.get("custom4")), + fieldWithPath("custom5").description(classificationFieldDescriptionsMap.get("custom5")), + fieldWithPath("custom6").description(classificationFieldDescriptionsMap.get("custom6")), + fieldWithPath("custom7").description(classificationFieldDescriptionsMap.get("custom7")), + fieldWithPath("custom8").description(classificationFieldDescriptionsMap.get("custom8")), + fieldWithPath("_links.self.href").ignored() }; - classificationSubsetFieldDescriptors = new FieldDescriptor[] { - - fieldWithPath("classificationId").description(classificationFieldDescriptionsMap.get("classificationId")), - fieldWithPath("key").description(classificationFieldDescriptionsMap.get("key")), - fieldWithPath("category").description(classificationFieldDescriptionsMap.get("category")), - fieldWithPath("type").description(classificationFieldDescriptionsMap.get("type")), - fieldWithPath("domain").description(classificationFieldDescriptionsMap.get("domain")), - fieldWithPath("isValidInDomain").ignored(), - fieldWithPath("created").ignored(), - fieldWithPath("modified").ignored(), - fieldWithPath("name").description(classificationFieldDescriptionsMap.get("name")), - fieldWithPath("parentId").description(classificationFieldDescriptionsMap.get("parentId")), - fieldWithPath("parentKey").description(classificationFieldDescriptionsMap.get("parentKey")), - fieldWithPath("description").ignored(), - fieldWithPath("priority").description(classificationFieldDescriptionsMap.get("priority")), - fieldWithPath("serviceLevel").description(classificationFieldDescriptionsMap.get("serviceLevel")), - fieldWithPath("applicationEntryPoint").ignored(), - fieldWithPath("custom1").description(classificationFieldDescriptionsMap.get("custom1")), - fieldWithPath("custom2").description(classificationFieldDescriptionsMap.get("custom2")), - fieldWithPath("custom3").description(classificationFieldDescriptionsMap.get("custom3")), - fieldWithPath("custom4").description(classificationFieldDescriptionsMap.get("custom4")), - fieldWithPath("custom5").description(classificationFieldDescriptionsMap.get("custom5")), - fieldWithPath("custom6").description(classificationFieldDescriptionsMap.get("custom6")), - fieldWithPath("custom7").description(classificationFieldDescriptionsMap.get("custom7")), - fieldWithPath("custom8").description(classificationFieldDescriptionsMap.get("custom8")), - fieldWithPath("_links.self.href").ignored() + classificationSubsetFieldDescriptors = + new FieldDescriptor[] { + fieldWithPath("classificationId") + .description(classificationFieldDescriptionsMap.get("classificationId")), + fieldWithPath("key").description(classificationFieldDescriptionsMap.get("key")), + fieldWithPath("category").description(classificationFieldDescriptionsMap.get("category")), + fieldWithPath("type").description(classificationFieldDescriptionsMap.get("type")), + fieldWithPath("domain").description(classificationFieldDescriptionsMap.get("domain")), + fieldWithPath("isValidInDomain").ignored(), + fieldWithPath("created").ignored(), + fieldWithPath("modified").ignored(), + fieldWithPath("name").description(classificationFieldDescriptionsMap.get("name")), + fieldWithPath("parentId").description(classificationFieldDescriptionsMap.get("parentId")), + fieldWithPath("parentKey") + .description(classificationFieldDescriptionsMap.get("parentKey")), + fieldWithPath("description").ignored(), + fieldWithPath("priority").description(classificationFieldDescriptionsMap.get("priority")), + fieldWithPath("serviceLevel") + .description(classificationFieldDescriptionsMap.get("serviceLevel")), + fieldWithPath("applicationEntryPoint").ignored(), + fieldWithPath("custom1").description(classificationFieldDescriptionsMap.get("custom1")), + fieldWithPath("custom2").description(classificationFieldDescriptionsMap.get("custom2")), + fieldWithPath("custom3").description(classificationFieldDescriptionsMap.get("custom3")), + fieldWithPath("custom4").description(classificationFieldDescriptionsMap.get("custom4")), + fieldWithPath("custom5").description(classificationFieldDescriptionsMap.get("custom5")), + fieldWithPath("custom6").description(classificationFieldDescriptionsMap.get("custom6")), + fieldWithPath("custom7").description(classificationFieldDescriptionsMap.get("custom7")), + fieldWithPath("custom8").description(classificationFieldDescriptionsMap.get("custom8")), + fieldWithPath("_links.self.href").ignored() }; - createClassificationFieldDescriptors = new FieldDescriptor[] { - - fieldWithPath("category").type("String") - .description("The category of the classification (MANUAL, EXTERNAL, AUTOMATIC, PROCESS)") - .optional(), - fieldWithPath("domain").description("The domain for which this classification is specified"), - fieldWithPath("key").description( - "The key of the classification. This is typically an externally known code or abbreviation of the classification"), - fieldWithPath("name").type("String").description("The name of the classification").optional(), - fieldWithPath("type").type("String").description("The type of classification (TASK, DOCUMENT)").optional(), - fieldWithPath("parentId").type("String") - .description(classificationFieldDescriptionsMap.get("parentId")) - .optional(), - fieldWithPath("parentKey").type("String") - .description(classificationFieldDescriptionsMap.get("parentKey")) - .optional(), - fieldWithPath("isValidInDomain").type("Boolean") - .description(classificationFieldDescriptionsMap.get("isValidInDomain")) - .optional(), - fieldWithPath("created").type("String") - .description(classificationFieldDescriptionsMap.get("created")) - .optional(), - fieldWithPath("modified").type("String") - .description(classificationFieldDescriptionsMap.get("modified")) - .optional(), - fieldWithPath("description").type("String") - .description(classificationFieldDescriptionsMap.get("description")) - .optional(), - fieldWithPath("priority").type("Number") - .description(classificationFieldDescriptionsMap.get("priority")) - .optional(), - fieldWithPath("serviceLevel").type("String") - .description(classificationFieldDescriptionsMap.get("serviceLevel")) - .optional(), - fieldWithPath("applicationEntryPoint").type("String") - .description(classificationFieldDescriptionsMap.get("applicationEntryPoint")) - .optional(), - fieldWithPath("custom1").type("String") - .description(classificationFieldDescriptionsMap.get("custom1")) - .optional(), - fieldWithPath("custom2").type("String") - .description(classificationFieldDescriptionsMap.get("custom2")) - .optional(), - fieldWithPath("custom3").type("String") - .description(classificationFieldDescriptionsMap.get("custom3")) - .optional(), - fieldWithPath("custom4").type("String") - .description(classificationFieldDescriptionsMap.get("custom4")) - .optional(), - fieldWithPath("custom5").type("String") - .description(classificationFieldDescriptionsMap.get("custom5")) - .optional(), - fieldWithPath("custom6").type("String") - .description(classificationFieldDescriptionsMap.get("custom6")) - .optional(), - fieldWithPath("custom7").type("String") - .description(classificationFieldDescriptionsMap.get("custom7")) - .optional(), - fieldWithPath("custom8").type("String") - .description(classificationFieldDescriptionsMap.get("custom8")) - .optional() + createClassificationFieldDescriptors = + new FieldDescriptor[] { + fieldWithPath("category") + .type("String") + .description( + "The category of the classification (MANUAL, EXTERNAL, AUTOMATIC, PROCESS)") + .optional(), + fieldWithPath("domain") + .description("The domain for which this classification is specified"), + fieldWithPath("key") + .description( + "The key of the classification. This is typically an externally known code or abbreviation of the classification"), + fieldWithPath("name") + .type("String") + .description("The name of the classification") + .optional(), + fieldWithPath("type") + .type("String") + .description("The type of classification (TASK, DOCUMENT)") + .optional(), + fieldWithPath("parentId") + .type("String") + .description(classificationFieldDescriptionsMap.get("parentId")) + .optional(), + fieldWithPath("parentKey") + .type("String") + .description(classificationFieldDescriptionsMap.get("parentKey")) + .optional(), + fieldWithPath("isValidInDomain") + .type("Boolean") + .description(classificationFieldDescriptionsMap.get("isValidInDomain")) + .optional(), + fieldWithPath("created") + .type("String") + .description(classificationFieldDescriptionsMap.get("created")) + .optional(), + fieldWithPath("modified") + .type("String") + .description(classificationFieldDescriptionsMap.get("modified")) + .optional(), + fieldWithPath("description") + .type("String") + .description(classificationFieldDescriptionsMap.get("description")) + .optional(), + fieldWithPath("priority") + .type("Number") + .description(classificationFieldDescriptionsMap.get("priority")) + .optional(), + fieldWithPath("serviceLevel") + .type("String") + .description(classificationFieldDescriptionsMap.get("serviceLevel")) + .optional(), + fieldWithPath("applicationEntryPoint") + .type("String") + .description(classificationFieldDescriptionsMap.get("applicationEntryPoint")) + .optional(), + fieldWithPath("custom1") + .type("String") + .description(classificationFieldDescriptionsMap.get("custom1")) + .optional(), + fieldWithPath("custom2") + .type("String") + .description(classificationFieldDescriptionsMap.get("custom2")) + .optional(), + fieldWithPath("custom3") + .type("String") + .description(classificationFieldDescriptionsMap.get("custom3")) + .optional(), + fieldWithPath("custom4") + .type("String") + .description(classificationFieldDescriptionsMap.get("custom4")) + .optional(), + fieldWithPath("custom5") + .type("String") + .description(classificationFieldDescriptionsMap.get("custom5")) + .optional(), + fieldWithPath("custom6") + .type("String") + .description(classificationFieldDescriptionsMap.get("custom6")) + .optional(), + fieldWithPath("custom7") + .type("String") + .description(classificationFieldDescriptionsMap.get("custom7")) + .optional(), + fieldWithPath("custom8") + .type("String") + .description(classificationFieldDescriptionsMap.get("custom8")) + .optional() }; - } + } - @Test - void getAllClassificationsDocTest() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders - .get(restHelper.toUrl(Mapping.URL_CLASSIFICATIONS) + "?domain=DOMAIN_B") - .accept("application/hal+json") - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("GetAllClassificationsDocTest", + @Test + void getAllClassificationsDocTest() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get( + restHelper.toUrl(Mapping.URL_CLASSIFICATIONS) + "?domain=DOMAIN_B") + .accept("application/hal+json") + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "GetAllClassificationsDocTest", responseFields(allClassificationsFieldDescriptors))); - } + } - @Test - void getSpecificClassificationDocTest() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders - .get(restHelper.toUrl(Mapping.URL_CLASSIFICATIONS_ID, "CLI:100000000000000000000000000000000009")) - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("GetSpecificClassificationDocTest", + @Test + void getSpecificClassificationDocTest() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get( + restHelper.toUrl( + Mapping.URL_CLASSIFICATIONS_ID, "CLI:100000000000000000000000000000000009")) + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "GetSpecificClassificationDocTest", responseFields(classificationFieldDescriptors))); - } + } - @Test - void classificationSubsetDocTest() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders - .get(restHelper.toUrl(Mapping.URL_CLASSIFICATIONS_ID, "CLI:100000000000000000000000000000000009")) - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("ClassificationSubset", - responseFields(classificationSubsetFieldDescriptors))); - } + @Test + void classificationSubsetDocTest() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get( + restHelper.toUrl( + Mapping.URL_CLASSIFICATIONS_ID, "CLI:100000000000000000000000000000000009")) + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "ClassificationSubset", responseFields(classificationSubsetFieldDescriptors))); + } - @Test - void createAndDeleteClassificationDocTest() throws Exception { - MvcResult result = this.mockMvc.perform(RestDocumentationRequestBuilders - .post(restHelper.toUrl(Mapping.URL_CLASSIFICATIONS)) - .contentType("application/hal+json") - .content("{\"key\":\"Key0815casdgdgh\", \"domain\":\"DOMAIN_B\"}") - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + @Test + void createAndDeleteClassificationDocTest() throws Exception { + MvcResult result = + this.mockMvc + .perform( + RestDocumentationRequestBuilders.post(restHelper.toUrl(Mapping.URL_CLASSIFICATIONS)) + .contentType("application/hal+json") + .content("{\"key\":\"Key0815casdgdgh\", \"domain\":\"DOMAIN_B\"}") + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) .andExpect(MockMvcResultMatchers.status().isCreated()) - .andDo(MockMvcRestDocumentation.document("CreateClassificationDocTest", - requestFields(createClassificationFieldDescriptors), - responseFields(classificationFieldDescriptors))) + .andDo( + MockMvcRestDocumentation.document( + "CreateClassificationDocTest", + requestFields(createClassificationFieldDescriptors), + responseFields(classificationFieldDescriptors))) .andReturn(); - String content = result.getResponse().getContentAsString(); - String newId = content.substring(content.indexOf("CLI:"), content.indexOf("CLI:") + 40); + String content = result.getResponse().getContentAsString(); + String newId = content.substring(content.indexOf("CLI:"), content.indexOf("CLI:") + 40); - this.mockMvc.perform(RestDocumentationRequestBuilders - .delete(restHelper.toUrl(Mapping.URL_CLASSIFICATIONS_ID, newId)) - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isNoContent()) - .andDo(MockMvcRestDocumentation.document("DeleteClassificationDocTest")); + this.mockMvc + .perform( + RestDocumentationRequestBuilders.delete( + restHelper.toUrl(Mapping.URL_CLASSIFICATIONS_ID, newId)) + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + .andExpect(MockMvcResultMatchers.status().isNoContent()) + .andDo(MockMvcRestDocumentation.document("DeleteClassificationDocTest")); + } + + @Test + void updateClassificationDocTest() throws Exception { + URL url = + new URL( + restHelper.toUrl( + Mapping.URL_CLASSIFICATIONS_ID, "CLI:100000000000000000000000000000000009")); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("GET"); + con.setRequestProperty("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x"); + assertEquals(200, con.getResponseCode()); + + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + StringBuffer content = new StringBuffer(); + while ((inputLine = in.readLine()) != null) { + content.append(inputLine); } + in.close(); + con.disconnect(); + String originalTask = content.toString(); + String modifiedTask = new String(originalTask.toString()); - @Test - void updateClassificationDocTest() throws Exception { - URL url = new URL( - restHelper.toUrl(Mapping.URL_CLASSIFICATIONS_ID, "CLI:100000000000000000000000000000000009")); - HttpURLConnection con = (HttpURLConnection) url.openConnection(); - con.setRequestMethod("GET"); - con.setRequestProperty("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x"); - assertEquals(200, con.getResponseCode()); - - BufferedReader in = new BufferedReader( - new InputStreamReader(con.getInputStream())); - String inputLine; - StringBuffer content = new StringBuffer(); - while ((inputLine = in.readLine()) != null) { - content.append(inputLine); - } - in.close(); - con.disconnect(); - String originalTask = content.toString(); - String modifiedTask = new String(originalTask.toString()); - - this.mockMvc.perform(RestDocumentationRequestBuilders - .put(restHelper.toUrl(Mapping.URL_CLASSIFICATIONS_ID, "CLI:100000000000000000000000000000000009")) - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x") - .contentType("application/json") - .content(modifiedTask)) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("UpdateClassificationDocTest", + this.mockMvc + .perform( + RestDocumentationRequestBuilders.put( + restHelper.toUrl( + Mapping.URL_CLASSIFICATIONS_ID, "CLI:100000000000000000000000000000000009")) + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x") + .contentType("application/json") + .content(modifiedTask)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "UpdateClassificationDocTest", requestFields(classificationFieldDescriptors), responseFields(classificationFieldDescriptors))); - } + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/ClassificationDefinitionControllerRestDocumentation.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/ClassificationDefinitionControllerRestDocumentation.java index 83789cb90..4f4e08525 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/ClassificationDefinitionControllerRestDocumentation.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/ClassificationDefinitionControllerRestDocumentation.java @@ -16,42 +16,49 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import pro.taskana.rest.Mapping; -/** - * Test ClassificationDefinitionControlller. - */ +/** Test ClassificationDefinitionControlller. */ class ClassificationDefinitionControllerRestDocumentation extends BaseRestDocumentation { - private FieldDescriptor[] classificationDefinitionsFieldDescriptors; + private FieldDescriptor[] classificationDefinitionsFieldDescriptors; - @BeforeEach - void setUp() { + @BeforeEach + void setUp() { - classificationDefinitionsFieldDescriptors = new FieldDescriptor[] { - subsectionWithPath("[]").description("An array of <>") + classificationDefinitionsFieldDescriptors = + new FieldDescriptor[] { + subsectionWithPath("[]") + .description("An array of <>") }; - } + } - @Test - void exportAllClassificationDefinitions() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders - .get(restHelper.toUrl(Mapping.URL_CLASSIFICATIONDEFINITION)) - .accept("application/json") - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("ExportClassificationDefinitionsDocTest", + @Test + void exportAllClassificationDefinitions() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get( + restHelper.toUrl(Mapping.URL_CLASSIFICATIONDEFINITION)) + .accept("application/json") + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "ExportClassificationDefinitionsDocTest", responseFields(classificationDefinitionsFieldDescriptors))); - } + } - @Test - void importClassificationDefinitions() throws Exception { - String definitionString = "[{\"key\":\"Key0815\", \"domain\":\"DOMAIN_B\"}]"; + @Test + void importClassificationDefinitions() throws Exception { + String definitionString = "[{\"key\":\"Key0815\", \"domain\":\"DOMAIN_B\"}]"; - this.mockMvc.perform(multipart(restHelper.toUrl(Mapping.URL_CLASSIFICATIONDEFINITION)) - .file("file", - definitionString.getBytes()) - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isNoContent()) - .andDo(document("ImportClassificationDefinitions", requestParts( - partWithName("file").description("The file to upload")))); - } + this.mockMvc + .perform( + multipart(restHelper.toUrl(Mapping.URL_CLASSIFICATIONDEFINITION)) + .file("file", definitionString.getBytes()) + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + .andExpect(MockMvcResultMatchers.status().isNoContent()) + .andDo( + document( + "ImportClassificationDefinitions", + requestParts(partWithName("file").description("The file to upload")))); + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/CommonRestDocumentation.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/CommonRestDocumentation.java index 8a2b1ab20..32596cd21 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/CommonRestDocumentation.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/CommonRestDocumentation.java @@ -4,7 +4,6 @@ import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWit import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; import java.util.HashMap; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation; @@ -14,61 +13,63 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import pro.taskana.rest.Mapping; -/** - * Generate common REST Documentation. - * - */ +/** Generate common REST Documentation. */ class CommonRestDocumentation extends BaseRestDocumentation { - private HashMap selfLinkFieldDescriptionsMap = new HashMap(); + private HashMap selfLinkFieldDescriptionsMap = new HashMap(); - private FieldDescriptor[] selfLinkFieldDescriptors; + private FieldDescriptor[] selfLinkFieldDescriptors; - @BeforeEach - void setUp() { + @BeforeEach + void setUp() { - selfLinkFieldDescriptionsMap.put("_links", "Links section"); - selfLinkFieldDescriptionsMap.put("_links.self", "Link to self"); - selfLinkFieldDescriptionsMap.put("_links.self.href", "Link to instance"); + selfLinkFieldDescriptionsMap.put("_links", "Links section"); + selfLinkFieldDescriptionsMap.put("_links.self", "Link to self"); + selfLinkFieldDescriptionsMap.put("_links.self.href", "Link to instance"); - selfLinkFieldDescriptors = new FieldDescriptor[] { - - fieldWithPath("classificationId").ignored(), - fieldWithPath("key").ignored(), - fieldWithPath("parentId").ignored(), - fieldWithPath("parentKey").ignored(), - fieldWithPath("category").ignored(), - fieldWithPath("type").ignored(), - fieldWithPath("domain").ignored(), - fieldWithPath("isValidInDomain").ignored(), - fieldWithPath("created").ignored(), - fieldWithPath("modified").ignored(), - fieldWithPath("name").ignored(), - fieldWithPath("description").ignored(), - fieldWithPath("priority").ignored(), - fieldWithPath("serviceLevel").ignored(), - fieldWithPath("applicationEntryPoint").ignored(), - fieldWithPath("custom1").ignored(), - fieldWithPath("custom2").ignored(), - fieldWithPath("custom3").ignored(), - fieldWithPath("custom4").ignored(), - fieldWithPath("custom5").ignored(), - fieldWithPath("custom6").ignored(), - fieldWithPath("custom7").ignored(), - fieldWithPath("custom8").ignored(), - fieldWithPath("_links").description(selfLinkFieldDescriptionsMap.get("_links")), - fieldWithPath("_links.self").description(selfLinkFieldDescriptionsMap.get("_links.self")), - fieldWithPath("_links.self.href").description(selfLinkFieldDescriptionsMap.get("_links.self.href")) + selfLinkFieldDescriptors = + new FieldDescriptor[] { + fieldWithPath("classificationId").ignored(), + fieldWithPath("key").ignored(), + fieldWithPath("parentId").ignored(), + fieldWithPath("parentKey").ignored(), + fieldWithPath("category").ignored(), + fieldWithPath("type").ignored(), + fieldWithPath("domain").ignored(), + fieldWithPath("isValidInDomain").ignored(), + fieldWithPath("created").ignored(), + fieldWithPath("modified").ignored(), + fieldWithPath("name").ignored(), + fieldWithPath("description").ignored(), + fieldWithPath("priority").ignored(), + fieldWithPath("serviceLevel").ignored(), + fieldWithPath("applicationEntryPoint").ignored(), + fieldWithPath("custom1").ignored(), + fieldWithPath("custom2").ignored(), + fieldWithPath("custom3").ignored(), + fieldWithPath("custom4").ignored(), + fieldWithPath("custom5").ignored(), + fieldWithPath("custom6").ignored(), + fieldWithPath("custom7").ignored(), + fieldWithPath("custom8").ignored(), + fieldWithPath("_links").description(selfLinkFieldDescriptionsMap.get("_links")), + fieldWithPath("_links.self").description(selfLinkFieldDescriptionsMap.get("_links.self")), + fieldWithPath("_links.self.href") + .description(selfLinkFieldDescriptionsMap.get("_links.self.href")) }; - } + } - @Test - void commonFieldsDocTest() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders - .get(restHelper.toUrl(Mapping.URL_CLASSIFICATIONS_ID, "CLI:100000000000000000000000000000000009")) - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("CommonFields", - responseFields(selfLinkFieldDescriptors))); - } + @Test + void commonFieldsDocTest() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get( + restHelper.toUrl( + Mapping.URL_CLASSIFICATIONS_ID, "CLI:100000000000000000000000000000000009")) + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "CommonFields", responseFields(selfLinkFieldDescriptors))); + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/MonitorControllerRestDocumentation.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/MonitorControllerRestDocumentation.java index b3ab8578c..77fa04000 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/MonitorControllerRestDocumentation.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/MonitorControllerRestDocumentation.java @@ -13,78 +13,91 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import pro.taskana.rest.Mapping; -/** - * Generate REST docu for the monitor controller. - * - */ +/** Generate REST docu for the monitor controller. */ class MonitorControllerRestDocumentation extends BaseRestDocumentation { - private FieldDescriptor[] taskReportFieldDescriptors; + private FieldDescriptor[] taskReportFieldDescriptors; - @BeforeEach - void setUp() { + @BeforeEach + void setUp() { - taskReportFieldDescriptors = new FieldDescriptor[] { - fieldWithPath("meta").description("Object holding metainfo on the report"), - fieldWithPath("meta.name").description("Name of the report"), - fieldWithPath("meta.date").description("Date of the report creation"), - fieldWithPath("meta.header").description("Column-headers of the report"), - fieldWithPath("meta.rowDesc").description("Descriptions for the rows the report"), - fieldWithPath("meta.totalDesc").description("Description for the sum column"), - fieldWithPath("rows").description("Array holding the rows of the report."), - fieldWithPath("rows[].cells").description("Array holding all the cell values of the given row"), - fieldWithPath("rows[].total").description("Sum of all values of the given row"), - fieldWithPath("rows[].depth").description( - "Depth of the row. If the depth is > 0, then this row is a sub-row of a prior row"), - fieldWithPath("rows[].desc").description("Array containing description of the row."), - fieldWithPath("rows[].display").description( - "Boolean identifying if the given row should be initially displayed or not."), - subsectionWithPath("sumRow").description( - "Array holding the sums in the columns over all rows. Structure same as 'rows'"), - fieldWithPath("_links.self.href").ignored() + taskReportFieldDescriptors = + new FieldDescriptor[] { + fieldWithPath("meta").description("Object holding metainfo on the report"), + fieldWithPath("meta.name").description("Name of the report"), + fieldWithPath("meta.date").description("Date of the report creation"), + fieldWithPath("meta.header").description("Column-headers of the report"), + fieldWithPath("meta.rowDesc").description("Descriptions for the rows the report"), + fieldWithPath("meta.totalDesc").description("Description for the sum column"), + fieldWithPath("rows").description("Array holding the rows of the report."), + fieldWithPath("rows[].cells") + .description("Array holding all the cell values of the given row"), + fieldWithPath("rows[].total").description("Sum of all values of the given row"), + fieldWithPath("rows[].depth") + .description( + "Depth of the row. If the depth is > 0, then this row is a sub-row of a prior row"), + fieldWithPath("rows[].desc").description("Array containing description of the row."), + fieldWithPath("rows[].display") + .description( + "Boolean identifying if the given row should be initially displayed or not."), + subsectionWithPath("sumRow") + .description( + "Array holding the sums in the columns over all rows. Structure same as 'rows'"), + fieldWithPath("_links.self.href").ignored() }; - } + } - @Test - void getTaskStatusReport() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders - .get(restHelper.toUrl(Mapping.URL_MONITOR_TASKSSTATUS)) - .header("Authorization", "Basic YWRtaW46YWRtaW4=")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("GetTaskStatusReportDocTest", - responseFields(taskReportFieldDescriptors))); - } + @Test + void getTaskStatusReport() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get(restHelper.toUrl(Mapping.URL_MONITOR_TASKSSTATUS)) + .header("Authorization", "Basic YWRtaW46YWRtaW4=")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "GetTaskStatusReportDocTest", responseFields(taskReportFieldDescriptors))); + } - @Test - void tasksWorkbasketReport() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders - .get(restHelper.toUrl(Mapping.URL_MONITOR_TASKSWORKBASKET) + "?daysInPast=4&states=READY,CLAIMED,COMPLETED") - .accept("application/hal+json") - .header("Authorization", "Basic YWRtaW46YWRtaW4=")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("GetTaskWorkbasketReportDocTest", - responseFields(taskReportFieldDescriptors))); - } + @Test + void tasksWorkbasketReport() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get( + restHelper.toUrl(Mapping.URL_MONITOR_TASKSWORKBASKET) + + "?daysInPast=4&states=READY,CLAIMED,COMPLETED") + .accept("application/hal+json") + .header("Authorization", "Basic YWRtaW46YWRtaW4=")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "GetTaskWorkbasketReportDocTest", responseFields(taskReportFieldDescriptors))); + } - @Test - void tasksClassificationReport() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders - .get(restHelper.toUrl(Mapping.URL_MONITOR_TASKSCLASSIFICATION)) - .accept("application/hal+json") - .header("Authorization", "Basic YWRtaW46YWRtaW4=")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("GetTaskClassificationReportDocTest", - responseFields(taskReportFieldDescriptors))); - } + @Test + void tasksClassificationReport() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get( + restHelper.toUrl(Mapping.URL_MONITOR_TASKSCLASSIFICATION)) + .accept("application/hal+json") + .header("Authorization", "Basic YWRtaW46YWRtaW4=")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "GetTaskClassificationReportDocTest", responseFields(taskReportFieldDescriptors))); + } - @Test - void getTimestampReport() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders - .get(restHelper.toUrl(Mapping.URL_MONITOR_TIMESTAMP)) - .accept("application/hal+json") - .header("Authorization", "Basic YWRtaW46YWRtaW4=")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("GetTimestampReportDocTest", - responseFields(taskReportFieldDescriptors))); - } + @Test + void getTimestampReport() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get(restHelper.toUrl(Mapping.URL_MONITOR_TIMESTAMP)) + .accept("application/hal+json") + .header("Authorization", "Basic YWRtaW46YWRtaW4=")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "GetTimestampReportDocTest", responseFields(taskReportFieldDescriptors))); + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/TaskControllerRestDocumentation.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/TaskControllerRestDocumentation.java index 3958c3e96..ced9f6533 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/TaskControllerRestDocumentation.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/TaskControllerRestDocumentation.java @@ -11,7 +11,6 @@ import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation; @@ -22,455 +21,671 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import pro.taskana.rest.Mapping; -/** - * Generate REST Documentation for the TaskController. - */ +/** Generate REST Documentation for the TaskController. */ class TaskControllerRestDocumentation extends BaseRestDocumentation { - private HashMap taskFieldDescriptionsMap = new HashMap(); + private HashMap taskFieldDescriptionsMap = new HashMap(); - private FieldDescriptor[] allTasksFieldDescriptors; - private FieldDescriptor[] taskFieldDescriptors; - private FieldDescriptor[] taskSubsetFieldDescriptors; - private FieldDescriptor[] createTaskFieldDescriptors; + private FieldDescriptor[] allTasksFieldDescriptors; + private FieldDescriptor[] taskFieldDescriptors; + private FieldDescriptor[] taskSubsetFieldDescriptors; + private FieldDescriptor[] createTaskFieldDescriptors; - @BeforeEach - void setUp() { + @BeforeEach + void setUp() { - taskFieldDescriptionsMap.put("taskId", "Unique ID"); - taskFieldDescriptionsMap.put("externalId", - "External ID. Can be used to enforce idempotency at task creation. Can identify an external task."); - taskFieldDescriptionsMap.put("created", "The creation timestamp of the task in the system."); - taskFieldDescriptionsMap.put("claimed", "The timestamp of the last claim-operation on the task"); - taskFieldDescriptionsMap.put("completed", "The timestamp of the completion of the task"); - taskFieldDescriptionsMap.put("modified", "Timestamp of the last modification of the task"); - taskFieldDescriptionsMap.put("planned", - "Planned start of the task. The actual completion of the task should be between PLANNED and DUE."); - taskFieldDescriptionsMap.put("due", - "Timestamp when the task is due. The actual completion of the task should be between PLANNED and DUE."); - taskFieldDescriptionsMap.put("name", "The name of the task"); - taskFieldDescriptionsMap.put("creator", ""); - taskFieldDescriptionsMap.put("description", "The description of the task"); - taskFieldDescriptionsMap.put("note", "note"); - taskFieldDescriptionsMap.put("priority", "The priority of the task"); - taskFieldDescriptionsMap.put("state", "he state of the task. See (...)"); - taskFieldDescriptionsMap.put("classificationSummaryResource", - "The <> of the task"); - taskFieldDescriptionsMap.put("workbasketSummaryResource", "The <> of the task"); - taskFieldDescriptionsMap.put("businessProcessId", ""); - taskFieldDescriptionsMap.put("parentBusinessProcessId", ""); - taskFieldDescriptionsMap.put("owner", "The owner of the tasks. The owner is set upon claiming of the task."); - taskFieldDescriptionsMap.put("primaryObjRef.id", ""); - taskFieldDescriptionsMap.put("primaryObjRef.company", "The company referenced primary object belongs to."); - taskFieldDescriptionsMap.put("primaryObjRef.system", - "The (kind of) system, the object resides in (e.g. SAP, MySystem A, ...) "); - taskFieldDescriptionsMap.put("primaryObjRef.systemInstance", - "The instance of the system, the object resides in."); - taskFieldDescriptionsMap.put("primaryObjRef.type", - "The type of the reference (contract, claim, policy, customer, ...)"); - taskFieldDescriptionsMap.put("primaryObjRef.value", "The value of the primary object reference"); - taskFieldDescriptionsMap.put("customAttributes", - "A container for all additional information on the task in JSON representation"); - taskFieldDescriptionsMap.put("callbackInfo", - "A container for all callback information of the task in JSON representation"); - taskFieldDescriptionsMap.put("attachments", ""); - taskFieldDescriptionsMap.put("custom1", "A custom property with name \"1\""); - taskFieldDescriptionsMap.put("custom2", "A custom property with name \"2\""); - taskFieldDescriptionsMap.put("custom3", "A custom property with name \"3\""); - taskFieldDescriptionsMap.put("custom4", "A custom property with name \"4\""); - taskFieldDescriptionsMap.put("custom5", "A custom property with name \"5\""); - taskFieldDescriptionsMap.put("custom6", "A custom property with name \"6\""); - taskFieldDescriptionsMap.put("custom7", "A custom property with name \"7\""); - taskFieldDescriptionsMap.put("custom8", "A custom property with name \"8\""); - taskFieldDescriptionsMap.put("custom9", "A custom property with name \"9\""); - taskFieldDescriptionsMap.put("custom10", "A custom property with name \"10\""); - taskFieldDescriptionsMap.put("custom11", "A custom property with name \"11\""); - taskFieldDescriptionsMap.put("custom12", "A custom property with name \"12\""); - taskFieldDescriptionsMap.put("custom13", "A custom property with name \"13\""); - taskFieldDescriptionsMap.put("custom14", "A custom property with name \"14\""); - taskFieldDescriptionsMap.put("custom15", "A custom property with name \"15\""); - taskFieldDescriptionsMap.put("custom16", "A custom property with name \"16\""); - taskFieldDescriptionsMap.put("read", "Indicator if the task has been read"); - taskFieldDescriptionsMap.put("transferred", "Indicator if the task has been transferred"); + taskFieldDescriptionsMap.put("taskId", "Unique ID"); + taskFieldDescriptionsMap.put( + "externalId", + "External ID. Can be used to enforce idempotency at task creation. Can identify an external task."); + taskFieldDescriptionsMap.put("created", "The creation timestamp of the task in the system."); + taskFieldDescriptionsMap.put( + "claimed", "The timestamp of the last claim-operation on the task"); + taskFieldDescriptionsMap.put("completed", "The timestamp of the completion of the task"); + taskFieldDescriptionsMap.put("modified", "Timestamp of the last modification of the task"); + taskFieldDescriptionsMap.put( + "planned", + "Planned start of the task. The actual completion of the task should be between PLANNED and DUE."); + taskFieldDescriptionsMap.put( + "due", + "Timestamp when the task is due. The actual completion of the task should be between PLANNED and DUE."); + taskFieldDescriptionsMap.put("name", "The name of the task"); + taskFieldDescriptionsMap.put("creator", ""); + taskFieldDescriptionsMap.put("description", "The description of the task"); + taskFieldDescriptionsMap.put("note", "note"); + taskFieldDescriptionsMap.put("priority", "The priority of the task"); + taskFieldDescriptionsMap.put("state", "he state of the task. See (...)"); + taskFieldDescriptionsMap.put( + "classificationSummaryResource", + "The <> of the task"); + taskFieldDescriptionsMap.put( + "workbasketSummaryResource", "The <> of the task"); + taskFieldDescriptionsMap.put("businessProcessId", ""); + taskFieldDescriptionsMap.put("parentBusinessProcessId", ""); + taskFieldDescriptionsMap.put( + "owner", "The owner of the tasks. The owner is set upon claiming of the task."); + taskFieldDescriptionsMap.put("primaryObjRef.id", ""); + taskFieldDescriptionsMap.put( + "primaryObjRef.company", "The company referenced primary object belongs to."); + taskFieldDescriptionsMap.put( + "primaryObjRef.system", + "The (kind of) system, the object resides in (e.g. SAP, MySystem A, ...) "); + taskFieldDescriptionsMap.put( + "primaryObjRef.systemInstance", "The instance of the system, the object resides in."); + taskFieldDescriptionsMap.put( + "primaryObjRef.type", "The type of the reference (contract, claim, policy, customer, ...)"); + taskFieldDescriptionsMap.put( + "primaryObjRef.value", "The value of the primary object reference"); + taskFieldDescriptionsMap.put( + "customAttributes", + "A container for all additional information on the task in JSON representation"); + taskFieldDescriptionsMap.put( + "callbackInfo", + "A container for all callback information of the task in JSON representation"); + taskFieldDescriptionsMap.put("attachments", ""); + taskFieldDescriptionsMap.put("custom1", "A custom property with name \"1\""); + taskFieldDescriptionsMap.put("custom2", "A custom property with name \"2\""); + taskFieldDescriptionsMap.put("custom3", "A custom property with name \"3\""); + taskFieldDescriptionsMap.put("custom4", "A custom property with name \"4\""); + taskFieldDescriptionsMap.put("custom5", "A custom property with name \"5\""); + taskFieldDescriptionsMap.put("custom6", "A custom property with name \"6\""); + taskFieldDescriptionsMap.put("custom7", "A custom property with name \"7\""); + taskFieldDescriptionsMap.put("custom8", "A custom property with name \"8\""); + taskFieldDescriptionsMap.put("custom9", "A custom property with name \"9\""); + taskFieldDescriptionsMap.put("custom10", "A custom property with name \"10\""); + taskFieldDescriptionsMap.put("custom11", "A custom property with name \"11\""); + taskFieldDescriptionsMap.put("custom12", "A custom property with name \"12\""); + taskFieldDescriptionsMap.put("custom13", "A custom property with name \"13\""); + taskFieldDescriptionsMap.put("custom14", "A custom property with name \"14\""); + taskFieldDescriptionsMap.put("custom15", "A custom property with name \"15\""); + taskFieldDescriptionsMap.put("custom16", "A custom property with name \"16\""); + taskFieldDescriptionsMap.put("read", "Indicator if the task has been read"); + taskFieldDescriptionsMap.put("transferred", "Indicator if the task has been transferred"); - allTasksFieldDescriptors = new FieldDescriptor[] { - - subsectionWithPath("tasks").description("An Array of <>"), - fieldWithPath("_links").ignored(), - fieldWithPath("_links.self").ignored(), - fieldWithPath("_links.self.href").ignored(), - fieldWithPath("page").ignored() + allTasksFieldDescriptors = + new FieldDescriptor[] { + subsectionWithPath("tasks").description("An Array of <>"), + fieldWithPath("_links").ignored(), + fieldWithPath("_links.self").ignored(), + fieldWithPath("_links.self.href").ignored(), + fieldWithPath("page").ignored() }; - taskFieldDescriptors = new FieldDescriptor[] { - - fieldWithPath("taskId").description(taskFieldDescriptionsMap.get("taskId")), - fieldWithPath("externalId").description(taskFieldDescriptionsMap.get("externalId")), - fieldWithPath("created").description(taskFieldDescriptionsMap.get("created")), - fieldWithPath("claimed").description(taskFieldDescriptionsMap.get("claimed")).type("String"), - fieldWithPath("completed").description(taskFieldDescriptionsMap.get("completed")).type("String"), - fieldWithPath("modified").description(taskFieldDescriptionsMap.get("modified")).type("String"), - fieldWithPath("planned").description(taskFieldDescriptionsMap.get("planned")).type("String"), - fieldWithPath("due").description(taskFieldDescriptionsMap.get("due")).type("String"), - fieldWithPath("name").description(taskFieldDescriptionsMap.get("name")), - fieldWithPath("creator").description(taskFieldDescriptionsMap.get("creator")), - fieldWithPath("description").description(taskFieldDescriptionsMap.get("description")), - fieldWithPath("note").description(taskFieldDescriptionsMap.get("note")).description("Some custom Note"), - fieldWithPath("priority").description(taskFieldDescriptionsMap.get("priority")), - fieldWithPath("state").description(taskFieldDescriptionsMap.get("state")), - subsectionWithPath("classificationSummaryResource") - .description(taskFieldDescriptionsMap.get("classificationSummaryResource")), - subsectionWithPath("workbasketSummaryResource") - .description(taskFieldDescriptionsMap.get("workbasketSummaryResource")), - fieldWithPath("businessProcessId").description(taskFieldDescriptionsMap.get("businessProcessId")), - fieldWithPath("parentBusinessProcessId") - .description(taskFieldDescriptionsMap.get("parentBusinessProcessId")), - fieldWithPath("owner").description(taskFieldDescriptionsMap.get("owner")).type("String"), - fieldWithPath("primaryObjRef.id").description(taskFieldDescriptionsMap.get("primaryObjRef.id")) - .type("String"), - fieldWithPath("primaryObjRef.company").description(taskFieldDescriptionsMap.get("primaryObjRef.company")), - fieldWithPath("primaryObjRef.system").description(taskFieldDescriptionsMap.get("primaryObjRef.system")), - fieldWithPath("primaryObjRef.systemInstance") - .description(taskFieldDescriptionsMap.get("primaryObjRef.systemInstance")), - fieldWithPath("primaryObjRef.type").description(taskFieldDescriptionsMap.get("primaryObjRef.type")), - fieldWithPath("primaryObjRef.value").description(taskFieldDescriptionsMap.get("primaryObjRef.value")), - fieldWithPath("read").description(taskFieldDescriptionsMap.get("read")), - fieldWithPath("transferred").description(taskFieldDescriptionsMap.get("transferred")), - fieldWithPath("customAttributes").description(taskFieldDescriptionsMap.get("customAttributes")), - fieldWithPath("callbackInfo").description(taskFieldDescriptionsMap.get("callbackInfo")), - fieldWithPath("attachments").description(taskFieldDescriptionsMap.get("attachments")), - fieldWithPath("custom1").description(taskFieldDescriptionsMap.get("custom1")).type("String"), - fieldWithPath("custom2").description(taskFieldDescriptionsMap.get("custom2")).type("String"), - fieldWithPath("custom3").description(taskFieldDescriptionsMap.get("custom3")).type("String"), - fieldWithPath("custom4").description(taskFieldDescriptionsMap.get("custom4")).type("String"), - fieldWithPath("custom5").description(taskFieldDescriptionsMap.get("custom5")).type("String"), - fieldWithPath("custom6").description(taskFieldDescriptionsMap.get("custom6")).type("String"), - fieldWithPath("custom7").description(taskFieldDescriptionsMap.get("custom7")).type("String"), - fieldWithPath("custom8").description(taskFieldDescriptionsMap.get("custom8")).type("String"), - fieldWithPath("custom9").description(taskFieldDescriptionsMap.get("custom9")).type("String"), - fieldWithPath("custom10").description(taskFieldDescriptionsMap.get("custom10")).type("String"), - fieldWithPath("custom11").description(taskFieldDescriptionsMap.get("custom11")).type("String"), - fieldWithPath("custom12").description(taskFieldDescriptionsMap.get("custom12")).type("String"), - fieldWithPath("custom13").description(taskFieldDescriptionsMap.get("custom13")).type("String"), - fieldWithPath("custom14").description(taskFieldDescriptionsMap.get("custom14")).type("String"), - fieldWithPath("custom15").description(taskFieldDescriptionsMap.get("custom15")).type("String"), - fieldWithPath("custom16").description(taskFieldDescriptionsMap.get("custom16")).type("String"), - fieldWithPath("_links.self.href").ignored() + taskFieldDescriptors = + new FieldDescriptor[] { + fieldWithPath("taskId").description(taskFieldDescriptionsMap.get("taskId")), + fieldWithPath("externalId").description(taskFieldDescriptionsMap.get("externalId")), + fieldWithPath("created").description(taskFieldDescriptionsMap.get("created")), + fieldWithPath("claimed") + .description(taskFieldDescriptionsMap.get("claimed")) + .type("String"), + fieldWithPath("completed") + .description(taskFieldDescriptionsMap.get("completed")) + .type("String"), + fieldWithPath("modified") + .description(taskFieldDescriptionsMap.get("modified")) + .type("String"), + fieldWithPath("planned") + .description(taskFieldDescriptionsMap.get("planned")) + .type("String"), + fieldWithPath("due").description(taskFieldDescriptionsMap.get("due")).type("String"), + fieldWithPath("name").description(taskFieldDescriptionsMap.get("name")), + fieldWithPath("creator").description(taskFieldDescriptionsMap.get("creator")), + fieldWithPath("description").description(taskFieldDescriptionsMap.get("description")), + fieldWithPath("note") + .description(taskFieldDescriptionsMap.get("note")) + .description("Some custom Note"), + fieldWithPath("priority").description(taskFieldDescriptionsMap.get("priority")), + fieldWithPath("state").description(taskFieldDescriptionsMap.get("state")), + subsectionWithPath("classificationSummaryResource") + .description(taskFieldDescriptionsMap.get("classificationSummaryResource")), + subsectionWithPath("workbasketSummaryResource") + .description(taskFieldDescriptionsMap.get("workbasketSummaryResource")), + fieldWithPath("businessProcessId") + .description(taskFieldDescriptionsMap.get("businessProcessId")), + fieldWithPath("parentBusinessProcessId") + .description(taskFieldDescriptionsMap.get("parentBusinessProcessId")), + fieldWithPath("owner").description(taskFieldDescriptionsMap.get("owner")).type("String"), + fieldWithPath("primaryObjRef.id") + .description(taskFieldDescriptionsMap.get("primaryObjRef.id")) + .type("String"), + fieldWithPath("primaryObjRef.company") + .description(taskFieldDescriptionsMap.get("primaryObjRef.company")), + fieldWithPath("primaryObjRef.system") + .description(taskFieldDescriptionsMap.get("primaryObjRef.system")), + fieldWithPath("primaryObjRef.systemInstance") + .description(taskFieldDescriptionsMap.get("primaryObjRef.systemInstance")), + fieldWithPath("primaryObjRef.type") + .description(taskFieldDescriptionsMap.get("primaryObjRef.type")), + fieldWithPath("primaryObjRef.value") + .description(taskFieldDescriptionsMap.get("primaryObjRef.value")), + fieldWithPath("read").description(taskFieldDescriptionsMap.get("read")), + fieldWithPath("transferred").description(taskFieldDescriptionsMap.get("transferred")), + fieldWithPath("customAttributes") + .description(taskFieldDescriptionsMap.get("customAttributes")), + fieldWithPath("callbackInfo").description(taskFieldDescriptionsMap.get("callbackInfo")), + fieldWithPath("attachments").description(taskFieldDescriptionsMap.get("attachments")), + fieldWithPath("custom1") + .description(taskFieldDescriptionsMap.get("custom1")) + .type("String"), + fieldWithPath("custom2") + .description(taskFieldDescriptionsMap.get("custom2")) + .type("String"), + fieldWithPath("custom3") + .description(taskFieldDescriptionsMap.get("custom3")) + .type("String"), + fieldWithPath("custom4") + .description(taskFieldDescriptionsMap.get("custom4")) + .type("String"), + fieldWithPath("custom5") + .description(taskFieldDescriptionsMap.get("custom5")) + .type("String"), + fieldWithPath("custom6") + .description(taskFieldDescriptionsMap.get("custom6")) + .type("String"), + fieldWithPath("custom7") + .description(taskFieldDescriptionsMap.get("custom7")) + .type("String"), + fieldWithPath("custom8") + .description(taskFieldDescriptionsMap.get("custom8")) + .type("String"), + fieldWithPath("custom9") + .description(taskFieldDescriptionsMap.get("custom9")) + .type("String"), + fieldWithPath("custom10") + .description(taskFieldDescriptionsMap.get("custom10")) + .type("String"), + fieldWithPath("custom11") + .description(taskFieldDescriptionsMap.get("custom11")) + .type("String"), + fieldWithPath("custom12") + .description(taskFieldDescriptionsMap.get("custom12")) + .type("String"), + fieldWithPath("custom13") + .description(taskFieldDescriptionsMap.get("custom13")) + .type("String"), + fieldWithPath("custom14") + .description(taskFieldDescriptionsMap.get("custom14")) + .type("String"), + fieldWithPath("custom15") + .description(taskFieldDescriptionsMap.get("custom15")) + .type("String"), + fieldWithPath("custom16") + .description(taskFieldDescriptionsMap.get("custom16")) + .type("String"), + fieldWithPath("_links.self.href").ignored() }; - taskSubsetFieldDescriptors = new FieldDescriptor[] { - - fieldWithPath("taskId").description(taskFieldDescriptionsMap.get("taskId")), - fieldWithPath("externalId").description(taskFieldDescriptionsMap.get("externalId")), - fieldWithPath("created").description(taskFieldDescriptionsMap.get("created")), - fieldWithPath("claimed").description(taskFieldDescriptionsMap.get("claimed")), - fieldWithPath("completed").description(taskFieldDescriptionsMap.get("completed")).type("String"), - fieldWithPath("modified").description(taskFieldDescriptionsMap.get("modified")).type("String"), - fieldWithPath("planned").description(taskFieldDescriptionsMap.get("planned")).type("String"), - fieldWithPath("due").description(taskFieldDescriptionsMap.get("due")).type("String"), - fieldWithPath("name").description(taskFieldDescriptionsMap.get("name")), - fieldWithPath("creator").description(taskFieldDescriptionsMap.get("creator")), - fieldWithPath("description").ignored(), - fieldWithPath("note").description(taskFieldDescriptionsMap.get("note")).description("Some custom Note"), - fieldWithPath("priority").description(taskFieldDescriptionsMap.get("priority")), - fieldWithPath("state").description(taskFieldDescriptionsMap.get("state")), - subsectionWithPath("classificationSummaryResource") - .description(taskFieldDescriptionsMap.get("classificationSummaryResource")), - subsectionWithPath("workbasketSummaryResource") - .description(taskFieldDescriptionsMap.get("workbasketSummaryResource")), - fieldWithPath("businessProcessId").description(taskFieldDescriptionsMap.get("businessProcessId")), - fieldWithPath("parentBusinessProcessId") - .description(taskFieldDescriptionsMap.get("parentBusinessProcessId")), - fieldWithPath("owner").description(taskFieldDescriptionsMap.get("owner")), - fieldWithPath("primaryObjRef.id").description(taskFieldDescriptionsMap.get("primaryObjRef.id")) - .type("String"), - fieldWithPath("primaryObjRef.company").description(taskFieldDescriptionsMap.get("primaryObjRef.company")), - fieldWithPath("primaryObjRef.system").description(taskFieldDescriptionsMap.get("primaryObjRef.system")), - fieldWithPath("primaryObjRef.systemInstance") - .description(taskFieldDescriptionsMap.get("primaryObjRef.systemInstance")), - fieldWithPath("primaryObjRef.type").description(taskFieldDescriptionsMap.get("primaryObjRef.type")), - fieldWithPath("primaryObjRef.value").description(taskFieldDescriptionsMap.get("primaryObjRef.value")), - fieldWithPath("read").description(taskFieldDescriptionsMap.get("read")), - fieldWithPath("transferred").description(taskFieldDescriptionsMap.get("transferred")), - fieldWithPath("customAttributes").ignored(), - fieldWithPath("callbackInfo").ignored(), - fieldWithPath("attachments").description(taskFieldDescriptionsMap.get("attachments")), - fieldWithPath("custom1").description(taskFieldDescriptionsMap.get("custom1")), - fieldWithPath("custom2").description(taskFieldDescriptionsMap.get("custom2")), - fieldWithPath("custom3").description(taskFieldDescriptionsMap.get("custom3")), - fieldWithPath("custom4").description(taskFieldDescriptionsMap.get("custom4")), - fieldWithPath("custom5").description(taskFieldDescriptionsMap.get("custom5")), - fieldWithPath("custom6").description(taskFieldDescriptionsMap.get("custom6")), - fieldWithPath("custom7").description(taskFieldDescriptionsMap.get("custom7")), - fieldWithPath("custom8").description(taskFieldDescriptionsMap.get("custom8")), - fieldWithPath("custom9").description(taskFieldDescriptionsMap.get("custom9")), - fieldWithPath("custom10").description(taskFieldDescriptionsMap.get("custom10")), - fieldWithPath("custom11").description(taskFieldDescriptionsMap.get("custom11")), - fieldWithPath("custom12").description(taskFieldDescriptionsMap.get("custom12")), - fieldWithPath("custom13").description(taskFieldDescriptionsMap.get("custom13")), - fieldWithPath("custom14").description(taskFieldDescriptionsMap.get("custom14")), - fieldWithPath("custom15").description(taskFieldDescriptionsMap.get("custom15")), - fieldWithPath("custom16").description(taskFieldDescriptionsMap.get("custom16")), - fieldWithPath("_links.self.href").ignored() + taskSubsetFieldDescriptors = + new FieldDescriptor[] { + fieldWithPath("taskId").description(taskFieldDescriptionsMap.get("taskId")), + fieldWithPath("externalId").description(taskFieldDescriptionsMap.get("externalId")), + fieldWithPath("created").description(taskFieldDescriptionsMap.get("created")), + fieldWithPath("claimed").description(taskFieldDescriptionsMap.get("claimed")), + fieldWithPath("completed") + .description(taskFieldDescriptionsMap.get("completed")) + .type("String"), + fieldWithPath("modified") + .description(taskFieldDescriptionsMap.get("modified")) + .type("String"), + fieldWithPath("planned") + .description(taskFieldDescriptionsMap.get("planned")) + .type("String"), + fieldWithPath("due").description(taskFieldDescriptionsMap.get("due")).type("String"), + fieldWithPath("name").description(taskFieldDescriptionsMap.get("name")), + fieldWithPath("creator").description(taskFieldDescriptionsMap.get("creator")), + fieldWithPath("description").ignored(), + fieldWithPath("note") + .description(taskFieldDescriptionsMap.get("note")) + .description("Some custom Note"), + fieldWithPath("priority").description(taskFieldDescriptionsMap.get("priority")), + fieldWithPath("state").description(taskFieldDescriptionsMap.get("state")), + subsectionWithPath("classificationSummaryResource") + .description(taskFieldDescriptionsMap.get("classificationSummaryResource")), + subsectionWithPath("workbasketSummaryResource") + .description(taskFieldDescriptionsMap.get("workbasketSummaryResource")), + fieldWithPath("businessProcessId") + .description(taskFieldDescriptionsMap.get("businessProcessId")), + fieldWithPath("parentBusinessProcessId") + .description(taskFieldDescriptionsMap.get("parentBusinessProcessId")), + fieldWithPath("owner").description(taskFieldDescriptionsMap.get("owner")), + fieldWithPath("primaryObjRef.id") + .description(taskFieldDescriptionsMap.get("primaryObjRef.id")) + .type("String"), + fieldWithPath("primaryObjRef.company") + .description(taskFieldDescriptionsMap.get("primaryObjRef.company")), + fieldWithPath("primaryObjRef.system") + .description(taskFieldDescriptionsMap.get("primaryObjRef.system")), + fieldWithPath("primaryObjRef.systemInstance") + .description(taskFieldDescriptionsMap.get("primaryObjRef.systemInstance")), + fieldWithPath("primaryObjRef.type") + .description(taskFieldDescriptionsMap.get("primaryObjRef.type")), + fieldWithPath("primaryObjRef.value") + .description(taskFieldDescriptionsMap.get("primaryObjRef.value")), + fieldWithPath("read").description(taskFieldDescriptionsMap.get("read")), + fieldWithPath("transferred").description(taskFieldDescriptionsMap.get("transferred")), + fieldWithPath("customAttributes").ignored(), + fieldWithPath("callbackInfo").ignored(), + fieldWithPath("attachments").description(taskFieldDescriptionsMap.get("attachments")), + fieldWithPath("custom1").description(taskFieldDescriptionsMap.get("custom1")), + fieldWithPath("custom2").description(taskFieldDescriptionsMap.get("custom2")), + fieldWithPath("custom3").description(taskFieldDescriptionsMap.get("custom3")), + fieldWithPath("custom4").description(taskFieldDescriptionsMap.get("custom4")), + fieldWithPath("custom5").description(taskFieldDescriptionsMap.get("custom5")), + fieldWithPath("custom6").description(taskFieldDescriptionsMap.get("custom6")), + fieldWithPath("custom7").description(taskFieldDescriptionsMap.get("custom7")), + fieldWithPath("custom8").description(taskFieldDescriptionsMap.get("custom8")), + fieldWithPath("custom9").description(taskFieldDescriptionsMap.get("custom9")), + fieldWithPath("custom10").description(taskFieldDescriptionsMap.get("custom10")), + fieldWithPath("custom11").description(taskFieldDescriptionsMap.get("custom11")), + fieldWithPath("custom12").description(taskFieldDescriptionsMap.get("custom12")), + fieldWithPath("custom13").description(taskFieldDescriptionsMap.get("custom13")), + fieldWithPath("custom14").description(taskFieldDescriptionsMap.get("custom14")), + fieldWithPath("custom15").description(taskFieldDescriptionsMap.get("custom15")), + fieldWithPath("custom16").description(taskFieldDescriptionsMap.get("custom16")), + fieldWithPath("_links.self.href").ignored() }; - createTaskFieldDescriptors = new FieldDescriptor[] { - - subsectionWithPath("classificationSummaryResource") - .description("The new classificationSummaryResource for the task"), - subsectionWithPath("workbasketSummaryResource") - .description("The new workbasketSummaryResource for the task"), - fieldWithPath("externalId").description(taskFieldDescriptionsMap.get("externalId")) - .type("String") - .optional(), - fieldWithPath("primaryObjRef.company").description(taskFieldDescriptionsMap.get("primaryObjRef.company")), - fieldWithPath("primaryObjRef.system").description(taskFieldDescriptionsMap.get("primaryObjRef.system")), - fieldWithPath("primaryObjRef.systemInstance") - .description(taskFieldDescriptionsMap.get("primaryObjRef.systemInstance")), - fieldWithPath("primaryObjRef.type").description(taskFieldDescriptionsMap.get("primaryObjRef.type")), - fieldWithPath("primaryObjRef.value").description(taskFieldDescriptionsMap.get("primaryObjRef.value")), - fieldWithPath("created").description(taskFieldDescriptionsMap.get("created")).type("String").optional(), - fieldWithPath("claimed").description(taskFieldDescriptionsMap.get("claimed")).type("String").optional(), - fieldWithPath("completed").description(taskFieldDescriptionsMap.get("completed")).type("String").optional(), - fieldWithPath("modified").description(taskFieldDescriptionsMap.get("modified")).type("String").optional(), - fieldWithPath("planned").description(taskFieldDescriptionsMap.get("planned")).type("String").optional(), - fieldWithPath("due").description(taskFieldDescriptionsMap.get("due")).type("String").optional(), - fieldWithPath("name").description(taskFieldDescriptionsMap.get("name")).type("String").optional(), - fieldWithPath("creator").description(taskFieldDescriptionsMap.get("creator")).type("String").optional(), - fieldWithPath("description").description(taskFieldDescriptionsMap.get("description")) - .type("String") - .optional(), - fieldWithPath("note").description(taskFieldDescriptionsMap.get("note")) - .description("Some custom Note") - .type("String") - .optional(), - fieldWithPath("priority").description(taskFieldDescriptionsMap.get("priority")).type("String").optional(), - fieldWithPath("state").description(taskFieldDescriptionsMap.get("state")).type("String").optional(), - fieldWithPath("businessProcessId").description(taskFieldDescriptionsMap.get("businessProcessId")) - .type("String") - .optional(), - fieldWithPath("parentBusinessProcessId") - .description(taskFieldDescriptionsMap.get("parentBusinessProcessId")) - .type("String") - .optional(), - fieldWithPath("owner").description(taskFieldDescriptionsMap.get("owner")).type("String").optional(), - fieldWithPath("primaryObjRef.id").description(taskFieldDescriptionsMap.get("primaryObjRef.id")) - .type("String") - .optional(), - fieldWithPath("customAttributes").description(taskFieldDescriptionsMap.get("customAttributes")) - .type("Object") - .optional(), - fieldWithPath("callbackInfo").description(taskFieldDescriptionsMap.get("callbackInfo")) - .type("Object") - .optional(), - fieldWithPath("attachments").description(taskFieldDescriptionsMap.get("attachments")) - .type("Array") - .optional(), - fieldWithPath("custom1").description(taskFieldDescriptionsMap.get("custom1")).type("String").optional(), - fieldWithPath("custom2").description(taskFieldDescriptionsMap.get("custom2")).type("String").optional(), - fieldWithPath("custom3").description(taskFieldDescriptionsMap.get("custom3")).type("String").optional(), - fieldWithPath("custom4").description(taskFieldDescriptionsMap.get("custom4")).type("String").optional(), - fieldWithPath("custom5").description(taskFieldDescriptionsMap.get("custom5")).type("String").optional(), - fieldWithPath("custom6").description(taskFieldDescriptionsMap.get("custom6")).type("String").optional(), - fieldWithPath("custom7").description(taskFieldDescriptionsMap.get("custom7")).type("String").optional(), - fieldWithPath("custom8").description(taskFieldDescriptionsMap.get("custom8")).type("String").optional(), - fieldWithPath("custom9").description(taskFieldDescriptionsMap.get("custom9")).type("String").optional(), - fieldWithPath("custom10").description(taskFieldDescriptionsMap.get("custom10")).type("String").optional(), - fieldWithPath("custom11").description(taskFieldDescriptionsMap.get("custom11")).type("String").optional(), - fieldWithPath("custom12").description(taskFieldDescriptionsMap.get("custom12")).type("String").optional(), - fieldWithPath("custom13").description(taskFieldDescriptionsMap.get("custom13")).type("String").optional(), - fieldWithPath("custom14").description(taskFieldDescriptionsMap.get("custom14")).type("String").optional(), - fieldWithPath("custom15").description(taskFieldDescriptionsMap.get("custom15")).type("String").optional(), - fieldWithPath("custom16").description(taskFieldDescriptionsMap.get("custom16")).type("String").optional(), - fieldWithPath("read").description(taskFieldDescriptionsMap.get("read")).type("Boolean").optional(), - fieldWithPath("transferred").description(taskFieldDescriptionsMap.get("transferred")) - .type("Boolean") - .optional() + createTaskFieldDescriptors = + new FieldDescriptor[] { + subsectionWithPath("classificationSummaryResource") + .description("The new classificationSummaryResource for the task"), + subsectionWithPath("workbasketSummaryResource") + .description("The new workbasketSummaryResource for the task"), + fieldWithPath("externalId") + .description(taskFieldDescriptionsMap.get("externalId")) + .type("String") + .optional(), + fieldWithPath("primaryObjRef.company") + .description(taskFieldDescriptionsMap.get("primaryObjRef.company")), + fieldWithPath("primaryObjRef.system") + .description(taskFieldDescriptionsMap.get("primaryObjRef.system")), + fieldWithPath("primaryObjRef.systemInstance") + .description(taskFieldDescriptionsMap.get("primaryObjRef.systemInstance")), + fieldWithPath("primaryObjRef.type") + .description(taskFieldDescriptionsMap.get("primaryObjRef.type")), + fieldWithPath("primaryObjRef.value") + .description(taskFieldDescriptionsMap.get("primaryObjRef.value")), + fieldWithPath("created") + .description(taskFieldDescriptionsMap.get("created")) + .type("String") + .optional(), + fieldWithPath("claimed") + .description(taskFieldDescriptionsMap.get("claimed")) + .type("String") + .optional(), + fieldWithPath("completed") + .description(taskFieldDescriptionsMap.get("completed")) + .type("String") + .optional(), + fieldWithPath("modified") + .description(taskFieldDescriptionsMap.get("modified")) + .type("String") + .optional(), + fieldWithPath("planned") + .description(taskFieldDescriptionsMap.get("planned")) + .type("String") + .optional(), + fieldWithPath("due") + .description(taskFieldDescriptionsMap.get("due")) + .type("String") + .optional(), + fieldWithPath("name") + .description(taskFieldDescriptionsMap.get("name")) + .type("String") + .optional(), + fieldWithPath("creator") + .description(taskFieldDescriptionsMap.get("creator")) + .type("String") + .optional(), + fieldWithPath("description") + .description(taskFieldDescriptionsMap.get("description")) + .type("String") + .optional(), + fieldWithPath("note") + .description(taskFieldDescriptionsMap.get("note")) + .description("Some custom Note") + .type("String") + .optional(), + fieldWithPath("priority") + .description(taskFieldDescriptionsMap.get("priority")) + .type("String") + .optional(), + fieldWithPath("state") + .description(taskFieldDescriptionsMap.get("state")) + .type("String") + .optional(), + fieldWithPath("businessProcessId") + .description(taskFieldDescriptionsMap.get("businessProcessId")) + .type("String") + .optional(), + fieldWithPath("parentBusinessProcessId") + .description(taskFieldDescriptionsMap.get("parentBusinessProcessId")) + .type("String") + .optional(), + fieldWithPath("owner") + .description(taskFieldDescriptionsMap.get("owner")) + .type("String") + .optional(), + fieldWithPath("primaryObjRef.id") + .description(taskFieldDescriptionsMap.get("primaryObjRef.id")) + .type("String") + .optional(), + fieldWithPath("customAttributes") + .description(taskFieldDescriptionsMap.get("customAttributes")) + .type("Object") + .optional(), + fieldWithPath("callbackInfo") + .description(taskFieldDescriptionsMap.get("callbackInfo")) + .type("Object") + .optional(), + fieldWithPath("attachments") + .description(taskFieldDescriptionsMap.get("attachments")) + .type("Array") + .optional(), + fieldWithPath("custom1") + .description(taskFieldDescriptionsMap.get("custom1")) + .type("String") + .optional(), + fieldWithPath("custom2") + .description(taskFieldDescriptionsMap.get("custom2")) + .type("String") + .optional(), + fieldWithPath("custom3") + .description(taskFieldDescriptionsMap.get("custom3")) + .type("String") + .optional(), + fieldWithPath("custom4") + .description(taskFieldDescriptionsMap.get("custom4")) + .type("String") + .optional(), + fieldWithPath("custom5") + .description(taskFieldDescriptionsMap.get("custom5")) + .type("String") + .optional(), + fieldWithPath("custom6") + .description(taskFieldDescriptionsMap.get("custom6")) + .type("String") + .optional(), + fieldWithPath("custom7") + .description(taskFieldDescriptionsMap.get("custom7")) + .type("String") + .optional(), + fieldWithPath("custom8") + .description(taskFieldDescriptionsMap.get("custom8")) + .type("String") + .optional(), + fieldWithPath("custom9") + .description(taskFieldDescriptionsMap.get("custom9")) + .type("String") + .optional(), + fieldWithPath("custom10") + .description(taskFieldDescriptionsMap.get("custom10")) + .type("String") + .optional(), + fieldWithPath("custom11") + .description(taskFieldDescriptionsMap.get("custom11")) + .type("String") + .optional(), + fieldWithPath("custom12") + .description(taskFieldDescriptionsMap.get("custom12")) + .type("String") + .optional(), + fieldWithPath("custom13") + .description(taskFieldDescriptionsMap.get("custom13")) + .type("String") + .optional(), + fieldWithPath("custom14") + .description(taskFieldDescriptionsMap.get("custom14")) + .type("String") + .optional(), + fieldWithPath("custom15") + .description(taskFieldDescriptionsMap.get("custom15")) + .type("String") + .optional(), + fieldWithPath("custom16") + .description(taskFieldDescriptionsMap.get("custom16")) + .type("String") + .optional(), + fieldWithPath("read") + .description(taskFieldDescriptionsMap.get("read")) + .type("Boolean") + .optional(), + fieldWithPath("transferred") + .description(taskFieldDescriptionsMap.get("transferred")) + .type("Boolean") + .optional() }; + } + + @Test + void getAllTasksDocTest() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get( + restHelper.toUrl(Mapping.URL_TASKS) + "?por.type=VNR&por.value=22334455") + .accept("application/hal+json") + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "GetAllTasksDocTest", responseFields(allTasksFieldDescriptors))); + } + + @Test + void getSpecificTaskDocTest() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get( + restHelper.toUrl( + Mapping.URL_TASKS_ID, "TKI:100000000000000000000000000000000000")) + .accept("application/hal+json") + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "GetSpecificTaskDocTest", responseFields(taskFieldDescriptors))); + } + + @Test + void taskSubSetDocTest() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get( + restHelper.toUrl( + Mapping.URL_TASKS_ID, "TKI:100000000000000000000000000000000000")) + .accept("application/hal+json") + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "TaskSubset", responseFields(taskSubsetFieldDescriptors))); + } + + @Test + void updateTaskDocTest() throws Exception { + URL url = + new URL(restHelper.toUrl(Mapping.URL_TASKS_ID, "TKI:100000000000000000000000000000000000")); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("GET"); + con.setRequestProperty("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x"); + assertEquals(200, con.getResponseCode()); + + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + StringBuilder content = new StringBuilder(); + while ((inputLine = in.readLine()) != null) { + content.append(inputLine); } + in.close(); + con.disconnect(); + String originalTask = content.toString(); - @Test - void getAllTasksDocTest() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders - .get(restHelper.toUrl(Mapping.URL_TASKS) + "?por.type=VNR&por.value=22334455") - .accept("application/hal+json") - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("GetAllTasksDocTest", - responseFields(allTasksFieldDescriptors))); - } - - @Test - void getSpecificTaskDocTest() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders - .get(restHelper.toUrl(Mapping.URL_TASKS_ID, "TKI:100000000000000000000000000000000000")) - .accept("application/hal+json") - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("GetSpecificTaskDocTest", - responseFields(taskFieldDescriptors))); - } - - @Test - void taskSubSetDocTest() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders - .get(restHelper.toUrl(Mapping.URL_TASKS_ID, "TKI:100000000000000000000000000000000000")) - .accept("application/hal+json") - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("TaskSubset", - responseFields(taskSubsetFieldDescriptors))); - } - - @Test - void updateTaskDocTest() throws Exception { - URL url = new URL(restHelper.toUrl(Mapping.URL_TASKS_ID, "TKI:100000000000000000000000000000000000")); - HttpURLConnection con = (HttpURLConnection) url.openConnection(); - con.setRequestMethod("GET"); - con.setRequestProperty("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x"); - assertEquals(200, con.getResponseCode()); - - BufferedReader in = new BufferedReader( - new InputStreamReader(con.getInputStream())); - String inputLine; - StringBuilder content = new StringBuilder(); - while ((inputLine = in.readLine()) != null) { - content.append(inputLine); - } - in.close(); - con.disconnect(); - String originalTask = content.toString(); - - this.mockMvc.perform(RestDocumentationRequestBuilders - .put(restHelper.toUrl(Mapping.URL_TASKS_ID, "TKI:100000000000000000000000000000000000")) - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x") - .contentType("application/json") - .content(originalTask)) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("UpdateTaskDocTest", + this.mockMvc + .perform( + RestDocumentationRequestBuilders.put( + restHelper.toUrl( + Mapping.URL_TASKS_ID, "TKI:100000000000000000000000000000000000")) + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x") + .contentType("application/json") + .content(originalTask)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "UpdateTaskDocTest", requestFields(taskFieldDescriptors), responseFields(taskFieldDescriptors))); - } + } - @Test - void createAndDeleteTaskDocTest() throws Exception { + @Test + void createAndDeleteTaskDocTest() throws Exception { - MvcResult result = this.mockMvc.perform(RestDocumentationRequestBuilders - .post(restHelper.toUrl(Mapping.URL_TASKS)) - .contentType("application/hal+json") - .content("{\"classificationSummaryResource\":{\"key\":\"L11010\"}," - + "\"workbasketSummaryResource\":{\"workbasketId\":\"WBI:100000000000000000000000000000000004\"}," - + "\"primaryObjRef\":{\"company\":\"MyCompany1\",\"system\":\"MySystem1\",\"systemInstance\":\"MyInstance1\",\"type\":\"MyType1\",\"value\":\"00000001\"}}") - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + MvcResult result = + this.mockMvc + .perform( + RestDocumentationRequestBuilders.post(restHelper.toUrl(Mapping.URL_TASKS)) + .contentType("application/hal+json") + .content( + "{\"classificationSummaryResource\":{\"key\":\"L11010\"}," + + "\"workbasketSummaryResource\":{\"workbasketId\":\"WBI:100000000000000000000000000000000004\"}," + + "\"primaryObjRef\":{\"company\":\"MyCompany1\",\"system\":\"MySystem1\",\"systemInstance\":\"MyInstance1\",\"type\":\"MyType1\",\"value\":\"00000001\"}}") + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) .andExpect(MockMvcResultMatchers.status().isCreated()) - .andDo(MockMvcRestDocumentation.document("CreateTaskDocTest", - requestFields(createTaskFieldDescriptors), - responseFields(taskFieldDescriptors))) + .andDo( + MockMvcRestDocumentation.document( + "CreateTaskDocTest", + requestFields(createTaskFieldDescriptors), + responseFields(taskFieldDescriptors))) .andReturn(); - String content = result.getResponse().getContentAsString(); - String newId = content.substring(content.indexOf("TKI:"), content.indexOf("TKI:") + 40); + String content = result.getResponse().getContentAsString(); + String newId = content.substring(content.indexOf("TKI:"), content.indexOf("TKI:") + 40); - this.mockMvc.perform(RestDocumentationRequestBuilders - .delete(restHelper.toUrl(Mapping.URL_TASKS_ID, newId)) - .header("Authorization", "Basic YWRtaW46YWRtaW4=")) // admin - .andExpect(MockMvcResultMatchers.status().isNoContent()) - .andDo(MockMvcRestDocumentation.document("DeleteTaskDocTest")); - } + this.mockMvc + .perform( + RestDocumentationRequestBuilders.delete(restHelper.toUrl(Mapping.URL_TASKS_ID, newId)) + .header("Authorization", "Basic YWRtaW46YWRtaW4=")) // admin + .andExpect(MockMvcResultMatchers.status().isNoContent()) + .andDo(MockMvcRestDocumentation.document("DeleteTaskDocTest")); + } - @Test - void claimTaskDocTest() throws Exception { + @Test + void claimTaskDocTest() throws Exception { - MvcResult result = this.mockMvc.perform(RestDocumentationRequestBuilders - .post(restHelper.toUrl(Mapping.URL_TASKS)) - .contentType("application/hal+json") - .content("{\"classificationSummaryResource\":{\"key\":\"L11010\"}," - + "\"workbasketSummaryResource\":{\"workbasketId\":\"WBI:100000000000000000000000000000000004\"}," - + "\"primaryObjRef\":{\"company\":\"MyCompany1\",\"system\":\"MySystem1\",\"systemInstance\":\"MyInstance1\",\"type\":\"MyType1\",\"value\":\"00000001\"}}") - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + MvcResult result = + this.mockMvc + .perform( + RestDocumentationRequestBuilders.post(restHelper.toUrl(Mapping.URL_TASKS)) + .contentType("application/hal+json") + .content( + "{\"classificationSummaryResource\":{\"key\":\"L11010\"}," + + "\"workbasketSummaryResource\":{\"workbasketId\":\"WBI:100000000000000000000000000000000004\"}," + + "\"primaryObjRef\":{\"company\":\"MyCompany1\",\"system\":\"MySystem1\",\"systemInstance\":\"MyInstance1\",\"type\":\"MyType1\",\"value\":\"00000001\"}}") + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) .andExpect(MockMvcResultMatchers.status().isCreated()) .andDo(MockMvcRestDocumentation.document("temp")) .andReturn(); - String content = result.getResponse().getContentAsString(); - String newId = content.substring(content.indexOf("TKI:"), content.indexOf("TKI:") + 40); + String content = result.getResponse().getContentAsString(); + String newId = content.substring(content.indexOf("TKI:"), content.indexOf("TKI:") + 40); - this.mockMvc.perform(RestDocumentationRequestBuilders - .post(restHelper.toUrl(Mapping.URL_TASKS_ID_CLAIM, newId)) - .accept("application/hal+json") - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x") - .content("{}")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("ClaimTaskDocTest", - responseFields(taskFieldDescriptors))); + this.mockMvc + .perform( + RestDocumentationRequestBuilders.post( + restHelper.toUrl(Mapping.URL_TASKS_ID_CLAIM, newId)) + .accept("application/hal+json") + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x") + .content("{}")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "ClaimTaskDocTest", responseFields(taskFieldDescriptors))); - this.mockMvc.perform(RestDocumentationRequestBuilders - .delete(restHelper.toUrl(Mapping.URL_TASKS_ID, newId)) - .header("Authorization", "Basic YWRtaW46YWRtaW4=")) // admin - .andExpect(MockMvcResultMatchers.status().isNoContent()) - .andDo(MockMvcRestDocumentation.document("DeleteTaskDocTest")); - } + this.mockMvc + .perform( + RestDocumentationRequestBuilders.delete(restHelper.toUrl(Mapping.URL_TASKS_ID, newId)) + .header("Authorization", "Basic YWRtaW46YWRtaW4=")) // admin + .andExpect(MockMvcResultMatchers.status().isNoContent()) + .andDo(MockMvcRestDocumentation.document("DeleteTaskDocTest")); + } - @Test - void completeTaskDocTest() throws Exception { - MvcResult result = this.mockMvc.perform(RestDocumentationRequestBuilders - .post(restHelper.toUrl(Mapping.URL_TASKS)) - .contentType("application/hal+json") - .content("{\"classificationSummaryResource\":{\"key\":\"L11010\"}," - + "\"workbasketSummaryResource\":{\"workbasketId\":\"WBI:100000000000000000000000000000000004\"}," - + "\"primaryObjRef\":{\"company\":\"MyCompany1\",\"system\":\"MySystem1\",\"systemInstance\":\"MyInstance1\",\"type\":\"MyType1\",\"value\":\"00000001\"}}") - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + @Test + void completeTaskDocTest() throws Exception { + MvcResult result = + this.mockMvc + .perform( + RestDocumentationRequestBuilders.post(restHelper.toUrl(Mapping.URL_TASKS)) + .contentType("application/hal+json") + .content( + "{\"classificationSummaryResource\":{\"key\":\"L11010\"}," + + "\"workbasketSummaryResource\":{\"workbasketId\":\"WBI:100000000000000000000000000000000004\"}," + + "\"primaryObjRef\":{\"company\":\"MyCompany1\",\"system\":\"MySystem1\",\"systemInstance\":\"MyInstance1\",\"type\":\"MyType1\",\"value\":\"00000001\"}}") + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) .andExpect(MockMvcResultMatchers.status().isCreated()) .andDo(MockMvcRestDocumentation.document("temp")) .andReturn(); - String content = result.getResponse().getContentAsString(); - String newId = content.substring(content.indexOf("TKI:"), content.indexOf("TKI:") + 40); + String content = result.getResponse().getContentAsString(); + String newId = content.substring(content.indexOf("TKI:"), content.indexOf("TKI:") + 40); - this.mockMvc.perform(RestDocumentationRequestBuilders - .post(restHelper.toUrl(Mapping.URL_TASKS_ID_COMPLETE, newId)) - .accept("application/hal+json") - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x") - .content("{}")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("CompleteTaskDocTest", - responseFields(taskFieldDescriptors))); + this.mockMvc + .perform( + RestDocumentationRequestBuilders.post( + restHelper.toUrl(Mapping.URL_TASKS_ID_COMPLETE, newId)) + .accept("application/hal+json") + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x") + .content("{}")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "CompleteTaskDocTest", responseFields(taskFieldDescriptors))); - this.mockMvc.perform(RestDocumentationRequestBuilders - .delete(restHelper.toUrl(Mapping.URL_TASKS_ID, newId)) - .header("Authorization", "Basic YWRtaW46YWRtaW4=")) // admin - .andExpect(MockMvcResultMatchers.status().isNoContent()) - .andDo(MockMvcRestDocumentation.document("DeleteTaskDocTest")); - } + this.mockMvc + .perform( + RestDocumentationRequestBuilders.delete(restHelper.toUrl(Mapping.URL_TASKS_ID, newId)) + .header("Authorization", "Basic YWRtaW46YWRtaW4=")) // admin + .andExpect(MockMvcResultMatchers.status().isNoContent()) + .andDo(MockMvcRestDocumentation.document("DeleteTaskDocTest")); + } - @Test - void transferTaskDocTest() throws Exception { - MvcResult result = this.mockMvc.perform(RestDocumentationRequestBuilders - .post(restHelper.toUrl(Mapping.URL_TASKS)) - .contentType("application/hal+json") - .content("{\"classificationSummaryResource\":{\"key\":\"L11010\"}," - + "\"workbasketSummaryResource\":{\"workbasketId\":\"WBI:100000000000000000000000000000000004\"}," - + "\"primaryObjRef\":{\"company\":\"MyCompany1\",\"system\":\"MySystem1\",\"systemInstance\":\"MyInstance1\",\"type\":\"MyType1\",\"value\":\"00000001\"}}") - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + @Test + void transferTaskDocTest() throws Exception { + MvcResult result = + this.mockMvc + .perform( + RestDocumentationRequestBuilders.post(restHelper.toUrl(Mapping.URL_TASKS)) + .contentType("application/hal+json") + .content( + "{\"classificationSummaryResource\":{\"key\":\"L11010\"}," + + "\"workbasketSummaryResource\":{\"workbasketId\":\"WBI:100000000000000000000000000000000004\"}," + + "\"primaryObjRef\":{\"company\":\"MyCompany1\",\"system\":\"MySystem1\",\"systemInstance\":\"MyInstance1\",\"type\":\"MyType1\",\"value\":\"00000001\"}}") + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) .andExpect(MockMvcResultMatchers.status().isCreated()) - .andDo(MockMvcRestDocumentation.document("TransferTaskDocTest", - responseFields(taskFieldDescriptors))) + .andDo( + MockMvcRestDocumentation.document( + "TransferTaskDocTest", responseFields(taskFieldDescriptors))) .andReturn(); - String content = result.getResponse().getContentAsString(); - String newId = content.substring(content.indexOf("TKI:"), content.indexOf("TKI:") + 40); + String content = result.getResponse().getContentAsString(); + String newId = content.substring(content.indexOf("TKI:"), content.indexOf("TKI:") + 40); - this.mockMvc.perform(RestDocumentationRequestBuilders - .post(restHelper.toUrl(Mapping.URL_TASKS_ID_TRANSFER_WORKBASKETID, newId, - "WBI:100000000000000000000000000000000001")) - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("TransferTaskDocTest", - responseFields(taskFieldDescriptors))); + this.mockMvc + .perform( + RestDocumentationRequestBuilders.post( + restHelper.toUrl( + Mapping.URL_TASKS_ID_TRANSFER_WORKBASKETID, + newId, + "WBI:100000000000000000000000000000000001")) + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "TransferTaskDocTest", responseFields(taskFieldDescriptors))); - this.mockMvc.perform(RestDocumentationRequestBuilders - .delete(restHelper.toUrl(Mapping.URL_TASKS_ID, newId)) - .header("Authorization", "Basic YWRtaW46YWRtaW4=")) // admin - .andExpect(MockMvcResultMatchers.status().isNoContent()); - } + this.mockMvc + .perform( + RestDocumentationRequestBuilders.delete(restHelper.toUrl(Mapping.URL_TASKS_ID, newId)) + .header("Authorization", "Basic YWRtaW46YWRtaW4=")) // admin + .andExpect(MockMvcResultMatchers.status().isNoContent()); + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/TaskanaEngineControllerRestDocumentation.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/TaskanaEngineControllerRestDocumentation.java index 20eb7a725..8fe9cd191 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/TaskanaEngineControllerRestDocumentation.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/TaskanaEngineControllerRestDocumentation.java @@ -12,90 +12,104 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import pro.taskana.rest.Mapping; -/** - * Generate REST Docu for the TaskanaEngineController. - * - */ +/** Generate REST Docu for the TaskanaEngineController. */ class TaskanaEngineControllerRestDocumentation extends BaseRestDocumentation { - private FieldDescriptor[] allDomainsFieldDescriptors; - private FieldDescriptor[] allClassificationCategoriesFieldDescriptors; - private FieldDescriptor[] allClassificationTypesFieldDescriptors; - private FieldDescriptor[] currentUserInfoFieldDescriptors; + private FieldDescriptor[] allDomainsFieldDescriptors; + private FieldDescriptor[] allClassificationCategoriesFieldDescriptors; + private FieldDescriptor[] allClassificationTypesFieldDescriptors; + private FieldDescriptor[] currentUserInfoFieldDescriptors; - @BeforeEach - void setUp() { + @BeforeEach + void setUp() { - allDomainsFieldDescriptors = new FieldDescriptor[] { - fieldWithPath("[]").description("An array with the domain-names as strings") + allDomainsFieldDescriptors = + new FieldDescriptor[] { + fieldWithPath("[]").description("An array with the domain-names as strings") }; - allClassificationCategoriesFieldDescriptors = new FieldDescriptor[] { - fieldWithPath("[]").description("An array with the classification-categories as strings") + allClassificationCategoriesFieldDescriptors = + new FieldDescriptor[] { + fieldWithPath("[]").description("An array with the classification-categories as strings") }; - allClassificationTypesFieldDescriptors = new FieldDescriptor[] { - fieldWithPath("[]").description("An array with the classification-types as strings") + allClassificationTypesFieldDescriptors = + new FieldDescriptor[] { + fieldWithPath("[]").description("An array with the classification-types as strings") }; - currentUserInfoFieldDescriptors = new FieldDescriptor[] { - fieldWithPath("userId").description("Id of the current user"), - fieldWithPath("groupIds").description("An array with the groups the current user is part of as strings"), - fieldWithPath("roles").description("An array with the roles the current user is granted") + currentUserInfoFieldDescriptors = + new FieldDescriptor[] { + fieldWithPath("userId").description("Id of the current user"), + fieldWithPath("groupIds") + .description("An array with the groups the current user is part of as strings"), + fieldWithPath("roles").description("An array with the roles the current user is granted") }; - } + } - @Test - void getAllDomainsDocTest() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders - .get(restHelper.toUrl(Mapping.URL_DOMAIN)) - .accept("application/json") - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("GetAllDomainsDocTest", - responseFields(allDomainsFieldDescriptors))); - } + @Test + void getAllDomainsDocTest() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get(restHelper.toUrl(Mapping.URL_DOMAIN)) + .accept("application/json") + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "GetAllDomainsDocTest", responseFields(allDomainsFieldDescriptors))); + } - @Test - void getAllClassificationCategoriesDocTest() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders - .get(restHelper.toUrl(Mapping.URL_CLASSIFICATIONCATEGORIES)) - .accept("application/json") - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("GetAllClassificationCategoriesDocTest", + @Test + void getAllClassificationCategoriesDocTest() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get( + restHelper.toUrl(Mapping.URL_CLASSIFICATIONCATEGORIES)) + .accept("application/json") + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "GetAllClassificationCategoriesDocTest", responseFields(allClassificationCategoriesFieldDescriptors))); - } + } - @Test - void getAllClassificationTypesDocTest() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders - .get(restHelper.toUrl(Mapping.URL_CLASSIFICATIONTYPES)) - .accept("application/json") - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("GetAllClassificationTypesDocTest", + @Test + void getAllClassificationTypesDocTest() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get(restHelper.toUrl(Mapping.URL_CLASSIFICATIONTYPES)) + .accept("application/json") + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "GetAllClassificationTypesDocTest", responseFields(allClassificationTypesFieldDescriptors))); - } + } - @Test - void getCurrentUserInfo() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders - .get(restHelper.toUrl(Mapping.URL_CURRENTUSER)) - .accept("application/json") - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("GetCurrentUserInfoDocTest", - responseFields(currentUserInfoFieldDescriptors))); - } + @Test + void getCurrentUserInfo() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get(restHelper.toUrl(Mapping.URL_CURRENTUSER)) + .accept("application/json") + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "GetCurrentUserInfoDocTest", responseFields(currentUserInfoFieldDescriptors))); + } - @Test - void getHistoryProviderIsEnabled() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders - .get(restHelper.toUrl(Mapping.URL_HISTORYENABLED)) - .accept("application/json") - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("GetHistoryProviderIsEnabled")); - } + @Test + void getHistoryProviderIsEnabled() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get(restHelper.toUrl(Mapping.URL_HISTORYENABLED)) + .accept("application/json") + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo(MockMvcRestDocumentation.document("GetHistoryProviderIsEnabled")); + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/WorkbasketAccessItemControllerRestDocumentation.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/WorkbasketAccessItemControllerRestDocumentation.java index a19b4ffec..697a3aef4 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/WorkbasketAccessItemControllerRestDocumentation.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/WorkbasketAccessItemControllerRestDocumentation.java @@ -4,7 +4,6 @@ import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWit import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; import java.util.HashMap; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation; @@ -15,119 +14,125 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import pro.taskana.rest.Mapping; -/** - * Generate REST Docu for the WorkbasketAccessItemController. - */ +/** Generate REST Docu for the WorkbasketAccessItemController. */ class WorkbasketAccessItemControllerRestDocumentation extends BaseRestDocumentation { - private HashMap accessItemFieldDescriptionsMap = new HashMap(); - private FieldDescriptor[] accessItemFieldDescriptors; + private HashMap accessItemFieldDescriptionsMap = new HashMap(); + private FieldDescriptor[] accessItemFieldDescriptors; - @BeforeEach - void setUp() { + @BeforeEach + void setUp() { - accessItemFieldDescriptionsMap.put("accessItems.accessItemId", "Unique ID"); - accessItemFieldDescriptionsMap.put("accessItems.workbasketId", "The workbasket id"); - accessItemFieldDescriptionsMap.put("accessItems.accessId", - "The access id. This could be either a userid or a full qualified group id"); - accessItemFieldDescriptionsMap.put("accessItems.accessName", "The name"); - accessItemFieldDescriptionsMap.put("accessItems.workbasketKey", "The workbasket key"); - accessItemFieldDescriptionsMap.put("accessItems.permRead", - "The permission to read the information about the workbasket"); - accessItemFieldDescriptionsMap.put("accessItems.permOpen", - "The permission to view the content (the tasks) of a workbasket"); - accessItemFieldDescriptionsMap.put("accessItems.permAppend", - "The permission to add tasks to the workbasket (required for creation and tranferring of tasks)"); - accessItemFieldDescriptionsMap.put("accessItems.permTransfer", - "The permission to transfer tasks (out of the current workbasket)"); - accessItemFieldDescriptionsMap.put("accessItems.permDistribute", - "The permission to distribute tasks from the workbasket"); - accessItemFieldDescriptionsMap.put("accessItems.permCustom1", ""); - accessItemFieldDescriptionsMap.put("accessItems.permCustom2", ""); - accessItemFieldDescriptionsMap.put("accessItems.permCustom3", ""); - accessItemFieldDescriptionsMap.put("accessItems.permCustom4", ""); - accessItemFieldDescriptionsMap.put("accessItems.permCustom5", ""); - accessItemFieldDescriptionsMap.put("accessItems.permCustom6", ""); - accessItemFieldDescriptionsMap.put("accessItems.permCustom7", ""); - accessItemFieldDescriptionsMap.put("accessItems.permCustom8", ""); - accessItemFieldDescriptionsMap.put("accessItems.permCustom9", ""); - accessItemFieldDescriptionsMap.put("accessItems.permCustom10", ""); - accessItemFieldDescriptionsMap.put("accessItems.permCustom11", ""); - accessItemFieldDescriptionsMap.put("accessItems.permCustom12", ""); - accessItemFieldDescriptionsMap.put("_links.self.href", "Link to self"); - accessItemFieldDescriptionsMap.put("page", "Number of page"); + accessItemFieldDescriptionsMap.put("accessItems.accessItemId", "Unique ID"); + accessItemFieldDescriptionsMap.put("accessItems.workbasketId", "The workbasket id"); + accessItemFieldDescriptionsMap.put( + "accessItems.accessId", + "The access id. This could be either a userid or a full qualified group id"); + accessItemFieldDescriptionsMap.put("accessItems.accessName", "The name"); + accessItemFieldDescriptionsMap.put("accessItems.workbasketKey", "The workbasket key"); + accessItemFieldDescriptionsMap.put( + "accessItems.permRead", "The permission to read the information about the workbasket"); + accessItemFieldDescriptionsMap.put( + "accessItems.permOpen", "The permission to view the content (the tasks) of a workbasket"); + accessItemFieldDescriptionsMap.put( + "accessItems.permAppend", + "The permission to add tasks to the workbasket (required for creation and tranferring of tasks)"); + accessItemFieldDescriptionsMap.put( + "accessItems.permTransfer", + "The permission to transfer tasks (out of the current workbasket)"); + accessItemFieldDescriptionsMap.put( + "accessItems.permDistribute", "The permission to distribute tasks from the workbasket"); + accessItemFieldDescriptionsMap.put("accessItems.permCustom1", ""); + accessItemFieldDescriptionsMap.put("accessItems.permCustom2", ""); + accessItemFieldDescriptionsMap.put("accessItems.permCustom3", ""); + accessItemFieldDescriptionsMap.put("accessItems.permCustom4", ""); + accessItemFieldDescriptionsMap.put("accessItems.permCustom5", ""); + accessItemFieldDescriptionsMap.put("accessItems.permCustom6", ""); + accessItemFieldDescriptionsMap.put("accessItems.permCustom7", ""); + accessItemFieldDescriptionsMap.put("accessItems.permCustom8", ""); + accessItemFieldDescriptionsMap.put("accessItems.permCustom9", ""); + accessItemFieldDescriptionsMap.put("accessItems.permCustom10", ""); + accessItemFieldDescriptionsMap.put("accessItems.permCustom11", ""); + accessItemFieldDescriptionsMap.put("accessItems.permCustom12", ""); + accessItemFieldDescriptionsMap.put("_links.self.href", "Link to self"); + accessItemFieldDescriptionsMap.put("page", "Number of page"); - accessItemFieldDescriptors = new FieldDescriptor[] { - fieldWithPath("accessItems[].accessItemId") - .description(accessItemFieldDescriptionsMap.get("accessItems.accessItemId")), - fieldWithPath("accessItems[].workbasketId") - .description(accessItemFieldDescriptionsMap.get("accessItems.workbasketId")), - fieldWithPath("accessItems[].accessId") - .description(accessItemFieldDescriptionsMap.get("accessItems.accessId")), - fieldWithPath("accessItems[].accessName") - .description(accessItemFieldDescriptionsMap.get("accessItems.accessName")), - fieldWithPath("accessItems[].workbasketKey") - .description(accessItemFieldDescriptionsMap.get("accessItems.workbasketKey")), - fieldWithPath("accessItems[].permRead") - .description(accessItemFieldDescriptionsMap.get("accessItems.permRead")), - fieldWithPath("accessItems[].permOpen") - .description(accessItemFieldDescriptionsMap.get("accessItems.permOpen")), - fieldWithPath("accessItems[].permAppend") - .description(accessItemFieldDescriptionsMap.get("accessItems.permAppend")), - fieldWithPath("accessItems[].permTransfer") - .description(accessItemFieldDescriptionsMap.get("accessItems.permTransfer")), - fieldWithPath("accessItems[].permDistribute") - .description(accessItemFieldDescriptionsMap.get("accessItems.permDistribute")), - fieldWithPath("accessItems[].permCustom1") - .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom1")), - fieldWithPath("accessItems[].permCustom2") - .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom2")), - fieldWithPath("accessItems[].permCustom3") - .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom3")), - fieldWithPath("accessItems[].permCustom4") - .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom4")), - fieldWithPath("accessItems[].permCustom5") - .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom5")), - fieldWithPath("accessItems[].permCustom6") - .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom6")), - fieldWithPath("accessItems[].permCustom7") - .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom7")), - fieldWithPath("accessItems[].permCustom8") - .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom8")), - fieldWithPath("accessItems[].permCustom9") - .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom9")), - fieldWithPath("accessItems[].permCustom10") - .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom10")), - fieldWithPath("accessItems[].permCustom11") - .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom11")), - fieldWithPath("accessItems[].permCustom12") - .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom12")), - fieldWithPath("_links.self.href").description(accessItemFieldDescriptionsMap.get("_links.self.href")), - fieldWithPath("page").description(accessItemFieldDescriptionsMap.get("page")) + accessItemFieldDescriptors = + new FieldDescriptor[] { + fieldWithPath("accessItems[].accessItemId") + .description(accessItemFieldDescriptionsMap.get("accessItems.accessItemId")), + fieldWithPath("accessItems[].workbasketId") + .description(accessItemFieldDescriptionsMap.get("accessItems.workbasketId")), + fieldWithPath("accessItems[].accessId") + .description(accessItemFieldDescriptionsMap.get("accessItems.accessId")), + fieldWithPath("accessItems[].accessName") + .description(accessItemFieldDescriptionsMap.get("accessItems.accessName")), + fieldWithPath("accessItems[].workbasketKey") + .description(accessItemFieldDescriptionsMap.get("accessItems.workbasketKey")), + fieldWithPath("accessItems[].permRead") + .description(accessItemFieldDescriptionsMap.get("accessItems.permRead")), + fieldWithPath("accessItems[].permOpen") + .description(accessItemFieldDescriptionsMap.get("accessItems.permOpen")), + fieldWithPath("accessItems[].permAppend") + .description(accessItemFieldDescriptionsMap.get("accessItems.permAppend")), + fieldWithPath("accessItems[].permTransfer") + .description(accessItemFieldDescriptionsMap.get("accessItems.permTransfer")), + fieldWithPath("accessItems[].permDistribute") + .description(accessItemFieldDescriptionsMap.get("accessItems.permDistribute")), + fieldWithPath("accessItems[].permCustom1") + .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom1")), + fieldWithPath("accessItems[].permCustom2") + .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom2")), + fieldWithPath("accessItems[].permCustom3") + .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom3")), + fieldWithPath("accessItems[].permCustom4") + .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom4")), + fieldWithPath("accessItems[].permCustom5") + .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom5")), + fieldWithPath("accessItems[].permCustom6") + .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom6")), + fieldWithPath("accessItems[].permCustom7") + .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom7")), + fieldWithPath("accessItems[].permCustom8") + .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom8")), + fieldWithPath("accessItems[].permCustom9") + .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom9")), + fieldWithPath("accessItems[].permCustom10") + .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom10")), + fieldWithPath("accessItems[].permCustom11") + .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom11")), + fieldWithPath("accessItems[].permCustom12") + .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom12")), + fieldWithPath("_links.self.href") + .description(accessItemFieldDescriptionsMap.get("_links.self.href")), + fieldWithPath("page").description(accessItemFieldDescriptionsMap.get("page")) }; - } + } - @Test - void getWorkbasketAccessItemsDocTest() throws Exception { - this.mockMvc - .perform(RestDocumentationRequestBuilders - .get(restHelper.toUrl(Mapping.URL_WORKBASKETACCESSITEMS) - + "?sort-by=workbasket-key&order=asc&access-ids=user_2_2") + @Test + void getWorkbasketAccessItemsDocTest() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get( + restHelper.toUrl(Mapping.URL_WORKBASKETACCESSITEMS) + + "?sort-by=workbasket-key&order=asc&access-ids=user_2_2") .accept("application/hal+json") .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("GetWorkbasketAccessItemsDocTest", - responseFields(accessItemFieldDescriptors))); - } + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "GetWorkbasketAccessItemsDocTest", responseFields(accessItemFieldDescriptors))); + } - @Test - @DirtiesContext - void removeWorkbasketAccessItemsDocTest() throws Exception { - this.mockMvc - .perform(RestDocumentationRequestBuilders - .delete(restHelper.toUrl(Mapping.URL_WORKBASKETACCESSITEMS) + "?access-id=user_2_2") + @Test + @DirtiesContext + void removeWorkbasketAccessItemsDocTest() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.delete( + restHelper.toUrl(Mapping.URL_WORKBASKETACCESSITEMS) + "?access-id=user_2_2") .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isNoContent()) - .andDo(MockMvcRestDocumentation.document("RemoveWorkbasketAccessItemsDocTest")); - } + .andExpect(MockMvcResultMatchers.status().isNoContent()) + .andDo(MockMvcRestDocumentation.document("RemoveWorkbasketAccessItemsDocTest")); + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/WorkbasketControllerRestDocumentation.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/WorkbasketControllerRestDocumentation.java index e8de1315a..ab4bb117a 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/WorkbasketControllerRestDocumentation.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/WorkbasketControllerRestDocumentation.java @@ -11,7 +11,6 @@ import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation; @@ -21,385 +20,471 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import pro.taskana.rest.Mapping; -/** - * Generate REST Documentatioon for the WorkbasketController. - */ +/** Generate REST Documentatioon for the WorkbasketController. */ class WorkbasketControllerRestDocumentation extends BaseRestDocumentation { - // HashMaps to store the field descriptions centrally for multiple uses - private HashMap workbasketFieldDescriptionsMap = new HashMap(); - private HashMap accessItemFieldDescriptionsMap = new HashMap(); + // HashMaps to store the field descriptions centrally for multiple uses + private HashMap workbasketFieldDescriptionsMap = new HashMap(); + private HashMap accessItemFieldDescriptionsMap = new HashMap(); - private FieldDescriptor[] allWorkbasketsFieldDescriptors; - private FieldDescriptor[] workbasketFieldDescriptors; - private FieldDescriptor[] workbasketSubsetFieldDescriptors; - private FieldDescriptor[] allWorkbasketAccessItemsFieldDescriptors; - private FieldDescriptor[] accessItemFieldDescriptors; - private FieldDescriptor[] allDistributionTargetsFieldDescriptors; - private FieldDescriptor[] createWorkbasketFieldDescriptors; + private FieldDescriptor[] allWorkbasketsFieldDescriptors; + private FieldDescriptor[] workbasketFieldDescriptors; + private FieldDescriptor[] workbasketSubsetFieldDescriptors; + private FieldDescriptor[] allWorkbasketAccessItemsFieldDescriptors; + private FieldDescriptor[] accessItemFieldDescriptors; + private FieldDescriptor[] allDistributionTargetsFieldDescriptors; + private FieldDescriptor[] createWorkbasketFieldDescriptors; - @BeforeEach - void setUp() { + @BeforeEach + void setUp() { - workbasketFieldDescriptionsMap.put("workbasketId", "Unique ID"); - workbasketFieldDescriptionsMap.put("key", ""); - workbasketFieldDescriptionsMap.put("name", "The name of the workbasket"); - workbasketFieldDescriptionsMap.put("domain", ""); - workbasketFieldDescriptionsMap.put("type", ""); - workbasketFieldDescriptionsMap.put("description", "The description of the workbasket"); - workbasketFieldDescriptionsMap.put("owner", - "The owner of the workbasket. The owner is responsible for the on-time completion of all tasks in the workbasket."); - workbasketFieldDescriptionsMap.put("orgLevel1", - "The first Org Level (the top one)\nThe Org Level is an association with an org hierarchie level in the organization. The values are used for monitoring and statistical purposes and should reflect the responsibility of the tasks in the workbasket."); - workbasketFieldDescriptionsMap.put("orgLevel2", "The second Org Level"); - workbasketFieldDescriptionsMap.put("orgLevel3", "The third Org Level"); - workbasketFieldDescriptionsMap.put("orgLevel4", "The fourth Org Level (the lowest one)."); - workbasketFieldDescriptionsMap.put("created", "The creation timestamp of the workbasket in the system."); - workbasketFieldDescriptionsMap.put("modified", "Timestamp of the last modification of the workbasket"); - workbasketFieldDescriptionsMap.put("custom1", "A custom property with name \"1\""); - workbasketFieldDescriptionsMap.put("custom2", "A custom property with name \"2\""); - workbasketFieldDescriptionsMap.put("custom3", "A custom property with name \"3\""); - workbasketFieldDescriptionsMap.put("custom4", "A custom property with name \"4\""); - workbasketFieldDescriptionsMap.put("_links.distributionTargets.href", - "The Distribution-Targets of the workbasket"); - workbasketFieldDescriptionsMap.put("_links.removeDistributionTargets.href", - "Link to remove all distribution-targets from the workbasket"); - workbasketFieldDescriptionsMap.put("_links.accessItems.href", "The Access-Items of the workbasket"); - workbasketFieldDescriptionsMap.put("_links.allWorkbaskets.href", "Link to all workbaskets"); + workbasketFieldDescriptionsMap.put("workbasketId", "Unique ID"); + workbasketFieldDescriptionsMap.put("key", ""); + workbasketFieldDescriptionsMap.put("name", "The name of the workbasket"); + workbasketFieldDescriptionsMap.put("domain", ""); + workbasketFieldDescriptionsMap.put("type", ""); + workbasketFieldDescriptionsMap.put("description", "The description of the workbasket"); + workbasketFieldDescriptionsMap.put( + "owner", + "The owner of the workbasket. The owner is responsible for the on-time completion of all tasks in the workbasket."); + workbasketFieldDescriptionsMap.put( + "orgLevel1", + "The first Org Level (the top one)\nThe Org Level is an association with an org hierarchie level in the organization. The values are used for monitoring and statistical purposes and should reflect the responsibility of the tasks in the workbasket."); + workbasketFieldDescriptionsMap.put("orgLevel2", "The second Org Level"); + workbasketFieldDescriptionsMap.put("orgLevel3", "The third Org Level"); + workbasketFieldDescriptionsMap.put("orgLevel4", "The fourth Org Level (the lowest one)."); + workbasketFieldDescriptionsMap.put( + "created", "The creation timestamp of the workbasket in the system."); + workbasketFieldDescriptionsMap.put( + "modified", "Timestamp of the last modification of the workbasket"); + workbasketFieldDescriptionsMap.put("custom1", "A custom property with name \"1\""); + workbasketFieldDescriptionsMap.put("custom2", "A custom property with name \"2\""); + workbasketFieldDescriptionsMap.put("custom3", "A custom property with name \"3\""); + workbasketFieldDescriptionsMap.put("custom4", "A custom property with name \"4\""); + workbasketFieldDescriptionsMap.put( + "_links.distributionTargets.href", "The Distribution-Targets of the workbasket"); + workbasketFieldDescriptionsMap.put( + "_links.removeDistributionTargets.href", + "Link to remove all distribution-targets from the workbasket"); + workbasketFieldDescriptionsMap.put( + "_links.accessItems.href", "The Access-Items of the workbasket"); + workbasketFieldDescriptionsMap.put("_links.allWorkbaskets.href", "Link to all workbaskets"); - accessItemFieldDescriptionsMap.put("accessItems.accessItemId", "Unique ID"); - accessItemFieldDescriptionsMap.put("accessItems.workbasketId", "The workbasket"); - accessItemFieldDescriptionsMap.put("accessItems.workbasketKey", "The workbasket key"); - accessItemFieldDescriptionsMap.put("accessItems.accessId", - "The access id, this ACL entry refers to. This could be either a userid or a full qualified group id (both lower case)"); - accessItemFieldDescriptionsMap.put("accessItems.accessName", ""); - accessItemFieldDescriptionsMap.put("accessItems.permRead", - "The permission to read the information about the workbasket"); - accessItemFieldDescriptionsMap.put("accessItems.permOpen", - "The permission to view the content (the tasks) of a workbasket"); - accessItemFieldDescriptionsMap.put("accessItems.permAppend", - "The permission to add tasks to the workbasket (required for creation and transferring of tasks)"); - accessItemFieldDescriptionsMap.put("accessItems.permTransfer", - "The permission to transfer tasks (out of the current workbasket)"); - accessItemFieldDescriptionsMap.put("accessItems.permDistribute", - "The permission to distribute tasks from the workbasket"); - accessItemFieldDescriptionsMap.put("accessItems.permCustom1", ""); - accessItemFieldDescriptionsMap.put("accessItems.permCustom2", ""); - accessItemFieldDescriptionsMap.put("accessItems.permCustom3", ""); - accessItemFieldDescriptionsMap.put("accessItems.permCustom4", ""); - accessItemFieldDescriptionsMap.put("accessItems.permCustom5", ""); - accessItemFieldDescriptionsMap.put("accessItems.permCustom6", ""); - accessItemFieldDescriptionsMap.put("accessItems.permCustom7", ""); - accessItemFieldDescriptionsMap.put("accessItems.permCustom8", ""); - accessItemFieldDescriptionsMap.put("accessItems.permCustom9", ""); - accessItemFieldDescriptionsMap.put("accessItems.permCustom10", ""); - accessItemFieldDescriptionsMap.put("accessItems.permCustom11", ""); - accessItemFieldDescriptionsMap.put("accessItems.permCustom12", ""); - accessItemFieldDescriptionsMap.put("accessItems._links.workbasket.href", "Link to the workbasket"); + accessItemFieldDescriptionsMap.put("accessItems.accessItemId", "Unique ID"); + accessItemFieldDescriptionsMap.put("accessItems.workbasketId", "The workbasket"); + accessItemFieldDescriptionsMap.put("accessItems.workbasketKey", "The workbasket key"); + accessItemFieldDescriptionsMap.put( + "accessItems.accessId", + "The access id, this ACL entry refers to. This could be either a userid or a full qualified group id (both lower case)"); + accessItemFieldDescriptionsMap.put("accessItems.accessName", ""); + accessItemFieldDescriptionsMap.put( + "accessItems.permRead", "The permission to read the information about the workbasket"); + accessItemFieldDescriptionsMap.put( + "accessItems.permOpen", "The permission to view the content (the tasks) of a workbasket"); + accessItemFieldDescriptionsMap.put( + "accessItems.permAppend", + "The permission to add tasks to the workbasket (required for creation and transferring of tasks)"); + accessItemFieldDescriptionsMap.put( + "accessItems.permTransfer", + "The permission to transfer tasks (out of the current workbasket)"); + accessItemFieldDescriptionsMap.put( + "accessItems.permDistribute", "The permission to distribute tasks from the workbasket"); + accessItemFieldDescriptionsMap.put("accessItems.permCustom1", ""); + accessItemFieldDescriptionsMap.put("accessItems.permCustom2", ""); + accessItemFieldDescriptionsMap.put("accessItems.permCustom3", ""); + accessItemFieldDescriptionsMap.put("accessItems.permCustom4", ""); + accessItemFieldDescriptionsMap.put("accessItems.permCustom5", ""); + accessItemFieldDescriptionsMap.put("accessItems.permCustom6", ""); + accessItemFieldDescriptionsMap.put("accessItems.permCustom7", ""); + accessItemFieldDescriptionsMap.put("accessItems.permCustom8", ""); + accessItemFieldDescriptionsMap.put("accessItems.permCustom9", ""); + accessItemFieldDescriptionsMap.put("accessItems.permCustom10", ""); + accessItemFieldDescriptionsMap.put("accessItems.permCustom11", ""); + accessItemFieldDescriptionsMap.put("accessItems.permCustom12", ""); + accessItemFieldDescriptionsMap.put( + "accessItems._links.workbasket.href", "Link to the workbasket"); - allWorkbasketsFieldDescriptors = new FieldDescriptor[] { - - subsectionWithPath("workbaskets").description( - "An Array of <>"), - fieldWithPath("_links.self.href").ignored(), - fieldWithPath("page").ignored() + allWorkbasketsFieldDescriptors = + new FieldDescriptor[] { + subsectionWithPath("workbaskets") + .description("An Array of <>"), + fieldWithPath("_links.self.href").ignored(), + fieldWithPath("page").ignored() }; - workbasketFieldDescriptors = new FieldDescriptor[] { - - fieldWithPath("workbasketId").description(workbasketFieldDescriptionsMap.get("workbasketId")), - fieldWithPath("key").description(workbasketFieldDescriptionsMap.get("key")), - fieldWithPath("created").description(workbasketFieldDescriptionsMap.get("created")), - fieldWithPath("modified").description(workbasketFieldDescriptionsMap.get("modified")), - fieldWithPath("name").description(workbasketFieldDescriptionsMap.get("name")), - fieldWithPath("description").description(workbasketFieldDescriptionsMap.get("description")), - fieldWithPath("owner").description(workbasketFieldDescriptionsMap.get("owner")), - fieldWithPath("domain").description(workbasketFieldDescriptionsMap.get("domain")), - fieldWithPath("type").description(workbasketFieldDescriptionsMap.get("type")), - fieldWithPath("custom1").description(workbasketFieldDescriptionsMap.get("custom1")), - fieldWithPath("custom2").description(workbasketFieldDescriptionsMap.get("custom2")), - fieldWithPath("custom3").description(workbasketFieldDescriptionsMap.get("custom3")), - fieldWithPath("custom4").description(workbasketFieldDescriptionsMap.get("custom4")), - fieldWithPath("orgLevel1").description(workbasketFieldDescriptionsMap.get("orgLevel1")), - fieldWithPath("orgLevel2").description(workbasketFieldDescriptionsMap.get("orgLevel2")), - fieldWithPath("orgLevel3").description(workbasketFieldDescriptionsMap.get("orgLevel3")), - fieldWithPath("orgLevel4").description(workbasketFieldDescriptionsMap.get("orgLevel4")), - fieldWithPath("_links.distributionTargets.href").description( - workbasketFieldDescriptionsMap.get("_links.distributionTargets.href")), - fieldWithPath("_links.removeDistributionTargets.href").description( - workbasketFieldDescriptionsMap.get("_links.removeDistributionTargets.href")), - fieldWithPath("_links.accessItems.href").description( - workbasketFieldDescriptionsMap.get("_links.accessItems.href")), - fieldWithPath("_links.allWorkbaskets.href").description( - workbasketFieldDescriptionsMap.get("_links.allWorkbaskets.href")), - fieldWithPath("_links.self.href").ignored() + workbasketFieldDescriptors = + new FieldDescriptor[] { + fieldWithPath("workbasketId") + .description(workbasketFieldDescriptionsMap.get("workbasketId")), + fieldWithPath("key").description(workbasketFieldDescriptionsMap.get("key")), + fieldWithPath("created").description(workbasketFieldDescriptionsMap.get("created")), + fieldWithPath("modified").description(workbasketFieldDescriptionsMap.get("modified")), + fieldWithPath("name").description(workbasketFieldDescriptionsMap.get("name")), + fieldWithPath("description") + .description(workbasketFieldDescriptionsMap.get("description")), + fieldWithPath("owner").description(workbasketFieldDescriptionsMap.get("owner")), + fieldWithPath("domain").description(workbasketFieldDescriptionsMap.get("domain")), + fieldWithPath("type").description(workbasketFieldDescriptionsMap.get("type")), + fieldWithPath("custom1").description(workbasketFieldDescriptionsMap.get("custom1")), + fieldWithPath("custom2").description(workbasketFieldDescriptionsMap.get("custom2")), + fieldWithPath("custom3").description(workbasketFieldDescriptionsMap.get("custom3")), + fieldWithPath("custom4").description(workbasketFieldDescriptionsMap.get("custom4")), + fieldWithPath("orgLevel1").description(workbasketFieldDescriptionsMap.get("orgLevel1")), + fieldWithPath("orgLevel2").description(workbasketFieldDescriptionsMap.get("orgLevel2")), + fieldWithPath("orgLevel3").description(workbasketFieldDescriptionsMap.get("orgLevel3")), + fieldWithPath("orgLevel4").description(workbasketFieldDescriptionsMap.get("orgLevel4")), + fieldWithPath("_links.distributionTargets.href") + .description(workbasketFieldDescriptionsMap.get("_links.distributionTargets.href")), + fieldWithPath("_links.removeDistributionTargets.href") + .description( + workbasketFieldDescriptionsMap.get("_links.removeDistributionTargets.href")), + fieldWithPath("_links.accessItems.href") + .description(workbasketFieldDescriptionsMap.get("_links.accessItems.href")), + fieldWithPath("_links.allWorkbaskets.href") + .description(workbasketFieldDescriptionsMap.get("_links.allWorkbaskets.href")), + fieldWithPath("_links.self.href").ignored() }; - workbasketSubsetFieldDescriptors = new FieldDescriptor[] { - - fieldWithPath("workbasketId").description(workbasketFieldDescriptionsMap.get("workbasketId")), - fieldWithPath("key").description(workbasketFieldDescriptionsMap.get("key")), - fieldWithPath("name").description(workbasketFieldDescriptionsMap.get("name")), - fieldWithPath("description").description(workbasketFieldDescriptionsMap.get("description")), - fieldWithPath("owner").description(workbasketFieldDescriptionsMap.get("owner")), - fieldWithPath("domain").description(workbasketFieldDescriptionsMap.get("domain")), - fieldWithPath("type").description(workbasketFieldDescriptionsMap.get("type")), - fieldWithPath("custom1").description(workbasketFieldDescriptionsMap.get("custom1")), - fieldWithPath("custom2").description(workbasketFieldDescriptionsMap.get("custom2")), - fieldWithPath("custom3").description(workbasketFieldDescriptionsMap.get("custom3")), - fieldWithPath("custom4").description(workbasketFieldDescriptionsMap.get("custom4")), - fieldWithPath("orgLevel1").description(workbasketFieldDescriptionsMap.get("orgLevel1")), - fieldWithPath("orgLevel2").description(workbasketFieldDescriptionsMap.get("orgLevel2")), - fieldWithPath("orgLevel3").description(workbasketFieldDescriptionsMap.get("orgLevel3")), - fieldWithPath("orgLevel4").description(workbasketFieldDescriptionsMap.get("orgLevel4")), - fieldWithPath("created").ignored(), - fieldWithPath("modified").ignored(), - fieldWithPath("_links.distributionTargets.href").ignored(), - fieldWithPath("_links.removeDistributionTargets.href").ignored(), - fieldWithPath("_links.accessItems.href").ignored(), - fieldWithPath("_links.allWorkbaskets.href").ignored(), - fieldWithPath("_links.self.href").ignored() + workbasketSubsetFieldDescriptors = + new FieldDescriptor[] { + fieldWithPath("workbasketId") + .description(workbasketFieldDescriptionsMap.get("workbasketId")), + fieldWithPath("key").description(workbasketFieldDescriptionsMap.get("key")), + fieldWithPath("name").description(workbasketFieldDescriptionsMap.get("name")), + fieldWithPath("description") + .description(workbasketFieldDescriptionsMap.get("description")), + fieldWithPath("owner").description(workbasketFieldDescriptionsMap.get("owner")), + fieldWithPath("domain").description(workbasketFieldDescriptionsMap.get("domain")), + fieldWithPath("type").description(workbasketFieldDescriptionsMap.get("type")), + fieldWithPath("custom1").description(workbasketFieldDescriptionsMap.get("custom1")), + fieldWithPath("custom2").description(workbasketFieldDescriptionsMap.get("custom2")), + fieldWithPath("custom3").description(workbasketFieldDescriptionsMap.get("custom3")), + fieldWithPath("custom4").description(workbasketFieldDescriptionsMap.get("custom4")), + fieldWithPath("orgLevel1").description(workbasketFieldDescriptionsMap.get("orgLevel1")), + fieldWithPath("orgLevel2").description(workbasketFieldDescriptionsMap.get("orgLevel2")), + fieldWithPath("orgLevel3").description(workbasketFieldDescriptionsMap.get("orgLevel3")), + fieldWithPath("orgLevel4").description(workbasketFieldDescriptionsMap.get("orgLevel4")), + fieldWithPath("created").ignored(), + fieldWithPath("modified").ignored(), + fieldWithPath("_links.distributionTargets.href").ignored(), + fieldWithPath("_links.removeDistributionTargets.href").ignored(), + fieldWithPath("_links.accessItems.href").ignored(), + fieldWithPath("_links.allWorkbaskets.href").ignored(), + fieldWithPath("_links.self.href").ignored() }; - accessItemFieldDescriptors = new FieldDescriptor[] { - fieldWithPath("accessItems[].accessItemId").description( - accessItemFieldDescriptionsMap.get("accessItems.accessItemId")), - fieldWithPath("accessItems[].workbasketId").description( - accessItemFieldDescriptionsMap.get("accessItems.workbasketId")), - fieldWithPath("accessItems[].workbasketKey").description( - accessItemFieldDescriptionsMap.get("accessItems.workbasketKey")), - fieldWithPath("accessItems[].accessId").description( - accessItemFieldDescriptionsMap.get("accessItems.accessId")), - fieldWithPath("accessItems[].accessName").description( - accessItemFieldDescriptionsMap.get("accessItems.accessName")), - fieldWithPath("accessItems[].permRead").description( - accessItemFieldDescriptionsMap.get("accessItems.permRead")), - fieldWithPath("accessItems[].permOpen").description( - accessItemFieldDescriptionsMap.get("accessItems.permOpen")), - fieldWithPath("accessItems[].permAppend").description( - accessItemFieldDescriptionsMap.get("accessItems.permAppend")), - fieldWithPath("accessItems[].permTransfer").description( - accessItemFieldDescriptionsMap.get("accessItems.permTransfer")), - fieldWithPath("accessItems[].permDistribute").description( - accessItemFieldDescriptionsMap.get("accessItems.permDistribute")), - fieldWithPath("accessItems[].permCustom1").description( - accessItemFieldDescriptionsMap.get("accessItems.permCustom1")), - fieldWithPath("accessItems[].permCustom2").description( - accessItemFieldDescriptionsMap.get("accessItems.permCustom2")), - fieldWithPath("accessItems[].permCustom3").description( - accessItemFieldDescriptionsMap.get("accessItems.permCustom3")), - fieldWithPath("accessItems[].permCustom4").description( - accessItemFieldDescriptionsMap.get("accessItems.permCustom4")), - fieldWithPath("accessItems[].permCustom5").description( - accessItemFieldDescriptionsMap.get("accessItems.permCustom5")), - fieldWithPath("accessItems[].permCustom6").description( - accessItemFieldDescriptionsMap.get("accessItems.permCustom6")), - fieldWithPath("accessItems[].permCustom7").description( - accessItemFieldDescriptionsMap.get("accessItems.permCustom7")), - fieldWithPath("accessItems[].permCustom8").description( - accessItemFieldDescriptionsMap.get("accessItems.permCustom8")), - fieldWithPath("accessItems[].permCustom9").description( - accessItemFieldDescriptionsMap.get("accessItems.permCustom9")), - fieldWithPath("accessItems[].permCustom10").description( - accessItemFieldDescriptionsMap.get("accessItems.permCustom10")), - fieldWithPath("accessItems[].permCustom11").description( - accessItemFieldDescriptionsMap.get("accessItems.permCustom11")), - fieldWithPath("accessItems[].permCustom12").description( - accessItemFieldDescriptionsMap.get("accessItems.permCustom12")), - fieldWithPath("_links.self.href").ignored(), - fieldWithPath("_links.workbasket.href").ignored() + accessItemFieldDescriptors = + new FieldDescriptor[] { + fieldWithPath("accessItems[].accessItemId") + .description(accessItemFieldDescriptionsMap.get("accessItems.accessItemId")), + fieldWithPath("accessItems[].workbasketId") + .description(accessItemFieldDescriptionsMap.get("accessItems.workbasketId")), + fieldWithPath("accessItems[].workbasketKey") + .description(accessItemFieldDescriptionsMap.get("accessItems.workbasketKey")), + fieldWithPath("accessItems[].accessId") + .description(accessItemFieldDescriptionsMap.get("accessItems.accessId")), + fieldWithPath("accessItems[].accessName") + .description(accessItemFieldDescriptionsMap.get("accessItems.accessName")), + fieldWithPath("accessItems[].permRead") + .description(accessItemFieldDescriptionsMap.get("accessItems.permRead")), + fieldWithPath("accessItems[].permOpen") + .description(accessItemFieldDescriptionsMap.get("accessItems.permOpen")), + fieldWithPath("accessItems[].permAppend") + .description(accessItemFieldDescriptionsMap.get("accessItems.permAppend")), + fieldWithPath("accessItems[].permTransfer") + .description(accessItemFieldDescriptionsMap.get("accessItems.permTransfer")), + fieldWithPath("accessItems[].permDistribute") + .description(accessItemFieldDescriptionsMap.get("accessItems.permDistribute")), + fieldWithPath("accessItems[].permCustom1") + .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom1")), + fieldWithPath("accessItems[].permCustom2") + .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom2")), + fieldWithPath("accessItems[].permCustom3") + .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom3")), + fieldWithPath("accessItems[].permCustom4") + .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom4")), + fieldWithPath("accessItems[].permCustom5") + .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom5")), + fieldWithPath("accessItems[].permCustom6") + .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom6")), + fieldWithPath("accessItems[].permCustom7") + .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom7")), + fieldWithPath("accessItems[].permCustom8") + .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom8")), + fieldWithPath("accessItems[].permCustom9") + .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom9")), + fieldWithPath("accessItems[].permCustom10") + .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom10")), + fieldWithPath("accessItems[].permCustom11") + .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom11")), + fieldWithPath("accessItems[].permCustom12") + .description(accessItemFieldDescriptionsMap.get("accessItems.permCustom12")), + fieldWithPath("_links.self.href").ignored(), + fieldWithPath("_links.workbasket.href").ignored() }; - allWorkbasketAccessItemsFieldDescriptors = new FieldDescriptor[] { - subsectionWithPath("accessItems").description("An array of <>"), - fieldWithPath("_links.self.href").ignored(), - fieldWithPath("_links.workbasket.href").ignored() + allWorkbasketAccessItemsFieldDescriptors = + new FieldDescriptor[] { + subsectionWithPath("accessItems") + .description("An array of <>"), + fieldWithPath("_links.self.href").ignored(), + fieldWithPath("_links.workbasket.href").ignored() }; - allDistributionTargetsFieldDescriptors = new FieldDescriptor[] { - subsectionWithPath("distributionTargets").description( - "An array of <>"), - fieldWithPath("_links.self.href").ignored(), - fieldWithPath("_links.workbasket.href").ignored() + allDistributionTargetsFieldDescriptors = + new FieldDescriptor[] { + subsectionWithPath("distributionTargets") + .description("An array of <>"), + fieldWithPath("_links.self.href").ignored(), + fieldWithPath("_links.workbasket.href").ignored() }; - createWorkbasketFieldDescriptors = new FieldDescriptor[] { - fieldWithPath("key").description(workbasketFieldDescriptionsMap.get("key")), - fieldWithPath("name").description(workbasketFieldDescriptionsMap.get("name")), - fieldWithPath("domain").description(workbasketFieldDescriptionsMap.get("domain")), - fieldWithPath("type").description(workbasketFieldDescriptionsMap.get("type")), - fieldWithPath("description").description(workbasketFieldDescriptionsMap.get("description")) - .type("String") - .optional(), - fieldWithPath("owner").description(workbasketFieldDescriptionsMap.get("owner")).type("String").optional(), - fieldWithPath("orgLevel1").description(workbasketFieldDescriptionsMap.get("orgLevel1")) - .type("String") - .optional(), - fieldWithPath("orgLevel2").description(workbasketFieldDescriptionsMap.get("orgLevel2")) - .type("String") - .optional(), - fieldWithPath("orgLevel3").description(workbasketFieldDescriptionsMap.get("orgLevel3")) - .type("String") - .optional(), - fieldWithPath("orgLevel4").description(workbasketFieldDescriptionsMap.get("orgLevel4")) - .type("String") - .optional(), - fieldWithPath("created").description(workbasketFieldDescriptionsMap.get("created")) - .type("String") - .optional(), - fieldWithPath("modified").description(workbasketFieldDescriptionsMap.get("modified")) - .type("String") - .optional(), - fieldWithPath("custom1").description(workbasketFieldDescriptionsMap.get("custom1")) - .type("String") - .optional(), - fieldWithPath("custom2").description(workbasketFieldDescriptionsMap.get("custom2")) - .type("String") - .optional(), - fieldWithPath("custom3").description(workbasketFieldDescriptionsMap.get("custom3")) - .type("String") - .optional(), - fieldWithPath("custom4").description(workbasketFieldDescriptionsMap.get("custom4")) - .type("String") - .optional(), - fieldWithPath("_links.distributionTargets.href").description( - workbasketFieldDescriptionsMap.get("_links.distributionTargets.href")).type("String").optional(), - fieldWithPath("_links.removeDistributionTargets.href").description( - workbasketFieldDescriptionsMap.get("_links.removeDistributionTargets.href")).type("String").optional(), - fieldWithPath("_links.accessItems.href").description( - workbasketFieldDescriptionsMap.get("_links.accessItems.href")).type("String").optional(), - fieldWithPath("_links.allWorkbaskets.href").description( - workbasketFieldDescriptionsMap.get("_links.allWorkbaskets.href")).type("String").optional() + createWorkbasketFieldDescriptors = + new FieldDescriptor[] { + fieldWithPath("key").description(workbasketFieldDescriptionsMap.get("key")), + fieldWithPath("name").description(workbasketFieldDescriptionsMap.get("name")), + fieldWithPath("domain").description(workbasketFieldDescriptionsMap.get("domain")), + fieldWithPath("type").description(workbasketFieldDescriptionsMap.get("type")), + fieldWithPath("description") + .description(workbasketFieldDescriptionsMap.get("description")) + .type("String") + .optional(), + fieldWithPath("owner") + .description(workbasketFieldDescriptionsMap.get("owner")) + .type("String") + .optional(), + fieldWithPath("orgLevel1") + .description(workbasketFieldDescriptionsMap.get("orgLevel1")) + .type("String") + .optional(), + fieldWithPath("orgLevel2") + .description(workbasketFieldDescriptionsMap.get("orgLevel2")) + .type("String") + .optional(), + fieldWithPath("orgLevel3") + .description(workbasketFieldDescriptionsMap.get("orgLevel3")) + .type("String") + .optional(), + fieldWithPath("orgLevel4") + .description(workbasketFieldDescriptionsMap.get("orgLevel4")) + .type("String") + .optional(), + fieldWithPath("created") + .description(workbasketFieldDescriptionsMap.get("created")) + .type("String") + .optional(), + fieldWithPath("modified") + .description(workbasketFieldDescriptionsMap.get("modified")) + .type("String") + .optional(), + fieldWithPath("custom1") + .description(workbasketFieldDescriptionsMap.get("custom1")) + .type("String") + .optional(), + fieldWithPath("custom2") + .description(workbasketFieldDescriptionsMap.get("custom2")) + .type("String") + .optional(), + fieldWithPath("custom3") + .description(workbasketFieldDescriptionsMap.get("custom3")) + .type("String") + .optional(), + fieldWithPath("custom4") + .description(workbasketFieldDescriptionsMap.get("custom4")) + .type("String") + .optional(), + fieldWithPath("_links.distributionTargets.href") + .description(workbasketFieldDescriptionsMap.get("_links.distributionTargets.href")) + .type("String") + .optional(), + fieldWithPath("_links.removeDistributionTargets.href") + .description( + workbasketFieldDescriptionsMap.get("_links.removeDistributionTargets.href")) + .type("String") + .optional(), + fieldWithPath("_links.accessItems.href") + .description(workbasketFieldDescriptionsMap.get("_links.accessItems.href")) + .type("String") + .optional(), + fieldWithPath("_links.allWorkbaskets.href") + .description(workbasketFieldDescriptionsMap.get("_links.allWorkbaskets.href")) + .type("String") + .optional() }; - } + } - @Test - void getAllWorkbasketsDocTest() throws Exception { - this.mockMvc.perform( - RestDocumentationRequestBuilders.get(restHelper.toUrl(Mapping.URL_WORKBASKET) + "?type=PERSONAL") + @Test + void getAllWorkbasketsDocTest() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get( + restHelper.toUrl(Mapping.URL_WORKBASKET) + "?type=PERSONAL") .accept("application/hal+json") .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("GetAllWorkbasketsDocTest", - responseFields(allWorkbasketsFieldDescriptors))); - } + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "GetAllWorkbasketsDocTest", responseFields(allWorkbasketsFieldDescriptors))); + } - @Test - void getSpecificWorkbasketDocTest() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders.get( - restHelper.toUrl(Mapping.URL_WORKBASKET_ID, "WBI:100000000000000000000000000000000001")) - .accept("application/hal+json") - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("GetSpecificWorkbasketDocTest", - responseFields(workbasketFieldDescriptors))); - } + @Test + void getSpecificWorkbasketDocTest() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get( + restHelper.toUrl( + Mapping.URL_WORKBASKET_ID, "WBI:100000000000000000000000000000000001")) + .accept("application/hal+json") + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "GetSpecificWorkbasketDocTest", responseFields(workbasketFieldDescriptors))); + } - @Test - void getAllWorkbasketAccessItemsDocTest() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders.get( - restHelper.toUrl(Mapping.URL_WORKBASKET_ID_ACCESSITEMS, "WBI:100000000000000000000000000000000001")) - .accept("application/hal+json") - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("GetAllWorkbasketAccessItemsDocTest", + @Test + void getAllWorkbasketAccessItemsDocTest() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get( + restHelper.toUrl( + Mapping.URL_WORKBASKET_ID_ACCESSITEMS, + "WBI:100000000000000000000000000000000001")) + .accept("application/hal+json") + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "GetAllWorkbasketAccessItemsDocTest", responseFields(allWorkbasketAccessItemsFieldDescriptors))); - } + } - @Test - void workbasketSubsetDocTest() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders.get( - restHelper.toUrl(Mapping.URL_WORKBASKET_ID, "WBI:100000000000000000000000000000000001")) - .accept("application/hal+json") - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("WorkbasketSubset", - responseFields(workbasketSubsetFieldDescriptors))); - } + @Test + void workbasketSubsetDocTest() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get( + restHelper.toUrl( + Mapping.URL_WORKBASKET_ID, "WBI:100000000000000000000000000000000001")) + .accept("application/hal+json") + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "WorkbasketSubset", responseFields(workbasketSubsetFieldDescriptors))); + } - @Test - void removeWorkbasketAsDistributionTargetDocTest() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders.delete( - restHelper.toUrl(Mapping.URL_WORKBASKET_DISTRIBUTION_ID, "WBI:100000000000000000000000000000000007")) - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isNoContent()) - .andDo(MockMvcRestDocumentation.document("RemoveWorkbasketAsDistributionTargetDocTest")); - } + @Test + void removeWorkbasketAsDistributionTargetDocTest() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.delete( + restHelper.toUrl( + Mapping.URL_WORKBASKET_DISTRIBUTION_ID, + "WBI:100000000000000000000000000000000007")) + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + .andExpect(MockMvcResultMatchers.status().isNoContent()) + .andDo(MockMvcRestDocumentation.document("RemoveWorkbasketAsDistributionTargetDocTest")); + } - @Test - void getAllWorkbasketDistributionTargets() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders.get( - restHelper.toUrl(Mapping.URL_WORKBASKET_ID_DISTRIBUTION, "WBI:100000000000000000000000000000000002")) - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("GetAllWorkbasketDistributionTargets", + @Test + void getAllWorkbasketDistributionTargets() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get( + restHelper.toUrl( + Mapping.URL_WORKBASKET_ID_DISTRIBUTION, + "WBI:100000000000000000000000000000000002")) + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "GetAllWorkbasketDistributionTargets", responseFields(allDistributionTargetsFieldDescriptors))); - } + } - @Test - void createWorkbasketDocTest() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders.post(restHelper.toUrl(Mapping.URL_WORKBASKET)) - .contentType("application/json") - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x") - .content( - "{\"key\" : \"asdasdasd\", \"name\" : \"Gruppenpostkorb KSC\", \"domain\" : \"DOMAIN_A\", \"type\" : \"GROUP\", \"created\" : \"2018-02-01T11:00:00Z\",\r\n" - + - " \"modified\" : \"2018-02-01T11:00:00Z\"}")) - .andExpect(MockMvcResultMatchers.status().isCreated()) - .andDo(MockMvcRestDocumentation.document("CreateWorkbasketDocTest", + @Test + void createWorkbasketDocTest() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.post(restHelper.toUrl(Mapping.URL_WORKBASKET)) + .contentType("application/json") + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x") + .content( + "{\"key\" : \"asdasdasd\", \"name\" : \"Gruppenpostkorb KSC\", \"domain\" : \"DOMAIN_A\", \"type\" : \"GROUP\", \"created\" : \"2018-02-01T11:00:00Z\",\r\n" + + " \"modified\" : \"2018-02-01T11:00:00Z\"}")) + .andExpect(MockMvcResultMatchers.status().isCreated()) + .andDo( + MockMvcRestDocumentation.document( + "CreateWorkbasketDocTest", requestFields(createWorkbasketFieldDescriptors), responseFields(workbasketFieldDescriptors))) - .andReturn(); + .andReturn(); + } + + @Test + void updateWorkbasketDocTest() throws Exception { + URL url = + new URL( + restHelper.toUrl( + Mapping.URL_WORKBASKET_ID, "WBI:100000000000000000000000000000000002")); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("GET"); + con.setRequestProperty("Authorization", "Basic YWRtaW46YWRtaW4="); + assertEquals(200, con.getResponseCode()); + + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + StringBuffer content = new StringBuffer(); + while ((inputLine = in.readLine()) != null) { + content.append(inputLine); } + in.close(); + con.disconnect(); + String originalWorkbasket = content.toString(); + String modifiedWorkbasket = new String(originalWorkbasket.toString()); - @Test - void updateWorkbasketDocTest() throws Exception { - URL url = new URL(restHelper.toUrl(Mapping.URL_WORKBASKET_ID, "WBI:100000000000000000000000000000000002")); - HttpURLConnection con = (HttpURLConnection) url.openConnection(); - con.setRequestMethod("GET"); - con.setRequestProperty("Authorization", "Basic YWRtaW46YWRtaW4="); - assertEquals(200, con.getResponseCode()); - - BufferedReader in = new BufferedReader( - new InputStreamReader(con.getInputStream())); - String inputLine; - StringBuffer content = new StringBuffer(); - while ((inputLine = in.readLine()) != null) { - content.append(inputLine); - } - in.close(); - con.disconnect(); - String originalWorkbasket = content.toString(); - String modifiedWorkbasket = new String(originalWorkbasket.toString()); - - this.mockMvc.perform(RestDocumentationRequestBuilders.put( - restHelper.toUrl(Mapping.URL_WORKBASKET_ID, "WBI:100000000000000000000000000000000002")) - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x") - .contentType("application/json") - .content(modifiedWorkbasket)) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("UpdateWorkbasketDocTest", + this.mockMvc + .perform( + RestDocumentationRequestBuilders.put( + restHelper.toUrl( + Mapping.URL_WORKBASKET_ID, "WBI:100000000000000000000000000000000002")) + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x") + .contentType("application/json") + .content(modifiedWorkbasket)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "UpdateWorkbasketDocTest", requestFields(workbasketFieldDescriptors), responseFields(workbasketFieldDescriptors))); - } + } - @Test - void markWorkbasketForDeletionDocTest() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders.delete( - restHelper.toUrl(Mapping.URL_WORKBASKET_ID, "WBI:100000000000000000000000000000000005")) - .header("Authorization", "Basic YWRtaW46YWRtaW4=")) - .andExpect(MockMvcResultMatchers.status().isAccepted()) - .andDo(MockMvcRestDocumentation.document("MarkWorkbasketForDeletionDocTest")); - } + @Test + void markWorkbasketForDeletionDocTest() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.delete( + restHelper.toUrl( + Mapping.URL_WORKBASKET_ID, "WBI:100000000000000000000000000000000005")) + .header("Authorization", "Basic YWRtaW46YWRtaW4=")) + .andExpect(MockMvcResultMatchers.status().isAccepted()) + .andDo(MockMvcRestDocumentation.document("MarkWorkbasketForDeletionDocTest")); + } - @Test - void accessItemDocTest() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders.get( - restHelper.toUrl(Mapping.URL_WORKBASKET_ID_ACCESSITEMS, "WBI:100000000000000000000000000000000001")) - .accept("application/hal+json") - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("AccessItemsDocTest", - responseFields(accessItemFieldDescriptors))); - } + @Test + void accessItemDocTest() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get( + restHelper.toUrl( + Mapping.URL_WORKBASKET_ID_ACCESSITEMS, + "WBI:100000000000000000000000000000000001")) + .accept("application/hal+json") + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "AccessItemsDocTest", responseFields(accessItemFieldDescriptors))); + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/WorkbasketDefinitionControllerRestDocumentation.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/WorkbasketDefinitionControllerRestDocumentation.java index 4e7658f45..fcb41a9d1 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/WorkbasketDefinitionControllerRestDocumentation.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/doc/api/WorkbasketDefinitionControllerRestDocumentation.java @@ -16,35 +16,39 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import pro.taskana.rest.Mapping; -/** - * Generate Rest Documentation for Workbasket Definitions. - */ +/** Generate Rest Documentation for Workbasket Definitions. */ class WorkbasketDefinitionControllerRestDocumentation extends BaseRestDocumentation { - private FieldDescriptor[] workbasketDefinitionsFieldDescriptors; + private FieldDescriptor[] workbasketDefinitionsFieldDescriptors; - @BeforeEach - void setUp() { + @BeforeEach + void setUp() { - workbasketDefinitionsFieldDescriptors = new FieldDescriptor[] { - subsectionWithPath("[]").description("An array of <>") + workbasketDefinitionsFieldDescriptors = + new FieldDescriptor[] { + subsectionWithPath("[]") + .description("An array of <>") }; - } + } - @Test - void exportAllWorkbasketDefinitions() throws Exception { - this.mockMvc.perform(RestDocumentationRequestBuilders - .get(restHelper.toUrl(Mapping.URL_WORKBASKETDEFIITIONS)) - .accept("application/json") - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andDo(MockMvcRestDocumentation.document("ExportWorkbasketdefinitionsDocTest", + @Test + void exportAllWorkbasketDefinitions() throws Exception { + this.mockMvc + .perform( + RestDocumentationRequestBuilders.get(restHelper.toUrl(Mapping.URL_WORKBASKETDEFIITIONS)) + .accept("application/json") + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo( + MockMvcRestDocumentation.document( + "ExportWorkbasketdefinitionsDocTest", responseFields(workbasketDefinitionsFieldDescriptors))); - } + } - @Test - void importWorkbasketDefinition() throws Exception { - String definitionString = "[" + @Test + void importWorkbasketDefinition() throws Exception { + String definitionString = + "[" + "{" + "\"distributionTargets\":[], " + "\"authorizations\":[], " @@ -52,12 +56,15 @@ class WorkbasketDefinitionControllerRestDocumentation extends BaseRestDocumentat + "}" + "]"; - this.mockMvc.perform(multipart(restHelper.toUrl(Mapping.URL_WORKBASKETDEFIITIONS)) - .file("file", - definitionString.getBytes()) - .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) - .andExpect(MockMvcResultMatchers.status().isNoContent()) - .andDo(document("ImportWorkbasketDefinitions", requestParts( - partWithName("file").description("The file to upload")))); - } + this.mockMvc + .perform( + multipart(restHelper.toUrl(Mapping.URL_WORKBASKETDEFIITIONS)) + .file("file", definitionString.getBytes()) + .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x")) + .andExpect(MockMvcResultMatchers.status().isNoContent()) + .andDo( + document( + "ImportWorkbasketDefinitions", + requestParts(partWithName("file").description("The file to upload")))); + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/ldap/LdapCacheTestImpl.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/ldap/LdapCacheTestImpl.java index 9e2b23558..4d1cb443a 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/ldap/LdapCacheTestImpl.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/ldap/LdapCacheTestImpl.java @@ -16,377 +16,389 @@ import pro.taskana.rest.resource.AccessIdResource; */ public class LdapCacheTestImpl implements LdapCache { - /** - * Dictionary is a {@link Map} collection that contains {@link AccessIdResource} as key (user) - * and {@link List} as value (groups of which the user is a member) . - */ - private static Map> users; - private static List accessIds = new ArrayList<>(Arrays.asList( - new AccessIdResource("Martin, Rojas Miguel Angel", "user_1_1"), - new AccessIdResource("Zorgati, Mustapha", "user_2_1"), - new AccessIdResource("Behrendt, Maximilian", "max"), - new AccessIdResource("Bert, Ali", "teamlead_5"), - new AccessIdResource("Hagen, Holger", "teamlead_3"), - new AccessIdResource("Breier, Bernd", "user_2_2"), - new AccessIdResource("Fielmalz, Anke", "user017"), - new AccessIdResource("Mente, Maximilian", "max_mente"), - new AccessIdResource("Theke, Bernd", "user_2_3"), - new AccessIdResource("Ferrante, Elena", "elena"), - new AccessIdResource("Mueller, Simone", "simone"), - new AccessIdResource("Sirup, Aaron", "user001"), - new AccessIdResource("Nacho, recuerda", "user_1_2"), - new AccessIdResource("Lass, Ada", "user003"), - new AccessIdResource("Tion, Addi", "user004"), - new AccessIdResource("Lette, Adi", "user005"), - new AccessIdResource("Admin", "teamlead_2"), - new AccessIdResource("Native, Alter", "user006"), - new AccessIdResource("Herum, Albert", "user007"), - new AccessIdResource("Meyer, Dominik", "teamlead_1"), - new AccessIdResource("Mente, Ali", "user009"), - new AccessIdResource("Nach, Alma", "user011"), - new AccessIdResource("Gehzauch, Anders", "user012"), - new AccessIdResource("Theke, Andi", "user013"), - new AccessIdResource("Kreuz, Andreas", "user014"), - new AccessIdResource("Tiefsee, Anka", "user016"), - new AccessIdResource("Fassen, Ann", "user018"), - new AccessIdResource("Probe, Ann", "user019"), - new AccessIdResource("Bolika, Anna", "user020"), - new AccessIdResource("Ecke, Anna", "user021"), - new AccessIdResource("Hosi, Anna", "user022"), - new AccessIdResource("Kronis-Tisch, Anna", "user023"), - new AccessIdResource("Logie, Anna", "user024"), - new AccessIdResource("Luehse, Anna", "user025"), - new AccessIdResource("Nass, Anna", "user026"), - new AccessIdResource("Thalb, Anna", "user027"), - new AccessIdResource("Tomie, Anna", "user028"), - new AccessIdResource("Donnich, Anne", "user029"), - new AccessIdResource("Kaffek, Anne", "user030"), - new AccessIdResource("Thek, Anne", "user031"), - new AccessIdResource("Matoer, Anni", "user032"), - new AccessIdResource("Ragentor, Ansgar", "user033"), - new AccessIdResource("Stoteles, Ari", "user034"), - new AccessIdResource("Thmetik, Ari", "user035"), - new AccessIdResource("Nuehm, Arno", "user036"), - new AccessIdResource("Schocke, Artie", "user037"), - new AccessIdResource("Stoppel, Bart", "user038"), - new AccessIdResource("Beitung, Bea", "user039"), - new AccessIdResource("Ildich, Bea", "user040"), - new AccessIdResource("Vista, Bella", "user041"), - new AccessIdResource("Utzer, Ben", "user042"), - new AccessIdResource("Zien, Ben", "user043"), - new AccessIdResource("Stein, Bernd", "user044"), - new AccessIdResource("Deramen, Bill", "user045"), - new AccessIdResource("Honig, Bine", "user046"), - new AccessIdResource("Densatz, Bo", "user047"), - new AccessIdResource("Densee, Bo", "user048"), - new AccessIdResource("Lerwagen, Bo", "user049"), - new AccessIdResource("Tail, Bob", "user050"), - new AccessIdResource("Ketta, Bruce", "user051"), - new AccessIdResource("Terrie, Bud", "user052"), - new AccessIdResource("Biener-Haken, Cara", "user053"), - new AccessIdResource("Ass, Caro", "user054"), - new AccessIdResource("Kaffee, Caro", "user055"), - new AccessIdResource("Linger, Caro", "user056"), - new AccessIdResource("tenSaft, Caro", "user057"), - new AccessIdResource("Antheme, Chris", "user058"), - new AccessIdResource("Baum, Chris", "user059"), - new AccessIdResource("Tall, Chris", "user060"), - new AccessIdResource("Reiniger, Claas", "user061"), - new AccessIdResource("Grube, Claire", "user062"), - new AccessIdResource("Fall, Clara", "user063"), - new AccessIdResource("Korn, Clara", "user064"), - new AccessIdResource("Lenriff, Cora", "user065"), - new AccessIdResource("Schiert, Cora", "user066"), - new AccessIdResource("Hose, Cord", "user067"), - new AccessIdResource("Onbleu, Cord", "user068"), - new AccessIdResource("Umkleide, Damon", "user069"), - new AccessIdResource("Affier, Dean", "user070"), - new AccessIdResource("Orm, Dean", "user071"), - new AccessIdResource("Platz, Dennis", "user072"), - new AccessIdResource("Milch, Dick", "user073"), - new AccessIdResource("Mow, Dina", "user074"), - new AccessIdResource("Keil, Donna", "user075"), - new AccessIdResource("Littchen, Donna", "user076"), - new AccessIdResource("Wetter, Donna", "user077"), - new AccessIdResource("Was, Ed", "user078"), - new AccessIdResource("Khar, Ede", "user079"), - new AccessIdResource("Nut, Ella", "user080"), - new AccessIdResource("Stisch, Ella", "user081"), - new AccessIdResource("Diel, Emma", "user082"), - new AccessIdResource("Herdamit, Emma", "user083"), - new AccessIdResource("Mitter-Uhe, Emma", "user084"), - new AccessIdResource("Tatt, Erich", "user085"), - new AccessIdResource("Drigend, Ernie", "user086"), - new AccessIdResource("Poly, Esther", "user087"), - new AccessIdResource("Trautz, Eugen", "user088"), - new AccessIdResource("Quiert, Eva", "user089"), - new AccessIdResource("Inurlaub, Fatma", "user090"), - new AccessIdResource("Land, Finn", "user091"), - new AccessIdResource("Sternis, Finn", "user092"), - new AccessIdResource("Furt, Frank", "user093"), - new AccessIdResource("Reich, Frank", "user094"), - new AccessIdResource("Iskaner, Franz", "user095"), - new AccessIdResource("Nerr, Franziska", "user096"), - new AccessIdResource("Zafen, Friedrich", "user097"), - new AccessIdResource("Pomm, Fritz", "user098"), - new AccessIdResource("deWegs, Gera", "user099"), - new AccessIdResource("Staebe, Gitta", "user100"), - new AccessIdResource("Zend, Glenn", "user101"), - new AccessIdResource("Fisch, Grete", "user102"), - new AccessIdResource("Zucker, Gus", "user103"), - new AccessIdResource("Muhn, Hanni", "user104"), - new AccessIdResource("Fermesse, Hanno", "user105"), - new AccessIdResource("Aplast, Hans", "user106"), - new AccessIdResource("Eart, Hans", "user107"), - new AccessIdResource("Back, Hardy", "user108"), - new AccessIdResource("Beau, Harry", "user109"), - new AccessIdResource("Kraut, Heide", "user110"), - new AccessIdResource("Witzka, Heide", "user111"), - new AccessIdResource("Buchen, Hein", "user112"), - new AccessIdResource("Lichkeit, Hein", "user113"), - new AccessIdResource("Suchung, Hein", "user114"), - new AccessIdResource("Ellmann, Heinz", "user115"), - new AccessIdResource("Ketchup, Heinz", "user116"), - new AccessIdResource("Zeim, Hilde", "user117"), - new AccessIdResource("Bilien, Immo", "user118"), - new AccessIdResource("Her, Inge", "user119"), - new AccessIdResource("Wahrsam, Inge", "user120"), - new AccessIdResource("Flamm, Ingo", "user121"), - new AccessIdResource("Enzien, Ingrid", "user122"), - new AccessIdResource("Rohsch, Inken", "user123"), - new AccessIdResource("Ihr, Insa", "user124"), - new AccessIdResource("Nerda, Iska", "user125"), - new AccessIdResource("Eitz, Jens", "user126"), - new AccessIdResource("Nastik, Jim", "user127"), - new AccessIdResource("Gurt, Jo", "user128"), - new AccessIdResource("Kurrth, Jo", "user129"), - new AccessIdResource("Kolade, Joe", "user130"), - new AccessIdResource("Iter, Johann", "user131"), - new AccessIdResource("Tick, Joyce", "user132"), - new AccessIdResource("Case, Justin", "user133"), - new AccessIdResource("Time, Justin", "user134"), - new AccessIdResource("Komp, Jutta", "user135"), - new AccessIdResource("Mauer, Kai", "user136"), - new AccessIdResource("Pirinja, Kai", "user137"), - new AccessIdResource("Serpfalz, Kai", "user138"), - new AccessIdResource("Auer, Karl", "user139"), - new AccessIdResource("Ielauge, Karl", "user140"), - new AccessIdResource("Ifornjen, Karl", "user141"), - new AccessIdResource("Radi, Karl", "user142"), - new AccessIdResource("Verti, Karl", "user143"), - new AccessIdResource("Sery, Karo", "user144"), - new AccessIdResource("Lisator, Katha", "user145"), - new AccessIdResource("Flo, Kati", "user146"), - new AccessIdResource("Schenn, Knut", "user147"), - new AccessIdResource("Achse, Kurt", "user148"), - new AccessIdResource("Zepause, Kurt", "user149"), - new AccessIdResource("Zerr, Kurt", "user150"), - new AccessIdResource("Reden, Lasse", "user151"), - new AccessIdResource("Metten, Lee", "user152"), - new AccessIdResource("Arm, Lene", "user153"), - new AccessIdResource("Thur, Linnea", "user154"), - new AccessIdResource("Bonn, Lisa", "user155"), - new AccessIdResource("Sembourg, Luc", "user156"), - new AccessIdResource("Rung, Lucky", "user157"), - new AccessIdResource("Zafen, Ludwig", "user158"), - new AccessIdResource("Hauden, Lukas", "user159"), - new AccessIdResource("Hose, Lutz", "user160"), - new AccessIdResource("Tablette, Lutz", "user161"), - new AccessIdResource("Fehr, Luzie", "user162"), - new AccessIdResource("Nalyse, Magda", "user163"), - new AccessIdResource("Ehfer, Maik", "user164"), - new AccessIdResource("Sehr, Malte", "user165"), - new AccessIdResource("Thon, Mara", "user166"), - new AccessIdResource("Quark, Marga", "user167"), - new AccessIdResource("Nade, Marie", "user168"), - new AccessIdResource("Niert, Marie", "user169"), - new AccessIdResource("Neese, Mario", "user170"), - new AccessIdResource("Nette, Marion", "user171"), - new AccessIdResource("Nesium, Mark", "user172"), - new AccessIdResource("Thalle, Mark", "user173"), - new AccessIdResource("Diven, Marle", "user174"), - new AccessIdResource("Fitz, Marle", "user175"), - new AccessIdResource("Pfahl, Marta", "user176"), - new AccessIdResource("Zorn, Martin", "user177"), - new AccessIdResource("Krissmes, Mary", "user178"), - new AccessIdResource("Jess, Matt", "user179"), - new AccessIdResource("Strammer, Max", "user180"), - new AccessIdResource("Mumm, Maxi", "user181"), - new AccessIdResource("Morphose, Meta", "user182"), - new AccessIdResource("Uh, Mia", "user183"), - new AccessIdResource("Rofon, Mike", "user184"), - new AccessIdResource("Rosoft, Mike", "user185"), - new AccessIdResource("Liter, Milli", "user186"), - new AccessIdResource("Thär, Milli", "user187"), - new AccessIdResource("Welle, Mirko", "user188"), - new AccessIdResource("Thorat, Mo", "user189"), - new AccessIdResource("Thor, Moni", "user190"), - new AccessIdResource("Kinolta, Monika", "user191"), - new AccessIdResource("Mundhaar, Monika", "user192"), - new AccessIdResource("Munter, Monika", "user193"), - new AccessIdResource("Zwerg, Nat", "user194"), - new AccessIdResource("Elmine, Nick", "user195"), - new AccessIdResource("Thien, Niko", "user196"), - new AccessIdResource("Pferd, Nils", "user197"), - new AccessIdResource("Lerweise, Norma", "user198"), - new AccessIdResource("Motor, Otto", "user199"), - new AccessIdResource("Totol, Otto", "user200"), - new AccessIdResource("Nerr, Paula", "user201"), - new AccessIdResource("Imeter, Peer", "user202"), - new AccessIdResource("Serkatze, Peer", "user203"), - new AccessIdResource("Gogisch, Peter", "user204"), - new AccessIdResource("Silje, Peter", "user205"), - new AccessIdResource("Harmonie, Phil", "user206"), - new AccessIdResource("Ihnen, Philip", "user207"), - new AccessIdResource("Uto, Pia", "user208"), - new AccessIdResource("Kothek, Pina", "user209"), - new AccessIdResource("Zar, Pit", "user210"), - new AccessIdResource("Zeih, Polly", "user211"), - new AccessIdResource("Tswan, Puh", "user212"), - new AccessIdResource("Zufall, Rainer", "user213"), - new AccessIdResource("Lien, Rita", "user214"), - new AccessIdResource("Held, Roman", "user215"), - new AccessIdResource("Haar, Ross", "user216"), - new AccessIdResource("Dick, Roy", "user217"), - new AccessIdResource("Enplaner, Ruth", "user218"), - new AccessIdResource("Kommen, Ryan", "user219"), - new AccessIdResource("Philo, Sophie", "user220"), - new AccessIdResource("Matisier, Stig", "user221"), - new AccessIdResource("Loniki, Tessa", "user222"), - new AccessIdResource("Tralisch, Thea", "user223"), - new AccessIdResource("Logie, Theo", "user224"), - new AccessIdResource("Ister, Thorn", "user225"), - new AccessIdResource("Buktu, Tim", "user226"), - new AccessIdResource("Ate, Tom", "user227"), - new AccessIdResource("Pie, Udo", "user228"), - new AccessIdResource("Aloe, Vera", "user229"), - new AccessIdResource("Hausver, Walter", "user230"), - new AccessIdResource("Schuh, Wanda", "user231"), - new AccessIdResource("Rahm, Wolf", "user232"), + /** + * Dictionary is a {@link Map} collection that contains {@link AccessIdResource} as key (user) and + * {@link List} as value (groups of which the user is a member) . + */ + private static Map> users; - new AccessIdResource("businessadmin", "cn=businessadmin,ou=groups,o=taskanatest"), - new AccessIdResource("UsersGroup", "cn=usersgroup,ou=groups,o=taskanatest"), - new AccessIdResource("DevelopersGroup", "cn=developersgroup,ou=groups,o=taskanatest"), - new AccessIdResource("businessadmin", "cn=customersgroup,ou=groups,o=taskanatest"), + private static List accessIds = + new ArrayList<>( + Arrays.asList( + new AccessIdResource("Martin, Rojas Miguel Angel", "user_1_1"), + new AccessIdResource("Zorgati, Mustapha", "user_2_1"), + new AccessIdResource("Behrendt, Maximilian", "max"), + new AccessIdResource("Bert, Ali", "teamlead_5"), + new AccessIdResource("Hagen, Holger", "teamlead_3"), + new AccessIdResource("Breier, Bernd", "user_2_2"), + new AccessIdResource("Fielmalz, Anke", "user017"), + new AccessIdResource("Mente, Maximilian", "max_mente"), + new AccessIdResource("Theke, Bernd", "user_2_3"), + new AccessIdResource("Ferrante, Elena", "elena"), + new AccessIdResource("Mueller, Simone", "simone"), + new AccessIdResource("Sirup, Aaron", "user001"), + new AccessIdResource("Nacho, recuerda", "user_1_2"), + new AccessIdResource("Lass, Ada", "user003"), + new AccessIdResource("Tion, Addi", "user004"), + new AccessIdResource("Lette, Adi", "user005"), + new AccessIdResource("Admin", "teamlead_2"), + new AccessIdResource("Native, Alter", "user006"), + new AccessIdResource("Herum, Albert", "user007"), + new AccessIdResource("Meyer, Dominik", "teamlead_1"), + new AccessIdResource("Mente, Ali", "user009"), + new AccessIdResource("Nach, Alma", "user011"), + new AccessIdResource("Gehzauch, Anders", "user012"), + new AccessIdResource("Theke, Andi", "user013"), + new AccessIdResource("Kreuz, Andreas", "user014"), + new AccessIdResource("Tiefsee, Anka", "user016"), + new AccessIdResource("Fassen, Ann", "user018"), + new AccessIdResource("Probe, Ann", "user019"), + new AccessIdResource("Bolika, Anna", "user020"), + new AccessIdResource("Ecke, Anna", "user021"), + new AccessIdResource("Hosi, Anna", "user022"), + new AccessIdResource("Kronis-Tisch, Anna", "user023"), + new AccessIdResource("Logie, Anna", "user024"), + new AccessIdResource("Luehse, Anna", "user025"), + new AccessIdResource("Nass, Anna", "user026"), + new AccessIdResource("Thalb, Anna", "user027"), + new AccessIdResource("Tomie, Anna", "user028"), + new AccessIdResource("Donnich, Anne", "user029"), + new AccessIdResource("Kaffek, Anne", "user030"), + new AccessIdResource("Thek, Anne", "user031"), + new AccessIdResource("Matoer, Anni", "user032"), + new AccessIdResource("Ragentor, Ansgar", "user033"), + new AccessIdResource("Stoteles, Ari", "user034"), + new AccessIdResource("Thmetik, Ari", "user035"), + new AccessIdResource("Nuehm, Arno", "user036"), + new AccessIdResource("Schocke, Artie", "user037"), + new AccessIdResource("Stoppel, Bart", "user038"), + new AccessIdResource("Beitung, Bea", "user039"), + new AccessIdResource("Ildich, Bea", "user040"), + new AccessIdResource("Vista, Bella", "user041"), + new AccessIdResource("Utzer, Ben", "user042"), + new AccessIdResource("Zien, Ben", "user043"), + new AccessIdResource("Stein, Bernd", "user044"), + new AccessIdResource("Deramen, Bill", "user045"), + new AccessIdResource("Honig, Bine", "user046"), + new AccessIdResource("Densatz, Bo", "user047"), + new AccessIdResource("Densee, Bo", "user048"), + new AccessIdResource("Lerwagen, Bo", "user049"), + new AccessIdResource("Tail, Bob", "user050"), + new AccessIdResource("Ketta, Bruce", "user051"), + new AccessIdResource("Terrie, Bud", "user052"), + new AccessIdResource("Biener-Haken, Cara", "user053"), + new AccessIdResource("Ass, Caro", "user054"), + new AccessIdResource("Kaffee, Caro", "user055"), + new AccessIdResource("Linger, Caro", "user056"), + new AccessIdResource("tenSaft, Caro", "user057"), + new AccessIdResource("Antheme, Chris", "user058"), + new AccessIdResource("Baum, Chris", "user059"), + new AccessIdResource("Tall, Chris", "user060"), + new AccessIdResource("Reiniger, Claas", "user061"), + new AccessIdResource("Grube, Claire", "user062"), + new AccessIdResource("Fall, Clara", "user063"), + new AccessIdResource("Korn, Clara", "user064"), + new AccessIdResource("Lenriff, Cora", "user065"), + new AccessIdResource("Schiert, Cora", "user066"), + new AccessIdResource("Hose, Cord", "user067"), + new AccessIdResource("Onbleu, Cord", "user068"), + new AccessIdResource("Umkleide, Damon", "user069"), + new AccessIdResource("Affier, Dean", "user070"), + new AccessIdResource("Orm, Dean", "user071"), + new AccessIdResource("Platz, Dennis", "user072"), + new AccessIdResource("Milch, Dick", "user073"), + new AccessIdResource("Mow, Dina", "user074"), + new AccessIdResource("Keil, Donna", "user075"), + new AccessIdResource("Littchen, Donna", "user076"), + new AccessIdResource("Wetter, Donna", "user077"), + new AccessIdResource("Was, Ed", "user078"), + new AccessIdResource("Khar, Ede", "user079"), + new AccessIdResource("Nut, Ella", "user080"), + new AccessIdResource("Stisch, Ella", "user081"), + new AccessIdResource("Diel, Emma", "user082"), + new AccessIdResource("Herdamit, Emma", "user083"), + new AccessIdResource("Mitter-Uhe, Emma", "user084"), + new AccessIdResource("Tatt, Erich", "user085"), + new AccessIdResource("Drigend, Ernie", "user086"), + new AccessIdResource("Poly, Esther", "user087"), + new AccessIdResource("Trautz, Eugen", "user088"), + new AccessIdResource("Quiert, Eva", "user089"), + new AccessIdResource("Inurlaub, Fatma", "user090"), + new AccessIdResource("Land, Finn", "user091"), + new AccessIdResource("Sternis, Finn", "user092"), + new AccessIdResource("Furt, Frank", "user093"), + new AccessIdResource("Reich, Frank", "user094"), + new AccessIdResource("Iskaner, Franz", "user095"), + new AccessIdResource("Nerr, Franziska", "user096"), + new AccessIdResource("Zafen, Friedrich", "user097"), + new AccessIdResource("Pomm, Fritz", "user098"), + new AccessIdResource("deWegs, Gera", "user099"), + new AccessIdResource("Staebe, Gitta", "user100"), + new AccessIdResource("Zend, Glenn", "user101"), + new AccessIdResource("Fisch, Grete", "user102"), + new AccessIdResource("Zucker, Gus", "user103"), + new AccessIdResource("Muhn, Hanni", "user104"), + new AccessIdResource("Fermesse, Hanno", "user105"), + new AccessIdResource("Aplast, Hans", "user106"), + new AccessIdResource("Eart, Hans", "user107"), + new AccessIdResource("Back, Hardy", "user108"), + new AccessIdResource("Beau, Harry", "user109"), + new AccessIdResource("Kraut, Heide", "user110"), + new AccessIdResource("Witzka, Heide", "user111"), + new AccessIdResource("Buchen, Hein", "user112"), + new AccessIdResource("Lichkeit, Hein", "user113"), + new AccessIdResource("Suchung, Hein", "user114"), + new AccessIdResource("Ellmann, Heinz", "user115"), + new AccessIdResource("Ketchup, Heinz", "user116"), + new AccessIdResource("Zeim, Hilde", "user117"), + new AccessIdResource("Bilien, Immo", "user118"), + new AccessIdResource("Her, Inge", "user119"), + new AccessIdResource("Wahrsam, Inge", "user120"), + new AccessIdResource("Flamm, Ingo", "user121"), + new AccessIdResource("Enzien, Ingrid", "user122"), + new AccessIdResource("Rohsch, Inken", "user123"), + new AccessIdResource("Ihr, Insa", "user124"), + new AccessIdResource("Nerda, Iska", "user125"), + new AccessIdResource("Eitz, Jens", "user126"), + new AccessIdResource("Nastik, Jim", "user127"), + new AccessIdResource("Gurt, Jo", "user128"), + new AccessIdResource("Kurrth, Jo", "user129"), + new AccessIdResource("Kolade, Joe", "user130"), + new AccessIdResource("Iter, Johann", "user131"), + new AccessIdResource("Tick, Joyce", "user132"), + new AccessIdResource("Case, Justin", "user133"), + new AccessIdResource("Time, Justin", "user134"), + new AccessIdResource("Komp, Jutta", "user135"), + new AccessIdResource("Mauer, Kai", "user136"), + new AccessIdResource("Pirinja, Kai", "user137"), + new AccessIdResource("Serpfalz, Kai", "user138"), + new AccessIdResource("Auer, Karl", "user139"), + new AccessIdResource("Ielauge, Karl", "user140"), + new AccessIdResource("Ifornjen, Karl", "user141"), + new AccessIdResource("Radi, Karl", "user142"), + new AccessIdResource("Verti, Karl", "user143"), + new AccessIdResource("Sery, Karo", "user144"), + new AccessIdResource("Lisator, Katha", "user145"), + new AccessIdResource("Flo, Kati", "user146"), + new AccessIdResource("Schenn, Knut", "user147"), + new AccessIdResource("Achse, Kurt", "user148"), + new AccessIdResource("Zepause, Kurt", "user149"), + new AccessIdResource("Zerr, Kurt", "user150"), + new AccessIdResource("Reden, Lasse", "user151"), + new AccessIdResource("Metten, Lee", "user152"), + new AccessIdResource("Arm, Lene", "user153"), + new AccessIdResource("Thur, Linnea", "user154"), + new AccessIdResource("Bonn, Lisa", "user155"), + new AccessIdResource("Sembourg, Luc", "user156"), + new AccessIdResource("Rung, Lucky", "user157"), + new AccessIdResource("Zafen, Ludwig", "user158"), + new AccessIdResource("Hauden, Lukas", "user159"), + new AccessIdResource("Hose, Lutz", "user160"), + new AccessIdResource("Tablette, Lutz", "user161"), + new AccessIdResource("Fehr, Luzie", "user162"), + new AccessIdResource("Nalyse, Magda", "user163"), + new AccessIdResource("Ehfer, Maik", "user164"), + new AccessIdResource("Sehr, Malte", "user165"), + new AccessIdResource("Thon, Mara", "user166"), + new AccessIdResource("Quark, Marga", "user167"), + new AccessIdResource("Nade, Marie", "user168"), + new AccessIdResource("Niert, Marie", "user169"), + new AccessIdResource("Neese, Mario", "user170"), + new AccessIdResource("Nette, Marion", "user171"), + new AccessIdResource("Nesium, Mark", "user172"), + new AccessIdResource("Thalle, Mark", "user173"), + new AccessIdResource("Diven, Marle", "user174"), + new AccessIdResource("Fitz, Marle", "user175"), + new AccessIdResource("Pfahl, Marta", "user176"), + new AccessIdResource("Zorn, Martin", "user177"), + new AccessIdResource("Krissmes, Mary", "user178"), + new AccessIdResource("Jess, Matt", "user179"), + new AccessIdResource("Strammer, Max", "user180"), + new AccessIdResource("Mumm, Maxi", "user181"), + new AccessIdResource("Morphose, Meta", "user182"), + new AccessIdResource("Uh, Mia", "user183"), + new AccessIdResource("Rofon, Mike", "user184"), + new AccessIdResource("Rosoft, Mike", "user185"), + new AccessIdResource("Liter, Milli", "user186"), + new AccessIdResource("Thär, Milli", "user187"), + new AccessIdResource("Welle, Mirko", "user188"), + new AccessIdResource("Thorat, Mo", "user189"), + new AccessIdResource("Thor, Moni", "user190"), + new AccessIdResource("Kinolta, Monika", "user191"), + new AccessIdResource("Mundhaar, Monika", "user192"), + new AccessIdResource("Munter, Monika", "user193"), + new AccessIdResource("Zwerg, Nat", "user194"), + new AccessIdResource("Elmine, Nick", "user195"), + new AccessIdResource("Thien, Niko", "user196"), + new AccessIdResource("Pferd, Nils", "user197"), + new AccessIdResource("Lerweise, Norma", "user198"), + new AccessIdResource("Motor, Otto", "user199"), + new AccessIdResource("Totol, Otto", "user200"), + new AccessIdResource("Nerr, Paula", "user201"), + new AccessIdResource("Imeter, Peer", "user202"), + new AccessIdResource("Serkatze, Peer", "user203"), + new AccessIdResource("Gogisch, Peter", "user204"), + new AccessIdResource("Silje, Peter", "user205"), + new AccessIdResource("Harmonie, Phil", "user206"), + new AccessIdResource("Ihnen, Philip", "user207"), + new AccessIdResource("Uto, Pia", "user208"), + new AccessIdResource("Kothek, Pina", "user209"), + new AccessIdResource("Zar, Pit", "user210"), + new AccessIdResource("Zeih, Polly", "user211"), + new AccessIdResource("Tswan, Puh", "user212"), + new AccessIdResource("Zufall, Rainer", "user213"), + new AccessIdResource("Lien, Rita", "user214"), + new AccessIdResource("Held, Roman", "user215"), + new AccessIdResource("Haar, Ross", "user216"), + new AccessIdResource("Dick, Roy", "user217"), + new AccessIdResource("Enplaner, Ruth", "user218"), + new AccessIdResource("Kommen, Ryan", "user219"), + new AccessIdResource("Philo, Sophie", "user220"), + new AccessIdResource("Matisier, Stig", "user221"), + new AccessIdResource("Loniki, Tessa", "user222"), + new AccessIdResource("Tralisch, Thea", "user223"), + new AccessIdResource("Logie, Theo", "user224"), + new AccessIdResource("Ister, Thorn", "user225"), + new AccessIdResource("Buktu, Tim", "user226"), + new AccessIdResource("Ate, Tom", "user227"), + new AccessIdResource("Pie, Udo", "user228"), + new AccessIdResource("Aloe, Vera", "user229"), + new AccessIdResource("Hausver, Walter", "user230"), + new AccessIdResource("Schuh, Wanda", "user231"), + new AccessIdResource("Rahm, Wolf", "user232"), + new AccessIdResource("businessadmin", "cn=businessadmin,ou=groups,o=taskanatest"), + new AccessIdResource("UsersGroup", "cn=usersgroup,ou=groups,o=taskanatest"), + new AccessIdResource("DevelopersGroup", "cn=developersgroup,ou=groups,o=taskanatest"), + new AccessIdResource("businessadmin", "cn=customersgroup,ou=groups,o=taskanatest"), + new AccessIdResource("user_domain_A", "cn=user_domain_a,ou=groups,o=taskanatest"), + new AccessIdResource("monitor", "cn=monitor,ou=groups,o=taskanatest"), + new AccessIdResource("user_domain_C", "cn=user_domain_c,ou=groups,o=taskanatest"), + new AccessIdResource("user_domain_D", "cn=user_domain_d,ou=groups,o=taskanatest"), + new AccessIdResource("admin", "cn=admin,ou=groups,o=taskanatest"), + new AccessIdResource( + "manager_domain_B", "cn=manager_domain_b,ou=groups,o=taskanatest"), + new AccessIdResource( + "manager_domain_C", "cn=manager_domain_c,ou=groups,o=taskanatest"), + new AccessIdResource( + "manager_domain_D", "cn=manager_domain_d,ou=groups,o=taskanatest"), + new AccessIdResource("teamlead_2", "cn=teamlead_2" + ",ou=groups,o=taskanatest"), + new AccessIdResource("teamlead_4", "cn=teamlead_4" + ",ou=groups,o=taskanatest"), + new AccessIdResource("team_3", "cn=team_3" + ",ou=groups,o=taskanatest"), + new AccessIdResource("team_4", "cn=team_4" + ",ou=groups,o=taskanatest"))); - new AccessIdResource("user_domain_A", "cn=user_domain_a,ou=groups,o=taskanatest"), - new AccessIdResource("monitor", "cn=monitor,ou=groups,o=taskanatest"), - new AccessIdResource("user_domain_C", "cn=user_domain_c,ou=groups,o=taskanatest"), - new AccessIdResource("user_domain_D", "cn=user_domain_d,ou=groups,o=taskanatest"), + @Override + public List findMatchingAccessId( + String searchFor, int maxNumberOfReturnedAccessIds) { + return findAcessIdResource(searchFor, maxNumberOfReturnedAccessIds, false); + } - new AccessIdResource("admin", "cn=admin,ou=groups,o=taskanatest"), - new AccessIdResource("manager_domain_B", "cn=manager_domain_b,ou=groups,o=taskanatest"), - new AccessIdResource("manager_domain_C", "cn=manager_domain_c,ou=groups,o=taskanatest"), - new AccessIdResource("manager_domain_D", "cn=manager_domain_d,ou=groups,o=taskanatest"), - - new AccessIdResource("teamlead_2", "cn=teamlead_2" + ",ou=groups,o=taskanatest"), - new AccessIdResource("teamlead_4", "cn=teamlead_4" + ",ou=groups,o=taskanatest"), - new AccessIdResource("team_3", "cn=team_3" + ",ou=groups,o=taskanatest"), - new AccessIdResource("team_4", "cn=team_4" + ",ou=groups,o=taskanatest"))); - - @Override - public List findMatchingAccessId(String searchFor, int maxNumberOfReturnedAccessIds) { - return findAcessIdResource(searchFor, maxNumberOfReturnedAccessIds, false); + @Override + public List findGroupsOfUser( + String searchFor, int maxNumberOfReturnedAccessIds) { + if (users == null) { + addUsersToGroups(); } + return findAcessIdResource(searchFor, maxNumberOfReturnedAccessIds, true); + } - @Override - public List findGroupsOfUser(String searchFor, int maxNumberOfReturnedAccessIds) { - if (users == null) { - addUsersToGroups(); - } - return findAcessIdResource(searchFor, maxNumberOfReturnedAccessIds, true); - } + @Override + public List validateAccessId(String accessId) { + return accessIds.stream() + .filter(t -> (t.getAccessId().equalsIgnoreCase(accessId.toLowerCase()))) + .collect(Collectors.toList()); + } - @Override - public List validateAccessId(String accessId) { - return accessIds.stream() - .filter(t -> (t.getAccessId().equalsIgnoreCase(accessId.toLowerCase()))) - .collect(Collectors.toList()); - } - - private List findAcessIdResource(String searchFor, int maxNumberOfReturnedAccessIds, - boolean groupMember) { - List usersAndGroups = accessIds.stream() - .filter(t -> (t.getName().toLowerCase().contains(searchFor.toLowerCase()) - || t.getAccessId().toLowerCase().contains(searchFor.toLowerCase()))) + private List findAcessIdResource( + String searchFor, int maxNumberOfReturnedAccessIds, boolean groupMember) { + List usersAndGroups = + accessIds.stream() + .filter( + t -> + (t.getName().toLowerCase().contains(searchFor.toLowerCase()) + || t.getAccessId().toLowerCase().contains(searchFor.toLowerCase()))) .collect(Collectors.toList()); - List usersAndGroupsAux = new ArrayList<>(usersAndGroups); - if (groupMember) { - usersAndGroupsAux.forEach(item -> { - if (users.get(item) != null) { - usersAndGroups.addAll(users.get(item)); - } - }); - } - - usersAndGroups.sort((AccessIdResource a, AccessIdResource b) -> { - return a.getAccessId().compareToIgnoreCase(b.getAccessId()); - }); - - List result = usersAndGroups.subList(0, - Math.min(usersAndGroups.size(), maxNumberOfReturnedAccessIds)); - - return result; + List usersAndGroupsAux = new ArrayList<>(usersAndGroups); + if (groupMember) { + usersAndGroupsAux.forEach( + item -> { + if (users.get(item) != null) { + usersAndGroups.addAll(users.get(item)); + } + }); } - private void addUsersToGroups() { - List groups = new ArrayList<>(); - users = new HashMap<>(); - - accessIds.forEach(item -> { - if (!item.getAccessId().contains("ou=groups")) { - users.put(item, new ArrayList<>()); - } else { - groups.add(item); - } + usersAndGroups.sort( + (AccessIdResource a, AccessIdResource b) -> { + return a.getAccessId().compareToIgnoreCase(b.getAccessId()); }); - int groupNumber = 0; - List group0 = new ArrayList<>(), group1 = new ArrayList<>(), group2 = new ArrayList<>(), group3 = new ArrayList<>(); + List result = + usersAndGroups.subList(0, Math.min(usersAndGroups.size(), maxNumberOfReturnedAccessIds)); - for (AccessIdResource group : groups) { - switch (groupNumber) { - case 0: - group0.add(group); - break; - case 1: - group1.add(group); - break; - case 2: - group2.add(group); - break; - case 3: - group3.add(group); - break; - default: - break; - } - groupNumber = (groupNumber + 1) % 4; - } + return result; + } - int countUser = 0; - for (AccessIdResource item : accessIds) { - if (!item.getAccessId().contains("ou=groups")) { - switch (countUser) { - case 0: - users.put(item, group0); - break; - case 1: - users.put(item, group1); - break; - case 2: - users.put(item, group2); - break; - case 3: - users.put(item, group3); - break; - default: - break; - } - } - countUser = (countUser + 1) % 4; - } + private void addUsersToGroups() { + List groups = new ArrayList<>(); + users = new HashMap<>(); + + accessIds.forEach( + item -> { + if (!item.getAccessId().contains("ou=groups")) { + users.put(item, new ArrayList<>()); + } else { + groups.add(item); + } + }); + + int groupNumber = 0; + List group0 = new ArrayList<>(), + group1 = new ArrayList<>(), + group2 = new ArrayList<>(), + group3 = new ArrayList<>(); + + for (AccessIdResource group : groups) { + switch (groupNumber) { + case 0: + group0.add(group); + break; + case 1: + group1.add(group); + break; + case 2: + group2.add(group); + break; + case 3: + group3.add(group); + break; + default: + break; + } + groupNumber = (groupNumber + 1) % 4; } + int countUser = 0; + for (AccessIdResource item : accessIds) { + if (!item.getAccessId().contains("ou=groups")) { + switch (countUser) { + case 0: + users.put(item, group0); + break; + case 1: + users.put(item, group1); + break; + case 2: + users.put(item, group2); + break; + case 3: + users.put(item, group3); + break; + default: + break; + } + } + countUser = (countUser + 1) % 4; + } + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/ClassificationControllerIntTest.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/ClassificationControllerIntTest.java index 78a0cd4c3..2c4cf1690 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/ClassificationControllerIntTest.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/ClassificationControllerIntTest.java @@ -6,7 +6,6 @@ import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.IOException; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -34,219 +33,253 @@ import pro.taskana.rest.resource.ClassificationSummaryResource; @TaskanaSpringBootTest class ClassificationControllerIntTest { - @Autowired RestHelper restHelper; + static RestTemplate template = RestHelper.getRestTemplate(); + @Autowired RestHelper restHelper; - static RestTemplate template = RestHelper.getRestTemplate(); - - @Test - void testGetAllClassifications() { - ResponseEntity response = template.exchange( - restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), HttpMethod.GET, restHelper.defaultRequest(), - ParameterizedTypeReference.forType(ClassificationSummaryListResource.class)); - assertNotNull(response.getBody().getLink(Link.REL_SELF)); - } - - @Test - void testGetAllClassificationsFilterByCustomAttribute() { - ResponseEntity response = template.exchange( - restHelper.toUrl(Mapping.URL_CLASSIFICATIONS) + "?domain=DOMAIN_A&custom-1-like=RVNR", HttpMethod.GET, + @Test + void testGetAllClassifications() { + ResponseEntity response = + template.exchange( + restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), + HttpMethod.GET, restHelper.defaultRequest(), ParameterizedTypeReference.forType(ClassificationSummaryListResource.class)); - assertNotNull(response.getBody().getLink(Link.REL_SELF)); - assertEquals(13, response.getBody().getContent().size()); - } + assertNotNull(response.getBody().getLink(Link.REL_SELF)); + } - @Test - void testGetAllClassificationsKeepingFilters() { - ResponseEntity response = template.exchange( - restHelper.toUrl(Mapping.URL_CLASSIFICATIONS) + "?domain=DOMAIN_A&sort-by=key&order=asc", HttpMethod.GET, + @Test + void testGetAllClassificationsFilterByCustomAttribute() { + ResponseEntity response = + template.exchange( + restHelper.toUrl(Mapping.URL_CLASSIFICATIONS) + "?domain=DOMAIN_A&custom-1-like=RVNR", + HttpMethod.GET, restHelper.defaultRequest(), ParameterizedTypeReference.forType(ClassificationSummaryListResource.class)); - assertNotNull(response.getBody().getLink(Link.REL_SELF)); - assertTrue(response.getBody() + assertNotNull(response.getBody().getLink(Link.REL_SELF)); + assertEquals(13, response.getBody().getContent().size()); + } + + @Test + void testGetAllClassificationsKeepingFilters() { + ResponseEntity response = + template.exchange( + restHelper.toUrl(Mapping.URL_CLASSIFICATIONS) + + "?domain=DOMAIN_A&sort-by=key&order=asc", + HttpMethod.GET, + restHelper.defaultRequest(), + ParameterizedTypeReference.forType(ClassificationSummaryListResource.class)); + assertNotNull(response.getBody().getLink(Link.REL_SELF)); + assertTrue( + response + .getBody() .getLink(Link.REL_SELF) .getHref() .endsWith("/api/v1/classifications?domain=DOMAIN_A&sort-by=key&order=asc")); - assertEquals(17, response.getBody().getContent().size()); - assertEquals("A12", response.getBody().getContent().iterator().next().key); - } + assertEquals(17, response.getBody().getContent().size()); + assertEquals("A12", response.getBody().getContent().iterator().next().key); + } - @Test - void testGetSecondPageSortedByKey() { - ResponseEntity response = template.exchange( - restHelper.toUrl(Mapping.URL_CLASSIFICATIONS) + "?domain=DOMAIN_A&sort-by=key&order=asc&page=2&page-size=5", + @Test + void testGetSecondPageSortedByKey() { + ResponseEntity response = + template.exchange( + restHelper.toUrl(Mapping.URL_CLASSIFICATIONS) + + "?domain=DOMAIN_A&sort-by=key&order=asc&page=2&page-size=5", HttpMethod.GET, restHelper.defaultRequest(), ParameterizedTypeReference.forType(ClassificationSummaryListResource.class)); - assertEquals(5, response.getBody().getContent().size()); - assertEquals("L1050", response.getBody().getContent().iterator().next().key); - assertNotNull(response.getBody().getLink(Link.REL_SELF)); - assertTrue(response.getBody() + assertEquals(5, response.getBody().getContent().size()); + assertEquals("L1050", response.getBody().getContent().iterator().next().key); + assertNotNull(response.getBody().getLink(Link.REL_SELF)); + assertTrue( + response + .getBody() .getLink(Link.REL_SELF) .getHref() - .endsWith("/api/v1/classifications?domain=DOMAIN_A&sort-by=key&order=asc&page=2&page-size=5")); - assertNotNull(response.getBody().getLink(Link.REL_FIRST)); - assertNotNull(response.getBody().getLink(Link.REL_LAST)); - assertNotNull(response.getBody().getLink(Link.REL_NEXT)); - assertNotNull(response.getBody().getLink(Link.REL_PREVIOUS)); - } + .endsWith( + "/api/v1/classifications?domain=DOMAIN_A&sort-by=key&order=asc&page=2&page-size=5")); + assertNotNull(response.getBody().getLink(Link.REL_FIRST)); + assertNotNull(response.getBody().getLink(Link.REL_LAST)); + assertNotNull(response.getBody().getLink(Link.REL_NEXT)); + assertNotNull(response.getBody().getLink(Link.REL_PREVIOUS)); + } - @Test - @DirtiesContext - void testCreateClassification() { - String newClassification = "{\"classificationId\":\"\",\"category\":\"MANUAL\",\"domain\":\"DOMAIN_A\",\"key\":\"NEW_CLASS\",\"name\":\"new classification\",\"type\":\"TASK\"}"; + @Test + @DirtiesContext + void testCreateClassification() { + String newClassification = + "{\"classificationId\":\"\",\"category\":\"MANUAL\",\"domain\":\"DOMAIN_A\",\"key\":\"NEW_CLASS\",\"name\":\"new classification\",\"type\":\"TASK\"}"; - ResponseEntity responseEntity = template.exchange( + ResponseEntity responseEntity = + template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), HttpMethod.POST, new HttpEntity<>(newClassification, restHelper.getHeaders()), - ParameterizedTypeReference.forType(ClassificationResource.class) - ); + ParameterizedTypeReference.forType(ClassificationResource.class)); - assertNotNull(responseEntity); - assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); + assertNotNull(responseEntity); + assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); - newClassification = "{\"classificationId\":\"\",\"category\":\"MANUAL\",\"domain\":\"DOMAIN_A\",\"key\":\"NEW_CLASS_2\",\"name\":\"new classification\",\"type\":\"TASK\"}"; + newClassification = + "{\"classificationId\":\"\",\"category\":\"MANUAL\",\"domain\":\"DOMAIN_A\",\"key\":\"NEW_CLASS_2\",\"name\":\"new classification\",\"type\":\"TASK\"}"; - responseEntity = template.exchange(restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), - HttpMethod.POST, - new HttpEntity<>(newClassification, restHelper.getHeaders()), - ParameterizedTypeReference.forType(ClassificationResource.class) - ); - - assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); - } - - @Test - @DirtiesContext - void testCreateClassificationWithParentId() { - String newClassification = "{\"classificationId\":\"\",\"category\":\"MANUAL\",\"domain\":\"DOMAIN_B\",\"key\":\"NEW_CLASS_P1\",\"name\":\"new classification\",\"type\":\"TASK\",\"parentId\":\"CLI:200000000000000000000000000000000015\"}"; - - ResponseEntity responseEntity = template.exchange( + responseEntity = + template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), HttpMethod.POST, new HttpEntity<>(newClassification, restHelper.getHeaders()), - ParameterizedTypeReference.forType(ClassificationResource.class) - ); + ParameterizedTypeReference.forType(ClassificationResource.class)); - assertNotNull(responseEntity); - assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); + assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); + } - } + @Test + @DirtiesContext + void testCreateClassificationWithParentId() { + String newClassification = + "{\"classificationId\":\"\",\"category\":\"MANUAL\",\"domain\":\"DOMAIN_B\",\"key\":\"NEW_CLASS_P1\",\"name\":\"new classification\",\"type\":\"TASK\",\"parentId\":\"CLI:200000000000000000000000000000000015\"}"; - @Test - @DirtiesContext - void testCreateClassificationWithParentKey() { - String newClassification = "{\"classificationId\":\"\",\"category\":\"MANUAL\",\"domain\":\"DOMAIN_B\",\"key\":\"NEW_CLASS_P2\",\"name\":\"new classification\",\"type\":\"TASK\",\"parentKey\":\"T2100\"}"; - - ResponseEntity responseEntity = template.exchange( + ResponseEntity responseEntity = + template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), HttpMethod.POST, new HttpEntity<>(newClassification, restHelper.getHeaders()), - ParameterizedTypeReference.forType(ClassificationResource.class) - ); + ParameterizedTypeReference.forType(ClassificationResource.class)); - assertNotNull(responseEntity); - assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); - } + assertNotNull(responseEntity); + assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); + } - @Test - @DirtiesContext - void testCreateClassificationWithParentKeyInDOMAIN_AShouldCreateAClassificationInRootDomain() - throws IOException { - String newClassification = "{\"classificationId\":\"\",\"category\":\"MANUAL\",\"domain\":\"DOMAIN_A\",\"key\":\"NEW_CLASS_P2\",\"name\":\"new classification\",\"type\":\"TASK\",\"parentKey\":\"T2100\"}"; + @Test + @DirtiesContext + void testCreateClassificationWithParentKey() { + String newClassification = + "{\"classificationId\":\"\",\"category\":\"MANUAL\",\"domain\":\"DOMAIN_B\",\"key\":\"NEW_CLASS_P2\",\"name\":\"new classification\",\"type\":\"TASK\",\"parentKey\":\"T2100\"}"; - ResponseEntity responseEntity = template.exchange( + ResponseEntity responseEntity = + template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), HttpMethod.POST, new HttpEntity<>(newClassification, restHelper.getHeaders()), - ParameterizedTypeReference.forType(ClassificationResource.class) - ); + ParameterizedTypeReference.forType(ClassificationResource.class)); - assertNotNull(responseEntity); - assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); + assertNotNull(responseEntity); + assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); + } - ResponseEntity response = template.exchange( - restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), HttpMethod.GET, + @Test + @DirtiesContext + void testCreateClassificationWithParentKeyInDOMAIN_AShouldCreateAClassificationInRootDomain() + throws IOException { + String newClassification = + "{\"classificationId\":\"\",\"category\":\"MANUAL\",\"domain\":\"DOMAIN_A\",\"key\":\"NEW_CLASS_P2\",\"name\":\"new classification\",\"type\":\"TASK\",\"parentKey\":\"T2100\"}"; + + ResponseEntity responseEntity = + template.exchange( + restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), + HttpMethod.POST, + new HttpEntity<>(newClassification, restHelper.getHeaders()), + ParameterizedTypeReference.forType(ClassificationResource.class)); + + assertNotNull(responseEntity); + assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); + + ResponseEntity response = + template.exchange( + restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), + HttpMethod.GET, restHelper.defaultRequest(), ParameterizedTypeReference.forType(ClassificationSummaryListResource.class)); - assertNotNull(response.getBody().getLink(Link.REL_SELF)); - boolean foundClassificationCreated = false; - for (ClassificationSummaryResource classification : response.getBody().getContent()) { - if ("NEW_CLASS_P2".equals(classification.getKey()) && "".equals(classification.getDomain()) - && "T2100".equals(classification.getParentKey())) { - foundClassificationCreated = true; - } - } - - assertEquals(true, foundClassificationCreated); + assertNotNull(response.getBody().getLink(Link.REL_SELF)); + boolean foundClassificationCreated = false; + for (ClassificationSummaryResource classification : response.getBody().getContent()) { + if ("NEW_CLASS_P2".equals(classification.getKey()) + && "".equals(classification.getDomain()) + && "T2100".equals(classification.getParentKey())) { + foundClassificationCreated = true; + } } - @Test - @DirtiesContext - void testReturn400IfCreateClassificationWithIncompatibleParentIdAndKey() throws IOException { - String newClassification = "{\"classificationId\":\"\",\"category\":\"MANUAL\",\"domain\":\"DOMAIN_B\",\"key\":\"NEW_CLASS_P3\",\"name\":\"new classification\",\"type\":\"TASK\",\"parentId\":\"CLI:200000000000000000000000000000000015\",\"parentKey\":\"T2000\"}"; + assertEquals(true, foundClassificationCreated); + } - HttpClientErrorException e = Assertions.assertThrows(HttpClientErrorException.class, () -> template.exchange( - restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), - HttpMethod.POST, - new HttpEntity<>(newClassification, restHelper.getHeaders()), - ParameterizedTypeReference.forType(ClassificationResource.class) - )); + @Test + @DirtiesContext + void testReturn400IfCreateClassificationWithIncompatibleParentIdAndKey() throws IOException { + String newClassification = + "{\"classificationId\":\"\",\"category\":\"MANUAL\",\"domain\":\"DOMAIN_B\",\"key\":\"NEW_CLASS_P3\",\"name\":\"new classification\",\"type\":\"TASK\",\"parentId\":\"CLI:200000000000000000000000000000000015\",\"parentKey\":\"T2000\"}"; - assertNotNull(e); - assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); - } + HttpClientErrorException e = + Assertions.assertThrows( + HttpClientErrorException.class, + () -> + template.exchange( + restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), + HttpMethod.POST, + new HttpEntity<>(newClassification, restHelper.getHeaders()), + ParameterizedTypeReference.forType(ClassificationResource.class))); - @Test - @DirtiesContext - void testCreateClassificationWithClassificationIdReturnsError400() throws IOException { - String newClassification = "{\"classificationId\":\"someId\",\"category\":\"MANUAL\",\"domain\":\"DOMAIN_A\",\"key\":\"NEW_CLASS\",\"name\":\"new classification\",\"type\":\"TASK\"}"; + assertNotNull(e); + assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); + } - HttpClientErrorException e = Assertions.assertThrows(HttpClientErrorException.class, () -> template.exchange( - restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), - HttpMethod.POST, - new HttpEntity<>(newClassification, restHelper.getHeaders()), - ParameterizedTypeReference.forType(ClassificationResource.class) - )); + @Test + @DirtiesContext + void testCreateClassificationWithClassificationIdReturnsError400() throws IOException { + String newClassification = + "{\"classificationId\":\"someId\",\"category\":\"MANUAL\",\"domain\":\"DOMAIN_A\",\"key\":\"NEW_CLASS\",\"name\":\"new classification\",\"type\":\"TASK\"}"; - assertNotNull(e); - assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); - } + HttpClientErrorException e = + Assertions.assertThrows( + HttpClientErrorException.class, + () -> + template.exchange( + restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), + HttpMethod.POST, + new HttpEntity<>(newClassification, restHelper.getHeaders()), + ParameterizedTypeReference.forType(ClassificationResource.class))); - @Test - void testGetClassificationWithSpecialCharacter() { + assertNotNull(e); + assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); + } - HttpEntity request = new HttpEntity(restHelper.getHeadersAdmin()); - ResponseEntity response = template.exchange( - restHelper.toUrl(Mapping.URL_CLASSIFICATIONS_ID, "CLI:100000000000000000000000000000000009"), + @Test + void testGetClassificationWithSpecialCharacter() { + + HttpEntity request = new HttpEntity(restHelper.getHeadersAdmin()); + ResponseEntity response = + template.exchange( + restHelper.toUrl( + Mapping.URL_CLASSIFICATIONS_ID, "CLI:100000000000000000000000000000000009"), HttpMethod.GET, request, - ParameterizedTypeReference.forType(ClassificationSummaryResource.class) - ); - assertEquals("Zustimmungserklärung", response.getBody().name); - } + ParameterizedTypeReference.forType(ClassificationSummaryResource.class)); + assertEquals("Zustimmungserklärung", response.getBody().name); + } - @Test - @DirtiesContext - void testDeleteClassification() { - HttpEntity request = new HttpEntity(restHelper.getHeaders()); + @Test + @DirtiesContext + void testDeleteClassification() { + HttpEntity request = new HttpEntity(restHelper.getHeaders()); - ResponseEntity response = template.exchange( - restHelper.toUrl(Mapping.URL_CLASSIFICATIONS_ID, "CLI:200000000000000000000000000000000004"), + ResponseEntity response = + template.exchange( + restHelper.toUrl( + Mapping.URL_CLASSIFICATIONS_ID, "CLI:200000000000000000000000000000000004"), HttpMethod.DELETE, request, - ParameterizedTypeReference.forType(ClassificationSummaryResource.class) - ); - assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + ParameterizedTypeReference.forType(ClassificationSummaryResource.class)); + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); - assertThrows(HttpClientErrorException.class, () -> { - template.exchange( - restHelper.toUrl(Mapping.URL_CLASSIFICATIONS_ID, "CLI:200000000000000000000000000000000004"), - HttpMethod.GET, - request, - ParameterizedTypeReference.forType(ClassificationSummaryResource.class) - ); + assertThrows( + HttpClientErrorException.class, + () -> { + template.exchange( + restHelper.toUrl( + Mapping.URL_CLASSIFICATIONS_ID, "CLI:200000000000000000000000000000000004"), + HttpMethod.GET, + request, + ParameterizedTypeReference.forType(ClassificationSummaryResource.class)); }); - } + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/ClassificationDefinitionControllerIntTest.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/ClassificationDefinitionControllerIntTest.java index 9e0b863ec..423dff231 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/ClassificationDefinitionControllerIntTest.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/ClassificationDefinitionControllerIntTest.java @@ -8,6 +8,7 @@ import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -15,7 +16,6 @@ import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; - import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.slf4j.Logger; @@ -34,384 +34,404 @@ import org.springframework.util.MultiValueMap; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; -import com.fasterxml.jackson.databind.ObjectMapper; - import pro.taskana.RestHelper; import pro.taskana.TaskanaSpringBootTest; import pro.taskana.rest.resource.ClassificationResource; import pro.taskana.rest.resource.ClassificationSummaryListResource; import pro.taskana.rest.resource.ClassificationSummaryResource; -/** - * Test classification definitions. - */ - +/** Test classification definitions. */ @TaskanaSpringBootTest class ClassificationDefinitionControllerIntTest { - private static final Logger LOGGER = LoggerFactory.getLogger(ClassificationController.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ClassificationController.class); + private static RestTemplate template; + @Autowired RestHelper restHelper; + private ObjectMapper objMapper = new ObjectMapper(); - private ObjectMapper objMapper = new ObjectMapper(); + @BeforeAll + static void init() { + template = RestHelper.getRestTemplate(); + } - @Autowired RestHelper restHelper; - - private static RestTemplate template; - - @BeforeAll - static void init() { - template = RestHelper.getRestTemplate(); - } - - @Test - void testExportClassifications() { - ResponseEntity response = template.exchange( + @Test + void testExportClassifications() { + ResponseEntity response = + template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONDEFINITION) + "?domain=DOMAIN_B", - HttpMethod.GET, restHelper.defaultRequest(), + HttpMethod.GET, + restHelper.defaultRequest(), ParameterizedTypeReference.forType(ClassificationResource[].class)); - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertTrue(response.getBody().length >= 5); - assertTrue(response.getBody().length <= 7); - assertThat(response.getBody()[0], instanceOf(ClassificationResource.class)); - } + assertEquals(HttpStatus.OK, response.getStatusCode()); + assertTrue(response.getBody().length >= 5); + assertTrue(response.getBody().length <= 7); + assertThat(response.getBody()[0], instanceOf(ClassificationResource.class)); + } - @Test - void testExportClassificationsFromWrongDomain() { - ResponseEntity response = template.exchange( + @Test + void testExportClassificationsFromWrongDomain() { + ResponseEntity response = + template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONDEFINITION) + "?domain=ADdfe", - HttpMethod.GET, restHelper.defaultRequest(), + HttpMethod.GET, + restHelper.defaultRequest(), ParameterizedTypeReference.forType(ClassificationResource[].class)); - assertEquals(0, response.getBody().length); + assertEquals(0, response.getBody().length); + } + + @Test + void testImportFilledClassification() throws IOException { + ClassificationResource classification = new ClassificationResource(); + classification.setClassificationId("classificationId_"); + classification.setKey("key drelf"); + classification.setParentId("CLI:100000000000000000000000000000000016"); + classification.setParentKey("T2000"); + classification.setCategory("MANUAL"); + classification.setType("TASK"); + classification.setDomain("DOMAIN_A"); + classification.setIsValidInDomain(true); + classification.setCreated("2016-05-12T10:12:12.12Z"); + classification.setModified("2018-05-12T10:12:12.12Z"); + classification.setName("name"); + classification.setDescription("description"); + classification.setPriority(4); + classification.setServiceLevel("P2D"); + classification.setApplicationEntryPoint("entry1"); + classification.setCustom1("custom"); + classification.setCustom2("custom"); + classification.setCustom3("custom"); + classification.setCustom4("custom"); + classification.setCustom5("custom"); + classification.setCustom6("custom"); + classification.setCustom7("custom"); + classification.setCustom8("custom"); + + List clList = new ArrayList<>(); + clList.add(objMapper.writeValueAsString(classification)); + + ResponseEntity response = importRequest(clList); + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + } + + @Test + void testFailureWhenKeyIsMissing() throws IOException { + ClassificationResource classification = new ClassificationResource(); + classification.setDomain("DOMAIN_A"); + List clList = new ArrayList<>(); + clList.add(objMapper.writeValueAsString(classification)); + + try { + importRequest(clList); + } catch (HttpClientErrorException e) { + assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); } + } - @Test - void testImportFilledClassification() throws IOException { - ClassificationResource classification = new ClassificationResource(); - classification.setClassificationId("classificationId_"); - classification.setKey("key drelf"); - classification.setParentId("CLI:100000000000000000000000000000000016"); - classification.setParentKey("T2000"); - classification.setCategory("MANUAL"); - classification.setType("TASK"); - classification.setDomain("DOMAIN_A"); - classification.setIsValidInDomain(true); - classification.setCreated("2016-05-12T10:12:12.12Z"); - classification.setModified("2018-05-12T10:12:12.12Z"); - classification.setName("name"); - classification.setDescription("description"); - classification.setPriority(4); - classification.setServiceLevel("P2D"); - classification.setApplicationEntryPoint("entry1"); - classification.setCustom1("custom"); - classification.setCustom2("custom"); - classification.setCustom3("custom"); - classification.setCustom4("custom"); - classification.setCustom5("custom"); - classification.setCustom6("custom"); - classification.setCustom7("custom"); - classification.setCustom8("custom"); + @Test + void testFailureWhenDomainIsMissing() throws IOException { + ClassificationResource classification = new ClassificationResource(); + classification.setKey("one"); + List clList = new ArrayList<>(); + clList.add(objMapper.writeValueAsString(classification)); - List clList = new ArrayList<>(); - clList.add(objMapper.writeValueAsString(classification)); - - ResponseEntity response = importRequest(clList); - assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + try { + importRequest(clList); + } catch (HttpClientErrorException e) { + assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); } + } - @Test - void testFailureWhenKeyIsMissing() throws IOException { - ClassificationResource classification = new ClassificationResource(); - classification.setDomain("DOMAIN_A"); - List clList = new ArrayList<>(); - clList.add(objMapper.writeValueAsString(classification)); + @Test + void testFailureWhenUpdatingTypeOfExistingClassification() throws IOException { + ClassificationSummaryResource classification = + this.getClassificationWithKeyAndDomain("T6310", ""); + classification.setType("DOCUMENT"); + List clList = new ArrayList<>(); + clList.add(objMapper.writeValueAsString(classification)); - try { - importRequest(clList); - } catch (HttpClientErrorException e) { - assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); - } + try { + importRequest(clList); + } catch (HttpClientErrorException e) { + assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); } + } - @Test - void testFailureWhenDomainIsMissing() throws IOException { - ClassificationResource classification = new ClassificationResource(); - classification.setKey("one"); - List clList = new ArrayList<>(); - clList.add(objMapper.writeValueAsString(classification)); + @Test + void testImportMultipleClassifications() throws IOException { + ClassificationResource classification1 = + this.createClassification("id1", "ImportKey1", "DOMAIN_A", null, null); + String c1 = objMapper.writeValueAsString(classification1); - try { - importRequest(clList); - } catch (HttpClientErrorException e) { - assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); - } + ClassificationResource classification2 = + this.createClassification( + "id2", "ImportKey2", "DOMAIN_A", "CLI:100000000000000000000000000000000016", "T2000"); + classification2.setCategory("MANUAL"); + classification2.setType("TASK"); + classification2.setIsValidInDomain(true); + classification2.setCreated("2016-05-12T10:12:12.12Z"); + classification2.setModified("2018-05-12T10:12:12.12Z"); + classification2.setName("name"); + classification2.setDescription("description"); + classification2.setPriority(4); + classification2.setServiceLevel("P2D"); + classification2.setApplicationEntryPoint("entry1"); + String c2 = objMapper.writeValueAsString(classification2); + + List clList = new ArrayList<>(); + clList.add(c1); + clList.add(c2); + + ResponseEntity response = importRequest(clList); + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + } + + @Test + void testImportDuplicateClassification() throws IOException { + ClassificationResource classification1 = new ClassificationResource(); + classification1.setClassificationId("id1"); + classification1.setKey("ImportKey3"); + classification1.setDomain("DOMAIN_A"); + String c1 = objMapper.writeValueAsString(classification1); + + List clList = new ArrayList<>(); + clList.add(c1); + clList.add(c1); + + try { + importRequest(clList); + } catch (HttpClientErrorException e) { + assertEquals(HttpStatus.CONFLICT, e.getStatusCode()); } + } - @Test - void testFailureWhenUpdatingTypeOfExistingClassification() throws IOException { - ClassificationSummaryResource classification = this.getClassificationWithKeyAndDomain("T6310", ""); - classification.setType("DOCUMENT"); - List clList = new ArrayList<>(); - clList.add(objMapper.writeValueAsString(classification)); + @Test + void testInsertExistingClassificationWithOlderTimestamp() throws IOException { + ClassificationSummaryResource existingClassification = + getClassificationWithKeyAndDomain("L110107", "DOMAIN_A"); + existingClassification.setName("first new Name"); + List clList = new ArrayList<>(); + clList.add(objMapper.writeValueAsString(existingClassification)); - try { - importRequest(clList); - } catch (HttpClientErrorException e) { - assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); - } + ResponseEntity response = importRequest(clList); + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + + existingClassification.setName("second new Name"); + clList = new ArrayList<>(); + clList.add(objMapper.writeValueAsString(existingClassification)); + + response = importRequest(clList); + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + + ClassificationSummaryResource testClassification = + this.getClassificationWithKeyAndDomain("L110107", "DOMAIN_A"); + assertEquals("second new Name", testClassification.getName()); + } + + @Test + void testHookExistingChildToNewParent() throws IOException { + ClassificationResource newClassification = + createClassification("new Classification", "newClass", "DOMAIN_A", null, "L11010"); + ClassificationSummaryResource existingClassification = + getClassificationWithKeyAndDomain("L110102", "DOMAIN_A"); + existingClassification.setParentId("new Classification"); + existingClassification.setParentKey("newClass"); + + List clList = new ArrayList<>(); + clList.add(objMapper.writeValueAsString(existingClassification)); + clList.add(objMapper.writeValueAsString(newClassification)); + + ResponseEntity response = importRequest(clList); + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + + ClassificationSummaryResource parentCl = + getClassificationWithKeyAndDomain("L11010", "DOMAIN_A"); + ClassificationSummaryResource testNewCl = + getClassificationWithKeyAndDomain("newClass", "DOMAIN_A"); + ClassificationSummaryResource testExistingCl = + getClassificationWithKeyAndDomain("L110102", "DOMAIN_A"); + + assertNotNull(parentCl); + assertNotNull(testNewCl); + assertNotNull(testExistingCl); + assertEquals(testNewCl.getClassificationId(), testExistingCl.getParentId()); + assertEquals(parentCl.getClassificationId(), testNewCl.getParentId()); + } + + @Test + void testImportParentAndChildClassification() throws IOException { + ClassificationResource classification1 = + this.createClassification("parentId", "ImportKey6", "DOMAIN_A", null, null); + String c1 = objMapper.writeValueAsString(classification1); + + ClassificationResource classification2 = + this.createClassification("childId1", "ImportKey7", "DOMAIN_A", null, "ImportKey6"); + String c21 = objMapper.writeValueAsString(classification2); + classification2 = + this.createClassification("childId2", "ImportKey8", "DOMAIN_A", "parentId", null); + String c22 = objMapper.writeValueAsString(classification2); + + ClassificationResource classification3 = + this.createClassification( + "grandchildId1", "ImportKey9", "DOMAIN_A", "childId1", "ImportKey7"); + String c31 = objMapper.writeValueAsString(classification3); + classification3 = + this.createClassification("grandchild2", "ImportKey10", "DOMAIN_A", null, "ImportKey7"); + String c32 = objMapper.writeValueAsString(classification3); + + List clList = new ArrayList<>(); + clList.add(c31); + clList.add(c32); + clList.add(c21); + clList.add(c22); + clList.add(c1); + + ResponseEntity response = importRequest(clList); + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + + ClassificationSummaryResource parentCl = + getClassificationWithKeyAndDomain("ImportKey6", "DOMAIN_A"); + ClassificationSummaryResource childCl = + getClassificationWithKeyAndDomain("ImportKey7", "DOMAIN_A"); + ClassificationSummaryResource grandchildCl = + getClassificationWithKeyAndDomain("ImportKey9", "DOMAIN_A"); + + assertNotNull(parentCl); + assertNotNull(childCl); + assertNotNull(grandchildCl); + assertEquals(childCl.getClassificationId(), grandchildCl.getParentId()); + assertEquals(parentCl.getClassificationId(), childCl.getParentId()); + } + + @Test + void testImportParentAndChildClassificationWithKey() throws IOException { + ClassificationResource classification1 = + createClassification("parent", "ImportKey11", "DOMAIN_A", null, null); + classification1.setCustom1("parent is correct"); + String parent = objMapper.writeValueAsString(classification1); + ClassificationResource classification2 = + createClassification("wrongParent", "ImportKey11", "DOMAIN_B", null, null); + String wrongParent = objMapper.writeValueAsString(classification2); + ClassificationResource classification3 = + createClassification("child", "ImportKey13", "DOMAIN_A", null, "ImportKey11"); + String child = objMapper.writeValueAsString(classification3); + + List clList = new ArrayList<>(); + clList.add(wrongParent); + clList.add(parent); + clList.add(child); + + ResponseEntity response = importRequest(clList); + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + + ClassificationSummaryResource rightParentCl = + getClassificationWithKeyAndDomain("ImportKey11", "DOMAIN_A"); + ClassificationSummaryResource wrongParentCl = + getClassificationWithKeyAndDomain("ImportKey11", "DOMAIN_B"); + ClassificationSummaryResource childCl = + getClassificationWithKeyAndDomain("ImportKey13", "DOMAIN_A"); + + assertNotNull(rightParentCl); + assertNotNull(wrongParentCl); + assertNotNull(childCl); + assertEquals(rightParentCl.getClassificationId(), childCl.getParentId()); + assertNotEquals(wrongParentCl.getClassificationId(), childCl.getParentId()); + } + + @Test + void testChangeParentByImportingExistingClassification() + throws IOException, InterruptedException { + ClassificationSummaryResource child1 = + this.getClassificationWithKeyAndDomain("L110105", "DOMAIN_A"); + assertEquals("L11010", child1.getParentKey()); + child1.setParentId("CLI:100000000000000000000000000000000002"); + child1.setParentKey("L10303"); + String withNewParent = objMapper.writeValueAsString(child1); + + ClassificationSummaryResource child2 = + this.getClassificationWithKeyAndDomain("L110107", "DOMAIN_A"); + assertEquals("L11010", child2.getParentKey()); + child2.setParentId(""); + child2.setParentKey(""); + String withoutParent = objMapper.writeValueAsString(child2); + + List clList = new ArrayList<>(); + clList.add(withNewParent); + clList.add(withoutParent); + + ResponseEntity response = importRequest(clList); + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + Thread.sleep(10); + LOGGER.debug("Wait 10 ms to give the system a chance to update"); + + ClassificationSummaryResource childWithNewParent = + this.getClassificationWithKeyAndDomain("L110105", "DOMAIN_A"); + assertEquals(child1.parentKey, childWithNewParent.parentKey); + + ClassificationSummaryResource childWithoutParent = + this.getClassificationWithKeyAndDomain("L110107", "DOMAIN_A"); + assertEquals(child2.parentId, childWithoutParent.parentId); + assertEquals(child2.parentKey, childWithoutParent.parentKey); + } + + @Test + void testFailOnImportDuplicates() throws IOException { + ClassificationSummaryResource classification = + this.getClassificationWithKeyAndDomain("L110105", "DOMAIN_A"); + String classificationString = objMapper.writeValueAsString(classification); + + List clList = new ArrayList<>(); + clList.add(classificationString); + clList.add(classificationString); + + try { + importRequest(clList); + fail("Expected http-Status 409"); + } catch (HttpClientErrorException e) { + assertEquals(HttpStatus.CONFLICT, e.getStatusCode()); } + } - @Test - void testImportMultipleClassifications() throws IOException { - ClassificationResource classification1 = this.createClassification("id1", "ImportKey1", "DOMAIN_A", null, null); - String c1 = objMapper.writeValueAsString(classification1); + private ClassificationResource createClassification( + String id, String key, String domain, String parentId, String parentKey) { + ClassificationResource classificationResource = new ClassificationResource(); + classificationResource.setClassificationId(id); + classificationResource.setKey(key); + classificationResource.setDomain(domain); + classificationResource.setParentId(parentId); + classificationResource.setParentKey(parentKey); + return classificationResource; + } - ClassificationResource classification2 = this.createClassification("id2", "ImportKey2", "DOMAIN_A", - "CLI:100000000000000000000000000000000016", "T2000"); - classification2.setCategory("MANUAL"); - classification2.setType("TASK"); - classification2.setIsValidInDomain(true); - classification2.setCreated("2016-05-12T10:12:12.12Z"); - classification2.setModified("2018-05-12T10:12:12.12Z"); - classification2.setName("name"); - classification2.setDescription("description"); - classification2.setPriority(4); - classification2.setServiceLevel("P2D"); - classification2.setApplicationEntryPoint("entry1"); - String c2 = objMapper.writeValueAsString(classification2); - - List clList = new ArrayList<>(); - clList.add(c1); - clList.add(c2); - - ResponseEntity response = importRequest(clList); - assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); - } - - @Test - void testImportDuplicateClassification() throws IOException { - ClassificationResource classification1 = new ClassificationResource(); - classification1.setClassificationId("id1"); - classification1.setKey("ImportKey3"); - classification1.setDomain("DOMAIN_A"); - String c1 = objMapper.writeValueAsString(classification1); - - List clList = new ArrayList<>(); - clList.add(c1); - clList.add(c1); - - try { - importRequest(clList); - } catch (HttpClientErrorException e) { - assertEquals(HttpStatus.CONFLICT, e.getStatusCode()); - } - } - - @Test - void testInsertExistingClassificationWithOlderTimestamp() throws IOException { - ClassificationSummaryResource existingClassification = getClassificationWithKeyAndDomain("L110107", "DOMAIN_A"); - existingClassification.setName("first new Name"); - List clList = new ArrayList<>(); - clList.add(objMapper.writeValueAsString(existingClassification)); - - ResponseEntity response = importRequest(clList); - assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); - - existingClassification.setName("second new Name"); - clList = new ArrayList<>(); - clList.add(objMapper.writeValueAsString(existingClassification)); - - response = importRequest(clList); - assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); - - ClassificationSummaryResource testClassification = this.getClassificationWithKeyAndDomain("L110107", - "DOMAIN_A"); - assertEquals("second new Name", testClassification.getName()); - } - - @Test - void testHookExistingChildToNewParent() throws IOException { - ClassificationResource newClassification = createClassification( - "new Classification", "newClass", "DOMAIN_A", null, "L11010"); - ClassificationSummaryResource existingClassification = getClassificationWithKeyAndDomain("L110102", "DOMAIN_A"); - existingClassification.setParentId("new Classification"); - existingClassification.setParentKey("newClass"); - - List clList = new ArrayList<>(); - clList.add(objMapper.writeValueAsString(existingClassification)); - clList.add(objMapper.writeValueAsString(newClassification)); - - ResponseEntity response = importRequest(clList); - assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); - - ClassificationSummaryResource parentCl = getClassificationWithKeyAndDomain("L11010", "DOMAIN_A"); - ClassificationSummaryResource testNewCl = getClassificationWithKeyAndDomain("newClass", "DOMAIN_A"); - ClassificationSummaryResource testExistingCl = getClassificationWithKeyAndDomain("L110102", "DOMAIN_A"); - - assertNotNull(parentCl); - assertNotNull(testNewCl); - assertNotNull(testExistingCl); - assertEquals(testNewCl.getClassificationId(), testExistingCl.getParentId()); - assertEquals(parentCl.getClassificationId(), testNewCl.getParentId()); - } - - @Test - void testImportParentAndChildClassification() throws IOException { - ClassificationResource classification1 = this.createClassification("parentId", "ImportKey6", "DOMAIN_A", null, - null); - String c1 = objMapper.writeValueAsString(classification1); - - ClassificationResource classification2 = this.createClassification("childId1", "ImportKey7", "DOMAIN_A", null, - "ImportKey6"); - String c21 = objMapper.writeValueAsString(classification2); - classification2 = this.createClassification("childId2", "ImportKey8", "DOMAIN_A", "parentId", null); - String c22 = objMapper.writeValueAsString(classification2); - - ClassificationResource classification3 = this.createClassification("grandchildId1", "ImportKey9", "DOMAIN_A", - "childId1", "ImportKey7"); - String c31 = objMapper.writeValueAsString(classification3); - classification3 = this.createClassification("grandchild2", "ImportKey10", "DOMAIN_A", null, "ImportKey7"); - String c32 = objMapper.writeValueAsString(classification3); - - List clList = new ArrayList<>(); - clList.add(c31); - clList.add(c32); - clList.add(c21); - clList.add(c22); - clList.add(c1); - - ResponseEntity response = importRequest(clList); - assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); - - ClassificationSummaryResource parentCl = getClassificationWithKeyAndDomain("ImportKey6", "DOMAIN_A"); - ClassificationSummaryResource childCl = getClassificationWithKeyAndDomain("ImportKey7", "DOMAIN_A"); - ClassificationSummaryResource grandchildCl = getClassificationWithKeyAndDomain("ImportKey9", "DOMAIN_A"); - - assertNotNull(parentCl); - assertNotNull(childCl); - assertNotNull(grandchildCl); - assertEquals(childCl.getClassificationId(), grandchildCl.getParentId()); - assertEquals(parentCl.getClassificationId(), childCl.getParentId()); - } - - @Test - void testImportParentAndChildClassificationWithKey() throws IOException { - ClassificationResource classification1 = createClassification("parent", "ImportKey11", "DOMAIN_A", null, null); - classification1.setCustom1("parent is correct"); - String parent = objMapper.writeValueAsString(classification1); - ClassificationResource classification2 = createClassification("wrongParent", "ImportKey11", "DOMAIN_B", null, - null); - String wrongParent = objMapper.writeValueAsString(classification2); - ClassificationResource classification3 = createClassification("child", "ImportKey13", "DOMAIN_A", null, - "ImportKey11"); - String child = objMapper.writeValueAsString(classification3); - - List clList = new ArrayList<>(); - clList.add(wrongParent); - clList.add(parent); - clList.add(child); - - ResponseEntity response = importRequest(clList); - assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); - - ClassificationSummaryResource rightParentCl = getClassificationWithKeyAndDomain("ImportKey11", "DOMAIN_A"); - ClassificationSummaryResource wrongParentCl = getClassificationWithKeyAndDomain("ImportKey11", "DOMAIN_B"); - ClassificationSummaryResource childCl = getClassificationWithKeyAndDomain("ImportKey13", "DOMAIN_A"); - - assertNotNull(rightParentCl); - assertNotNull(wrongParentCl); - assertNotNull(childCl); - assertEquals(rightParentCl.getClassificationId(), childCl.getParentId()); - assertNotEquals(wrongParentCl.getClassificationId(), childCl.getParentId()); - } - - @Test - void testChangeParentByImportingExistingClassification() throws IOException, InterruptedException { - ClassificationSummaryResource child1 = this.getClassificationWithKeyAndDomain("L110105", "DOMAIN_A"); - assertEquals("L11010", child1.getParentKey()); - child1.setParentId("CLI:100000000000000000000000000000000002"); - child1.setParentKey("L10303"); - String withNewParent = objMapper.writeValueAsString(child1); - - ClassificationSummaryResource child2 = this.getClassificationWithKeyAndDomain("L110107", "DOMAIN_A"); - assertEquals("L11010", child2.getParentKey()); - child2.setParentId(""); - child2.setParentKey(""); - String withoutParent = objMapper.writeValueAsString(child2); - - List clList = new ArrayList<>(); - clList.add(withNewParent); - clList.add(withoutParent); - - ResponseEntity response = importRequest(clList); - assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); - Thread.sleep(10); - LOGGER.debug("Wait 10 ms to give the system a chance to update"); - - ClassificationSummaryResource childWithNewParent = this.getClassificationWithKeyAndDomain("L110105", - "DOMAIN_A"); - assertEquals(child1.parentKey, childWithNewParent.parentKey); - - ClassificationSummaryResource childWithoutParent = this.getClassificationWithKeyAndDomain("L110107", - "DOMAIN_A"); - assertEquals(child2.parentId, childWithoutParent.parentId); - assertEquals(child2.parentKey, childWithoutParent.parentKey); - } - - @Test - void testFailOnImportDuplicates() throws IOException { - ClassificationSummaryResource classification = this.getClassificationWithKeyAndDomain("L110105", "DOMAIN_A"); - String classificationString = objMapper.writeValueAsString(classification); - - List clList = new ArrayList<>(); - clList.add(classificationString); - clList.add(classificationString); - - try { - importRequest(clList); - fail("Expected http-Status 409"); - } catch (HttpClientErrorException e) { - assertEquals(HttpStatus.CONFLICT, e.getStatusCode()); - } - } - - private ClassificationResource createClassification(String id, String key, String domain, String parentId, - String parentKey) { - ClassificationResource classificationResource = new ClassificationResource(); - classificationResource.setClassificationId(id); - classificationResource.setKey(key); - classificationResource.setDomain(domain); - classificationResource.setParentId(parentId); - classificationResource.setParentKey(parentKey); - return classificationResource; - } - - private ClassificationSummaryResource getClassificationWithKeyAndDomain(String key, String domain) { - LOGGER.debug("Request classification with key={} in domain={}", key, domain); - HttpEntity request = new HttpEntity(restHelper.getHeaders()); - ResponseEntity response = template.exchange( + private ClassificationSummaryResource getClassificationWithKeyAndDomain( + String key, String domain) { + LOGGER.debug("Request classification with key={} in domain={}", key, domain); + HttpEntity request = new HttpEntity(restHelper.getHeaders()); + ResponseEntity response = + template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS) + "?key=" + key + "&domain=" + domain, HttpMethod.GET, request, ParameterizedTypeReference.forType(ClassificationSummaryListResource.class)); - return response.getBody().getContent().toArray(new ClassificationSummaryResource[1])[0]; - } + return response.getBody().getContent().toArray(new ClassificationSummaryResource[1])[0]; + } - private ResponseEntity importRequest(List clList) throws IOException { - LOGGER.debug("Start Import"); - File tmpFile = File.createTempFile("test", ".tmp"); - OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(tmpFile), StandardCharsets.UTF_8); - writer.write(clList.toString()); - writer.close(); + private ResponseEntity importRequest(List clList) throws IOException { + LOGGER.debug("Start Import"); + File tmpFile = File.createTempFile("test", ".tmp"); + OutputStreamWriter writer = + new OutputStreamWriter(new FileOutputStream(tmpFile), StandardCharsets.UTF_8); + writer.write(clList.toString()); + writer.close(); - MultiValueMap body = new LinkedMultiValueMap<>(); + MultiValueMap body = new LinkedMultiValueMap<>(); - HttpHeaders headers = restHelper.getHeaders(); - headers.setContentType(MediaType.MULTIPART_FORM_DATA); - body.add("file", new FileSystemResource(tmpFile)); + HttpHeaders headers = restHelper.getHeaders(); + headers.setContentType(MediaType.MULTIPART_FORM_DATA); + body.add("file", new FileSystemResource(tmpFile)); - HttpEntity> requestEntity = new HttpEntity<>(body, headers); - String serverUrl = restHelper.toUrl(Mapping.URL_CLASSIFICATIONDEFINITION); - - return template.postForEntity(serverUrl, requestEntity, Void.class); - } + HttpEntity> requestEntity = new HttpEntity<>(body, headers); + String serverUrl = restHelper.toUrl(Mapping.URL_CLASSIFICATIONDEFINITION); + return template.postForEntity(serverUrl, requestEntity, Void.class); + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/ExampleDocumentationApp.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/ExampleDocumentationApp.java index 7a0a8eb31..ffc942b89 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/ExampleDocumentationApp.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/ExampleDocumentationApp.java @@ -1,10 +1,8 @@ package pro.taskana.rest; import java.sql.SQLException; - import javax.annotation.PostConstruct; import javax.sql.DataSource; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; @@ -23,54 +21,53 @@ import org.springframework.transaction.PlatformTransactionManager; import pro.taskana.ldap.LdapCacheTestImpl; import pro.taskana.sampledata.SampleDataGenerator; -/** - * Example Application to create the documentation. - */ +/** Example Application to create the documentation. */ @SpringBootApplication @EnableScheduling @ComponentScan(basePackages = "pro.taskana") @Import({RestConfiguration.class}) public class ExampleDocumentationApp { - @Value("${taskana.schemaName:TASKANA}") - private String schemaName; + @Value("${taskana.schemaName:TASKANA}") + private String schemaName; - @Autowired - private SampleDataGenerator sampleDataGenerator; + @Autowired private SampleDataGenerator sampleDataGenerator; - public static void main(String[] args) { - SpringApplication.run(ExampleDocumentationApp.class, args); - } + public static void main(String[] args) { + SpringApplication.run(ExampleDocumentationApp.class, args); + } - @Bean - @Primary - @ConfigurationProperties(prefix = "datasource") - public DataSourceProperties dataSourceProperties() { - DataSourceProperties props = new DataSourceProperties(); - props.setUrl("jdbc:h2:mem:taskana;IGNORECASE=TRUE;LOCK_MODE=0;INIT=CREATE SCHEMA IF NOT EXISTS " + schemaName); - return props; - } + @Bean + @Primary + @ConfigurationProperties(prefix = "datasource") + public DataSourceProperties dataSourceProperties() { + DataSourceProperties props = new DataSourceProperties(); + props.setUrl( + "jdbc:h2:mem:taskana;IGNORECASE=TRUE;LOCK_MODE=0;INIT=CREATE SCHEMA IF NOT EXISTS " + + schemaName); + return props; + } - @Bean - public DataSource dataSource(DataSourceProperties properties) { - return properties.initializeDataSourceBuilder().build(); - } + @Bean + public DataSource dataSource(DataSourceProperties properties) { + return properties.initializeDataSourceBuilder().build(); + } - @Bean - public PlatformTransactionManager txManager(DataSource dataSource) { - return new DataSourceTransactionManager(dataSource); - } + @Bean + public PlatformTransactionManager txManager(DataSource dataSource) { + return new DataSourceTransactionManager(dataSource); + } - @Bean - @DependsOn("getTaskanaEngine") // generate sample data after schema was inserted - public SampleDataGenerator generateSampleData(DataSource dataSource) { - sampleDataGenerator = new SampleDataGenerator(dataSource, schemaName); - return sampleDataGenerator; - } + @Bean + @DependsOn("getTaskanaEngine") // generate sample data after schema was inserted + public SampleDataGenerator generateSampleData(DataSource dataSource) { + sampleDataGenerator = new SampleDataGenerator(dataSource, schemaName); + return sampleDataGenerator; + } - @PostConstruct - private void init() throws SQLException { - AccessIdController.setLdapCache(new LdapCacheTestImpl()); - sampleDataGenerator.generateSampleData(); - } + @PostConstruct + private void init() throws SQLException { + AccessIdController.setLdapCache(new LdapCacheTestImpl()); + sampleDataGenerator.generateSampleData(); + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/GeneralExceptionHandlingTest.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/GeneralExceptionHandlingTest.java index c8e4441cd..bf9f91cd6 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/GeneralExceptionHandlingTest.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/GeneralExceptionHandlingTest.java @@ -13,33 +13,30 @@ import pro.taskana.RestHelper; import pro.taskana.TaskanaSpringBootTest; import pro.taskana.rest.resource.ClassificationSummaryListResource; -/** - * Test general Exception Handling. - */ - +/** Test general Exception Handling. */ @TaskanaSpringBootTest class GeneralExceptionHandlingTest { - @Autowired RestHelper restHelper; + private static RestTemplate template; + @Autowired RestHelper restHelper; - private static RestTemplate template; + @BeforeAll + static void init() { + template = RestHelper.getRestTemplate(); + } - @BeforeAll - static void init() { - template = RestHelper.getRestTemplate(); - } + @Test + void testDeleteNonExisitingClassificationExceptionIsLogged() { - @Test - void testDeleteNonExisitingClassificationExceptionIsLogged() { - - HttpClientErrorException ex = Assertions.assertThrows(HttpClientErrorException.class, + HttpClientErrorException ex = + Assertions.assertThrows( + HttpClientErrorException.class, () -> template.exchange( - restHelper.toUrl(Mapping.URL_CLASSIFICATIONS_ID, "non-existing-id"), HttpMethod.DELETE, + restHelper.toUrl(Mapping.URL_CLASSIFICATIONS_ID, "non-existing-id"), + HttpMethod.DELETE, restHelper.defaultRequest(), - ParameterizedTypeReference.forType(ClassificationSummaryListResource.class) - )); - Assertions.assertTrue( - ex.getResponseBodyAsString().contains("non-existing-id")); - } + ParameterizedTypeReference.forType(ClassificationSummaryListResource.class))); + Assertions.assertTrue(ex.getResponseBodyAsString().contains("non-existing-id")); + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/MappingTest.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/MappingTest.java index 916d98d2e..19c989b4c 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/MappingTest.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/MappingTest.java @@ -8,26 +8,26 @@ import org.junit.jupiter.api.Test; import org.springframework.util.LinkedMultiValueMap; import org.springframework.web.util.UriComponentsBuilder; -/** - * Test Mapping and Linkbuilder. - */ +/** Test Mapping and Linkbuilder. */ class MappingTest { - @Test - void testMapping() throws Exception { + @Test + void testMapping() throws Exception { - String mapUrl = Mapping.URL_TASKS; - String buildUrl = linkTo(methodOn(TaskController.class).getTasks(new LinkedMultiValueMap<>())).toString(); - Assertions.assertEquals(mapUrl, buildUrl); - } + String mapUrl = Mapping.URL_TASKS; + String buildUrl = + linkTo(methodOn(TaskController.class).getTasks(new LinkedMultiValueMap<>())).toString(); + Assertions.assertEquals(mapUrl, buildUrl); + } - @Test - void testMappingWithVariable() throws Exception { + @Test + void testMappingWithVariable() throws Exception { - String id = "25"; + String id = "25"; - String mapUrl = UriComponentsBuilder.fromPath(Mapping.URL_TASKS_ID).buildAndExpand(id).toUriString(); - String buildUrl = linkTo(methodOn(TaskController.class).getTask(id)).toString(); - Assertions.assertEquals(mapUrl, buildUrl); - } + String mapUrl = + UriComponentsBuilder.fromPath(Mapping.URL_TASKS_ID).buildAndExpand(id).toUriString(); + String buildUrl = linkTo(methodOn(TaskController.class).getTask(id)).toString(); + Assertions.assertEquals(mapUrl, buildUrl); + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/TaskControllerIntTest.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/TaskControllerIntTest.java index 780e87c59..b30ee3f5d 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/TaskControllerIntTest.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/TaskControllerIntTest.java @@ -7,6 +7,9 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; @@ -15,9 +18,7 @@ import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.time.Instant; - import javax.sql.DataSource; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -33,10 +34,6 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - import pro.taskana.ObjectReference; import pro.taskana.RestHelper; import pro.taskana.TaskanaSpringBootTest; @@ -46,386 +43,415 @@ import pro.taskana.rest.resource.TaskSummaryListResource; import pro.taskana.rest.resource.WorkbasketSummaryResource; import pro.taskana.sampledata.SampleDataGenerator; -/** - * Test Task Controller. - */ - +/** Test Task Controller. */ @TaskanaSpringBootTest class TaskControllerIntTest { - @Value("${taskana.schemaName:TASKANA}") - public String schemaName; + private static RestTemplate template; + @Value("${taskana.schemaName:TASKANA}") + public String schemaName; + @Autowired RestHelper restHelper; + @Autowired private DataSource dataSource; - @Autowired RestHelper restHelper; + @BeforeAll + static void init() { + template = RestHelper.getRestTemplate(); + } - private static RestTemplate template; + void resetDb() { + SampleDataGenerator sampleDataGenerator = new SampleDataGenerator(dataSource, schemaName); + sampleDataGenerator.generateSampleData(); + } - @BeforeAll - static void init() { - template = RestHelper.getRestTemplate(); - } - - @Autowired - private DataSource dataSource; - - void resetDb() { - SampleDataGenerator sampleDataGenerator = new SampleDataGenerator(dataSource, schemaName); - sampleDataGenerator.generateSampleData(); - } - - @Test - void testGetAllTasks() { - ResponseEntity response = template.exchange( - restHelper.toUrl(Mapping.URL_TASKS), HttpMethod.GET, restHelper.defaultRequest(), + @Test + void testGetAllTasks() { + ResponseEntity response = + template.exchange( + restHelper.toUrl(Mapping.URL_TASKS), + HttpMethod.GET, + restHelper.defaultRequest(), ParameterizedTypeReference.forType(TaskSummaryListResource.class)); - assertNotNull(response.getBody().getLink(Link.REL_SELF)); - assertEquals(25, response.getBody().getContent().size()); - } + assertNotNull(response.getBody().getLink(Link.REL_SELF)); + assertEquals(25, response.getBody().getContent().size()); + } - @Test - void testGetAllTasksByWorkbasketId() { - ResponseEntity response = template.exchange( - restHelper.toUrl(Mapping.URL_TASKS) + "?workbasket-id=WBI:100000000000000000000000000000000001", - HttpMethod.GET, restHelper.defaultRequest(), + @Test + void testGetAllTasksByWorkbasketId() { + ResponseEntity response = + template.exchange( + restHelper.toUrl(Mapping.URL_TASKS) + + "?workbasket-id=WBI:100000000000000000000000000000000001", + HttpMethod.GET, + restHelper.defaultRequest(), ParameterizedTypeReference.forType(TaskSummaryListResource.class)); - assertNotNull(response.getBody().getLink(Link.REL_SELF)); - assertEquals(22, response.getBody().getContent().size()); - } + assertNotNull(response.getBody().getLink(Link.REL_SELF)); + assertEquals(22, response.getBody().getContent().size()); + } - @Test - void testGetAllTasksByWorkbasketKeyAndDomain() { - HttpHeaders headers = new HttpHeaders(); - headers.add("Authorization", "Basic dXNlcl8xXzI6dXNlcl8xXzI="); // user_1_2 - HttpEntity request = new HttpEntity(headers); - ResponseEntity response = template.exchange( + @Test + void testGetAllTasksByWorkbasketKeyAndDomain() { + HttpHeaders headers = new HttpHeaders(); + headers.add("Authorization", "Basic dXNlcl8xXzI6dXNlcl8xXzI="); // user_1_2 + HttpEntity request = new HttpEntity(headers); + ResponseEntity response = + template.exchange( restHelper.toUrl(Mapping.URL_TASKS) + "?workbasket-key=USER_1_2&domain=DOMAIN_A", - HttpMethod.GET, request, + HttpMethod.GET, + request, ParameterizedTypeReference.forType(TaskSummaryListResource.class)); - assertNotNull(response.getBody().getLink(Link.REL_SELF)); - assertEquals(20, response.getBody().getContent().size()); + assertNotNull(response.getBody().getLink(Link.REL_SELF)); + assertEquals(20, response.getBody().getContent().size()); + } + + @Test + void testExceptionIfKeyIsSetButDomainIsMissing() { + + HttpHeaders headers = new HttpHeaders(); + headers.add("Authorization", "Basic dXNlcl8xXzI6dXNlcl8xXzI="); // user_1_2 + HttpEntity request = new HttpEntity(headers); + try { + ResponseEntity response = + template.exchange( + restHelper.toUrl(Mapping.URL_TASKS) + "?workbasket-key=USER_1_2", + HttpMethod.GET, + request, + ParameterizedTypeReference.forType(TaskSummaryListResource.class)); + fail(); + } catch (HttpClientErrorException e) { + assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); } + } - @Test - void testExceptionIfKeyIsSetButDomainIsMissing() { - - HttpHeaders headers = new HttpHeaders(); - headers.add("Authorization", "Basic dXNlcl8xXzI6dXNlcl8xXzI="); // user_1_2 - HttpEntity request = new HttpEntity(headers); - try { - ResponseEntity response = template.exchange( - restHelper.toUrl(Mapping.URL_TASKS) + "?workbasket-key=USER_1_2", - HttpMethod.GET, request, - ParameterizedTypeReference.forType(TaskSummaryListResource.class)); - fail(); - } catch (HttpClientErrorException e) { - assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); - } - } - - @Test - void testGetAllTasksWithAdminRole() { - ResponseEntity response = template.exchange( - restHelper.toUrl(Mapping.URL_TASKS), HttpMethod.GET, new HttpEntity<>(restHelper.getHeadersAdmin()), + @Test + void testGetAllTasksWithAdminRole() { + ResponseEntity response = + template.exchange( + restHelper.toUrl(Mapping.URL_TASKS), + HttpMethod.GET, + new HttpEntity<>(restHelper.getHeadersAdmin()), ParameterizedTypeReference.forType(TaskSummaryListResource.class)); - assertNotNull(response.getBody().getLink(Link.REL_SELF)); - assertEquals(73, response.getBody().getContent().size()); - } + assertNotNull(response.getBody().getLink(Link.REL_SELF)); + assertEquals(73, response.getBody().getContent().size()); + } - @Test - void testGetAllTasksKeepingFilters() { - ResponseEntity response = template.exchange( - restHelper.toUrl(Mapping.URL_TASKS) + "?por.type=VNR&por.value=22334455&sort-by=por.value&order=desc", - HttpMethod.GET, restHelper.defaultRequest(), + @Test + void testGetAllTasksKeepingFilters() { + ResponseEntity response = + template.exchange( + restHelper.toUrl(Mapping.URL_TASKS) + + "?por.type=VNR&por.value=22334455&sort-by=por.value&order=desc", + HttpMethod.GET, + restHelper.defaultRequest(), ParameterizedTypeReference.forType(TaskSummaryListResource.class)); - assertNotNull(response.getBody().getLink(Link.REL_SELF)); - assertTrue(response.getBody() + assertNotNull(response.getBody().getLink(Link.REL_SELF)); + assertTrue( + response + .getBody() .getLink(Link.REL_SELF) .getHref() - .endsWith("/api/v1/tasks?por.type=VNR&por.value=22334455&sort-by=por.value&order=desc")); + .endsWith( + "/api/v1/tasks?por.type=VNR&por.value=22334455&sort-by=por.value&order=desc")); + } + + @Test + void testThrowsExceptionIfInvalidFilterIsUsed() { + try { + template.exchange( + restHelper.toUrl(Mapping.URL_TASKS) + "?invalid=VNR", + HttpMethod.GET, + restHelper.defaultRequest(), + ParameterizedTypeReference.forType(TaskSummaryListResource.class)); + fail(); + } catch (HttpClientErrorException e) { + assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); + assertTrue(e.getResponseBodyAsString().contains("[invalid]")); } + } - @Test - void testThrowsExceptionIfInvalidFilterIsUsed() { - try { - template.exchange( - restHelper.toUrl(Mapping.URL_TASKS) + "?invalid=VNR", - HttpMethod.GET, restHelper.defaultRequest(), - ParameterizedTypeReference.forType(TaskSummaryListResource.class)); - fail(); - } catch (HttpClientErrorException e) { - assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); - assertTrue(e.getResponseBodyAsString().contains("[invalid]")); - } - } + @Test + void testGetLastPageSortedByPorValue() { - @Test - void testGetLastPageSortedByPorValue() { - - HttpEntity request = new HttpEntity(restHelper.getHeadersAdmin()); - ResponseEntity response = template.exchange( + HttpEntity request = new HttpEntity(restHelper.getHeadersAdmin()); + ResponseEntity response = + template.exchange( restHelper.toUrl(Mapping.URL_TASKS) + "?state=READY,CLAIMED&sort-by=por.value&order=desc&page=15&page-size=5", HttpMethod.GET, request, ParameterizedTypeReference.forType(TaskSummaryListResource.class)); - assertEquals(1, response.getBody().getContent().size()); - assertTrue(response.getBody().getLink(Link.REL_LAST).getHref().contains("page=14")); - assertEquals("TKI:100000000000000000000000000000000000", - response.getBody().getContent().iterator().next().getTaskId()); - assertNotNull(response.getBody().getLink(Link.REL_SELF)); - assertTrue(response.getBody() + assertEquals(1, response.getBody().getContent().size()); + assertTrue(response.getBody().getLink(Link.REL_LAST).getHref().contains("page=14")); + assertEquals( + "TKI:100000000000000000000000000000000000", + response.getBody().getContent().iterator().next().getTaskId()); + assertNotNull(response.getBody().getLink(Link.REL_SELF)); + assertTrue( + response + .getBody() .getLink(Link.REL_SELF) .getHref() - .endsWith("/api/v1/tasks?state=READY,CLAIMED&sort-by=por.value&order=desc&page=15&page-size=5")); - assertNotNull(response.getBody().getLink(Link.REL_FIRST)); - assertNotNull(response.getBody().getLink(Link.REL_LAST)); - assertNotNull(response.getBody().getLink(Link.REL_PREVIOUS)); - } + .endsWith( + "/api/v1/tasks?state=READY,CLAIMED&sort-by=por.value&order=desc&page=15&page-size=5")); + assertNotNull(response.getBody().getLink(Link.REL_FIRST)); + assertNotNull(response.getBody().getLink(Link.REL_LAST)); + assertNotNull(response.getBody().getLink(Link.REL_PREVIOUS)); + } - @Test - void testGetLastPageSortedByDueWithHiddenTasksRemovedFromResult() { - resetDb(); // required because ClassificationControllerIntTest.testGetQueryByPorSecondPageSortedByType changes - // tasks and this test depends on the tasks as they are in sampledata + @Test + void testGetLastPageSortedByDueWithHiddenTasksRemovedFromResult() { + resetDb(); // required because + // ClassificationControllerIntTest.testGetQueryByPorSecondPageSortedByType changes + // tasks and this test depends on the tasks as they are in sampledata - HttpHeaders headers = new HttpHeaders(); - headers.add("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x"); - HttpEntity request = new HttpEntity(headers); + HttpHeaders headers = new HttpHeaders(); + headers.add("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x"); + HttpEntity request = new HttpEntity(headers); - ResponseEntity response = template.exchange( - restHelper.toUrl(Mapping.URL_TASKS) + "?sort-by=due&order=desc", HttpMethod.GET, + ResponseEntity response = + template.exchange( + restHelper.toUrl(Mapping.URL_TASKS) + "?sort-by=due&order=desc", + HttpMethod.GET, request, ParameterizedTypeReference.forType(TaskSummaryListResource.class)); - assertEquals(25, response.getBody().getContent().size()); + assertEquals(25, response.getBody().getContent().size()); - response = template.exchange( - restHelper.toUrl(Mapping.URL_TASKS) + "?sort-by=due&order=desc&page=5&page-size=5", HttpMethod.GET, + response = + template.exchange( + restHelper.toUrl(Mapping.URL_TASKS) + "?sort-by=due&order=desc&page=5&page-size=5", + HttpMethod.GET, request, ParameterizedTypeReference.forType(TaskSummaryListResource.class)); - assertEquals(5, response.getBody().getContent().size()); - assertTrue(response.getBody().getLink(Link.REL_LAST).getHref().contains("page=5")); - assertEquals("TKI:000000000000000000000000000000000023", - response.getBody().getContent().iterator().next().getTaskId()); - assertNotNull(response.getBody().getLink(Link.REL_SELF)); - assertTrue(response.getBody() + assertEquals(5, response.getBody().getContent().size()); + assertTrue(response.getBody().getLink(Link.REL_LAST).getHref().contains("page=5")); + assertEquals( + "TKI:000000000000000000000000000000000023", + response.getBody().getContent().iterator().next().getTaskId()); + assertNotNull(response.getBody().getLink(Link.REL_SELF)); + assertTrue( + response + .getBody() .getLink(Link.REL_SELF) .getHref() .endsWith("/api/v1/tasks?sort-by=due&order=desc&page=5&page-size=5")); - assertNotNull(response.getBody().getLink(Link.REL_FIRST)); - assertNotNull(response.getBody().getLink(Link.REL_LAST)); - assertNotNull(response.getBody().getLink(Link.REL_PREVIOUS)); - } + assertNotNull(response.getBody().getLink(Link.REL_FIRST)); + assertNotNull(response.getBody().getLink(Link.REL_LAST)); + assertNotNull(response.getBody().getLink(Link.REL_PREVIOUS)); + } - @Test - void testGetQueryByPorSecondPageSortedByType() { - resetDb(); // required because ClassificationControllerIntTest.testGetQueryByPorSecondPageSortedByType changes - // tasks and this test depends on the tasks as they are in sampledata + @Test + void testGetQueryByPorSecondPageSortedByType() { + resetDb(); // required because + // ClassificationControllerIntTest.testGetQueryByPorSecondPageSortedByType changes + // tasks and this test depends on the tasks as they are in sampledata - HttpHeaders headers = new HttpHeaders(); - headers.add("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x"); - HttpEntity request = new HttpEntity(headers); - ResponseEntity response = template.exchange( + HttpHeaders headers = new HttpHeaders(); + headers.add("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x"); + HttpEntity request = new HttpEntity(headers); + ResponseEntity response = + template.exchange( restHelper.toUrl(Mapping.URL_TASKS) + "?por.company=00&por.system=PASystem&por.instance=00&por.type=VNR&por.value=22334455&sort-by=por.type&order=asc&page=2&page-size=5", HttpMethod.GET, request, ParameterizedTypeReference.forType(TaskSummaryListResource.class)); - assertEquals(1, response.getBody().getContent().size()); - assertEquals("TKI:000000000000000000000000000000000013", - response.getBody().getContent().iterator().next().getTaskId()); - assertNotNull(response.getBody().getLink(Link.REL_SELF)); - assertTrue(response.getBody() + assertEquals(1, response.getBody().getContent().size()); + assertEquals( + "TKI:000000000000000000000000000000000013", + response.getBody().getContent().iterator().next().getTaskId()); + assertNotNull(response.getBody().getLink(Link.REL_SELF)); + assertTrue( + response + .getBody() .getLink(Link.REL_SELF) .getHref() .endsWith( "/api/v1/tasks?por.company=00&por.system=PASystem&por.instance=00&por.type=VNR&por.value=22334455&sort-by=por.type&order=asc&page=2&page-size=5")); - assertNotNull(response.getBody().getLink(Link.REL_FIRST)); - assertNotNull(response.getBody().getLink(Link.REL_LAST)); - assertNotNull(response.getBody().getLink(Link.REL_PREVIOUS)); + assertNotNull(response.getBody().getLink(Link.REL_FIRST)); + assertNotNull(response.getBody().getLink(Link.REL_LAST)); + assertNotNull(response.getBody().getLink(Link.REL_PREVIOUS)); + } + + @Test + void testGetTaskWithAttachments() throws IOException { + URL url = new URL(restHelper.toUrl("/api/v1/tasks/TKI:000000000000000000000000000000000002")); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("GET"); + con.setRequestProperty("Authorization", "Basic YWRtaW46YWRtaW4="); + assertEquals(200, con.getResponseCode()); + ObjectMapper objectMapper = new ObjectMapper(); + + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + StringBuffer content = new StringBuffer(); + while ((inputLine = in.readLine()) != null) { + content.append(inputLine); } + in.close(); + con.disconnect(); + String response = content.toString(); + JsonNode jsonNode = objectMapper.readTree(response); + String created = jsonNode.get("created").asText(); + assertFalse(response.contains("\"attachments\":[]")); + assertTrue(created.matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z")); + } - @Test - void testGetTaskWithAttachments() throws IOException { - URL url = new URL(restHelper.toUrl("/api/v1/tasks/TKI:000000000000000000000000000000000002")); - HttpURLConnection con = (HttpURLConnection) url.openConnection(); - con.setRequestMethod("GET"); - con.setRequestProperty("Authorization", "Basic YWRtaW46YWRtaW4="); - assertEquals(200, con.getResponseCode()); - ObjectMapper objectMapper = new ObjectMapper(); + @Test + void testGetAndUpdateTask() throws IOException { + URL url = new URL(restHelper.toUrl("/api/v1/tasks/TKI:100000000000000000000000000000000000")); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("GET"); + con.setRequestProperty("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x"); + assertEquals(200, con.getResponseCode()); - BufferedReader in = new BufferedReader( - new InputStreamReader(con.getInputStream())); - String inputLine; - StringBuffer content = new StringBuffer(); - while ((inputLine = in.readLine()) != null) { - content.append(inputLine); - } - in.close(); - con.disconnect(); - String response = content.toString(); - JsonNode jsonNode = objectMapper.readTree(response); - String created = jsonNode.get("created").asText(); - assertFalse(response.contains("\"attachments\":[]")); - assertTrue( - created.matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z")); + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + StringBuffer content = new StringBuffer(); + while ((inputLine = in.readLine()) != null) { + content.append(inputLine); } + in.close(); + con.disconnect(); + String originalTask = content.toString(); - @Test - void testGetAndUpdateTask() throws IOException { - URL url = new URL(restHelper.toUrl("/api/v1/tasks/TKI:100000000000000000000000000000000000")); - HttpURLConnection con = (HttpURLConnection) url.openConnection(); - con.setRequestMethod("GET"); - con.setRequestProperty("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x"); - assertEquals(200, con.getResponseCode()); + con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("PUT"); + con.setDoOutput(true); + con.setRequestProperty("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x"); + con.setRequestProperty("Content-Type", "application/json"); + BufferedWriter out = new BufferedWriter(new OutputStreamWriter(con.getOutputStream())); + out.write(content.toString()); + out.flush(); + out.close(); + assertEquals(200, con.getResponseCode()); + con.disconnect(); - BufferedReader in = new BufferedReader( - new InputStreamReader(con.getInputStream())); - String inputLine; - StringBuffer content = new StringBuffer(); - while ((inputLine = in.readLine()) != null) { - content.append(inputLine); - } - in.close(); - con.disconnect(); - String originalTask = content.toString(); - - con = (HttpURLConnection) url.openConnection(); - con.setRequestMethod("PUT"); - con.setDoOutput(true); - con.setRequestProperty("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x"); - con.setRequestProperty("Content-Type", "application/json"); - BufferedWriter out = new BufferedWriter(new OutputStreamWriter(con.getOutputStream())); - out.write(content.toString()); - out.flush(); - out.close(); - assertEquals(200, con.getResponseCode()); - con.disconnect(); - - url = new URL(restHelper.toUrl("/api/v1/tasks/TKI:100000000000000000000000000000000000")); - con = (HttpURLConnection) url.openConnection(); - con.setRequestMethod("GET"); - con.setRequestProperty("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x"); - assertEquals(200, con.getResponseCode()); - - in = new BufferedReader( - new InputStreamReader(con.getInputStream())); - content = new StringBuffer(); - while ((inputLine = in.readLine()) != null) { - content.append(inputLine); - } - in.close(); - con.disconnect(); - String updatedTask = content.toString(); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - TaskResource originalTaskObject = mapper.readValue(originalTask, TaskResource.class); - TaskResource updatedTaskObject = mapper.readValue(updatedTask, TaskResource.class); - - assertNotEquals( - originalTaskObject.getModified(), - updatedTaskObject.getModified()); + url = new URL(restHelper.toUrl("/api/v1/tasks/TKI:100000000000000000000000000000000000")); + con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("GET"); + con.setRequestProperty("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x"); + assertEquals(200, con.getResponseCode()); + in = new BufferedReader(new InputStreamReader(con.getInputStream())); + content = new StringBuffer(); + while ((inputLine = in.readLine()) != null) { + content.append(inputLine); } + in.close(); + con.disconnect(); + String updatedTask = content.toString(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + TaskResource originalTaskObject = mapper.readValue(originalTask, TaskResource.class); + TaskResource updatedTaskObject = mapper.readValue(updatedTask, TaskResource.class); - @Test - void testCreateAndDeleteTask() { + assertNotEquals(originalTaskObject.getModified(), updatedTaskObject.getModified()); + } - TaskResource taskResource = getTaskResourceSample(); - ResponseEntity responseCreate = template.exchange(restHelper.toUrl(Mapping.URL_TASKS), + @Test + void testCreateAndDeleteTask() { + + TaskResource taskResource = getTaskResourceSample(); + ResponseEntity responseCreate = + template.exchange( + restHelper.toUrl(Mapping.URL_TASKS), HttpMethod.POST, new HttpEntity<>(taskResource, restHelper.getHeaders()), ParameterizedTypeReference.forType(TaskResource.class)); - assertEquals(responseCreate.getStatusCode(), HttpStatus.CREATED); - assertNotNull(responseCreate.getBody()); + assertEquals(responseCreate.getStatusCode(), HttpStatus.CREATED); + assertNotNull(responseCreate.getBody()); - String taskIdOfCreatedTask = responseCreate.getBody().getTaskId(); - assertNotNull(taskIdOfCreatedTask); - assertTrue(taskIdOfCreatedTask.startsWith("TKI:")); + String taskIdOfCreatedTask = responseCreate.getBody().getTaskId(); + assertNotNull(taskIdOfCreatedTask); + assertTrue(taskIdOfCreatedTask.startsWith("TKI:")); - ResponseEntity responseDeleted = template.exchange( + ResponseEntity responseDeleted = + template.exchange( restHelper.toUrl(Mapping.URL_TASKS_ID, taskIdOfCreatedTask), HttpMethod.DELETE, new HttpEntity<>(restHelper.getHeadersAdmin()), ParameterizedTypeReference.forType(Void.class)); - assertEquals(HttpStatus.NO_CONTENT, responseDeleted.getStatusCode()); - } + assertEquals(HttpStatus.NO_CONTENT, responseDeleted.getStatusCode()); + } - /** - * TSK-926: If Planned and Due Date is provided to create a task - * and not matching to service level throw an exception - * One is calculated by other other date +- service level. - */ - @Test - void testCreateWithPlannedAndDueDate() { - TaskResource taskResource = getTaskResourceSample(); - Instant now = Instant.now(); - taskResource.setPlanned(now.toString()); - taskResource.setDue(now.toString()); + /** + * TSK-926: If Planned and Due Date is provided to create a task and not matching to service level + * throw an exception One is calculated by other other date +- service level. + */ + @Test + void testCreateWithPlannedAndDueDate() { + TaskResource taskResource = getTaskResourceSample(); + Instant now = Instant.now(); + taskResource.setPlanned(now.toString()); + taskResource.setDue(now.toString()); - HttpClientErrorException ex = Assertions.assertThrows(HttpClientErrorException.class, - () -> template.exchange(restHelper.toUrl(Mapping.URL_TASKS), HttpMethod.POST, - new HttpEntity<>(taskResource, restHelper.getHeaders()), - ParameterizedTypeReference.forType(TaskResource.class))); + HttpClientErrorException ex = + Assertions.assertThrows( + HttpClientErrorException.class, + () -> + template.exchange( + restHelper.toUrl(Mapping.URL_TASKS), + HttpMethod.POST, + new HttpEntity<>(taskResource, restHelper.getHeaders()), + ParameterizedTypeReference.forType(TaskResource.class))); + } - } - - private TaskResource getTaskResourceSample() { - ClassificationSummaryResource classificationResource = new ClassificationSummaryResource(); - classificationResource.key = "L11010"; - WorkbasketSummaryResource workbasketSummaryResource = new WorkbasketSummaryResource(); - workbasketSummaryResource.setWorkbasketId("WBI:100000000000000000000000000000000004"); - - ObjectReference objectReference = new ObjectReference(); - objectReference.setCompany("MyCompany1"); - objectReference.setSystem("MySystem1"); - objectReference.setSystemInstance("MyInstance1"); - objectReference.setType("MyType1"); - objectReference.setValue("00000001"); - - TaskResource taskResource = new TaskResource(); - taskResource.setClassificationSummaryResource(classificationResource); - taskResource.setWorkbasketSummaryResource(workbasketSummaryResource); - taskResource.setPrimaryObjRef(objectReference); - return taskResource; - } - - @Test - void testCreateTaskWithInvalidParameter() throws IOException { - String taskToCreateJson = "{\"classificationKey\":\"L11010\"," + @Test + void testCreateTaskWithInvalidParameter() throws IOException { + String taskToCreateJson = + "{\"classificationKey\":\"L11010\"," + "\"workbasketSummaryResource\":{\"workbasketId\":\"WBI:100000000000000000000000000000000004\"}," + "\"primaryObjRef\":{\"company\":\"MyCompany1\",\"system\":\"MySystem1\",\"systemInstance\":\"MyInstance1\",\"type\":\"MyType1\",\"value\":\"00000001\"}}"; - URL url = new URL(restHelper.toUrl(Mapping.URL_TASKS)); - HttpURLConnection con = (HttpURLConnection) url.openConnection(); - con.setRequestMethod("POST"); - con.setDoOutput(true); - con.setRequestProperty("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x"); - con.setRequestProperty("Content-Type", "application/json"); - BufferedWriter out = new BufferedWriter(new OutputStreamWriter(con.getOutputStream())); - out.write(taskToCreateJson); - out.flush(); - out.close(); - assertEquals(400, con.getResponseCode()); - con.disconnect(); + URL url = new URL(restHelper.toUrl(Mapping.URL_TASKS)); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("POST"); + con.setDoOutput(true); + con.setRequestProperty("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x"); + con.setRequestProperty("Content-Type", "application/json"); + BufferedWriter out = new BufferedWriter(new OutputStreamWriter(con.getOutputStream())); + out.write(taskToCreateJson); + out.flush(); + out.close(); + assertEquals(400, con.getResponseCode()); + con.disconnect(); - taskToCreateJson = - "{\"classificationSummaryResource\":{\"classificationId\":\"CLI:100000000000000000000000000000000004\"}," - + "\"workbasketSummaryResource\":{\"workbasketId\":\"\"}," - + "\"primaryObjRef\":{\"company\":\"MyCompany1\",\"system\":\"MySystem1\",\"systemInstance\":\"MyInstance1\",\"type\":\"MyType1\",\"value\":\"00000001\"}}"; + taskToCreateJson = + "{\"classificationSummaryResource\":{\"classificationId\":\"CLI:100000000000000000000000000000000004\"}," + + "\"workbasketSummaryResource\":{\"workbasketId\":\"\"}," + + "\"primaryObjRef\":{\"company\":\"MyCompany1\",\"system\":\"MySystem1\",\"systemInstance\":\"MyInstance1\",\"type\":\"MyType1\",\"value\":\"00000001\"}}"; - url = new URL(restHelper.toUrl(Mapping.URL_TASKS)); - con = (HttpURLConnection) url.openConnection(); - con.setRequestMethod("POST"); - con.setDoOutput(true); - con.setRequestProperty("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x"); - con.setRequestProperty("Content-Type", "application/json"); - out = new BufferedWriter(new OutputStreamWriter(con.getOutputStream())); - out.write(taskToCreateJson); - out.flush(); - out.close(); - assertEquals(400, con.getResponseCode()); - con.disconnect(); + url = new URL(restHelper.toUrl(Mapping.URL_TASKS)); + con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("POST"); + con.setDoOutput(true); + con.setRequestProperty("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x"); + con.setRequestProperty("Content-Type", "application/json"); + out = new BufferedWriter(new OutputStreamWriter(con.getOutputStream())); + out.write(taskToCreateJson); + out.flush(); + out.close(); + assertEquals(400, con.getResponseCode()); + con.disconnect(); + } - } + private TaskResource getTaskResourceSample() { + ClassificationSummaryResource classificationResource = new ClassificationSummaryResource(); + classificationResource.key = "L11010"; + WorkbasketSummaryResource workbasketSummaryResource = new WorkbasketSummaryResource(); + workbasketSummaryResource.setWorkbasketId("WBI:100000000000000000000000000000000004"); + ObjectReference objectReference = new ObjectReference(); + objectReference.setCompany("MyCompany1"); + objectReference.setSystem("MySystem1"); + objectReference.setSystemInstance("MyInstance1"); + objectReference.setType("MyType1"); + objectReference.setValue("00000001"); + + TaskResource taskResource = new TaskResource(); + taskResource.setClassificationSummaryResource(classificationResource); + taskResource.setWorkbasketSummaryResource(workbasketSummaryResource); + taskResource.setPrimaryObjRef(objectReference); + return taskResource; + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/TaskanaEngineControllerIntTest.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/TaskanaEngineControllerIntTest.java index ca8b34ffc..307be74c1 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/TaskanaEngineControllerIntTest.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/TaskanaEngineControllerIntTest.java @@ -5,7 +5,6 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.List; - import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -21,63 +20,71 @@ import pro.taskana.TaskanaRole; import pro.taskana.TaskanaSpringBootTest; import pro.taskana.rest.resource.TaskanaUserInfoResource; -/** - * Test TaskanaEngineController. - */ - +/** Test TaskanaEngineController. */ @TaskanaSpringBootTest class TaskanaEngineControllerIntTest { - @Autowired RestHelper restHelper; + private static RestTemplate template; + @Autowired RestHelper restHelper; - private static RestTemplate template; + @BeforeAll + static void init() { + template = RestHelper.getRestTemplate(); + } - @BeforeAll - static void init() { - template = RestHelper.getRestTemplate(); - } - - @Test - void testDomains() { - ResponseEntity> response = template.exchange( - restHelper.toUrl(Mapping.URL_DOMAIN), HttpMethod.GET, restHelper.defaultRequest(), + @Test + void testDomains() { + ResponseEntity> response = + template.exchange( + restHelper.toUrl(Mapping.URL_DOMAIN), + HttpMethod.GET, + restHelper.defaultRequest(), ParameterizedTypeReference.forType(List.class)); - assertTrue(response.getBody().contains("DOMAIN_A")); - } + assertTrue(response.getBody().contains("DOMAIN_A")); + } - @Test - void testClassificationTypes() { - ResponseEntity> response = template.exchange( - restHelper.toUrl(Mapping.URL_CLASSIFICATIONTYPES), HttpMethod.GET, restHelper.defaultRequest(), + @Test + void testClassificationTypes() { + ResponseEntity> response = + template.exchange( + restHelper.toUrl(Mapping.URL_CLASSIFICATIONTYPES), + HttpMethod.GET, + restHelper.defaultRequest(), ParameterizedTypeReference.forType(List.class)); - assertTrue(response.getBody().contains("TASK")); - assertTrue(response.getBody().contains("DOCUMENT")); - assertFalse(response.getBody().contains("UNKNOWN")); - } + assertTrue(response.getBody().contains("TASK")); + assertTrue(response.getBody().contains("DOCUMENT")); + assertFalse(response.getBody().contains("UNKNOWN")); + } - @Test - void testClassificationCategories() { - HttpHeaders headers = new HttpHeaders(); - headers.add("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x"); - HttpEntity request = new HttpEntity(headers); - ResponseEntity> response = template.exchange( - restHelper.toUrl(Mapping.URL_CLASSIFICATIONCATEGORIES), HttpMethod.GET, restHelper.defaultRequest(), + @Test + void testClassificationCategories() { + HttpHeaders headers = new HttpHeaders(); + headers.add("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x"); + HttpEntity request = new HttpEntity(headers); + ResponseEntity> response = + template.exchange( + restHelper.toUrl(Mapping.URL_CLASSIFICATIONCATEGORIES), + HttpMethod.GET, + restHelper.defaultRequest(), ParameterizedTypeReference.forType(List.class)); - assertTrue(response.getBody().contains("MANUAL")); - assertTrue(response.getBody().contains("EXTERNAL")); - assertTrue(response.getBody().contains("AUTOMATIC")); - assertTrue(response.getBody().contains("PROCESS")); - assertFalse(response.getBody().contains("UNKNOWN")); - } + assertTrue(response.getBody().contains("MANUAL")); + assertTrue(response.getBody().contains("EXTERNAL")); + assertTrue(response.getBody().contains("AUTOMATIC")); + assertTrue(response.getBody().contains("PROCESS")); + assertFalse(response.getBody().contains("UNKNOWN")); + } - @Test - void testGetCurrentUserInfo() { - ResponseEntity response = template.exchange( - restHelper.toUrl(Mapping.URL_CURRENTUSER), HttpMethod.GET, restHelper.defaultRequest(), + @Test + void testGetCurrentUserInfo() { + ResponseEntity response = + template.exchange( + restHelper.toUrl(Mapping.URL_CURRENTUSER), + HttpMethod.GET, + restHelper.defaultRequest(), ParameterizedTypeReference.forType(TaskanaUserInfoResource.class)); - assertEquals("teamlead_1", response.getBody().getUserId()); - assertTrue(response.getBody().getGroupIds().contains("businessadmin")); - assertTrue(response.getBody().getRoles().contains(TaskanaRole.BUSINESS_ADMIN)); - assertFalse(response.getBody().getRoles().contains(TaskanaRole.ADMIN)); - } + assertEquals("teamlead_1", response.getBody().getUserId()); + assertTrue(response.getBody().getGroupIds().contains("businessadmin")); + assertTrue(response.getBody().getRoles().contains(TaskanaRole.BUSINESS_ADMIN)); + assertFalse(response.getBody().getRoles().contains(TaskanaRole.ADMIN)); + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/TestConfiguration.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/TestConfiguration.java index ceb93e408..1575a08df 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/TestConfiguration.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/TestConfiguration.java @@ -1,22 +1,18 @@ package pro.taskana.rest; import javax.sql.DataSource; - import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Import; import pro.taskana.configuration.TaskanaEngineConfiguration; import pro.taskana.ldap.LdapConfiguration; -/** - * Configuration class for all rest tests. - */ +/** Configuration class for all rest tests. */ @Import({RestConfiguration.class, LdapConfiguration.class}) public class TestConfiguration { - @Bean - public DataSource dataSource() { - return TaskanaEngineConfiguration.createDefaultDataSource(); - } - + @Bean + public DataSource dataSource() { + return TaskanaEngineConfiguration.createDefaultDataSource(); + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/TestSchemaNameCustomizable.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/TestSchemaNameCustomizable.java index 4d80d5cdc..86c1c8db3 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/TestSchemaNameCustomizable.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/TestSchemaNameCustomizable.java @@ -3,9 +3,7 @@ package pro.taskana.rest; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; - import javax.sql.DataSource; - import org.junit.Assert; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -16,58 +14,60 @@ import pro.taskana.configuration.SpringTaskanaEngineConfiguration; import pro.taskana.exceptions.SystemException; import pro.taskana.sampledata.SampleDataGenerator; -/** - * Test that the schema name can be customized. - * - */ - +/** Test that the schema name can be customized. */ @TaskanaSpringBootTest class TestSchemaNameCustomizable { - String schemaName = "CUSTOMSCHEMANAME"; - boolean isPostgres = false; + String schemaName = "CUSTOMSCHEMANAME"; + boolean isPostgres = false; - @Autowired - private DataSource dataSource; + @Autowired private DataSource dataSource; - void resetDb() { - SampleDataGenerator sampleDataGenerator; - try { - if (DB.POSTGRESS.dbProductname.equals(dataSource.getConnection().getMetaData().getDatabaseProductName())) { - isPostgres = true; - schemaName = schemaName.toLowerCase(); - } - new SpringTaskanaEngineConfiguration(dataSource, true, true, schemaName); - sampleDataGenerator = new SampleDataGenerator(dataSource, schemaName); - sampleDataGenerator.generateSampleData(); - } catch (SQLException e) { - throw new SystemException("tried to reset DB and caught Exception " + e, e); - } + void resetDb() { + SampleDataGenerator sampleDataGenerator; + try { + if (DB.POSTGRESS.dbProductname.equals( + dataSource.getConnection().getMetaData().getDatabaseProductName())) { + isPostgres = true; + schemaName = schemaName.toLowerCase(); + } + new SpringTaskanaEngineConfiguration(dataSource, true, true, schemaName); + sampleDataGenerator = new SampleDataGenerator(dataSource, schemaName); + sampleDataGenerator.generateSampleData(); + } catch (SQLException e) { + throw new SystemException("tried to reset DB and caught Exception " + e, e); } + } - @Test - void chekCustomSchemaNameIsDefined() { - resetDb(); - ResultSet rs; - try { - Statement stmt = dataSource.getConnection().createStatement(); - if (isPostgres) { - rs = stmt.executeQuery( - "SELECT * FROM pg_catalog.pg_tables where schemaname = '" + schemaName.toLowerCase() + "'"); + @Test + void chekCustomSchemaNameIsDefined() { + resetDb(); + ResultSet rs; + try { + Statement stmt = dataSource.getConnection().createStatement(); + if (isPostgres) { + rs = + stmt.executeQuery( + "SELECT * FROM pg_catalog.pg_tables where schemaname = '" + + schemaName.toLowerCase() + + "'"); - } else { - rs = stmt.executeQuery( - "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '" + schemaName + "'"); - } - while (rs.next()) { - String tableName = rs.getString(isPostgres ? "tablename" : "TABLE_NAME"); - if (tableName.equals(isPostgres ? "workbasket" : "WORKBASKET")) { - Assert.assertEquals(tableName, isPostgres ? "workbasket" : "WORKBASKET"); - } - } - - } catch (SQLException e) { - e.printStackTrace(); + } else { + rs = + stmt.executeQuery( + "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '" + + schemaName + + "'"); + } + while (rs.next()) { + String tableName = rs.getString(isPostgres ? "tablename" : "TABLE_NAME"); + if (tableName.equals(isPostgres ? "workbasket" : "WORKBASKET")) { + Assert.assertEquals(tableName, isPostgres ? "workbasket" : "WORKBASKET"); } + } + + } catch (SQLException e) { + e.printStackTrace(); } + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/WorkbasketAccessItemControllerIntTest.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/WorkbasketAccessItemControllerIntTest.java index c69bf63e6..697fb44a9 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/WorkbasketAccessItemControllerIntTest.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/WorkbasketAccessItemControllerIntTest.java @@ -24,103 +24,106 @@ import pro.taskana.TaskanaSpringBootTest; import pro.taskana.rest.resource.WorkbasketAccessItemListResource; import pro.taskana.rest.resource.WorkbasketAccessItemPaginatedListResource; -/** - * Test WorkbasketAccessItemController. - */ +/** Test WorkbasketAccessItemController. */ @TestMethodOrder(MethodOrderer.Alphanumeric.class) @TaskanaSpringBootTest class WorkbasketAccessItemControllerIntTest { - @Autowired RestHelper restHelper; + private static RestTemplate template; + @Autowired RestHelper restHelper; - private static RestTemplate template; + @BeforeAll + static void init() { + template = RestHelper.getRestTemplate(); + } - @BeforeAll - static void init() { - template = RestHelper.getRestTemplate(); - } - - @Test - void testGetAllWorkbasketAccessItems() { - ResponseEntity response = template.exchange( - restHelper.toUrl(Mapping.URL_WORKBASKETACCESSITEMS), HttpMethod.GET, restHelper.defaultRequest(), - ParameterizedTypeReference.forType(WorkbasketAccessItemListResource.class)); - assertNotNull(response.getBody().getLink(Link.REL_SELF)); - } - - @Test - void testGetWorkbasketAccessItemsKeepingFilters() { - String parameters = "?sort-by=workbasket-key&order=asc&page=1&page-size=9&access-ids=user_1_1"; - ResponseEntity response = template.exchange( - restHelper.toUrl(Mapping.URL_WORKBASKETACCESSITEMS) + parameters, HttpMethod.GET, + @Test + void testGetAllWorkbasketAccessItems() { + ResponseEntity response = + template.exchange( + restHelper.toUrl(Mapping.URL_WORKBASKETACCESSITEMS), + HttpMethod.GET, restHelper.defaultRequest(), ParameterizedTypeReference.forType(WorkbasketAccessItemListResource.class)); - assertNotNull(response.getBody().getLink(Link.REL_SELF)); - assertTrue(response.getBody() - .getLink(Link.REL_SELF) - .getHref() - .endsWith(parameters)); - } + assertNotNull(response.getBody().getLink(Link.REL_SELF)); + } - @Test - void testThrowsExceptionIfInvalidFilterIsUsed() { - try { - template.exchange( - restHelper.toUrl(Mapping.URL_WORKBASKETACCESSITEMS) - + "?sort-by=workbasket-key&order=asc&page=1&page-size=9&invalid=user_1_1", HttpMethod.GET, - restHelper.defaultRequest(), - ParameterizedTypeReference.forType(WorkbasketAccessItemListResource.class)); - fail(); - } catch (HttpClientErrorException e) { - assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); - assertTrue(e.getResponseBodyAsString().contains("[invalid]")); - } - } + @Test + void testGetWorkbasketAccessItemsKeepingFilters() { + String parameters = "?sort-by=workbasket-key&order=asc&page=1&page-size=9&access-ids=user_1_1"; + ResponseEntity response = + template.exchange( + restHelper.toUrl(Mapping.URL_WORKBASKETACCESSITEMS) + parameters, + HttpMethod.GET, + restHelper.defaultRequest(), + ParameterizedTypeReference.forType(WorkbasketAccessItemListResource.class)); + assertNotNull(response.getBody().getLink(Link.REL_SELF)); + assertTrue(response.getBody().getLink(Link.REL_SELF).getHref().endsWith(parameters)); + } - @Test - void testGetSecondPageSortedByWorkbasketKey() { - String parameters = "?sort-by=workbasket-key&order=asc&page=2&page-size=9&access-ids=user_1_1"; - ResponseEntity response = template.exchange( - restHelper.toUrl(Mapping.URL_WORKBASKETACCESSITEMS) + parameters, HttpMethod.GET, + @Test + void testThrowsExceptionIfInvalidFilterIsUsed() { + try { + template.exchange( + restHelper.toUrl(Mapping.URL_WORKBASKETACCESSITEMS) + + "?sort-by=workbasket-key&order=asc&page=1&page-size=9&invalid=user_1_1", + HttpMethod.GET, + restHelper.defaultRequest(), + ParameterizedTypeReference.forType(WorkbasketAccessItemListResource.class)); + fail(); + } catch (HttpClientErrorException e) { + assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); + assertTrue(e.getResponseBodyAsString().contains("[invalid]")); + } + } + + @Test + void testGetSecondPageSortedByWorkbasketKey() { + String parameters = "?sort-by=workbasket-key&order=asc&page=2&page-size=9&access-ids=user_1_1"; + ResponseEntity response = + template.exchange( + restHelper.toUrl(Mapping.URL_WORKBASKETACCESSITEMS) + parameters, + HttpMethod.GET, restHelper.defaultRequest(), ParameterizedTypeReference.forType(WorkbasketAccessItemPaginatedListResource.class)); - assertEquals(1, response.getBody().getContent().size()); - assertEquals("user_1_1", response.getBody().getContent().iterator().next().accessId); - assertNotNull(response.getBody().getLink(Link.REL_SELF)); - assertTrue(response.getBody() - .getLink(Link.REL_SELF) - .getHref() - .endsWith(parameters)); - assertNotNull(response.getBody().getLink(Link.REL_FIRST)); - assertNotNull(response.getBody().getLink(Link.REL_LAST)); - assertEquals(9, response.getBody().getMetadata().getSize()); - assertEquals(1, response.getBody().getMetadata().getTotalElements()); - assertEquals(1, response.getBody().getMetadata().getTotalPages()); - assertEquals(1, response.getBody().getMetadata().getNumber()); - } + assertEquals(1, response.getBody().getContent().size()); + assertEquals("user_1_1", response.getBody().getContent().iterator().next().accessId); + assertNotNull(response.getBody().getLink(Link.REL_SELF)); + assertTrue(response.getBody().getLink(Link.REL_SELF).getHref().endsWith(parameters)); + assertNotNull(response.getBody().getLink(Link.REL_FIRST)); + assertNotNull(response.getBody().getLink(Link.REL_LAST)); + assertEquals(9, response.getBody().getMetadata().getSize()); + assertEquals(1, response.getBody().getMetadata().getTotalElements()); + assertEquals(1, response.getBody().getMetadata().getTotalPages()); + assertEquals(1, response.getBody().getMetadata().getNumber()); + } - @Test - void testRemoveWorkbasketAccessItemsOfUser() { + @Test + void testRemoveWorkbasketAccessItemsOfUser() { - String parameters = "?access-id=user_1_1"; - ResponseEntity response = template.exchange( - restHelper.toUrl(Mapping.URL_WORKBASKETACCESSITEMS) + parameters, HttpMethod.DELETE, + String parameters = "?access-id=user_1_1"; + ResponseEntity response = + template.exchange( + restHelper.toUrl(Mapping.URL_WORKBASKETACCESSITEMS) + parameters, + HttpMethod.DELETE, restHelper.defaultRequest(), ParameterizedTypeReference.forType(Void.class)); - assertNull(response.getBody()); - assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); - } + assertNull(response.getBody()); + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + } - @Test - void testGetBadRequestIfTryingToDeleteAccessItemsForGroup() { - String parameters = "?access-id=cn=DevelopersGroup,ou=groups,o=TaskanaTest"; - try { - ResponseEntity response = template.exchange( - restHelper.toUrl(Mapping.URL_WORKBASKETACCESSITEMS) + parameters, HttpMethod.DELETE, - restHelper.defaultRequest(), - ParameterizedTypeReference.forType(Void.class)); - } catch (HttpClientErrorException e) { - assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); - } + @Test + void testGetBadRequestIfTryingToDeleteAccessItemsForGroup() { + String parameters = "?access-id=cn=DevelopersGroup,ou=groups,o=TaskanaTest"; + try { + ResponseEntity response = + template.exchange( + restHelper.toUrl(Mapping.URL_WORKBASKETACCESSITEMS) + parameters, + HttpMethod.DELETE, + restHelper.defaultRequest(), + ParameterizedTypeReference.forType(Void.class)); + } catch (HttpClientErrorException e) { + assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); } + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/WorkbasketControllerIntTest.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/WorkbasketControllerIntTest.java index bddf988fd..3a3ef8c82 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/WorkbasketControllerIntTest.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/WorkbasketControllerIntTest.java @@ -7,7 +7,6 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.Iterator; - import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -25,105 +24,112 @@ import pro.taskana.rest.resource.DistributionTargetListResource; import pro.taskana.rest.resource.DistributionTargetResource; import pro.taskana.rest.resource.WorkbasketSummaryListResource; -/** - * Test WorkbasketController. - */ - +/** Test WorkbasketController. */ @TaskanaSpringBootTest class WorkbasketControllerIntTest { - @Autowired RestHelper restHelper; + private static RestTemplate template; + @Autowired RestHelper restHelper; - private static RestTemplate template; + @BeforeAll + static void init() { + template = RestHelper.getRestTemplate(); + } - @BeforeAll - static void init() { - template = RestHelper.getRestTemplate(); - } - - @Test - void testGetAllWorkbaskets() { - ResponseEntity response = template.exchange( - restHelper.toUrl(Mapping.URL_WORKBASKET), HttpMethod.GET, restHelper.defaultRequest(), - ParameterizedTypeReference.forType(WorkbasketSummaryListResource.class)); - assertNotNull(response.getBody().getLink(Link.REL_SELF)); - } - - @Test - void testGetAllWorkbasketsBusinessAdminHasOpenPermission() { - ResponseEntity response = template.exchange( - restHelper.toUrl(Mapping.URL_WORKBASKET) + "?required-permission=OPEN", HttpMethod.GET, + @Test + void testGetAllWorkbaskets() { + ResponseEntity response = + template.exchange( + restHelper.toUrl(Mapping.URL_WORKBASKET), + HttpMethod.GET, restHelper.defaultRequest(), ParameterizedTypeReference.forType(WorkbasketSummaryListResource.class)); - assertNotNull(response.getBody().getLink(Link.REL_SELF)); - assertEquals(3, response.getBody().getContent().size()); - } + assertNotNull(response.getBody().getLink(Link.REL_SELF)); + } - @Test - void testGetAllWorkbasketsKeepingFilters() { - String parameters = "?type=PERSONAL&sort-by=key&order=desc"; - ResponseEntity response = template.exchange( - restHelper.toUrl(Mapping.URL_WORKBASKET) + parameters, HttpMethod.GET, restHelper.defaultRequest(), + @Test + void testGetAllWorkbasketsBusinessAdminHasOpenPermission() { + ResponseEntity response = + template.exchange( + restHelper.toUrl(Mapping.URL_WORKBASKET) + "?required-permission=OPEN", + HttpMethod.GET, + restHelper.defaultRequest(), ParameterizedTypeReference.forType(WorkbasketSummaryListResource.class)); - assertNotNull(response.getBody().getLink(Link.REL_SELF)); - assertTrue(response.getBody() - .getLink(Link.REL_SELF) - .getHref() - .endsWith(parameters)); - } + assertNotNull(response.getBody().getLink(Link.REL_SELF)); + assertEquals(3, response.getBody().getContent().size()); + } - @Test - void testThrowsExceptionIfInvalidFilterIsUsed() { - try { - template.exchange( - restHelper.toUrl(Mapping.URL_WORKBASKET) + "?invalid=PERSONAL", HttpMethod.GET, - restHelper.defaultRequest(), - ParameterizedTypeReference.forType(WorkbasketSummaryListResource.class)); - fail(); - } catch (HttpClientErrorException e) { - assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); - assertTrue(e.getResponseBodyAsString().contains("[invalid]")); - } - } - - @Test - void testGetSecondPageSortedByKey() { - - String parameters = "?sort-by=key&order=desc&page=2&page-size=5"; - ResponseEntity response = template.exchange( - restHelper.toUrl(Mapping.URL_WORKBASKET) + parameters, HttpMethod.GET, restHelper.defaultRequest(), + @Test + void testGetAllWorkbasketsKeepingFilters() { + String parameters = "?type=PERSONAL&sort-by=key&order=desc"; + ResponseEntity response = + template.exchange( + restHelper.toUrl(Mapping.URL_WORKBASKET) + parameters, + HttpMethod.GET, + restHelper.defaultRequest(), ParameterizedTypeReference.forType(WorkbasketSummaryListResource.class)); - assertEquals(5, response.getBody().getContent().size()); - assertEquals("USER_1_1", response.getBody().getContent().iterator().next().getKey()); - assertNotNull(response.getBody().getLink(Link.REL_SELF)); - assertTrue(response.getBody() - .getLink(Link.REL_SELF) - .getHref() - .endsWith(parameters)); - assertNotNull(response.getBody().getLink(Link.REL_FIRST)); - assertNotNull(response.getBody().getLink(Link.REL_LAST)); - assertNotNull(response.getBody().getLink(Link.REL_NEXT)); - assertNotNull(response.getBody().getLink(Link.REL_PREVIOUS)); - } + assertNotNull(response.getBody().getLink(Link.REL_SELF)); + assertTrue(response.getBody().getLink(Link.REL_SELF).getHref().endsWith(parameters)); + } - @Test - void testRemoveWorkbasketAsDistributionTarget() { - ResponseEntity response = template.exchange( - restHelper.toUrl(Mapping.URL_WORKBASKET_DISTRIBUTION_ID, "WBI:100000000000000000000000000000000007"), - HttpMethod.DELETE, restHelper.defaultRequest(), - Void.class - ); - assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); - - ResponseEntity response2 = template.exchange( - restHelper.toUrl(Mapping.URL_WORKBASKET_ID_DISTRIBUTION, "WBI:100000000000000000000000000000000002"), - HttpMethod.GET, restHelper.defaultRequest(), - ParameterizedTypeReference.forType(DistributionTargetListResource.class) - ); - assertEquals(HttpStatus.OK, response2.getStatusCode()); - Iterator iterator = response2.getBody().getContent().iterator(); - while (iterator.hasNext()) { - assertNotEquals("WBI:100000000000000000000000000000000007", iterator.next().getWorkbasketId()); - } + @Test + void testThrowsExceptionIfInvalidFilterIsUsed() { + try { + template.exchange( + restHelper.toUrl(Mapping.URL_WORKBASKET) + "?invalid=PERSONAL", + HttpMethod.GET, + restHelper.defaultRequest(), + ParameterizedTypeReference.forType(WorkbasketSummaryListResource.class)); + fail(); + } catch (HttpClientErrorException e) { + assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); + assertTrue(e.getResponseBodyAsString().contains("[invalid]")); } + } + + @Test + void testGetSecondPageSortedByKey() { + + String parameters = "?sort-by=key&order=desc&page=2&page-size=5"; + ResponseEntity response = + template.exchange( + restHelper.toUrl(Mapping.URL_WORKBASKET) + parameters, + HttpMethod.GET, + restHelper.defaultRequest(), + ParameterizedTypeReference.forType(WorkbasketSummaryListResource.class)); + assertEquals(5, response.getBody().getContent().size()); + assertEquals("USER_1_1", response.getBody().getContent().iterator().next().getKey()); + assertNotNull(response.getBody().getLink(Link.REL_SELF)); + assertTrue(response.getBody().getLink(Link.REL_SELF).getHref().endsWith(parameters)); + assertNotNull(response.getBody().getLink(Link.REL_FIRST)); + assertNotNull(response.getBody().getLink(Link.REL_LAST)); + assertNotNull(response.getBody().getLink(Link.REL_NEXT)); + assertNotNull(response.getBody().getLink(Link.REL_PREVIOUS)); + } + + @Test + void testRemoveWorkbasketAsDistributionTarget() { + ResponseEntity response = + template.exchange( + restHelper.toUrl( + Mapping.URL_WORKBASKET_DISTRIBUTION_ID, "WBI:100000000000000000000000000000000007"), + HttpMethod.DELETE, + restHelper.defaultRequest(), + Void.class); + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + + ResponseEntity response2 = + template.exchange( + restHelper.toUrl( + Mapping.URL_WORKBASKET_ID_DISTRIBUTION, "WBI:100000000000000000000000000000000002"), + HttpMethod.GET, + restHelper.defaultRequest(), + ParameterizedTypeReference.forType(DistributionTargetListResource.class)); + assertEquals(HttpStatus.OK, response2.getStatusCode()); + Iterator iterator = response2.getBody().getContent().iterator(); + while (iterator.hasNext()) { + assertNotEquals( + "WBI:100000000000000000000000000000000007", iterator.next().getWorkbasketId()); + } + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/WorkbasketDefinitionControllerIntTest.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/WorkbasketDefinitionControllerIntTest.java index 00e4d3888..056b50898 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/WorkbasketDefinitionControllerIntTest.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/WorkbasketDefinitionControllerIntTest.java @@ -7,12 +7,12 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; - import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.slf4j.Logger; @@ -31,135 +31,132 @@ import org.springframework.util.MultiValueMap; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; -import com.fasterxml.jackson.databind.ObjectMapper; - import pro.taskana.RestHelper; import pro.taskana.TaskanaSpringBootTest; import pro.taskana.rest.resource.WorkbasketDefinitionResource; -/** - * Integration tests for WorkbasketDefinitionController. - */ +/** Integration tests for WorkbasketDefinitionController. */ @TaskanaSpringBootTest class WorkbasketDefinitionControllerIntTest { - private static final Logger LOGGER = LoggerFactory.getLogger(ClassificationController.class); - private ObjectMapper objMapper = new ObjectMapper(); + private static final Logger LOGGER = LoggerFactory.getLogger(ClassificationController.class); + private static RestTemplate template; + @Autowired RestHelper restHelper; + private ObjectMapper objMapper = new ObjectMapper(); - @Autowired RestHelper restHelper; + @BeforeAll + static void init() { + template = RestHelper.getRestTemplate(); + } - private static RestTemplate template; - - @BeforeAll - static void init() { - template = RestHelper.getRestTemplate(); - } - - @Test - void testExportWorkbasketFromDomain() { - ResponseEntity> response = template.exchange( - restHelper.toUrl(Mapping.URL_WORKBASKETDEFIITIONS) + "?domain=DOMAIN_A", HttpMethod.GET, + @Test + void testExportWorkbasketFromDomain() { + ResponseEntity> response = + template.exchange( + restHelper.toUrl(Mapping.URL_WORKBASKETDEFIITIONS) + "?domain=DOMAIN_A", + HttpMethod.GET, restHelper.defaultRequest(), - new ParameterizedTypeReference>() { + new ParameterizedTypeReference>() {}); - }); - assertNotNull(response.getBody()); - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertThat(response.getBody().get(0), instanceOf(WorkbasketDefinitionResource.class)); + assertNotNull(response.getBody()); + assertEquals(HttpStatus.OK, response.getStatusCode()); + assertThat(response.getBody().get(0), instanceOf(WorkbasketDefinitionResource.class)); - boolean allAuthorizationsAreEmpty = true, allDistributionTargetsAreEmpty = true; - for (WorkbasketDefinitionResource workbasketDefinition : response.getBody()) { - if (allAuthorizationsAreEmpty && !workbasketDefinition.getAuthorizations().isEmpty()) { - allAuthorizationsAreEmpty = false; - } - if (allDistributionTargetsAreEmpty && !workbasketDefinition.getDistributionTargets().isEmpty()) { - allDistributionTargetsAreEmpty = false; - } - if (!allAuthorizationsAreEmpty && !allDistributionTargetsAreEmpty) { - break; - } - } - assertFalse(allDistributionTargetsAreEmpty); - assertFalse(allAuthorizationsAreEmpty); + boolean allAuthorizationsAreEmpty = true, allDistributionTargetsAreEmpty = true; + for (WorkbasketDefinitionResource workbasketDefinition : response.getBody()) { + if (allAuthorizationsAreEmpty && !workbasketDefinition.getAuthorizations().isEmpty()) { + allAuthorizationsAreEmpty = false; + } + if (allDistributionTargetsAreEmpty + && !workbasketDefinition.getDistributionTargets().isEmpty()) { + allDistributionTargetsAreEmpty = false; + } + if (!allAuthorizationsAreEmpty && !allDistributionTargetsAreEmpty) { + break; + } } + assertFalse(allDistributionTargetsAreEmpty); + assertFalse(allAuthorizationsAreEmpty); + } - @Test - void testExportWorkbasketsFromWrongDomain() { - ResponseEntity> response = template.exchange( - restHelper.toUrl(Mapping.URL_WORKBASKETDEFIITIONS) + "?domain=wrongDomain", HttpMethod.GET, + @Test + void testExportWorkbasketsFromWrongDomain() { + ResponseEntity> response = + template.exchange( + restHelper.toUrl(Mapping.URL_WORKBASKETDEFIITIONS) + "?domain=wrongDomain", + HttpMethod.GET, restHelper.defaultRequest(), ParameterizedTypeReference.forType(List.class)); - assertEquals(0, response.getBody().size()); - } + assertEquals(0, response.getBody().size()); + } - @Test - void testImportWorkbasket() throws IOException { - ResponseEntity> response = template.exchange( - - restHelper.toUrl(Mapping.URL_WORKBASKETDEFIITIONS) + "?domain=DOMAIN_A", HttpMethod.GET, + @Test + void testImportWorkbasket() throws IOException { + ResponseEntity> response = + template.exchange( + restHelper.toUrl(Mapping.URL_WORKBASKETDEFIITIONS) + "?domain=DOMAIN_A", + HttpMethod.GET, restHelper.defaultRequest(), ParameterizedTypeReference.forType(List.class)); - List list = new ArrayList<>(); - list.add(objMapper.writeValueAsString(response.getBody().get(0))); - ResponseEntity responseImport = importRequest(list); - assertEquals(HttpStatus.NO_CONTENT, responseImport.getStatusCode()); - } + List list = new ArrayList<>(); + list.add(objMapper.writeValueAsString(response.getBody().get(0))); + ResponseEntity responseImport = importRequest(list); + assertEquals(HttpStatus.NO_CONTENT, responseImport.getStatusCode()); + } - @Test - void testFailOnImportDuplicates() throws IOException { - ResponseEntity> response = template.exchange( - restHelper.toUrl(Mapping.URL_WORKBASKETDEFIITIONS) + "?domain=DOMAIN_A", HttpMethod.GET, + @Test + void testFailOnImportDuplicates() throws IOException { + ResponseEntity> response = + template.exchange( + restHelper.toUrl(Mapping.URL_WORKBASKETDEFIITIONS) + "?domain=DOMAIN_A", + HttpMethod.GET, restHelper.defaultRequest(), - new ParameterizedTypeReference>() { + new ParameterizedTypeReference>() {}); - }); - - List list = new ArrayList<>(); - list.add(objMapper.writeValueAsString(response.getBody().get(0))); - list.add(objMapper.writeValueAsString(response.getBody().get(0))); - try { - importRequest(list); - fail("Expected http-Status 409"); - } catch (HttpClientErrorException e) { - assertEquals(HttpStatus.CONFLICT, e.getStatusCode()); - } + List list = new ArrayList<>(); + list.add(objMapper.writeValueAsString(response.getBody().get(0))); + list.add(objMapper.writeValueAsString(response.getBody().get(0))); + try { + importRequest(list); + fail("Expected http-Status 409"); + } catch (HttpClientErrorException e) { + assertEquals(HttpStatus.CONFLICT, e.getStatusCode()); } + } - @Test - void testNoErrorWhenImportWithSameIdButDifferentKeyAndDomain() - throws IOException { - ResponseEntity> response = template.exchange( - - restHelper.toUrl(Mapping.URL_WORKBASKETDEFIITIONS) + "?domain=DOMAIN_A", HttpMethod.GET, + @Test + void testNoErrorWhenImportWithSameIdButDifferentKeyAndDomain() throws IOException { + ResponseEntity> response = + template.exchange( + restHelper.toUrl(Mapping.URL_WORKBASKETDEFIITIONS) + "?domain=DOMAIN_A", + HttpMethod.GET, restHelper.defaultRequest(), - new ParameterizedTypeReference>() { + new ParameterizedTypeReference>() {}); - }); + List list = new ArrayList<>(); + WorkbasketDefinitionResource wbDef = response.getBody().get(0); + list.add(objMapper.writeValueAsString(wbDef)); + wbDef.getWorkbasket().setKey("new Key for this WB"); + list.add(objMapper.writeValueAsString(wbDef)); + ResponseEntity responseImport = importRequest(list); + assertEquals(HttpStatus.NO_CONTENT, responseImport.getStatusCode()); + } - List list = new ArrayList<>(); - WorkbasketDefinitionResource wbDef = response.getBody().get(0); - list.add(objMapper.writeValueAsString(wbDef)); - wbDef.getWorkbasket().setKey("new Key for this WB"); - list.add(objMapper.writeValueAsString(wbDef)); - ResponseEntity responseImport = importRequest(list); - assertEquals(HttpStatus.NO_CONTENT, responseImport.getStatusCode()); - } + private ResponseEntity importRequest(List clList) throws IOException { + File tmpFile = File.createTempFile("test", ".tmp"); + FileWriter writer = new FileWriter(tmpFile); + writer.write(clList.toString()); + writer.close(); - private ResponseEntity importRequest(List clList) throws IOException { - File tmpFile = File.createTempFile("test", ".tmp"); - FileWriter writer = new FileWriter(tmpFile); - writer.write(clList.toString()); - writer.close(); + MultiValueMap body = new LinkedMultiValueMap<>(); + HttpHeaders headers = restHelper.getHeaders(); + headers.setContentType(MediaType.MULTIPART_FORM_DATA); + body.add("file", new FileSystemResource(tmpFile)); - MultiValueMap body = new LinkedMultiValueMap<>(); - HttpHeaders headers = restHelper.getHeaders(); - headers.setContentType(MediaType.MULTIPART_FORM_DATA); - body.add("file", new FileSystemResource(tmpFile)); + HttpEntity> requestEntity = new HttpEntity<>(body, headers); + String serverUrl = restHelper.toUrl(Mapping.URL_WORKBASKETDEFIITIONS); - HttpEntity> requestEntity = new HttpEntity<>(body, headers); - String serverUrl = restHelper.toUrl(Mapping.URL_WORKBASKETDEFIITIONS); - - return template.postForEntity(serverUrl, requestEntity, Void.class); - } + return template.postForEntity(serverUrl, requestEntity, Void.class); + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/resource/ClassificationAssemblerTest.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/resource/ClassificationAssemblerTest.java index d9c2939b2..33034efa6 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/resource/ClassificationAssemblerTest.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/resource/ClassificationAssemblerTest.java @@ -1,7 +1,6 @@ package pro.taskana.rest.resource; import java.time.Instant; - import org.junit.Assert; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -11,106 +10,106 @@ import pro.taskana.ClassificationService; import pro.taskana.TaskanaSpringBootTest; import pro.taskana.impl.ClassificationImpl; -/** - * Test for {@link ClassificationResourceAssembler}. - */ +/** Test for {@link ClassificationResourceAssembler}. */ @TaskanaSpringBootTest class ClassificationAssemblerTest { - @Autowired - private ClassificationResourceAssembler classificationResourceAssembler; + @Autowired private ClassificationResourceAssembler classificationResourceAssembler; - @Autowired - private ClassificationService classificationService; + @Autowired private ClassificationService classificationService; - @Test - void classificationToResource() { - // given - ClassificationImpl classification = (ClassificationImpl) classificationService.newClassification("DOMAIN_A", - "1", "A"); - classification.setId("1"); - classification.setCategory("ABC"); - classification.setName("Classification 1"); - classification.setIsValidInDomain(true); - classification.setCustom1("Custom1"); - classification.setCustom2("Custom2"); - classification.setCustom3("Custom3"); - classification.setCustom4("Custom4"); - classification.setCustom5("Custom5"); - classification.setCustom6("Custom6"); - classification.setCustom7("Custom7"); - classification.setCustom8("Custom8"); - classification.setParentId("2"); - classification.setPriority(2); - classification.setApplicationEntryPoint("12"); - classification.setServiceLevel("P1D"); - classification.setDescription("Test"); - classification.setCreated(Instant.parse("2010-01-01T12:00:00Z")); - classification.setModified(Instant.parse("2011-11-11T11:00:00Z")); - // when - ClassificationResource classificationResource = classificationResourceAssembler.toResource(classification); - // then - testEquality(classification, classificationResource); - } + @Test + void classificationToResource() { + // given + ClassificationImpl classification = + (ClassificationImpl) classificationService.newClassification("DOMAIN_A", "1", "A"); + classification.setId("1"); + classification.setCategory("ABC"); + classification.setName("Classification 1"); + classification.setIsValidInDomain(true); + classification.setCustom1("Custom1"); + classification.setCustom2("Custom2"); + classification.setCustom3("Custom3"); + classification.setCustom4("Custom4"); + classification.setCustom5("Custom5"); + classification.setCustom6("Custom6"); + classification.setCustom7("Custom7"); + classification.setCustom8("Custom8"); + classification.setParentId("2"); + classification.setPriority(2); + classification.setApplicationEntryPoint("12"); + classification.setServiceLevel("P1D"); + classification.setDescription("Test"); + classification.setCreated(Instant.parse("2010-01-01T12:00:00Z")); + classification.setModified(Instant.parse("2011-11-11T11:00:00Z")); + // when + ClassificationResource classificationResource = + classificationResourceAssembler.toResource(classification); + // then + testEquality(classification, classificationResource); + } - @Test - void resourceToClassification() { - ClassificationImpl classification = (ClassificationImpl) classificationService.newClassification("12", - "DOMAIN_B", "AB"); + @Test + void resourceToClassification() { + ClassificationImpl classification = + (ClassificationImpl) classificationService.newClassification("12", "DOMAIN_B", "AB"); - // given - classification.setId("1"); - classification.setType("AB"); - classification.setDomain("DOMAIN_B"); - classification.setApplicationEntryPoint("Test"); - classification.setCategory("ABC"); - classification.setCreated(Instant.parse("2010-01-01T12:00:00Z")); - classification.setModified(Instant.parse("2011-11-11T11:00:00Z")); - classification.setCustom1("Custom"); - classification.setCustom2("Custom2"); - classification.setCustom1("Custom1"); - classification.setCustom3("Custom3"); - classification.setCustom4("Custom4"); - classification.setCustom5("Custom5"); - classification.setCustom6("Custom6"); - classification.setCustom7("Custom7"); - classification.setCustom8("Custom8"); - classification.setParentId("2"); - classification.setPriority(2); - classification.setApplicationEntryPoint("12"); - classification.setServiceLevel("P1D"); - classification.setDescription("Test"); - classification.setIsValidInDomain(true); + // given + classification.setId("1"); + classification.setType("AB"); + classification.setDomain("DOMAIN_B"); + classification.setApplicationEntryPoint("Test"); + classification.setCategory("ABC"); + classification.setCreated(Instant.parse("2010-01-01T12:00:00Z")); + classification.setModified(Instant.parse("2011-11-11T11:00:00Z")); + classification.setCustom1("Custom"); + classification.setCustom2("Custom2"); + classification.setCustom1("Custom1"); + classification.setCustom3("Custom3"); + classification.setCustom4("Custom4"); + classification.setCustom5("Custom5"); + classification.setCustom6("Custom6"); + classification.setCustom7("Custom7"); + classification.setCustom8("Custom8"); + classification.setParentId("2"); + classification.setPriority(2); + classification.setApplicationEntryPoint("12"); + classification.setServiceLevel("P1D"); + classification.setDescription("Test"); + classification.setIsValidInDomain(true); - ClassificationResource classificationResource = new ClassificationResource(classification); + ClassificationResource classificationResource = new ClassificationResource(classification); - // when - classification = (ClassificationImpl) classificationResourceAssembler - .toModel(classificationResource); - // then - testEquality(classification, classificationResource); - } + // when + classification = + (ClassificationImpl) classificationResourceAssembler.toModel(classificationResource); + // then + testEquality(classification, classificationResource); + } - private void testEquality(Classification classification, ClassificationResource classificationResource) { - Assert.assertEquals(classification.getApplicationEntryPoint(), classificationResource.applicationEntryPoint); - Assert.assertEquals(classification.getKey(), classificationResource.key); - Assert.assertEquals(classification.getDomain(), classificationResource.domain); - Assert.assertEquals(classification.getId(), classificationResource.classificationId); - Assert.assertEquals(classification.getDescription(), classificationResource.description); - Assert.assertEquals(classification.getName(), classificationResource.name); - Assert.assertEquals(classification.getServiceLevel(), classificationResource.serviceLevel); - Assert.assertEquals(classification.getCategory(), classificationResource.category); - Assert.assertEquals(classification.getCustom1(), classificationResource.custom1); - Assert.assertEquals(classification.getCustom2(), classificationResource.custom2); - Assert.assertEquals(classification.getCustom3(), classificationResource.custom3); - Assert.assertEquals(classification.getCustom4(), classificationResource.custom4); - Assert.assertEquals(classification.getCustom5(), classificationResource.custom5); - Assert.assertEquals(classification.getCustom6(), classificationResource.custom6); - Assert.assertEquals(classification.getCustom7(), classificationResource.custom7); - Assert.assertEquals(classification.getCustom8(), classificationResource.custom8); - Assert.assertEquals(classification.getParentId(), classificationResource.parentId); - Assert.assertEquals(classification.getType(), classificationResource.type); - Assert.assertEquals(classification.getPriority(), classificationResource.priority); - Assert.assertEquals(classification.getIsValidInDomain(), classificationResource.isValidInDomain); - } + private void testEquality( + Classification classification, ClassificationResource classificationResource) { + Assert.assertEquals( + classification.getApplicationEntryPoint(), classificationResource.applicationEntryPoint); + Assert.assertEquals(classification.getKey(), classificationResource.key); + Assert.assertEquals(classification.getDomain(), classificationResource.domain); + Assert.assertEquals(classification.getId(), classificationResource.classificationId); + Assert.assertEquals(classification.getDescription(), classificationResource.description); + Assert.assertEquals(classification.getName(), classificationResource.name); + Assert.assertEquals(classification.getServiceLevel(), classificationResource.serviceLevel); + Assert.assertEquals(classification.getCategory(), classificationResource.category); + Assert.assertEquals(classification.getCustom1(), classificationResource.custom1); + Assert.assertEquals(classification.getCustom2(), classificationResource.custom2); + Assert.assertEquals(classification.getCustom3(), classificationResource.custom3); + Assert.assertEquals(classification.getCustom4(), classificationResource.custom4); + Assert.assertEquals(classification.getCustom5(), classificationResource.custom5); + Assert.assertEquals(classification.getCustom6(), classificationResource.custom6); + Assert.assertEquals(classification.getCustom7(), classificationResource.custom7); + Assert.assertEquals(classification.getCustom8(), classificationResource.custom8); + Assert.assertEquals(classification.getParentId(), classificationResource.parentId); + Assert.assertEquals(classification.getType(), classificationResource.type); + Assert.assertEquals(classification.getPriority(), classificationResource.priority); + Assert.assertEquals( + classification.getIsValidInDomain(), classificationResource.isValidInDomain); + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/resource/ReportResourceTest.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/resource/ReportResourceTest.java index 226f4332c..a9b8fb335 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/resource/ReportResourceTest.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/resource/ReportResourceTest.java @@ -12,7 +12,6 @@ import java.time.temporal.ChronoUnit; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -24,321 +23,324 @@ import pro.taskana.impl.report.item.MonitorQueryItem; import pro.taskana.report.ClassificationReport; import pro.taskana.report.WorkbasketReport; -/** - * Test for {@link ReportResourceAssembler}. - */ - +/** Test for {@link ReportResourceAssembler}. */ @TaskanaSpringBootTest class ReportResourceTest { - @Autowired - private ReportResourceAssembler reportResourceAssembler; + @Autowired private ReportResourceAssembler reportResourceAssembler; - private int daysDiff; - private LocalDateTime now; - private List headers; + private int daysDiff; + private LocalDateTime now; + private List headers; - @BeforeEach - void before() { - now = LocalDate.parse("2019-01-02").atStartOfDay(); - daysDiff = (int) LocalDateTime.now().until(now, ChronoUnit.DAYS); - headers = IntStream.range(daysDiff - 5, daysDiff) + @BeforeEach + void before() { + now = LocalDate.parse("2019-01-02").atStartOfDay(); + daysDiff = (int) LocalDateTime.now().until(now, ChronoUnit.DAYS); + headers = + IntStream.range(daysDiff - 5, daysDiff) .mapToObj(TimeIntervalColumnHeader.Date::new) .collect(Collectors.toList()); + } - } + @Test + void testEmptyReport() { + // given + WorkbasketReport report = new WorkbasketReport(headers); + // when + ReportResource resource = + reportResourceAssembler.toReportResource(report, now.toInstant(ZoneOffset.UTC)); + // then - @Test - void testEmptyReport() { - // given - WorkbasketReport report = new WorkbasketReport(headers); - // when - ReportResource resource = reportResourceAssembler.toReportResource(report, now.toInstant(ZoneOffset.UTC)); - // then + // meta + ReportResource.MetaInformation meta = resource.getMeta(); + assertEquals("WorkbasketReport", meta.getName()); + assertEquals("2019-01-02T00:00:00Z", meta.getDate()); + assertArrayEquals(new String[] {"WORKBASKET KEYS"}, meta.getRowDesc()); + assertArrayEquals( + headers.stream().map(TimeIntervalColumnHeader::getDisplayName).toArray(), meta.getHeader()); + assertEquals("Total", meta.getTotalDesc()); - // meta - ReportResource.MetaInformation meta = resource.getMeta(); - assertEquals("WorkbasketReport", meta.getName()); - assertEquals("2019-01-02T00:00:00Z", meta.getDate()); - assertArrayEquals(new String[] {"WORKBASKET KEYS"}, meta.getRowDesc()); - assertArrayEquals(headers.stream().map(TimeIntervalColumnHeader::getDisplayName).toArray(), meta.getHeader()); - assertEquals("Total", meta.getTotalDesc()); + // rows + assertTrue(resource.getRows().isEmpty()); - // rows - assertTrue(resource.getRows().isEmpty()); + // sumRow + assertEquals(1, resource.getSumRow().size()); + ReportResource.RowResource sumRow = resource.getSumRow().get(0); + assertArrayEquals(new String[] {"Total"}, sumRow.getDesc()); + assertTrue(sumRow.isDisplay()); + assertEquals(0, sumRow.getDepth()); + assertEquals(0, sumRow.getTotal()); + assertArrayEquals(new int[] {0, 0, 0, 0, 0}, sumRow.getCells()); + } - // sumRow - assertEquals(1, resource.getSumRow().size()); - ReportResource.RowResource sumRow = resource.getSumRow().get(0); - assertArrayEquals(new String[] {"Total"}, sumRow.getDesc()); - assertTrue(sumRow.isDisplay()); - assertEquals(0, sumRow.getDepth()); - assertEquals(0, sumRow.getTotal()); - assertArrayEquals(new int[] {0, 0, 0, 0, 0}, sumRow.getCells()); - } + @Test + void testOneSingleRow() { + // given + ClassificationReport report = new ClassificationReport(headers); + MonitorQueryItem item = new MonitorQueryItem(); + item.setAgeInDays(daysDiff - 1); + item.setNumberOfTasks(2); + item.setKey("key"); + report.addItem(item); + // when + ReportResource resource = + reportResourceAssembler.toReportResource(report, now.toInstant(ZoneOffset.UTC)); + // then - @Test - void testOneSingleRow() { - // given - ClassificationReport report = new ClassificationReport(headers); - MonitorQueryItem item = new MonitorQueryItem(); - item.setAgeInDays(daysDiff - 1); - item.setNumberOfTasks(2); - item.setKey("key"); - report.addItem(item); - // when - ReportResource resource = reportResourceAssembler.toReportResource(report, now.toInstant(ZoneOffset.UTC)); - // then + // meta + ReportResource.MetaInformation meta = resource.getMeta(); + assertEquals("ClassificationReport", meta.getName()); + assertEquals("2019-01-02T00:00:00Z", meta.getDate()); + assertArrayEquals(new String[] {"CLASSIFICATION KEYS"}, meta.getRowDesc()); + assertArrayEquals( + headers.stream().map(TimeIntervalColumnHeader::getDisplayName).toArray(), meta.getHeader()); + assertEquals("Total", meta.getTotalDesc()); - // meta - ReportResource.MetaInformation meta = resource.getMeta(); - assertEquals("ClassificationReport", meta.getName()); - assertEquals("2019-01-02T00:00:00Z", meta.getDate()); - assertArrayEquals(new String[] {"CLASSIFICATION KEYS"}, meta.getRowDesc()); - assertArrayEquals(headers.stream().map(TimeIntervalColumnHeader::getDisplayName).toArray(), meta.getHeader()); - assertEquals("Total", meta.getTotalDesc()); + // rows + List rows = resource.getRows(); + assertEquals(1, rows.size()); + ReportResource.RowResource row = rows.get(0); + assertArrayEquals(new String[] {"key"}, row.getDesc()); + assertEquals(0, row.getDepth()); + assertEquals(2, row.getTotal()); - // rows - List rows = resource.getRows(); - assertEquals(1, rows.size()); - ReportResource.RowResource row = rows.get(0); - assertArrayEquals(new String[] {"key"}, row.getDesc()); - assertEquals(0, row.getDepth()); - assertEquals(2, row.getTotal()); + assertTrue(row.isDisplay()); + assertArrayEquals(new int[] {0, 0, 0, 0, 2}, row.getCells()); - assertTrue(row.isDisplay()); - assertArrayEquals(new int[] {0, 0, 0, 0, 2}, row.getCells()); + // sumRow + assertEquals(1, resource.getSumRow().size()); + ReportResource.RowResource sumRow = resource.getSumRow().get(0); + assertArrayEquals(new String[] {"Total"}, sumRow.getDesc()); + assertTrue(sumRow.isDisplay()); + assertEquals(0, sumRow.getDepth()); + assertEquals(2, sumRow.getTotal()); + assertArrayEquals(new int[] {0, 0, 0, 0, 2}, sumRow.getCells()); + } - // sumRow - assertEquals(1, resource.getSumRow().size()); - ReportResource.RowResource sumRow = resource.getSumRow().get(0); - assertArrayEquals(new String[] {"Total"}, sumRow.getDesc()); - assertTrue(sumRow.isDisplay()); - assertEquals(0, sumRow.getDepth()); - assertEquals(2, sumRow.getTotal()); - assertArrayEquals(new int[] {0, 0, 0, 0, 2}, sumRow.getCells()); + @Test + void testMultipleSingleRows() { + // given + ClassificationReport report = new ClassificationReport(headers); + MonitorQueryItem item = new MonitorQueryItem(); + item.setAgeInDays(daysDiff - 1); + item.setNumberOfTasks(2); + item.setKey("key"); + report.addItem(item); + item.setKey("key2"); + report.addItem(item); + // when + ReportResource resource = + reportResourceAssembler.toReportResource(report, now.toInstant(ZoneOffset.UTC)); + // then - } + // meta + ReportResource.MetaInformation meta = resource.getMeta(); + assertEquals("ClassificationReport", meta.getName()); + assertEquals("2019-01-02T00:00:00Z", meta.getDate()); + assertArrayEquals(new String[] {"CLASSIFICATION KEYS"}, meta.getRowDesc()); + assertArrayEquals( + headers.stream().map(TimeIntervalColumnHeader::getDisplayName).toArray(), meta.getHeader()); + assertEquals("Total", meta.getTotalDesc()); - @Test - void testMultipleSingleRows() { - // given - ClassificationReport report = new ClassificationReport(headers); - MonitorQueryItem item = new MonitorQueryItem(); - item.setAgeInDays(daysDiff - 1); - item.setNumberOfTasks(2); - item.setKey("key"); - report.addItem(item); - item.setKey("key2"); - report.addItem(item); - // when - ReportResource resource = reportResourceAssembler.toReportResource(report, now.toInstant(ZoneOffset.UTC)); - // then + // rows + List rows = resource.getRows(); + assertEquals(2, rows.size()); - // meta - ReportResource.MetaInformation meta = resource.getMeta(); - assertEquals("ClassificationReport", meta.getName()); - assertEquals("2019-01-02T00:00:00Z", meta.getDate()); - assertArrayEquals(new String[] {"CLASSIFICATION KEYS"}, meta.getRowDesc()); - assertArrayEquals(headers.stream().map(TimeIntervalColumnHeader::getDisplayName).toArray(), meta.getHeader()); - assertEquals("Total", meta.getTotalDesc()); + ReportResource.RowResource row = rows.get(0); + assertArrayEquals(new String[] {"key"}, row.getDesc()); + assertEquals(0, row.getDepth()); + assertTrue(row.isDisplay()); + assertEquals(2, row.getTotal()); + assertArrayEquals(new int[] {0, 0, 0, 0, 2}, row.getCells()); - // rows - List rows = resource.getRows(); - assertEquals(2, rows.size()); + row = rows.get(1); + assertArrayEquals(new String[] {"key2"}, row.getDesc()); + assertEquals(0, row.getDepth()); + assertTrue(row.isDisplay()); + assertEquals(2, row.getTotal()); + assertArrayEquals(new int[] {0, 0, 0, 0, 2}, row.getCells()); - ReportResource.RowResource row = rows.get(0); - assertArrayEquals(new String[] {"key"}, row.getDesc()); - assertEquals(0, row.getDepth()); - assertTrue(row.isDisplay()); - assertEquals(2, row.getTotal()); - assertArrayEquals(new int[] {0, 0, 0, 0, 2}, row.getCells()); + // sumRow + assertEquals(1, resource.getSumRow().size()); + ReportResource.RowResource sumRow = resource.getSumRow().get(0); + assertArrayEquals(new String[] {"Total"}, sumRow.getDesc()); + assertEquals(0, sumRow.getDepth()); + assertTrue(sumRow.isDisplay()); + assertEquals(4, sumRow.getTotal()); + assertArrayEquals(new int[] {0, 0, 0, 0, 4}, sumRow.getCells()); + } - row = rows.get(1); - assertArrayEquals(new String[] {"key2"}, row.getDesc()); - assertEquals(0, row.getDepth()); - assertTrue(row.isDisplay()); - assertEquals(2, row.getTotal()); - assertArrayEquals(new int[] {0, 0, 0, 0, 2}, row.getCells()); + @Test + void testOneFoldableRow() { + // given + ClassificationReport.DetailedClassificationReport report = + new ClassificationReport.DetailedClassificationReport(headers); + DetailedMonitorQueryItem item = new DetailedMonitorQueryItem(); + item.setAgeInDays(daysDiff - 1); + item.setNumberOfTasks(2); + item.setKey("key"); + item.setAttachmentKey("attachment"); + report.addItem(item); + item.setAttachmentKey(null); + report.addItem(item); + // when + ReportResource resource = + reportResourceAssembler.toReportResource(report, now.toInstant(ZoneOffset.UTC)); + // then - // sumRow - assertEquals(1, resource.getSumRow().size()); - ReportResource.RowResource sumRow = resource.getSumRow().get(0); - assertArrayEquals(new String[] {"Total"}, sumRow.getDesc()); - assertEquals(0, sumRow.getDepth()); - assertTrue(sumRow.isDisplay()); - assertEquals(4, sumRow.getTotal()); - assertArrayEquals(new int[] {0, 0, 0, 0, 4}, sumRow.getCells()); - } + // meta + ReportResource.MetaInformation meta = resource.getMeta(); + assertEquals("DetailedClassificationReport", meta.getName()); + assertEquals("2019-01-02T00:00:00Z", meta.getDate()); + assertArrayEquals(new String[] {"TASK CLASSIFICATION KEYS", "ATTACHMENT"}, meta.getRowDesc()); + assertArrayEquals( + headers.stream().map(TimeIntervalColumnHeader::getDisplayName).toArray(), meta.getHeader()); + assertEquals("Total", meta.getTotalDesc()); - @Test - void testOneFoldableRow() { - // given - ClassificationReport.DetailedClassificationReport report = new ClassificationReport.DetailedClassificationReport( - headers); - DetailedMonitorQueryItem item = new DetailedMonitorQueryItem(); - item.setAgeInDays(daysDiff - 1); - item.setNumberOfTasks(2); - item.setKey("key"); - item.setAttachmentKey("attachment"); - report.addItem(item); - item.setAttachmentKey(null); - report.addItem(item); - // when - ReportResource resource = reportResourceAssembler.toReportResource(report, now.toInstant(ZoneOffset.UTC)); - // then + // rows + List rows = resource.getRows(); + assertEquals(1 + 2, rows.size()); - // meta - ReportResource.MetaInformation meta = resource.getMeta(); - assertEquals("DetailedClassificationReport", meta.getName()); - assertEquals("2019-01-02T00:00:00Z", meta.getDate()); - assertArrayEquals(new String[] {"TASK CLASSIFICATION KEYS", "ATTACHMENT"}, meta.getRowDesc()); - assertArrayEquals(headers.stream().map(TimeIntervalColumnHeader::getDisplayName).toArray(), meta.getHeader()); - assertEquals("Total", meta.getTotalDesc()); + ReportResource.RowResource row = rows.get(0); + assertArrayEquals(new String[] {"key", null}, row.getDesc()); + assertEquals(0, row.getDepth()); + assertTrue(row.isDisplay()); + assertEquals(4, row.getTotal()); + assertArrayEquals(new int[] {0, 0, 0, 0, 4}, row.getCells()); - // rows - List rows = resource.getRows(); - assertEquals(1 + 2, rows.size()); + row = rows.get(1); + assertArrayEquals(new String[] {"key", "attachment"}, row.getDesc()); + assertEquals(1, row.getDepth()); + assertFalse(row.isDisplay()); + assertEquals(2, row.getTotal()); + assertArrayEquals(new int[] {0, 0, 0, 0, 2}, row.getCells()); - ReportResource.RowResource row = rows.get(0); - assertArrayEquals(new String[] {"key", null}, row.getDesc()); - assertEquals(0, row.getDepth()); - assertTrue(row.isDisplay()); - assertEquals(4, row.getTotal()); - assertArrayEquals(new int[] {0, 0, 0, 0, 4}, row.getCells()); + row = rows.get(2); + assertArrayEquals(new String[] {"key", "N/A"}, row.getDesc()); + assertEquals(1, row.getDepth()); + assertFalse(row.isDisplay()); + assertEquals(2, row.getTotal()); + assertArrayEquals(new int[] {0, 0, 0, 0, 2}, row.getCells()); - row = rows.get(1); - assertArrayEquals(new String[] {"key", "attachment"}, row.getDesc()); - assertEquals(1, row.getDepth()); - assertFalse(row.isDisplay()); - assertEquals(2, row.getTotal()); - assertArrayEquals(new int[] {0, 0, 0, 0, 2}, row.getCells()); + // sumRow + List sumRow = resource.getSumRow(); + assertEquals(1 + 2, sumRow.size()); - row = rows.get(2); - assertArrayEquals(new String[] {"key", "N/A"}, row.getDesc()); - assertEquals(1, row.getDepth()); - assertFalse(row.isDisplay()); - assertEquals(2, row.getTotal()); - assertArrayEquals(new int[] {0, 0, 0, 0, 2}, row.getCells()); + row = sumRow.get(0); + assertArrayEquals(new String[] {"Total", null}, row.getDesc()); + assertEquals(0, row.getDepth()); + assertTrue(row.isDisplay()); + assertEquals(4, row.getTotal()); + assertArrayEquals(new int[] {0, 0, 0, 0, 4}, row.getCells()); - // sumRow - List sumRow = resource.getSumRow(); - assertEquals(1 + 2, sumRow.size()); + row = sumRow.get(1); + assertArrayEquals(new String[] {"Total", "attachment"}, row.getDesc()); + assertEquals(1, row.getDepth()); + assertFalse(row.isDisplay()); + assertEquals(2, row.getTotal()); + assertArrayEquals(new int[] {0, 0, 0, 0, 2}, row.getCells()); - row = sumRow.get(0); - assertArrayEquals(new String[] {"Total", null}, row.getDesc()); - assertEquals(0, row.getDepth()); - assertTrue(row.isDisplay()); - assertEquals(4, row.getTotal()); - assertArrayEquals(new int[] {0, 0, 0, 0, 4}, row.getCells()); + row = sumRow.get(2); + assertArrayEquals(new String[] {"Total", "N/A"}, row.getDesc()); + assertEquals(1, row.getDepth()); + assertFalse(row.isDisplay()); + assertEquals(2, row.getTotal()); + assertArrayEquals(new int[] {0, 0, 0, 0, 2}, row.getCells()); + } - row = sumRow.get(1); - assertArrayEquals(new String[] {"Total", "attachment"}, row.getDesc()); - assertEquals(1, row.getDepth()); - assertFalse(row.isDisplay()); - assertEquals(2, row.getTotal()); - assertArrayEquals(new int[] {0, 0, 0, 0, 2}, row.getCells()); + @Test + void testMultipleFoldableRows() { + // given + ClassificationReport.DetailedClassificationReport report = + new ClassificationReport.DetailedClassificationReport(headers); + DetailedMonitorQueryItem item = new DetailedMonitorQueryItem(); + item.setAgeInDays(daysDiff - 1); + item.setNumberOfTasks(2); + item.setKey("key"); + item.setAttachmentKey("attachment"); + report.addItem(item); + item.setAttachmentKey(null); + report.addItem(item); + item.setKey("key2"); + report.addItem(item); + // when + ReportResource resource = + reportResourceAssembler.toReportResource(report, now.toInstant(ZoneOffset.UTC)); + // then - row = sumRow.get(2); - assertArrayEquals(new String[] {"Total", "N/A"}, row.getDesc()); - assertEquals(1, row.getDepth()); - assertFalse(row.isDisplay()); - assertEquals(2, row.getTotal()); - assertArrayEquals(new int[] {0, 0, 0, 0, 2}, row.getCells()); - } + // meta + ReportResource.MetaInformation meta = resource.getMeta(); + assertEquals("DetailedClassificationReport", meta.getName()); + assertEquals("2019-01-02T00:00:00Z", meta.getDate()); + assertArrayEquals(new String[] {"TASK CLASSIFICATION KEYS", "ATTACHMENT"}, meta.getRowDesc()); + assertArrayEquals( + headers.stream().map(TimeIntervalColumnHeader::getDisplayName).toArray(), meta.getHeader()); + assertEquals("Total", meta.getTotalDesc()); - @Test - void testMultipleFoldableRows() { - // given - ClassificationReport.DetailedClassificationReport report = new ClassificationReport.DetailedClassificationReport( - headers); - DetailedMonitorQueryItem item = new DetailedMonitorQueryItem(); - item.setAgeInDays(daysDiff - 1); - item.setNumberOfTasks(2); - item.setKey("key"); - item.setAttachmentKey("attachment"); - report.addItem(item); - item.setAttachmentKey(null); - report.addItem(item); - item.setKey("key2"); - report.addItem(item); - // when - ReportResource resource = reportResourceAssembler.toReportResource(report, now.toInstant(ZoneOffset.UTC)); - // then + // rows + List rows = resource.getRows(); + assertEquals((1 + 2) + (1 + 1), rows.size()); - // meta - ReportResource.MetaInformation meta = resource.getMeta(); - assertEquals("DetailedClassificationReport", meta.getName()); - assertEquals("2019-01-02T00:00:00Z", meta.getDate()); - assertArrayEquals(new String[] {"TASK CLASSIFICATION KEYS", "ATTACHMENT"}, meta.getRowDesc()); - assertArrayEquals(headers.stream().map(TimeIntervalColumnHeader::getDisplayName).toArray(), meta.getHeader()); - assertEquals("Total", meta.getTotalDesc()); + ReportResource.RowResource row = rows.get(0); + assertArrayEquals(new String[] {"key", null}, row.getDesc()); + assertEquals(0, row.getDepth()); + assertTrue(row.isDisplay()); + assertEquals(4, row.getTotal()); + assertArrayEquals(new int[] {0, 0, 0, 0, 4}, row.getCells()); - // rows - List rows = resource.getRows(); - assertEquals((1 + 2) + (1 + 1), rows.size()); + row = rows.get(1); + assertArrayEquals(new String[] {"key", "attachment"}, row.getDesc()); + assertEquals(1, row.getDepth()); + assertFalse(row.isDisplay()); + assertEquals(2, row.getTotal()); + assertArrayEquals(new int[] {0, 0, 0, 0, 2}, row.getCells()); - ReportResource.RowResource row = rows.get(0); - assertArrayEquals(new String[] {"key", null}, row.getDesc()); - assertEquals(0, row.getDepth()); - assertTrue(row.isDisplay()); - assertEquals(4, row.getTotal()); - assertArrayEquals(new int[] {0, 0, 0, 0, 4}, row.getCells()); + row = rows.get(2); + assertArrayEquals(new String[] {"key", "N/A"}, row.getDesc()); + assertEquals(1, row.getDepth()); + assertFalse(row.isDisplay()); + assertEquals(2, row.getTotal()); + assertArrayEquals(new int[] {0, 0, 0, 0, 2}, row.getCells()); - row = rows.get(1); - assertArrayEquals(new String[] {"key", "attachment"}, row.getDesc()); - assertEquals(1, row.getDepth()); - assertFalse(row.isDisplay()); - assertEquals(2, row.getTotal()); - assertArrayEquals(new int[] {0, 0, 0, 0, 2}, row.getCells()); + row = rows.get(3); + assertArrayEquals(new String[] {"key2", null}, row.getDesc()); + assertEquals(0, row.getDepth()); + assertTrue(row.isDisplay()); + assertEquals(2, row.getTotal()); + assertArrayEquals(new int[] {0, 0, 0, 0, 2}, row.getCells()); - row = rows.get(2); - assertArrayEquals(new String[] {"key", "N/A"}, row.getDesc()); - assertEquals(1, row.getDepth()); - assertFalse(row.isDisplay()); - assertEquals(2, row.getTotal()); - assertArrayEquals(new int[] {0, 0, 0, 0, 2}, row.getCells()); + row = rows.get(4); + assertArrayEquals(new String[] {"key2", "N/A"}, row.getDesc()); + assertEquals(1, row.getDepth()); + assertFalse(row.isDisplay()); + assertEquals(2, row.getTotal()); + assertArrayEquals(new int[] {0, 0, 0, 0, 2}, row.getCells()); - row = rows.get(3); - assertArrayEquals(new String[] {"key2", null}, row.getDesc()); - assertEquals(0, row.getDepth()); - assertTrue(row.isDisplay()); - assertEquals(2, row.getTotal()); - assertArrayEquals(new int[] {0, 0, 0, 0, 2}, row.getCells()); + // sumRow - row = rows.get(4); - assertArrayEquals(new String[] {"key2", "N/A"}, row.getDesc()); - assertEquals(1, row.getDepth()); - assertFalse(row.isDisplay()); - assertEquals(2, row.getTotal()); - assertArrayEquals(new int[] {0, 0, 0, 0, 2}, row.getCells()); + List sumRow = resource.getSumRow(); + assertEquals(1 + 2, sumRow.size()); - // sumRow + row = sumRow.get(0); + assertArrayEquals(new String[] {"Total", null}, row.getDesc()); + assertEquals(0, row.getDepth()); + assertTrue(row.isDisplay()); + assertEquals(6, row.getTotal()); + assertArrayEquals(new int[] {0, 0, 0, 0, 6}, row.getCells()); - List sumRow = resource.getSumRow(); - assertEquals(1 + 2, sumRow.size()); - - row = sumRow.get(0); - assertArrayEquals(new String[] {"Total", null}, row.getDesc()); - assertEquals(0, row.getDepth()); - assertTrue(row.isDisplay()); - assertEquals(6, row.getTotal()); - assertArrayEquals(new int[] {0, 0, 0, 0, 6}, row.getCells()); - - row = sumRow.get(1); - assertArrayEquals(new String[] {"Total", "attachment"}, row.getDesc()); - assertEquals(1, row.getDepth()); - assertFalse(row.isDisplay()); - assertEquals(2, row.getTotal()); - assertArrayEquals(new int[] {0, 0, 0, 0, 2}, row.getCells()); - - row = sumRow.get(2); - assertArrayEquals(new String[] {"Total", "N/A"}, row.getDesc()); - assertEquals(1, row.getDepth()); - assertFalse(row.isDisplay()); - assertEquals(4, row.getTotal()); - assertArrayEquals(new int[] {0, 0, 0, 0, 4}, row.getCells()); - - } + row = sumRow.get(1); + assertArrayEquals(new String[] {"Total", "attachment"}, row.getDesc()); + assertEquals(1, row.getDepth()); + assertFalse(row.isDisplay()); + assertEquals(2, row.getTotal()); + assertArrayEquals(new int[] {0, 0, 0, 0, 2}, row.getCells()); + row = sumRow.get(2); + assertArrayEquals(new String[] {"Total", "N/A"}, row.getDesc()); + assertEquals(1, row.getDepth()); + assertFalse(row.isDisplay()); + assertEquals(4, row.getTotal()); + assertArrayEquals(new int[] {0, 0, 0, 0, 4}, row.getCells()); + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/resource/TaskResourceAssemberTest.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/resource/TaskResourceAssemberTest.java index a45771f4e..4d79dbe06 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/resource/TaskResourceAssemberTest.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/resource/TaskResourceAssemberTest.java @@ -3,7 +3,6 @@ package pro.taskana.rest.resource; import java.util.Collections; import java.util.List; import java.util.Map; - import org.junit.Assert; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -16,142 +15,145 @@ import pro.taskana.TaskState; import pro.taskana.TaskanaSpringBootTest; import pro.taskana.exceptions.InvalidArgumentException; -/** - * Test for {@link TaskResourceAssembler}. - */ - +/** Test for {@link TaskResourceAssembler}. */ @TaskanaSpringBootTest class TaskResourceAssemberTest { - @Autowired - TaskService taskService; - @Autowired - TaskResourceAssembler taskResourceAssembler; + @Autowired TaskService taskService; + @Autowired TaskResourceAssembler taskResourceAssembler; - @Test - void testSimpleResourceToModel() throws InvalidArgumentException { - //given - ObjectReference primaryObjRef = new ObjectReference(); - primaryObjRef.setId("abc"); - WorkbasketSummaryResource workbasketResource = new WorkbasketSummaryResource(); - workbasketResource.setWorkbasketId("workbasketId"); - ClassificationSummaryResource classificationResource = new ClassificationSummaryResource(); - classificationResource.key = "keyabc"; - classificationResource.domain = "DOMAIN_A"; - classificationResource.type = "MANUAL"; - AttachmentResource attachement = new AttachmentResource(); - attachement.setClassificationSummary(classificationResource); - attachement.setAttachmentId("attachementId"); - TaskResource resource = new TaskResource(); - resource.setTaskId("taskId"); - resource.setExternalId("externalId"); - resource.setCreated("2019-09-13T08:44:17.588Z"); - resource.setClaimed("2019-09-13T08:44:17.588Z"); - resource.setCompleted("2019-09-13T08:44:17.588Z"); - resource.setModified("2019-09-13T08:44:17.588Z"); - resource.setPlanned("2019-09-13T08:44:17.588Z"); - resource.setDue("2019-09-13T08:44:17.588Z"); - resource.setName("name"); - resource.setCreator("creator"); - resource.setDescription("desc"); - resource.setNote("note"); - resource.setPriority(123); - resource.setState(TaskState.READY); - resource.setClassificationSummaryResource(classificationResource); - resource.setWorkbasketSummaryResource(workbasketResource); - resource.setBusinessProcessId("businessProcessId"); - resource.setParentBusinessProcessId("parentBusinessProcessId"); - resource.setOwner("owner"); - resource.setPrimaryObjRef(primaryObjRef); - resource.setRead(true); - resource.setTransferred(true); - resource.setCustomAttributes(Collections.singletonList(new TaskResource.CustomAttribute("abc", "def"))); - resource.setCallbackInfo(Collections.singletonList(new TaskResource.CustomAttribute("ghi", "jkl"))); - resource.setAttachments(Collections.singletonList(attachement)); - resource.setCustom1("custom1"); - resource.setCustom2("custom2"); - resource.setCustom3("custom3"); - resource.setCustom4("custom4"); - resource.setCustom5("custom5"); - resource.setCustom6("custom6"); - resource.setCustom7("custom7"); - resource.setCustom8("custom8"); - resource.setCustom9("custom9"); - resource.setCustom10("custom10"); - resource.setCustom11("custom11"); - resource.setCustom12("custom12"); - resource.setCustom13("custom13"); - resource.setCustom14("custom14"); - resource.setCustom15("custom15"); - //when - Task task = taskResourceAssembler.toModel(resource); - //then - testEquality(task, resource); - } - - void testEquality(Task task, TaskResource resource) throws InvalidArgumentException { - Assert.assertEquals(task.getId(), resource.getTaskId()); - Assert.assertEquals(task.getExternalId(), resource.getExternalId()); - Assert.assertEquals(task.getCreated() == null ? null : task.getCreated().toString(), resource.getCreated()); - Assert.assertEquals(task.getClaimed() == null ? null : task.getClaimed().toString(), resource.getClaimed()); - Assert.assertEquals(task.getCompleted() == null ? null : task.getCompleted().toString(), - resource.getCompleted()); - Assert.assertEquals(task.getModified() == null ? null : task.getModified().toString(), resource.getModified()); - Assert.assertEquals(task.getPlanned() == null ? null : task.getPlanned().toString(), resource.getPlanned()); - Assert.assertEquals(task.getDue() == null ? null : task.getDue().toString(), resource.getDue()); - Assert.assertEquals(task.getName(), resource.getName()); - Assert.assertEquals(task.getCreator(), resource.getCreator()); - Assert.assertEquals(task.getDescription(), resource.getDescription()); - Assert.assertEquals(task.getNote(), resource.getNote()); - Assert.assertEquals(task.getPriority(), resource.getPriority()); - Assert.assertEquals(task.getState(), resource.getState()); - Assert.assertEquals(task.getClassificationSummary().getId(), - resource.getClassificationSummaryResource().getClassificationId()); - Assert.assertEquals(task.getWorkbasketSummary().getId(), - resource.getWorkbasketSummaryResource().getWorkbasketId()); - Assert.assertEquals(task.getBusinessProcessId(), resource.getBusinessProcessId()); - Assert.assertEquals(task.getParentBusinessProcessId(), resource.getParentBusinessProcessId()); - Assert.assertEquals(task.getOwner(), resource.getOwner()); - Assert.assertEquals(task.getPrimaryObjRef(), resource.getPrimaryObjRef()); - Assert.assertEquals(task.isRead(), resource.isRead()); - Assert.assertEquals(task.isTransferred(), resource.isTransferred()); - testEquality(task.getCustomAttributes(), resource.getCustomAttributes()); - testEquality(task.getCallbackInfo(), resource.getCallbackInfo()); - testEqualityAttachements(task.getAttachments(), resource.getAttachments()); - Assert.assertEquals(task.getCustomAttribute("1"), resource.getCustom1()); - Assert.assertEquals(task.getCustomAttribute("2"), resource.getCustom2()); - Assert.assertEquals(task.getCustomAttribute("3"), resource.getCustom3()); - Assert.assertEquals(task.getCustomAttribute("4"), resource.getCustom4()); - Assert.assertEquals(task.getCustomAttribute("5"), resource.getCustom5()); - Assert.assertEquals(task.getCustomAttribute("6"), resource.getCustom6()); - Assert.assertEquals(task.getCustomAttribute("7"), resource.getCustom7()); - Assert.assertEquals(task.getCustomAttribute("8"), resource.getCustom8()); - Assert.assertEquals(task.getCustomAttribute("9"), resource.getCustom9()); - Assert.assertEquals(task.getCustomAttribute("10"), resource.getCustom10()); - Assert.assertEquals(task.getCustomAttribute("11"), resource.getCustom11()); - Assert.assertEquals(task.getCustomAttribute("12"), resource.getCustom12()); - Assert.assertEquals(task.getCustomAttribute("13"), resource.getCustom13()); - Assert.assertEquals(task.getCustomAttribute("14"), resource.getCustom14()); - Assert.assertEquals(task.getCustomAttribute("15"), resource.getCustom15()); - Assert.assertEquals(task.getCustomAttribute("16"), resource.getCustom16()); - - } - - void testEqualityAttachements(List attachments, List resources) { - Assert.assertEquals(attachments.size(), resources.size()); - for (int i = 0; i < resources.size(); i++) { - AttachmentResource resource = resources.get(i); - Attachment attachment = attachments.get(i); - //Anything else shoulde be tested in AttachementResourceAssemblerTest - Assert.assertEquals(attachment.getId(), resource.getAttachmentId()); - } - } - - void testEquality(Map customAttributes, - List resourceAttributes) { - Assert.assertEquals(customAttributes.size(), resourceAttributes.size()); - resourceAttributes.forEach( - attribute -> Assert.assertEquals(customAttributes.get(attribute.getKey()), attribute.getValue())); + @Test + void testSimpleResourceToModel() throws InvalidArgumentException { + // given + ObjectReference primaryObjRef = new ObjectReference(); + primaryObjRef.setId("abc"); + WorkbasketSummaryResource workbasketResource = new WorkbasketSummaryResource(); + workbasketResource.setWorkbasketId("workbasketId"); + ClassificationSummaryResource classificationResource = new ClassificationSummaryResource(); + classificationResource.key = "keyabc"; + classificationResource.domain = "DOMAIN_A"; + classificationResource.type = "MANUAL"; + AttachmentResource attachement = new AttachmentResource(); + attachement.setClassificationSummary(classificationResource); + attachement.setAttachmentId("attachementId"); + TaskResource resource = new TaskResource(); + resource.setTaskId("taskId"); + resource.setExternalId("externalId"); + resource.setCreated("2019-09-13T08:44:17.588Z"); + resource.setClaimed("2019-09-13T08:44:17.588Z"); + resource.setCompleted("2019-09-13T08:44:17.588Z"); + resource.setModified("2019-09-13T08:44:17.588Z"); + resource.setPlanned("2019-09-13T08:44:17.588Z"); + resource.setDue("2019-09-13T08:44:17.588Z"); + resource.setName("name"); + resource.setCreator("creator"); + resource.setDescription("desc"); + resource.setNote("note"); + resource.setPriority(123); + resource.setState(TaskState.READY); + resource.setClassificationSummaryResource(classificationResource); + resource.setWorkbasketSummaryResource(workbasketResource); + resource.setBusinessProcessId("businessProcessId"); + resource.setParentBusinessProcessId("parentBusinessProcessId"); + resource.setOwner("owner"); + resource.setPrimaryObjRef(primaryObjRef); + resource.setRead(true); + resource.setTransferred(true); + resource.setCustomAttributes( + Collections.singletonList(new TaskResource.CustomAttribute("abc", "def"))); + resource.setCallbackInfo( + Collections.singletonList(new TaskResource.CustomAttribute("ghi", "jkl"))); + resource.setAttachments(Collections.singletonList(attachement)); + resource.setCustom1("custom1"); + resource.setCustom2("custom2"); + resource.setCustom3("custom3"); + resource.setCustom4("custom4"); + resource.setCustom5("custom5"); + resource.setCustom6("custom6"); + resource.setCustom7("custom7"); + resource.setCustom8("custom8"); + resource.setCustom9("custom9"); + resource.setCustom10("custom10"); + resource.setCustom11("custom11"); + resource.setCustom12("custom12"); + resource.setCustom13("custom13"); + resource.setCustom14("custom14"); + resource.setCustom15("custom15"); + // when + Task task = taskResourceAssembler.toModel(resource); + // then + testEquality(task, resource); + } + + void testEquality(Task task, TaskResource resource) throws InvalidArgumentException { + Assert.assertEquals(task.getId(), resource.getTaskId()); + Assert.assertEquals(task.getExternalId(), resource.getExternalId()); + Assert.assertEquals( + task.getCreated() == null ? null : task.getCreated().toString(), resource.getCreated()); + Assert.assertEquals( + task.getClaimed() == null ? null : task.getClaimed().toString(), resource.getClaimed()); + Assert.assertEquals( + task.getCompleted() == null ? null : task.getCompleted().toString(), + resource.getCompleted()); + Assert.assertEquals( + task.getModified() == null ? null : task.getModified().toString(), resource.getModified()); + Assert.assertEquals( + task.getPlanned() == null ? null : task.getPlanned().toString(), resource.getPlanned()); + Assert.assertEquals(task.getDue() == null ? null : task.getDue().toString(), resource.getDue()); + Assert.assertEquals(task.getName(), resource.getName()); + Assert.assertEquals(task.getCreator(), resource.getCreator()); + Assert.assertEquals(task.getDescription(), resource.getDescription()); + Assert.assertEquals(task.getNote(), resource.getNote()); + Assert.assertEquals(task.getPriority(), resource.getPriority()); + Assert.assertEquals(task.getState(), resource.getState()); + Assert.assertEquals( + task.getClassificationSummary().getId(), + resource.getClassificationSummaryResource().getClassificationId()); + Assert.assertEquals( + task.getWorkbasketSummary().getId(), + resource.getWorkbasketSummaryResource().getWorkbasketId()); + Assert.assertEquals(task.getBusinessProcessId(), resource.getBusinessProcessId()); + Assert.assertEquals(task.getParentBusinessProcessId(), resource.getParentBusinessProcessId()); + Assert.assertEquals(task.getOwner(), resource.getOwner()); + Assert.assertEquals(task.getPrimaryObjRef(), resource.getPrimaryObjRef()); + Assert.assertEquals(task.isRead(), resource.isRead()); + Assert.assertEquals(task.isTransferred(), resource.isTransferred()); + testEquality(task.getCustomAttributes(), resource.getCustomAttributes()); + testEquality(task.getCallbackInfo(), resource.getCallbackInfo()); + testEqualityAttachements(task.getAttachments(), resource.getAttachments()); + Assert.assertEquals(task.getCustomAttribute("1"), resource.getCustom1()); + Assert.assertEquals(task.getCustomAttribute("2"), resource.getCustom2()); + Assert.assertEquals(task.getCustomAttribute("3"), resource.getCustom3()); + Assert.assertEquals(task.getCustomAttribute("4"), resource.getCustom4()); + Assert.assertEquals(task.getCustomAttribute("5"), resource.getCustom5()); + Assert.assertEquals(task.getCustomAttribute("6"), resource.getCustom6()); + Assert.assertEquals(task.getCustomAttribute("7"), resource.getCustom7()); + Assert.assertEquals(task.getCustomAttribute("8"), resource.getCustom8()); + Assert.assertEquals(task.getCustomAttribute("9"), resource.getCustom9()); + Assert.assertEquals(task.getCustomAttribute("10"), resource.getCustom10()); + Assert.assertEquals(task.getCustomAttribute("11"), resource.getCustom11()); + Assert.assertEquals(task.getCustomAttribute("12"), resource.getCustom12()); + Assert.assertEquals(task.getCustomAttribute("13"), resource.getCustom13()); + Assert.assertEquals(task.getCustomAttribute("14"), resource.getCustom14()); + Assert.assertEquals(task.getCustomAttribute("15"), resource.getCustom15()); + Assert.assertEquals(task.getCustomAttribute("16"), resource.getCustom16()); + } + + void testEqualityAttachements(List attachments, List resources) { + Assert.assertEquals(attachments.size(), resources.size()); + for (int i = 0; i < resources.size(); i++) { + AttachmentResource resource = resources.get(i); + Attachment attachment = attachments.get(i); + // Anything else shoulde be tested in AttachementResourceAssemblerTest + Assert.assertEquals(attachment.getId(), resource.getAttachmentId()); } + } + void testEquality( + Map customAttributes, List resourceAttributes) { + Assert.assertEquals(customAttributes.size(), resourceAttributes.size()); + resourceAttributes.forEach( + attribute -> + Assert.assertEquals(customAttributes.get(attribute.getKey()), attribute.getValue())); + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/resource/WorkbasketAccessItemResourceAssemblerTest.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/resource/WorkbasketAccessItemResourceAssemblerTest.java index b81f9e749..9858371f3 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/resource/WorkbasketAccessItemResourceAssemblerTest.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/resource/WorkbasketAccessItemResourceAssemblerTest.java @@ -9,101 +9,96 @@ import pro.taskana.WorkbasketAccessItem; import pro.taskana.WorkbasketService; import pro.taskana.impl.WorkbasketAccessItemImpl; -/** - * Test for {@link WorkbasketAccessItemResourceAssembler}. - */ - +/** Test for {@link WorkbasketAccessItemResourceAssembler}. */ @TaskanaSpringBootTest class WorkbasketAccessItemResourceAssemblerTest { - @Autowired - WorkbasketAccessItemResourceAssembler workbasketAccessItemResourceAssembler; + @Autowired WorkbasketAccessItemResourceAssembler workbasketAccessItemResourceAssembler; - @Autowired - WorkbasketService workbasketService; + @Autowired WorkbasketService workbasketService; - @Test - void workBasketAccessItemToResourcePropertiesEqual() { - // given - WorkbasketAccessItem accessItem = workbasketService.newWorkbasketAccessItem("1", "2"); - ((WorkbasketAccessItemImpl) accessItem).setWorkbasketKey("workbasketKey"); - accessItem.setPermDistribute(false); - accessItem.setPermOpen(true); - accessItem.setPermAppend(false); - accessItem.setPermRead(false); - accessItem.setPermTransfer(true); - accessItem.setPermCustom1(false); - accessItem.setPermCustom2(false); - accessItem.setPermCustom3(true); - accessItem.setPermCustom4(true); - accessItem.setPermCustom5(true); - accessItem.setPermCustom6(true); - accessItem.setPermCustom7(true); - accessItem.setPermCustom8(true); - accessItem.setPermCustom9(true); - accessItem.setPermCustom10(true); - accessItem.setPermCustom11(true); - accessItem.setPermCustom12(true); - // when - WorkbasketAccessItemResource resource = workbasketAccessItemResourceAssembler.toResource( - accessItem); - // then - testEquality(accessItem, resource); - } + @Test + void workBasketAccessItemToResourcePropertiesEqual() { + // given + WorkbasketAccessItem accessItem = workbasketService.newWorkbasketAccessItem("1", "2"); + ((WorkbasketAccessItemImpl) accessItem).setWorkbasketKey("workbasketKey"); + accessItem.setPermDistribute(false); + accessItem.setPermOpen(true); + accessItem.setPermAppend(false); + accessItem.setPermRead(false); + accessItem.setPermTransfer(true); + accessItem.setPermCustom1(false); + accessItem.setPermCustom2(false); + accessItem.setPermCustom3(true); + accessItem.setPermCustom4(true); + accessItem.setPermCustom5(true); + accessItem.setPermCustom6(true); + accessItem.setPermCustom7(true); + accessItem.setPermCustom8(true); + accessItem.setPermCustom9(true); + accessItem.setPermCustom10(true); + accessItem.setPermCustom11(true); + accessItem.setPermCustom12(true); + // when + WorkbasketAccessItemResource resource = + workbasketAccessItemResourceAssembler.toResource(accessItem); + // then + testEquality(accessItem, resource); + } - @Test - void workBasketAccessItemToModelPropertiesEqual() { - // given - WorkbasketAccessItemResource resource = new WorkbasketAccessItemResource(); - resource.setAccessId("10"); - resource.setWorkbasketKey("workbasketKey"); - resource.setAccessItemId("120"); - resource.setWorkbasketId("1"); - resource.setPermRead(true); - resource.setPermAppend(false); - resource.setPermDistribute(false); - resource.setPermOpen(false); - resource.setPermTransfer(true); - resource.setPermCustom1(false); - resource.setPermCustom2(false); - resource.setPermCustom3(false); - resource.setPermCustom4(false); - resource.setPermCustom5(true); - resource.setPermCustom6(false); - resource.setPermCustom7(false); - resource.setPermCustom8(false); - resource.setPermCustom9(false); - resource.setPermCustom10(false); - resource.setPermCustom11(true); - resource.setPermCustom12(false); - // when - WorkbasketAccessItem accessItem = workbasketAccessItemResourceAssembler.toModel(resource); - // then - testEquality(accessItem, resource); - } + @Test + void workBasketAccessItemToModelPropertiesEqual() { + // given + WorkbasketAccessItemResource resource = new WorkbasketAccessItemResource(); + resource.setAccessId("10"); + resource.setWorkbasketKey("workbasketKey"); + resource.setAccessItemId("120"); + resource.setWorkbasketId("1"); + resource.setPermRead(true); + resource.setPermAppend(false); + resource.setPermDistribute(false); + resource.setPermOpen(false); + resource.setPermTransfer(true); + resource.setPermCustom1(false); + resource.setPermCustom2(false); + resource.setPermCustom3(false); + resource.setPermCustom4(false); + resource.setPermCustom5(true); + resource.setPermCustom6(false); + resource.setPermCustom7(false); + resource.setPermCustom8(false); + resource.setPermCustom9(false); + resource.setPermCustom10(false); + resource.setPermCustom11(true); + resource.setPermCustom12(false); + // when + WorkbasketAccessItem accessItem = workbasketAccessItemResourceAssembler.toModel(resource); + // then + testEquality(accessItem, resource); + } - private void testEquality(WorkbasketAccessItem accessItem, - WorkbasketAccessItemResource resource) { - Assert.assertEquals(accessItem.getAccessId(), resource.accessId); - Assert.assertEquals(accessItem.getWorkbasketKey(), resource.workbasketKey); - Assert.assertEquals(accessItem.getId(), resource.accessItemId); - Assert.assertEquals(accessItem.getWorkbasketId(), resource.workbasketId); - Assert.assertEquals(accessItem.isPermAppend(), resource.permAppend); - Assert.assertEquals(accessItem.isPermCustom1(), resource.permCustom1); - Assert.assertEquals(accessItem.isPermCustom2(), resource.permCustom2); - Assert.assertEquals(accessItem.isPermCustom3(), resource.permCustom3); - Assert.assertEquals(accessItem.isPermCustom4(), resource.permCustom4); - Assert.assertEquals(accessItem.isPermCustom5(), resource.permCustom5); - Assert.assertEquals(accessItem.isPermCustom6(), resource.permCustom6); - Assert.assertEquals(accessItem.isPermCustom7(), resource.permCustom7); - Assert.assertEquals(accessItem.isPermCustom8(), resource.permCustom8); - Assert.assertEquals(accessItem.isPermCustom9(), resource.permCustom9); - Assert.assertEquals(accessItem.isPermCustom10(), resource.permCustom10); - Assert.assertEquals(accessItem.isPermCustom11(), resource.permCustom11); - Assert.assertEquals(accessItem.isPermCustom12(), resource.permCustom12); - Assert.assertEquals(accessItem.isPermDistribute(), resource.permDistribute); - Assert.assertEquals(accessItem.isPermRead(), resource.permRead); - Assert.assertEquals(accessItem.isPermOpen(), resource.permOpen); - Assert.assertEquals(accessItem.isPermTransfer(), resource.permTransfer); - } + private void testEquality( + WorkbasketAccessItem accessItem, WorkbasketAccessItemResource resource) { + Assert.assertEquals(accessItem.getAccessId(), resource.accessId); + Assert.assertEquals(accessItem.getWorkbasketKey(), resource.workbasketKey); + Assert.assertEquals(accessItem.getId(), resource.accessItemId); + Assert.assertEquals(accessItem.getWorkbasketId(), resource.workbasketId); + Assert.assertEquals(accessItem.isPermAppend(), resource.permAppend); + Assert.assertEquals(accessItem.isPermCustom1(), resource.permCustom1); + Assert.assertEquals(accessItem.isPermCustom2(), resource.permCustom2); + Assert.assertEquals(accessItem.isPermCustom3(), resource.permCustom3); + Assert.assertEquals(accessItem.isPermCustom4(), resource.permCustom4); + Assert.assertEquals(accessItem.isPermCustom5(), resource.permCustom5); + Assert.assertEquals(accessItem.isPermCustom6(), resource.permCustom6); + Assert.assertEquals(accessItem.isPermCustom7(), resource.permCustom7); + Assert.assertEquals(accessItem.isPermCustom8(), resource.permCustom8); + Assert.assertEquals(accessItem.isPermCustom9(), resource.permCustom9); + Assert.assertEquals(accessItem.isPermCustom10(), resource.permCustom10); + Assert.assertEquals(accessItem.isPermCustom11(), resource.permCustom11); + Assert.assertEquals(accessItem.isPermCustom12(), resource.permCustom12); + Assert.assertEquals(accessItem.isPermDistribute(), resource.permDistribute); + Assert.assertEquals(accessItem.isPermRead(), resource.permRead); + Assert.assertEquals(accessItem.isPermOpen(), resource.permOpen); + Assert.assertEquals(accessItem.isPermTransfer(), resource.permTransfer); + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/resource/WorkbasketResourceAssemblerTest.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/resource/WorkbasketResourceAssemblerTest.java index b8ac24e71..58283b25b 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/resource/WorkbasketResourceAssemblerTest.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/resource/WorkbasketResourceAssemblerTest.java @@ -1,7 +1,6 @@ package pro.taskana.rest.resource; import java.time.Instant; - import org.junit.Assert; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -14,115 +13,112 @@ import pro.taskana.exceptions.NotAuthorizedException; import pro.taskana.exceptions.WorkbasketNotFoundException; import pro.taskana.impl.WorkbasketImpl; -/** - * Test for {@link WorkbasketResourceAssembler}. - */ - +/** Test for {@link WorkbasketResourceAssembler}. */ @TaskanaSpringBootTest class WorkbasketResourceAssemblerTest { - @Autowired - WorkbasketService workbasketService; - @Autowired - WorkbasketResourceAssembler workbasketResourceAssembler; + @Autowired WorkbasketService workbasketService; + @Autowired WorkbasketResourceAssembler workbasketResourceAssembler; - @Test - void workbasketToResource() throws NotAuthorizedException, WorkbasketNotFoundException { - // given - Workbasket workbasket = workbasketService.newWorkbasket("1", "DOMAIN_A"); - ((WorkbasketImpl) workbasket).setId("ID"); - workbasket.setType(WorkbasketType.PERSONAL); - workbasket.setName("Testbasket"); - workbasket.setOrgLevel1("Org1"); - workbasket.setOrgLevel2("Org2"); - workbasket.setOrgLevel3("Org3"); - workbasket.setOrgLevel4("Org4"); - workbasket.setDescription("A test workbasket"); - workbasket.setCustom1("1"); - workbasket.setCustom2("2"); - workbasket.setCustom3("3"); - workbasket.setCustom4("4"); - workbasket.setOwner("Lars"); - ((WorkbasketImpl) workbasket).setCreated(Instant.parse("2010-01-01T12:00:00Z")); - ((WorkbasketImpl) workbasket).setModified(Instant.parse("2010-01-01T12:00:00Z")); - // when - WorkbasketResource workbasketResource = workbasketResourceAssembler.toResource(workbasket); - // then - testEquality(workbasket, workbasketResource); - } + @Test + void workbasketToResource() throws NotAuthorizedException, WorkbasketNotFoundException { + // given + Workbasket workbasket = workbasketService.newWorkbasket("1", "DOMAIN_A"); + ((WorkbasketImpl) workbasket).setId("ID"); + workbasket.setType(WorkbasketType.PERSONAL); + workbasket.setName("Testbasket"); + workbasket.setOrgLevel1("Org1"); + workbasket.setOrgLevel2("Org2"); + workbasket.setOrgLevel3("Org3"); + workbasket.setOrgLevel4("Org4"); + workbasket.setDescription("A test workbasket"); + workbasket.setCustom1("1"); + workbasket.setCustom2("2"); + workbasket.setCustom3("3"); + workbasket.setCustom4("4"); + workbasket.setOwner("Lars"); + ((WorkbasketImpl) workbasket).setCreated(Instant.parse("2010-01-01T12:00:00Z")); + ((WorkbasketImpl) workbasket).setModified(Instant.parse("2010-01-01T12:00:00Z")); + // when + WorkbasketResource workbasketResource = workbasketResourceAssembler.toResource(workbasket); + // then + testEquality(workbasket, workbasketResource); + } - @Test - void resourceWithoutCreated() { - //given - WorkbasketResource resource = new WorkbasketResource(); - resource.setWorkbasketId("1"); - resource.setModified("2010-01-01T12:00:00Z"); - resource.setType(WorkbasketType.PERSONAL); - //when - Workbasket workbasket = workbasketResourceAssembler.toModel(resource); - //then - testEquality(workbasket, resource); - } + @Test + void resourceWithoutCreated() { + // given + WorkbasketResource resource = new WorkbasketResource(); + resource.setWorkbasketId("1"); + resource.setModified("2010-01-01T12:00:00Z"); + resource.setType(WorkbasketType.PERSONAL); + // when + Workbasket workbasket = workbasketResourceAssembler.toModel(resource); + // then + testEquality(workbasket, resource); + } - @Test - void resourceWithoutModified() { - //given - WorkbasketResource resource = new WorkbasketResource(); - resource.setWorkbasketId("1"); - resource.setCreated("2010-01-01T12:00:00Z"); - resource.setType(WorkbasketType.PERSONAL); - //when - Workbasket workbasket = workbasketResourceAssembler.toModel(resource); - //then - testEquality(workbasket, resource); - } + @Test + void resourceWithoutModified() { + // given + WorkbasketResource resource = new WorkbasketResource(); + resource.setWorkbasketId("1"); + resource.setCreated("2010-01-01T12:00:00Z"); + resource.setType(WorkbasketType.PERSONAL); + // when + Workbasket workbasket = workbasketResourceAssembler.toModel(resource); + // then + testEquality(workbasket, resource); + } - @Test - void resourceToWorkbasket() { - // given - WorkbasketResource workbasketResource = new WorkbasketResource(); - workbasketResource.setWorkbasketId("1"); - workbasketResource.setCreated("2010-01-01T12:00:00Z"); - workbasketResource.setModified("2010-01-01T12:00:00Z"); - workbasketResource.setCustom1("Custom1"); - workbasketResource.setCustom2("Custom2"); - workbasketResource.setCustom3("Custom3"); - workbasketResource.setCustom4("Custom4"); - workbasketResource.setDescription("Test Ressource"); - workbasketResource.setDomain("DOMAIN_A"); - workbasketResource.setKey("1"); - workbasketResource.setName("Ressource"); - workbasketResource.setOrgLevel1("Org1"); - workbasketResource.setOrgLevel2("Org2"); - workbasketResource.setOrgLevel3("Org3"); - workbasketResource.setOrgLevel4("Org4"); - workbasketResource.setOwner("Lars"); - workbasketResource.setType(WorkbasketType.PERSONAL); - // when - Workbasket workbasket = workbasketResourceAssembler.toModel(workbasketResource); - // then - testEquality(workbasket, workbasketResource); - } + @Test + void resourceToWorkbasket() { + // given + WorkbasketResource workbasketResource = new WorkbasketResource(); + workbasketResource.setWorkbasketId("1"); + workbasketResource.setCreated("2010-01-01T12:00:00Z"); + workbasketResource.setModified("2010-01-01T12:00:00Z"); + workbasketResource.setCustom1("Custom1"); + workbasketResource.setCustom2("Custom2"); + workbasketResource.setCustom3("Custom3"); + workbasketResource.setCustom4("Custom4"); + workbasketResource.setDescription("Test Ressource"); + workbasketResource.setDomain("DOMAIN_A"); + workbasketResource.setKey("1"); + workbasketResource.setName("Ressource"); + workbasketResource.setOrgLevel1("Org1"); + workbasketResource.setOrgLevel2("Org2"); + workbasketResource.setOrgLevel3("Org3"); + workbasketResource.setOrgLevel4("Org4"); + workbasketResource.setOwner("Lars"); + workbasketResource.setType(WorkbasketType.PERSONAL); + // when + Workbasket workbasket = workbasketResourceAssembler.toModel(workbasketResource); + // then + testEquality(workbasket, workbasketResource); + } - private void testEquality(Workbasket workbasket, WorkbasketResource workbasketResource) { - Assert.assertEquals(workbasket.getId(), workbasketResource.workbasketId); - Assert.assertEquals(workbasket.getKey(), workbasketResource.key); - Assert.assertEquals(workbasket.getCreated() == null ? null : workbasket.getCreated().toString(), - workbasketResource.created); - Assert.assertEquals(workbasket.getModified() == null ? null : workbasket.getModified().toString(), - workbasketResource.modified); - Assert.assertEquals(workbasket.getName(), workbasketResource.name); - Assert.assertEquals(workbasket.getDescription(), workbasketResource.description); - Assert.assertEquals(workbasket.getOwner(), workbasketResource.owner); - Assert.assertEquals(workbasket.getDomain(), workbasketResource.domain); - Assert.assertEquals(workbasket.getType(), workbasketResource.type); - Assert.assertEquals(workbasket.getCustom1(), workbasketResource.custom1); - Assert.assertEquals(workbasket.getCustom2(), workbasketResource.custom2); - Assert.assertEquals(workbasket.getCustom3(), workbasketResource.custom3); - Assert.assertEquals(workbasket.getCustom4(), workbasketResource.custom4); - Assert.assertEquals(workbasket.getOrgLevel1(), workbasketResource.orgLevel1); - Assert.assertEquals(workbasket.getOrgLevel2(), workbasketResource.orgLevel2); - Assert.assertEquals(workbasket.getOrgLevel3(), workbasketResource.orgLevel3); - Assert.assertEquals(workbasket.getOrgLevel4(), workbasketResource.orgLevel4); - } + private void testEquality(Workbasket workbasket, WorkbasketResource workbasketResource) { + Assert.assertEquals(workbasket.getId(), workbasketResource.workbasketId); + Assert.assertEquals(workbasket.getKey(), workbasketResource.key); + Assert.assertEquals( + workbasket.getCreated() == null ? null : workbasket.getCreated().toString(), + workbasketResource.created); + Assert.assertEquals( + workbasket.getModified() == null ? null : workbasket.getModified().toString(), + workbasketResource.modified); + Assert.assertEquals(workbasket.getName(), workbasketResource.name); + Assert.assertEquals(workbasket.getDescription(), workbasketResource.description); + Assert.assertEquals(workbasket.getOwner(), workbasketResource.owner); + Assert.assertEquals(workbasket.getDomain(), workbasketResource.domain); + Assert.assertEquals(workbasket.getType(), workbasketResource.type); + Assert.assertEquals(workbasket.getCustom1(), workbasketResource.custom1); + Assert.assertEquals(workbasket.getCustom2(), workbasketResource.custom2); + Assert.assertEquals(workbasket.getCustom3(), workbasketResource.custom3); + Assert.assertEquals(workbasket.getCustom4(), workbasketResource.custom4); + Assert.assertEquals(workbasket.getOrgLevel1(), workbasketResource.orgLevel1); + Assert.assertEquals(workbasket.getOrgLevel2(), workbasketResource.orgLevel2); + Assert.assertEquals(workbasket.getOrgLevel3(), workbasketResource.orgLevel3); + Assert.assertEquals(workbasket.getOrgLevel4(), workbasketResource.orgLevel4); + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/resource/WorkbasketSummaryAssemblerTest.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/resource/WorkbasketSummaryAssemblerTest.java index 2591f54ef..2c145d464 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/resource/WorkbasketSummaryAssemblerTest.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/resource/WorkbasketSummaryAssemblerTest.java @@ -9,53 +9,50 @@ import pro.taskana.WorkbasketService; import pro.taskana.WorkbasketType; import pro.taskana.impl.WorkbasketSummaryImpl; -/** - * Test for {@link WorkbasketSummaryResourceAssembler}. - */ - +/** Test for {@link WorkbasketSummaryResourceAssembler}. */ @TaskanaSpringBootTest class WorkbasketSummaryAssemblerTest { - @Autowired - WorkbasketSummaryResourceAssembler workbasketSummaryAssembler; - @Autowired - WorkbasketService workbasketService; + @Autowired WorkbasketSummaryResourceAssembler workbasketSummaryAssembler; + @Autowired WorkbasketService workbasketService; - @Test - void workbasketSummaryToResource() { - // given - WorkbasketSummaryImpl workbasketSummary = (WorkbasketSummaryImpl) workbasketService.newWorkbasket("1", - "DOMAIN_A").asSummary(); - workbasketSummary.setDescription("WorkbasketSummaryImplTes"); - workbasketSummary.setId("1"); - workbasketSummary.setName("WorkbasketSummary"); - workbasketSummary.setCustom1("custom1"); - workbasketSummary.setCustom2("custom2"); - workbasketSummary.setCustom3("custom3"); - workbasketSummary.setCustom4("custom4"); - workbasketSummary.setOrgLevel1("Org1"); - workbasketSummary.setOrgLevel2("Org2"); - workbasketSummary.setOrgLevel3("Org3"); - workbasketSummary.setOrgLevel4("Org4"); - workbasketSummary.setOwner("Lars"); - workbasketSummary.setType(WorkbasketType.PERSONAL); - // when - WorkbasketSummaryResource workbasketSummaryResource = workbasketSummaryAssembler.toResource(workbasketSummary); - // then - Assert.assertEquals(workbasketSummary.getDescription(), workbasketSummaryResource.getDescription()); - Assert.assertEquals(workbasketSummary.getDomain(), workbasketSummaryResource.getDomain()); - Assert.assertEquals(workbasketSummary.getId(), workbasketSummaryResource.getWorkbasketId()); - Assert.assertEquals(workbasketSummary.getKey(), workbasketSummaryResource.getKey()); - Assert.assertEquals(workbasketSummary.getName(), workbasketSummaryResource.getName()); - Assert.assertEquals(workbasketSummary.getCustom1(), workbasketSummaryResource.getCustom1()); - Assert.assertEquals(workbasketSummary.getCustom2(), workbasketSummaryResource.getCustom2()); - Assert.assertEquals(workbasketSummary.getCustom3(), workbasketSummaryResource.getCustom3()); - Assert.assertEquals(workbasketSummary.getCustom4(), workbasketSummaryResource.getCustom4()); - Assert.assertEquals(workbasketSummary.getOrgLevel1(), workbasketSummaryResource.getOrgLevel1()); - Assert.assertEquals(workbasketSummary.getOrgLevel2(), workbasketSummaryResource.getOrgLevel2()); - Assert.assertEquals(workbasketSummary.getOrgLevel3(), workbasketSummaryResource.getOrgLevel3()); - Assert.assertEquals(workbasketSummary.getOrgLevel4(), workbasketSummaryResource.getOrgLevel4()); - Assert.assertEquals(workbasketSummary.getOwner(), workbasketSummaryResource.getOwner()); - Assert.assertEquals(workbasketSummary.getType(), workbasketSummaryResource.getType()); - } + @Test + void workbasketSummaryToResource() { + // given + WorkbasketSummaryImpl workbasketSummary = + (WorkbasketSummaryImpl) workbasketService.newWorkbasket("1", "DOMAIN_A").asSummary(); + workbasketSummary.setDescription("WorkbasketSummaryImplTes"); + workbasketSummary.setId("1"); + workbasketSummary.setName("WorkbasketSummary"); + workbasketSummary.setCustom1("custom1"); + workbasketSummary.setCustom2("custom2"); + workbasketSummary.setCustom3("custom3"); + workbasketSummary.setCustom4("custom4"); + workbasketSummary.setOrgLevel1("Org1"); + workbasketSummary.setOrgLevel2("Org2"); + workbasketSummary.setOrgLevel3("Org3"); + workbasketSummary.setOrgLevel4("Org4"); + workbasketSummary.setOwner("Lars"); + workbasketSummary.setType(WorkbasketType.PERSONAL); + // when + WorkbasketSummaryResource workbasketSummaryResource = + workbasketSummaryAssembler.toResource(workbasketSummary); + // then + Assert.assertEquals( + workbasketSummary.getDescription(), workbasketSummaryResource.getDescription()); + Assert.assertEquals(workbasketSummary.getDomain(), workbasketSummaryResource.getDomain()); + Assert.assertEquals(workbasketSummary.getId(), workbasketSummaryResource.getWorkbasketId()); + Assert.assertEquals(workbasketSummary.getKey(), workbasketSummaryResource.getKey()); + Assert.assertEquals(workbasketSummary.getName(), workbasketSummaryResource.getName()); + Assert.assertEquals(workbasketSummary.getCustom1(), workbasketSummaryResource.getCustom1()); + Assert.assertEquals(workbasketSummary.getCustom2(), workbasketSummaryResource.getCustom2()); + Assert.assertEquals(workbasketSummary.getCustom3(), workbasketSummaryResource.getCustom3()); + Assert.assertEquals(workbasketSummary.getCustom4(), workbasketSummaryResource.getCustom4()); + Assert.assertEquals(workbasketSummary.getOrgLevel1(), workbasketSummaryResource.getOrgLevel1()); + Assert.assertEquals(workbasketSummary.getOrgLevel2(), workbasketSummaryResource.getOrgLevel2()); + Assert.assertEquals(workbasketSummary.getOrgLevel3(), workbasketSummaryResource.getOrgLevel3()); + Assert.assertEquals(workbasketSummary.getOrgLevel4(), workbasketSummaryResource.getOrgLevel4()); + Assert.assertEquals(workbasketSummary.getOwner(), workbasketSummaryResource.getOwner()); + Assert.assertEquals(workbasketSummary.getType(), workbasketSummaryResource.getType()); + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/security/SampleLoginModule.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/security/SampleLoginModule.java index 17175db13..7110a7a49 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/security/SampleLoginModule.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/security/SampleLoginModule.java @@ -2,14 +2,12 @@ package pro.taskana.rest.security; import java.util.List; import java.util.Map; - import javax.security.auth.Subject; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.spi.LoginModule; - import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import pro.taskana.ldap.LdapCacheTestImpl; @@ -22,63 +20,66 @@ import pro.taskana.security.UserPrincipal; */ public class SampleLoginModule extends UsernamePasswordAuthenticationFilter implements LoginModule { - private NameCallback nameCallback; + private NameCallback nameCallback; - private PasswordCallback passwordCallback; + private PasswordCallback passwordCallback; - private Subject subject; + private Subject subject; - @Override - public boolean abort() { - return true; + @Override + public boolean abort() { + return true; + } + + @Override + public boolean commit() { + addUserPrincipalToSubject(); + addGroupSubjectsDerivedFromUsername(); + return true; + } + + @Override + public void initialize( + Subject subject, + CallbackHandler callbackHandler, + Map sharedState, + Map options) { + + this.subject = subject; + + try { + nameCallback = new NameCallback("prompt"); + passwordCallback = new PasswordCallback("prompt", false); + + callbackHandler.handle(new Callback[] {nameCallback, passwordCallback}); + } catch (Exception e) { + throw new RuntimeException(e); } + } - @Override - public boolean commit() { - addUserPrincipalToSubject(); - addGroupSubjectsDerivedFromUsername(); - return true; - } + @Override + public boolean login() { + return nameCallback.getName().equals(new String(passwordCallback.getPassword())); + } - private void addGroupSubjectsDerivedFromUsername() { - LdapCacheTestImpl ldapCacheTest = new LdapCacheTestImpl(); - String username = nameCallback.getName().toLowerCase(); - List groups = ldapCacheTest.findGroupsOfUser(username, Integer.MAX_VALUE); - groups.forEach((AccessIdResource group) -> { - if (group.getAccessId().contains("ou=groups")) { - subject.getPrincipals().add(new GroupPrincipal(group.getName())); - } + @Override + public boolean logout() { + return true; + } + + private void addGroupSubjectsDerivedFromUsername() { + LdapCacheTestImpl ldapCacheTest = new LdapCacheTestImpl(); + String username = nameCallback.getName().toLowerCase(); + List groups = ldapCacheTest.findGroupsOfUser(username, Integer.MAX_VALUE); + groups.forEach( + (AccessIdResource group) -> { + if (group.getAccessId().contains("ou=groups")) { + subject.getPrincipals().add(new GroupPrincipal(group.getName())); + } }); - } - - private void addUserPrincipalToSubject() { - subject.getPrincipals().add(new UserPrincipal(nameCallback.getName())); - } - - @Override - public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, - Map options) { - - this.subject = subject; - - try { - nameCallback = new NameCallback("prompt"); - passwordCallback = new PasswordCallback("prompt", false); - - callbackHandler.handle(new Callback[] {nameCallback, passwordCallback}); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - @Override - public boolean login() { - return nameCallback.getName().equals(new String(passwordCallback.getPassword())); - } - - @Override - public boolean logout() { - return true; - } + } + private void addUserPrincipalToSubject() { + subject.getPrincipals().add(new UserPrincipal(nameCallback.getName())); + } } diff --git a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/security/WebSecurityConfig.java b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/security/WebSecurityConfig.java index a3bb2a923..870bcbe47 100644 --- a/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/security/WebSecurityConfig.java +++ b/rest/taskana-rest-spring/src/test/java/pro/taskana/rest/security/WebSecurityConfig.java @@ -1,7 +1,6 @@ package pro.taskana.rest.security; import java.util.Collections; - import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -21,65 +20,66 @@ import org.springframework.web.filter.CorsFilter; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -/** - * Default basic configuration for taskana web example. - */ +/** Default basic configuration for taskana web example. */ @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { - @Override - protected void configure(HttpSecurity http) throws Exception { + @Bean + public JaasAuthenticationProvider jaasAuthProvider() { + JaasAuthenticationProvider authenticationProvider = new JaasAuthenticationProvider(); + authenticationProvider.setAuthorityGranters( + new AuthorityGranter[] {p -> Collections.singleton(p.getName())}); + authenticationProvider.setCallbackHandlers( + new JaasAuthenticationCallbackHandler[] { + new JaasNameCallbackHandler(), new JaasPasswordCallbackHandler() + }); + authenticationProvider.setLoginContextName("taskana"); + authenticationProvider.setLoginConfig(new ClassPathResource("pss_jaas.config")); + return authenticationProvider; + } - http.authorizeRequests() - .and() - .csrf() - .disable() - .httpBasic() - .and() - .authenticationProvider(jaasAuthProvider()) - .authorizeRequests() - .and() - .addFilter(new JaasApiIntegrationFilter()) - .authorizeRequests() - .anyRequest() - .fullyAuthenticated(); - } + @Bean + public WebMvcConfigurer corsConfigurer() { + return new WebMvcConfigurer() { - @Bean - public JaasAuthenticationProvider jaasAuthProvider() { - JaasAuthenticationProvider authenticationProvider = new JaasAuthenticationProvider(); - authenticationProvider.setAuthorityGranters(new AuthorityGranter[] {p -> Collections.singleton(p.getName())}); - authenticationProvider.setCallbackHandlers(new JaasAuthenticationCallbackHandler[] { - new JaasNameCallbackHandler(), new JaasPasswordCallbackHandler()}); - authenticationProvider.setLoginContextName("taskana"); - authenticationProvider.setLoginConfig(new ClassPathResource("pss_jaas.config")); - return authenticationProvider; - } + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**").allowedOrigins("*"); + } + }; + } - @Bean - public WebMvcConfigurer corsConfigurer() { - return new WebMvcConfigurer() { + @Bean + public FilterRegistrationBean corsFilter() { + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + CorsConfiguration config = new CorsConfiguration(); + config.setAllowCredentials(true); + config.addAllowedOrigin("*"); + config.addAllowedHeader("*"); + config.addAllowedMethod("*"); + config.addAllowedMethod("POST"); + source.registerCorsConfiguration("/**", config); + FilterRegistrationBean bean = new FilterRegistrationBean<>(new CorsFilter(source)); + bean.setOrder(0); + return bean; + } - @Override - public void addCorsMappings(CorsRegistry registry) { - registry.addMapping("/**").allowedOrigins("*"); - } - }; - } + @Override + protected void configure(HttpSecurity http) throws Exception { - @Bean - public FilterRegistrationBean corsFilter() { - UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); - CorsConfiguration config = new CorsConfiguration(); - config.setAllowCredentials(true); - config.addAllowedOrigin("*"); - config.addAllowedHeader("*"); - config.addAllowedMethod("*"); - config.addAllowedMethod("POST"); - source.registerCorsConfiguration("/**", config); - FilterRegistrationBean bean = new FilterRegistrationBean<>(new CorsFilter(source)); - bean.setOrder(0); - return bean; - } + http.authorizeRequests() + .and() + .csrf() + .disable() + .httpBasic() + .and() + .authenticationProvider(jaasAuthProvider()) + .authorizeRequests() + .and() + .addFilter(new JaasApiIntegrationFilter()) + .authorizeRequests() + .anyRequest() + .fullyAuthenticated(); + } }