diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 00000000..5594efc3 --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,92 @@ +#!groovy +//JRS REST clients + +pipeline { + agent { label 'qaa' } + options { + timeout(time: 1, unit: 'HOURS') + buildDiscarder(logRotator(artifactNumToKeepStr: '5')) + timestamps() + } + environment { + PROD_MVNREPO_SERVER_ID = 'jaspersoft-jfrog-io' + PROD_SNAPSHOT_REPO = 'jaspersoft-clients-snapshots' + PROD_PROD_REPO = 'jaspersoft-clients-releases' + + DEV_MVNREPO_SERVER_ID = 'mvnrepo-jaspersoft-com' + DEV_SNAPSHOT_REPO = 'rest-client-test' + DEV_PROD_REPO = 'rest-client-test-prod' + + RESOLVE_REPO_ID = "${env.DEV_MVNREPO_SERVER_ID}" + RESOLVE_REPO = 'repo' + + devBuild = JENKINS_URL.contains('-dev') + + MVNREPO_SERVER_ID = "${devBuild ? env.DEV_MVNREPO_SERVER_ID : env.PROD_MVNREPO_SERVER_ID}" + SNAPSHOT_REPO = "${devBuild ? env.DEV_SNAPSHOT_REPO : env.PROD_SNAPSHOT_REPO}" + PROD_REPO = "${devBuild ? env.DEV_PROD_REPO : env.PROD_PROD_REPO}" + + MVN_NAME = 'mvn-default' + JDK_NAME = 'jdk-default' + + } + tools { + maven env.MVN_NAME + jdk env.JDK_NAME + } + stages { + stage('Configure') { + steps { + rtMavenResolver ( + id: "maven-resolver-${env.JOB_BASE_NAME}", + serverId: "${env.RESOLVE_REPO_ID}", + releaseRepo: "${env.RESOLVE_REPO}", + snapshotRepo: "${env.RESOLVE_REPO}", + ) + rtMavenDeployer ( + id: "maven-deployer-${env.JOB_BASE_NAME}", + serverId: "${env.MVNREPO_SERVER_ID}", + releaseRepo: "${env.PROD_REPO}", + snapshotRepo: "${env.SNAPSHOT_REPO}", + ) + rtBuildInfo ( + captureEnv: true, + ) + } + } + stage('Build'){ + steps { + rtMavenRun ( + pom: 'pom.xml', + goals: "clean install source:jar --update-snapshots -Dmaven.repo.local=${env.WORKSPACE}/.m2/repository --batch-mode", + /* Not working, bug recently fixed and not yet released. See https://github.com/jfrog/jenkins-artifactory-plugin/pull/139 and HAP-1183 + opts: "--update-snapshots -Dmaven.repo.local=${env.WORKSPACE}/.m2/repository --batch-mode", + */ + resolverId: "maven-resolver-${env.JOB_BASE_NAME}", + deployerId: "maven-deployer-${env.JOB_BASE_NAME}", + ) + } + } + } + post { + success { + archiveArtifacts allowEmptyArchive: true, artifacts: '**/target/*.jar' + script { + echo "devBuid: ${env.devBuild}, server: ${env.MVNREPO_SERVER_ID}, snapshots: ${env.SNAPSHOT_REPO}, release: ${env.PROD_REPO}, JENKINS_URL: ${JENKINS_URL}" + step([$class: 'Publisher', reportFilenamePattern: '**/target/*-reports/*.xml' ]) + } + rtPublishBuildInfo ( + serverId: "${env.MVNREPO_SERVER_ID}", + ) + rtAddInteractivePromotion ( + serverId: "${env.MVNREPO_SERVER_ID}", + targetRepo: "${env.PROD_REPO}", + sourceRepo: "${env.SNAPSHOT_REPO}", + copy: true, + ) + } + cleanup { + cleanWs() + } + } +} diff --git a/README.Jenkinsfile.md b/README.Jenkinsfile.md new file mode 100644 index 00000000..600b5279 --- /dev/null +++ b/README.Jenkinsfile.md @@ -0,0 +1,46 @@ +# JRS java REST client build setup via pipeline + +## Builds +Every branch with exisiting `Jenkisfile` will be picked up by CI and built +Exceptions: +* branches containing `dev-` in names are built on development CI +* branches containing `dev-` in names are **not** built on production CI + +## Pipeline +`Jenkinsfile` uses [Declarative Pipeline]( +https://jenkins.io/doc/book/pipeline/syntax/#declarative-pipeline) +syntax. +`rtMavenResolver`, `rtMavenDeployer`, `rtBuildInfo`, `rtMavenRun`, `rtPublishBuildInfo` and +`rtAddInteractivePromotion` are declarative steps for [Jenkins Artifactory Plugin]( +https://github.com/JFrog/jenkins-artifactory-plugin) and are documented in +[Working With Pipeline Jobs in Jenkins](https://www.jfrog.com/confluence/display/RTF/Working+With+Pipeline+Jobs+in+Jenkins) + +## Flowchart +```mermaid +graph TB + subgraph agent 'qaa' + subgraph pipeline options, environment and tools + A1[Setup pipeline] + end + subgraph stages + subgraph stage Configure + A1 --> B1["Configure (artifactory pipeline plugin)"] + end + subgraph stage Build + B1 --> B2["Build (run Maven via artifactory pipeline plugin)"] + end + end + subgraph Post-build + subgraph success + B2 --> C2[archive artifacts] + C2 --> C3[publish test results] + C3 --> C4[Set buildInfo and interactive promotion artifactory plugin] + end + A1 --> |Timeout or Error | E2 + subgraph always + E2[Remove workspace] + end + C4 --> E2 + end +end +``` diff --git a/README.md b/README.md index d13363da..fe1584da 100755 --- a/README.md +++ b/README.md @@ -1,12 +1,10 @@ Rest Client for JasperReports Server [![Build Status](https://travis-ci.org/Jaspersoft/jrs-rest-java-client.svg?branch=master)](https://travis-ci.org/Jaspersoft/jrs-rest-java-client) [![Coverage Status](https://coveralls.io/repos/Jaspersoft/jrs-rest-java-client/badge.png?branch=master)](https://coveralls.io/r/Jaspersoft/jrs-rest-java-client?branch=master) -========================================= - With this library you can easily write Java applications which can interact with one or more JasperReports servers simultaneously in a very simple way. Library provides very friendly API for user, it minimizes possibility of building wrong requests. Table of Contents ------------------ -1. [Introduction](#introduction). -2. [Configuration](#configuration). +* [Introduction](#introduction). +* [Configuration](#configuration). * [Loading configuration from file](#loading-configuration-from-file). * [Creation of manual configuration](#creation-of-manual-configuration). * [HTTPS configuration](#https-configuration). @@ -16,38 +14,44 @@ Table of Contents * [Logging](#logging). * [Switching between JSON and XML](#switching-between-json-and-xml). * [Client instantiation](#client-instantiation). -3. [Authentication](#authentication). +* [Authentication](#authentication). * [Anonymous session](#anonymous-session). * [Invalidating session](#invalidating-session). -4. [Report services](#report-services). +* [Report services](#report-services). * [Running a report](#running-a-report). * [Requesting report execution status](#requesting-report-execution-status). * [Requesting report execution details](#requesting-report-execution-details). * [Requesting Report Output](#requesting-report-output). * [Download file attachments for report output](#download-file-attachments-for-report-output). - * [Exporting a Report Asynchronously](#exporting-a-report-asynchronously). + * [Updating report execution parameters](#updating-report-execution-parameters). + * [Running new export](#running-new-export). * [Polling Export Execution](#polling-export-execution). * [Finding Running Reports and Jobs](#finding-running-reports-and-jobs). - * [Stopping Running Reports and Jobs](#stopping-running-reports-and-jobs). -5. [Input controls service](#input-controls-service). + * [Stopping Running Reports](#stopping-running-reports). + * [Report options service](#report-options-service). + * [Listing report options](#listing-report-options). + * [Creating report options](#creating-report-options). + * [Updating report options](#updating-report-options). + * [Deleting report options](#deleting-report-options). +* [Input controls service](#input-controls-service). * [Listing input controls structure](#listing-input-controls-structure). * [Reordering input controls structure](#reordering-input-controls-structure). * [Listing input controls values](#listing-input-controls-values). * [Setting input controls values](#setting-input-controls-values). -6. [Administration services](#administration-services). - 1. [Organizations service](#organizations-service). +* [Administration services](#administration-services). + * [Organizations service](#organizations-service). * [Searching for Organizations](#searching-for-organizations). * [Viewing an Organization](#viewing-an-organization). * [Creating an Organization](#creating-an-organization). * [Modifying Organization Properties](#modifying-organization-properties). * [Deleting an Organization](#deleting-an-organization). - 2. [Users service](#users-service). + * [Users service](#users-service). * [Searching for Users](#searching-for-users). * [Viewing a User](#viewing-a-user). * [Creating a User](#creating-a-user). * [Modifying User Properties](#modifying-user-properties). * [Deleting a User](#deleting-a-user). - 3. [Attributes service](#attributes-service). + * [Attributes service](#attributes-service). * [Viewing User Attributes](#viewing-user-attributes). * [Setting User Attributes](#setting-user-attributes). * [Deleting User Attributes](#deleting-user-attributes). @@ -59,17 +63,17 @@ Table of Contents * [Deleting Server Attributes](#deleting-server-attributes). * [Getting attributes permissions](#getting-attributes-permissions). * [Searching attributes ](#searching-attributes). - 4. [The Roles Service](#the-roles-service). + * [The Roles Service](#the-roles-service). * [Searching for Roles](#searching-for-roles). * [Viewing a Role](#viewing-a-role). * [Creating a Role](#creating-a-role). * [Modifying a Role](#modifying-a-role). * [Setting Role Membership](#setting-role-membership). * [Deleting a Role](#deleting-a-role). - 5. [The Settings Service](#settings-service). + * [The Settings Service](#settings-service). * [Getting server specific settings](#getting-server-specific-settings). -7. [Repository Services](#repository-services). - 1. [Resources Service](#resources-service). +* [Repository Services](#repository-services). + * [Resources Service](#resources-service). * [Searching the Repository](#searching-the-repository). * [Viewing Resource Details](#viewing-resource-details). * [Downloading File Resources](#downloading-file-resources). @@ -83,14 +87,14 @@ Table of Contents * [Uploading ReportUnit](#uploading-reportunit). * [Uploading File Resources](#uploading-file-resources). * [Deleting Resources](#deleting-resources). - 2. [The Permissions Service](#the-permissions-service). + * [The Permissions Service](#the-permissions-service). * [Viewing Multiple Permissions](#viewing-multiple-permissions). * [Viewing a Single Permission](#viewing-a-single-permission). * [Setting Multiple Permissions](#setting-multiple-permissions). * [Setting a Single Permission](#setting-a-single-permission). * [Deleting Permissions in Bulk](#deleting-permissions-in-bulk). * [Deleting a Single Permission](#deleting-a-single-permission). -8. [Jobs service](#jobs-service). +* [Jobs service](#jobs-service). * [Listing Report Jobs](#listing-report-jobs). * [Viewing a Job Definition](#viewing-a-job-definition). * [Extended Job Search](#extended-job-search). @@ -101,44 +105,60 @@ Table of Contents * [Pausing Jobs](#pausing-jobs). * [Resuming Jobs](#resuming-jobs). * [Restarting Failed Jobs](#restarting-failed-jobs). -9. [Calendars service](#calendars-service). + * [Calendars service](#calendars-service). * [Listing All Registered Calendar Names](#listing-all-registered-calendar-names). * [Viewing an Exclusion Calendar](#viewing-an-exclusion-calendar). * [Adding or Updating an Exclusion Calendar](#adding-or-updating-an-exclusion-calendar). * [Deleting an Exclusion Calendar](#deleting-an-exclusion-calendar). -10. [Import/Export](#importexport). - 1. [Export service](#export-service). - * [Checking the Export State](#checking-the-export-state). - * [Fetching the Export Output](#fetching-the-export-output). - 2. [Import service](#import-service). - * [Checking the Import State](#checking-the-import-state). -11. [Domain metadata service](#domainmetadata-service). -12. [Thumbnail Search Service](#thumbnail-search-service). -13. [Diagnostic Service](#diagnostic-service). -14. [Query Executor Service](#query-executor-service). -15. [Server Information Service](#server-information-service). -16. [Bundles service](#bundles-service). -17. [Asynchronous API](#asynchronous-api). -18. [Getting serialized content from response](#getting-serialized-content-from-response). -19. [Possible issues](#possible-issues). -20. [Maven dependency to add jasperserver-rest-client to your app](#maven-dependency-to-add-jasperserver-rest-client-to-your-app). -21. [License](#license). +* [Import/Export](#importexport). + * [Export service](#export-service). + * [Strat export](#strat-export). + * [Check the export state](#check-the-export-state). + * [Fetching the export output](#fetching-the-export-output). + * [Cancel the export task](#cancel-the-export-task). + * [Import service](#import-service). + * [Strat import](#strat-import). + * [Import using mulpipart form](#import-using-mulpipart-form). + * [Check the Import State](#check-the-import-state). + * [Getting and restarting import task](#checking-the-export-state). + * [Check import state](#check-import-state). + * [Cancel import task](#cancel-import-task). +* [Metadata](#metadata) + * [Domain metadata](#domain-metadata). + * [Report metadata](#report-metadata). +* [Thumbnail Search Service](#thumbnail-search-service). +* [Diagnostic Service](#diagnostic-service). +* [Contexts service](#contexts-service) + * [Domain Context Service](#domain-context-service). +* [Data Discovery Service](#data-discovery-service). + * [Domain data discovery](#domain-data-discovery). + * [DomEl data discovery](#domel-data-discovery). + * [Derived table data discovery](#derived-table-data-discovery). +* [Query Execution Service](#query-execution-service). +* [Server Information Service](#server-information-service). +* [Bundles service](#bundles-service). +* [Asynchronous API](#asynchronous-api). +* [Getting serialized content from response](#getting-serialized-content-from-response). +* [Possible issues](#possible-issues). +* [Maven dependency to add jasperserver-rest-client to your app](#maven-dependency-to-add-jasperserver-rest-client-to-your-app). +* [License](#license). Introduction -------------- +============ With this library you can easily write Java applications which can interact with one or more JasperReports servers simultaneously in a very simple way. Library provides very friendly API for user, it minimizes possibility of building wrong requests. To use library in your maven-based application you need just to specify dependency and repository which are given below or download jar file manually from ``` http://jaspersoft.artifactoryonline.com/jaspersoft/repo/com/jaspersoft/jrs-rest-java-client/{version}/jrs-rest-java-client-{version}.jar ``` Configuration -------------- +============= To start working with the library you should firstly configure one ore more instances of `JasperserverRestClient`. To do this you should create instance of `RestClientConfiguration`. It can be done in two ways: - loading configuration from file; - creation of manual configuration in java code. -###Loading configuration from file: +Loading configuration from file: +-------------------------------- ```java RestClientConfiguration configuration = RestClientConfiguration.loadConfiguration("configuration.properties"); ``` @@ -161,13 +181,15 @@ acceptMimeType=JSON File must contain at least URL which is entry point to your server's REST services and it is needed to URL corresponds to this pattern `{protocol}://{host}:{port}/{contextPath}`. Please notice, configuration settings may be changed after loading manually in java code. -###Creation of manual configuration +Creation of manual configuration +-------------------------------- To configure `JasperserverRestClient` manually, use the constructor of `RestClientConfiguration` and properties: ```java RestClientConfiguration configuration = new RestClientConfiguration("http://localhost:8080/jasperserver"); configuration.setAcceptMimeType(MimeType.JSON).setContentMimeType(MimeType.JSON).setJrsVersion(JRSVersion.v6_0_0).setLogHttp(true); ``` -####HTTPS configuration +HTTPS configuration +------------------- **To use HTTPS you need:** 1. Configure your server to support HTTPS 2. Download [InstallCert](http://miteff.com/files/InstallCert-bin.zip) util and follow [InstallCert-Guide](http://www.mkyong.com/webservices/jax-ws/suncertpathbuilderexception-unable-to-find-valid-certification-path-to-requested-target/) instructions. @@ -181,7 +203,8 @@ TrustManager[] trustManagers = new TrustManager[1]; trustManagers[0] = x509TrustManager; configuration.setTrustManagers(trustManagers); ``` -####X-HTTP-Method override +X-HTTP-Method override +---------------------- To avoid situation, when your proxies or web services do not support arbitrary HTTP methods or newer HTTP methods, you can use “restricted mode”. In this mode `JaperserverRestClient` sends requests through POST method and set the `X-HTTP-Method-Override` header with value of intended HTTP method. To use this mode you should set flag `RestrictedHttpMethods`: ```java configuration.setRestrictedHttpMethods(true); @@ -191,7 +214,9 @@ Or in configuration file: restrictedHttpMethods=false ```` If you do not use the "restricted mode", POST or GET methods and server returns the response with 411 error code, `JaperserverRestClient` resend this request through POST method with the X-HTTP-Method-Override header automatically. -####Switching authentication type + +Switching authentication type +----------------------------- `JasperserverRestClient` supports two authentication types: SPRING and BASIC. `SPRING` type of authentication means that your credentials are sent as a form to `/j_security_check directly/` uri. Using these types you obtain JSESSIONID cookie of authenticated session after sending credentials. In the `BASIC` mode `JasperserverRestClient` uses basic authentication (sends encrypted credentials with each request). @@ -206,7 +231,9 @@ Or set authentication type in configuration file: authenticationType=BASIC ``` Please notice, the basic authentication is not stateless and it is valid till method logout() is called or the application is restarted and you can not use this authentication type for Report Service, because all operations must be executed in the same session (for details, read section [Report services](https://github.com/Jaspersoft/jrs-rest-java-client/blob/master/README.md#report-services)). -####Exception handling + +Exception handling +------------------ You can choose strategy of errors that are specified by status code of server response: 1. handling of errors directly. This mode is allowed by default. 2. getting operation result in any case with null entity and handling error after calling `getEntity()` method: @@ -235,7 +262,8 @@ JRS REST client exception handling system is based on `com.jaspersoft.jasperserv 2. You can create your own handler by implementing `com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.ErrorHandler`. 3. You can extend `com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultExceptionHandler` or any other handler and override its methods `void handleBodyError(Response response)` and/or `void handleStatusCodeError(Response response, String overridingMessage)`. -####Logging +Logging +------- It is possible to log outgoing requests and incoming responses using `logHttp` property of `RestCleintConfiguration`: ```java config.setLogHttp(true); @@ -249,7 +277,8 @@ In configuration file: logHttp=true logHttpEntity=true ``` -####Switching between JSON and XML +Switching between JSON and XML +------------------------------ You can configure a client to make request either with JSON or XML content. ```java RestClientConfiguration configuration = new RestClientConfiguration("http://localhost:4444/jasperserver"); @@ -264,14 +293,15 @@ or contentMimeType=XML acceptMimeType=XML ``` -####Client instantiation: +Client instantiation: +--------------------- After configuration you need just to pass `configuration` instance to `JasperserverRestClient` constructor. ```java JasperserverRestClient client = new JasperserverRestClient(configuration); ``` Authentication ---------------- +============== This library automatically encrypts your password before send it if encryption is on, so to authenticate you need just specify login and password (not encrypted) in `authenticate()` method. ```java Session session = client.authenticate("jasperadmin", "jasperadmin"); @@ -290,234 +320,352 @@ Session session = client.authenticate("jasperadmin", "jasperadmin", new Locale(" // or Session session = client.authenticate("jasperadmin", "jasperadmin", "de", America/Los_Angeles"); ``` -###Anonymous session +Anonymous session +----------------- For some Jasperserver services authentication is not required (for example, settings service, bundles service or server info service), so you can use anonymous session: ```java AnonymousSession session = client.getAnonymousSession(); ``` -####Invalidating session +Invalidating session +-------------------- Not to store session on server you can invalidate it with `logout()` method. ```java session.logout(); ``` - Report services =============== -After you've configured the client you can easily use any of available services. For reporting service there is one feature that should be noted - when you are running a report all subsequent operations must be executed in the same session. Here's the code: +This service allows to start report execution(export with certain options) and get report execution metadata (i.e. execution status, total pages count, errors occured during execution, attachments names etc.). +Another major feature is possibility to run/export report asynchronously. +For reporting service there is one feature that should be noted - when you are running a report all subsequent operations must be executed **in the same session**. Here's the code: + +Running a report: +----------------- +jaserserver REST API allows to run report execution in synchronous and asynchronous modes. The `async` mode is set in ReportExecutionRequest or as part of builer chain: ```java -Session session = client.authenticate("jasperadmin", "password"); + OperationResult result = session + .reportingService() + .report(reportUnitUri) + .reportExecutions() + .outputFormat(ReportOutputFormat.PDF) + .pages(1) + .reportParameter("Cascading_state_multi_select", "CA") + .reportParameter("Cascading_state_multi_select", "OR", "WA") + .reportParameter("Country_multi_select", "USA") + .async(Boolean.FALSE) + .run(); + + ReportExecution entity = result.getEntity(); + + // OR set parameters as ReportEecutionrequest + + final ReportParameter reportParameter1 = new ReportParameter().setName(name).setValues(asList(value1, Value2)); + reportParameters.setReportParameters(asList(reportParameter1)); + + final ReportExecutionRequest reportExecutionRequest = new ReportExecutionRequest() + .setReportUnitUri(reportUnitUri) + .setPages("1") + .setParameters(reportParameters) + .setOutputFormat("pdf") + .setAsync(Boolean.TRUE); + + OperationResult result = session + .reportingService() + .reportExecution(reportExecutionRequest) + .run(); + + ReportExecution entity = result.getEntity(); ``` -We've authenticated as `jasperadmin` user an got a session for this user, all subsequent operations must be done through this session instance. -####Running a report: -There are two approaches to run a report - in synchronous and asynchronous modes. -To run report in synchronous mode you can use the code below: +Please notice, if you pass zero as number of page, you will get all pages of report. + +In order to run a report, you need firstly build `ReportExecutionRequest` instance and specify all the parameters needed to launch a report. The response from the server is the `ReportExecution`, the edscriptor of execution, contains the request ID needed to track the execution until completion and others report parameters. + +Requesting report execution status: +----------------------------------- +After you've got `ReportExecutionDescriptor` you can request for the report execution status: ```java -OperationResult result = client - .authenticate("jasperadmin", "jasperadmin") - .reportingService() - .report("/reports/samples/Cascading_multi_select_report") - .prepareForRun(ReportOutputFormat.HTML, 1) - .parameter("Cascading_name_single_select", "A & U Stalker Telecommunications, Inc") - .run(); -InputStream report = result.getEntity(); + final OperationResult operationResult = session + .reportingService() + .reportExecution(executionId) + .status(); + final ReportExecutionStatusObject entity = operationResult.getEntity(); + ``` -You can set format of report as String as well(name of format is case insensitive): +To get report execution status with error descriptor from server just specify `.withErrorDescriptor(Boolean.TRUE)` setting: ```java -OperationResult result = client - .authenticate("jasperadmin", "jasperadmin") - .reportingService() - .report("/reports/samples/Cascading_multi_select_report") - .prepareForRun("HTML", 1) - .parameter("Cascading_name_single_select", "A & U Stalker Telecommunications, Inc") - .run(); + final OperationResult statusOperationResult = session + .reportingService() + .reportExecution(executionId) + .export(exportId) + .withErrordescriptor(Boolean.TRUE) + .status(); ``` -Also you can use this method to run report with several values for the same parameter. In this case new values of the parameter are added to the previous ones (new values do not replace previous values of the parameter): + +Requesting report execution details: +------------------------------------ +Once the report is ready, your client must determine the names of the files to download by requesting the +reportExecution descriptor again. ```java -OperationResult result = client - .authenticate("superuser", "superuser") - .reportingService() - .report("/reports/samples/Cascading_multi_select_report") - .prepareForRun(ReportOutputFormat.PDF, 1) - .parameter("Cascading_state_multi_select", "CA") - .parameter("Cascading_state_multi_select", "OR", "WA") - .parameter("Cascading_name_single_select", "Adams-Steen Transportation Holdings") - .parameter("Country_multi_select", "USA") - .run(); + final OperationResult operationResult = session + .reportingService() + .reportExecution(executionId) + .details(); + + ReportExecution details = operationResult.getEntity(); ``` -Please notice, if you pass zero as number of page, you will get all pages of report. -In this mode you don't need to work in one session. In the above code we specified report URI, format in which we want to get a report and some report parameters. As we a result we got `InputStream` instance. In synchronous mode as a response you get a report itself while in asynchronous you get just a descriptor with report ID which you can use to download report afer it will be ready. -If you need run report in another time zone specify it using `forTimeZone()` method: + +Requesting Report Output +------------------------ +After requesting a report execution and waiting synchronously or asynchronously for it to finish, you are ready to download the report output. Every export format of the report has an ID that is used to retrieve it. For example, the HTML export has the ID html. To download the main report output, specify this export ID in the `export` method. For example, to download the main HTML of the report execution response above, use the following code: ```java -OperationResult result = session + OperationResult runOperationResult = session .reportingService() - .report("/public/Samples/Reports/12g.PromotionDetailsReport") - .prepareForRun(ReportOutputFormat.PDF, 1) - .forTimeZone(TimeZone.getTimeZone("America/Los_Angeles")) + .report(reportUri) + .reportExecutions() + .outputFormat(ReportOutputFormat.HTML) + .pages(1) + .async(Boolean.FALSE) .run(); -InputStream report = result.getEntity(); - - // or set time zones as string + final ReportExecution entity = runOperationResult.getEntity(); + + String executionId = entity.getRequestId(); + + final ExportExecution export = entity.getExports().iterator().next(); + + final String exportId = export.getId(); + + OperationResult outputResourceOperationResult = session + .reportingService() + .reportExecution(executionId) + .export(exportId) + .getOutputResource(); +``` +As a response you'll get an `InputStream` instance. If the output resourse is one of test formats(txt, html, csv etc), resource output is sent as String, so to get output, use +```java + OperationResult outputResourceOperationResult = session + .reportingService() + .reportExecution(executionId) + .export(exportId) + .getOutputResourceAsText(); + String output = outputResourceOperationResult.getEntity(); +``` +There is a shorter way to get report output, but you sould take into account that it works onlly in asynchronous way, allows set limited set od settings and retuns report parametest in deprecated format: +```java OperationResult result = session .reportingService() - .report("/public/Samples/Reports/12g.PromotionDetailsReport") + .report(reportUri) .prepareForRun(ReportOutputFormat.PDF, 1) - .forTimeZone("America/Los_Angeles") + .forTimeZone(TimeZone.getTimeZone("America/Los_Angeles"))//if the time zone is defferent from session time zone .run(); +InputStream report = result.getEntity(); ``` -In order to run a report in asynchronous mode, you need firstly build `ReportExecutionRequest` instance and specify all the parameters needed to launch a report. The response from the server is the `ReportExecutionDescriptor` instance which contains the request ID needed to track the execution until completion and others report parameters. Here's the code to run a report: -```java -//instantiating request and specifying report parameters -ReportExecutionRequest request = new ReportExecutionRequest(); -request.setReportUnitUri("/reports/samples/StandardChartsReport"); -request - .setAsync(true) //this means that report will be run on server asynchronously - .setOutputFormat(ReportOutputFormat.HTML); //report can be requested in different formats e.g. html, pdf, etc. -OperationResult operationResult = - session //pay attention to this, all requests are in the same session!!! +Download file attachments for report output: +-------------------------------------------- +To download file attachments for HTML output, use the following code. You must download all attachments to display the HMTL content properly. +```java + OperationResult runOperationResult = session .reportingService() - .newReportExecutionRequest(request); + .report(reportUri) + .reportExecutions() + .outputFormat(ReportOutputFormat.HTML) + .pages(1) + .async(Boolean.FALSE) + .run(); -reportExecutionDescriptor = operationResult.getEntity(); + final ReportExecution entity = runOperationResult.getEntity(); + String executionId = entity.getRequestId(); + final ExportExecution export = entity.getExports().iterator().next(); + final OutputResourceDescriptor attachment = export.getAttachments().entrySet().iterator().next().getValue(); + + final String exportId = export.getId(); + + final OperationResult outputResourceOperationResult = session + .reportingService() + .reportExecution(executionId) + .export(exportId) + .getOutputResourceAttachment(attacment); ``` -In the above code we've created `ReportExecutionRequest` instance and sent it to JR server through the `newReportExecutionRequest` method. As a response we've got `OperationResult` instance which contains HTTP response wrapper and instance of `ReportExecutionDescriptor` which we can get with `operationResult.getEntity()`. -Also you can set output format as String: +Updating report execution parameters +------------------------------------ +Use the next code to change report execution parameters (e.g. input controls values) without change of report execution ID and to keep exports set. Report is executed again on this request but with updated parameters. ```java -ReportExecutionRequest request = new ReportExecutionRequest(); -request.setReportUnitUri("/reports/samples/StandardChartsReport"); -request - .setAsync(true) - .setOutputFormat("html"); + session + .reportingService() + .reportExecution(executionId) + .updateParameters(reportParameters); ``` -As in sync mode you can set report time zone: -```java -ReportExecutionRequest request = new ReportExecutionRequest(); -request - .setOutputFormat(ReportOutputFormat.PDF) - .setPages("1") - .setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")) - .setReportUnitUri("/public/Samples/Reports/12g.PromotionDetailsReport") - .setAsync(true); + +Running new export +------------------ +After running a report and downloading its content in a given format, you can request the same report in other formats (or with other options) without restaring export execution. As with exporting report formats through the user interface, the report does not run again because the export process is independent of the report. +```java + ExportExecutionOptions executionOptions = new ExportExecutionOptions(); + executionOptions.setBaseUrl(jasperserverUri); + executionOptions.setOutputFormat(ReportOutputFormat.PDF.name()); + executionOptions.setPages("1"); + executionOptions.setIgnorePagination(Boolean.FALSE); + final OperationResult expoirtExecutionOpertaionResult = session + .reportingService() + .reportExecution(executionId) + .export() + .withOptions(executionOptions) + .run(); ``` -####Requesting report execution status: -After you've got `ReportExecutionDescriptor` you can request for the report execution status: +Polling Export Execution +------------------------ +As with the execution of the main report, you can also poll the execution of the export process. +For example, to get the status export use the following code: ```java -OperationResult operationResult = - session //pay attention to this, all requests are in the same session!!! + final OperationResult statusOperationResult = session .reportingService() - .reportExecutionRequest(reportExecutionDescriptor.getRequestId()) + .reportExecution(executionId) + .export(exportId) .status(); ReportExecutionStatusEntity statusEntity = operationResult.getEntity(); ``` -In the above code we've just specified request ID and got its status as a `ReportExecutionStatusEntity` instance. -####Requesting report execution details: -Once the report is ready, your client must determine the names of the files to download by requesting the -reportExecution descriptor again. + +Finding Running Reports and Jobs +-------------------------------- +You can search for reports that are running on the server, including report jobs triggered by the scheduler. To search for running reports, use the search arguments from `ReportSearchParameter` enumeration. ```java -OperationResult operationResult = - session //pay attention to this, all requests are in the same session!!! + final OperationResult operationResult = session .reportingService() - .reportExecutionRequest(reportExecutionDescriptor.getRequestId()) - .executionDetails(); - -ReportExecutionDescriptor descriptor = operationResult.getEntity(); + .reportExecutions() + .queryParameter(ReportSearchParameter.REPORT_URI, reportUnitUri) + .search(); + final ReportExecutionsSetWrapper entity = operationResult.getEntity(); ``` -####Requesting Report Output -After requesting a report execution and waiting synchronously or asynchronously for it to finish, you are ready to download the report output. Every export format of the report has an ID that is used to retrieve it. For example, the HTML export has the ID html. To download the main report output, specify this export ID in the `export` method. For example, to download the main HTML of the report execution response above, use the following code: + +Stopping Running Reports +--------------------------------- +To stop a report that is running and cancel its output, use the code below: ```java -OperationResult operationResult = - session //pay attention to this, all requests are in the same session!!! + final OperationResult operationResult = session .reportingService() - .reportExecutionRequest(reportExecutionDescriptor.getRequestId()) - .export("html") - .outputResource(); - -InputStream file = operationResult.getEntity(); + .reportExecution(executionId) + .cancel(); ``` -As a response you'll get an `InputStream` instance. -####Download file attachments for report output: -To download file attachments for HTML output, use the following code. You must download all attachments to display the HMTL content properly. +To delete report execution: ```java -ExportDescriptor htmlExportDescriptor = ... //retrieving htmlExportDescriptor from reportExecutionDescriptor + final OperationResult deleteOperationresult = session + .reportingService() + .reportExecution(executionId) + .delete(); +``` -for(AttachmentDescriptor attDescriptor : htmlExportDescriptor.getAttachments()){ - OperationResult operationResult = - session //pay attention to this, all requests are in the same session!!! +Report options service +---------------------- +Report options are sets of input control values that are saved in the repository. A report option is always associated with a report. + +### Listing report options +```java + OperationResult result = session .reportingService() - .reportExecutionRequest(reportExecutionDescriptor.getRequestId()) - .export(htmlExportDescriptor.getId()) - .attachment(attDescriptor.getFileName()); + .report(reportUnitUri) + .reportOptions() + .get(); - InputStream file = operationResult.getEntity(); - //doing something with file -} + final ReportOptionsSummaryList entity = result.getEntity(); ``` -####Exporting a Report Asynchronously -After running a report and downloading its content in a given format, you can request the same report in other formats. As with exporting report formats through the user interface, the report does not run again because the export process is independent of the report. +The body of the response contains the description of the report options(URI, Id and label). + +### Creating report options +The following code example creates a new report option for a given report. A report option is defined by a set of values for **all** of the report’s input controls. ```java -ExportExecutionOptions exportExecutionOptions = new ExportExecutionOptions() - .setOutputFormat(ReportOutputFormat.PDF) - .setPages("3"); + final MultivaluedHashMap map = new MultivaluedHashMap(); + map.addAll("Country_multi_select", "Mexico"); + map.addAll("Cascading_state_multi_select", "Guerrero", "Sinaloa"); + map.addAll("Cascading_name_single_select", "Crow-Sims Construction Associates"); -OperationResult operationResult = - session - .reportingService() - .reportExecutionRequest(reportExecutionDescriptor.getRequestId()) - .runExport(exportExecutionOptions); + OperationResult result = session + .reportingService() + .report(reportUnitUri) + .reportOptions(map) + .label(OPTIONS_LABEL) + .create(); -ExportExecutionDescriptor statusEntity = operationResult.getEntity(); -``` -####Polling Export Execution -As with the execution of the main report, you can also poll the execution of the export process. -For example, to get the status of the HTML export in the previous example, use the following code: + final ReportOptionsSummary entity = result.getEntity(); + ``` + or + ```java + final List reportParameters = new LinkedList(); + reportParameters.add(new ReportParameter().setName("Country_multi_select").setValues(asList("Mexico"))); + reportParameters.add(new ReportParameter().setName("Cascading_state_multi_select").setValues(asList("Guerrero", "Sinaloa"))); + reportParameters.add(new ReportParameter().setName("Cascading_name_single_select").setValues(asList("Crow-Sims Construction Associates"))); + + + OperationResult result = session + .reportingService() + .report(reportUnitUri) + .reportOptions(reportParameters) + .label(OPTIONS_LABEL) + .create(); + + final ReportOptionsSummary entity = result.getEntity() + ``` +The server responds with a JSON object that describes the new report options + +### Updating report options +Use the following example to modify the values in a given report option ```java -OperationResult operationResult = - session //pay attention to this, all requests are in the same session!!! - .reportingService() - .reportExecutionRequest(reportExecutionDescriptor.getRequestId()) - .export("html") - .status(); + final MultivaluedHashMap map = new MultivaluedHashMap(); + map.addAll("Country_multi_select", "USA"); -ReportExecutionStatusEntity statusEntity = operationResult.getEntity(); + OperationResult result = session + .reportingService() + .report(reportUnitUri) + .reportOptions(OPTIONS_LABEL) + .update(map); ``` -####Finding Running Reports and Jobs -You can search for reports that are running on the server, including -report jobs triggered by the scheduler. -To search for running reports, use the search arguments from `ReportAndJobSearchParameter` enumeration. +or ```java -OperationResult operationResult = - session - .reportingService() - .runningReportsAndJobs() - .parameter(ReportAndJobSearchParameter.REPORT_URI, "/reports/samples/AllAccounts") - .find(); + final List reportParameters = new LinkedList(); + reportParameters.add(new ReportParameter().setName("Country_multi_select").setValues(asList("USA"))); + -ReportExecutionListWrapper entity = operationResult1.getEntity(); + + OperationResult result = session + .reportingService() + .report(reportUnitUri) + .reportOptions(OPTIONS_LABEL) + .update(reportParameters); + + final ReportOptionsSummary entity = result.getEntity(); ``` -####Stopping Running Reports and Jobs -To stop a report that is running and cancel its output, use the code below: -```java -OperationResult operationResult1 = - session - .reportingService() - .reportExecutionRequest(executionDescriptor.getRequestId()) - .cancelExecution(); -ReportExecutionStatusEntity statusEntity = operationResult1.getEntity(); +### Deleting report options +To delete a given report option you can use followingcode: +```java + OperationResult result = session + .reportingService() + .report(reportUnitUri) + .reportOptions(OPTIONS_LABEL) + .delete(); ``` -###Input controls service: -The reports service includes methods for reading and setting input controls of any input controls container, i.e. reportUnit, reportOptions, dashboard, adhocDataView -####Listing Report Parameters Structure +Input controls service: +======================= +The reports service includes methods for reading and setting input controls of any input controls container, i.e. reportUnit, reportOptions, dashboard, adhocDataView. JRS Rest client allows to work with report input controls as part of ReportService or as independent InputControlService. + +Listing Report Parameters Structure +----------------------------------- The following code returns a description of the structure of the input controls for a given container. ```java + OperationResult operationResult = session + .reportingService() + .report(REPORT_URI) + .inputControls() + .get(); + + // or + OperationResult operationResult = session .inputControlsService() .inputControls() - .container("/reports/samples/Cascading_multi_select_report") + .forReport(REPORT_URI) .get(); ReportInputControlsListWrapper result = operationResult.getEntity(); ``` @@ -527,83 +675,175 @@ The structure includes a set of validation rules for each report parameter. Thes * dateTimeFormatValidation – This input must have a data time format and your client should ensure the user enters a valid date and time. To skip input controls state generation use `excludeState(true)` setting: ```java + OperationResult operationResult = session + .reportingService() + .report(REPORT_URI) + .inputControls() + .excludeState(Boolean.TRUE) + .get(); + + // or + OperationResult operationResult = session .inputControlsService() .inputControls() - .container("/reports/samples/Cascading_multi_select_report") + .forReport(REPORT_URI) .excludeState(true) .get(); ReportInputControlsListWrapper result = operationResult.getEntity(); ``` -####Reordering input controls structure + +Reordering input controls structure +----------------------------------- You can change structure of input controls according to client demands using the next code: ```java + OperationResult reorderedOperationResult = session + .reportingService() + .report(REPORT_URI) + .inputControls() + .reorder(inputParameters); + + //or + + OperationResult reorderedOperationResult = session .inputControlsService() .inputControls() - .container("/reports/samples/Cascading_multi_select_report") + .forReport(REPORT_URI) .reorder(inputParameters); ``` It is impossible to change input controls except change of theirs order. Sent to server structure MUST be the same as it received from there, except order. You cannot modify some values, add or remove control, etc. -####Listing input controls values + +Listing input controls values +----------------------------- The following code returns a description of the possible values of all report parameters for the report. Among these choices, it shows which ones are selected. ```java + OperationResult operationResult = session + .reportingService() + .report(REPORT_URI) + .inputControls() + .values() + .get(); + OperationResult operationResult = session .inputControlsService() .inputControls() - .container("/reports/samples/Cascading_multi_select_report") + .forReport(REPORT_URI) .values() .get(); InputControlStateListWrapper result = operationResult.getEntity(); ``` The response contains the structure of the report parameters for the report. If a selection-type report parameter has a null value, it is given as `NULL`. If no selection is made, its value is given as `NOTHING`. -Use setting `useCashedData(false)` to avoid getting cashed data: +Use setting `useCachedData(false)` to avoid getting cashed data: ```java OperationResult operationResult = session .inputControlsService() .inputControls() .container("/reports/samples/Cascading_multi_select_report") .values() - .useCashedData(false) + .useCachedData(false) .get(); InputControlStateListWrapper result = operationResult.getEntity(); ``` -####Setting input controls values + +Setting input controls values +----------------------------- The following code updates the state of specified input controls values, so they are set for the next run of the report. ```java + OperationResult operationResult = session + .reportingService() + .report(REPORT_URI) + .inputControls() + .values() + .forInputConrol(id, value1, value2) + .forInputConrol(id1, value3) + .update(); + + //or + + MultivaluedHashMap inputControls = new NullableMultivaluedHashMap(); + inputControls.addAll("Country_multi_select", "Mexico"); + inputControls.addAll("Cascading_state_multi_select", "Guerrero", "Sinaloa"); + + OperationResult operationResult = session + .reportingService() + .report(REPORT_URI) + .inputControls() + .values() + .update(inputControls); + + // or + OperationResult operationResult = session .inputControlsService() .inputControls() - .container("/reports/samples/Cascading_multi_select_report") + .forReport("/reports/samples/Cascading_multi_select_report") .values() - .parameter("Country_multi_select", "Mexico") - .parameter("Cascading_state_multi_select", "Guerrero", "Sinaloa") + .forInputControl(id, value) + .forInputControl(id, value1, value2) .run(); InputControlStateListWrapper result = operationResult.getEntity(); ``` In response you get updated values for specified input controls. If you want to get updated values with full structure of input controls, you should use `includeFullStructure(true)` setting: ```java + OperationResult operationResult = session + .reportingService() + .report(REPORT_URI) + .inputControls() + .values() + .forInputConrol(id, value1, value2) + .forInputConrol(id1, value3) + .includeFullStructure(true) + .update(); + + // or + + OperationResult operationResult = session .inputControlsService() .inputControls() - .container("/reports/samples/Cascading_multi_select_report") + .forReport("/reports/samples/Cascading_multi_select_report") .values() - .parameter("Country_multi_select", "USA") - .parameter("Cascading_state_multi_select", "CA", "OR", "WA") - .includeFullStructure(true) + .forInputControl(id, value) + .forInputControl(id, value1, value2) + .includeFullStructure(true) .run(); InputControlStateListWrapper result = operationResult.getEntity(); ``` +To uptate values of input controls with their structure in the same request: +```java + MultivaluedHashMap inputControls = new NullableMultivaluedHashMap(); + inputControls.addAll("Cascading_state_multi_select", "OR", "CA", "WA"); + inputControls.addAll("Country_multi_select", "USA", "Canada"); + + final OperationResult operationResult = session + .reportingService() + .report(REPORT_URI) + .inputControls() + .values() + .updateAndReorder(inputControls); + + // or + + final OperationResult operationResult = session + .inputControlsService() + .inputControls() + .forReport("/reports/samples/Cascading_multi_select_report") + .values() + .updateAndReorder(inputControls); +``` Administration services: ======================== Only administrative users may access the REST services for administration. -###Organizations service +Organizations service +--------------------- It provides methods that allow you to list, view, create, modify, and delete organizations (also known as tenants). Because the organization ID is used in the URL, this service can operate only on organizations whose ID is less than 100 characters long and does not contain spaces or special symbols. As with resource IDs, the organization ID is permanent and cannot be modified for the life of the organization. -####Searching for Organizations + +### Searching for Organizations The service searches for organizations by ID, alias, or display name. If no search is specified, it returns a list of all organizations. Searches and listings start from but do not include the logged-in user’s organization or the specified base. ```java @@ -613,7 +853,8 @@ OperationResult result = session .parameter(OrganizationParameter.INCLUDE_PARENTS, "true") .get(); ``` -####Viewing an Organization + +### Viewing an Organization The `organization()` method with an organization ID retrieves a single descriptor containing the list of properties for the organization. When you specify an organization, use its unique ID, not its path. ```java OperationResult result = session @@ -631,7 +872,8 @@ OperationResult result = session .organization(organization) .get(); ``` -####Creating an Organization + +### Creating an Organization To create an organization, put all information in an organization descriptor, and include it in a request to the `rest_v2/organizations` service, with no ID specified. The organization is created in the organization specified by the `parentId` value of the descriptor. ```java OperationResult result = session @@ -649,7 +891,8 @@ OperationResult result = session Be carefully using this method because you can damage existing organization if the `organizationId` of new organization is already used. The descriptor is sent in the request should contain all the properties you want to set on the new organization. Specify the `parentId` value to set the parent of the organization, not the `tenantUri` or `tenantFolderUri` properties. However, all properties have defaults or can be determined based on the alias value. The minimal descriptor necessary to create an organization is simply the alias property. In this case, the organization is created as child of the logged-in user’s home organization. -####Modifying Organization Properties + +### Modifying Organization Properties To modify the properties of an organization, use the `update` method and specify the organization ID in the URL. The request must include an organization descriptor with the values you want to change. You cannot change the ID of an organization, only its name (used for display) and its alias (used for logging in). ```java Organization organization = new Organization(); @@ -660,7 +903,8 @@ OperationResult result = session .organization("myOrg1") .createOrUpdate(organization); ``` -####Deleting an Organization + +### Deleting an Organization To delete an organization, use the `delete()` method and specify the organization ID in the `organization()` method. When deleting an organization, all of its resources in the repository, all of its sub-organizations, all of its users, and all of its roles are permanently deleted. ```java OperationResult result = session @@ -668,10 +912,13 @@ OperationResult result = session .organization("myOrg1") .delete(); ``` -###Users service + +Users service +------------- It provides methods that allow you to list, view, create, modify, and delete user accounts, including setting role membership. Because the user ID is used in the URL, this service can operate only on users whose ID is less than 100 characters long and does not contain spaces or special symbols. As with resource IDs, the user ID is permanent and cannot be modified for the life of the user account. -####Searching for Users + +### Searching for Users You can search for users by name or by role. If no search is specified, service returns all users. ```java OperationResult operationResult = @@ -683,7 +930,8 @@ OperationResult operationResult = UsersListWrapper usersListWrapper = operationResult.getEntity(); ``` -####Viewing a User + +### Viewing a User Method `username()` with a user ID (username) retrieves a single descriptor containing the full list of user properties and roles. ```java OperationResult operationResult = @@ -714,7 +962,8 @@ OperationResult operationResult = ClientUser user = operationResult.getEntity(); ``` The full user descriptor includes detailed information about the user account, including any roles. -####Creating a User + +### Creating a User To create a user account, put all required information in a user descriptor `ClientUser`, and include it in a request to the users service (`createOrUpdate()` method), with the intended user ID (username) specified in the `username()` method. To create a user, the user ID in the `username()` method must be unique on the server. If the user ID already exists, that user account will be modified. The descriptor sent in the request should contain all the properties you want to set on the new user, except for the username that is specified in the `username()` method. To set roles on the user, specify them as a list of roles. ```java //Creating a user @@ -750,7 +999,8 @@ client .user(user.getUsername()) .createOrUpdate(user); ``` -####Modifying User Properties + +### Modifying User Properties To modify the properties of a user account, put all desired information in a user descriptor (`ClientUser`), and include it in a request to the users service (`createOrUpdate()` method), with the existing user ID (username) specified in the `username()` method. To modify a user, the user ID must already exist on the server. If the user ID doesn’t exist, a user account will be created. To add a role to the user, specify the entire list of roles with the desired role added. To remove a role from a user, specify the entire list of roles without the desired role removed. ```java ClientUser user = new ClientUser() @@ -767,7 +1017,8 @@ client .user("john.doe") .createOrUpdate(user); ``` -####Deleting a User + +### Deleting a User To delete a user, call the `delete()` method and specify the user ID in the `username()` method. ```java client @@ -777,11 +1028,13 @@ client .delete(); ``` -###Attributes service +Attributes service +------------------ Attributes, also called profile attributes, are name-value pairs associated with a user, organization or server. Certain advanced features such as Domain security and OLAP access grants use profile attributes in addition to roles to grant certain permissions. Unlike roles, attributes are not pre-defined, and thus any attribute name can be assigned any value at any time. Attributes service provides methods for reading, writing, and deleting attributes on any given holder (server, organization or user account). All attribute operations apply to a single specific holder; there are no operations for reading or searching attributes from multiple holders. As the holder's id is used in the URL, this service can operate only on holders whose ID is less than 100 characters long and does not contain spaces or special symbols. In addition, both attribute names and attribute values being written with this service are limited to 255 characters and may not be empty (null) or not contain only whitespace characters. -####Viewing User Attributes + +### Viewing User Attributes The code below allow you to retrieve single attribute defined for the user: ```java HypermediaAttribute userAttribute = session @@ -856,7 +1109,7 @@ You can get the list of all attributes that includes the name and value of each ``` Each attribute may only have one value, however that value may contain a comma-separated list that is interpreted by the server as being multi-valued. -####Setting User Attributes +### Setting User Attributes The `createOrUpdate()` method of the attributes service adds or replaces attributes on the specified user. The list of attributes defines the name and value of each attribute. Each attribute may only have one value, however, that value may contain a comma separated list that is interpreted by the server as being multi-valued. There are two syntaxes, the following one is for adding or replacing all attributes ```java @@ -899,7 +1152,8 @@ The second way of using the attributes service is adding or replacing individual .createOrUpdate(attribute) .getEntity(); ``` -####Deleting User Attributes + +### Deleting User Attributes The `delete()` method of the attributes service removes attributes from the specified user. When attributes are removed, both the name and the value of the attribute are removed, not only the value. There are two syntaxes, the following one is for deleting multiple attributes or all attributes at once. @@ -930,7 +1184,8 @@ session .attribute("attributeName") .delete(); ``` -####Viewing Organization Attributes + +### Viewing Organization Attributes The code below retrieves the list of attributes, if any, defined for the organization. ```java List attributes = session @@ -960,7 +1215,8 @@ HypermediaAttribute attributes = session .get() .getEntity(); ``` -####Setting Organization Attributes + +### Setting Organization Attributes Service allows you to create new organization attributes. See code below: ```java HypermediaAttributesListWrapper attributes = new HypermediaAttributesListWrapper(); @@ -993,7 +1249,8 @@ OperationResult retrieved = session .createOrUpdate(attribute); ``` Attribute name should not exist on the server and match with `name` field of `attribute` object, otherwise the attribute will be deleted. -####Deleting Organization Attributes + +### Deleting Organization Attributes You can also delete a single organization attribute. ```java OperationResult operationResult = session @@ -1010,7 +1267,8 @@ OperationResult operationResult = session .attributes("number_of_employees", "country_code") .delete(); ``` -####Viewing Server Attributes + +### Viewing Server Attributes We have also provided service to get server attributes. Code below return available server attributes. ```java List attributes = session @@ -1028,7 +1286,7 @@ HypermediaAttribute entity = session .get() .getEntity(); ``` -####Setting Server Attributes +### Setting Server Attributes It is possible to create new server attributes. ```java HypermediaAttributesListWrapper serverAttributes = new HypermediaAttributesListWrapper(); @@ -1059,7 +1317,8 @@ HypermediaAttribute attribute = new HypermediaAttribute(new ClientUserAttribute( .createOrUpdate(attribute); ``` Attribute name should not exist on the server and match with `name` field of `attribute` object, otherwise the attribute will be deleted. -####Deleting Server Attributes + +### Deleting Server Attributes You can also delete all server attribute. ```java session @@ -1082,7 +1341,8 @@ session .attributes("max_threads", "admin_cell_phone") .delete(); ``` -###Getting attributes permissions + +### Getting attributes permissions Since `6.1` version of `JaspersoftReportServer` you can obtain attributes with permissions using additional parameter `setIncludePermissions()`: ```java @@ -1094,7 +1354,8 @@ Since `6.1` version of `JaspersoftReportServer` you can obtain attributes with p .getEntity(); ``` Pay attention, the setting `setIncludePermission()` specify only the **server response format**, you can not set any permissions with this setting. -####Seasching Attributes + +### Seasching Attributes To get full list of attributes with specified parameters use the next code: ```java session @@ -1150,7 +1411,8 @@ To specify the holder you can use the existing API: .search(); HypermediaAttributesListWrapper attributes = operationResult.getEntity(); ``` -###Getting attributes permissions + +### Getting attributes permissions Since `6.1` version of `JaspersoftReportServer` you can obtain attributes with permissions using additional parameter `setIncludePermissions()`: ```java @@ -1163,9 +1425,11 @@ Since `6.1` version of `JaspersoftReportServer` you can obtain attributes with p ``` Pay attention, the setting `setIncludePermission()` specify only the **server response format**, you can not set any permissions with this setting. -###The Roles Service +The Roles Service +----------------- It provides similar methods that allow you to list, view, create, modify, and delete roles. The new service provides improved search functionality, including user-based role searches. Because the role ID is used in the URL, this service can operate only on roles whose ID is less than 100 characters long and does not contain spaces or special symbols. Unlike resource IDs, the role ID is the role name and can be modified. -####Searching for Roles + +### Searching for Roles The `allRoles()` method searches for and lists role definitions. It has options to search for roles by name or by user (`param()` method) that belong to the role. If no search is specified, it returns all roles. ```java @@ -1179,7 +1443,8 @@ OperationResult operationResult = RolesListWrapper rolesListWrapper = operationResult.getEntity(); ``` -####Viewing a Role + +### Viewing a Role The `rolename()` method with a role ID retrieves a single role descriptor containing the role properties. ```java OperationResult operationResult = @@ -1191,7 +1456,8 @@ OperationResult operationResult = ClientRole role = operationResult.getEntity(); ``` -####Creating a Role + +### Creating a Role To create a role, send the request via `createOrUpdate()` method to the roles service with the intended role ID (name) specified in the URL. Roles do not have any properties to specify other than the role ID, but the request must include a descriptor that can be empty. ```java @@ -1207,7 +1473,8 @@ OperationResult operationResult = Response response = operationResult.getResponse(); ``` -####Modifying a Role + +### Modifying a Role To change the name of a role, send a request via `createOrUpdate()` to the roles service and specify the new name in the role descriptor. The only property of a role that you can modify is the role’s name. After the update, all members of the role are members of the new role name, and all permissions associated with the old role name are updated to the new role name. ```java ClientRole roleHello = new ClientRole() @@ -1222,10 +1489,12 @@ OperationResult operationResult = Response response = operationResult.getResponse(); ``` -####Setting Role Membership + +### Setting Role Membership To assign role membership to a user, set the roles property on the user account with the PUT method of the rest_ v2/users service. For details, see section [creating a user](https://github.com/Jaspersoft/jrs-rest-java-client/blob/master/README.md#creating-a-user). -####Deleting a Role + +### Deleting a Role To delete a role, send the DELETE method and specify the role ID (name) in the URL. When this method is successful, the role is permanently deleted. ```java @@ -1237,12 +1506,12 @@ OperationResult operationResult = .delete(); Response response = operationResult.getResponse(); ``` -Settings Service -================ +Settings Service +---------------- It provides method that allow you to get server specific settings, required by UI to work with the server in sync. There can be formats and patterns, modes for some modules etc. -####Getting server specific settings +### Getting server specific settings To get settings, use the `getEntity()` method and specify the group of settings in the `group()` method and class of entity as shown below. The method `getEntity()` returns instance of specified class: ```java final Map settings = session @@ -1323,9 +1592,12 @@ OperationResult ofInputControlsGroup(); Repository Services ===================== -###Resources Service -This new service provides greater performance and more consistent handling of resource descriptors for all repository resource types. The service has two formats, one takes search parameters to find resources, the other takes a repository URI to access resource descriptors and file contents. -####Searching the Repository + +Resources Service +----------------- +This service provides greater performance and more consistent handling of resource descriptors for all repository resource types. The service has two formats, one takes search parameters to find resources, the other takes a repository URI to access resource descriptors and file contents. + +### Searching the Repository The resources service, when `resources()` method used without specifying any repository URI, is used to search the repository. The various parameters let you refine the search and specify how you receive search results. ```java OperationResult result = client @@ -1345,8 +1617,9 @@ OperationResult result = client ClientResourceListWrapper resourceListWrapper = result.getEntity(); ``` The response of a search is a set of shortened descriptors showing only the common attributes of each resource. One additional attribute specifies the type of the resource. This allows you to quickly receive a list of resources for display or further processing. -####Viewing Resource Details -Use the `resource()` method and a resource URI with `details()` method to request the resource's complete descriptor. + +### Viewing Resource Details +Use the `resource(uri)` method and a resource URI with `details()` method to request the file resource's complete descriptor. ```java OperationResult result = client .authenticate("jasperadmin", "jasperadmin") @@ -1354,7 +1627,17 @@ OperationResult result = client .resource("/properties/GlobalPropertiesList") .details(); ``` -####Downloading File Resources +To get details of resource with particular type, use `detailsForType(resourceClass)` method: +```java +OperationResult result = client + .authenticate("jasperadmin", "jasperadmin") + .resourcesService() + .resource("/properties/GlobalPropertiesList") + .detailsForType(); +``` + + +### Downloading File Resources There are two operations on file resources: * Viewing the file resource details to determine the file format * Downloading the binary file contents @@ -1371,34 +1654,83 @@ OperationResult result = client InputStream inputStream = result.getEntity(); ``` To get file MIME type yo can get `Content-Type` header from the `Response` instance. -####Creating a Resource -The `createNew()` and `createOrUpdate()` methods offer alternative ways to create resources. Both take a resource descriptor but each handles the URL differently. With the `createNew()` method, specify a folder in the URL, and the new resource ID is created automatically from the label attribute in its descriptor. With the `createOrUpdate()` method, specify a unique new resource ID as part of the URL in `resource()` method. -```java -ClientFolder folder = new ClientFolder(); -String parentUri = "/reports"; -folder - .setUri("/reports/testFolder") - .setLabel("Test Folder") - .setDescription("Test folder description") - .setPermissionMask(0) - .setCreationDate("2014-01-24 16:27:47") - .setUpdateDate("2014-01-24 16:27:47") - .setVersion(0); -OperationResult result = client - .authenticate("jasperadmin", "jasperadmin") - .resourcesService() - .resource(folder.getUri()) - .createOrUpdate(folder); +### Creating a Resource +The `create()` and `createOrUpdate()` methods offer two alternative ways to create resources. Both take a resource descriptor but each handles the URL differently and use different HTTP methods. With the `create()` method, specify a folder in the URL, and the new resource ID is created automatically from the label attribute in its descriptor in body of POST request. With the `createOrUpdate()` method, specify a unique new resource ID as part of the URL in `resource()` method and uses PUR method. +```java + ClientFolder new Folder = new ClientFolder(); + folder + .setLabel("testFolder") + .setDescription("Test folder"); + + final OperationResult operationResult = session + .resourcesService() + .resource(newFolder) + .inFolder("/public") + .create(); //OR -OperationResult result = client - .authenticate("jasperadmin", "jasperadmin") - .resourcesService() - .resource(parenUri) - .createNew(folder); -``` -####Modifying a Resource + ClientFolder folder = new ClientFolder(); + folder + .setUri("/public/testFolder1") + .setLabel("testFolder1") + .setDescription("Test folder") + .setVersion(-1); + + OperationResult operationResult = session + .resourcesService() + .resource(folder.getUri()) + .createOrUpdate(folder); +``` +#### Creating File resource +The REST client allows to create file resource in few ways: + - **as direct streaming** + ```java + ClientFile fileResourceDescriptor = new ClientFile() + .setLabel("testImage.jpg") + .setDescription("test description") + .setType(ClientFile.FileType.img); + OperationResult result = session + .resourcesService() + .fileResource(new FileInputStream(pathToFile), fileResourceDescriptor) + .asInputStream() + .inFolder("/public") + .create(); + ``` + - **as Base64** encoded content: + ```java + final ClientFile resourceDescriptor = new ClientFile().setLabel("testImage1.jpg") + .setDescription("test description") + .setType(ClientFile.FileType.img); + + OperationResult result = session + .resourcesService() + .fileResource(new FileInputStream(pathToFile), resourceDescriptor) + .asBase64EncodedContent() + .inFolder("/public") + .create(); + ``` + - **as multipart form** : + ```java + final ClientFile resourceDescriptor = new ClientFile() + .setLabel("testImage2.jpg") + .setDescription("test description") + .setType(ClientFile.FileType.img); + OperationResult result = session + .resourcesService() + .fileResource(new FileInputStream(pathToFile), + resourceDescriptor) + .asMultipartForm() + .inFolder("/public") + .create(); + ``` +### Modifying a Resource Use the `createOrUpdate()` method above to overwrite an entire resource. Specify the path of the target resource in the `resource()` method and specify resource of the same type. Use `parameter(ResourceServiceParameter.OVERWRITE, "true")` to replace a resource of a different type. The resource descriptor must completely describe the updated resource, not use individual fields. The descriptor must also use only references for nested resources, not other resources expanded inline. You can update the local resources using the hidden folder _file. +```java + OperationResult result = session + .resourcesService() + .resource(testResourceUri) + .createOrUpdate(testResource.setLabel("New test label").setDescription("new test description")); +``` The `patchResource()` method updates individual descriptor fields on the target resource. It also accept expressions that modify the descriptor in the Spring Expression Language. This expression language lets you easily modify the structure and values of descriptors. ```java PatchDescriptor patchDescriptor = new PatchDescriptor(); @@ -1412,83 +1744,289 @@ OperationResult result = client .patchResource(ClientFolder.class, patchDescriptor); ``` Note that you must explicitly set the type of resource to update because of server issue. -####Copying a Resource -To copy a resource, specify in `copyFrom()` method its URI and in `resource()` method URI of destination location. + +### Copying a Resource +To copy a resource, specify in `toFolder()` method its URI and in `resource()` method URI of destination location. ```java -OperationResult result = client - .authenticate("jasperadmin", "jasperadmin") - .resourcesService() - .resource("/reports") - .copyFrom("/datasources/testFolder"); + OperationResult clientResource = session.resourcesService() + .resource(testDomainUri) + .inFolder("/public/testFolder") + .copy(); ``` -####Moving a Resource + +### Moving a Resource To move a resource, specify in `moveFrom()` method its URI and in `resource()` method URI of destination location. ```java -OperationResult result = client - .authenticate("jasperadmin", "jasperadmin") - .resourcesService() - .resource("/datasources") - .moveFrom("/reports/testFolder"); -``` -####Uploading File Resources -To upload file you must specify the MIME type that corresponds with the desired file type, you can take it from `ClientFile.FileType` enumeration. + OperationResult clientResource = session.resourcesService() + .resource(testResourceUri) + .inFolder("/public/testFolder") + .move(); +``` +### Uploading complex resources +RestClient also provides API that allows to create complex resources and their nested resources in a single multipart request. Supported resources are: + - SemanticLayerDataSource; + - Domain; + - ReportUnit; + - MondrianConnection; + - SecureMondrianConnection. + +#### Uploading SemanticLayerDataSource +SemanticLayerDataSource nested resources (schema, bundles and security file) might be specified as java.io.InputStream, java.io.File, content as java.lang.String or resource descriptor (with resource's URI or BASE64 encoded content). +```java + OperationResult testResource = + session.resourcesService() + .semanticLayerDataSourceResource() + .withDataSource(new ClientReference().setUri(datasourceUri)) + .withSchema(schemaInputStream, schemaFilelabel, schemaFileDescription) + //OR .withSchema(schemaStringXmlContent, label, description) + //OR .withSchema(schemaUri) + .withSecurityFile(securityFileInputStream, label, description) + //OR .withSecurityFile(securityFile, label, description) + //OR .withSecurityFile(securityFileXmlStringCntent, label, description) + //OR .withSecurityFile(securityFileDecriptor) + .withBundle(bundleInputStream, label, description) + //OR .withBundle(bundleFile, label, description, locale) + //OR .withBundle(bundleSringContent, label, description, locale) + //OR .withBundle(bundleDescriptor) + //OR .withBundles(bundlesDescriptorsList) + .withLabel("testDomain") + .withDescription("testDescription") + .inFolder("/public") + .create(); +``` +The other way to create SemanticLayerDataSource is to decribe it in resourceDescriptor. In this case nested resources (schema, bundles and security file) can be specified as resource descriptors (with resource's URI or BASE64 encoded content). +```java + ClientSemanticLayerDataSource resourceDescriptor = new ClientSemanticLayerDataSource() + .setSchema(new ClientFile() + .setUri(schemaUri) + .setType(ClientFile.FileType.xml) + .setLabel("schema.Xml")) + .setDataSource(new ClientReference().setUri(domain.getDataSource().getUri())) + .setLabel("testDomain"); + + OperationResult testResource = + session.resourcesService() + .semanticLayerDataSourceResource(resourceDescriptor) + .inFolder("/public") + .create(); +``` +or +```java + ClientSemanticLayerDataSource resourceDescriptor = new ClientSemanticLayerDataSource() + .setDataSource(new ClientReference().setUri(domain.getDataSource().getUri())) + .setLabel("testDomain") + .setDescription("testDescription"); + OperationResult testResource = + session.resourcesService() + .semanticLayerDataSourceResource(resourceDescriptor) + .withSchema(schemaInputStream, schemaFilelabel, schemaFileDescription) + //OR .withSchema(schemaStringXmlContent, label, description) + //OR .withSchema(schemaUri) + .withSecurityFile(securityFileInputStream, label, description) + //OR .withSecurityFile(securityFile, label, description) + //OR .withSecurityFile(securityFileXmlStringCntent, label, description) + //OR .withSecurityFile(securityFileDecriptor) + .withBundle(bundleInputStream, label, description) + //OR .withBundle(bundleFile, label, description, locale) + //OR .withBundle(bundleSringContent, label, description, locale) + //OR .withBundle(bundleDescriptor) + //OR .withBundles(bundlesDescriptorsList) + .inFolder("/public") + .create(); +``` + +#### Uploading MondrianConnection +REST Client allows you to create `MondrianConnection` resource with mondrian schema XML file specified as java.io.InputStream, java.io.File or as java.lang.String. + ```java -OperationResult result = client - .authenticate("jasperadmin", "jasperadmin") - .resourcesService() - .resource("/reports/testFolder") - .uploadFile(imageFile, ClientFile.FileType.img, "fileName", "fileDescription"); + ClientMondrianConnection connection = session + .resourcesService() + .mondrianConnection() + .withMondrianSchema(schemaInputStream, label, description) + //OR .withMondrianSchema(schemaFile, label, description) + //OR .withMondrianSchema(schemaXmlStringContent, label, description) + .withDatasource(dataSource) + .withLabel(label) + .withDescription(description) + .inFolder(parentFolderUri) + .create() +``` +or +```java +ClientMondrianConnection resourceDescriptor = new ClientMondrianConnection() + .setDatasource(dataSource) + .setLabel(label) + .setDescription(description) + ClientMondrianConnection connection = session + .resourcesService() + .mondrianConnection(resourceDescriptor) + .withMondrianSchema(schemaInputStream, label, description) + //OR .withMondrianSchema(schemaFile, label, description) + //OR .withMondrianSchema(schemaXmlStringContent, label, description) + .inFolder(parentFolderUri) + .create() +``` +or create `MondrianConnection` using resource descriptor: +```java + ClientMondrianConnection connection = session + .resourcesService() + .mondrianConnection(respurceDescriptor) + .inFolder(parentFolder) + .create() +``` + +#### Uploading SecureMondrianConnection +REST Client allows you to create `MondrianConnection` resource with mondrian schema XML and AccessGrantSchemas specified as java.io.InputStream, java.io.File or as java.lang.String. + +```java + ClientMondrianConnection connection = session + .resourcesService() + .secureMondrianConnection() + . withMondrianSchema(schemainputStream, label, description) + //OR .withMondrianSchema(schemaFile, label, description) + //OR .withMondrianSchema(schemaXmlStringContent, label, description) + .withDatasource(dataSource) + .withLabel(label) + .withDescription(description) + .inFolder(parentFolderUri) + .create() +``` +or +```java + ClientMondrianConnection resourceDescriptor = new ClientMondrianConnection() + .setDatasource(dataSource) + .setLabel(label) + .setDescription(description) + ClientMondrianConnection connection = session + .resourcesService() + .secureMondrianConnection(respurceDescriptor) + . withMondrianSchema(schemainputStream, label, description) + //OR .withMondrianSchema(schemaFile, label, description) + //OR .withMondrianSchema(schemaXmlStringContent, label, description) + .withDatasource(dataSource) + .withLabel(label) + .withDescription(description) + .inFolder(parentFolderUri) + .create() +``` +or create `MondrianConnection` using resource descriptor: +```java + ClientMondrianConnection connection = session + .resourcesService() + .secureMondrianConnection(respurceDescriptor) + .inFolder(parentFolder) + .create() +``` + +#### Uploading ReportUnit +To upload `ReportUnit` resource to the server you can use next API, where JRXML file can be added as java.lang.String, java.io.File, java.io.InputStream or as resource URI in resource descriptor. A bunch of various additional files like images and others can be added as well. +```java + OperationResult repUnut = + session.resourcesService() + .reportUnitResource() + .withJrxml(inputStream, label, description) + //OR .withJrxml(jrxmlStringContent, label, description) + //OR .withJrxml(jrxmlFile, label, description) + //OR .withJrxml(resourceDescriptor) + .withFile(new ClientReference().setUri(fileUri), label, fileType) + .withFile(new ClientReference().setUri(fileUri), label, fileType) + //OR .withFile(InputStream fileData, String label, String description, fileType) + //OR .withFile(File fileData, String label, String description, fileType) + //OR .withFile(String fileData, String label, String description, fileType) + //OR .withFile(ClientReferenceableFile fileUri, String name, fileType) + .withLabel("testReport") + .withDescription("testDescription") + .inFolder("/public") + .create(); +``` +or +```java + ClientReportUnit resourceDescriptor = new ClientReportUnit() + .setLabel("testReport") + .setDescription("testDescription"); + + OperationResult repUnut = + session.resourcesService() + .reportUnitResource(resourceDescriptor) + .withJrxml(inputStream, label, description) + //OR .withJrxml(jrxmlStringContent, label, description) + //OR .withJrxml(jrxmlFile, label, description) + //OR .withJrxml(resourceDescriptor) + .withFile(new ClientReference().setUri(fileUri), label, fileType) + .withFile(new ClientReference().setUri(fileUri), label, fileType) + //OR .withFile(InputStream fileData, String label, String description, fileType) + //OR .withFile(File fileData, String label, String description, fileType) + //OR .withFile(String fileData, String label, String description, fileType) + //OR .withFile(ClientReferenceableFile fileUri, String name, fileType) + .inFolder("/public") + .create(); +``` +Also the API allows to upload reportUnit described in resource descriptor only: +```java + final ClientReportUnit clientReportUnit = new ClientReportUnit() + .setLabel("testReport") + .setDescription("testDescription"); + clientReportUnit.setFiles(new HashMap()); + clientReportUnit.getFiles().put(label, new ClientFile() + .setUri(fileUri) + .setLabel(label) + .setType(ClientFile.FileType.img)); + + clientReportUnit.setJrxml(new ClientFile() + .setLabel(jrxmlLabel) + .setType(ClientFile.FileType.jrxml) + .setContent(base64EncodedContent); + + OperationResult repUnut = + session.resourcesService() + .reportUnitResource(clientReportUnit) + .inFolder("/public") + .create(); +``` +#### Uploading domain +Domain's its nested resources (bundles and security file) might be specified as java.io.InputStream, java.io.File, content as java.lang.String or resource descriptor (with resource's URI or BASE64 encoded content). +Please, pay attention, unlike SemanticLayerDataSource the Domain resource doesn't reference external schema file, so schema can be specified only as Java object. +```java + OperationResult resDomain = + session.resourcesService() + .domainResource() + .withDataSource(new ClientReference().setUri(datasourceUri)) + .withSchema(schemaObject) + .withLabel("testDomain") + .withDescription("testDescription") + .inFolder("/public") + .create(); + ``` -####Uploading SemanticLayerDataSource -RestClient also supports a way to create complex resources and their nested resources in a single multipart request. One of such resources is `SemanticLayerDataSource`. +or +```java + ClientDomain resourceDescriptor = new ClientDomain () + .setDataSource(new ClientReference().setUri(datasourceUri)) + .setSchema(schemaObject) + .setLabel("testDomain") + .setDescription("testDescription") + OperationResult resDomain = + session.resourcesService() + .domainResource() + .withSchema(schemaObject) + .inFolder("/public") + .create(); + +``` +The other way to create SemanticLayerDataSource is to decribe it in resourceDescriptor. In this case nested resources (schema, bundles and security file) can be specified as resource descriptors (with resource's URI or BASE64 encoded content). ```java -ClientSemanticLayerDataSource domainEntity = session - .resourcesService() - .resource(domain) - .withBundle(defBundle, newDefaultBundle) - .withBundle(enUSBundle, newEnUsBundle) - .withSecurityFile(securityFile, securityFile) - .withSchema(schemaFile, schema) - .inFolder("/my/new/folder/") - .create() - .entity(); -``` -####Uploading MondrianConnection -REST Client allows you to create `MondrianConnection` Resource with mondrian schema XML file. You can specify the folder in which the resource will be placed. Provided API allows to add XML schema as `String` or `InputStream`. -```java -ClientMondrianConnection connection = session - .resourcesService() - .resource(mondrianConnection) - .withMondrianSchema(schema, schemaRef) - .createInFolder("my/olap/folder") - .entity(); -``` -####Uploading SecureMondrianConnection -To upload `SecureMondrianConnection` Resource with a bunch of support files such as Mondrian schema XML file and AccessGrantSchemas files you can use our new API -```java -ClientSecureMondrianConnection entity = session.resourcesService() - .resource(secureMondrianConnection) - .withMondrianSchema(mondrianSchema) - .withAccessGrantSchemas(Arrays.asList(accessGrantSchema)) - .createInFolder("/my/new/folder/") - .entity(); -``` -####Uploading ReportUnit -To upload `ReportUnit` resource to the server you can use next API, which allows you to do it in a very simple way. You can add JRXML file and a bunch of various files like images and others as well. -```java -ClientReportUnit entity = session.resourcesService() - .resource(reportUnit) - .withJrxml(file, descriptor) - .withNewFile(imgFile, "myFile", imgDescriptor) - .createInFolder("/my/new/folder/") - .entity(); -``` -####Deleting Resources + ClientDomain resDomain = + session.resourcesService() + .domainResource(domain) + .inFolder("/public") + .create() +``` + +### Deleting Resources You can delete resources in two ways, one for single resources and one for multiple resources. To delete multiple resources at once, specify multiple URIs with the `ResourceSearchParameter.RESOURCE_URI` parameter. ```java //multiple -OperationResult result = client - .authenticate("jasperadmin", "jasperadmin") +OperationResult result = session .resourcesService() .resources() .parameter(ResourceSearchParameter.RESOURCE_URI, "/some/resource/uri/1") @@ -1496,104 +2034,108 @@ OperationResult result = client .delete(); //OR //single -OperationResult result = client - .authenticate("jasperadmin", "jasperadmin") +OperationResult result = session .resourcesService() .resource("/reports/testFolder") .delete(); ``` -###The Permissions Service + +The Permissions Service +----------------------- In the permissions service, the syntax is expanded so that you can specify the resource, the recipient (user name or role name) and the permission value within the URL. This makes it simpler to set permissions because you don’t need to send a resource descriptor to describe the permissions. In order to set, modify, or delete permissions, you must use credentials or login with a user that has “administer” permissions on the target resource. Because a permission can apply to either a user or a role, the permissions service uses the concept of a “recipient”. A recipient specifies whether the permission applies to a user or a role, and gives the ID of the user or role. There are two qualities of a permission: * The assigned permission is one that is set explicitly for a given resource and a given user or role. Not all permissions are assigned, in which case the permission is inherited from the parent folder. * The effective permission is the permission that is being enforced, whether it is assigned or inherited. -####Viewing Multiple Permissions - +### Viewing Multiple Permissions ```java -OperationResult operationResult = - client - .authenticate("jasperadmin", "jasperadmin") + OperationResult operationResult = session .permissionsService() - .resource("/datasources") + .forResource(RESOURCE_URI) + .permissions() .get(); ``` -####Viewing a Single Permission +Also serch permissions with parameters is supported. Available parameters are: + **effectivePermissions** - when set to true shows all permissions who affect given uri, if false - only directly assigned. If recipient does not have any permission assigned or permission is not reacheable not uri will be returned. Default - false; + **recipientType** - type of recipient (e.g. user/role); + **recipientId** - Id of recipient, requires `recipientType`. For multitenant environment should be tenant qualified. + **resolveAll** - describes resolving of recipients. Default - false; + **offset** - pagination. Start index for requested pate; + **limit** - pagination, resources count per page; + +### Viewing a Single Permission Specify the recipient in the URL to see a specific assigned permission. ```java -OperationResult operationResult = - client - .authenticate("jasperadmin", "jasperadmin") + OperationResult operationResult = session .permissionsService() - .resource("/datasources") + .forResource(RESOURCE_URI) + .permission() .permissionRecipient(PermissionRecipient.ROLE, "ROLE_USER") .get(); RepositoryPermission permission = operationResult.getEntity(); ``` -####Setting Multiple Permissions -The `createNew()` method assigns any number of permissions to any number of resources specified in the body of the request. All permissions must be newly assigned, and the request will fail if a recipient already has an assigned (not inherited) permission. Use the `createOrUpdate()` method to update assigned permissions. The `createOrUpdate()` method modifies exiting permissions (already assigned). -```java -List permissionList = new ArrayList(); -permissionList.add(new RepositoryPermission("/themes", "user:/joeuser", 30)); -RepositoryPermissionListWrapper permissionListWrapper = new RepositoryPermissionListWrapper(permissionList); +### Setting Multiple Permissions +The `create()` method assigns any number of permissions to any number of resources specified in the body of the request. All permissions must be newly assigned, and the request will fail if a recipient already has an assigned (not inherited) permission. Use the `createOrUpdate()` method to update assigned permissions. The `createOrUpdate()` method modifies exiting permissions (already assigned). +```java + RepositoryPermissionListWrapper permissions = new RepositoryPermissionListWrapper(); + final RepositoryPermission repositoryPermission = new RepositoryPermission().setUri(RESOURCE_URI).setRecipient("role:/ROLE_USER").setMask(1); + final RepositoryPermission repositoryPermission1 = new RepositoryPermission().setUri(RESOURCE_URI).setRecipient("role:/ROLE_ADMIN").setMask(1); + permissions.setPermissions(asList(repositoryPermission, repositoryPermission1)); -OperationResult operationResult = - client - .authenticate("jasperadmin", "jasperadmin") + OperationResult operationResult = session .permissionsService() - .createNew(permissionListWrapper); - -Response response = operationResult.getResponse(); + .permissions(permissions) + .create(); ``` -####Setting a Single Permission + +### Setting a Single Permission The `createNew()` method accepts a single permission descriptor. ```java -RepositoryPermission permission = new RepositoryPermission(); -permission - .setUri("/") - .setRecipient("user:/joeuser") - .setMask(PermissionMask.READ_WRITE_DELETE); + final RepositoryPermission repositoryPermission = new RepositoryPermission() + .setUri(RESOURCE_URI) + .setRecipient("role:/ROLE_USER") + .setMask(1); -OperationResult operationResult = - client - .authenticate("jasperadmin", "jasperadmin") + OperationResult operationResult = session .permissionsService() - .createNew(permission); - -Response response = operationResult.getResponse(); + .permission(repositoryPermission) + .create(); ``` -####Deleting Permissions in Bulk + +### Deleting Permissions in Bulk The `delete()` method removes all assigned permissions from the designated resource. After returning successfully, all effective permissions for the resource are inherited. ```java -OperationResult operationResult = - client - .authenticate("jasperadmin", "jasperadmin") + OperationResult operationResult = session .permissionsService() - .resource("/themes") + .forResource(RESOURCE_URI) + .permissions() .delete(); - -Response response = operationResult.getResponse(); ``` -####Deleting a Single Permission + +### Deleting a Single Permission Specify a recipient in the `permissionRecipient()` method and call the `delete()` method to remove only that permission. ```java OperationResult operationResult = client .authenticate("jasperadmin", "jasperadmin") .permissionsService() - .resource("/") + .forResource(RESOURCE_URI) + .permission() .permissionRecipient(PermissionRecipient.USER, "joeuser") .delete(); Response response = operationResult.getResponse(); ``` + Jobs service ================== The jobs service provides the interface to schedule reports and manage scheduled reports (also called jobs). In addition, this service provides an API to scheduler features that were introduced in JasperReports Server 4.7, such as bulk updates, pausing jobs, FTP output and exclusion calendars. -####Listing Report Jobs + +Listing Report Jobs +------------------- Use the following method to list all jobs managed by the scheduler. ```java OperationResult result = client @@ -1605,7 +2147,9 @@ OperationResult result = client JobSummaryListWrapper jobSummaryListWrapper = result.getEntity(); ``` The jobs are described in the `JobSummary` element. -####Viewing a Job Definition + +Viewing a Job Definition +------------------------ The following piece of code with a specific job ID specified in `job()` method retrieves the detailed information about that scheduled job. ```java OperationResult result = client @@ -1617,7 +2161,9 @@ OperationResult result = client Job job = result.getEntity(); ``` This code returns a job element that gives the output, scheduling, and parameter details, if any, for the job. -####Extended Job Search + +Extended Job Search +------------------- The `search()` method is used for more advanced job searches. Some field of the jobsummary descriptor can be used directly as parameters, and fields of the job descriptor can also be used as search criteria. You can also control the pagination and sorting order of the reply. ```java Job criteria = new Job); @@ -1643,7 +2189,9 @@ JobExtension criteria = new JobExtension(); criteria.setOutputFormats(wrapper); ``` Currently the code is a little bit littered, in futere versions it will be eliminated. -####Scheduling a Report + +Scheduling a Report +------------------- To schedule a report, create its job descriptor similar to the one returned by the `job(id).get();` method, and use the `scheduleReport()` method of the jobs service. Specify the report being scheduled inside the job descriptor. You do not need to specify any job IDs in the descriptor, because the server will assign them. ```java job.setLabel("NewScheduledReport"); @@ -1659,19 +2207,23 @@ OperationResult result = client job = result.getEntity(); ``` The body contains the job descriptor of the newly created job. It is similar to the one that was sent but now contains the jobID for the new job. -####Viewing Job Status + +Viewing Job Status +------------------ The following method returns the current runtime state of a job: ```java OperationResult result = client .authenticate("jasperadmin", "jasperadmin") .jobsService() .job(8600) - .state(); + .jobState(); JobState jobState = result.getEntity(); ``` Response contains the `JobState` status descriptor. -####Editing a Job Definition + +Editing a Job Definition +------------------------ To modify an existing job definition, use the `job(id).get()` method to read its job descriptor, modify the descriptor as required, and use the `update()` method of the jobs service. The `update()` method replaces the definition of the job with the given job ID. ```java String label = "updatedLabel"; @@ -1686,7 +2238,9 @@ OperationResult result = client Job job = result.getEntity(); ``` -####Updating Jobs in Bulk + +Updating Jobs in Bulk +--------------------- To update several jobs at once you should specify jobs IDs as parameters, and send a descriptor with filled fields to update. ```java Job jobDescriptor = new Job(); @@ -1701,7 +2255,9 @@ OperationResult result = client .update(jobDescriptor); ``` The code above will update the `description` field of jobs with IDs `8600` and `8601`. -####Pausing Jobs + +Pausing Jobs +------------ The following method pauses currently scheduled job execution. Pausing keeps the job schedule and all other details but prevents the job from running. It does not delete the job. ```java OperationResult result = client @@ -1709,9 +2265,11 @@ OperationResult result = client .jobsService() .jobs() .parameter(JobsParameter.JOB_ID, "8600") - .pause(); + .pauseJobs(); ``` -####Resuming Jobs + +Resuming Jobs +------------- Use the following method to resume any or all paused jobs in the scheduler. Resuming a job means that any defined trigger in the schedule that occurs after the time it is resumed will cause the report to run again. Missed schedule triggers that occur before the job is resumed are never run. ```java OperationResult result = client @@ -1719,9 +2277,11 @@ OperationResult result = client .jobsService() .jobs() .parameter(JobsParameter.JOB_ID, "8600") - .resume(); + .resumeJobs(); ``` -####Restarting Failed Jobs + +Restarting Failed Jobs +---------------------- Use the following method to rerun failed jobs in the scheduler. For each job to be restarted, the scheduler creates an immediate single-run copy of job, to replace the one that failed. Therefore, all jobs listed in the request body will run once immediately after issuing this command. The single-run copies have a misfire policy set so that they do not trigger any further failures (`MISFIRE_ INSTRUCTION_IGNORE_MISFIRE_POLICY`). If the single-run copies fail themselves, no further attempts are made automatically. ```java OperationResult result = client @@ -1729,33 +2289,41 @@ OperationResult result = client .jobsService() .jobs() .parameter(JobsParameter.JOB_ID, "8600") - .restart(); + .restarJobs(); ``` -###Calendars service + +Calendars service +================= The scheduler allows a job to be defined with a list of excluded days or times when you do not want the job to run. For example, if you have a report scheduled to run every business day, you want to exclude holidays that change every year. The list for excluded days and times is defined as a calendar, and there are various ways to define the calendar. The scheduler stores any number of exclusion calendars that you can reference by name. When scheduling a report, reference the name of the calendar to exclude, and the scheduler automatically calculates the correct days to trigger the report. The scheduler also allows you to update an exclusion calendar and update all of the report jobs that used it. Therefore, you can update the calendar of excluded holidays every year and not need to modify any report jobs. -####Listing All Registered Calendar Names + +Listing All Registered Calendar Names +------------------------------------- The following method returns the list of all calendar names that were added to the scheduler. ```java OperationResult result = client .authenticate("jasperadmin", "jasperadmin") .jobsService() - .calendars(); //OR .calendars(CalendarType.HOLIDAY); //to specify the desired calendar type + .allCalendars(); CalendarNameListWrapper calendarNameListWrapper = result.getEntity(); ``` -####Viewing an Exclusion Calendar + +Viewing an Exclusion Calendar +----------------------------- The following method takes the name of an exclusion calendar and returns the definition of the calendar: ```java OperationResult result = client .authenticate("jasperadmin", "jasperadmin") .jobsService() .calendar("testCalendar") - .get(); + .getCalendar(); Calendar jobCalendar = result.getEntity(); ``` As a result we have common caledar descriptor `ReportJobCalendar`. -####Adding or Updating an Exclusion Calendar + +Adding or Updating an Exclusion Calendar +---------------------------------------- This method creates a named exclusion calendar that you can use when scheduling reports. If the calendar already exists, you have the option of replacing it and updating all the jobs that used it. ```java WeeklyCalendar calendar = new WeeklyCalendar(); @@ -1770,7 +2338,9 @@ OperationResult result = client .createOrUpdate(calendar); ``` Unlike common `ReportJobCalendar` which we receive as result of GET operation here we need create the calendar instance of desired type and path it to the `createOrUpdate()` method. -####Deleting an Exclusion Calendar + +Deleting an Exclusion Calendar +------------------------------ Use the following method to delete a calendar by name. ```java OperationResult result = client @@ -1781,7 +2351,11 @@ OperationResult result = client ``` Import/Export ============= -###Export service + +Export service +-------------- + +### Strat export The export service works asynchronously: first you request the export with the desired options, then you monitor the state of the export, and finally you request the output file. You must be authenticated as the system admin (superuser)or jasperadmin for the export services. ```java OperationResult operationResult = @@ -1795,7 +2369,7 @@ OperationResult operationResult = .create(); State state = operationResult.getEntity(); - +``` The export parameters you can specify are: `everything `- export everything except audit data: all repository resources, permissions, report jobs, users, and roles. This option is equivalent to:--uris --repository-permissions --report-jobs --users --roles @@ -1820,8 +2394,8 @@ The export parameters you can specify are: `skip-suborganizations `- if the parameter is set to true, the system will omit all the items(e.g. resources, user, roles, organizations) which belong to "sub organizations" even they are directly specified using corresponding options (default value is false). `skip-dependent-resources `- skip dependent resources (domain, datasource etc.) to be exported (default value is false). -//TODO task -Also you can specify: + +In sent tas DTO you can specify: `uris` - list of folder or resource URIs in the repository to export. `scheduledJobs` - list of repository report unit and folder URIs for which report unit jobs should be exported. For a folder URI, this option exports the scheduled jobs of all reports in the folder and all subfolders. `roles` - list of roles to export. @@ -1830,53 +2404,73 @@ Also you can specify: `organization` - identifier of organization to export together with its sub organizations. If it is specified it also will be the root organization, starting from it system will export all resources, users, roles e.t.c. ```java + ExportTask exportTask = new ExportTask() + .setUris(asList(TEST_URI)) + .setUsers(asList("superuser")) + .setRoles(asList("ROLE_USER")); OperationResult stateOperationResult = session .exportService() - .newTask() - .uri("/temp/supermartDomain") - .user("jasperadmin") - .role("ROLE_USER") - .resourceTypes(asList("jdbcDataSource", "reportUnit", "file")) - .parameter(ExportParameter.EVERYTHING) + .newTask(exportTask) .create(); + + State stateDto = stateOperationResult.getEntity(); + taskId = stateDto.getId(); ``` -``` -####Checking the Export State + +### Check the export state After receiving the export ID, you can check the state of the export operation. ```java -OperationResult operationResult = - client - .authenticate("jasperadmin", "jasperadmin") + OperationResult stateOperationResult = session .exportService() - .task(state.getId()) + .task(taskId) .state(); -State state = operationResult.getEntity(); + State stateOperationResult = operationResult.getEntity(); ``` The body of the response contains the current state of the export operation. -####Fetching the Export Output + +### Fetching the export output When the export state is ready, you can download the zip file containing the export catalog. ```java -OperationResult operationResult1 = - client - .authenticate("jasperadmin", "jasperadmin") + String state = "inprogres"; + while (!"finished".equals(state)) { + state = session.exportService().task(taskId).state().getEntity().getPhase(); + try { + Thread.sleep(1000); + } catch (InterruptedException ignored) { + + } + } + + OperationResult operationResult = session .exportService() - .task(state.getId()) - .fetch(); + .task(taskId) + .fetchToFile("export.zip"); -InputStream inputStream = operationResult1.getEntity(); + InputStream inputStream = operationResult.getEntity(); ``` -###Import service +Please, pay attention, only export with "finished" state can be fetched. + +### Cancel the export task +Only `stateDto.getPhase() = "inprogress"` export can be cancelled: +```java + OperationResult OperationResult = session + .exportService() + .task(taskId) + .cancel(); +``` + +Import service +-------------- +### Strat import Use the following service to upload a catalog as a zip file and import it with the given options. Specify options as arguments from `com.jaspersoft.jasperserver.jaxrs.client.apiadapters.importexport.importservice.ImportParameter`. Arguments that are omitted are assumed to be false. You must be authenticated as the system admin (superuser) or jasperadmin for the import service. Jaspersoft does not recommend uploading files greater than 2 gigabytes. ```java -URL url = ImportService.class.getClassLoader().getResource("testExportArchive.zip"); -OperationResult operationResult = - client - .authenticate("jasperadmin", "jasperadmin") + OperationResult operationResult = session .importService() - .newTask() - .parameter(ImportParameter.INCLUDE_ACCESS_EVENTS, true) - .create(new File(url.toURI())); + .newImport(pathToFile) + .parameter(ImportParameter.UPDATE, true) + .create(); + State state = operationResult.getEntity(); ``` @@ -1888,46 +2482,39 @@ Available parameters are: `includeMonitoringEvents` - include monitoring events (default value is false). `includeServerSettings` - include server settings (default value is false). `mergeOrganization` - allows merging of exported organization/resource into organization with different identifier. In the case if it is false, then system will throw an exception, if exportedOrganizationId != organizationId_we_import_Into (default value is false). -`brokenDependencies` - defines strategy with broken dependencies. Available values are - fail, skip, include (default value is fail). - -Also you can set: `brokenDependencies` - defines strategy with broken dependencies. Available values are: - - fail - server will give an error (errorCode=import.broken.dependencies) if import archive contain broken dependent resources. - skip - import will skip from import broken resources. + fail - server will give an error (errorCode=import.broken.dependencies) if import archive contain broken dependent resources. + skip - import will skip from import broken resources. include - import will proceed with broken dependencies. In this case server will try to import broken dependent resources. a) In the case when in target environment there are already dependent resources import of target resource will be success, and resource will be skipped from import if there are no dependent resources to recover dependency chain. -`parameters` - list of import parameters. `organization` - organization identifier we import into. -```java +#### Import using mulpipart form +```java + State state = session + .importService() + .newMultiPartImport(new File(pathToFile)) + .parameter(ImportParameter.UPDATE, true) + .create() + .getEntity(); ``` -####Checking the Import State + +### Check the Import State After receiving the import ID, you can check the state of the import operation. ```java -OperationResult operationResult = - client - .authenticate("jasperadmin", "jasperadmin") + OperationResult operationResult = session .importService() - .task(state.getId()) + .task(taskId) .state(); -State state = operationResult.getEntity(); + State stateDto = operationResult.getEntity(); ``` -####Getting and restarting import task +### Getting and restarting import task To get import task metadata you can use next code example: ```java - OperationResult operationResult = session - .importService() - .newTask() - .parameter(ImportParameter.INCLUDE_ACCESS_EVENTS, true) - .parameter(ImportParameter.UPDATE, true) - .create(new File("\\import.zip")); - State state = operationResult.getEntity(); - ImportTask task = session .importService() - .task(state.getId()) + .task(taskId) .getTask() .getEntity(); ``` @@ -1939,9 +2526,31 @@ Also you can restart import task: .restartTask(new ImportTask().setBrokenDependencies("false")) .getEntity(); ``` +Notice, only task in phase "pending" can be restarted. Pending will happen if import task failed with error codes: import.organizations.not.match or import.broken.dependencies. + +### Check import state +```java + OperationResult operationResult = session + .importService() + .task(taskId) + .state(); + + State state = operationResult.getEntity(); +``` + +### Cancel import task +```java + OperationResult operationResult = session + .importService() + .task(taskId) + .cancel(); +``` +Metadata +======== -####DomainMetadata Service -The DomainMetadata Service gives access to the sets and items exposed by a Domain for use in Ad +Domain Metadata +--------------- +The domain metadata describes the sets and items exposed by a Domain for use in Ad Hoc reports. Items are database fields exposed by the Domain, after all joins, filters, and calculated fields have been applied to the database tables selected in the Domain. Sets are groups of items, arranged by the Domain creator for use by report creators. @@ -1952,12 +2561,62 @@ Domain. Fields that belong to tables that are not joined in the Domain belong to The following code retrieves metadata of Domain. ```java -DomainMetaData domainMetaData = session.domainService() - .domainMetadata("/Foodmart_Sales") - .retrieve() - .getEntity(); +// create domain context by Id of context + ClientSemanticLayerDataSource domainContext = new ClientSemanticLayerDataSource(). + setUri("/organizations/organization_1/Domains/Simple_Domain"); + OperationResult operationResult = session + .dataDiscoveryService() + .domainContext() + .create(domainContext); +// get uuId of context from "Location" header of response +// get metadata of domain bi uuId of context + OperationResult operationResult = session + .dataDiscoveryService() + .domainContext() + .fetchMetadataById(uuId); + +// or you can get metadata by context directly + + OperationResult operationResult = session + .dataDiscoveryService() + .domainContext() + .fetchMetadataByContext(domainContext); + + DataIslandsContainer metadata = operationResult.getEntity(); +``` + +Report Metadata +--------------- +Report metadata is used for building AdHoc and query accordingly. +To get metadata use next code example: +```java +// create domain context by Id of context +ClientReportUnit reportUnit = new ClientReportUnit().setUri("/public/Samples/Domains/supermartDomain"); + + OperationResult operationResult = session + .dataDiscoveryService() + .topicContext() + .create(reportUnit); +// get uuId of context from "Location" header of response +// get metadata of domain bi uuId of context + OperationResult operationResult = session + .dataDiscoveryService() + .topicContext() + .fetchMetadataById(uuId); + ResourceGroupElement metadata = operationResult.getEntity(); + +// or you can get metadata by context directly + + OperationResult operationResult = session + .dataDiscoveryService() + .topicContext() + .fetchMetadataByContext(reportUnit); + + ResourceGroupElement metadata = operationResult.getEntity(); ``` -####Thumbnail Search Service + +Thumbnail Search Service +======================== This service is used for requesting a thumbnail image of an existing resource. You can get a single resource. See code below. ```java InputStream entity = session.thumbnailsService() @@ -1989,11 +2648,11 @@ List entity = session.thumbnailsService() .get() .getEntity() .getThumbnails(); - ``` +``` Please notice that ResourceThumbnail class (DTO) contains the content in Base64 string format (not InputStream). -###Diagnostic Service - +Diagnostic Service +================== The service is used to create, update, stop log collectors and get logs and data snapshots. To create log collector use the code below: ```java @@ -2098,19 +2757,295 @@ OperationResult operationResult = session .delete(); ``` -###Query Executor Service -In addition to running reports, JasperReports Server exposes queries that you can run through the QueryExecutor service. -For now the only resource that supports queries is a Domain. +Contexts Service +================ +Using the service you are able to keep some state or context on the server and execute some actions on this state. General service have next API: +- save context: +```java + OperationResult operationResult = session + .contextService() + .context(contextClass, contextMimeType) + .create(context); +``` +Response header `"Content-Location"`contains contextUuid. -The following code executes query and retrieves a result of execution as QueryResult entity. +- get context: ```java -QueryResult queryResult = session.queryExecutorService() - .query(queryFromXmlFile, "/organizations/organization_1/Domains/Simple_Domain") - .execute() - .getEntity(); + OperationResult operationResult = session + .contextService() + .context(contextClass, contextMimeType, uuId) + .get(context); +``` + +- modify context: +```java + OperationResult operationResult = session + .contextService() + .context(contextClass, contextMimeType, uuId) + .update(context); +``` +- delete context: +```java + OperationResult operationResult = session + .contextService() + .context(uuId) + .delete(); +``` +- get context metadata: +```java + OperationResult operationResult = session + .contextService() + .context(uuId, contextMatadataClass, contextMetadataMimeType) + .metadata(); + +// get context metadata with paramerets + OperationResult operationResult = session + .contextService() + .context(uuId, contextMatadataClass, contextMetadataMimeType) + .addParameter("expand", "public.accounts") + .addParameter("", "") + .metadata(); + + OperationResult operationResult = session + .contextService() + .context(uuId, contextMatadataClass, contextMetadataMimeType) + .addParameter("include", "public.currency") + .metadata(); + + // or + OperationResult operationResult = session + .contextService() + .context(uuId, contextMatadataClass, contextMetadataMimeType) + .addParameter("expands", "public.account") + .addParameter("expands", "public.category") + .partialMetadata(); + + OperationResult operationResult = session + .contextService() + .context(uuId, contextMatadataClass, contextMetadataMimeType) + .addParameter("includes", "public.currency") + .partialMetadata(); +``` +The difference between `.metadata()` and `.partialMetadata()` is in HTTP methods and a way to pass parameters: +`.metadata()` - sends GET request and parameters as URL query parameters; +`.partialMetadata()` - sends POST request and parameters as JSON; + +- create context and get context metadata: +```java + OperationResult operationResult = session + .contextService() + .context(contextClass, contextMimeType,contextMatadataClass, contextMetadataMimeType) + .createAndGetMetadata(context); +``` + +Domain Context Service +---------------------- +This service allows to execute query of in-memory domain. I.e. domain, that doesn't exist in repository. +- to create context: +```java + OperationResult operationResult = session + .domainContextService() + .context(context) + .create(); +``` +`context` here might be instance of ClientDomain or ClientSemanticLayerDataSource with data source URI and domain schema URI of datasource. +- to get domain metadata: +```java + + OperationResult operationResult = session + .domainContextService() + .context(context) + .create().getMetadata(); + // or expznded metadata + OperationResult operationResult = session + .domainContextService() + .context(context) + .create() + .addParam("expand", nodeName) + .getMetadata(); +``` +- to execute query (only multi level queries are supported): +```java + ClientMultiLevelQuery clientMultiLevelQuery = new ClientMultiLevelQuery().setGroupBy( + new ClientQueryGroupBy().setGroups( + asList(new ClientQueryGroup(). + setId("account_type"). + setFieldName("account_type")))); + OperationResult operationResult = session + .domainContextService() + .context(clientDomain) + .create().executeQuery(clientMultiLevelQuery); +``` + +Data Discovery Service +====================== +The service based on Context Service and allows to work with supported contexts(Domain, DomEl, reports etc) directly. + +Domain data discovery +--------------------- +This API allows to execute query of in-memory domain. I.e. domain, that doesn't exist in repository. + +```java + private String uuId; // available in Content-Location header in responce + private ClientDomain domainContext = new ClientDomain().setUri("/public/Samples/Domains/supermartDomain"); + +// create context + OperationResult operationResult = session + .dataDiscoveryService() + .domainContext() + .create(domainContext); +// get context metadata + OperationResult operationResult = session + .dataDiscoveryService() + .domainContext() + .fetchMetadataById(uuId); +// create context and get metadata + OperationResult operationResult = session + .dataDiscoveryService() + .domainContext() + .fetchMetadataByContext(domainContext); +``` + +DomEl data discovery +-------------------- +This API allows to validate DomEL expressions and convert them from string representation to object representation and back. + +```java + private DomElExpressionContext expressionStringContext; + private DomElExpressionContext expressionObjectContext; + + expressionObjectContext = new DomElExpressionContext(). + setExpression(new ClientExpressionContainer().setObject(new ClientFunction(). + setFunctionName("concat").addOperand(new ClientVariable("test")).addOperand(new ClientVariable("test1")).addOperand(new ClientVariable("b")))). + setVariables(Arrays.asList(new DomElVariable().setName("test").setType("java.lang.String"), + new DomElVariable().setName("test1").setType("java.lang.String"))). + setResultType("java.lang.String"); + + expressionStringContext= new DomElExpressionContext(). + setExpression(new ClientExpressionContainer().setString("concat(test, test1,'b')")). + setVariables(Arrays.asList(new DomElVariable().setName("test").setType("java.lang.String"), + new DomElVariable().setName("test1").setType("java.lang.String"))). + setResultType("java.lang.String"); + +// convert sring expression to object representation + OperationResult operationResult = session + .dataDiscoveryService() + .domElContext() + .create(expressionStringContext); +// convert object representation o fexpression to stirng view + OperationResult operationResult = session + .dataDiscoveryService() + .domElContext() + .create(expressionStringContext); +``` + +Derived table data discovery +---------------------------- +This API allows to validate DomEL expressions and convert them from string representation to object representation and back. + +```java + private SqlExecutionRequest sqlExecutionRequest; + sqlExecutionRequest = new SqlExecutionRequest(). + setSql("select * from account"). + setDataSourceUri("/public/Samples/Data_Sources/FoodmartDataSource"); + + OperationResult operationResult = session + .dataDiscoveryService() + .derivedTableContext() + .execute(sqlExecutionRequest); + + ``` -###Server Information Service +Query Execution Service +======================= +In addition to running reports, JasperReports Server exposes queries that you can run through the QueryExecution service. +For now the only resource that supports queries is an AdHoc data view. In present time JasperReportsServer supports only synchronize query execution. + +The following code examples execute query and retrieve a result data for different queries: +- for flat query: +```java + OperationResult execute = session. + queryExecutionService(). + flatQuery(). + execute(queryExecution); +``` +- for multi level query: +```java + OperationResult execute = session. + queryExecutionService(). + multiLevelQuery(). + execute(queryExecution); +``` +Result data set of multi level query can be obtained as MultiLevelResultData(by default) or as FlatQueryResultData: +```java + OperationResult execute = session. + queryExecutionService(). + multiLevelQuery(). + asResultDataSet(QueryResultDataMediaType.FLAT_DATA_JSON). + execute(queryExecution); +``` +- for multi axes query: +```java + OperationResult execute = session. + queryExecutionService(). + multiAxesQuery(). + execute(queryExecution); +``` +- for provided query: +```java + OperationResult execute = session. + queryExecutionService(). + providedQuery(). + execute(queryExecution); +``` +Please notice, that the client resolve type of result dataset according to "Content-Type" header of server's response. + +Also you can get fragment of result data: +```java + OperationResult execute = session. + queryExecutionService(). + providedQuery(). + offset(0). + pageSize(100). + retrieveData(uuId); + // where uuId - is Id of query execution, that you can obtain from "Content-Location" header of server's response after execution query. +``` + +To see all submitted query executions you can use: +```java + OperationResult result = seesion + .queryExecutionService() + .get() +``` + +To see just one specific query execution you should use: + +```java + OperationResult result = seesion + .queryExecutionService() + .execution(uuid) // where uuId - is Id of query execution + .get() +``` + +Also, you can see the status of any query execution using the following piece of code: +```java + OperationResult result = seesion + .queryExecutionService() + .execution(uuid) // where uuId - is Id of query execution + .status() +``` + +And you can delete execution using the following code: +```java + OperationResult execute = session. + queryExecutionService(). + execution(uuId). + delete(); +``` + +Server Information Service +========================== Use the following service to verify the server information, the same as the `About JasperReports Server` link in the user interface. ```java OperationResult result = client @@ -2138,7 +3073,9 @@ OperationResult result = client String edition = result.getEntity(); ``` -###Bundles service + +Bundles service +=============== Use bundles service to get bundles of internalization properties for particular or default user’s locale as JSON. By default service use default system locale where the application was stared. If user specified locale at authentication, the service will use it as default locale. @@ -2181,7 +3118,8 @@ final Map bundle = session .getEntity(); ``` -###Asynchronous API +Asynchronous API +================ Each operation which requests server has its asynchronous brother which has same name with `async` prefix, e. g. `get() -> asyncGet()`. Each of these operations take a `com.jaspersoft.jasperserver.jaxrs.client.core.Callback` implementation with `execute()` method implemented. `execute()` takes an `OperationResult` instance as a parameter. The `execute` method is called when the response from server came. Each of these `async` operations returns `com.jaspersoft.jasperserver.jaxrs.client.core.RequestExecution` instance which gives you ability to cancel execution. Example: @@ -2200,14 +3138,16 @@ RequestExecution requestExecution = session requestExecution.cancel(); ``` -###Getting serialized content from response +Getting serialized content from response +======================================== If you need to get a plain response body, either JSON, XML, HTML or plain text, you gen get it it with code below: ```java OperationResult result = ... result.getSerializedContent(); ``` -###Possible issues +Possible issues +=============== 1. Deploying jrs-rest-client within web app to any Appplication Server, e.g. JBoss, Glassfish, WebSphere etc. jrs-rest-client uses the implementation of JAX-RS API of version 2.0 and if your application server does not support this version you will get an error. To solve this problem you need to add to your application a deployment configuration specific for your AS where you need to exclude modules with old JAX-RS API version. Example of such descriptor for JBoss AS you can find below: @@ -2238,13 +3178,14 @@ jrs-rest-client uses the implementation of JAX-RS API of version 2.0 and if your ``` -###Maven dependency to add jasperserver-rest-client to your app: +Maven dependency to add jasperserver-rest-client to your app: +============================================================= ```xml - + com.jaspersoft jrs-rest-java-client - 6.3.1 + ${current.version} @@ -2260,7 +3201,7 @@ jrs-rest-client uses the implementation of JAX-RS API of version 2.0 and if your ``` License --------- +======= Copyright © 2005 - 2014 Jaspersoft Corporation. All rights reserved. http://www.jaspersoft.com. diff --git a/pom.xml b/pom.xml index 3d778066..89135d6c 100644 --- a/pom.xml +++ b/pom.xml @@ -7,14 +7,14 @@ com.jaspersoft jrs-rest-java-client - 6.3.1 + 7.9.0 REST client for JasperReports server http://github.com/Jaspersoft/jrs-rest-java-client UTF-8 1.5.5 - 6.3.0 + 7.9.0 @@ -23,7 +23,7 @@ HEAD - + jaspersoft-clients-snapshots Jaspersoft clients snapshots @@ -33,14 +33,20 @@ central jaspersoft-releases https://jaspersoft.jfrog.io/jaspersoft/jrs-ce-releases - - + + com.jaspersoft.jasperserver jasperserver-dto ${jasperserver-dto.version} + + + jackson-annotations + com.fasterxml.jackson.core + + @@ -50,13 +56,13 @@ 2.22.1 - com.sun.jersey - jersey-json - 1.19 + org.glassfish.jersey.media + jersey-media-multipart + 2.22.1 - com.sun.jersey.contribs - jersey-multipart + com.sun.jersey + jersey-json 1.19 @@ -162,8 +168,8 @@ maven-compiler-plugin 3.1 - 1.6 - 1.6 + 1.7 + 1.7 @@ -182,6 +188,7 @@ **/com/jaspersoft/jasperserver/jaxrs/client/core/exceptions/** **/com/jaspersoft/jasperserver/jaxrs/client/core/enums/** + **/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/adhoc/queryexecution/enums/** @@ -203,6 +210,7 @@ 2.12 false + false **/IT.java diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/adhoc/queryexecution/QueryExecutionAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/adhoc/queryexecution/QueryExecutionAdapter.java new file mode 100755 index 00000000..8ec3cfcc --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/adhoc/queryexecution/QueryExecutionAdapter.java @@ -0,0 +1,177 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.adhoc.queryexecution; + +import com.jaspersoft.jasperserver.dto.executions.AbstractClientExecution; +import com.jaspersoft.jasperserver.dto.executions.ClientExecutionListWrapper; +import com.jaspersoft.jasperserver.dto.executions.ExecutionStatusObject; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.MimeType; +import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.MandatoryParameterNotFoundException; +import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import org.apache.commons.lang3.StringUtils; + +import javax.ws.rs.core.MultivaluedHashMap; +import java.util.ArrayList; +import java.util.List; + +import static javax.ws.rs.core.MediaType.APPLICATION_JSON; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class QueryExecutionAdapter extends AbstractAdapter { + + + private String serviceURI = "queryExecutions"; + private List uri; + private Class responseClass; + private String contentType; + private String[] acceptType; + private MimeType responseFormat = sessionStorage.getConfiguration().getAcceptMimeType(); + private MultivaluedHashMap params; + + public QueryExecutionAdapter(SessionStorage sessionStorage, String contentType, Class responseClass, String... acceptType) { + super(sessionStorage); + this.contentType = contentType; + this.acceptType = acceptType; + this.responseClass = responseClass; + params = new MultivaluedHashMap<>(); + uri = new ArrayList<>(); + uri.add(serviceURI); + } + + public QueryExecutionAdapter(SessionStorage sessionStorage, String executionId) { + super(sessionStorage); + uri = new ArrayList<>(); + uri.add(serviceURI); + uri.add(executionId); + } + + public QueryExecutionAdapter(SessionStorage sessionStorage) { + super(sessionStorage); + uri = new ArrayList<>(); + uri.add(serviceURI); + } + + public QueryExecutionAdapter asXml() { + responseFormat = MimeType.XML; + return this; + } + + public QueryExecutionAdapter asJson() { + responseFormat = MimeType.JSON; + return this; + } + + public QueryExecutionAdapter asResultDataSet(String resultMimeType) { + acceptType = new String[]{resultMimeType}; + responseClass = QueryResultDataHelper.getResultDataType(resultMimeType); + return this; + } + + public QueryExecutionAdapter asResultExecution(String resultMimeType) { + acceptType = new String[]{resultMimeType}; + responseClass = QueryExecutionHelper.getClassForMime(resultMimeType); + return this; + } + + public QueryExecutionAdapter asDefaultAccept() { + acceptType = new String[]{APPLICATION_JSON}; + responseClass = QueryExecutionHelper.getClassForMime(contentType); + return this; + } + + public QueryExecutionAdapter offset(Integer offset) { + params.add("offset", offset.toString()); + return this; + } + + public QueryExecutionAdapter pageSize(Integer pageSize) { + params.add("pageSize", pageSize.toString()); + return this; + } + + public QueryExecutionAdapter withQueryParameter(String name, String value) { + params.add(name, value); + return this; + } + + public OperationResult retrieveData(String executionId) { + uri.add(executionId); + uri.add("data"); + JerseyRequest request = buildRequest(responseClass); + if (params.size() > 0) { + request.addParams(params); + } + + request.setAccept(StringUtils.join(acceptType, ",")); + return request.get(); + } + + /** + * @deprecated Replaced by {@link QueryExecutionAdapter#delete()} + */ + @Deprecated + public OperationResult deleteExecution(String executionId) { + uri.add(executionId); + JerseyRequest request = buildRequest(responseClass); + return request.delete(); + } + + public OperationResult delete() { + JerseyRequest request = buildRequest(Object.class); + return request.delete(); + } + + public OperationResult getExecutions() { + JerseyRequest request = buildRequest(ClientExecutionListWrapper.class); + return request.get(); + } + + public OperationResult get() { + JerseyRequest request = buildRequest(AbstractClientExecution.class); + return request.get(); + } + + public OperationResult status() { + uri.add("status"); + + JerseyRequest request = buildRequest(ExecutionStatusObject.class); + return request.get(); + } + + public OperationResult execute(AbstractClientExecution query) { + if (query == null) { + throw new MandatoryParameterNotFoundException("Query must be specified"); + } + JerseyRequest request = buildRequest(responseClass); + request.setContentType(contentType); + if (!(sessionStorage.getConfiguration().getAcceptMimeType() == responseFormat)) { + for (int i = 0; i < acceptType.length; i++) { + String type = acceptType[i]; + acceptType[i] = type.replace(type.substring(type.lastIndexOf("+") + 1), responseFormat.toString().toLowerCase()); + } + } + request.setAccept(StringUtils.join(acceptType, ",")); + request.addParams(params); + return request. + post(query); + } + + protected JerseyRequest buildRequest(Class responseType) { + JerseyRequest request = JerseyRequest.buildRequest(sessionStorage, + responseType, + uri.toArray(new String[uri.size()]), + new DefaultErrorHandler()); + + return request; + } + +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/adhoc/queryexecution/QueryExecutionHelper.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/adhoc/queryexecution/QueryExecutionHelper.java new file mode 100644 index 00000000..a80b7a7c --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/adhoc/queryexecution/QueryExecutionHelper.java @@ -0,0 +1,34 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.adhoc.queryexecution; + +import com.jaspersoft.jasperserver.dto.executions.AbstractClientExecution; +import com.jaspersoft.jasperserver.dto.executions.ClientMultiAxisQueryExecution; +import com.jaspersoft.jasperserver.dto.executions.ClientMultiLevelQueryExecution; +import com.jaspersoft.jasperserver.dto.executions.ClientProvidedQueryExecution; + +import java.util.HashMap; +import java.util.Map; + +import static com.jaspersoft.jasperserver.dto.executions.QueryExecutionsMediaType.EXECUTION_MULTI_LEVEL_QUERY_JSON; +import static com.jaspersoft.jasperserver.dto.executions.QueryExecutionsMediaType.EXECUTION_MULTI_AXIS_QUERY_JSON; +import static com.jaspersoft.jasperserver.dto.executions.QueryExecutionsMediaType.EXECUTION_PROVIDED_QUERY_JSON; + +public class QueryExecutionHelper { + + private static Map> mediaTypeWithExecutionClassInfo = + new HashMap>(){{ + put(EXECUTION_MULTI_LEVEL_QUERY_JSON, ClientMultiLevelQueryExecution.class); + put(EXECUTION_MULTI_AXIS_QUERY_JSON, ClientMultiAxisQueryExecution.class); + put(EXECUTION_PROVIDED_QUERY_JSON, ClientProvidedQueryExecution.class); + }}; + + public static Class getClassForMime(String mime) { + for (Map.Entry> entry : + mediaTypeWithExecutionClassInfo.entrySet()) { + if (entry.getKey().equalsIgnoreCase(mime)) { + return entry.getValue(); + } + } + return null; + } + +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/adhoc/queryexecution/QueryExecutionService.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/adhoc/queryexecution/QueryExecutionService.java new file mode 100755 index 00000000..c675285f --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/adhoc/queryexecution/QueryExecutionService.java @@ -0,0 +1,95 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.adhoc.queryexecution; + +import com.jaspersoft.jasperserver.dto.executions.ClientFlatQueryResultData; +import com.jaspersoft.jasperserver.dto.executions.ClientMultiAxisQueryResultData; +import com.jaspersoft.jasperserver.dto.executions.ClientMultiLevelQueryResultData; +import com.jaspersoft.jasperserver.dto.executions.ClientQueryResultData; +import com.jaspersoft.jasperserver.dto.executions.ClientExecutionListWrapper; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.MimeType; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; + +import static com.jaspersoft.jasperserver.dto.executions.QueryExecutionsMediaType.EXECUTION_MULTI_AXIS_QUERY_JSON; +import static com.jaspersoft.jasperserver.dto.executions.QueryExecutionsMediaType.EXECUTION_MULTI_AXIS_QUERY_XML; +import static com.jaspersoft.jasperserver.dto.executions.QueryExecutionsMediaType.EXECUTION_MULTI_LEVEL_QUERY_JSON; +import static com.jaspersoft.jasperserver.dto.executions.QueryExecutionsMediaType.EXECUTION_MULTI_LEVEL_QUERY_XML; +import static com.jaspersoft.jasperserver.dto.executions.QueryExecutionsMediaType.EXECUTION_PROVIDED_QUERY_JSON; +import static com.jaspersoft.jasperserver.dto.executions.QueryExecutionsMediaType.EXECUTION_PROVIDED_QUERY_XML; +import static com.jaspersoft.jasperserver.dto.executions.QueryResultDataMediaType.FLAT_DATA_JSON; +import static com.jaspersoft.jasperserver.dto.executions.QueryResultDataMediaType.FLAT_DATA_XML; +import static com.jaspersoft.jasperserver.dto.executions.QueryResultDataMediaType.MULTI_AXIS_DATA_JSON; +import static com.jaspersoft.jasperserver.dto.executions.QueryResultDataMediaType.MULTI_AXIS_DATA_XML; +import static com.jaspersoft.jasperserver.dto.executions.QueryResultDataMediaType.MULTI_LEVEL_DATA_JSON; +import static com.jaspersoft.jasperserver.dto.executions.QueryResultDataMediaType.MULTI_LEVEL_DATA_XML; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class QueryExecutionService extends AbstractAdapter { + + public QueryExecutionService(SessionStorage sessionStorage) { + super(sessionStorage); + } + + public QueryExecutionAdapter flatQuery() { + return this.adapter(sessionStorage, + (sessionStorage.getConfiguration().getContentMimeType().equals(MimeType.JSON)) ? + EXECUTION_MULTI_LEVEL_QUERY_JSON : EXECUTION_MULTI_LEVEL_QUERY_XML, + ClientFlatQueryResultData.class, + (sessionStorage.getConfiguration().getAcceptMimeType().equals(MimeType.JSON)) ? + FLAT_DATA_JSON : FLAT_DATA_XML); + } + + public QueryExecutionAdapter multiLevelQuery() { + return this.adapter(sessionStorage, + (sessionStorage.getConfiguration().getContentMimeType().equals(MimeType.JSON)) ? + EXECUTION_MULTI_LEVEL_QUERY_JSON : EXECUTION_MULTI_LEVEL_QUERY_XML, + ClientMultiLevelQueryResultData.class, + (sessionStorage.getConfiguration().getAcceptMimeType().equals(MimeType.JSON)) ? + MULTI_LEVEL_DATA_JSON : MULTI_LEVEL_DATA_XML); + } + + public QueryExecutionAdapter multiAxisQuery() { + return this.adapter(sessionStorage, + (sessionStorage.getConfiguration().getContentMimeType().equals(MimeType.JSON)) ? + EXECUTION_MULTI_AXIS_QUERY_JSON : EXECUTION_MULTI_AXIS_QUERY_XML, + ClientMultiAxisQueryResultData.class, + (sessionStorage.getConfiguration().getAcceptMimeType().equals(MimeType.JSON)) ? + MULTI_AXIS_DATA_JSON : MULTI_AXIS_DATA_XML); + } + + + public QueryExecutionAdapter providedQuery() { + + return this.adapter(sessionStorage, + (sessionStorage.getConfiguration().getContentMimeType().equals(MimeType.JSON)) ? + EXECUTION_PROVIDED_QUERY_JSON : EXECUTION_PROVIDED_QUERY_XML, + ClientQueryResultData.class, + (sessionStorage.getConfiguration().getAcceptMimeType().equals(MimeType.JSON)) ? + new String[]{FLAT_DATA_JSON, MULTI_LEVEL_DATA_JSON, MULTI_AXIS_DATA_JSON} : + new String[]{FLAT_DATA_XML, MULTI_LEVEL_DATA_XML, MULTI_AXIS_DATA_XML}); + } + + public OperationResult get() { + return new QueryExecutionAdapter(sessionStorage).getExecutions(); + } + + public QueryExecutionAdapter execution(String uuIUd) { + return new QueryExecutionAdapter(sessionStorage, uuIUd); + } + + + protected QueryExecutionAdapter adapter(SessionStorage sessionStorage, + String contentType, + Class clazz, + String... acceptType) { + return new QueryExecutionAdapter(sessionStorage, contentType, clazz, acceptType); + } + +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/adhoc/queryexecution/QueryResultDataHelper.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/adhoc/queryexecution/QueryResultDataHelper.java new file mode 100644 index 00000000..dffeb148 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/adhoc/queryexecution/QueryResultDataHelper.java @@ -0,0 +1,34 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.adhoc.queryexecution; + +import com.jaspersoft.jasperserver.dto.executions.ClientFlatQueryResultData; +import com.jaspersoft.jasperserver.dto.executions.ClientMultiAxisQueryResultData; +import com.jaspersoft.jasperserver.dto.executions.ClientMultiLevelQueryResultData; +import com.jaspersoft.jasperserver.dto.executions.ClientQueryResultData; + +import java.util.HashMap; +import java.util.Map; + +import static com.jaspersoft.jasperserver.dto.executions.QueryResultDataMediaType.FLAT_DATA_JSON; +import static com.jaspersoft.jasperserver.dto.executions.QueryResultDataMediaType.MULTI_AXIS_DATA_JSON; +import static com.jaspersoft.jasperserver.dto.executions.QueryResultDataMediaType.MULTI_LEVEL_DATA_JSON; + +public class QueryResultDataHelper { + + private static Map> mediaTypeWithResultDataClassInfo = + new HashMap>(){{ + put(FLAT_DATA_JSON, ClientFlatQueryResultData.class); + put(MULTI_LEVEL_DATA_JSON, ClientMultiLevelQueryResultData.class); + put(MULTI_AXIS_DATA_JSON, ClientMultiAxisQueryResultData.class); + }}; + + public static Class getResultDataType(String access) { + for (Map.Entry> entry : + mediaTypeWithResultDataClassInfo.entrySet()) { + if (entry.getKey().equalsIgnoreCase(access)) { + return entry.getValue(); + } + } + return null; + } + +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/attributes/AttributesSearchParameter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/attributes/AttributesSearchParameter.java index a125f9aa..ed969968 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/attributes/AttributesSearchParameter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/attributes/AttributesSearchParameter.java @@ -14,6 +14,11 @@ public enum AttributesSearchParameter { */ HOLDER("holder"), + /** + * name of the attribute + */ + NAME("name"), + /** * Attribute group: * @@ -50,7 +55,7 @@ public enum AttributesSearchParameter { /** * Pagination. Resources count per page */ - LIMIT("limit"); + LIMIT("limit");// @QueryParam("_embedded") String embedded, private String name; diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/attributes/BatchAttributeAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/attributes/BatchAttributeAdapter.java index 93e79219..feee16f8 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/attributes/BatchAttributeAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/attributes/BatchAttributeAdapter.java @@ -32,12 +32,13 @@ import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.MandatoryParameterNotFoundException; import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; + +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; import static java.util.Arrays.asList; @@ -59,7 +60,7 @@ public class BatchAttributeAdapter extends AbstractAdapter { public BatchAttributeAdapter(String organizationId, String userName, SessionStorage sessionStorage) { super(sessionStorage); - if (!"/" .equals(organizationId) && organizationId != null) { + if (!"/".equals(organizationId) && organizationId != null) { path.add("organizations"); path.add(organizationId); } @@ -213,9 +214,11 @@ private JerseyRequest buildSearchRequest() { HypermediaAttributesListWrapper.class, new String[]{SERVICE_URI}, new DefaultErrorHandler()); if (includePermissions) { + request.setAccept(MimeTypeUtil.toCorrectAcceptMime(sessionStorage.getConfiguration(), "application/attributes.collection.hal+{mime}")); request.addParam("_embedded", "permission"); + } else { + request.setAccept(MimeTypeUtil.toCorrectAcceptMime(sessionStorage.getConfiguration(), "application/attributes.collection+{mime}")); } - request.setAccept(MimeTypeUtil.toCorrectAcceptMime(sessionStorage.getConfiguration(), "application/attributes.collection+{mime}")); request.addParams(params); // if user did not specified holder make it form organizationId and userName variables @@ -230,7 +233,8 @@ private JerseyRequest buildSearchRequest() { if (userName != null) { holderId.append(SEPARATOR); holderId.append(userName); - }; + } + ; request.addParam("holder", holderId.toString()); } return request; diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/organizations/BatchOrganizationsAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/organizations/BatchOrganizationsAdapter.java index 4c25ebb6..a6b4381f 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/organizations/BatchOrganizationsAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/organizations/BatchOrganizationsAdapter.java @@ -28,8 +28,10 @@ import com.jaspersoft.jasperserver.jaxrs.client.core.RequestExecution; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; import com.jaspersoft.jasperserver.jaxrs.client.core.ThreadPoolUtil; +import com.jaspersoft.jasperserver.jaxrs.client.core.UrlUtils; import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; + import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; @@ -40,11 +42,11 @@ public class BatchOrganizationsAdapter extends AbstractAdapter { public BatchOrganizationsAdapter(SessionStorage sessionStorage) { super(sessionStorage); - params = new MultivaluedHashMap(); + params = new MultivaluedHashMap<>(); } public BatchOrganizationsAdapter parameter(OrganizationParameter orgParam, String value) { - params.add(orgParam.getParamName(), value); + params.add(orgParam.getParamName(), UrlUtils.encode(value)); return this; } @@ -75,7 +77,7 @@ public void run() { private JerseyRequest buildRequest(Class responseType) { - return JerseyRequest.buildRequest(sessionStorage, responseType, + return JerseyRequest.buildRequest(sessionStorage, responseType, new String[]{SERVICE_URI}, new DefaultErrorHandler()); } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/organizations/OrganizationParameter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/organizations/OrganizationParameter.java index 0258fd1d..e74db324 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/organizations/OrganizationParameter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/organizations/OrganizationParameter.java @@ -56,11 +56,38 @@ public enum OrganizationParameter { * users. * Type: Boolean (Optional) */ - CREATE_DEFAULT_USERS("createDefaultUsers"); + CREATE_DEFAULT_USERS("createDefaultUsers"), + + /** + * Pagination + * + * Default value: 0 + */ + OFFSET("offset"), + + /** + * Sagination + * + * Default value: 0 + */ + LIMIT("limit"), + + /** + * Enables sorting by "name", "alias", "id". All other values are ignored. + * Default order is natural order (order, in which organizations were created) + */ + SORT_BY("sortBy"), + + /** + * Max depth of organization tree traversing. + * + * Default value: 0 + */ + MAX_DEPTH("maxDepth"); private String paramName; - private OrganizationParameter(String paramName){ + private OrganizationParameter(String paramName) { this.paramName = paramName; } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/organizations/OrganizationsService.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/organizations/OrganizationsService.java index c065b916..6d51118d 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/organizations/OrganizationsService.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/organizations/OrganizationsService.java @@ -31,11 +31,11 @@ public OrganizationsService(SessionStorage sessionStorage) { } public SingleOrganizationAdapter organization(ClientTenant organization) { - if (organization == null || (organization.getId() == null || organization.getId().equals("") - && (organization.getAlias() == null || organization.getAlias().equals("")))) { - throw new IllegalArgumentException("Organization is not valid."); + if (organization != null && ((organization.getAlias() != null && !organization.getAlias().isEmpty()) + ||(organization.getId() != null && !organization.getId().isEmpty()) )) { + return new SingleOrganizationAdapter(sessionStorage, organization); } - return new SingleOrganizationAdapter(sessionStorage, organization); + throw new IllegalArgumentException("Organization is not valid."); } public SingleOrganizationAdapter organization(String organizationId) { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/organizations/SingleOrganizationAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/organizations/SingleOrganizationAdapter.java index 0fb750eb..da43991a 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/organizations/SingleOrganizationAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/organizations/SingleOrganizationAdapter.java @@ -28,6 +28,7 @@ import com.jaspersoft.jasperserver.jaxrs.client.core.RequestExecution; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; import com.jaspersoft.jasperserver.jaxrs.client.core.ThreadPoolUtil; +import com.jaspersoft.jasperserver.jaxrs.client.core.UrlUtils; import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; import javax.ws.rs.core.MultivaluedHashMap; @@ -42,7 +43,7 @@ public class SingleOrganizationAdapter extends AbstractAdapter { public SingleOrganizationAdapter(SessionStorage sessionStorage, ClientTenant clientTenant) { super(sessionStorage); this.clientTenant = clientTenant; - this.params = new MultivaluedHashMap(); + this.params = new MultivaluedHashMap<>(); } public OperationResult get() { @@ -104,7 +105,7 @@ public SingleOrganizationAdapter parameter(OrganizationParameter parameter, bool } public SingleOrganizationAdapter parameter(OrganizationParameter parameter, String value) { - params.add(parameter.getParamName(), value); + params.add(parameter.getParamName(), UrlUtils.encode(value)); return this; } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/roles/BatchRolesRequestAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/roles/BatchRolesRequestAdapter.java index bc5fc6bf..fc59a7e9 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/roles/BatchRolesRequestAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/roles/BatchRolesRequestAdapter.java @@ -28,22 +28,24 @@ import com.jaspersoft.jasperserver.jaxrs.client.core.RequestExecution; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; import com.jaspersoft.jasperserver.jaxrs.client.core.ThreadPoolUtil; +import com.jaspersoft.jasperserver.jaxrs.client.core.UrlUtils; import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; -import java.util.ArrayList; + import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; +import java.util.ArrayList; import static com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest.buildRequest; public class BatchRolesRequestAdapter extends AbstractAdapter { private final MultivaluedMap params; - private final ArrayList uri = new ArrayList(); + private final ArrayList uri = new ArrayList<>(); public BatchRolesRequestAdapter(SessionStorage sessionStorage, String organizationId) { super(sessionStorage); - params = new MultivaluedHashMap(); + params = new MultivaluedHashMap<>(); if (organizationId != null) { uri.add("organizations"); uri.add(organizationId); @@ -54,7 +56,7 @@ public BatchRolesRequestAdapter(SessionStorage sessionStorage, String organizati } public BatchRolesRequestAdapter param(RolesParameter rolesParam, String value) { - params.add(rolesParam.getParamName(), value); + params.add(rolesParam.getParamName(), UrlUtils.encode(value)); return this; } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/users/BatchUsersRequestAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/users/BatchUsersRequestAdapter.java index 55541848..76907c70 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/users/BatchUsersRequestAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/users/BatchUsersRequestAdapter.java @@ -28,11 +28,13 @@ import com.jaspersoft.jasperserver.jaxrs.client.core.RequestExecution; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; import com.jaspersoft.jasperserver.jaxrs.client.core.ThreadPoolUtil; +import com.jaspersoft.jasperserver.jaxrs.client.core.UrlUtils; import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; -import java.util.ArrayList; + import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; +import java.util.ArrayList; public class BatchUsersRequestAdapter extends AbstractAdapter { @@ -41,7 +43,7 @@ public class BatchUsersRequestAdapter extends AbstractAdapter { public BatchUsersRequestAdapter(SessionStorage sessionStorage, String organizationId) { super(sessionStorage); - params = new MultivaluedHashMap(); + params = new MultivaluedHashMap<>(); if (organizationId != null && !organizationId.equals("")) { uri.add("organizations"); uri.add(organizationId); @@ -50,7 +52,7 @@ public BatchUsersRequestAdapter(SessionStorage sessionStorage, String organizati } public BatchUsersRequestAdapter param(UsersParameter userParam, String value) { - params.add(userParam.getParamName(), value); + params.add(userParam.getParamName(), UrlUtils.encode(value)); return this; } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/users/UsersParameter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/users/UsersParameter.java index 3584e9fe..88cb19bf 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/users/UsersParameter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/users/UsersParameter.java @@ -59,7 +59,25 @@ public enum UsersParameter { /** * is true by default */ - INCLUDE_SUB_ORGS("includeSubOrgs") + INCLUDE_SUB_ORGS("includeSubOrgs"), + + /** + * Search for user having the specified text in the name. + * Note that the search string does not match in the ID of resources. + * + * Type/Value: String + */ + Q("q"), + + /** + * Specifies the maximum number of users return in + * each response. + * + * Type/Value: integer + */ + LIMIT("limit"), + + OFFSET("offset") ; private String paramName; diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/users/UsersService.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/users/UsersService.java index 5baa7f5c..df63163e 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/users/UsersService.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/users/UsersService.java @@ -53,11 +53,9 @@ public SingleUserRequestAdapter user(ClientUser user) { if (user == null || user.getUsername() == null || user.getUsername().equals("")) { throw new IllegalArgumentException("User is not valid."); } - if (organizationId != null && user.getTenantId() == null) { - user.setTenantId(organizationId); - } - - return new SingleUserRequestAdapter(sessionStorage, user); + return new SingleUserRequestAdapter(sessionStorage, + (organizationId != null && user.getTenantId() == null) ? + new ClientUser(user).setTenantId(organizationId) : user); } public SingleUserRequestAdapter user(String userName) diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/connections/ConnectionsService.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/connections/ConnectionsService.java index c1155bfb..69b76ac4 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/connections/ConnectionsService.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/connections/ConnectionsService.java @@ -10,37 +10,34 @@ * @author tetiana.iefimenko * @version $Id$ * @see + * + * @deprecated Replaced by {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.ContextService} */ public class ConnectionsService extends AbstractAdapter { public ConnectionsService(SessionStorage sessionStorage) { super(sessionStorage); } - - public SingleConnectionsAdapter connection(String uuId) { - return this.connection(Object.class, null, Object.class, null, uuId); + public SingleConnectionsAdapter connection(Class connectionClass, String connectionMimeType) { + return new SingleConnectionsAdapter(sessionStorage, connectionClass, connectionMimeType); } - public SingleConnectionsAdapter connection(Class connectionClass, String connectionMimeType, String uuId) { - return this.connection(connectionClass, connectionMimeType, Object.class, null, uuId); + public SingleConnectionsAdapter connection(Class connectionClass, String connectionMimeType, String uuId) { + return new SingleConnectionsAdapter(sessionStorage, connectionClass, connectionMimeType, uuId); } - public SingleConnectionsAdapter connection(Class connectionClass, String connectionMimeType) { - return this.connection(connectionClass, connectionMimeType, Object.class, null, null); + public SingleConnectionsAdapter connection(String uuId, Class metadataClass, String metadataMimeType) { + return new SingleConnectionsAdapter(sessionStorage, uuId, metadataClass, metadataMimeType); } - public SingleConnectionsAdapter connection(Class connection, - String connectionMimeType, - Class metadata, - String metadataMimeType, - String uuId) { - + public SingleConnectionsAdapter connection(Class connection, String connectionMimeType, + Class metadataClass, + String metadataMimeType) { + return new SingleConnectionsAdapter(sessionStorage, connection, connectionMimeType, metadataClass, metadataMimeType); + } - return new SingleConnectionsAdapter(sessionStorage, connection, - connectionMimeType, - metadata, - metadataMimeType, - uuId); + public SingleConnectionsAdapter connection(String uuId) { + return new SingleConnectionsAdapter(sessionStorage, uuId); } -} +} \ No newline at end of file diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/connections/SingleConnectionsAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/connections/SingleConnectionsAdapter.java index a69a8980..3df4139d 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/connections/SingleConnectionsAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/connections/SingleConnectionsAdapter.java @@ -1,13 +1,7 @@ package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.connections; -import com.jaspersoft.jasperserver.dto.connection.FtpConnection; -import com.jaspersoft.jasperserver.dto.connection.LfsConnection; -import com.jaspersoft.jasperserver.dto.resources.ClientCustomDataSource; -import com.jaspersoft.jasperserver.dto.resources.ClientJdbcDataSource; -import com.jaspersoft.jasperserver.dto.resources.ClientJndiJdbcDataSource; -import com.jaspersoft.jasperserver.dto.resources.ClientReportUnit; -import com.jaspersoft.jasperserver.dto.resources.ClientSemanticLayerDataSource; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.connections.query.SingleQueryAdapter; import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; import com.jaspersoft.jasperserver.jaxrs.client.core.MimeTypeUtil; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; @@ -22,9 +16,12 @@ * @author tetiana.iefimenko * @version $Id$ * @see + * @deprecated Replaced by {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.SingleContextAdapter} */ public class SingleConnectionsAdapter extends AbstractAdapter { + public static final String SERVICE_URI = "connections"; + private String uuId; private Class connectionClass; private String connectionMimeType; @@ -44,10 +41,36 @@ public SingleConnectionsAdapter(SessionStorage sessionStorage, Class connecti this.metadataMimeType = metadataMimeType; } + public SingleConnectionsAdapter(SessionStorage sessionStorage, Class connectionClass, + String connectionMimeType) { + this(sessionStorage, connectionClass, connectionMimeType, null, null, null); + } + + public SingleConnectionsAdapter(SessionStorage sessionStorage, Class connectionClass, + String connectionMimeType, String uuId) { + this(sessionStorage, connectionClass, connectionMimeType, null, null, uuId); + } + + public SingleConnectionsAdapter(SessionStorage sessionStorage, String uuId, Class metadataClass, + String metadataMimeType) { + this(sessionStorage, null, null, metadataClass, metadataMimeType, uuId); + } + + public SingleConnectionsAdapter(SessionStorage sessionStorage, Class connectionClass, + String connectionMimeType, + Class metadataClass, + String metadataMimeType) { + this(sessionStorage, connectionClass, connectionMimeType, metadataClass, metadataMimeType, null); + } + + public SingleConnectionsAdapter(SessionStorage sessionStorage, String uuId) { + this(sessionStorage, (Class) Object.class, null, null, null, uuId); + } + @SuppressWarnings("unchecked") public OperationResult create(C connection) { - if (!isConnectionTypeValid(connection)) { - throw new IllegalArgumentException("Unsupported connectionClass type"); + if (connection == null) { + throw new MandatoryParameterNotFoundException("Connection is null"); } JerseyRequest jerseyRequest = JerseyRequest.buildRequest(this.sessionStorage , connectionClass @@ -67,8 +90,8 @@ public OperationResult get() { } public OperationResult update(C connection) { - if (!isConnectionTypeValid(connection)) { - throw new IllegalArgumentException("Unsupported connectionClass type"); + if (connection == null) { + throw new MandatoryParameterNotFoundException("Connection is null"); } JerseyRequest jerseyRequest = buildRequest(); if (connectionMimeType != null) { @@ -109,8 +132,8 @@ public OperationResult metadata() { } public OperationResult createAndGetMetadata(C connection) { - if (!isConnectionTypeValid(connection)) { - throw new IllegalArgumentException("Unsupported connectionClass type"); + if (connection == null) { + throw new MandatoryParameterNotFoundException("Connection is null"); } JerseyRequest jerseyRequest = JerseyRequest.buildRequest(this.sessionStorage , metadataClass @@ -125,16 +148,8 @@ public OperationResult createAndGetMetadata(C connection) { return jerseyRequest.post(connection); } - protected Boolean isConnectionTypeValid(T connection) { - if (connection == null) { - throw new MandatoryParameterNotFoundException("Connection is null"); - } - return (connection instanceof FtpConnection || - connection instanceof LfsConnection || - connection instanceof ClientSemanticLayerDataSource || - connection instanceof ClientCustomDataSource || - connection instanceof ClientJndiJdbcDataSource || - connection instanceof ClientJdbcDataSource || - connection instanceof ClientReportUnit); + + public SingleQueryAdapter query(String query, Class queryResponseClass) { + return new SingleQueryAdapter(sessionStorage, uuId, query, queryResponseClass); } } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/connections/query/SingleQueryAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/connections/query/SingleQueryAdapter.java new file mode 100644 index 00000000..c86ed128 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/connections/query/SingleQueryAdapter.java @@ -0,0 +1,59 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.connections.query; + +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.MimeTypeUtil; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.MandatoryParameterNotFoundException; +import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class SingleQueryAdapter extends AbstractAdapter { + + private String query; + private String uuId; + private Class queryResponseClass; + + public SingleQueryAdapter(SessionStorage sessionStorage, + String uuId, + String query, + Class queryResponceClass) { + super(sessionStorage); + this.query = query; + this.uuId = uuId; + this.queryResponseClass = queryResponceClass; + } + + + public OperationResult execute() { + return (OperationResult) buildRequest().setContentType("text/plain").post(query); + } + + @SuppressWarnings("unchecked") + public OperationResult resultSetMetadata() { + return (OperationResult) buildRequest(). + setAccept(MimeTypeUtil.toCorrectAcceptMime(sessionStorage.getConfiguration() + , "application/dataset.metadata+{mime}")). + post(query); + } + + @SuppressWarnings("unchecked") + protected JerseyRequest buildRequest() { + if (this.uuId == null) { + throw new MandatoryParameterNotFoundException("Uuid of the connection must be specified"); + } + return (JerseyRequest) JerseyRequest.buildRequest(sessionStorage, + queryResponseClass, + new String[]{"/connections", uuId, "data"}, + new DefaultErrorHandler()); + } + +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/ContextService.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/ContextService.java new file mode 100644 index 00000000..18539b30 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/ContextService.java @@ -0,0 +1,41 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context; + +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class ContextService extends AbstractAdapter { + + public ContextService(SessionStorage sessionStorage) { + super(sessionStorage); + } + public SingleContextAdapter context(Class contextClass, String contextMimeType) { + return new SingleContextAdapter(sessionStorage, contextClass, contextMimeType); + } + + public SingleContextAdapter context(Class contextClass, String contextMimeType, String uuId) { + return new SingleContextAdapter(sessionStorage, contextClass, contextMimeType, uuId); + } + + public SingleContextAdapter context(String uuId, Class metadataClass, String metadataMimeType) { + return new SingleContextAdapter(sessionStorage, uuId, metadataClass, metadataMimeType); + } + + public SingleContextAdapter context(Class context, String contextMimeType, + Class metadataClass, + String metadataMimeType) { + return new SingleContextAdapter(sessionStorage, context, contextMimeType, metadataClass, metadataMimeType); + } + + public SingleContextAdapter context(String uuId) { + return new SingleContextAdapter(sessionStorage, uuId); + } + +} \ No newline at end of file diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/SingleContextAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/SingleContextAdapter.java new file mode 100644 index 00000000..176bc7ea --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/SingleContextAdapter.java @@ -0,0 +1,214 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context; + +import com.jaspersoft.jasperserver.dto.adhoc.query.ClientMultiLevelQuery; +import com.jaspersoft.jasperserver.dto.connection.metadata.PartialMetadataOptions; +import com.jaspersoft.jasperserver.dto.executions.ClientMultiLevelQueryResultData; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.UrlUtils; +import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.MandatoryParameterNotFoundException; +import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; + +import javax.ws.rs.core.MultivaluedHashMap; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class SingleContextAdapter extends AbstractAdapter { + + public static final String SERVICE_URI = "contexts"; + + private String uuId; + private Class contextClass; + private String contextContentMimeType; + private Class metadataClass; + private String metadataMimeType; + private MultivaluedHashMap params; + + public SingleContextAdapter(SessionStorage sessionStorage, Class contextClass, + String contextContentMimeType, + Class metadataClass, + String metadataMimeType, + String uuId) { + super(sessionStorage); + this.uuId = uuId; + this.contextClass = contextClass; + this.contextContentMimeType = contextContentMimeType; + this.metadataClass = metadataClass; + this.metadataMimeType = metadataMimeType; + params = new MultivaluedHashMap<>(); + } + + public SingleContextAdapter(SessionStorage sessionStorage, Class contextClass, + String contextContentMimeType) { + this(sessionStorage, contextClass, contextContentMimeType, null, null, null); + } + + public SingleContextAdapter(SessionStorage sessionStorage, Class contextClass, + String contextContentMimeType, String uuId) { + this(sessionStorage, contextClass, contextContentMimeType, null, null, uuId); + } + + public SingleContextAdapter(SessionStorage sessionStorage, String uuId, Class metadataClass, + String metadataMimeType) { + this(sessionStorage, null, null, metadataClass, metadataMimeType, uuId); + } + + public SingleContextAdapter(SessionStorage sessionStorage, Class contextClass, + String contextContentMimeType, + Class metadataClass, + String metadataMimeType) { + this(sessionStorage, contextClass, contextContentMimeType, metadataClass, metadataMimeType, null); + } + + public SingleContextAdapter(SessionStorage sessionStorage, String uuId) { + this(sessionStorage, (Class) Object.class, null, null, null, uuId); + } + + public SingleContextAdapter addParameter(String key, String value) { + params.add(key, UrlUtils.encode(value)); + return this; + } + + public SingleContextAdapter addParameter(String key, String... value) { + params.addAll(key, UrlUtils.encode(Arrays.asList(value))); + return this; + } + + public SingleContextAdapter addParameters(MultivaluedHashMap values) { + for (Map.Entry> entry : values.entrySet()) { + params.addAll(entry.getKey(), UrlUtils.encode(entry.getValue())); + } + return this; + } + + public SingleContextAdapter addParameter(String key, List value) { + params.addAll(key, UrlUtils.encode(value)); + return this; + } + + @SuppressWarnings("unchecked") + public OperationResult create(C context) { + if (context == null) { + throw new MandatoryParameterNotFoundException("Context is null"); + } + JerseyRequest jerseyRequest = JerseyRequest.buildRequest(this.sessionStorage + , contextClass + , new String[]{SERVICE_URI} + , new DefaultErrorHandler()); + if (contextContentMimeType != null) { + jerseyRequest + .setContentType(contextContentMimeType); + } + return jerseyRequest.post(context); + } + + public OperationResult get() { + JerseyRequest jerseyRequest = buildRequest(); + return jerseyRequest.get(); + } + + public OperationResult update(C context) { + JerseyRequest jerseyRequest = buildRequest(); + if (contextContentMimeType != null) { + jerseyRequest + .setContentType(contextContentMimeType); + } + return jerseyRequest.put(context); + } + + public OperationResult delete() { + return buildRequest().delete(); + } + + protected JerseyRequest buildRequest() { + if (uuId == null || uuId.isEmpty()) { + throw new MandatoryParameterNotFoundException("Uuid of the context must be specified"); + } + return JerseyRequest.buildRequest(this.sessionStorage + , contextClass + , new String[]{SERVICE_URI, uuId} + , new DefaultErrorHandler()); + } + + public OperationResult metadata() { + if (uuId == null || uuId.isEmpty()) { + throw new MandatoryParameterNotFoundException("Uuid of the context must be specified"); + } + JerseyRequest jerseyRequest = JerseyRequest.buildRequest( + sessionStorage, + metadataClass, + new String[]{SERVICE_URI, uuId, "metadata"}, + new DefaultErrorHandler() + ); + jerseyRequest.setAccept(metadataMimeType); + if (!params.isEmpty()) jerseyRequest.addParams(params); + return jerseyRequest.get(); + } + + public OperationResult partialMetadata() { + if (uuId == null || uuId.isEmpty()) { + throw new MandatoryParameterNotFoundException("Uuid of the context must be specified"); + } + + JerseyRequest jerseyRequest = JerseyRequest.buildRequest( + sessionStorage, + metadataClass, + new String[]{SERVICE_URI, uuId, "metadata"}, + new DefaultErrorHandler() + ); + jerseyRequest.setContentType(metadataMimeType); + return jerseyRequest.post(params); + } + + public OperationResult partialMetadata(PartialMetadataOptions options) { + if (uuId == null || uuId.isEmpty()) { + throw new MandatoryParameterNotFoundException("Uuid of the context must be specified"); + } + + JerseyRequest jerseyRequest = JerseyRequest.buildRequest( + sessionStorage, + metadataClass, + new String[]{SERVICE_URI, uuId, "metadata"}, + new DefaultErrorHandler() + ); + jerseyRequest.setContentType(metadataMimeType); + return jerseyRequest.post(options); + } + + public OperationResult createAndGetMetadata(C context) { + if (context == null) { + throw new MandatoryParameterNotFoundException("Context is null"); + } + JerseyRequest jerseyRequest = JerseyRequest.buildRequest(this.sessionStorage + , metadataClass + , new String[]{SERVICE_URI} + , new DefaultErrorHandler()); + jerseyRequest + .setContentType(contextContentMimeType); + jerseyRequest + .setAccept(metadataMimeType); + if (!params.isEmpty()) jerseyRequest.addParams(params); + return jerseyRequest.post(context); + } + + public OperationResult executeQuery(ClientMultiLevelQuery query) { + + JerseyRequest jerseyRequest = JerseyRequest.buildRequest(this.sessionStorage + , ClientMultiLevelQueryResultData.class + , new String[]{SERVICE_URI, uuId, "data"}); + jerseyRequest + .setContentType("application/adhoc.multiLevelQuery+json"); + return jerseyRequest.post(query); + } +} \ No newline at end of file diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/domain/DomainContextOperationResult.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/domain/DomainContextOperationResult.java new file mode 100644 index 00000000..6fbd886a --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/domain/DomainContextOperationResult.java @@ -0,0 +1,114 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.domain; + +import com.jaspersoft.jasperserver.dto.adhoc.query.ClientMultiLevelQuery; +import com.jaspersoft.jasperserver.dto.executions.ClientMultiLevelQueryResultData; +import com.jaspersoft.jasperserver.dto.resources.ClientResourceLookup; +import com.jaspersoft.jasperserver.dto.resources.ClientSemanticLayerDataSource; +import com.jaspersoft.jasperserver.dto.resources.domain.ClientDomain; +import com.jaspersoft.jasperserver.dto.resources.domain.PresentationGroupElement; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.ContextService; +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.ContextMediaTypes; +import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.ResourceNotFoundException; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import java.util.HashMap; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.Response; + +import static java.util.Arrays.asList; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class DomainContextOperationResult extends OperationResult { + + private String uuId; + private T context; + private Class contextClass; + private String contextMimeType; + private Class metadataClass = PresentationGroupElement.class; + private String metadataMimeType; + private MultivaluedHashMap params = new MultivaluedHashMap<>(); + private ContextService service; + private static HashMap mimeTypes = new HashMap<>(); + + static { + mimeTypes.put(ClientResourceLookup.class, ContextMediaTypes.RESOURCE_LOOKUP_JSON); + mimeTypes.put(ClientDomain.class, ContextMediaTypes.DOMAIN_JSON); + mimeTypes.put(ClientSemanticLayerDataSource.class, ContextMediaTypes.DOMAIN_DATA_SOURCE_JSON); + } + + + public DomainContextOperationResult(Response response, + Class entityClass, + ContextService service) { + super(response, (Class) entityClass); + this.contextClass = (Class) entityClass; + this.context = super.getEntity(); + contextMimeType = mimeTypes.get(contextClass); + this.service = service; + extractUuid(); + } + + public T getEntity() { + return super.getEntity(); + } + + public DomainContextOperationResult addParam(String key, String value) { + params.add(key, value); + return this; + } + + public DomainContextOperationResult addParam(String key, String... value) { + params.addAll(key, asList(value)); + return this; + } + + protected void extractUuid() { + String location = response.getHeaderString("Location"); + uuId = location.substring(location.lastIndexOf("/") + 1); + } + + protected String completeMetadataMimeType(String contextMimeType) { + return contextMimeType.replace("+", ".metadata+"); + } + + public OperationResult executeQuery(ClientMultiLevelQuery query) { + + OperationResult queryOperationResult; + try { + queryOperationResult = service + .context(uuId) + .executeQuery(query); + } catch (ResourceNotFoundException e) { + response = service.context(contextClass, contextMimeType).create(context).getResponse(); + extractUuid(); + queryOperationResult = service + .context(uuId) + .executeQuery(query); + } + return queryOperationResult; + } + + + public OperationResult getMetadata() { + metadataMimeType = completeMetadataMimeType(contextMimeType); + OperationResult metadata; + try { + metadata = service + .context(uuId, metadataClass, metadataMimeType).addParameters(params) + .metadata(); + } catch (ResourceNotFoundException e) { + response = service.context(contextClass, contextMimeType).create(this.context).getResponse(); + extractUuid(); + metadata = service + .context(uuId, metadataClass, metadataMimeType).addParameters(params).metadata(); + } + return metadata; + } + +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/domain/DomainContextService.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/domain/DomainContextService.java new file mode 100644 index 00000000..e6706af8 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/domain/DomainContextService.java @@ -0,0 +1,46 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.domain; + +import com.jaspersoft.jasperserver.dto.resources.ClientResourceLookup; +import com.jaspersoft.jasperserver.dto.resources.ClientSemanticLayerDataSource; +import com.jaspersoft.jasperserver.dto.resources.domain.ClientDomain; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.ContextMediaTypes; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class DomainContextService extends AbstractAdapter { + + public DomainContextService(SessionStorage sessionStorage) { + super(sessionStorage); + } + + public SingleDomainContextAdapter context(String contextUri) { + return new SingleDomainContextAdapter<>(sessionStorage, + new ClientResourceLookup().setUri(contextUri), + ClientResourceLookup.class, + ContextMediaTypes.RESOURCE_LOOKUP_JSON); + } + + public SingleDomainContextAdapter context(ClientDomain context) { + return new SingleDomainContextAdapter<>(sessionStorage, + context, + ClientDomain.class, + ContextMediaTypes.DOMAIN_JSON); + } + + public SingleDomainContextAdapter context(ClientSemanticLayerDataSource context) { + return new SingleDomainContextAdapter(sessionStorage, + context, + ClientSemanticLayerDataSource.class, + ContextMediaTypes.DOMAIN_DATA_SOURCE_JSON); + } + + +} \ No newline at end of file diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/domain/SingleDomainContextAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/domain/SingleDomainContextAdapter.java new file mode 100644 index 00000000..66e9d262 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/domain/SingleDomainContextAdapter.java @@ -0,0 +1,53 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.domain; + +import com.jaspersoft.jasperserver.dto.resources.ClientResourceLookup; +import com.jaspersoft.jasperserver.dto.resources.ClientSemanticLayerDataSource; +import com.jaspersoft.jasperserver.dto.resources.domain.ClientDomain; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.ContextService; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.IllegalParameterValueException; +import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.MandatoryParameterNotFoundException; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class SingleDomainContextAdapter extends AbstractAdapter { + + private C context; + private Class contextClass; + private String contextMimeType; + private ContextService service; + + public SingleDomainContextAdapter(SessionStorage sessionStorage, + C context, + Class contextClass, + String contextMimeType) { + super(sessionStorage); + this.context = context; + if (!isContextTypeValid(context)) throw new IllegalParameterValueException(); + this.contextClass = contextClass; + this.contextMimeType = contextMimeType; + service = new ContextService(sessionStorage); + } + public DomainContextOperationResult create() { + OperationResult operationResult = service.context(contextClass, contextMimeType).create(this.context); + return new DomainContextOperationResult(operationResult.getResponse(), + operationResult.getEntity().getClass(), service); + } + + protected Boolean isContextTypeValid(T context) { + if (context == null) { + throw new MandatoryParameterNotFoundException("context is null"); + } + return (context instanceof ClientResourceLookup || + context instanceof ClientDomain || + context instanceof ClientSemanticLayerDataSource); + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/DataDiscoveryService.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/DataDiscoveryService.java new file mode 100644 index 00000000..739fdbad --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/DataDiscoveryService.java @@ -0,0 +1,36 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.datadiscovery; + +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class DataDiscoveryService extends AbstractAdapter { + + public DataDiscoveryService(SessionStorage sessionStorage) { + super(sessionStorage); + } + + public DomainContextManager domainContext() { + return new DomainContextManager(sessionStorage); + } + + public TopicContextManager topicContext() { + return new TopicContextManager(sessionStorage); + } + + public DomElContextManager domElContext() { + return new DomElContextManager(sessionStorage); + } + + public DerivedTableContextManager derivedTableContext() { + return new DerivedTableContextManager(sessionStorage); + } + +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/DerivedTableContextManager.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/DerivedTableContextManager.java new file mode 100644 index 00000000..eb541022 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/DerivedTableContextManager.java @@ -0,0 +1,34 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.datadiscovery; + +import com.jaspersoft.jasperserver.dto.resources.SqlExecutionRequest; +import com.jaspersoft.jasperserver.dto.resources.domain.PresentationGroupElement; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.ContextService; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.ContextMediaTypes; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class DerivedTableContextManager extends AbstractAdapter { + + public DerivedTableContextManager(SessionStorage sessionStorage) { + super(sessionStorage); + } + + public OperationResult execute(SqlExecutionRequest sqlExecutionRequest) { + return new ContextService(sessionStorage). + context(SqlExecutionRequest.class, + ContextMediaTypes.SQL_EXECUTION_JSON, + PresentationGroupElement.class, + ContextMediaTypes.DATASET_METADATA_JSON). + createAndGetMetadata(sqlExecutionRequest); + } + +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/DomElContextManager.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/DomElContextManager.java new file mode 100644 index 00000000..96b0fb34 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/DomElContextManager.java @@ -0,0 +1,37 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.datadiscovery; + +import com.jaspersoft.jasperserver.dto.domain.DomElExpressionCollectionContext; +import com.jaspersoft.jasperserver.dto.domain.DomElExpressionContext; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.ContextService; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.ContextMediaTypes; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class DomElContextManager extends AbstractAdapter { + + public DomElContextManager(SessionStorage sessionStorage) { + super(sessionStorage); + } + + public OperationResult create(DomElExpressionContext expressionContext) { + return new ContextService(sessionStorage). + context(DomElExpressionContext.class, ContextMediaTypes.DOM_EL_CONTEXT_JSON). + create(expressionContext); + } + + public OperationResult create(DomElExpressionCollectionContext expressionCollectionContext) { + return new ContextService(sessionStorage). + context(DomElExpressionCollectionContext.class, + ContextMediaTypes.DOM_EL_COLLECTION_CONTEXT_JSON). + create(expressionCollectionContext); + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/DomainContextManager.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/DomainContextManager.java new file mode 100644 index 00000000..73237c7c --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/DomainContextManager.java @@ -0,0 +1,45 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.datadiscovery; + +import com.jaspersoft.jasperserver.dto.resources.domain.ClientDomain; +import com.jaspersoft.jasperserver.dto.resources.domain.PresentationGroupElement; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.ContextService; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.ContextMediaTypes; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class DomainContextManager { + private SessionStorage sessionStorage; + public DomainContextManager(SessionStorage sessionStorage) { + this.sessionStorage = sessionStorage; + } + + public OperationResult create(ClientDomain domain) { + return new ContextService(sessionStorage). + context(ClientDomain.class, ContextMediaTypes.DOMAIN_JSON). + create(domain); + } + + public OperationResult fetchMetadataById(String id) { + return new ContextService(sessionStorage).context(id, + PresentationGroupElement.class, + ContextMediaTypes.DOMAIN_METADATA_JSON). + metadata(); + } + + public OperationResult fetchMetadataByContext(ClientDomain domain) { + return new ContextService(sessionStorage). + context(ClientDomain.class, + ContextMediaTypes.DOMAIN_JSON, + PresentationGroupElement.class, + ContextMediaTypes.DOMAIN_METADATA_JSON). + createAndGetMetadata(domain); + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/TopicContextManager.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/TopicContextManager.java new file mode 100644 index 00000000..3adcdb25 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/TopicContextManager.java @@ -0,0 +1,47 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.datadiscovery; + +import com.jaspersoft.jasperserver.dto.resources.ClientReportUnit; +import com.jaspersoft.jasperserver.dto.resources.domain.ResourceGroupElement; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.ContextService; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.ContextMediaTypes; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class TopicContextManager { + private SessionStorage sessionStorage; + public TopicContextManager(SessionStorage sessionStorage) { + this.sessionStorage = sessionStorage; + } + + public OperationResult create(ClientReportUnit reportUnit) { + return new ContextService(sessionStorage). + context(ClientReportUnit.class, + ContextMediaTypes.REPORT_UNIT_JSON). + create(reportUnit); + } + + public OperationResult fetchMetadataById(String id) { + return new ContextService(sessionStorage). + context(id, + ResourceGroupElement.class, + ContextMediaTypes.REPORT_UNIT_METADATA_JSON). + metadata(); + } + + public OperationResult fetchMetadataByContext(ClientReportUnit reportUnit) { + return new ContextService(sessionStorage). + context(ClientReportUnit.class, + ContextMediaTypes.REPORT_UNIT_JSON, + ResourceGroupElement.class, + ContextMediaTypes.REPORT_UNIT_METADATA_JSON). + createAndGetMetadata(reportUnit); + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/DomainService.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/DomainService.java new file mode 100644 index 00000000..785612b5 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/DomainService.java @@ -0,0 +1,47 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.domain; + +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.domain.metadata.DomainMetadataAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.domain.newDomain.DomainAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.domain.schema.DomainSchemaAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.MandatoryParameterNotFoundException; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class DomainService extends AbstractAdapter { + private String uri; + + public DomainService(SessionStorage sessionStorage) { + super(sessionStorage); + } + + public DomainService forDomain(String uri) { + if (uri == null) { + throw new MandatoryParameterNotFoundException("URI must be specified"); + } + this.uri = uri; + return this; + } + + public DomainAdapter domain(String uri) { + if (uri == null) { + throw new MandatoryParameterNotFoundException("URI must be specified"); + } + return new DomainAdapter(sessionStorage, uri); + } + + public DomainMetadataAdapter metadata() { + return new DomainMetadataAdapter(sessionStorage, uri); + } + + public DomainSchemaAdapter schema() { + return new DomainSchemaAdapter(sessionStorage, uri); + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/DomainMetadataAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/metadata/DomainMetadataAdapter.java similarity index 96% rename from src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/DomainMetadataAdapter.java rename to src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/metadata/DomainMetadataAdapter.java index 3db20409..e8a84fd4 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/DomainMetadataAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/metadata/DomainMetadataAdapter.java @@ -18,7 +18,7 @@ * You should have received a copy of the GNU Affero General Public License * along with this program.  If not, see . */ -package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.domain; +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.domain.metadata; import com.jaspersoft.jasperserver.dto.domain.DomainMetaData; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; @@ -30,7 +30,7 @@ import java.util.Arrays; public class DomainMetadataAdapter extends AbstractAdapter { - private final ArrayList path = new ArrayList(); + private final ArrayList path = new ArrayList<>(); public DomainMetadataAdapter(SessionStorage sessionStorage, String domainURI) { super(sessionStorage); diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/newDomain/DomainAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/newDomain/DomainAdapter.java new file mode 100644 index 00000000..f9b7eaed --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/newDomain/DomainAdapter.java @@ -0,0 +1,71 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.domain.newDomain; + +import com.jaspersoft.jasperserver.dto.resources.domain.ClientDomain; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.MimeTypeUtil; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import java.util.ArrayList; +import java.util.List; + +import static java.util.Arrays.asList; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class DomainAdapter extends AbstractAdapter { + + public static final String SERVICE_URI = "resources"; + private List path = new ArrayList(); + + public DomainAdapter(SessionStorage sessionStorage, String uri) { + super(sessionStorage); + this.path.add(SERVICE_URI); + this.path.addAll(asList(uri.split("/"))); + } + + + public OperationResult create(ClientDomain domain) { + JerseyRequest request = buildRequest(); + request.setContentType(MimeTypeUtil.toCorrectAcceptMime(sessionStorage.getConfiguration(), "application/repository.domain+{mime}")); + return request.post(domain); + } + + + public OperationResult get() { + JerseyRequest request = buildRequest(); + request.setAccept(MimeTypeUtil.toCorrectAcceptMime(sessionStorage.getConfiguration(), "application/repository.domain+{mime}")); + return request.get(); + } + + + public OperationResult update(ClientDomain domain) { + JerseyRequest request = buildRequest(); + request.setContentType(MimeTypeUtil.toCorrectAcceptMime(sessionStorage.getConfiguration(), "application/repository.domain+{mime}")); + return request.put(domain); + } + + public OperationResult delete() { + return buildRequest().delete(); + } + + + protected JerseyRequest buildRequest() { + JerseyRequest jerseyRequest = JerseyRequest.buildRequest( + sessionStorage, + ClientDomain.class, + path.toArray(new String[path.size()]), + new DefaultErrorHandler() + ); + return jerseyRequest; + } + + +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/schema/DomainSchemaAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/schema/DomainSchemaAdapter.java new file mode 100644 index 00000000..27248bac --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/schema/DomainSchemaAdapter.java @@ -0,0 +1,112 @@ +/* + * Copyright (C) 2005 - 2014 Jaspersoft Corporation. All rights reserved. + * http://www.jaspersoft.com. + * + * Unless you have purchased a commercial license agreement from Jaspersoft, + * the following license terms apply: + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see . + */ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.domain.schema; + +import com.jaspersoft.jasperserver.dto.resources.ClientFile; +import com.jaspersoft.jasperserver.dto.resources.domain.Schema; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.MimeTypeUtil; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.MediaType; + +import static java.util.Arrays.asList; + +public class DomainSchemaAdapter extends AbstractAdapter { + public static final String SERVICE_URI = "resources"; + private final List path = new ArrayList(); + + public DomainSchemaAdapter(SessionStorage sessionStorage, String domainURI) { + super(sessionStorage); + this.path.add(SERVICE_URI); + this.path.addAll(asList(domainURI.split("/"))); + } + + public OperationResult get() { + JerseyRequest request = buildRequest(); + request.setAccept(MimeTypeUtil.toCorrectAcceptMime(sessionStorage.getConfiguration(), + "application/repository.domainSchema+{mime}")); + return request.get(); + } + + + public OperationResult update(Schema schema) { + JerseyRequest request = buildRequest(); + request.setContentType(MimeTypeUtil.toCorrectAcceptMime(sessionStorage.getConfiguration(), + "application/repository.domainSchema+{mime}")); + return request.put(schema); + } + + + public OperationResult upload(String path, String name, String description) { + File file = new File(path); + return uploadFile(file, ClientFile.FileType.xml, name, description); + } + + + protected JerseyRequest buildRequest() { + JerseyRequest jerseyRequest = JerseyRequest.buildRequest( + sessionStorage, + Schema.class, + path.toArray(new String[path.size()]), + new DefaultErrorHandler() + ); + return jerseyRequest; + } + + protected OperationResult uploadFile(File fileContent, + ClientFile.FileType fileType, + String label, + String description) { + FormDataMultiPart form = prepareUploadForm(fileContent, fileType, label, description); + JerseyRequest request = prepareUploadFileRequest(); + return request.post(form); + } + + protected FormDataMultiPart prepareUploadForm(File fileContent, + ClientFile.FileType fileType, + String label, + String description) { + FormDataMultiPart form = new FormDataMultiPart(); + form + .field("data", fileContent, MediaType.WILDCARD_TYPE) + .field("label", label) + .field("description", description) + .field("type", fileType.name()); + return form; + } + + + protected JerseyRequest prepareUploadFileRequest() { + JerseyRequest request = JerseyRequest.buildRequest(sessionStorage, + ClientFile.class, + path.toArray(new String[path.size()])); + request.setContentType(MediaType.MULTIPART_FORM_DATA); + return request; + } + +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/exportservice/ExportParameter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/exportservice/ExportParameter.java index fc17e28c..b06965cd 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/exportservice/ExportParameter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/exportservice/ExportParameter.java @@ -88,7 +88,16 @@ public enum ExportParameter { * and enabled skip-dependent-resources - in this case just report without dependent resources(like domain, * datasource) will be exported. */ - SKIP_DEPENDENT_RESOURCES("skip-dependent-resources"); + SKIP_DEPENDENT_RESOURCES("skip-dependent-resources"), + /** + * Pagination. Start index for requested pate. + */ + OFFSET("offset"), + + /** + * Pagination. Resources count per page + */ + LIMIT("limit"); private String paramName; diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/exportservice/ExportRequestAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/exportservice/ExportRequestAdapter.java index 3d5409e7..f1ac69d5 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/exportservice/ExportRequestAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/exportservice/ExportRequestAdapter.java @@ -20,6 +20,7 @@ */ package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.importexport.exportservice; +import com.jaspersoft.jasperserver.dto.importexport.ExportTask; import com.jaspersoft.jasperserver.dto.importexport.State; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; import com.jaspersoft.jasperserver.jaxrs.client.core.Callback; @@ -29,6 +30,7 @@ import com.jaspersoft.jasperserver.jaxrs.client.core.ThreadPoolUtil; import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.ExportFailedException; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; + import java.io.InputStream; import java.util.Arrays; @@ -40,17 +42,51 @@ public class ExportRequestAdapter extends AbstractAdapter { public static final String EXPORT_FILE = "exportFile"; private static final String STATE_URI = "state"; - private final String taskId; + private String taskId; + private ExportTask exportTask; public ExportRequestAdapter(SessionStorage sessionStorage, String taskId) { super(sessionStorage); this.taskId = taskId; } + public ExportRequestAdapter(SessionStorage sessionStorage, ExportTask exportTask) { + super(sessionStorage); + this.exportTask = exportTask; + } + + public OperationResult create() { + return JerseyRequest.buildRequest(sessionStorage, State.class, new String[]{SERVICE_URI}).post(exportTask); + } + + public RequestExecution asyncCreate(final Callback, R> callback) { + final JerseyRequest request = JerseyRequest.buildRequest(sessionStorage, State.class, new String[]{SERVICE_URI}); + request.setAccept("application/zip"); + // Guarantee that exportTask won't be modified from another thread + final ExportTask localCopy = new ExportTask(exportTask); + RequestExecution task = new RequestExecution(new Runnable() { + @Override + public void run() { + callback.execute(request.post(localCopy)); + } + }); + ThreadPoolUtil.runAsynchronously(task); + return task; + } + + + public OperationResult getMetadata() { + return buildRequest(sessionStorage, ExportTask.class, new String[]{SERVICE_URI, taskId}).get(); + } + public OperationResult state() { return buildRequest(sessionStorage, State.class, new String[]{SERVICE_URI, taskId, STATE_URI}).get(); } + public OperationResult cancel() { + return buildRequest(sessionStorage, Object.class, new String[]{SERVICE_URI, taskId}).delete(); + } + public RequestExecution asyncState(final Callback, R> callback) { final JerseyRequest request = buildRequest(sessionStorage, State.class, new String[]{SERVICE_URI, taskId, STATE_URI}); RequestExecution task = new RequestExecution(new Runnable() { @@ -63,7 +99,17 @@ public void run() { return task; } + /** + * @deprecated Replaced by {@link ExportRequestAdapter#fetch(long)} + */ + @Deprecated public OperationResult fetch() { + + return fetch(500); + } + + @Deprecated + public OperationResult fetch(long interval) { State state; while (!"finished".equals((state = state().getEntity()).getPhase())) { if ("failed".equals(state.getPhase())) { @@ -74,16 +120,17 @@ public OperationResult fetch() { } } try { - Thread.sleep(500); + Thread.sleep(interval); } catch (InterruptedException ignored) { // NOP } } - JerseyRequest request = buildRequest(sessionStorage, InputStream.class, new String[]{SERVICE_URI, taskId, EXPORT_FILE}); + JerseyRequest request = buildRequest(sessionStorage, InputStream.class, new String[]{SERVICE_URI, taskId, EXPORT_FILE});//eeeee request.setAccept("application/zip"); return request.get(); } + @Deprecated public RequestExecution asyncFetch(final Callback, R> callback) { final JerseyRequest request = buildRequest(sessionStorage, InputStream.class, new String[]{SERVICE_URI, taskId, EXPORT_FILE}); request.setAccept("application/zip"); @@ -111,4 +158,25 @@ public void run() { ThreadPoolUtil.runAsynchronously(task); return task; } -} \ No newline at end of file + + + public OperationResult fetchToFile(String fileName) { + + JerseyRequest request = buildRequest(sessionStorage, InputStream.class, new String[]{SERVICE_URI, taskId, fileName});//eeeee + request.setAccept("application/zip"); + return request.get(); + } + + public RequestExecution asyncFetchToFile(String fileName, final Callback, R> callback) { + final JerseyRequest request = buildRequest(sessionStorage, InputStream.class, new String[]{SERVICE_URI, taskId, fileName});//eeeee + request.setContentType("application/zip"); + RequestExecution task = new RequestExecution(new Runnable() { + @Override + public void run() { + callback.execute(request.get()); + } + }); + ThreadPoolUtil.runAsynchronously(task); + return task; + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/exportservice/ExportService.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/exportservice/ExportService.java index a2889135..43123069 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/exportservice/ExportService.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/exportservice/ExportService.java @@ -20,6 +20,7 @@ */ package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.importexport.exportservice; +import com.jaspersoft.jasperserver.dto.importexport.ExportTask; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; @@ -29,10 +30,18 @@ public ExportService(SessionStorage sessionStorage) { super(sessionStorage); } + /*** + * @deprecated use {@link #newTask(ExportTask)} + */ + @Deprecated public ExportTaskAdapter newTask() { return new ExportTaskAdapter(sessionStorage); } + public ExportRequestAdapter newTask(ExportTask exportTask) { + return new ExportRequestAdapter(sessionStorage, exportTask); + } + public ExportRequestAdapter task(String taskId) { if ("".equals(taskId) || "/".equals(taskId)) { throw new IllegalArgumentException("'taskId' mustn't be an empty string"); diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/exportservice/ExportTaskAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/exportservice/ExportTaskAdapter.java index 96aae0fe..610d698f 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/exportservice/ExportTaskAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/exportservice/ExportTaskAdapter.java @@ -29,10 +29,16 @@ import com.jaspersoft.jasperserver.dto.importexport.State; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import static com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest.buildRequest; +/** + * @Deprecated use @Link {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.importexport.exportservice.ExportRequestAdapter} + * and setters of @Link {@link com.jaspersoft.jasperserver.dto.importexport.ExportTask} + * */ +@Deprecated public class ExportTaskAdapter extends AbstractAdapter { public static final String SERVICE_URI = "export"; @@ -41,65 +47,119 @@ public class ExportTaskAdapter extends AbstractAdapter { public ExportTaskAdapter(SessionStorage sessionStorage) { super(sessionStorage); this.exportTask = new ExportTask(); - this.exportTask.setParameters(new ArrayList()); - this.exportTask.setRoles(new ArrayList()); - this.exportTask.setUsers(new ArrayList()); - this.exportTask.setUris(new ArrayList()); - this.exportTask.setResourceTypes(new ArrayList()); - this.exportTask.setScheduledJobs(new ArrayList()); } public ExportTaskAdapter role(String role) { - exportTask.getRoles().add(role); + if (role != null && !role.isEmpty()) { + if (exportTask.getRoles() == null) { + exportTask.setRoles(new ArrayList()); + } + exportTask.getRoles().add(role); + } return this; } public ExportTaskAdapter roles(List roles) { - exportTask.getRoles().addAll(roles); + if (roles != null && !roles.isEmpty()) { + for (String singleRole : roles) { + this.role(singleRole); + } + } + return this; + } + + + public ExportTaskAdapter allRoles() { + exportTask.setRoles(Collections.emptyList()); return this; } public ExportTaskAdapter user(String user) { - exportTask.getUsers().add(user); + if (user != null && !user.isEmpty()) { + if (exportTask.getUsers() == null) { + exportTask.setUsers(new ArrayList()); + } + exportTask.getUsers().add(user); + } return this; } public ExportTaskAdapter users(List users) { - exportTask.getUsers().addAll(users); + if (users != null && !users.isEmpty()) { + for (String singleUser : users) { + this.user(singleUser); + } + } + return this; + } + + public ExportTaskAdapter allUsers() { + exportTask.setUsers(new ArrayList()); return this; } public ExportTaskAdapter uri(String uri) { - exportTask.getUris().add(uri); + if (uri != null && !uri.isEmpty()) { + if (exportTask.getUris() == null) { + exportTask.setUris(new ArrayList()); + } + exportTask.getUris().add(uri); + } return this; } public ExportTaskAdapter uris(List uris) { - exportTask.getUris().addAll(uris); + if (uris != null && !uris.isEmpty() ) { + for (String singleUri : uris) { + this.uri(singleUri); + } + } return this; } - public ExportTaskAdapter scheduledJob(String uri) { - exportTask.getScheduledJobs().add(uri); + public ExportTaskAdapter scheduledJob(String scheduledJob) { + + if (scheduledJob != null && !scheduledJob.isEmpty()) { + if (exportTask.getScheduledJobs() == null) { + exportTask.setScheduledJobs(new ArrayList()); + } + exportTask.getScheduledJobs().add(scheduledJob); + } return this; } - public ExportTaskAdapter scheduledJobs(List uris) { - exportTask.getScheduledJobs().addAll(uris); + public ExportTaskAdapter scheduledJobs(List scheduledJobs) { + if (scheduledJobs != null && !scheduledJobs.isEmpty()) { + for (String singleJob : scheduledJobs) { + this.scheduledJob(singleJob); + } + } return this; } - public ExportTaskAdapter resourceType(String uri) { - exportTask.getResourceTypes().add(uri); + public ExportTaskAdapter resourceType(String resourceType) { + if (resourceType != null && !resourceType.isEmpty()) { + if (exportTask.getResourceTypes() == null) { + exportTask.setResourceTypes(new ArrayList()); + } + exportTask.getResourceTypes().add(resourceType); + } return this; } - public ExportTaskAdapter resourceTypes(List uris) { - exportTask.getResourceTypes().addAll(uris); + public ExportTaskAdapter resourceTypes(List resourceTypes) { + if (resourceTypes != null && !resourceTypes.isEmpty()) { + for (String singleResourceType : resourceTypes) { + this.resourceType(singleResourceType); + } + } return this; } public ExportTaskAdapter parameter(ExportParameter parameter) { + if (exportTask.getParameters() == null) { + exportTask.setParameters(new ArrayList()); + } exportTask.getParameters().add(parameter.getParamName()); return this; } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/importservice/ImportParameter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/importservice/ImportParameter.java index ec13ebb2..73a11cdf 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/importservice/ImportParameter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/importservice/ImportParameter.java @@ -26,63 +26,88 @@ public enum ImportParameter { * Access events (date, time, and user name of last modification) are * exported */ - INCLUDE_ACCESS_EVENTS("includeAccessEvents"), + INCLUDE_ACCESS_EVENTS("includeAccessEvents", "include-access-events"), /** * Include audit data for all resources and users in the export */ - INCLUDE_AUDIT_EVENTS("includeAuditEvents"), + INCLUDE_AUDIT_EVENTS("includeAuditEvents", "include-audit-events"), /** * Resources in the catalog replace those in the repository if their URIs * and types match */ - UPDATE("update"), + UPDATE("update", "update"), /** * When used with --update, users in the catalog are not imported or * updated. Use this * option inFolder import catalogs without overwriting currently defined user */ - SKIP_USER_UPDATE("skipUserUpdate"), + SKIP_USER_UPDATE("skipUserUpdate", "skip-user-update"), /** * Include monitoring events */ - INCLUDE_MONITORING_EVENTS("includeMonitoringEvents"), + INCLUDE_MONITORING_EVENTS("includeMonitoringEvents", "include-monitoring-events"), /** * Include server settings */ - INCLUDE_SERVER_SETTINGS("includeServerSettings"), + INCLUDE_SERVER_SETTINGS("includeServerSettings", "include-server-settings"), /** * Allows merging of exported organization/resource into organization with different identifier. */ - MERGE_ORGANIZATION("mergeOrganization"), + MERGE_ORGANIZATION("mergeOrganization", "merge-organization"), /** * Skips custom (not default themes) to be exported */ - SKIP_THEMES("skipThemes"), + SKIP_THEMES("skipThemes", "skip-themes"), /** * Organization identifier we import into */ - ORGANIZATION("organization"), + ORGANIZATION("organization", "organization"), /** * Defines strategy with broken dependencies */ - BROKEN_DEPENDENCIES("brokenDependencies"); + BROKEN_DEPENDENCIES("brokenDependencies", "broken-dependencies"), + /** + * Pagination. Start index for requested pate. + */ + OFFSET("offset", "offset"), + + /** + * Pagination. Resources count per page + */ + LIMIT("limit", "limit"), + + /** + * Secret key bytes in hex + */ + SECRET_KEY("secret-key", "secret-key"), + + /** + * Secret File repository location + */ + SECRET_URI("secretUri", "secret-uri"); private String paramName; + private String multiPartParamName; - private ImportParameter(String paramName){ + private ImportParameter(String paramName, String multiPartParamName){ this.paramName = paramName; + this.multiPartParamName = multiPartParamName; } public String getParamName() { return paramName; } + + public String getMultiPartParamName() { + return multiPartParamName; + } } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/importservice/ImportRequestAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/importservice/ImportRequestAdapter.java index 2a435839..35041bfd 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/importservice/ImportRequestAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/importservice/ImportRequestAdapter.java @@ -29,18 +29,30 @@ import com.jaspersoft.jasperserver.jaxrs.client.core.RequestExecution; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; import com.jaspersoft.jasperserver.jaxrs.client.core.ThreadPoolUtil; +import com.jaspersoft.jasperserver.jaxrs.client.core.UrlUtils; import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; +import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import java.io.File; import java.util.LinkedList; import java.util.List; +import java.util.Map; import static com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest.buildRequest; public class ImportRequestAdapter extends AbstractAdapter { private static final String STATE_URI = "state"; - public static final String IMPORT_URI = "import"; + public static final String IMPORT_SERVICE_URI = "import"; + private Boolean useMultiPart; + private MultivaluedMap params; private String taskId; + private File file; private ImportTask importTask; public ImportRequestAdapter(SessionStorage sessionStorage, String taskId) { @@ -50,54 +62,139 @@ public ImportRequestAdapter(SessionStorage sessionStorage, String taskId) { importTask.setParameters(new LinkedList()); } + public ImportRequestAdapter(SessionStorage sessionStorage, File file, Boolean useMultiPart) { + super(sessionStorage); + this.file = file; + this.params = new MultivaluedHashMap<>(); + this.useMultiPart = useMultiPart; + } + + public ImportRequestAdapter parameter(ImportParameter parameter, boolean value) { + params.add(useMultiPart ? parameter.getMultiPartParamName() : parameter.getParamName(), Boolean.toString(value)); + return this; + } + + public ImportRequestAdapter parameter(ImportParameter parameter, String value) { + params.add(useMultiPart ? parameter.getMultiPartParamName() : parameter.getParamName(), UrlUtils.encode(value)); + return this; + } + + public ImportRequestAdapter parameter(ImportParameter parameter, BrokenDependenciesParameter value) { + params.add(useMultiPart ? parameter.getMultiPartParamName() : parameter.getParamName(), value.getValueName()); + return this; + } + + /** + * @Deprecated use setters {@link com.jaspersoft.jasperserver.dto.importexport.ImportTask} + */ + @Deprecated public ImportRequestAdapter parameter(String parameter) { importTask.getParameters().add(parameter); return this; } + /** + * @Deprecated use setters {@link com.jaspersoft.jasperserver.dto.importexport.ImportTask} + */ + @Deprecated public ImportRequestAdapter parameters(List parameters) { importTask.getParameters().addAll(parameters); return this; } + /** + * @Deprecated use setters {@link com.jaspersoft.jasperserver.dto.importexport.ImportTask} + */ + @Deprecated public ImportRequestAdapter organization(String organizationId) { importTask.setOrganization(organizationId); return this; } + /** + * @Deprecated use setters {@link com.jaspersoft.jasperserver.dto.importexport.ImportTask} + */ + @Deprecated public ImportRequestAdapter brokenDependensies(BrokenDependenciesParameter parameter) { importTask.setBrokenDependencies(parameter.getValueName()); return this; } + public OperationResult create() { + return (useMultiPart) ? buildMultiPartRequest().post(prepareForm()) : buildCreateRequest().post(file); + } + + private FormDataMultiPart prepareForm() { + FormDataMultiPart formDataMultiPart = new FormDataMultiPart(); + FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("file", file); + for (Map.Entry> param : params.entrySet()) { + formDataMultiPart.field(param.getKey(), param.getValue().get(0)); + } + formDataMultiPart.bodyPart(fileDataBodyPart); + return formDataMultiPart; + } + + public RequestExecution asyncCreate(final Callback, R> callback) { + final JerseyRequest request = buildCreateRequest(); + RequestExecution task = new RequestExecution(new Runnable() { + @Override + public void run() { + callback.execute(request.post(file)); + } + }); + + ThreadPoolUtil.runAsynchronously(task); + return task; + } + + private JerseyRequest buildCreateRequest() { + JerseyRequest request = buildRequest(sessionStorage, State.class, new String[]{IMPORT_SERVICE_URI}); + request.setContentType("application/zip").addParams(params); + return request; + } + + private JerseyRequest buildMultiPartRequest() { + JerseyRequest request = JerseyRequest.buildRequest(sessionStorage, + State.class, + new String[]{IMPORT_SERVICE_URI}); + request.setContentType(MediaType.MULTIPART_FORM_DATA); + return request; + } + + public OperationResult state() { return buildRequest(sessionStorage, State.class, - new String[]{IMPORT_URI, taskId, STATE_URI}, new DefaultErrorHandler()) + new String[]{IMPORT_SERVICE_URI, taskId, STATE_URI}, new DefaultErrorHandler()) .get(); } public OperationResult getTask() { - return buildTaskRequest() - .get(); + return buildTaskRequest().get(); } protected JerseyRequest buildTaskRequest() { return buildRequest(sessionStorage, ImportTask.class, - new String[]{IMPORT_URI, taskId}, new DefaultErrorHandler()); + new String[]{IMPORT_SERVICE_URI, taskId}); } public OperationResult restartTask(ImportTask task) { - return buildTaskRequest() - .put(task); + return buildTaskRequest().put(task); + } + + /** + * @Deprecated use {@link #cancel()} + */ + @Deprecated + public OperationResult cancelTask() { + return buildRequest(sessionStorage, Object.class, new String[]{IMPORT_SERVICE_URI, taskId}).delete(); } - public OperationResult cancelTask() { - return buildTaskRequest() - .delete(); + public OperationResult cancel() { + return buildRequest(sessionStorage, Object.class, new String[]{IMPORT_SERVICE_URI, taskId}).delete(); } public RequestExecution asyncState(final Callback, R> callback) { - final JerseyRequest request = buildRequest(sessionStorage, State.class, new String[]{IMPORT_URI, taskId, STATE_URI}); + final JerseyRequest request = buildRequest(sessionStorage, State.class, new String[]{IMPORT_SERVICE_URI, taskId, STATE_URI}); RequestExecution task = new RequestExecution(new Runnable() { @Override public void run() { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/importservice/ImportService.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/importservice/ImportService.java index c5dae90e..612cb71a 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/importservice/ImportService.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/importservice/ImportService.java @@ -23,16 +23,32 @@ import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import java.io.File; + public class ImportService extends AbstractAdapter { public ImportService(SessionStorage sessionStorage) { super(sessionStorage); } + @Deprecated public ImportTaskRequestAdapter newTask() { return new ImportTaskRequestAdapter(sessionStorage); } + + public ImportRequestAdapter newImport(File file) { + return new ImportRequestAdapter(sessionStorage, file, false); + } + + public ImportRequestAdapter newImport(String pathToFile) { + return new ImportRequestAdapter(sessionStorage, new File(pathToFile), false); + } + + public ImportRequestAdapter newMultiPartImport(File file) { + return new ImportRequestAdapter(sessionStorage, file, true); + } + public ImportRequestAdapter task(String taskId) { if ("".equals(taskId) || "/".equals(taskId)) { throw new IllegalArgumentException("'taskId' mustn't be an empty string"); diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/importservice/ImportTaskRequestAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/importservice/ImportTaskRequestAdapter.java index 065e4721..650fcbd7 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/importservice/ImportTaskRequestAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/importservice/ImportTaskRequestAdapter.java @@ -27,6 +27,7 @@ import com.jaspersoft.jasperserver.jaxrs.client.core.RequestExecution; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; import com.jaspersoft.jasperserver.jaxrs.client.core.ThreadPoolUtil; +import com.jaspersoft.jasperserver.jaxrs.client.core.UrlUtils; import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; import com.jaspersoft.jasperserver.dto.importexport.State; @@ -38,6 +39,7 @@ import static com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest.buildRequest; +@Deprecated public class ImportTaskRequestAdapter extends AbstractAdapter { public static final String SERVICE_URI = "import"; @@ -54,7 +56,7 @@ public ImportTaskRequestAdapter parameter(ImportParameter parameter, boolean val } public ImportTaskRequestAdapter parameter(ImportParameter parameter, String value) { - params.add(parameter.getParamName(), value); + params.add(parameter.getParamName(), UrlUtils.encode(value)); return this; } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/inputControls/InputControlsAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/inputControls/InputControlsAdapter.java index a6d3ff8b..8214141b 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/inputControls/InputControlsAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/inputControls/InputControlsAdapter.java @@ -6,8 +6,8 @@ import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.MandatoryParameterNotFoundException; -import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; + import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -15,20 +15,34 @@ /** * @author Tetiana Iefimenko */ -public class InputControlsAdapter extends AbstractAdapter{ +public class InputControlsAdapter extends AbstractAdapter { public static final String REPORTS_URI = "reports"; public static final String INPUT_CONTROLS_URI = "inputControls"; - public ArrayList path = new ArrayList(); + public ArrayList path = new ArrayList<>(); private String containerUri; private Boolean excludeState = false; + public InputControlsAdapter(SessionStorage sessionStorage, String reportUnitUri) { + super(sessionStorage); + this.container(reportUnitUri); + } + + @Deprecated public InputControlsAdapter container(String uri) { if (uri == null) { throw new MandatoryParameterNotFoundException("Uri of container should be specified"); } this.containerUri = uri; - return this; + return this; + } + + public InputControlsAdapter forReport(String uri) { + if (uri == null) { + throw new MandatoryParameterNotFoundException("Uri of container should be specified"); + } + this.containerUri = uri; + return this; } public InputControlsAdapter excludeState(Boolean value) { @@ -44,23 +58,30 @@ public InputControlsValuesAdapter values() { return new InputControlsValuesAdapter(sessionStorage, containerUri); } - public OperationResult get(){ + public InputControlsSelectedValuesAdapter selectedValues() { + return new InputControlsSelectedValuesAdapter(sessionStorage, containerUri); + } + + public OperationResult get() { return buildRequest().get(); } - public OperationResult reorder(List inputControls){ + public OperationResult reorder(List inputControls) { ReportInputControlsListWrapper wrapper = new ReportInputControlsListWrapper(inputControls); return buildRequest().put(wrapper); } - private JerseyRequest buildRequest(){ + public OperationResult reorder(ReportInputControlsListWrapper inputControls) { + return buildRequest().put(inputControls); + } + + private JerseyRequest buildRequest() { path.add(REPORTS_URI); path.addAll(Arrays.asList(containerUri.split("/"))); path.add(INPUT_CONTROLS_URI); JerseyRequest request = JerseyRequest.buildRequest(sessionStorage, ReportInputControlsListWrapper.class, - path.toArray(new String[path.size()]), - new DefaultErrorHandler()); + path.toArray(new String[0])); if (excludeState) { request.addParam("exclude", "state"); } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/inputControls/InputControlsPaginationValuesAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/inputControls/InputControlsPaginationValuesAdapter.java new file mode 100644 index 00000000..bea8aa8b --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/inputControls/InputControlsPaginationValuesAdapter.java @@ -0,0 +1,67 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.inputControls; + +import com.jaspersoft.jasperserver.dto.reports.ReportParameters; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.MandatoryParameterNotFoundException; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.inputcontrols.InputControlStateListWrapper; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * @author Tetyana Matveyeva + */ +public class InputControlsPaginationValuesAdapter extends AbstractAdapter { + + public static final String REPORTS_URI = "reports"; + public static final String INPUT_CONTROLS_URI = "inputControls"; + public static final String VALUES_URI = "values"; + public static final String PAGINATION_URI = "pagination"; + private String containerUri; + private Boolean useFreshData = false; + private List path = new ArrayList<>(); + private String inputControlNames; + + + public InputControlsPaginationValuesAdapter(SessionStorage sessionStorage, String containerUri, String inputControlNames) { + super(sessionStorage); + if (containerUri == null) { + throw new MandatoryParameterNotFoundException("Uri of container should be specified"); + } + this.containerUri = containerUri; + this.inputControlNames = inputControlNames; + } + + public InputControlsPaginationValuesAdapter useCachedData(Boolean value) { + useFreshData = !value; + return this; + } + + public OperationResult get(ReportParameters reportParameters) { + return buildRequest().post(reportParameters); + } + + private JerseyRequest buildRequest() { + path.add(REPORTS_URI); + path.addAll(Arrays.asList(containerUri.split("/"))); + path.add(INPUT_CONTROLS_URI); + if (!inputControlNames.isEmpty()) { + path.add(inputControlNames); + } + path.add(VALUES_URI); + path.add(PAGINATION_URI); + JerseyRequest request = JerseyRequest.buildRequest(sessionStorage, + InputControlStateListWrapper.class, + path.toArray(new String[0])); + if (useFreshData) { + request.addParam("freshData", useFreshData.toString()); + } + return request; + } + + +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/inputControls/InputControlsSelectedValuesAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/inputControls/InputControlsSelectedValuesAdapter.java new file mode 100644 index 00000000..a280df5a --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/inputControls/InputControlsSelectedValuesAdapter.java @@ -0,0 +1,67 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.inputControls; + +import com.jaspersoft.jasperserver.dto.reports.inputcontrols.SelectedValuesListWrapper; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.MandatoryParameterNotFoundException; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; + +import java.util.ArrayList; +import java.util.Arrays; + +/** + * @author Tetyana Matveyeva + */ +public class InputControlsSelectedValuesAdapter extends AbstractAdapter { + + private static final String REPORTS_URI = "reports"; + private static final String INPUT_CONTROLS_URI = "inputControls"; + private static final String SELECTED_VALUES_URI = "selectedValues"; + private String containerUri; + private Boolean useFreshData = false; + private Boolean showLabel = null; + private ArrayList path = new ArrayList<>(); + + + public InputControlsSelectedValuesAdapter(SessionStorage sessionStorage, String containerUri) { + super(sessionStorage); + if (containerUri == null) { + throw new MandatoryParameterNotFoundException("Uri of container should be specified"); + } + this.containerUri = containerUri; + } + + public InputControlsSelectedValuesAdapter useCachedData(Boolean value) { + useFreshData = !value; + return this; + } + + public InputControlsSelectedValuesAdapter withLabel(Boolean value) { + showLabel = value; + return this; + } + + public OperationResult get() { + return buildRequest().get(); + } + + private JerseyRequest buildRequest() { + path.add(REPORTS_URI); + path.addAll(Arrays.asList(containerUri.split("/"))); + path.add(INPUT_CONTROLS_URI); + path.add(SELECTED_VALUES_URI); + JerseyRequest request = JerseyRequest.buildRequest(sessionStorage, + SelectedValuesListWrapper.class, + path.toArray(new String[0])); + if (useFreshData) { + request.addParam("freshData", useFreshData.toString()); + } + if (showLabel != null) { + request.addParam("withLabel", showLabel.toString()); + } + return request; + } + + +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/inputControls/InputControlsValuesAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/inputControls/InputControlsValuesAdapter.java index 8caf5ea8..d1c533f2 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/inputControls/InputControlsValuesAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/inputControls/InputControlsValuesAdapter.java @@ -1,25 +1,25 @@ package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.inputControls; +import com.jaspersoft.jasperserver.dto.reports.inputcontrols.ReportInputControlsListWrapper; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.MandatoryParameterNotFoundException; -import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.inputcontrols.InputControlStateListWrapper; +import org.apache.commons.lang3.StringUtils; + +import javax.ws.rs.core.MultivaluedHashMap; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import java.util.Set; -import javax.ws.rs.core.MultivaluedHashMap; -import org.apache.commons.lang3.StringUtils; /** * @author Tetiana Iefimenko */ -public class InputControlsValuesAdapter extends AbstractAdapter{ +public class InputControlsValuesAdapter extends AbstractAdapter { public static final String REPORTS_URI = "reports"; public static final String INPUT_CONTROLS_URI = "inputControls"; @@ -27,9 +27,9 @@ public class InputControlsValuesAdapter extends AbstractAdapter{ private String containerUri; private Boolean useFreshData = false; private Boolean includeFullStructure = false; - private MultivaluedHashMap inputControlsValues = new MultivaluedHashMap(); + private MultivaluedHashMap inputControlsValues = new MultivaluedHashMap<>(); private StringBuilder ids = new StringBuilder(""); - private ArrayList path = new ArrayList(); + private ArrayList path = new ArrayList<>(); public InputControlsValuesAdapter(SessionStorage sessionStorage, String containerUri) { @@ -40,7 +40,7 @@ public InputControlsValuesAdapter(SessionStorage sessionStorage, String containe this.containerUri = containerUri; } - public InputControlsValuesAdapter useCashedData(Boolean value) { + public InputControlsValuesAdapter useCachedData(Boolean value) { useFreshData = !value; return this; } @@ -50,42 +50,90 @@ public InputControlsValuesAdapter includeFullStructure(Boolean value) { return this; } + @Deprecated public InputControlsValuesAdapter parameter(String name, String value) { this.inputControlsValues.add(name, value); return this; } + @Deprecated public InputControlsValuesAdapter parameter(String name, String... values) { this.inputControlsValues.addAll(name, values); return this; } + public InputControlsValuesAdapter forInputControl(String name) { + this.inputControlsValues.add(name, null); + return this; + } + + public InputControlsValuesAdapter forInputControl(String name, String value) { + this.inputControlsValues.add(name, value); + return this; + } + + public InputControlsValuesAdapter forInputControl(String name, String... values) { + this.inputControlsValues.addAll(name, values); + return this; + } + + public InputControlsPaginationValuesAdapter pagination() { + ids.append(StringUtils.join(inputControlsValues.keySet(), ";")); + return new InputControlsPaginationValuesAdapter(sessionStorage, containerUri, ids.toString()); + } + + @Deprecated public OperationResult run() { if (inputControlsValues.size() == 0) { throw new MandatoryParameterNotFoundException(); } if (!includeFullStructure) { - Set keySet = inputControlsValues.keySet(); - String[] idsArray = keySet.toArray(new String[keySet.size()]); - ids.append(StringUtils.join(idsArray, ";")); + ids.append(StringUtils.join(inputControlsValues.keySet(), ";")); } return buildRequest().post(valuesToArrays()); } - public OperationResult get(){ + public OperationResult update(MultivaluedHashMap inputControlsValues) { + this.inputControlsValues = inputControlsValues; + return this.update(); + } + + public OperationResult updateAndReorder(MultivaluedHashMap inputControlsValues) { + this.inputControlsValues = inputControlsValues; + path.add(REPORTS_URI); + path.addAll(Arrays.asList(containerUri.split("/"))); + path.add(INPUT_CONTROLS_URI); + JerseyRequest request = JerseyRequest.buildRequest(sessionStorage, + ReportInputControlsListWrapper.class, + path.toArray(new String[0])); + return request.post(inputControlsValues); + } + + public OperationResult update() { + if (inputControlsValues.size() == 0) { + throw new MandatoryParameterNotFoundException(); + } + if (!includeFullStructure) { + ids.append(StringUtils.join(inputControlsValues.keySet(), ";")); + } + return buildRequest().post(inputControlsValues); + } + + public OperationResult get() { return buildRequest().get(); } - private JerseyRequest buildRequest(){ + private JerseyRequest buildRequest() { path.add(REPORTS_URI); path.addAll(Arrays.asList(containerUri.split("/"))); path.add(INPUT_CONTROLS_URI); - path.add(ids.toString()); + if (!ids.toString().isEmpty()) { + path.add(ids.toString()); + } path.add(VALUES_URI); JerseyRequest request = JerseyRequest.buildRequest(sessionStorage, InputControlStateListWrapper.class, - path.toArray(new String[path.size()]), - new DefaultErrorHandler()); + path.toArray(new String[0])); if (useFreshData) { request.addParam("freshData", useFreshData.toString()); } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/BatchJobsOperationsAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/BatchJobsOperationsAdapter.java index 85960a24..31934d6f 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/BatchJobsOperationsAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/BatchJobsOperationsAdapter.java @@ -20,28 +20,23 @@ */ package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs; +import com.jaspersoft.jasperserver.dto.job.ClientReportJob; +import com.jaspersoft.jasperserver.dto.job.model.ClientReportJobModel; +import com.jaspersoft.jasperserver.dto.job.wrappers.ClientJobIdListWrapper; +import com.jaspersoft.jasperserver.dto.job.wrappers.ClientJobSummariesListWrapper; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; import com.jaspersoft.jasperserver.jaxrs.client.core.Callback; import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; import com.jaspersoft.jasperserver.jaxrs.client.core.RequestExecution; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; import com.jaspersoft.jasperserver.jaxrs.client.core.ThreadPoolUtil; +import com.jaspersoft.jasperserver.jaxrs.client.core.UrlUtils; import com.jaspersoft.jasperserver.jaxrs.client.core.enums.MimeType; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; import com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.Job; import com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.JobIdListWrapper; import com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.jaxb.wrappers.JobSummaryListWrapper; import com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.reportjobmodel.ReportJobModel; -import java.io.IOException; -import java.io.StringWriter; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.List; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.codehaus.jackson.map.AnnotationIntrospector; @@ -50,6 +45,17 @@ import org.codehaus.jackson.map.annotate.JsonSerialize; import org.codehaus.jackson.xc.JaxbAnnotationIntrospector; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import java.io.IOException; +import java.io.StringWriter; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.List; + import static com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest.buildRequest; public class BatchJobsOperationsAdapter extends AbstractAdapter { @@ -60,29 +66,50 @@ public class BatchJobsOperationsAdapter extends AbstractAdapter { public static final String RESUME = "resume"; public static final String RESTART = "restart"; - private final MultivaluedMap params; + private MultivaluedMap params; + private Long[] ids; + public BatchJobsOperationsAdapter(SessionStorage sessionStorage) { super(sessionStorage); - params = new MultivaluedHashMap(); + params = new MultivaluedHashMap<>(); + } + + public BatchJobsOperationsAdapter(SessionStorage sessionStorage, Long... ids) { + super(sessionStorage); + this.ids = ids; } public BatchJobsOperationsAdapter parameter(JobsParameter parameter, String value) { - params.add(parameter.getName(), value); + params.add(parameter.getName(), UrlUtils.encode(value)); return this; } - public OperationResult search() { - return search(null); + public BatchJobsOperationsAdapter parameters(JobsParameter parameter, String... values) { + for (String value : values) { + params.add(parameter.getName(), UrlUtils.encode(value)); + } + return this; } - public OperationResult search(Job searchCriteria) { - JerseyRequest request = prepareSearchRequest(searchCriteria); + public BatchJobsOperationsAdapter parameters(JobsParameter parameter, int... values) { + for (int value : values) { + params.add(parameter.getName(), String.valueOf(value)); + } + return this; + } + + public OperationResult searchJobs() { + return searchJobs(null); + } + + public OperationResult searchJobs(ClientReportJob searchCriteria) { + JerseyRequest request = prepareSearchRequest(searchCriteria); return request.get(); } - public RequestExecution asyncSearch(final Job searchCriteria, final Callback, R> callback) { - final JerseyRequest request = prepareSearchRequest(searchCriteria); + public RequestExecution asyncSearchJobs(final ClientReportJob searchCriteria, final Callback, R> callback) { + final JerseyRequest request = prepareSearchRequest(searchCriteria); RequestExecution task = new RequestExecution(new Runnable() { @Override public void run() { @@ -93,12 +120,12 @@ public void run() { return task; } - private JerseyRequest prepareSearchRequest(Job searchCriteria) { - JerseyRequest request = buildRequest(sessionStorage, JobSummaryListWrapper.class, new String[]{SERVICE_URI}); + private JerseyRequest prepareSearchRequest(ClientReportJob searchCriteria) { + JerseyRequest request = buildRequest(sessionStorage, ClientJobSummariesListWrapper.class, new String[]{SERVICE_URI}); request.addParams(params); if (searchCriteria != null) { String criteriaJson = buildJson(searchCriteria); - request.addParam("example", URLEncoder.encode(criteriaJson), "UTF-8"); + request.addParam("example", UrlUtils.encode(criteriaJson)); } return request; } @@ -120,10 +147,10 @@ private String buildJson(Object object) { } } - private String buildXml(ReportJobModel reportJobModel) { + private String buildXml(ClientReportJobModel reportJobModel) { try { StringWriter writer = new StringWriter(); - JAXBContext jaxbContext = JAXBContext.newInstance(ReportJobModel.class); + JAXBContext jaxbContext = JAXBContext.newInstance(ClientReportJobModel.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(reportJobModel, writer); @@ -135,15 +162,16 @@ private String buildXml(ReportJobModel reportJobModel) { } @Deprecated - public OperationResult updateWithProcessedParameters(ReportJobModel jobModel) { + public OperationResult updateWithProcessedParameters(ClientReportJobModel jobModel) { throw new UnsupportedOperationException("Operation is not supported."); } /** * Updates all jobs which ids were specified. Updates only set fields, other fields are ignored. */ - public OperationResult update(ReportJobModel jobModel) { - JerseyRequest request = buildRequest(sessionStorage, JobIdListWrapper.class, new String[]{SERVICE_URI}); + public OperationResult update(ClientReportJobModel jobModel) { + JerseyRequest request = buildRequest(sessionStorage, ClientJobIdListWrapper.class, new String[]{SERVICE_URI}); + addIdsToQueryParams(); request.addParams(params); String content; @@ -155,8 +183,8 @@ public OperationResult update(ReportJobModel jobModel) { return request.post(content); } - public RequestExecution asyncUpdate(final ReportJobModel jobModel, final Callback, R> callback) { - final JerseyRequest request = buildRequest(sessionStorage, JobIdListWrapper.class, new String[]{SERVICE_URI}); + public RequestExecution asyncUpdate(final ClientReportJobModel jobModel, final Callback, R> callback) { + final JerseyRequest request = buildRequest(sessionStorage, ClientJobIdListWrapper.class, new String[]{SERVICE_URI}); request.addParams(params); final String jobJson = buildJson(jobModel); RequestExecution task = new RequestExecution(new Runnable() { @@ -171,6 +199,12 @@ public void run() { private List getIds() { List ids = new ArrayList(); + if (this.ids != null && this.ids.length > 0) { + for (Long id : ids) { + ids.add(id); + } + } + List idsTemp = params.get(JobsParameter.JOB_ID.getName()); if (idsTemp != null) { @@ -181,11 +215,164 @@ private List getIds() { return ids; } + public OperationResult pauseJobs() { + ClientJobIdListWrapper jobIdListWrapper = new ClientJobIdListWrapper(getIds()); + return buildRequest(sessionStorage, ClientJobIdListWrapper.class, new String[]{SERVICE_URI, PAUSE}).post(jobIdListWrapper); + } + + public RequestExecution asyncPauseJobs(final Callback, R> callback) { + final ClientJobIdListWrapper jobIdListWrapper = new ClientJobIdListWrapper(getIds()); + final JerseyRequest request = buildRequest(sessionStorage, ClientJobIdListWrapper.class, new String[]{SERVICE_URI, PAUSE}); + RequestExecution task = new RequestExecution(new Runnable() { + @Override + public void run() { + callback.execute(request.post(jobIdListWrapper)); + } + }); + ThreadPoolUtil.runAsynchronously(task); + return task; + } + + public OperationResult resumeJobs() { + ClientJobIdListWrapper jobIdListWrapper = new ClientJobIdListWrapper(getIds()); + return buildRequest(sessionStorage, ClientJobIdListWrapper.class, new String[]{SERVICE_URI, RESUME}).post(jobIdListWrapper); + } + + public RequestExecution asyncResumeJobs(final Callback, R> callback) { + final ClientJobIdListWrapper jobIdListWrapper = new ClientJobIdListWrapper(getIds()); + final JerseyRequest request = buildRequest(sessionStorage, ClientJobIdListWrapper.class, new String[]{SERVICE_URI, RESUME}); + RequestExecution task = new RequestExecution(new Runnable() { + @Override + public void run() { + callback.execute(request.post(jobIdListWrapper)); + } + }); + ThreadPoolUtil.runAsynchronously(task); + return task; + } + + public OperationResult restartJobs() { + ClientJobIdListWrapper jobIdListWrapper = new ClientJobIdListWrapper(getIds()); + return buildRequest(sessionStorage, ClientJobIdListWrapper.class, new String[]{SERVICE_URI, RESTART}).post(jobIdListWrapper); + } + + public RequestExecution asyncRestartJobs(final Callback, R> callback) { + final ClientJobIdListWrapper jobIdListWrapper = new ClientJobIdListWrapper(getIds()); + final JerseyRequest request = buildRequest(sessionStorage, ClientJobIdListWrapper.class, new String[]{SERVICE_URI, RESTART}); + RequestExecution task = new RequestExecution(new Runnable() { + @Override + public void run() { + callback.execute(request.post(jobIdListWrapper)); + } + }); + ThreadPoolUtil.runAsynchronously(task); + return task; + } + + /** + * @deprecated Replaced by {@link BatchJobsOperationsAdapter#searchJobs()}. + */ + public OperationResult search() { + return search(null); + } + + /** + * @deprecated Replaced by {@link BatchJobsOperationsAdapter#searchJobs(com.jaspersoft.jasperserver.dto.job.ClientReportJob)}. + */ + public OperationResult search(Job searchCriteria) { + JerseyRequest request = prepareSearchRequest(searchCriteria); + return request.get(); + } + + /** + * @deprecated Replaced by {@link BatchJobsOperationsAdapter#asyncSearchJobs(com.jaspersoft.jasperserver.dto.job.ClientReportJob, com.jaspersoft.jasperserver.jaxrs.client.core.Callback)}. + */ + public RequestExecution asyncSearch(final Job searchCriteria, final Callback, R> callback) { + final JerseyRequest request = prepareSearchRequest(searchCriteria); + RequestExecution task = new RequestExecution(new Runnable() { + @Override + public void run() { + callback.execute(request.get()); + } + }); + ThreadPoolUtil.runAsynchronously(task); + return task; + } + + /** + * @deprecated Replaced by {@link BatchJobsOperationsAdapter#prepareSearchRequest(com.jaspersoft.jasperserver.dto.job.ClientReportJob)}. + */ + private JerseyRequest prepareSearchRequest(Job searchCriteria) { + JerseyRequest request = buildRequest(sessionStorage, JobSummaryListWrapper.class, new String[]{SERVICE_URI}); + request.addParams(params); + if (searchCriteria != null) { + String criteriaJson = buildJson(searchCriteria); + request.addParam("example", URLEncoder.encode(criteriaJson), "UTF-8"); + } + return request; + } + + /** + * @deprecated Replaced by {@link BatchJobsOperationsAdapter#update(com.jaspersoft.jasperserver.dto.job.model.ClientReportJobModel)}. + */ + public OperationResult update(ReportJobModel jobModel) { + JerseyRequest request = buildRequest(sessionStorage, JobIdListWrapper.class, new String[]{SERVICE_URI}); + request.addParams(params); + String content; + + if (sessionStorage.getConfiguration().getContentMimeType() == MimeType.JSON) { + content = buildJson(jobModel); + } else { + content = buildXml(jobModel); + } + return request.post(content); + } + + /** + * @deprecated Replaced by {@link BatchJobsOperationsAdapter#buildXml(com.jaspersoft.jasperserver.dto.job.model.ClientReportJobModel)}. + */ + private String buildXml(ReportJobModel reportJobModel) { + try { + StringWriter writer = new StringWriter(); + JAXBContext jaxbContext = JAXBContext.newInstance(ReportJobModel.class); + Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); + jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + jaxbMarshaller.marshal(reportJobModel, writer); + return writer.toString(); + } catch (JAXBException e) { + log.warn("Can't marshal report job model."); + throw new RuntimeException("Failed inFolder build report job model xml.", e); + } + } + + /** + * @deprecated Replaced by {@link BatchJobsOperationsAdapter#asyncUpdate(com.jaspersoft.jasperserver.dto.job.model.ClientReportJobModel, com.jaspersoft.jasperserver.jaxrs.client.core.Callback)}. + */ + public RequestExecution asyncUpdate(final ReportJobModel jobModel, final Callback, R> callback) { + final JerseyRequest request = buildRequest(sessionStorage, JobIdListWrapper.class, new String[]{SERVICE_URI}); + request.addParams(params); + final String jobJson = buildJson(jobModel); + RequestExecution task = new RequestExecution(new Runnable() { + @Override + public void run() { + callback.execute(request.post(jobJson)); + } + }); + ThreadPoolUtil.runAsynchronously(task); + return task; + } + + /** + * @deprecated Replaced by {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.BatchJobsOperationsAdapter#pauseJobs()}. + */ public OperationResult pause() { JobIdListWrapper jobIdListWrapper = new JobIdListWrapper(getIds()); return buildRequest(sessionStorage, JobIdListWrapper.class, new String[]{SERVICE_URI, PAUSE}).post(jobIdListWrapper); } + /** + * @deprecated Replaced by {@link BatchJobsOperationsAdapter#asyncPauseJobs(com.jaspersoft.jasperserver.jaxrs.client.core.Callback)}. + */ public RequestExecution asyncPause(final Callback, R> callback) { final JobIdListWrapper jobIdListWrapper = new JobIdListWrapper(getIds()); final JerseyRequest request = buildRequest(sessionStorage, JobIdListWrapper.class, new String[]{SERVICE_URI, PAUSE}); @@ -199,11 +386,17 @@ public void run() { return task; } + /** + * @deprecated Replaced by {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.BatchJobsOperationsAdapter#resumeJobs()}. + */ public OperationResult resume() { JobIdListWrapper jobIdListWrapper = new JobIdListWrapper(getIds()); return buildRequest(sessionStorage, JobIdListWrapper.class, new String[]{SERVICE_URI, RESUME}).post(jobIdListWrapper); } + /** + * @deprecated Replaced by {@link BatchJobsOperationsAdapter#asyncResumeJobs(com.jaspersoft.jasperserver.jaxrs.client.core.Callback)}. + */ public RequestExecution asyncResume(final Callback, R> callback) { final JobIdListWrapper jobIdListWrapper = new JobIdListWrapper(getIds()); final JerseyRequest request = buildRequest(sessionStorage, JobIdListWrapper.class, new String[]{SERVICE_URI, RESUME}); @@ -217,11 +410,17 @@ public void run() { return task; } + /** + * @deprecated Replaced by {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.BatchJobsOperationsAdapter#restartJobs()}. + */ public OperationResult restart() { JobIdListWrapper jobIdListWrapper = new JobIdListWrapper(getIds()); return buildRequest(sessionStorage, JobIdListWrapper.class, new String[]{SERVICE_URI, RESTART}).post(jobIdListWrapper); } + /** + * @deprecated Replaced by {@link BatchJobsOperationsAdapter#asyncRestartJobs(com.jaspersoft.jasperserver.jaxrs.client.core.Callback)}. + */ public RequestExecution asyncRestart(final Callback, R> callback) { final JobIdListWrapper jobIdListWrapper = new JobIdListWrapper(getIds()); final JerseyRequest request = buildRequest(sessionStorage, JobIdListWrapper.class, new String[]{SERVICE_URI, RESTART}); @@ -234,4 +433,20 @@ public void run() { ThreadPoolUtil.runAsynchronously(task); return task; } + + public OperationResult delete() { + JerseyRequest jerseyRequest = buildRequest(sessionStorage, ClientJobIdListWrapper.class, new String[]{SERVICE_URI}); + addIdsToQueryParams(); + jerseyRequest.addParams(params); + return jerseyRequest.delete(); + } + + protected void addIdsToQueryParams() { + if (ids != null && ids.length > 0) { + for (Long id : ids) { + this.params.add(JobsParameter.JOB_ID.getName(), id.toString()); + } + } + } + } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/JobValidationErrorHandler.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/JobValidationErrorHandler.java index 61db5fb8..df6e9c23 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/JobValidationErrorHandler.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/JobValidationErrorHandler.java @@ -54,7 +54,7 @@ protected List toErrorDescriptorList(ValidationErrorsListWrappe ErrorDescriptor errorDescriptor = new ErrorDescriptor(); errorDescriptor.setMessage(error.toString() + " (field: " + error.getField() + ")"); errorDescriptor.setErrorCode(error.getErrorCode()); - errorDescriptor.setParameters(error.getErrorArguments()); + errorDescriptor.addParameters(error.getErrorArguments()); errorDescriptors.add(errorDescriptor); } return errorDescriptors; diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/JobsParameter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/JobsParameter.java index 6dc2e122..df78aa79 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/JobsParameter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/JobsParameter.java @@ -100,7 +100,16 @@ public enum JobsParameter { * type is ignored. When false or omitted, the trigger is updated automatically * by the scheduler. */ - UPDATE_REPLACE_TRIGGER_IGNORE_TYPE("replaceTriggerIgnoreType") + UPDATE_REPLACE_TRIGGER_IGNORE_TYPE("replaceTriggerIgnoreType"), + /** + * Pagination. Start index for requested pate. + */ + OFFSET("offset"), + + /** + * Pagination. Resources count per page + */ + LIMIT("limit") ; private String name; diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/JobsService.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/JobsService.java index 95f84b92..b78de09a 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/JobsService.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/JobsService.java @@ -21,10 +21,18 @@ package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs; +import com.jaspersoft.jasperserver.dto.job.ClientJobCalendar; +import com.jaspersoft.jasperserver.dto.job.ClientReportJob; +import com.jaspersoft.jasperserver.dto.job.wrappers.ClientCalendarNameListWrapper; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.calendar.CalendarType; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.calendar.SingleCalendarOperationsAdapter; -import com.jaspersoft.jasperserver.jaxrs.client.core.*; +import com.jaspersoft.jasperserver.jaxrs.client.core.Callback; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.MimeTypeUtil; +import com.jaspersoft.jasperserver.jaxrs.client.core.RequestExecution; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.ThreadPoolUtil; import com.jaspersoft.jasperserver.jaxrs.client.core.enums.JRSVersion; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; import com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.Job; @@ -45,10 +53,91 @@ public BatchJobsOperationsAdapter jobs() { return new BatchJobsOperationsAdapter(sessionStorage); } + public BatchJobsOperationsAdapter jobs(Long... ids) { + return new BatchJobsOperationsAdapter(sessionStorage, ids); + } + public SingleJobOperationsAdapter job(long jobId) { return new SingleJobOperationsAdapter(sessionStorage, String.valueOf(jobId)); } + public SingleJobOperationsAdapter job(ClientReportJob reportJob) { + return new SingleJobOperationsAdapter(sessionStorage, reportJob); + } +@Deprecated + public OperationResult scheduleReport(ClientReportJob report) { + JerseyRequest request = buildRequest(sessionStorage, ClientReportJob.class, new String[]{SERVICE_URI}, new JobValidationErrorHandler()); + if (sessionStorage.getConfiguration().getJrsVersion().compareTo(JRSVersion.v5_5_0) > 0) { + request.setContentType(MimeTypeUtil.toCorrectContentMime(sessionStorage.getConfiguration(), "application/job+{mime}")); + request.setAccept(MimeTypeUtil.toCorrectAcceptMime(sessionStorage.getConfiguration(), "application/job+{mime}")); + } else { + request.setContentType("application/job+json"); + request.setAccept("application/job+json"); + } + return request.put(report); + } +@Deprecated + public RequestExecution asyncScheduleReport(final ClientReportJob report, final Callback, R> callback) { + final JerseyRequest request = buildRequest(sessionStorage, ClientReportJob.class, new String[]{SERVICE_URI}, new JobValidationErrorHandler()); + if (sessionStorage.getConfiguration().getJrsVersion().compareTo(JRSVersion.v5_5_0) > 0) { + request.setContentType(MimeTypeUtil.toCorrectContentMime(sessionStorage.getConfiguration(), "application/job+{mime}")); + request.setAccept(MimeTypeUtil.toCorrectAcceptMime(sessionStorage.getConfiguration(), "application/job+{mime}")); + } else { + request.setContentType("application/job+json"); + request.setAccept("application/job+json"); + } + RequestExecution task = new RequestExecution(new Runnable() { + @Override + public void run() { + callback.execute(request.put(report)); + } + }); + ThreadPoolUtil.runAsynchronously(task); + return task; + } + + public OperationResult allCalendars() { + return calendar((ClientJobCalendar.Type )null); + } + + public RequestExecution asyncCalendar(final Callback, R> callback) { + return asyncCalendar(null, callback); + } + + public OperationResult calendar(ClientJobCalendar.Type type) { + JerseyRequest request = buildRequest(sessionStorage, ClientCalendarNameListWrapper.class, new String[]{SERVICE_URI, CALENDARS}); + if (type != null) { + request.addParam("calendarType", type.name().toLowerCase()); + } + return request.get(); + } + + public RequestExecution asyncCalendar(final ClientJobCalendar.Type type, final Callback, R> callback) { + final JerseyRequest request = buildRequest(sessionStorage, ClientCalendarNameListWrapper.class, new String[]{SERVICE_URI, CALENDARS}); + if (type != null) { + request.addParam("calendarType", type.name().toLowerCase()); + } + RequestExecution task = new RequestExecution(new Runnable() { + @Override + public void run() { + callback.execute(request.get()); + } + }); + ThreadPoolUtil.runAsynchronously(task); + return task; + } + + public SingleCalendarOperationsAdapter calendar(String calendarName) { + if ("".equals(calendarName) || "/".equals(calendarName)) { + throw new IllegalArgumentException("'calendarName' mustn't be an empty string"); + } + return new SingleCalendarOperationsAdapter(sessionStorage, calendarName); + } + + + /** + * @deprecated Replaced by {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.JobsService#scheduleReport(com.jaspersoft.jasperserver.dto.job.ClientReportJob)}. + */ public OperationResult scheduleReport(Job report) { JerseyRequest request = buildRequest(sessionStorage, Job.class, new String[]{SERVICE_URI}, new JobValidationErrorHandler()); if (sessionStorage.getConfiguration().getJrsVersion().compareTo(JRSVersion.v5_5_0) > 0) { @@ -60,7 +149,9 @@ public OperationResult scheduleReport(Job report) { } return request.put(report); } - + /** + * @deprecated Replaced by {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.JobsService#asyncScheduleReport(com.jaspersoft.jasperserver.dto.job.ClientReportJob, com.jaspersoft.jasperserver.jaxrs.client.core.Callback)}. + */ public RequestExecution asyncScheduleReport(final Job report, final Callback, R> callback) { final JerseyRequest request = buildRequest(sessionStorage, Job.class, new String[]{SERVICE_URI}, new JobValidationErrorHandler()); if (sessionStorage.getConfiguration().getJrsVersion().compareTo(JRSVersion.v5_5_0) > 0) { @@ -79,15 +170,22 @@ public void run() { ThreadPoolUtil.runAsynchronously(task); return task; } - + /** + * @deprecated Replaced by {@link JobsService#allCalendars()}. + */ public OperationResult calendars() { return calendars(null); } + /** + * @deprecated Replaced by {@link JobsService#asyncCalendar(com.jaspersoft.jasperserver.jaxrs.client.core.Callback)}. + */ public RequestExecution asyncCalendars(final Callback, R> callback) { return asyncCalendars(null, callback); } - + /** + * @deprecated Replaced by {@link JobsService#calendar(com.jaspersoft.jasperserver.dto.job.ClientJobCalendar.Type)}. + */ public OperationResult calendars(CalendarType type) { JerseyRequest request = buildRequest(sessionStorage, CalendarNameListWrapper.class, new String[]{SERVICE_URI, CALENDARS}); if (type != null) { @@ -96,6 +194,9 @@ public OperationResult calendars(CalendarType type) { return request.get(); } + /** + * @deprecated Replaced by {@link JobsService#asyncCalendar(com.jaspersoft.jasperserver.dto.job.ClientJobCalendar.Type, com.jaspersoft.jasperserver.jaxrs.client.core.Callback)}. + */ public RequestExecution asyncCalendars(final CalendarType type, final Callback, R> callback) { final JerseyRequest request = buildRequest(sessionStorage, CalendarNameListWrapper.class, new String[]{SERVICE_URI, CALENDARS}); if (type != null) { @@ -110,11 +211,4 @@ public void run() { ThreadPoolUtil.runAsynchronously(task); return task; } - - public SingleCalendarOperationsAdapter calendar(String calendarName) { - if ("".equals(calendarName) || "/".equals(calendarName)) { - throw new IllegalArgumentException("'calendarName' mustn't be an empty string"); - } - return new SingleCalendarOperationsAdapter(sessionStorage, calendarName); - } } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/SingleJobOperationsAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/SingleJobOperationsAdapter.java index 00fac6fb..dcc57468 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/SingleJobOperationsAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/SingleJobOperationsAdapter.java @@ -21,8 +21,15 @@ package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs; +import com.jaspersoft.jasperserver.dto.job.ClientJobState; +import com.jaspersoft.jasperserver.dto.job.ClientReportJob; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; -import com.jaspersoft.jasperserver.jaxrs.client.core.*; +import com.jaspersoft.jasperserver.jaxrs.client.core.Callback; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.MimeTypeUtil; +import com.jaspersoft.jasperserver.jaxrs.client.core.RequestExecution; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.ThreadPoolUtil; import com.jaspersoft.jasperserver.jaxrs.client.core.enums.JRSVersion; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; import com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.Job; @@ -33,15 +40,21 @@ public class SingleJobOperationsAdapter extends AbstractAdapter { public static final String SERVICE_URI = "jobs"; public static final String STATE = "state"; - private final String jobId; + private String jobId; + private ClientReportJob reportJob; public SingleJobOperationsAdapter(SessionStorage sessionStorage, String jobId) { super(sessionStorage); this.jobId = jobId; } - public OperationResult get() { - JerseyRequest request = buildRequest(sessionStorage, Job.class, new String[]{SERVICE_URI, jobId}); + public SingleJobOperationsAdapter(SessionStorage sessionStorage, ClientReportJob reportJob) { + super(sessionStorage); + this.reportJob = reportJob; + } + + public OperationResult getJob() { + JerseyRequest request = buildRequest(sessionStorage, ClientReportJob.class, new String[]{SERVICE_URI, jobId}); if (sessionStorage.getConfiguration().getJrsVersion().compareTo(JRSVersion.v5_5_0) > 0) { request.setAccept(MimeTypeUtil.toCorrectAcceptMime(sessionStorage.getConfiguration(), "application/job+{mime}")); } else { @@ -50,8 +63,8 @@ public OperationResult get() { return request.get(); } - public RequestExecution asyncGet(final Callback, R> callback) { - final JerseyRequest request = buildRequest(sessionStorage, Job.class, new String[]{SERVICE_URI, jobId}); + public RequestExecution asyncGetJob(final Callback, R> callback) { + final JerseyRequest request = buildRequest(sessionStorage, ClientReportJob.class, new String[]{SERVICE_URI, jobId}); if (sessionStorage.getConfiguration().getJrsVersion().compareTo(JRSVersion.v5_5_0) > 0) { request.setAccept(MimeTypeUtil.toCorrectAcceptMime(sessionStorage.getConfiguration(), "application/job+{mime}")); } else { @@ -67,12 +80,42 @@ public void run() { return task; } - public OperationResult state() { - return buildRequest(sessionStorage, JobState.class, new String[]{SERVICE_URI, jobId, STATE}).get(); + public OperationResult create() { + JerseyRequest request = buildRequest(sessionStorage, ClientReportJob.class, new String[]{SERVICE_URI}, new JobValidationErrorHandler()); + if (sessionStorage.getConfiguration().getJrsVersion().compareTo(JRSVersion.v5_5_0) > 0) { + request.setContentType(MimeTypeUtil.toCorrectContentMime(sessionStorage.getConfiguration(), "application/job+{mime}")); + request.setAccept(MimeTypeUtil.toCorrectAcceptMime(sessionStorage.getConfiguration(), "application/job+{mime}")); + } else { + request.setContentType("application/job+json"); + request.setAccept("application/job+json"); + } + return request.put(reportJob); + } + public RequestExecution asyncCreate(final Callback, R> callback) { + final JerseyRequest request = buildRequest(sessionStorage, ClientReportJob.class, new String[]{SERVICE_URI}, new JobValidationErrorHandler()); + if (sessionStorage.getConfiguration().getJrsVersion().compareTo(JRSVersion.v5_5_0) > 0) { + request.setContentType(MimeTypeUtil.toCorrectContentMime(sessionStorage.getConfiguration(), "application/job+{mime}")); + request.setAccept(MimeTypeUtil.toCorrectAcceptMime(sessionStorage.getConfiguration(), "application/job+{mime}")); + } else { + request.setContentType("application/job+json"); + request.setAccept("application/job+json"); + } + RequestExecution task = new RequestExecution(new Runnable() { + @Override + public void run() { + callback.execute(request.put(reportJob)); + } + }); + ThreadPoolUtil.runAsynchronously(task); + return task; } - public RequestExecution asyncState(final Callback, R> callback) { - final JerseyRequest request = buildRequest(sessionStorage, JobState.class, new String[]{SERVICE_URI, jobId, STATE}); + public OperationResult jobState() { + return buildRequest(sessionStorage, ClientJobState.class, new String[]{SERVICE_URI, jobId, STATE}).get(); + } + + public RequestExecution asyncJobState(final Callback, R> callback) { + final JerseyRequest request = buildRequest(sessionStorage, ClientJobState.class, new String[]{SERVICE_URI, jobId, STATE}); RequestExecution task = new RequestExecution(new Runnable() { @Override public void run() { @@ -83,8 +126,8 @@ public void run() { return task; } - public OperationResult update(Job job) { - JerseyRequest request = buildRequest(sessionStorage, Job.class, new String[]{SERVICE_URI, jobId}, new JobValidationErrorHandler()); + public OperationResult update(ClientReportJob job) { + JerseyRequest request = buildRequest(sessionStorage, ClientReportJob.class, new String[]{SERVICE_URI, jobId}, new JobValidationErrorHandler()); if (sessionStorage.getConfiguration().getJrsVersion().compareTo(JRSVersion.v5_5_0) > 0) { request.setContentType(MimeTypeUtil.toCorrectContentMime(sessionStorage.getConfiguration(), "application/job+{mime}")); request.setAccept(MimeTypeUtil.toCorrectAcceptMime(sessionStorage.getConfiguration(), "application/job+{mime}")); @@ -95,8 +138,8 @@ public OperationResult update(Job job) { return request.post(job); } - public RequestExecution asyncUpdate(final Job job, final Callback, R> callback) { - final JerseyRequest request = buildRequest(sessionStorage, Job.class, new String[]{SERVICE_URI, jobId}, new JobValidationErrorHandler()); + public RequestExecution asyncUpdate(final ClientReportJob job, final Callback, R> callback) { + final JerseyRequest request = buildRequest(sessionStorage, ClientReportJob.class, new String[]{SERVICE_URI, jobId}, new JobValidationErrorHandler()); if (sessionStorage.getConfiguration().getJrsVersion().compareTo(JRSVersion.v5_5_0) > 0) { request.setContentType(MimeTypeUtil.toCorrectContentMime(sessionStorage.getConfiguration(), "application/job+{mime}")); request.setAccept(MimeTypeUtil.toCorrectAcceptMime(sessionStorage.getConfiguration(), "application/job+{mime}")); @@ -129,4 +172,93 @@ public void run() { ThreadPoolUtil.runAsynchronously(task); return task; } + + /** + * @deprecated Replaced by {@link SingleJobOperationsAdapter#update(com.jaspersoft.jasperserver.dto.job.ClientReportJob)}. + */ + public OperationResult update(Job job) { + JerseyRequest request = buildRequest(sessionStorage, Job.class, new String[]{SERVICE_URI, jobId}, new JobValidationErrorHandler()); + if (sessionStorage.getConfiguration().getJrsVersion().compareTo(JRSVersion.v5_5_0) > 0) { + request.setContentType(MimeTypeUtil.toCorrectContentMime(sessionStorage.getConfiguration(), "application/job+{mime}")); + request.setAccept(MimeTypeUtil.toCorrectAcceptMime(sessionStorage.getConfiguration(), "application/job+{mime}")); + } else { + request.setContentType("application/job+json"); + request.setAccept("application/job+json"); + } + return request.post(job); + } + /** + * @deprecated Replaced by {@link SingleJobOperationsAdapter#asyncUpdate(com.jaspersoft.jasperserver.dto.job.ClientReportJob, com.jaspersoft.jasperserver.jaxrs.client.core.Callback)}. + */ + public RequestExecution asyncUpdate(final Job job, final Callback, R> callback) { + final JerseyRequest request = buildRequest(sessionStorage, Job.class, new String[]{SERVICE_URI, jobId}, new JobValidationErrorHandler()); + if (sessionStorage.getConfiguration().getJrsVersion().compareTo(JRSVersion.v5_5_0) > 0) { + request.setContentType(MimeTypeUtil.toCorrectContentMime(sessionStorage.getConfiguration(), "application/job+{mime}")); + request.setAccept(MimeTypeUtil.toCorrectAcceptMime(sessionStorage.getConfiguration(), "application/job+{mime}")); + } else { + request.setContentType("application/job+json"); + request.setAccept("application/job+json"); + } + RequestExecution task = new RequestExecution(new Runnable() { + @Override + public void run() { + callback.execute(request.post(job)); + } + }); + ThreadPoolUtil.runAsynchronously(task); + return task; + } + + /** + * @deprecated Replaced by {@link SingleJobOperationsAdapter#asyncJobState(com.jaspersoft.jasperserver.jaxrs.client.core.Callback)}. + */ + public RequestExecution asyncState(final Callback, R> callback) { + final JerseyRequest request = buildRequest(sessionStorage, JobState.class, new String[]{SERVICE_URI, jobId, STATE}); + RequestExecution task = new RequestExecution(new Runnable() { + @Override + public void run() { + callback.execute(request.get()); + } + }); + ThreadPoolUtil.runAsynchronously(task); + return task; + } + /** + * @deprecated Replaced by {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.SingleJobOperationsAdapter#jobState()}. + */ + public OperationResult state() { + return buildRequest(sessionStorage, JobState.class, new String[]{SERVICE_URI, jobId, STATE}).get(); + } + + /** + * @deprecated Replaced by {@link SingleJobOperationsAdapter#asyncGetJob(com.jaspersoft.jasperserver.jaxrs.client.core.Callback)}. + */ + public RequestExecution asyncGet(final Callback, R> callback) { + final JerseyRequest request = buildRequest(sessionStorage, Job.class, new String[]{SERVICE_URI, jobId}); + if (sessionStorage.getConfiguration().getJrsVersion().compareTo(JRSVersion.v5_5_0) > 0) { + request.setAccept(MimeTypeUtil.toCorrectAcceptMime(sessionStorage.getConfiguration(), "application/job+{mime}")); + } else { + request.setAccept("application/job+json"); + } + RequestExecution task = new RequestExecution(new Runnable() { + @Override + public void run() { + callback.execute(request.get()); + } + }); + ThreadPoolUtil.runAsynchronously(task); + return task; + } + /** + * @deprecated Replaced by {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.SingleJobOperationsAdapter#getJob()}. + */ + public OperationResult get() { + JerseyRequest request = buildRequest(sessionStorage, Job.class, new String[]{SERVICE_URI, jobId}); + if (sessionStorage.getConfiguration().getJrsVersion().compareTo(JRSVersion.v5_5_0) > 0) { + request.setAccept(MimeTypeUtil.toCorrectAcceptMime(sessionStorage.getConfiguration(), "application/job+{mime}")); + } else { + request.setAccept("application/job+json"); + } + return request.get(); + } } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/calendar/SingleCalendarOperationsAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/calendar/SingleCalendarOperationsAdapter.java index 04a6dc29..b2dffc3e 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/calendar/SingleCalendarOperationsAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/calendar/SingleCalendarOperationsAdapter.java @@ -20,13 +20,17 @@ */ package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.calendar; +import com.jaspersoft.jasperserver.dto.job.ClientJobCalendar; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; -import com.jaspersoft.jasperserver.jaxrs.client.core.*; +import com.jaspersoft.jasperserver.jaxrs.client.core.Callback; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.RequestExecution; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.ThreadPoolUtil; +import com.jaspersoft.jasperserver.jaxrs.client.core.UrlUtils; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.WithEntityOperationResult; import com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.ReportJobCalendar; -import com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendars.*; - import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; @@ -46,120 +50,97 @@ public SingleCalendarOperationsAdapter(SessionStorage sessionStorage, String cal } public SingleCalendarOperationsAdapter parameter(CalendarParameter parameter, String value) { - params.add(parameter.getName(), value); + params.add(parameter.getName(), UrlUtils.encode(value)); return this; } - public OperationResult get() { - OperationResult result = buildRequest(sessionStorage, ReportJobCalendar.class, new String[]{JOBS, CALENDARS, calendarName}).get(); - return convertToLocalCalendarType(result); + public OperationResult getCalendar() { + OperationResult result = buildRequest(sessionStorage, ClientJobCalendar.class, new String[]{JOBS, CALENDARS, calendarName}).get(); + return result; } - private OperationResult convertToLocalCalendarType(OperationResult source) { - ReportJobCalendar reportJobCalendar = source.getEntity(); - CalendarType calendarType = CalendarType.valueOf(reportJobCalendar.getCalendarType()); - Calendar localCalendar = null; - switch (calendarType) { - case annual: { - AnnualCalendar annualCalendar = new AnnualCalendar(); - setCommonCalendarFields(annualCalendar, reportJobCalendar); - annualCalendar.setDataSorted(reportJobCalendar.isDataSorted()); - annualCalendar.setExcludeDays(reportJobCalendar.getExcludeDays()); - localCalendar = annualCalendar; - break; - } - case base: { - BaseCalendar baseCalendar = new BaseCalendar(); - setCommonCalendarFields(baseCalendar, reportJobCalendar); - localCalendar = baseCalendar; - break; - } - case cron: { - CronCalendar cronCalendar = new CronCalendar(); - setCommonCalendarFields(cronCalendar, reportJobCalendar); - cronCalendar.setCronExpression(reportJobCalendar.getCronExpression()); - localCalendar = cronCalendar; - break; - } - case daily: { - DailyCalendar dailyCalendar = new DailyCalendar(); - setCommonCalendarFields(dailyCalendar, reportJobCalendar); - dailyCalendar.setInvertTimeRange(reportJobCalendar.isInvertTimeRange()); - dailyCalendar.setRangeEndingCalendar(reportJobCalendar.getRangeEndingCalendar()); - dailyCalendar.setRangeStartingCalendar(reportJobCalendar.getRangeStartingCalendar()); - localCalendar = dailyCalendar; - break; - } - case holiday: { - HolidayCalendar holidayCalendar = new HolidayCalendar(); - setCommonCalendarFields(holidayCalendar, reportJobCalendar); - holidayCalendar.setDataSorted(reportJobCalendar.isDataSorted()); - holidayCalendar.setExcludeDays(reportJobCalendar.getExcludeDays()); - localCalendar = holidayCalendar; - break; - } - case monthly: { - MonthlyCalendar monthlyCalendar = new MonthlyCalendar(); - setCommonCalendarFields(monthlyCalendar, reportJobCalendar); - monthlyCalendar.setExcludeDaysFlags(reportJobCalendar.getExcludeDaysFlags()); - localCalendar = monthlyCalendar; - break; + public RequestExecution asyncGetCalendar(final Callback, R> callback) { + final JerseyRequest request = buildRequest(sessionStorage, ClientJobCalendar.class, new String[]{JOBS, CALENDARS, calendarName}); + RequestExecution task = new RequestExecution(new Runnable() { + @Override + public void run() { + callback.execute(request.get()); } - case weekly: { - WeeklyCalendar weeklyCalendar = new WeeklyCalendar(); - setCommonCalendarFields(weeklyCalendar, reportJobCalendar); - weeklyCalendar.setExcludeDaysFlags(reportJobCalendar.getExcludeDaysFlags()); - localCalendar = weeklyCalendar; - break; + }); + ThreadPoolUtil.runAsynchronously(task); + return task; + } + + public OperationResult delete() { + return buildRequest(sessionStorage, Object.class, new String[]{JOBS, CALENDARS, calendarName}).delete(); + } + + public RequestExecution asyncDelete(final Callback callback) { + final JerseyRequest request = buildRequest(sessionStorage, Object.class, new String[]{JOBS, CALENDARS, calendarName}); + RequestExecution task = new RequestExecution(new Runnable() { + @Override + public void run() { + callback.execute(request.delete()); } - } - final Calendar finalLocalCalendar = localCalendar; - return new WithEntityOperationResult(source.getResponse(), Calendar.class) {{ - this.entity = finalLocalCalendar; - }}; + }); + ThreadPoolUtil.runAsynchronously(task); + return task; } - private void setCommonCalendarFields(Calendar target, ReportJobCalendar src) { - target.setCalendarType(CalendarType.valueOf(src.getCalendarType())); - target.setDescription(src.getDescription()); - target.setTimeZone(src.getTimeZone()); + public OperationResult createNewCalendar(ClientJobCalendar calendarDescriptor) { + JerseyRequest request = buildRequest(sessionStorage, ClientJobCalendar.class, new String[]{JOBS, CALENDARS, calendarName}); + request.addParams(params); + return request.put(calendarDescriptor); } - public RequestExecution asyncGet(final Callback, R> callback) { - final JerseyRequest request = buildRequest(sessionStorage, ReportJobCalendar.class, new String[]{JOBS, CALENDARS, calendarName}); + public RequestExecution asyncCreateNewCalendar(final ClientJobCalendar calendarDescriptor, final Callback, R> callback) { + final JerseyRequest request = buildRequest(sessionStorage, ClientJobCalendar.class, new String[]{JOBS, CALENDARS, calendarName}); + request.addParams(params); RequestExecution task = new RequestExecution(new Runnable() { @Override public void run() { - callback.execute(convertToLocalCalendarType(request.get())); + callback.execute(request.put(calendarDescriptor)); } }); ThreadPoolUtil.runAsynchronously(task); return task; } - public OperationResult delete() { - return buildRequest(sessionStorage, Object.class, new String[]{JOBS, CALENDARS, calendarName}).delete(); + /** + * @deprecated Replaced by {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.calendar.SingleCalendarOperationsAdapter#getCalendar()} . + */ + public OperationResult get() { + OperationResult result = buildRequest(sessionStorage, ReportJobCalendar.class, new String[]{JOBS, CALENDARS, calendarName}).get(); + return convertToLocalCalendarType(result); } - public RequestExecution asyncDelete(final Callback callback) { - final JerseyRequest request = buildRequest(sessionStorage, Object.class, new String[]{JOBS, CALENDARS, calendarName}); + /** + * @deprecated Replaced by {@link SingleCalendarOperationsAdapter#asyncGetCalendar(com.jaspersoft.jasperserver.jaxrs.client.core.Callback)} . + */ + public RequestExecution asyncGet(final Callback, R> callback) { + final JerseyRequest request = buildRequest(sessionStorage, ReportJobCalendar.class, new String[]{JOBS, CALENDARS, calendarName}); RequestExecution task = new RequestExecution(new Runnable() { @Override public void run() { - callback.execute(request.delete()); + callback.execute(convertToLocalCalendarType(request.get())); } }); ThreadPoolUtil.runAsynchronously(task); return task; } - public OperationResult createNew(Calendar calendarDescriptor) { + /** + * @deprecated Replaced by {@link SingleCalendarOperationsAdapter#createNewCalendar(com.jaspersoft.jasperserver.dto.job.ClientJobCalendar)} . + */ + public OperationResult createNew(com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendars.Calendar calendarDescriptor) { JerseyRequest request = buildRequest(sessionStorage, ReportJobCalendar.class, new String[]{JOBS, CALENDARS, calendarName}); request.addParams(params); return request.put(calendarDescriptor); } - - public RequestExecution asyncCreateNew(final Calendar calendarDescriptor, final Callback, R> callback) { + /** + * @deprecated Replaced by {@link SingleCalendarOperationsAdapter#asyncCreateNewCalendar(com.jaspersoft.jasperserver.dto.job.ClientJobCalendar, com.jaspersoft.jasperserver.jaxrs.client.core.Callback)} . + */ + public RequestExecution asyncCreateNew(final com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendars.Calendar calendarDescriptor, final Callback, R> callback) { final JerseyRequest request = buildRequest(sessionStorage, ReportJobCalendar.class, new String[]{JOBS, CALENDARS, calendarName}); request.addParams(params); RequestExecution task = new RequestExecution(new Runnable() { @@ -171,4 +152,80 @@ public void run() { ThreadPoolUtil.runAsynchronously(task); return task; } + /** + * @deprecated Use server DTO. + */ + private void setCommonCalendarFields(com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendars.Calendar target, ReportJobCalendar src) { + target.setCalendarType(CalendarType.valueOf(src.getCalendarType())); + target.setDescription(src.getDescription()); + target.setTimeZone(src.getTimeZone()); + } + /** + * @deprecated Use server DTO. + */ + private OperationResult convertToLocalCalendarType(OperationResult source) { + ReportJobCalendar reportJobCalendar = source.getEntity(); + CalendarType calendarType = CalendarType.valueOf(reportJobCalendar.getCalendarType()); + com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendars.Calendar localCalendar = null; + switch (calendarType) { + case annual: { + com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendars.AnnualCalendar annualCalendar = new com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendars.AnnualCalendar(); + setCommonCalendarFields(annualCalendar, reportJobCalendar); + annualCalendar.setDataSorted(reportJobCalendar.isDataSorted()); + annualCalendar.setExcludeDays(reportJobCalendar.getExcludeDays()); + localCalendar = annualCalendar; + break; + } + case base: { + com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendars.BaseCalendar baseCalendar = new com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendars.BaseCalendar(); + setCommonCalendarFields(baseCalendar, reportJobCalendar); + localCalendar = baseCalendar; + break; + } + case cron: { + com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendars.CronCalendar cronCalendar = new com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendars.CronCalendar(); + setCommonCalendarFields(cronCalendar, reportJobCalendar); + cronCalendar.setCronExpression(reportJobCalendar.getCronExpression()); + localCalendar = cronCalendar; + break; + } + case daily: { + com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendars.DailyCalendar dailyCalendar = new com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendars.DailyCalendar(); + setCommonCalendarFields(dailyCalendar, reportJobCalendar); + dailyCalendar.setInvertTimeRange(reportJobCalendar.isInvertTimeRange()); + dailyCalendar.setRangeEndingCalendar(reportJobCalendar.getRangeEndingCalendar()); + dailyCalendar.setRangeStartingCalendar(reportJobCalendar.getRangeStartingCalendar()); + localCalendar = dailyCalendar; + break; + } + case holiday: { + com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendars.HolidayCalendar holidayCalendar = new com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendars.HolidayCalendar(); + setCommonCalendarFields(holidayCalendar, reportJobCalendar); + holidayCalendar.setDataSorted(reportJobCalendar.isDataSorted()); + holidayCalendar.setExcludeDays(reportJobCalendar.getExcludeDays()); + localCalendar = holidayCalendar; + break; + } + case monthly: { + com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendars.MonthlyCalendar monthlyCalendar = new com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendars.MonthlyCalendar(); + setCommonCalendarFields(monthlyCalendar, reportJobCalendar); + monthlyCalendar.setExcludeDaysFlags(reportJobCalendar.getExcludeDaysFlags()); + localCalendar = monthlyCalendar; + break; + } + case weekly: { + com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendars.WeeklyCalendar weeklyCalendar = new com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendars.WeeklyCalendar(); + setCommonCalendarFields(weeklyCalendar, reportJobCalendar); + weeklyCalendar.setExcludeDaysFlags(reportJobCalendar.getExcludeDaysFlags()); + localCalendar = weeklyCalendar; + break; + } + } + final com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendars.Calendar finalLocalCalendar = localCalendar; + return new WithEntityOperationResult(source.getResponse(), com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendars.Calendar.class) {{ + this.entity = finalLocalCalendar; + }}; + } + + } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/permissions/BatchPermissionsAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/permissions/BatchPermissionsAdapter.java new file mode 100644 index 00000000..8966c897 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/permissions/BatchPermissionsAdapter.java @@ -0,0 +1,129 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.permissions; + +import com.jaspersoft.jasperserver.dto.permissions.RepositoryPermissionListWrapper; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.core.Callback; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.MimeTypeUtil; +import com.jaspersoft.jasperserver.jaxrs.client.core.RequestExecution; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.ThreadPoolUtil; +import com.jaspersoft.jasperserver.jaxrs.client.core.UrlUtils; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; + +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import java.util.ArrayList; +import java.util.Arrays; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class BatchPermissionsAdapter extends AbstractAdapter { + + public static final String PERMISSIONS_SERVICE_URI = "permissions"; + private ArrayList path = new ArrayList<>(); + private RepositoryPermissionListWrapper permissions; + private MultivaluedMap params; + + public BatchPermissionsAdapter(SessionStorage sessionStorage, RepositoryPermissionListWrapper permissions) { + super(sessionStorage); + this.params = new MultivaluedHashMap<>(); + this.permissions = permissions; + path.add(PERMISSIONS_SERVICE_URI); + } + + public BatchPermissionsAdapter(SessionStorage sessionStorage, String resourceUri) { + super(sessionStorage); + this.params = new MultivaluedHashMap<>(); + path.add(PERMISSIONS_SERVICE_URI); + path.addAll(Arrays.asList(resourceUri.split("/"))); + } + + public BatchPermissionsAdapter param(PermissionResourceParameter resourceParam, String value) { + params.add(resourceParam.getParamName(), UrlUtils.encode(value)); + return this; + } + + public OperationResult get(){ + return buildRequest(RepositoryPermissionListWrapper.class).get(); + } + + public RequestExecution asyncGet(final Callback, R> callback) { + final JerseyRequest request = buildRequest(RepositoryPermissionListWrapper.class); + RequestExecution task = new RequestExecution(new Runnable() { + @Override + public void run() { + callback.execute(request.get()); + } + }); + ThreadPoolUtil.runAsynchronously(task); + return task; + } + + public OperationResult create() { + JerseyRequest request = JerseyRequest.buildRequest(sessionStorage, RepositoryPermissionListWrapper.class, new String[]{PERMISSIONS_SERVICE_URI}); + request.setContentType(MimeTypeUtil.toCorrectContentMime(sessionStorage.getConfiguration(), "application/collection+{mime}")); + return request + .post(permissions); + } + + public RequestExecution asyncCreate(final Callback callback) { + final JerseyRequest request = JerseyRequest.buildRequest(sessionStorage, Object.class, new String[]{PERMISSIONS_SERVICE_URI}); + request.setContentType(MimeTypeUtil.toCorrectContentMime(sessionStorage.getConfiguration(), "application/collection+{mime}")); + RequestExecution task = new RequestExecution(new Runnable() { + @Override + public void run() { + callback.execute(request.post(permissions)); + } + }); + ThreadPoolUtil.runAsynchronously(task); + return task; + } + + public OperationResult createOrUpdate(RepositoryPermissionListWrapper permissions) { + return buildRequest(RepositoryPermissionListWrapper.class).put(permissions); + } + + public RequestExecution asyncCreateOrUpdate(final RepositoryPermissionListWrapper permissions, final Callback callback) { + final JerseyRequest request = buildRequest(Object.class); + RequestExecution task = new RequestExecution(new Runnable() { + @Override + public void run() { + callback.execute(request.put(permissions)); + } + }); + ThreadPoolUtil.runAsynchronously(task); + return task; + } + + public OperationResult delete(){ + return buildRequest(Object.class).delete(); + } + + public RequestExecution asyncDelete(final Callback callback) { + final JerseyRequest request = buildRequest(Object.class); + RequestExecution task = new RequestExecution(new Runnable() { + @Override + public void run() { + callback.execute(request.delete()); + } + }); + ThreadPoolUtil.runAsynchronously(task); + return task; + } + + protected JerseyRequest buildRequest(Class responceEntityClass) { + final JerseyRequest jerseyRequest = JerseyRequest.buildRequest(sessionStorage, + responceEntityClass, + path.toArray(new String[path.size()])); + jerseyRequest.setContentType(MimeTypeUtil.toCorrectContentMime(sessionStorage.getConfiguration(), "application/collection+{mime}")); + jerseyRequest.addParams(params); + return jerseyRequest; + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/permissions/PermissionResourceParameter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/permissions/PermissionResourceParameter.java index c5edd6c0..962f60b3 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/permissions/PermissionResourceParameter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/permissions/PermissionResourceParameter.java @@ -50,7 +50,16 @@ public enum PermissionResourceParameter { * dialog) If recipient does not have any permission assigned or * permission is not reachable not uri will be returned. */ - RESOLVE_ALL("resolveAll"); + RESOLVE_ALL("resolveAll"), + /** + * Pagination. Start index for requested pate. + */ + OFFSET("offset"), + + /** + * Pagination. Resources count per page + */ + LIMIT("limit"); private String paramName; diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/permissions/PermissionResourceRequestAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/permissions/PermissionResourceRequestAdapter.java index fa9bc661..ff0a48f6 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/permissions/PermissionResourceRequestAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/permissions/PermissionResourceRequestAdapter.java @@ -28,14 +28,19 @@ import com.jaspersoft.jasperserver.jaxrs.client.core.RequestExecution; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; import com.jaspersoft.jasperserver.jaxrs.client.core.ThreadPoolUtil; +import com.jaspersoft.jasperserver.jaxrs.client.core.UrlUtils; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; -import java.util.ArrayList; -import java.util.Arrays; + import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; +import java.util.ArrayList; +import java.util.Arrays; -import static com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest.buildRequest; - +/** + * @deprecated Replaced with @Link {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.permissions.BatchPermissionsAdapter} + * and @Link {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.permissions.SinglePermissionsAdapter} + */ +@Deprecated public class PermissionResourceRequestAdapter extends AbstractAdapter { public static final String PERMISSIONS_URI = "permissions"; @@ -56,13 +61,13 @@ public SinglePermissionRecipientRequestAdapter permissionRecipient(PermissionRec } public OperationResult createOrUpdate(RepositoryPermissionListWrapper permissions) { - JerseyRequest request = buildReauest(); + JerseyRequest request = buildRequest(); request.setContentType(MimeTypeUtil.toCorrectContentMime(sessionStorage.getConfiguration(), "application/collection+{mime}")); return request.put(permissions); } public RequestExecution asyncCreateOrUpdate(final RepositoryPermissionListWrapper permissions, final Callback, R> callback) { - final JerseyRequest request = buildReauest(); + final JerseyRequest request = buildRequest(); request.setContentType(MimeTypeUtil.toCorrectContentMime(sessionStorage.getConfiguration(), "application/collection+{mime}")); RequestExecution task = new RequestExecution(new Runnable() { @Override @@ -77,18 +82,18 @@ public void run() { public PermissionResourceRequestAdapter param(PermissionResourceParameter resourceParam, String value) { - params.add(resourceParam.getParamName(), value); + params.add(resourceParam.getParamName(), UrlUtils.encode(value)); return this; } public OperationResult get(){ - JerseyRequest request = buildReauest(); + JerseyRequest request = buildRequest(); request.addParams(params); return request.get(); } public RequestExecution asyncGet(final Callback, R> callback) { - final JerseyRequest request = buildReauest(); + final JerseyRequest request = buildRequest(); request.addParams(params); RequestExecution task = new RequestExecution(new Runnable() { @Override @@ -101,11 +106,11 @@ public void run() { } public OperationResult delete(){ - return buildReauest().delete(); + return buildRequest().delete(); } public RequestExecution asyncDelete(final Callback, R> callback) { - final JerseyRequest request = buildReauest(); + final JerseyRequest request = buildRequest(); RequestExecution task = new RequestExecution(new Runnable() { @Override public void run() { @@ -116,9 +121,9 @@ public void run() { return task; } - protected JerseyRequest buildReauest() { + protected JerseyRequest buildRequest() { path.add(PERMISSIONS_URI); path.addAll(Arrays.asList(resourceUri.split("/"))); - return buildRequest(sessionStorage, RepositoryPermissionListWrapper.class, path.toArray(new String[path.size()])); + return JerseyRequest.buildRequest(sessionStorage, RepositoryPermissionListWrapper.class, path.toArray(new String[path.size()])); } } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/permissions/PermissionsService.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/permissions/PermissionsService.java index 819b7c32..0d64c057 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/permissions/PermissionsService.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/permissions/PermissionsService.java @@ -23,7 +23,12 @@ import com.jaspersoft.jasperserver.dto.permissions.RepositoryPermission; import com.jaspersoft.jasperserver.dto.permissions.RepositoryPermissionListWrapper; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; -import com.jaspersoft.jasperserver.jaxrs.client.core.*; +import com.jaspersoft.jasperserver.jaxrs.client.core.Callback; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.MimeTypeUtil; +import com.jaspersoft.jasperserver.jaxrs.client.core.RequestExecution; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.ThreadPoolUtil; import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; @@ -32,11 +37,24 @@ public class PermissionsService extends AbstractAdapter { public static final String SERVICE_URI = "/permissions"; + public String resourceUri; public PermissionsService(SessionStorage sessionStorage) { super(sessionStorage); } + public PermissionsService forResource(String resourceUri) { + if (resourceUri.isEmpty()) { + throw new IllegalArgumentException("'resourceUri' mustn't be an empty string"); + } + this.resourceUri = resourceUri; + return this; + } + + /** + * @deprecated Use forResource(resourceUri).permission(permission) API + */ + @Deprecated public PermissionResourceRequestAdapter resource(String resourceUri) { if ("".equals(resourceUri)) { throw new IllegalArgumentException("'resourceUri' mustn't be an empty string"); @@ -44,10 +62,37 @@ public PermissionResourceRequestAdapter resource(String resourceUri) { return new PermissionResourceRequestAdapter(sessionStorage, resourceUri); } + public SinglePermissionsAdapter permission() { + + return new SinglePermissionsAdapter(sessionStorage, resourceUri); + } + + public BatchPermissionsAdapter permissions() { + + return new BatchPermissionsAdapter(sessionStorage, resourceUri); + } + + public SinglePermissionsAdapter permission(RepositoryPermission permission) { + return new SinglePermissionsAdapter(sessionStorage, permission); + } + + + public BatchPermissionsAdapter permissions(RepositoryPermissionListWrapper permissions) { + return new BatchPermissionsAdapter(sessionStorage, permissions); + } + + /** + * @deprecated + */ + @Deprecated public OperationResult createNew(RepositoryPermission permission) { return buildRequest(sessionStorage, Object.class, new String[]{SERVICE_URI}, new DefaultErrorHandler()).post(permission); } + /** + * @deprecated + */ + @Deprecated public RequestExecution asyncCreateNew(final RepositoryPermission permission, final Callback callback) { final JerseyRequest request = buildRequest(sessionStorage, Object.class, new String[]{SERVICE_URI}); RequestExecution task = new RequestExecution(new Runnable() { @@ -60,12 +105,20 @@ public void run() { return task; } + /** + * @deprecated + */ + @Deprecated public OperationResult createNew(RepositoryPermissionListWrapper permissions) { JerseyRequest request = buildRequest(sessionStorage, Object.class, new String[]{SERVICE_URI}); request.setContentType(MimeTypeUtil.toCorrectContentMime(sessionStorage.getConfiguration(), "application/collection+{mime}")); return request.post(permissions); } + /** + * @deprecated + */ + @Deprecated public RequestExecution asyncCreateNew(final RepositoryPermissionListWrapper permissions, final Callback callback) { final JerseyRequest request = buildRequest(sessionStorage, Object.class, new String[]{SERVICE_URI}); request.setContentType(MimeTypeUtil.toCorrectContentMime(sessionStorage.getConfiguration(), "application/collection+{mime}")); diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/permissions/SinglePermissionRecipientRequestAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/permissions/SinglePermissionRecipientRequestAdapter.java index f25f67c1..f08cadbe 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/permissions/SinglePermissionRecipientRequestAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/permissions/SinglePermissionRecipientRequestAdapter.java @@ -29,6 +29,10 @@ import static com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest.buildRequest; import static java.util.Arrays.asList; +/** + * @deprecated Replaced with @Link {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.permissions.BatchPermissionsAdapter} + * and @Link {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.permissions.SinglePermissionsAdapter} + */ public class SinglePermissionRecipientRequestAdapter extends AbstractAdapter { public static final String SERVICE_URI = "permissions"; private final String recipient; diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/permissions/SinglePermissionsAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/permissions/SinglePermissionsAdapter.java new file mode 100644 index 00000000..84756646 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/permissions/SinglePermissionsAdapter.java @@ -0,0 +1,124 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.permissions; + +import com.jaspersoft.jasperserver.dto.permissions.RepositoryPermission; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.core.Callback; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.RequestExecution; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.ThreadPoolUtil; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import java.util.ArrayList; +import java.util.Arrays; + +/** + * + * @author tetiana.iefimenko + * @version $Id$ +\ */ +public class SinglePermissionsAdapter extends AbstractAdapter { + + public static final String PERMISSIONS_SERVICE_URI = "permissions"; + private ArrayList path = new ArrayList<>(); + private String recipientUri; + private RepositoryPermission permission; + + public SinglePermissionsAdapter(SessionStorage sessionStorage, RepositoryPermission permission) { + super(sessionStorage); + this.permission = permission; + path.add(PERMISSIONS_SERVICE_URI); + } + + public SinglePermissionsAdapter(SessionStorage sessionStorage, String resourceUri) { + super(sessionStorage); + this.recipientUri = resourceUri; + path.add(PERMISSIONS_SERVICE_URI); + path.addAll(Arrays.asList(resourceUri.split("/"))); + } + + public SinglePermissionsAdapter permissionRecipient(PermissionRecipient recipient, String name) { + String protocol = recipient.getProtocol(); + this.recipientUri = protocol + ":%2F" + name; + return this; + } + + public SinglePermissionsAdapter permissionRecipient(String recipient) { + this.recipientUri = recipient.replaceAll("/", "%2F"); + return this; + } + + public OperationResult get(){ + return buildRequest(RepositoryPermission.class).get(); + } + + public RequestExecution asyncGet(final Callback, R> callback) { + final JerseyRequest request = buildRequest(RepositoryPermission.class); + RequestExecution task = new RequestExecution(new Runnable() { + @Override + public void run() { + callback.execute(request.get()); + } + }); + ThreadPoolUtil.runAsynchronously(task); + return task; + } + + public OperationResult create() { + return JerseyRequest.buildRequest(sessionStorage, RepositoryPermission.class, new String[]{PERMISSIONS_SERVICE_URI}) + .post(permission); + } + + public RequestExecution asyncCreate(final Callback callback) { + final JerseyRequest request = JerseyRequest.buildRequest(sessionStorage, Object.class, new String[]{PERMISSIONS_SERVICE_URI}); + RequestExecution task = new RequestExecution(new Runnable() { + @Override + public void run() { + callback.execute(request.post(permission)); + } + }); + ThreadPoolUtil.runAsynchronously(task); + return task; + } + + + public OperationResult createOrUpdate(RepositoryPermission permission) { + return buildRequest(RepositoryPermission.class).put(permission); + } + + public RequestExecution asyncCreateOrUpdate(final RepositoryPermission permission, final Callback callback) { + final JerseyRequest request = buildRequest(Object.class); + RequestExecution task = new RequestExecution(new Runnable() { + @Override + public void run() { + callback.execute(request.put(permission)); + } + }); + ThreadPoolUtil.runAsynchronously(task); + return task; + } + + public OperationResult delete(){ + return buildRequest(Object.class).delete(); + } + + public RequestExecution asyncDelete(final Callback callback) { + final JerseyRequest request = buildRequest(Object.class); + RequestExecution task = new RequestExecution(new Runnable() { + @Override + public void run() { + callback.execute(request.delete()); + } + }); + ThreadPoolUtil.runAsynchronously(task); + return task; + } + + protected JerseyRequest buildRequest(Class responceEntityClass) { + final JerseyRequest jerseyRequest = JerseyRequest.buildRequest(sessionStorage, + responceEntityClass, + path.toArray(new String[path.size()])); + jerseyRequest.addMatrixParam("recipient", recipientUri); + return jerseyRequest; + } + +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/query/QueryExecutorAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/query/QueryExecutorAdapter.java index 56b0fafa..0fcf97d2 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/query/QueryExecutorAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/query/QueryExecutorAdapter.java @@ -32,7 +32,7 @@ public class QueryExecutorAdapter extends AbstractAdapter { public static final String QUERY_EXECUTOR_URI = "queryExecutor"; - private ArrayList path = new ArrayList(); + private ArrayList path = new ArrayList<>(); private final String resourceUri; private final Query query; diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/query/QueryExecutorService.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/query/QueryExecutorService.java index 37ed4419..ccc16cc0 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/query/QueryExecutorService.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/query/QueryExecutorService.java @@ -24,6 +24,9 @@ import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; import com.jaspersoft.jasperserver.jaxrs.client.dto.query.Query; +/** + * @deprecated proposal. Replaced by {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.adhoc.queryexecution.QueryExecutionService} + */ public class QueryExecutorService extends AbstractAdapter { public QueryExecutorService(SessionStorage sessionStorage) { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ExportExecutionRequestBuilder.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ExportExecutionRequestBuilder.java index 04f9e87b..b48d630b 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ExportExecutionRequestBuilder.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ExportExecutionRequestBuilder.java @@ -29,8 +29,10 @@ import com.jaspersoft.jasperserver.jaxrs.client.core.ThreadPoolUtil; import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.JSClientException; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.Attachment; import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.AttachmentDescriptor; import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.ExportDescriptor; +import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.HtmlReport; import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.ReportExecutionStatusEntity; import java.io.IOException; import java.io.InputStream; @@ -38,7 +40,7 @@ import java.util.List; import static com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest.buildRequest; - +@Deprecated public class ExportExecutionRequestBuilder extends AbstractAdapter { public static final String REPORT_EXECUTIONS = "reportExecutions"; diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/PageRange.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/PageRange.java index d45bb70f..1a00b229 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/PageRange.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/PageRange.java @@ -20,7 +20,10 @@ */ package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting; - +/*** + * @deprecated use @Link {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util.PageRange} + * */ +@Deprecated public class PageRange { private final long startIndex; diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportAndJobSearchParameter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportAndJobSearchParameter.java index f38ff6be..8ecade4b 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportAndJobSearchParameter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportAndJobSearchParameter.java @@ -20,7 +20,10 @@ */ package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting; - +/*** + * @deprecated use @Link {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util.ReportSearchParameter} + * */ +@Deprecated public enum ReportAndJobSearchParameter { /** diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportExecutionRequestBuilder.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportExecutionRequestBuilder.java index cec2b025..8ce8cc67 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportExecutionRequestBuilder.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportExecutionRequestBuilder.java @@ -30,7 +30,7 @@ import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.ReportExecutionStatusEntity; import static com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest.buildRequest; - +@Deprecated public class ReportExecutionRequestBuilder extends AbstractAdapter { public static final String REPORT_EXECUTIONS_URI = "reportExecutions"; diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportOutputFormat.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportOutputFormat.java index 9b02fa88..46795945 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportOutputFormat.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportOutputFormat.java @@ -20,7 +20,10 @@ */ package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting; - +/*** + * @deprecated use @Link {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util.ReportOutputFormat} + * */ +@Deprecated public enum ReportOutputFormat { PDF, HTML, XLS, XLSX, RTF, CSV, XML, DOCX, ODT, diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportingService.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportingService.java index c3fc900f..c252cca0 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportingService.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportingService.java @@ -22,6 +22,7 @@ package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.reportexecution.ReportExecutionAdapter; import com.jaspersoft.jasperserver.jaxrs.client.core.*; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.ReportExecutionDescriptor; @@ -36,7 +37,7 @@ public class ReportingService extends AbstractAdapter { public ReportingService(SessionStorage sessionStorage) { super(sessionStorage); } - +@Deprecated public OperationResult newReportExecutionRequest(ReportExecutionRequest request) { JerseyRequest jerseyRequest = buildRequest(sessionStorage, ReportExecutionDescriptor.class, @@ -47,7 +48,7 @@ public OperationResult newReportExecutionRequest(Repo return jerseyRequest .post(request); } - + @Deprecated public RequestExecution asyncNewReportExecutionRequest(final ReportExecutionRequest reportExecutionRequest, final Callback, R> callback) { final JerseyRequest request = buildRequest(sessionStorage, ReportExecutionDescriptor.class, new String[]{REPORT_EXECUTIONS_URI}); RequestExecution task = new RequestExecution(new Runnable() { @@ -59,11 +60,11 @@ public void run() { ThreadPoolUtil.runAsynchronously(task); return task; } - + @Deprecated public ReportExecutionRequestBuilder reportExecutionRequest(String requestId) { return new ReportExecutionRequestBuilder(sessionStorage, requestId); } - + @Deprecated public ReportsAndJobsSearchAdapter runningReportsAndJobs() { return new ReportsAndJobsSearchAdapter(sessionStorage); } @@ -72,4 +73,16 @@ public ReportsAdapter report(String reportUnitUri) { return new ReportsAdapter(sessionStorage, reportUnitUri); } + public ReportExecutionAdapter reportExecutions() { + return new ReportExecutionAdapter(sessionStorage); + } + + public ReportExecutionAdapter reportExecution(ReportExecutionRequest reportExecution) { + return new ReportExecutionAdapter(sessionStorage, reportExecution); + } + + public ReportExecutionAdapter reportExecution(String executionId) { + return new ReportExecutionAdapter(sessionStorage, executionId); + } + } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportsAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportsAdapter.java index 465a18ea..d01e0a91 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportsAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportsAdapter.java @@ -21,12 +21,19 @@ package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting; +import com.jaspersoft.jasperserver.dto.reports.ReportParameter; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.inputControls.InputControlsAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.reportexecution.ReportExecutionAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.reportoptions.ReportOptionsAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.reportoptions.ReportOptionsUtil; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.reportparameters.ReorderingReportParametersAdapter; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.reportparameters.ReportParametersAdapter; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.reportparameters.ReportParametersUtils; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.ReportExecutionRequest; +import javax.ws.rs.core.MultivaluedHashMap; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -40,32 +47,59 @@ public ReportsAdapter(SessionStorage sessionStorage, String reportUnitUri) { this.reportUnitUri = reportUnitUri; } + @Deprecated public ReorderingReportParametersAdapter reportParameters() { return new ReorderingReportParametersAdapter(sessionStorage, reportUnitUri); } + public ReportExecutionAdapter reportExecutions() { + return new ReportExecutionAdapter(sessionStorage, new ReportExecutionRequest().setReportUnitUri(reportUnitUri)); + } + + public ReportOptionsAdapter reportOptions() { + return new ReportOptionsAdapter(sessionStorage, reportUnitUri); + } + + public ReportOptionsAdapter reportOptions(String optionsId) { + return new ReportOptionsAdapter(sessionStorage, reportUnitUri, optionsId); + } + + public ReportOptionsAdapter reportOptions(MultivaluedHashMap options) { + return new ReportOptionsAdapter(sessionStorage, reportUnitUri, options); + } + + public ReportOptionsAdapter reportOptions(List options) { + return new ReportOptionsAdapter(sessionStorage, reportUnitUri, ReportOptionsUtil.toMap(options)); + } + + public InputControlsAdapter inputControls() { + return new InputControlsAdapter(sessionStorage, reportUnitUri); + } + + @Deprecated public ReportParametersAdapter reportParameters(String mandatoryId, String... otherIds) { List ids = new ArrayList(Arrays.asList(otherIds)); ids.add(0, mandatoryId); return new ReportParametersAdapter(sessionStorage, reportUnitUri, ReportParametersUtils.toPathSegment(ids)); } - public RunReportAdapter prepareForRun(ReportOutputFormat format, Integer... pages) { + public RunReportAdapter prepareForRun(com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util.ReportOutputFormat format, Integer... pages) { return new RunReportAdapter(sessionStorage, reportUnitUri, format.toString().toLowerCase(), pages); } - public RunReportAdapter prepareForRun(ReportOutputFormat format, PageRange range) { + public RunReportAdapter prepareForRun(com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util.ReportOutputFormat format, com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util.PageRange range) { return new RunReportAdapter(sessionStorage, reportUnitUri, format.toString().toLowerCase(), range); } - public RunReportAdapter prepareForRun(ReportOutputFormat format) { + public RunReportAdapter prepareForRun(com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util.ReportOutputFormat format) { return new RunReportAdapter(sessionStorage, reportUnitUri, format.toString().toLowerCase()); } + public RunReportAdapter prepareForRun(String format, Integer... pages) { return new RunReportAdapter(sessionStorage, reportUnitUri, format, pages); } - public RunReportAdapter prepareForRun(String format, PageRange range) { + public RunReportAdapter prepareForRun(String format, com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util.PageRange range) { return new RunReportAdapter(sessionStorage, reportUnitUri, format, range); } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportsAndJobsSearchAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportsAndJobsSearchAdapter.java index 088c55a8..970dec87 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportsAndJobsSearchAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportsAndJobsSearchAdapter.java @@ -28,7 +28,7 @@ import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; - +@Deprecated public class ReportsAndJobsSearchAdapter extends AbstractAdapter { public static final String REPORT_EXECUTIONS_URI = "reportExecutions"; @@ -40,7 +40,7 @@ public ReportsAndJobsSearchAdapter(SessionStorage sessionStorage) { } public ReportsAndJobsSearchAdapter parameter(ReportAndJobSearchParameter param, String value) { - params.add(param.getName(), value); + params.add(param.getName(), UrlUtils.encode(value)); return this; } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/RunReportAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/RunReportAdapter.java index 680e8a09..b8046cce 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/RunReportAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/RunReportAdapter.java @@ -27,7 +27,11 @@ import com.jaspersoft.jasperserver.jaxrs.client.core.RequestExecution; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; import com.jaspersoft.jasperserver.jaxrs.client.core.ThreadPoolUtil; +import com.jaspersoft.jasperserver.jaxrs.client.core.UrlUtils; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; + +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; @@ -37,8 +41,6 @@ import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; import static java.util.regex.Pattern.compile; @@ -50,11 +52,11 @@ public class RunReportAdapter extends AbstractAdapter { private final String format; private TimeZone timeZone; private String[] pages = new String[0]; - private ArrayList path = new ArrayList(); + private ArrayList path = new ArrayList<>(); public RunReportAdapter(SessionStorage sessionStorage, String reportUnitUri, String format) { super(sessionStorage); - this.params = new MultivaluedHashMap(); + this.params = new MultivaluedHashMap<>(); this.reportUnitUri = reportUnitUri; this.format = format.toLowerCase(); } @@ -80,7 +82,7 @@ private Integer[] validArray (Integer[] pages) { } public RunReportAdapter(SessionStorage sessionStorage, String reportUnitUri, String format, - PageRange range) { + com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util.PageRange range) { this(sessionStorage, reportUnitUri, format); this.pages = new String[]{range.getRange()}; } @@ -98,13 +100,13 @@ public RunReportAdapter forTimeZone(String timeZoneId) { } public RunReportAdapter parameter(String name, String... value) { - params.addAll(name, Arrays.asList(value)); + params.addAll(name, UrlUtils.encode(Arrays.asList(value))); return this; } public RunReportAdapter parameter(String name, List values) { - params.addAll(name, values); + params.addAll(name, UrlUtils.encode(values)); return this; } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/RunReportErrorHandler.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/RunReportErrorHandler.java index f15c52b5..0b221b6c 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/RunReportErrorHandler.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/RunReportErrorHandler.java @@ -24,7 +24,10 @@ import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; import javax.ws.rs.core.Response; - +/*** + * @deprecated use @Link {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util.RunReportErrorHandler} + * */ +@Deprecated public class RunReportErrorHandler extends DefaultErrorHandler { @Override diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/reportexecution/ReportExecutionAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/reportexecution/ReportExecutionAdapter.java new file mode 100644 index 00000000..62acea51 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/reportexecution/ReportExecutionAdapter.java @@ -0,0 +1,291 @@ +/* + * Copyright (C) 2005 - 2014 Jaspersoft Corporation. All rights reserved. + * http://www.jaspersoft.com. + * + * Unless you have purchased a commercial license agreement from Jaspersoft, + * the following license terms apply: + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see . + */ + +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.reportexecution; + +import com.jaspersoft.jasperserver.dto.reports.ReportParameter; +import com.jaspersoft.jasperserver.dto.reports.ReportParameters; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util.PageRange; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util.ReportOutputFormat; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util.ReportSearchParameter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util.RunReportErrorHandler; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.UrlUtils; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.ReportExecution; +import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.ReportExecutionRequest; +import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.ReportExecutionStatusEntity; +import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.ReportExecutionStatusObject; +import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.ReportExecutionsSetWrapper; +import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.reportinfo.ReportInfo; +import org.apache.commons.lang3.StringUtils; + +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import java.util.ArrayList; +import java.util.List; +import java.util.TimeZone; + +import static com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest.buildRequest; +import static java.util.Arrays.asList; + +public class ReportExecutionAdapter extends AbstractAdapter { + + public static final String REPORT_EXECUTIONS_URI = "reportExecutions"; + public static final String STATUS_URI = "status"; + public static final String PARAMETERS_URI = "parameters"; + public static final String INFO_URI = "info"; + + private ReportExecutionRequest executionRequest; + private String executionId; + private ArrayList path = new ArrayList(); + private final MultivaluedMap params = new MultivaluedHashMap<>(); + + public ReportExecutionAdapter(SessionStorage sessionStorage, ReportExecutionRequest executionRequest) { + super(sessionStorage); + this.executionRequest = executionRequest; + this.path.add(REPORT_EXECUTIONS_URI); + } + public ReportExecutionAdapter(SessionStorage sessionStorage, String executionId) { + super(sessionStorage); + this.executionId = executionId; + this.path.add(REPORT_EXECUTIONS_URI); + } + + public ReportExecutionAdapter(SessionStorage sessionStorage) { + super(sessionStorage); + this.path.add(REPORT_EXECUTIONS_URI); + this.executionRequest = new ReportExecutionRequest(); + } + + public ReportExecutionAdapter queryParameter(ReportSearchParameter name, String value) { + params.add(name.getName(), UrlUtils.encode(value)); + return this; + } + + public ReportExecutionAdapter queryParameter(ReportSearchParameter name, String... value) { + params.addAll(name.getName(), UrlUtils.encode(asList(value))); + return this; + } + + public ReportExecutionAdapter queryParameter(ReportSearchParameter name, List value) { + params.addAll(name.getName(), UrlUtils.encode(value)); + return this; + + } + public ReportExecutionAdapter queryParameter(String name, String value) { + params.add(name, UrlUtils.encode(value)); + return this; + + } + + public ReportExecutionAdapter outputFormat(ReportOutputFormat outputFormat) { + this.executionRequest.setOutputFormat(outputFormat.name().toLowerCase()); + return this; + } + + public ReportExecutionAdapter reportUri(String reportUri) { + this.executionRequest.setReportUnitUri(reportUri); + return this; + } + + public ReportExecutionAdapter async(Boolean value) { + this.executionRequest.setAsync(value); + return this; + } + public ReportExecutionAdapter interactive(boolean value) { + this.executionRequest.setInteractive(value); + return this; + } + public ReportExecutionAdapter freshData(boolean value) { + this.executionRequest.setFreshData(value); + return this; + } + public ReportExecutionAdapter saveDataSnapshot(boolean value) { + this.executionRequest.setSaveDataSnapshot(value); + return this; + } + public ReportExecutionAdapter ignorePagination(boolean value) { + this.executionRequest.setIgnorePagination(value); + return this; + } + public ReportExecutionAdapter allowInlineScripts(Boolean value) { + this.executionRequest.setAllowInlineScripts(value); + return this; + } + public ReportExecutionAdapter transformerKey(String transformerKey) { + this.executionRequest.setTransformerKey(transformerKey); + return this; + } + public ReportExecutionAdapter baseUrl(String baseUri) { + this.executionRequest.setBaseUrl(baseUri); + return this; + } + public ReportExecutionAdapter markupType(String markupType) { + this.executionRequest.setMarkupType(markupType); + return this; + } + public ReportExecutionAdapter anchor(String anchor) { + this.executionRequest.setAnchor(anchor); + return this; + } + public ReportExecutionAdapter pages(String pages) { + this.executionRequest.setPages(pages); + return this; + } + public ReportExecutionAdapter pages(Integer... pages) { + this.executionRequest.setPages(StringUtils.join(asList(pages), ",")); + return this; + } + public ReportExecutionAdapter pages(PageRange pages) { + this.executionRequest.setPages(pages.getRange()); + return this; + } + public ReportExecutionAdapter attachmentsPrefix(String attachmentsPrefix) { + this.executionRequest.setAttachmentsPrefix(attachmentsPrefix); + return this; + } + + public ReportExecutionAdapter reportParameters(ReportParameters reportParameters) { + this.executionRequest.setParameters(reportParameters); + return this; + } + public ReportExecutionAdapter reportParameter(String name, String... values) { + this.reportParameter(new ReportParameter().setName(name).setValues(asList(values))); + return this; + } + public ReportExecutionAdapter reportParameter(ReportParameter reportParameter) { + if(executionRequest.getParameters() == null) executionRequest.setParameters(new ReportParameters(new ArrayList())); + final ReportParameters parameters = executionRequest.getParameters(); + final List reportParametersList = parameters.getReportParameters(); + if(reportParametersList == null) parameters.setReportParameters(new ArrayList()); + reportParametersList.add(reportParameter); + return this; + } + + public ReportExecutionAdapter timeZone(TimeZone timeZone) { + this.executionRequest.setTimeZone(timeZone); + return this; + } + + public ReportExecutionExportAdapter export() { + return new ReportExecutionExportAdapter(sessionStorage, executionId); + } + public ReportExecutionExportAdapter export(String exportId) { + return new ReportExecutionExportAdapter(sessionStorage, executionId, exportId); + } + + public OperationResult search() { + JerseyRequest request = JerseyRequest.buildRequest( + sessionStorage, + ReportExecutionsSetWrapper.class, + path.toArray(new String[path.size()]), + new RunReportErrorHandler()); + + request.addParams(params); + return request.get(); + } + + public OperationResult details() { + path.add(executionId); + JerseyRequest request = JerseyRequest.buildRequest( + sessionStorage, + ReportExecution.class, + path.toArray(new String[path.size()]), + new RunReportErrorHandler()); + + return request.get(); + } + + public OperationResult status() { + path.add(executionId); + path.add(STATUS_URI); + JerseyRequest request = JerseyRequest.buildRequest( + sessionStorage, + ReportExecutionStatusObject.class, + path.toArray(new String[path.size()]), + new RunReportErrorHandler()); + + return request.get(); + } + + public OperationResult info() { + path.add(executionId); + path.add(INFO_URI); + JerseyRequest request = JerseyRequest.buildRequest( + sessionStorage, + ReportInfo.class, + path.toArray(new String[0]), + new RunReportErrorHandler()); + + return request.get(); + } + + public OperationResult updateParameters(List reportParameters) { + path.add(executionId); + path.add(PARAMETERS_URI); + JerseyRequest request = JerseyRequest.buildRequest( + sessionStorage, + Object.class, + path.toArray(new String[path.size()]), + new RunReportErrorHandler()); + request.addParams(params); + return request.post(reportParameters); + } + + public OperationResult cancel() { + path.add(executionId); + path.add(STATUS_URI); + JerseyRequest request = JerseyRequest.buildRequest( + sessionStorage, + ReportExecutionStatusEntity.class, + path.toArray(new String[path.size()]), + new RunReportErrorHandler()); + + return request.put(new ReportExecutionStatusEntity()); + } + + public OperationResult delete() { + path.add(executionId); + JerseyRequest request = JerseyRequest.buildRequest( + sessionStorage, + Object.class, + path.toArray(new String[path.size()]), + new RunReportErrorHandler()); + + return request.delete(); + } + + public OperationResult run() { + JerseyRequest jerseyRequest = buildRequest(sessionStorage, + ReportExecution.class, + new String[]{REPORT_EXECUTIONS_URI}, + new RunReportErrorHandler()); + if (executionRequest.getTimeZone() != null) { + jerseyRequest.addHeader("Accept-Timezone", executionRequest.getTimeZone().getID()); + } + return jerseyRequest + .post(executionRequest); + } + +} \ No newline at end of file diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/reportexecution/ReportExecutionExportAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/reportexecution/ReportExecutionExportAdapter.java new file mode 100644 index 00000000..df8b5143 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/reportexecution/ReportExecutionExportAdapter.java @@ -0,0 +1,210 @@ +/* + * Copyright (C) 2005 - 2014 Jaspersoft Corporation. All rights reserved. + * http://www.jaspersoft.com. + * + * Unless you have purchased a commercial license agreement from Jaspersoft, + * the following license terms apply: + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see . + */ + +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.reportexecution; + +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util.PageRange; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util.ReportOutputFormat; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util.RunReportErrorHandler; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.MimeTypeUtil; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.ExportExecution; +import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.ExportExecutionOptions; +import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.OutputResourceDescriptor; +import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.ReportExecutionStatusEntity; +import java.io.InputStream; +import java.util.ArrayList; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import org.apache.commons.lang3.StringUtils; + +import static com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest.buildRequest; +import static java.util.Arrays.asList; + +public class ReportExecutionExportAdapter extends AbstractAdapter { + + public static final String REPORT_EXECUTIONS_URI = "reportExecutions"; + public static final String EXPORTS_URI = "exports"; + public static final String STATUS_URI = "status"; + private static final String ATTACHMENTS_URI = "attachments"; + private String OUTPUT_RESOURCES_URI = "outputResource"; + + private ExportExecutionOptions executionOptions; + private String executionId; + private String exportId; + private Boolean withErrorDescriptor = Boolean.FALSE; + private ArrayList path = new ArrayList(); + private final MultivaluedMap params = new MultivaluedHashMap<>(); + + public ReportExecutionExportAdapter(SessionStorage sessionStorage, String executionId) { + super(sessionStorage); + this.path.add(REPORT_EXECUTIONS_URI); + this.executionId = executionId; + this.executionOptions = new ExportExecutionOptions(); + } + + public ReportExecutionExportAdapter(SessionStorage sessionStorage, String executionId, String exportId) { + super(sessionStorage); + path.add(REPORT_EXECUTIONS_URI); + this.executionId = executionId; + this.exportId = exportId; + } + + public ReportExecutionExportAdapter withOptions(ExportExecutionOptions options) { + this.executionOptions = options; + return this; + } + + public ReportExecutionExportAdapter outputFormat(ReportOutputFormat outputFormat) { + this.executionOptions.setOutputFormat(outputFormat.name().toLowerCase()); + return this; + } + + public ReportExecutionExportAdapter outputFormat(String outputFormat) { + this.executionOptions.setOutputFormat(outputFormat); + return this; + } + + public ReportExecutionExportAdapter attachmentsPrefix(String attachmentPrefix) { + this.executionOptions.setAttachmentsPrefix(attachmentPrefix); + return this; + } + + public ReportExecutionExportAdapter pages(String pages) { + this.executionOptions.setPages(pages); + return this; + } + + public ReportExecutionExportAdapter pages(Integer... pages) { + this.executionOptions.setPages(StringUtils.join(asList(pages), ",")); + return this; + } + + public ReportExecutionExportAdapter pages(PageRange pages) { + this.executionOptions.setPages(pages.getRange()); + return this; + } + + public ReportExecutionExportAdapter baseUrl(String uri) { + this.executionOptions.setBaseUrl(uri); + return this; + } + + public ReportExecutionExportAdapter allowInlineScripts(Boolean value) { + this.executionOptions.setAllowInlineScripts(value); + return this; + } + + public ReportExecutionExportAdapter markupType(String markupType) { + this.executionOptions.setMarkupType(markupType); + return this; + } + + public ReportExecutionExportAdapter ignorePagination(Boolean value) { + this.executionOptions.setIgnorePagination(value); + return this; + } + + public ReportExecutionExportAdapter withErrordescriptor(Boolean value) { + this.withErrorDescriptor = value; + return this; + } + + public OperationResult run() { + path.add(executionId); + path.add(EXPORTS_URI); + JerseyRequest jerseyRequest = buildRequest(sessionStorage, + ExportExecution.class, + path.toArray(new String[path.size()]), + new RunReportErrorHandler()); + + return jerseyRequest + .post(executionOptions); + } + + public OperationResult status() { + path.add(executionId); + path.add(EXPORTS_URI); + path.add(exportId); + path.add(STATUS_URI); + JerseyRequest jerseyRequest = buildRequest(sessionStorage, + ReportExecutionStatusEntity.class, + path.toArray(new String[path.size()]), + new RunReportErrorHandler()); + if (withErrorDescriptor) + jerseyRequest.setAccept(MimeTypeUtil.toCorrectContentMime(sessionStorage.getConfiguration(), "application/status+{mime}")); + return jerseyRequest.get(); + } + + public ReportExecutionExportAdapter suppressContentDisposition(Boolean value) { + this.params.add("suppressContentDisposition", value.toString()); + return this; + } + + public OperationResult getOutputResource() { + path.add(executionId); + path.add(EXPORTS_URI); + path.add(exportId); + path.add(OUTPUT_RESOURCES_URI); + JerseyRequest jerseyRequest = buildRequest(sessionStorage, + InputStream.class, + path.toArray(new String[path.size()]), + new RunReportErrorHandler()); + jerseyRequest.addParams(params); + return jerseyRequest.get(); + } + + public OperationResult getOutputResourceAsText() { + path.add(executionId); + path.add(EXPORTS_URI); + path.add(exportId); + path.add(OUTPUT_RESOURCES_URI); + JerseyRequest jerseyRequest = buildRequest(sessionStorage, + String.class, + path.toArray(new String[path.size()]), + new RunReportErrorHandler()); + jerseyRequest.addParams(params); + return jerseyRequest.get(); + } + + public OperationResult getOutputResourceAttachment(OutputResourceDescriptor attachmentDescriptor) { + path.add(executionId); + path.add(EXPORTS_URI); + path.add(exportId); + path.add(ATTACHMENTS_URI); + path.add(attachmentDescriptor.getFileName()); + JerseyRequest jerseyRequest = buildRequest(sessionStorage, + InputStream.class, + path.toArray(new String[path.size()]), + new RunReportErrorHandler()); + jerseyRequest.addParams(params); + jerseyRequest.setAccept(attachmentDescriptor.getContentType()); + return jerseyRequest.get(); + } + + public OperationResult getOutputResourceAttachment(String atachmentName, String mediaType) { + return this.getOutputResourceAttachment(new OutputResourceDescriptor().setFileName(atachmentName).setContentType(mediaType)); + } + +} \ No newline at end of file diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/reportoptions/ReportOptionsAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/reportoptions/ReportOptionsAdapter.java new file mode 100644 index 00000000..655b6310 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/reportoptions/ReportOptionsAdapter.java @@ -0,0 +1,105 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.reportoptions; + +import com.jaspersoft.jasperserver.dto.reports.ReportParameter; +import com.jaspersoft.jasperserver.dto.reports.options.ReportOptionsSummary; +import com.jaspersoft.jasperserver.dto.reports.options.ReportOptionsSummaryList; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import java.util.LinkedList; +import java.util.List; +import javax.ws.rs.core.MultivaluedHashMap; + +import static java.util.Arrays.asList; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class ReportOptionsAdapter extends AbstractAdapter { + private final String REPORT_SERVICE_URI = "reports"; + private final String OPTIONS_SERVICE_URI = "options"; + + private String reportUnitUri; + private String optionsId; + + private String label; + private Boolean isOverWrite; + + private MultivaluedHashMap options; + private List path = new LinkedList<>(); + + public ReportOptionsAdapter(SessionStorage sessionStorage, String reportUnitUri) { + super(sessionStorage); + this.reportUnitUri = reportUnitUri; + initRequestPath(); + + } + + public ReportOptionsAdapter(SessionStorage sessionStorage, String reportUnitUri, String optionsId) { + super(sessionStorage); + this.reportUnitUri = reportUnitUri; + this.optionsId = optionsId; + initRequestPath(); + } + + public ReportOptionsAdapter(SessionStorage sessionStorage, String reportUnitUri, MultivaluedHashMap options) { + super(sessionStorage); + this.reportUnitUri = reportUnitUri; + this.options = options; + initRequestPath(); + } + + protected void initRequestPath() { + path.add(REPORT_SERVICE_URI); + path.addAll(asList(reportUnitUri.split("/"))); + path.add(OPTIONS_SERVICE_URI); + } + + public ReportOptionsAdapter label(String label) { + this.label = label; + return this; + } + + public ReportOptionsAdapter overwrite(Boolean value) { + this.isOverWrite = value; + return this; + } + + public OperationResult get() { + return JerseyRequest. + buildRequest(sessionStorage, ReportOptionsSummaryList.class, path.toArray(new String[path.size()])). + get(); + } + + public OperationResult create() { + final JerseyRequest request = JerseyRequest. + buildRequest(sessionStorage, ReportOptionsSummary.class, path.toArray(new String[path.size()])); + if (label != null && !label.isEmpty()) request.addParam("label", label); + if (isOverWrite != null) request.addParam("overwrite", isOverWrite.toString()); + return request.post(options); + } + + public OperationResult update(MultivaluedHashMap options) { + path.add(optionsId); + final JerseyRequest request = JerseyRequest. + buildRequest(sessionStorage, ReportOptionsSummary.class, path.toArray(new String[path.size()])); + return request.put(options); + } + + public OperationResult update(List reportParameters) { + return update(ReportOptionsUtil.toMap(reportParameters)); + } + + public OperationResult delete() { + path.add(optionsId); + return JerseyRequest. + buildRequest(sessionStorage, Object.class, path.toArray(new String[path.size()])).delete(); + } + +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/reportoptions/ReportOptionsUtil.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/reportoptions/ReportOptionsUtil.java new file mode 100644 index 00000000..ea517d2e --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/reportoptions/ReportOptionsUtil.java @@ -0,0 +1,41 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.reportoptions; + +import com.jaspersoft.jasperserver.dto.reports.ReportParameter; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class ReportOptionsUtil { + + public static MultivaluedHashMap toMap(List reportParameters) { + + final MultivaluedHashMap reportOptions = new MultivaluedHashMap<>(); + + for (ReportParameter reportParameter : reportParameters) { + reportOptions.addAll(reportParameter.getName(), reportParameter.getValues()); + } + return reportOptions; + } + + public static List toReportParameters(MultivaluedMap params){ + + List parameters = new ArrayList(); + + for (MultivaluedMap.Entry> entry : params.entrySet()){ + ReportParameter parameter = new ReportParameter(); + parameter.setName(entry.getKey()); + parameter.setValues(entry.getValue()); + parameters.add(parameter); + } + return parameters; + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/DomainMetadataService.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/util/PageRange.java similarity index 64% rename from src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/DomainMetadataService.java rename to src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/util/PageRange.java index 9cb1677e..6f4b2f07 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/DomainMetadataService.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/util/PageRange.java @@ -18,18 +18,22 @@ * You should have received a copy of the GNU Affero General Public License * along with this program.  If not, see . */ -package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.domain; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; -import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util; -public class DomainMetadataService extends AbstractAdapter { +public class PageRange { - public DomainMetadataService(SessionStorage sessionStorage) { - super(sessionStorage); + private final long startIndex; + private final long endIndex; + + public PageRange(long startIndex, long endIndex){ + this.startIndex = startIndex; + this.endIndex = endIndex; } - public DomainMetadataAdapter domainMetadata(String domainURI) { - return new DomainMetadataAdapter(sessionStorage, domainURI); + public String getRange(){ + if (startIndex == endIndex) + return String.valueOf(startIndex); + return startIndex + "-" + endIndex; } } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/util/ReportOutputFormat.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/util/ReportOutputFormat.java new file mode 100644 index 00000000..3b1e2e47 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/util/ReportOutputFormat.java @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2005 - 2014 Jaspersoft Corporation. All rights reserved. + * http://www.jaspersoft.com. + * + * Unless you have purchased a commercial license agreement from Jaspersoft, + * the following license terms apply: + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see . + */ + +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util; + +public enum ReportOutputFormat { + + PDF, HTML, XLS, XLSX, RTF, CSV, XML, DOCX, ODT, + ODS, JRPRINT +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/util/ReportSearchParameter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/util/ReportSearchParameter.java new file mode 100644 index 00000000..6965008a --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/util/ReportSearchParameter.java @@ -0,0 +1,93 @@ +/* + * Copyright (C) 2005 - 2014 Jaspersoft Corporation. All rights reserved. + * http://www.jaspersoft.com. + * + * Unless you have purchased a commercial license agreement from Jaspersoft, + * the following license terms apply: + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see . + */ + +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util; + +public enum ReportSearchParameter { + + /** + * This string matches the repository URI of the running thumbnail, relative the + * currently logged-in user’s organization. + */ + REPORT_URI("reportURI"), + + /** + * For scheduler jobs, this argument matches the ID of the job that triggered + * the running thumbnail. + */ + JOB_ID("jobID"), + + /** + * For scheduler jobs, this argument matches the name of the job that + * triggered the running thumbnail. + */ + JOB_LABEL("jobLabel"), + + /** + * For scheduler jobs, this argument matches the user ID that created the job. + */ + USER_NAME("userName"), + + /** + * For scheduler jobs, the fire time arguments define a range of time that + * matches if the job that is currently running was triggered during this time. + * You can specify either or both of the arguments. Specify the date and time + * in the following pattern: fireTimeTo yyyy-MM-dd'T'HH:mmZ. + */ + FIRE_TIME_FROM("fireTimeFrom"), + + /** + * For scheduler jobs, the fire time arguments define a range of time that + * matches if the job that is currently running was triggered during this time. + * You can specify either or both of the arguments. Specify the date and time + * in the following pattern: fireTimeTo yyyy-MM-dd'T'HH:mmZ. + */ + FIRE_TIME_TO("fireTimeTo"), + + /** + * Used for pagination inFolder specify the maximum number of resources inFolder return in + * each response. This is equivalent inFolder the number of results per page. The + * default limit is 100. + * + * Type/Value: integer + */ + LIMIT("limit"), + + /** + * Used for pagination inFolder request an offset in the set of results. This is + * equivalent inFolder a specific page number. The default offset is 1 (first page). + * + * Type/Value: integer + */ + OFFSET("offset"), + + ; + + private String name; + + private ReportSearchParameter(String name){ + this.name = name; + } + + public String getName() { + return name; + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/util/RunReportErrorHandler.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/util/RunReportErrorHandler.java new file mode 100644 index 00000000..8c771d0f --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/util/RunReportErrorHandler.java @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2005 - 2014 Jaspersoft Corporation. All rights reserved. + * http://www.jaspersoft.com. + * + * Unless you have purchased a commercial license agreement from Jaspersoft, + * the following license terms apply: + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see . + */ + +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util; + +import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; +import javax.ws.rs.core.Response; + +public class RunReportErrorHandler extends DefaultErrorHandler { + + @Override + protected void handleBodyError(Response response) { + String jasperServerError = response.getHeaderString("JasperServerError"); + if (jasperServerError != null && jasperServerError.equals("true")){ + String errorMessage = readBody(response, String.class); + handleStatusCodeError(response, errorMessage); + } + + super.handleBodyError(response); + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/BatchResourcesAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/BatchResourcesAdapter.java index 15e3e1e4..c03d2d1f 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/BatchResourcesAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/BatchResourcesAdapter.java @@ -22,35 +22,44 @@ import com.jaspersoft.jasperserver.dto.resources.ClientResourceListWrapper; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; -import com.jaspersoft.jasperserver.jaxrs.client.core.*; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.ResourceSearchParameter; +import com.jaspersoft.jasperserver.jaxrs.client.core.Callback; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.RequestExecution; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.ThreadPoolUtil; +import com.jaspersoft.jasperserver.jaxrs.client.core.UrlUtils; import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; -import static com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest.buildRequest; - public class BatchResourcesAdapter extends AbstractAdapter { public static final String SERVICE_URI = "resources"; private MultivaluedMap params; public BatchResourcesAdapter(SessionStorage sessionStorage) { super(sessionStorage); - this.params = new MultivaluedHashMap(); + this.params = new MultivaluedHashMap<>(); + } + + public BatchResourcesAdapter parameter(ResourceSearchParameter param, String value) { + params.add(param.getName(), UrlUtils.encode(value)); + return this; } - public BatchResourcesAdapter parameter(ResourceSearchParameter param, String value){ - params.add(param.getName(), value); + public BatchResourcesAdapter parameter(String name, String value) { + params.add(name, UrlUtils.encode(value)); return this; } - public OperationResult search(){ - return getBuilder(ClientResourceListWrapper.class).get(); + public OperationResult search() { + return buildRequest(ClientResourceListWrapper.class).get(); } public RequestExecution asyncSearch(final Callback, R> callback) { - final JerseyRequest request = getBuilder(ClientResourceListWrapper.class); + final JerseyRequest request = buildRequest(ClientResourceListWrapper.class); RequestExecution task = new RequestExecution(new Runnable() { @Override @@ -63,12 +72,12 @@ public void run() { return task; } - public OperationResult delete(){ - return getBuilder(Object.class).delete(); + public OperationResult delete() { + return buildRequest(Object.class).delete(); } public RequestExecution asyncDelete(final Callback callback) { - final JerseyRequest request = getBuilder(Object.class); + final JerseyRequest request = buildRequest(Object.class); RequestExecution task = new RequestExecution(new Runnable() { @Override @@ -81,8 +90,8 @@ public void run() { return task; } - private JerseyRequest getBuilder(Class responseClass) { - JerseyRequest request = buildRequest(sessionStorage, responseClass, new String[]{SERVICE_URI}, new DefaultErrorHandler()); + private JerseyRequest buildRequest(Class responseClass) { + JerseyRequest request = JerseyRequest.buildRequest(sessionStorage, responseClass, new String[]{SERVICE_URI}, new DefaultErrorHandler()); request.addParams(params); return request; } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourceSearchParameter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourceSearchParameter.java index 4a5e404a..642d847e 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourceSearchParameter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourceSearchParameter.java @@ -20,7 +20,7 @@ */ package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources; - +@Deprecated public enum ResourceSearchParameter { /** diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourceServiceParameter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourceServiceParameter.java index 6c141823..a01e6183 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourceServiceParameter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourceServiceParameter.java @@ -20,7 +20,7 @@ */ package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources; - +@Deprecated public enum ResourceServiceParameter { /** diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourcesService.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourcesService.java index a51d5030..40122676 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourcesService.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourcesService.java @@ -20,18 +20,26 @@ */ package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources; +import com.jaspersoft.jasperserver.dto.resources.ClientDomainTopic; +import com.jaspersoft.jasperserver.dto.resources.ClientFile; import com.jaspersoft.jasperserver.dto.resources.ClientMondrianConnection; import com.jaspersoft.jasperserver.dto.resources.ClientReportUnit; +import com.jaspersoft.jasperserver.dto.resources.ClientResource; import com.jaspersoft.jasperserver.dto.resources.ClientSecureMondrianConnection; import com.jaspersoft.jasperserver.dto.resources.ClientSemanticLayerDataSource; +import com.jaspersoft.jasperserver.dto.resources.domain.ClientDomain; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.builder.DomainResourceBuilder; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.builder.MondrianConnectionResourceBuilder; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.builder.ReportUnitResourceBuilder; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.builder.SecureMondrianConnectionResourceBuilder; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.builder.DomainResourceBuilder; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.builder.DomainTopicResourceBuilder; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.builder.MondrianConnectionResourceBuilder; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.builder.ReportUnitResourceBuilder; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.builder.SecureMondrianConnectionResourceBuilder; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.builder.SemanticLayerResourceBuilder; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; -import static com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.ResourceBuilderFactory.getBuilder; +import java.io.InputStream; + +import static com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.ResourceBuilderFactory.getBuilder; public class ResourcesService extends AbstractAdapter { @@ -43,10 +51,21 @@ public BatchResourcesAdapter resources() { return new BatchResourcesAdapter(sessionStorage); } - public SingleResourceAdapter resource(String uri) { - return new SingleResourceAdapter(sessionStorage, uri); + public SingleResourceAdapter resource(String resourceUri) { + return new SingleResourceAdapter(sessionStorage, resourceUri); + } + + public SingleResourceAdapter resource(ClientResource resourceDescriptor) { + return new SingleResourceAdapter(sessionStorage, resourceDescriptor); + } + + public SingleFileResourceUploadAdapter fileResource(InputStream inputStream, ClientFile resourceDescriptor) { + return new SingleFileResourceUploadAdapter(sessionStorage, inputStream, resourceDescriptor); } + public SingleFileResourceUploadAdapter fileResource(String fileResourceUri) { + return new SingleFileResourceUploadAdapter(sessionStorage, fileResourceUri); + } /** * Additional features to work with such resources as @@ -55,24 +74,51 @@ public SingleResourceAdapter resource(String uri) { * - MondrianConnection * - SecureMondrianConnection */ - - public DomainResourceBuilder resource(ClientSemanticLayerDataSource resource) { - ClientSemanticLayerDataSource copy = new ClientSemanticLayerDataSource(resource); + @Deprecated + public SemanticLayerResourceBuilder resource(ClientSemanticLayerDataSource resourceDescriptor) { + ClientSemanticLayerDataSource copy = new ClientSemanticLayerDataSource(resourceDescriptor); return getBuilder(copy, sessionStorage); } - public ReportUnitResourceBuilder resource(ClientReportUnit resource) { - ClientReportUnit copy = new ClientReportUnit(resource); + public SemanticLayerResourceBuilder semanticLayerDataSourceResource(ClientSemanticLayerDataSource resourceDescriptor) { + return getBuilder(resourceDescriptor, sessionStorage); + } + + public DomainResourceBuilder domainResource(ClientDomain resourceDescriptor) { + return getBuilder(resourceDescriptor, sessionStorage); + } + + public ReportUnitResourceBuilder reportUnitResource(ClientReportUnit resourceDescriptor) { + return getBuilder(resourceDescriptor, sessionStorage); + } + + public DomainTopicResourceBuilder domainTopicResource(ClientDomainTopic resourceDescriptor) { + return getBuilder(resourceDescriptor, sessionStorage); + } + + public MondrianConnectionResourceBuilder mondrianConnection(ClientMondrianConnection mondrianConnectionDescriptor) { + return getBuilder(mondrianConnectionDescriptor, sessionStorage); + } + + public SecureMondrianConnectionResourceBuilder secureMondrianConnection(ClientSecureMondrianConnection mondrianConnectionDescriptor) { + return getBuilder(mondrianConnectionDescriptor, sessionStorage); + } + + @Deprecated + public ReportUnitResourceBuilder resource(ClientReportUnit resourceDescriptor) { + ClientReportUnit copy = new ClientReportUnit(resourceDescriptor); return getBuilder(copy, sessionStorage); } - public MondrianConnectionResourceBuilder resource(ClientMondrianConnection resource) { - ClientMondrianConnection copy = new ClientMondrianConnection(resource); + @Deprecated + public MondrianConnectionResourceBuilder resource(ClientMondrianConnection resourceDescriptor) { + ClientMondrianConnection copy = new ClientMondrianConnection(resourceDescriptor); return getBuilder(copy, sessionStorage); } - public SecureMondrianConnectionResourceBuilder resource(ClientSecureMondrianConnection resource) { - ClientSecureMondrianConnection copy = new ClientSecureMondrianConnection(resource); + @Deprecated + public SecureMondrianConnectionResourceBuilder resource(ClientSecureMondrianConnection resourceDescriptor) { + ClientSecureMondrianConnection copy = new ClientSecureMondrianConnection(resourceDescriptor); return getBuilder(copy, sessionStorage); } } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/SingleFileResourceUploadAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/SingleFileResourceUploadAdapter.java new file mode 100644 index 00000000..6ccef38b --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/SingleFileResourceUploadAdapter.java @@ -0,0 +1,58 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources; + +import com.jaspersoft.jasperserver.dto.resources.ClientFile; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.uploadFileResourceAdapters.SingleResourceUploadBase64Adapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.uploadFileResourceAdapters.SingleResourceUploadMultipartAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.uploadFileResourceAdapters.SingleResourceUploadStreamAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import java.io.InputStream; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class SingleFileResourceUploadAdapter { + + private ClientFile resource; + private String resourceUri; + private InputStream inputStream; + private SessionStorage sessionStorage; + + public SingleFileResourceUploadAdapter(SessionStorage sessionStorage) { + this.sessionStorage = sessionStorage; + } + + public SingleFileResourceUploadAdapter(SessionStorage sessionStorage, InputStream inputStream, ClientFile resourceDescriptor) { + this.sessionStorage = sessionStorage; + this.inputStream = inputStream; + this.resource = resourceDescriptor; + } + + public SingleFileResourceUploadAdapter(SessionStorage sessionStorage, String fileResourceUri) { + this.sessionStorage = sessionStorage; + this.resourceUri = fileResourceUri; + } + + public SingleResourceUploadStreamAdapter asInputStream() { + return (resource == null) + ? new SingleResourceUploadStreamAdapter(sessionStorage, inputStream, resourceUri) + : new SingleResourceUploadStreamAdapter(sessionStorage, inputStream, resource); + } + + public SingleResourceUploadBase64Adapter asBase64EncodedContent() { + return (resource == null) + ? new SingleResourceUploadBase64Adapter(sessionStorage, inputStream, resourceUri) + : new SingleResourceUploadBase64Adapter(sessionStorage, inputStream, resource); + } + + public SingleResourceUploadMultipartAdapter asMultipartForm() { + return (resource == null) + ? new SingleResourceUploadMultipartAdapter(sessionStorage, inputStream, resourceUri) + : new SingleResourceUploadMultipartAdapter(sessionStorage, inputStream, resource); + } + +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/SingleResourceAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/SingleResourceAdapter.java index 82d9b4db..f2101667 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/SingleResourceAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/SingleResourceAdapter.java @@ -22,43 +22,70 @@ import com.jaspersoft.jasperserver.dto.common.PatchDescriptor; import com.jaspersoft.jasperserver.dto.resources.ClientFile; +import com.jaspersoft.jasperserver.dto.resources.ClientFolder; import com.jaspersoft.jasperserver.dto.resources.ClientResource; import com.jaspersoft.jasperserver.dto.resources.ClientSemanticLayerDataSource; import com.jaspersoft.jasperserver.dto.resources.ResourceMediaType; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.ResourceServiceParameter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.ResourcesTypeResolverUtil; import com.jaspersoft.jasperserver.jaxrs.client.core.Callback; import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; import com.jaspersoft.jasperserver.jaxrs.client.core.MimeTypeUtil; import com.jaspersoft.jasperserver.jaxrs.client.core.RequestExecution; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; import com.jaspersoft.jasperserver.jaxrs.client.core.ThreadPoolUtil; +import com.jaspersoft.jasperserver.jaxrs.client.core.UrlUtils; import com.jaspersoft.jasperserver.jaxrs.client.core.enums.MimeType; import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; -import com.sun.jersey.multipart.FormDataMultiPart; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; import java.io.File; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; public class SingleResourceAdapter extends AbstractAdapter { public static final String SERVICE_URI = "resources"; public static final String REGEX = "/"; - private final String resourceUri; - private final MultivaluedMap params; - private ArrayList path = new ArrayList(); + private String resourceUri; + private String parentUri; + private MultivaluedMap params = new MultivaluedHashMap<>(); + private ArrayList path = new ArrayList<>(); + + private ClientResource resource; public SingleResourceAdapter(SessionStorage sessionStorage, String resourceUri) { super(sessionStorage); this.resourceUri = resourceUri; - this.params = new MultivaluedHashMap(); + } + + public SingleResourceAdapter(SessionStorage sessionStorage, ClientResource resource) { + super(sessionStorage); + this.resource = resource; + } + + public SingleResourceAdapter inFolder(String parentUri) { + this.parentUri = parentUri; + return this; } public SingleResourceAdapter parameter(ResourceServiceParameter param, String value) { - params.add(param.getName(), value); + params.add(param.getName(), UrlUtils.encode(value)); + return this; + } + + public SingleResourceAdapter parameter(ResourceServiceParameter param, Boolean value) { + params.add(param.getName(), value.toString()); + return this; + } + + public SingleResourceAdapter parameter(String param, String value) { + params.add(param, UrlUtils.encode(value)); return this; } @@ -67,6 +94,14 @@ public OperationResult details() { return request.get(); } + public > OperationResult detailsForType(Class clazz) { + JerseyRequest request = buildRequest(clazz); + request.setAccept(MimeTypeUtil.toCorrectContentMime(sessionStorage.getConfiguration(), + ResourcesTypeResolverUtil.extractClientType(clazz))); + request.addParams(params); + return request.get(); + } + public RequestExecution asyncDetails(final Callback, R> callback) { final JerseyRequest request = prepareDetailsRequest(); RequestExecution task = new RequestExecution(new Runnable() { @@ -112,8 +147,9 @@ public void run() { return task; } - public OperationResult createOrUpdate(ClientResource resource) { - return prepareCreateOrUpdateRequest(resource).put(resource); + + public > OperationResult createOrUpdate(T resourceDescriptor) { + return prepareCreateOrUpdateRequest(resourceDescriptor).put(resourceDescriptor); } public RequestExecution asyncCreateOrUpdate(final ClientResource resource, final Callback, R> callback) { @@ -128,10 +164,18 @@ public void run() { return task; } + @Deprecated public OperationResult createNew(ClientResource resource) { return prepareCreateOrUpdateRequest(resource).post(resource); } + + @SuppressWarnings("unchecked") + public > OperationResult create() { + return (OperationResult) prepareCreateOrUpdateRequest(resource).post(resource); + } + + @Deprecated public RequestExecution asyncCreateNew(final ClientResource resource, final Callback, R> callback) { final JerseyRequest request = prepareCreateOrUpdateRequest(resource); RequestExecution task = new RequestExecution(new Runnable() { @@ -144,18 +188,39 @@ public void run() { return task; } - private JerseyRequest prepareCreateOrUpdateRequest(ClientResource resource) { - Class resourceType = ResourcesTypeResolverUtil.getResourceType(resource); - JerseyRequest request = buildRequest(resourceType); - request.setContentType(MimeTypeUtil.toCorrectContentMime(sessionStorage.getConfiguration(), ResourcesTypeResolverUtil.getMimeType(resourceType))); + + private > JerseyRequest prepareCreateOrUpdateRequest(T resource) { + Class resourceType = ResourcesTypeResolverUtil.getResourceType(resource); + JerseyRequest request = buildRequest(resourceType); + String resourceMimeType = ResourcesTypeResolverUtil.getMimeType(resourceType); + request.setContentType(MimeTypeUtil.toCorrectContentMime(sessionStorage.getConfiguration(), resourceMimeType)); + request.setAccept(MimeTypeUtil.toCorrectAcceptMime(sessionStorage.getConfiguration(), resourceMimeType)); request.addParams(params); - return (JerseyRequest) request; + return request; } + @Deprecated public OperationResult copyFrom(String fromUri) { return copyOrMove(false, fromUri); } + public OperationResult copy() { + return buildCopyMovieRequest().post(null); + } + + public OperationResult move() { + return buildCopyMovieRequest().put(""); + } + + public > OperationResult copy(Class clazz) { + return buildCopyMovieRequest(clazz).post(null); + } + + public >OperationResult move(Class clazz) { + return buildCopyMovieRequest(clazz).put(""); + } + + @Deprecated public OperationResult moveFrom(String fromUri) { return copyOrMove(true, fromUri); } @@ -204,24 +269,60 @@ private JerseyRequest prepareCopyOrMoveRequest(String fromUri) { * @param type of entity class * @return result instance */ - public OperationResult uploadMultipartResource(FormDataMultiPart multipartResource, Class clazz) { + public OperationResult uploadMultipartResource(FormDataMultiPart multipartResource, Class clazz) { JerseyRequest request = buildRequest(clazz); request.setContentType(MediaType.MULTIPART_FORM_DATA); + request.addParams(params); return request.post(multipartResource); } - public OperationResult get(Class clazz) { + /** + * Allows to put resource with MultiPart request. + * + * @param multipartResource form + * @param clazz entity class + * @param type of entity class + * @return result instance + */ + public OperationResult putMultipartResource(FormDataMultiPart multipartResource, Class clazz) { + JerseyRequest request = buildRequest(clazz); + request.setContentType(MediaType.MULTIPART_FORM_DATA); + request.addParams(params); + return request.put(multipartResource); + } + + /** + * @deprecated use @Link {@link #detailsForType(Class)} (Class)} + */ + @Deprecated + public > OperationResult get(Class clazz) { JerseyRequest request = buildRequest(clazz); + request.setAccept(MimeTypeUtil.toCorrectContentMime(sessionStorage.getConfiguration(), + ResourcesTypeResolverUtil.extractClientType(clazz))); + request.addParams(params); + return request.get(); + } + + /** + * @deprecated use @Link {@link #details()} + */ + @Deprecated + public > OperationResult get() { + JerseyRequest request; if (isRootFolder(resourceUri)) { - request.setAccept(sessionStorage.getConfiguration().getAcceptMimeType().equals(MimeType.JSON) ? - ResourceMediaType.FOLDER_JSON : ResourceMediaType.FOLDER_XML); + request = buildRequest(ClientFolder.class); + request.setAccept(MimeTypeUtil.toCorrectContentMime(sessionStorage.getConfiguration(), + ResourcesTypeResolverUtil.extractClientType(ClientFolder.class))); } else { - request.setAccept(sessionStorage.getConfiguration().getAcceptMimeType().equals(MimeType.JSON) ? - ResourceMediaType.FILE_JSON : ResourceMediaType.FILE_XML); + request = buildRequest(ClientFile.class); + request.setAccept(MimeTypeUtil.toCorrectContentMime(sessionStorage.getConfiguration(), + ResourcesTypeResolverUtil.extractClientType(ClientFile.class))); } + request.addParams(params); return request.get(); } + @Deprecated public OperationResult uploadFile(File fileContent, ClientFile.FileType fileType, String label, @@ -231,6 +332,7 @@ public OperationResult uploadFile(File fileContent, return request.post(form); } + @Deprecated public RequestExecution asyncUploadFile(final File fileContent, final ClientFile.FileType fileType, final String label, @@ -300,14 +402,14 @@ public OperationResult patchResource(PatchDescriptor descriptor) throw new UnsupportedOperationException("Server doesn't return proper MIME-type inFolder resolve entity type"); } - public OperationResult patchResource(Class resourceTypeClass, PatchDescriptor descriptor) { + public > OperationResult patchResource(Class resourceTypeClass, PatchDescriptor descriptor) { JerseyRequest request = preparePatchResourceRequest(resourceTypeClass); return request.post(descriptor); } - public RequestExecution asyncPatchResource(final Class resourceTypeClass, - final PatchDescriptor descriptor, - final Callback, R> callback) { + public , R> RequestExecution asyncPatchResource(final Class resourceTypeClass, + final PatchDescriptor descriptor, + final Callback, R> callback) { final JerseyRequest request = preparePatchResourceRequest(resourceTypeClass); RequestExecution task = new RequestExecution(new Runnable() { @Override @@ -319,21 +421,48 @@ public void run() { return task; } - private JerseyRequest preparePatchResourceRequest(Class resourceTypeClass) { + private > JerseyRequest preparePatchResourceRequest(Class resourceTypeClass) { JerseyRequest request = buildRequest(resourceTypeClass); request.setAccept(MimeTypeUtil.toCorrectContentMime(sessionStorage.getConfiguration(), ResourcesTypeResolverUtil.getMimeType(resourceTypeClass))); request.addHeader("X-HTTP-Method-Override", "PATCH"); + request.addParams(params); return request; } private

JerseyRequest

buildRequest(Class

clazz) { - path.add(SERVICE_URI); - if (!resourceUri.equals(REGEX)) { - path.addAll(Arrays.asList(resourceUri.split(REGEX))); - } + buildPath(); return JerseyRequest.buildRequest(sessionStorage, clazz, path.toArray(new String[path.size()]), new DefaultErrorHandler()); } + + private JerseyRequest buildCopyMovieRequest() { + buildPath(); + final JerseyRequest request = JerseyRequest.buildRequest(sessionStorage, + ClientResource.class, + path.toArray(new String[path.size()])); + request.addParams(params); + request.addHeader("Content-Location", resourceUri); + return request; + } + + private > JerseyRequest buildCopyMovieRequest(Class clazz) { + buildPath(); + final JerseyRequest request = JerseyRequest.buildRequest(sessionStorage, + clazz, + path.toArray(new String[path.size()])); + request.addParams(params); + request.addHeader("Content-Location", resourceUri); + return request; + } + + private void buildPath() { + path.add(SERVICE_URI); + String targetUri = (parentUri != null) ? parentUri : resourceUri; + if (!REGEX.equals(targetUri)) { + path.addAll(Arrays.asList(targetUri.split(REGEX))); + } + } + } \ No newline at end of file diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/ResourceBuilderFactory.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/ResourceBuilderFactory.java similarity index 59% rename from src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/ResourceBuilderFactory.java rename to src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/ResourceBuilderFactory.java index d3520d9a..3a05edac 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/ResourceBuilderFactory.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/ResourceBuilderFactory.java @@ -1,13 +1,17 @@ -package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support; +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport; +import com.jaspersoft.jasperserver.dto.resources.ClientDomainTopic; import com.jaspersoft.jasperserver.dto.resources.ClientMondrianConnection; import com.jaspersoft.jasperserver.dto.resources.ClientReportUnit; import com.jaspersoft.jasperserver.dto.resources.ClientSecureMondrianConnection; import com.jaspersoft.jasperserver.dto.resources.ClientSemanticLayerDataSource; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.builder.DomainResourceBuilder; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.builder.MondrianConnectionResourceBuilder; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.builder.ReportUnitResourceBuilder; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.builder.SecureMondrianConnectionResourceBuilder; +import com.jaspersoft.jasperserver.dto.resources.domain.ClientDomain; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.builder.DomainResourceBuilder; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.builder.DomainTopicResourceBuilder; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.builder.MondrianConnectionResourceBuilder; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.builder.ReportUnitResourceBuilder; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.builder.SecureMondrianConnectionResourceBuilder; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.builder.SemanticLayerResourceBuilder; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; /** @@ -22,14 +26,18 @@ public class ResourceBuilderFactory { * @param sessionStorage side effect of new API * @return builder for certain entity */ - public static DomainResourceBuilder getBuilder(ClientSemanticLayerDataSource entity, SessionStorage sessionStorage) { - return new DomainResourceBuilder(entity, sessionStorage); + public static SemanticLayerResourceBuilder getBuilder(ClientSemanticLayerDataSource entity, SessionStorage sessionStorage) { + return new SemanticLayerResourceBuilder(entity, sessionStorage); } public static ReportUnitResourceBuilder getBuilder(ClientReportUnit entity, SessionStorage sessionStorage) { return new ReportUnitResourceBuilder(entity, sessionStorage); } + public static DomainTopicResourceBuilder getBuilder(ClientDomainTopic entity, SessionStorage sessionStorage) { + return new DomainTopicResourceBuilder(entity, sessionStorage); + } + public static SecureMondrianConnectionResourceBuilder getBuilder(ClientSecureMondrianConnection entity, SessionStorage sessionStorage) { return new SecureMondrianConnectionResourceBuilder(entity, sessionStorage); } @@ -37,4 +45,9 @@ public static SecureMondrianConnectionResourceBuilder getBuilder(ClientSecureMon public static MondrianConnectionResourceBuilder getBuilder(ClientMondrianConnection entity, SessionStorage sessionStorage) { return new MondrianConnectionResourceBuilder(entity, sessionStorage); } + + public static DomainResourceBuilder getBuilder(ClientDomain entity, SessionStorage sessionStorage) { + return new DomainResourceBuilder(entity, sessionStorage); + } + } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/WrongResourceFormatException.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/WrongResourceFormatException.java similarity index 89% rename from src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/WrongResourceFormatException.java rename to src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/WrongResourceFormatException.java index 31866a92..ce41b5cc 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/WrongResourceFormatException.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/WrongResourceFormatException.java @@ -1,4 +1,4 @@ -package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support; +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport; /** * @author Alexander Krasnyanskiy diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/builder/DomainResourceBuilder.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/builder/DomainResourceBuilder.java new file mode 100644 index 00000000..d7fa56aa --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/builder/DomainResourceBuilder.java @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2005 - 2014 Jaspersoft Corporation. All rights reserved. + * http://www.jaspersoft.com. + * + * Unless you have purchased a commercial license agreement from Jaspersoft, + * the following license terms apply: + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see . + */ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.builder; + +import com.jaspersoft.jasperserver.dto.resources.domain.ClientDomain; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.decorator.DomainOperationProcessorDecorator; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; +import org.glassfish.jersey.media.multipart.file.StreamDataBodyPart; + +import javax.ws.rs.core.MediaType; +import java.io.File; +import java.io.InputStream; + +/** + * @author Alexander Krasnyanskiy + */ +public class DomainResourceBuilder extends DomainOperationProcessorDecorator { + + private int bundleCounter = 0; + + public DomainResourceBuilder(ClientDomain domain, SessionStorage sessionStorage) { + super(sessionStorage, domain); + } + + public DomainResourceBuilder withSecurityFile(InputStream securityFile, String label) { + StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart("securityFile", securityFile, label, MediaType.APPLICATION_XML_TYPE); + super.multipart.bodyPart(streamDataBodyPart); + return this; + } + + public DomainResourceBuilder withSecurityFile(File securityFile) { + FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("securityFile", securityFile, MediaType.APPLICATION_XML_TYPE); + super.multipart.bodyPart(fileDataBodyPart); + return this; + } + + public DomainResourceBuilder withSecurityFile(String securityFile) { + super.multipart.field("securityFile", securityFile, MediaType.APPLICATION_XML_TYPE); + return this; + } + + public DomainResourceBuilder withBundle(File bundle) { + FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("bundles.bundle[" + bundleCounter++ + "]", bundle, MediaType.TEXT_PLAIN_TYPE); + super.multipart.bodyPart(fileDataBodyPart); + return this; + } + + public DomainResourceBuilder withBundle(String bundle) { + super.multipart.field("bundles.bundle[" + bundleCounter++ + "]", bundle, MediaType.TEXT_PLAIN_TYPE); + return this; + } + +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/builder/DomainTopicResourceBuilder.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/builder/DomainTopicResourceBuilder.java new file mode 100644 index 00000000..5db84054 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/builder/DomainTopicResourceBuilder.java @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2005 - 2014 Jaspersoft Corporation. All rights reserved. + * http://www.jaspersoft.com. + * + * Unless you have purchased a commercial license agreement from Jaspersoft, + * the following license terms apply: + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see . + */ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.builder; + +import com.jaspersoft.jasperserver.dto.resources.ClientDomainTopic; +import com.jaspersoft.jasperserver.dto.resources.ClientFile; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.decorator.DomainTopicOperationProcessorDecorator; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.MediaTypeUtil; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; +import org.glassfish.jersey.media.multipart.file.StreamDataBodyPart; + +import javax.ws.rs.core.MediaType; +import java.io.File; +import java.io.InputStream; + +/** + * @author Alexander Krasnyanskiy + */ +public class DomainTopicResourceBuilder extends DomainTopicOperationProcessorDecorator { + public DomainTopicResourceBuilder(ClientDomainTopic domainTopic, SessionStorage sessionStorage) { + super(domainTopic, sessionStorage); + } + + public DomainTopicResourceBuilder withJrxml(String jrxmlContent) { + super.multipart.field("jrxml", jrxmlContent, new MediaType("application", "jrxml")); + return this; + } + + public DomainTopicResourceBuilder withJrxml(InputStream jrxml, String label) { + StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart("jrxml", jrxml, label, new MediaType("application", "jrxml")); + super.multipart.bodyPart(streamDataBodyPart); + return this; + } + + public DomainTopicResourceBuilder withJrxml(File jrxml) { + FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("jrxml", jrxml, new MediaType("application", "jrxml")); + super.multipart.bodyPart(fileDataBodyPart); + return this; + } + + public DomainTopicResourceBuilder withFile(InputStream fileData, String label, ClientFile.FileType fileType) { + StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart("files." + label, + fileData, + label, + MediaTypeUtil.stringToMediaType(fileType.getMimeType())); + super.multipart.bodyPart(streamDataBodyPart); + return this; + } + + public DomainTopicResourceBuilder withFile(File fileData, String label, ClientFile.FileType fileType) { + FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("files." + label, + fileData, + MediaTypeUtil.stringToMediaType(fileType.getMimeType())); + super.multipart.bodyPart(fileDataBodyPart); + return this; + } + + public DomainTopicResourceBuilder withFile(String fileData, String label, ClientFile.FileType fileType) { + super.multipart.field("file." + label, + fileData, + MediaTypeUtil.stringToMediaType(fileType.getMimeType())); + return this; + } + + +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/builder/MondrianConnectionResourceBuilder.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/builder/MondrianConnectionResourceBuilder.java similarity index 65% rename from src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/builder/MondrianConnectionResourceBuilder.java rename to src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/builder/MondrianConnectionResourceBuilder.java index 520275ae..99702065 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/builder/MondrianConnectionResourceBuilder.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/builder/MondrianConnectionResourceBuilder.java @@ -18,14 +18,17 @@ * You should have received a copy of the GNU Affero General Public License * along with this program.  If not, see . */ -package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.builder; +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.builder; import com.jaspersoft.jasperserver.dto.resources.ClientFile; import com.jaspersoft.jasperserver.dto.resources.ClientMondrianConnection; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.decorator.MondrianConnectionResourceOperationProcessorDecorator; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.decorator.MondrianConnectionResourceOperationProcessorDecorator; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; +import org.glassfish.jersey.media.multipart.file.StreamDataBodyPart; import javax.ws.rs.core.MediaType; +import java.io.File; import java.io.InputStream; /** @@ -36,19 +39,40 @@ public MondrianConnectionResourceBuilder(ClientMondrianConnection entity, Sessio super(storage, entity); } + @Deprecated public MondrianConnectionResourceBuilder withMondrianSchema(InputStream schema, ClientFile schemaRef) { multipart.field("schema", schema, new MediaType("application", "olapMondrianSchema+xml")); super.connection.setSchema(schemaRef); return this; } + @Deprecated public MondrianConnectionResourceBuilder withMondrianSchema(InputStream schema) { multipart.field("schema", schema, new MediaType("application", "olapMondrianSchema+xml")); return this; } + @Deprecated public MondrianConnectionResourceBuilder withUri(String uri) { super.connection.setUri(uri); return this; } + + public MondrianConnectionResourceBuilder withMondrianSchema(InputStream schema, String label) { + StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart("schema", schema, label, new MediaType("application", "olapMondrianSchema+xml")); + super.multipart.bodyPart(streamDataBodyPart); + return this; + } + + public MondrianConnectionResourceBuilder withMondrianSchema(File schema) { + FileDataBodyPart streamDataBodyPart = new FileDataBodyPart("schema", schema, new MediaType("application", "olapMondrianSchema+xml")); + super.multipart.bodyPart(streamDataBodyPart); + return this; + } + + public MondrianConnectionResourceBuilder withMondrianSchema(String schema) { + multipart.field("schema", schema, new MediaType("application", "olapMondrianSchema+xml")); + return this; + } + } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/builder/ReportUnitResourceBuilder.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/builder/ReportUnitResourceBuilder.java similarity index 61% rename from src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/builder/ReportUnitResourceBuilder.java rename to src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/builder/ReportUnitResourceBuilder.java index 6ea5c043..88885f81 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/builder/ReportUnitResourceBuilder.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/builder/ReportUnitResourceBuilder.java @@ -18,16 +18,20 @@ * You should have received a copy of the GNU Affero General Public License * along with this program.  If not, see . */ -package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.builder; +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.builder; import com.jaspersoft.jasperserver.dto.resources.ClientFile; import com.jaspersoft.jasperserver.dto.resources.ClientReference; import com.jaspersoft.jasperserver.dto.resources.ClientReferenceableFile; import com.jaspersoft.jasperserver.dto.resources.ClientReportUnit; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.decorator.ReportUnitResourceOperationProcessorDecorator; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.decorator.ReportUnitResourceOperationProcessorDecorator; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.MediaTypeUtil; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; +import org.glassfish.jersey.media.multipart.file.StreamDataBodyPart; import javax.ws.rs.core.MediaType; +import java.io.File; import java.io.InputStream; import java.util.HashMap; import java.util.Map; @@ -36,22 +40,43 @@ * @author Alexander Krasnyanskiy */ public class ReportUnitResourceBuilder extends ReportUnitResourceOperationProcessorDecorator { - public ReportUnitResourceBuilder(ClientReportUnit entity, SessionStorage sessionStorage) { - super(entity, sessionStorage); + public ReportUnitResourceBuilder(ClientReportUnit reportUnit, SessionStorage sessionStorage) { + super(reportUnit, sessionStorage); } + @Deprecated public ReportUnitResourceBuilder withJrxml(InputStream jrxml, ClientFile jrxmlDescriptor) { multipart.field("jrxml", jrxml, MediaType.APPLICATION_XML_TYPE); super.reportUnit.setJrxml(jrxmlDescriptor); return this; } + @Deprecated public ReportUnitResourceBuilder withJrxml(String jrxml, ClientFile jrxmlDescriptor) { multipart.field("jrxml", jrxml, MediaType.APPLICATION_XML_TYPE); super.reportUnit.setJrxml(jrxmlDescriptor); return this; } + + public ReportUnitResourceBuilder withJrxml(String jrxmlContent) { + super.multipart.field("jrxml", jrxmlContent, new MediaType("application", "jrxml")); + return this; + } + + public ReportUnitResourceBuilder withJrxml(InputStream jrxml, String label) { + StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart("jrxml", jrxml, label, new MediaType("application", "jrxml")); + super.multipart.bodyPart(streamDataBodyPart); + return this; + } + + public ReportUnitResourceBuilder withJrxml(File jrxml) { + FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("jrxml", jrxml, new MediaType("application", "jrxml")); + super.multipart.bodyPart(fileDataBodyPart); + return this; + } + + @Deprecated public ReportUnitResourceBuilder withNewFile(String content, String fileName, ClientFile fileDescriptor) { multipart.field("files." + fileName, content, MediaType.TEXT_PLAIN_TYPE); Map files = super.reportUnit.getFiles(); @@ -64,6 +89,7 @@ public ReportUnitResourceBuilder withNewFile(String content, String fileName, Cl return this; } + @Deprecated public ReportUnitResourceBuilder withNewFile(InputStream content, String fileName, ClientFile fileDescriptor) { multipart.field("files." + fileName, content, MediaType.TEXT_PLAIN_TYPE); Map files = super.reportUnit.getFiles(); @@ -76,6 +102,7 @@ public ReportUnitResourceBuilder withNewFile(InputStream content, String fileNam return this; } + @Deprecated public ReportUnitResourceBuilder withNewFileReference(String fileName, ClientReference fileDescriptor) { Map files = super.reportUnit.getFiles(); if (files != null) { @@ -86,4 +113,28 @@ public ReportUnitResourceBuilder withNewFileReference(String fileName, ClientRef } return this; } + + public ReportUnitResourceBuilder withFile(InputStream fileData, String label, ClientFile.FileType fileType) { + StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart("files." + label, + fileData, + label, + MediaTypeUtil.stringToMediaType(fileType.getMimeType())); + super.multipart.bodyPart(streamDataBodyPart); + return this; + } + + public ReportUnitResourceBuilder withFile(File fileData, String label, ClientFile.FileType fileType) { + FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("files." + label, + fileData, + MediaTypeUtil.stringToMediaType(fileType.getMimeType())); + super.multipart.bodyPart(fileDataBodyPart); + return this; + } + + public ReportUnitResourceBuilder withFile(String fileData, String label, ClientFile.FileType fileType) { + super.multipart.field("file." + label, + fileData, + MediaTypeUtil.stringToMediaType(fileType.getMimeType())); + return this; + } } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/builder/SecureMondrianConnectionResourceBuilder.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/builder/SecureMondrianConnectionResourceBuilder.java similarity index 63% rename from src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/builder/SecureMondrianConnectionResourceBuilder.java rename to src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/builder/SecureMondrianConnectionResourceBuilder.java index 091aee1a..fb4be2c1 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/builder/SecureMondrianConnectionResourceBuilder.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/builder/SecureMondrianConnectionResourceBuilder.java @@ -18,15 +18,18 @@ * You should have received a copy of the GNU Affero General Public License * along with this program.  If not, see . */ -package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.builder; +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.builder; import com.jaspersoft.jasperserver.dto.resources.ClientFile; import com.jaspersoft.jasperserver.dto.resources.ClientReferenceableFile; import com.jaspersoft.jasperserver.dto.resources.ClientSecureMondrianConnection; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.decorator.SecureMondrianConnectionResourceOperationProcessorDecorator; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.decorator.SecureMondrianConnectionResourceOperationProcessorDecorator; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; +import org.glassfish.jersey.media.multipart.file.StreamDataBodyPart; import javax.ws.rs.core.MediaType; +import java.io.File; import java.io.InputStream; import java.util.List; @@ -41,28 +44,21 @@ public SecureMondrianConnectionResourceBuilder(ClientSecureMondrianConnection en super(storage, entity); } + @Deprecated public SecureMondrianConnectionResourceBuilder withMondrianSchema(InputStream schema, ClientFile schemaDescriptor) { multipart.field("schema", schema, new MediaType("application", "olapMondrianSchema+xml")); super.connection.setSchema(schemaDescriptor); return this; } + @Deprecated public SecureMondrianConnectionResourceBuilder withMondrianSchema(String schema, ClientFile schemaDescriptor) { multipart.field("schema", schema, new MediaType("application", "olapMondrianSchema+xml")); super.connection.setSchema(schemaDescriptor); return this; } -// public SecureMondrianConnectionResourceBuilder withMondrianSchema(InputStream schema) { -// multipart.field("schema", schema, new MediaType("application", "olapMondrianSchema+xml")); -// return this; -// } - -// public SecureMondrianConnectionResourceBuilder withMondrianSchema(String schema) { -// multipart.field("schema", schema, new MediaType("application", "olapMondrianSchema+xml")); -// return this; -// } - + @Deprecated public SecureMondrianConnectionResourceBuilder withAccessGrantSchemasAsStream(List schemas, List schemaDescriptors) { super.connection.setAccessGrants(schemaDescriptors); for (InputStream schema : schemas) { @@ -71,6 +67,7 @@ public SecureMondrianConnectionResourceBuilder withAccessGrantSchemasAsStream(Li return this; } + @Deprecated public SecureMondrianConnectionResourceBuilder withAccessGrantSchemasAsString(List schemas, List schemaDescriptors) { super.connection.setAccessGrants(schemaDescriptors); for (String schema : schemas) { @@ -79,22 +76,40 @@ public SecureMondrianConnectionResourceBuilder withAccessGrantSchemasAsString(Li return this; } -// public SecureMondrianConnectionResourceBuilder withAccessGrantSchemas(List schemas) { -// for (InputStream schema : schemas) { -// multipart.field("accessGrantSchemas.accessGrantSchema[" + schemaCounter + "]", schema, new MediaType("application", "accessGrantSchema+xml")); -// } -// return this; -// } - -// public SecureMondrianConnectionResourceBuilder withAccessGrantSchemasAsString(List schemas) { -// for (String schema : schemas) { -// multipart.field("accessGrantSchemas.accessGrantSchema[" + schemaCounter + "]", schema, new MediaType("application", "accessGrantSchema+xml")); -// } -// return this; -// } - + @Deprecated public SecureMondrianConnectionResourceBuilder withUri(String uri) { super.connection.setUri(uri); return this; } + + + public SecureMondrianConnectionResourceBuilder withMondrianSchema(InputStream schema, String label) { + StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart("schema", schema, label, new MediaType("application", "olapMondrianSchema+xml")); + super.multipart.bodyPart(streamDataBodyPart); + return this; + } + + public SecureMondrianConnectionResourceBuilder withMondrianSchema(File schema) { + FileDataBodyPart streamDataBodyPart = new FileDataBodyPart("schema", schema, new MediaType("application", "olapMondrianSchema+xml")); + super.multipart.bodyPart(streamDataBodyPart); + return this; + } + + public SecureMondrianConnectionResourceBuilder withMondrianSchema(String schema) { + multipart.field("schema", schema, new MediaType("application", "olapMondrianSchema+xml")); + return this; + } + + public SecureMondrianConnectionResourceBuilder withAccessGrantSchema(InputStream schema, String label) { + StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart("accessGrantSchemas.accessGrantSchema[" + schemaCounter++ + "]", schema, label, new MediaType("application", "accessGrantSchema+xml")); + super.multipart.bodyPart(streamDataBodyPart); + return this; + } + + public SecureMondrianConnectionResourceBuilder withAccessGrantSchema(File schema) { + FileDataBodyPart streamDataBodyPart = new FileDataBodyPart("accessGrantSchemas.accessGrantSchema[" + schemaCounter++ + "]", schema, new MediaType("application", "accessGrantSchema+xml")); + super.multipart.bodyPart(streamDataBodyPart); + return this; + } + } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/builder/SemanticLayerResourceBuilder.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/builder/SemanticLayerResourceBuilder.java new file mode 100644 index 00000000..d1a39136 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/builder/SemanticLayerResourceBuilder.java @@ -0,0 +1,160 @@ +/* + * Copyright (C) 2005 - 2014 Jaspersoft Corporation. All rights reserved. + * http://www.jaspersoft.com. + * + * Unless you have purchased a commercial license agreement from Jaspersoft, + * the following license terms apply: + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see . + */ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.builder; + +import com.jaspersoft.jasperserver.dto.resources.ClientBundle; +import com.jaspersoft.jasperserver.dto.resources.ClientFile; +import com.jaspersoft.jasperserver.dto.resources.ClientSemanticLayerDataSource; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.decorator.SemanticLayerResourceOperationProcessorDecorator; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; +import org.glassfish.jersey.media.multipart.file.StreamDataBodyPart; + +import javax.ws.rs.core.MediaType; +import java.io.File; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +/** + * @author Alexander Krasnyanskiy + */ +public class SemanticLayerResourceBuilder extends SemanticLayerResourceOperationProcessorDecorator { + + private int bundleCounter = 0; + + public SemanticLayerResourceBuilder(ClientSemanticLayerDataSource domain, SessionStorage sessionStorage) { + super(sessionStorage, domain); + } + + @Deprecated + public SemanticLayerResourceBuilder withSchema(String schema, ClientFile schemaRef) { + super.multipart.field("schema", schema, MediaType.APPLICATION_XML_TYPE); + super.domain.setSchema(schemaRef); + return this; + } + + @Deprecated + public SemanticLayerResourceBuilder withSchema(InputStream schema, ClientFile schemaRef) { + super.multipart.field("schema", schema, MediaType.APPLICATION_XML_TYPE); + super.domain.setSchema(schemaRef); + return this; + } + + public SemanticLayerResourceBuilder withSchema(String schemaContent) { + super.multipart.field("schema", schemaContent, MediaType.APPLICATION_XML_TYPE); + return this; + } + + public SemanticLayerResourceBuilder withSchema(InputStream schema, String label) { + StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart("schema", schema, label, MediaType.APPLICATION_XML_TYPE); + super.multipart.bodyPart(streamDataBodyPart); + return this; + } + + public SemanticLayerResourceBuilder withSchema(File schema) { + FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("schema", schema, MediaType.APPLICATION_XML_TYPE); + super.multipart.bodyPart(fileDataBodyPart); + return this; + } + + @Deprecated + public SemanticLayerResourceBuilder withSecurityFile(InputStream securityFile, ClientFile securityFileRef) { + super.multipart.field("securityFile", securityFile, MediaType.APPLICATION_XML_TYPE); + super.domain.setSecurityFile(securityFileRef); + return this; + } + + @Deprecated + public SemanticLayerResourceBuilder withSecurityFile(String securityFile, ClientFile securityFileRef) { + super.multipart.field("securityFile", securityFile, MediaType.APPLICATION_XML_TYPE); + super.domain.setSecurityFile(securityFileRef); + return this; + } + + public SemanticLayerResourceBuilder withSecurityFile(InputStream securityFile, String label) { + StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart("securityFile", securityFile, label, MediaType.APPLICATION_XML_TYPE); + super.multipart.bodyPart(streamDataBodyPart); + return this; + } + + public SemanticLayerResourceBuilder withSecurityFile(File securityFile) { + FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("securityFile", securityFile, MediaType.APPLICATION_XML_TYPE); + super.multipart.bodyPart(fileDataBodyPart); + return this; + } + + public SemanticLayerResourceBuilder withSecurityFile(String securityFile) { + super.multipart.field("securityFile", securityFile, MediaType.APPLICATION_XML_TYPE); + return this; + } + + @Deprecated + public SemanticLayerResourceBuilder withBundle(InputStream bundle, ClientBundle bundleRef) { + super.multipart.field("bundles.bundle[" + bundleCounter++ + "]", bundle, MediaType.TEXT_PLAIN_TYPE); + List bundles = super.domain.getBundles(); + + if (bundles != null) { + int index = bundles.indexOf(bundleRef); + if (index >= 0) { + bundles.set(index, bundleRef); + } else { + bundles.add(bundleRef); + } + } else { + bundles = new ArrayList(); + bundles.add(bundleRef); + } + + super.domain.setBundles(bundles); + return this; + } + + @Deprecated + public SemanticLayerResourceBuilder withBundle(String bundle, ClientBundle bundleRef) { + super.multipart.field("bundles.bundle[" + bundleCounter++ + "]", bundle, MediaType.TEXT_PLAIN_TYPE); + return this; + } + + public SemanticLayerResourceBuilder withBundle(InputStream bundle, String label) { + StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart("bundles.bundle[" + bundleCounter++ + "]", bundle, label, MediaType.TEXT_PLAIN_TYPE); + super.multipart.bodyPart(streamDataBodyPart); + return this; + } + + public SemanticLayerResourceBuilder withBundle(File bundle) { + FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("bundles.bundle[" + bundleCounter++ + "]", bundle, MediaType.TEXT_PLAIN_TYPE); + super.multipart.bodyPart(fileDataBodyPart); + return this; + } + + public SemanticLayerResourceBuilder withBundle(String bundle) { + super.multipart.field("bundles.bundle[" + bundleCounter++ + "]", bundle, MediaType.TEXT_PLAIN_TYPE); + return this; + } + + @Deprecated + public SemanticLayerResourceBuilder withUri(String uri) { + super.domain.setUri(uri); + return this; + } + +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/decorator/DomainOperationProcessorDecorator.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/decorator/DomainOperationProcessorDecorator.java new file mode 100644 index 00000000..e2b4d3ce --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/decorator/DomainOperationProcessorDecorator.java @@ -0,0 +1,94 @@ +/* + * Copyright (C) 2005 - 2014 Jaspersoft Corporation. All rights reserved. + * http://www.jaspersoft.com. + * + * Unless you have purchased a commercial license agreement from Jaspersoft, + * the following license terms apply: + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see . + */ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.decorator; + +import com.jaspersoft.jasperserver.dto.resources.domain.ClientDomain; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.WrongResourceFormatException; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.processor.CommonOperationProcessorImpl; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.ResourceServiceParameter; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.UrlUtils; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; + +/** + * @author Alexander Krasnyanskiy + */ +public class DomainOperationProcessorDecorator { + protected CommonOperationProcessorImpl processor; + protected ClientDomain domain; + protected FormDataMultiPart multipart; + protected String path; + private MultivaluedMap params = new MultivaluedHashMap<>(); + + public DomainOperationProcessorDecorator parameter(ResourceServiceParameter param, String value) { + params.add(param.getName(), UrlUtils.encode(value)); + return this; + } + + public DomainOperationProcessorDecorator parameter(ResourceServiceParameter param, Boolean value) { + params.add(param.getName(), value.toString()); + return this; + } + + public DomainOperationProcessorDecorator parameter(String param, String value) { + params.add(param, UrlUtils.encode(value)); + return this; + } + + + public DomainOperationProcessorDecorator(SessionStorage sessionStorage, ClientDomain domain) { + this.processor = new CommonOperationProcessorImpl(domain, domain.getClass(), sessionStorage); + this.multipart = new FormDataMultiPart(); + this.domain = domain; + } + + public OperationResult get() { + if (domain.getUri() == null) { + throw new WrongResourceFormatException("Can't find uri!"); + } + return processor.get(domain.getUri()); + } + + @Deprecated + public OperationResult createInFolder(String path) { + return processor.create(multipart, new MediaType("application", "repository.domain+json"), path, params); + } + + + public DomainOperationProcessorDecorator inFolder(String parentFolder) { + this.path = parentFolder; + return this; + } + + public OperationResult create() { + return processor.create(multipart, new MediaType("application", "repository.domain+json"), path, params); + } + + public OperationResult createOrUpdate() { + return processor.createOrUpdate(multipart, new MediaType("application", "repository.domain+json"), domain.getUri(), params); + } + +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/decorator/DomainTopicOperationProcessorDecorator.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/decorator/DomainTopicOperationProcessorDecorator.java new file mode 100644 index 00000000..2d933091 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/decorator/DomainTopicOperationProcessorDecorator.java @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2005 - 2014 Jaspersoft Corporation. All rights reserved. + * http://www.jaspersoft.com. + * + * Unless you have purchased a commercial license agreement from Jaspersoft, + * the following license terms apply: + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see . + */ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.decorator; + +import com.jaspersoft.jasperserver.dto.resources.ClientDomainTopic; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.processor.CommonOperationProcessorImpl; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.ResourceServiceParameter; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.UrlUtils; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; + +/** + * @author Alexander Krasnyanskiy + */ +public class DomainTopicOperationProcessorDecorator { + + protected CommonOperationProcessorImpl processor; + protected ClientDomainTopic domainTopic; + protected FormDataMultiPart multipart; + protected String path; + private MultivaluedMap params = new MultivaluedHashMap<>(); + + public DomainTopicOperationProcessorDecorator parameter(ResourceServiceParameter param, String value) { + params.add(param.getName(), UrlUtils.encode(value)); + return this; + } + + public DomainTopicOperationProcessorDecorator parameter(ResourceServiceParameter param, Boolean value) { + params.add(param.getName(), value.toString()); + return this; + } + + public DomainTopicOperationProcessorDecorator parameter(String param, String value) { + params.add(param, UrlUtils.encode(value)); + return this; + } + + public DomainTopicOperationProcessorDecorator(ClientDomainTopic domainTopic, SessionStorage sessionStorage) { + this.processor = new CommonOperationProcessorImpl(domainTopic, domainTopic.getClass(), sessionStorage); + this.multipart = new FormDataMultiPart(); + this.domainTopic = domainTopic; + } + + @Deprecated + public OperationResult createInFolder(String path) { + return processor.create(multipart, new MediaType("application", "repository.domainTopic+json"), path, params); + } + + public DomainTopicOperationProcessorDecorator inFolder(String parentFolder) { + this.path = parentFolder; + return this; + } + + public OperationResult create() { + return processor.create(multipart, new MediaType("application", "repository.domainTopic+json"), path, params); + } + + public OperationResult createOrUpdate() { + return processor.createOrUpdate(multipart, new MediaType("application", "repository.domainTopic+json"), domainTopic.getUri(), params); + } + +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/decorator/MondrianConnectionResourceOperationProcessorDecorator.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/decorator/MondrianConnectionResourceOperationProcessorDecorator.java similarity index 52% rename from src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/decorator/MondrianConnectionResourceOperationProcessorDecorator.java rename to src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/decorator/MondrianConnectionResourceOperationProcessorDecorator.java index ad2e9254..1fc2e5fa 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/decorator/MondrianConnectionResourceOperationProcessorDecorator.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/decorator/MondrianConnectionResourceOperationProcessorDecorator.java @@ -18,22 +18,44 @@ * You should have received a copy of the GNU Affero General Public License * along with this program.  If not, see . */ -package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.decorator; +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.decorator; import com.jaspersoft.jasperserver.dto.resources.ClientMondrianConnection; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.processor.CommonOperationProcessorImpl; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.processor.CommonOperationProcessorImpl; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.ResourceServiceParameter; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.UrlUtils; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; -import com.sun.jersey.multipart.FormDataMultiPart; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; + import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; /** * @author Alexander Krasnyanskiy */ -public abstract class MondrianConnectionResourceOperationProcessorDecorator { +public class MondrianConnectionResourceOperationProcessorDecorator { protected CommonOperationProcessorImpl processor; protected ClientMondrianConnection connection; protected FormDataMultiPart multipart; + protected String path; + private MultivaluedMap params = new MultivaluedHashMap<>(); + + public MondrianConnectionResourceOperationProcessorDecorator parameter(ResourceServiceParameter param, String value) { + params.add(param.getName(), UrlUtils.encode(value)); + return this; + } + + public MondrianConnectionResourceOperationProcessorDecorator parameter(ResourceServiceParameter param, Boolean value) { + params.add(param.getName(), value.toString()); + return this; + } + + public MondrianConnectionResourceOperationProcessorDecorator parameter(String param, String value) { + params.add(param, UrlUtils.encode(value)); + return this; + } public MondrianConnectionResourceOperationProcessorDecorator(SessionStorage sessionStorage, ClientMondrianConnection connection) { this.processor = new CommonOperationProcessorImpl(connection, connection.getClass(), sessionStorage); @@ -41,8 +63,22 @@ public MondrianConnectionResourceOperationProcessorDecorator(SessionStorage sess this.connection = connection; } + @Deprecated public OperationResult createInFolder(String path) { - return processor.create(multipart, new MediaType("application", "repository.mondrianConnection+xml"), path); + return processor.create(multipart, new MediaType("application", "repository.mondrianConnection+xml"), path, params); + } + + public MondrianConnectionResourceOperationProcessorDecorator inFolder(String parentFolder) { + this.path = parentFolder; + return this; + } + + public OperationResult create() { + return processor.create(multipart, new MediaType("application", "repository.mondrianConnection+xml"), path, params); + } + + public OperationResult createOrUpdate() { + return processor.createOrUpdate(multipart, new MediaType("application", "repository.mondrianConnection+json"), connection.getUri(), params); } } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/decorator/ReportUnitResourceOperationProcessorDecorator.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/decorator/ReportUnitResourceOperationProcessorDecorator.java similarity index 52% rename from src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/decorator/ReportUnitResourceOperationProcessorDecorator.java rename to src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/decorator/ReportUnitResourceOperationProcessorDecorator.java index 05fc538e..e1cdc723 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/decorator/ReportUnitResourceOperationProcessorDecorator.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/decorator/ReportUnitResourceOperationProcessorDecorator.java @@ -18,23 +18,45 @@ * You should have received a copy of the GNU Affero General Public License * along with this program.  If not, see . */ -package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.decorator; +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.decorator; import com.jaspersoft.jasperserver.dto.resources.ClientReportUnit; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.processor.CommonOperationProcessorImpl; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.processor.CommonOperationProcessorImpl; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.ResourceServiceParameter; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.UrlUtils; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; -import com.sun.jersey.multipart.FormDataMultiPart; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; + import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; /** * @author Alexander Krasnyanskiy */ -public abstract class ReportUnitResourceOperationProcessorDecorator { +public class ReportUnitResourceOperationProcessorDecorator { protected CommonOperationProcessorImpl processor; protected ClientReportUnit reportUnit; protected FormDataMultiPart multipart; + protected String path; + private MultivaluedMap params = new MultivaluedHashMap<>(); + + public ReportUnitResourceOperationProcessorDecorator parameter(ResourceServiceParameter param, String value) { + params.add(param.getName(), UrlUtils.encode(value)); + return this; + } + + public ReportUnitResourceOperationProcessorDecorator parameter(ResourceServiceParameter param, Boolean value) { + params.add(param.getName(), value.toString()); + return this; + } + + public ReportUnitResourceOperationProcessorDecorator parameter(String param, String value) { + params.add(param, UrlUtils.encode(value)); + return this; + } public ReportUnitResourceOperationProcessorDecorator(ClientReportUnit reportUnit, SessionStorage sessionStorage) { this.processor = new CommonOperationProcessorImpl(reportUnit, reportUnit.getClass(), sessionStorage); @@ -42,7 +64,21 @@ public ReportUnitResourceOperationProcessorDecorator(ClientReportUnit reportUnit this.reportUnit = reportUnit; } + @Deprecated public OperationResult createInFolder(String path) { - return processor.create(multipart, new MediaType("application", "repository.reportUnit+json"), path); + return processor.create(multipart, new MediaType("application", "repository.reportUnit+json"), path, params); + } + + public ReportUnitResourceOperationProcessorDecorator inFolder(String parentFolder) { + this.path = parentFolder; + return this; + } + + public OperationResult create() { + return processor.create(multipart, new MediaType("application", "repository.reportUnit+json"), path, params); + } + + public OperationResult createOrUpdate() { + return processor.createOrUpdate(multipart, new MediaType("application", "repository.reportUnit+json"), reportUnit.getUri(), params); } } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/decorator/SecureMondrianConnectionResourceOperationProcessorDecorator.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/decorator/SecureMondrianConnectionResourceOperationProcessorDecorator.java similarity index 52% rename from src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/decorator/SecureMondrianConnectionResourceOperationProcessorDecorator.java rename to src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/decorator/SecureMondrianConnectionResourceOperationProcessorDecorator.java index 1504a369..2f059a38 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/decorator/SecureMondrianConnectionResourceOperationProcessorDecorator.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/decorator/SecureMondrianConnectionResourceOperationProcessorDecorator.java @@ -18,22 +18,44 @@ * You should have received a copy of the GNU Affero General Public License * along with this program.  If not, see . */ -package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.decorator; +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.decorator; import com.jaspersoft.jasperserver.dto.resources.ClientSecureMondrianConnection; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.processor.CommonOperationProcessorImpl; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.processor.CommonOperationProcessorImpl; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.ResourceServiceParameter; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.UrlUtils; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; -import com.sun.jersey.multipart.FormDataMultiPart; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; + import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; /** * @author Alexander Krasnyanskiy */ -public abstract class SecureMondrianConnectionResourceOperationProcessorDecorator { +public class SecureMondrianConnectionResourceOperationProcessorDecorator { protected CommonOperationProcessorImpl processor; protected ClientSecureMondrianConnection connection; protected FormDataMultiPart multipart; + protected String path; + private MultivaluedMap params = new MultivaluedHashMap<>(); + + public SecureMondrianConnectionResourceOperationProcessorDecorator parameter(ResourceServiceParameter param, String value) { + params.add(param.getName(), UrlUtils.encode(value)); + return this; + } + + public SecureMondrianConnectionResourceOperationProcessorDecorator parameter(ResourceServiceParameter param, Boolean value) { + params.add(param.getName(), value.toString()); + return this; + } + + public SecureMondrianConnectionResourceOperationProcessorDecorator parameter(String param, String value) { + params.add(param, UrlUtils.encode(value)); + return this; + } public SecureMondrianConnectionResourceOperationProcessorDecorator(SessionStorage sessionStorage, ClientSecureMondrianConnection connection) { this.processor = new CommonOperationProcessorImpl(connection, connection.getClass(), sessionStorage); @@ -41,19 +63,24 @@ public SecureMondrianConnectionResourceOperationProcessorDecorator(SessionStorag this.connection = connection; } + @Deprecated public OperationResult createInFolder(String path) { - return processor.create(multipart, new MediaType("application", "repository.secureMondrianConnection+xml"), path); + return processor.create(multipart, new MediaType("application", "repository.secureMondrianConnection+xml"), path, params); } - public CommonOperationProcessorImpl getProcessor() { - return processor; + + public SecureMondrianConnectionResourceOperationProcessorDecorator inFolder(String parentFolder) { + this.path = parentFolder; + return this; } - public ClientSecureMondrianConnection getConnection() { - return connection; + public OperationResult create() { + return processor.create(multipart, new MediaType("application", "repository.secureMondrianConnection+xml"), path, params); } - public FormDataMultiPart getMultipart() { - return multipart; + public OperationResult createOrUpdate() { + return processor.createOrUpdate(multipart, new MediaType("application", "repository.secureMondrianConnection+json"), connection.getUri(), params); } + + } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/decorator/DomainResourceOperationProcessorDecorator.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/decorator/SemanticLayerResourceOperationProcessorDecorator.java similarity index 52% rename from src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/decorator/DomainResourceOperationProcessorDecorator.java rename to src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/decorator/SemanticLayerResourceOperationProcessorDecorator.java index 95bc333e..2e5b3eeb 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/decorator/DomainResourceOperationProcessorDecorator.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/decorator/SemanticLayerResourceOperationProcessorDecorator.java @@ -18,28 +18,51 @@ * You should have received a copy of the GNU Affero General Public License * along with this program.  If not, see . */ -package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.decorator; +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.decorator; import com.jaspersoft.jasperserver.dto.resources.ClientSemanticLayerDataSource; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.WrongResourceFormatException; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.processor.CommonOperationProcessorImpl; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.WrongResourceFormatException; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.processor.CommonOperationProcessorImpl; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.ResourceServiceParameter; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.UrlUtils; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; -import com.sun.jersey.multipart.FormDataMultiPart; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; + import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; /** * @author Alexander Krasnyanskiy */ -public abstract class DomainResourceOperationProcessorDecorator { +public class SemanticLayerResourceOperationProcessorDecorator { protected CommonOperationProcessorImpl processor; protected ClientSemanticLayerDataSource domain; protected FormDataMultiPart multipart; + protected String path; + private MultivaluedMap params = new MultivaluedHashMap<>(); + + public SemanticLayerResourceOperationProcessorDecorator parameter(ResourceServiceParameter param, String value) { + params.add(param.getName(), UrlUtils.encode(value)); + return this; + } + + public SemanticLayerResourceOperationProcessorDecorator parameter(ResourceServiceParameter param, Boolean value) { + params.add(param.getName(), value.toString()); + return this; + } - public DomainResourceOperationProcessorDecorator(SessionStorage sessionStorage, ClientSemanticLayerDataSource domain) { + public SemanticLayerResourceOperationProcessorDecorator parameter(String param, String value) { + params.add(param, UrlUtils.encode(value)); + return this; + } + + public SemanticLayerResourceOperationProcessorDecorator(SessionStorage sessionStorage, ClientSemanticLayerDataSource domain) { this.processor = new CommonOperationProcessorImpl(domain, domain.getClass(), sessionStorage); this.multipart = new FormDataMultiPart(); this.domain = domain; + } public OperationResult get() { @@ -49,19 +72,23 @@ public OperationResult get() { return processor.get(domain.getUri()); } + @Deprecated public OperationResult createInFolder(String path) { - return processor.create(multipart, new MediaType("application", "repository.semanticlayerdatasource+json"), path); + return processor.create(multipart, new MediaType("application", "repository.semanticLayerDataSource+json"), path, params); } - public CommonOperationProcessorImpl getProcessor() { - return processor; + public SemanticLayerResourceOperationProcessorDecorator inFolder(String path) { + this.path = path; + return this; } - public ClientSemanticLayerDataSource getDomain() { - return domain; + public OperationResult create() { + return processor.create(multipart, new MediaType("application", "repository.semanticLayerDataSource+json"), path, params); } - public FormDataMultiPart getMultipart() { - return multipart; + public OperationResult createOrUpdate() { + return processor.createOrUpdate(multipart, new MediaType("application", "repository.semanticLayerDataSource+json"), domain.getUri(), params); } + + } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/processor/CommonOperationProcessor.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/processor/CommonOperationProcessor.java similarity index 77% rename from src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/processor/CommonOperationProcessor.java rename to src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/processor/CommonOperationProcessor.java index 72ae545a..31d9ed5a 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/processor/CommonOperationProcessor.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/processor/CommonOperationProcessor.java @@ -18,16 +18,19 @@ * You should have received a copy of the GNU Affero General Public License * along with this program.  If not, see . */ -package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.processor; +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.processor; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; -import com.sun.jersey.multipart.FormDataMultiPart; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; + import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; /** * @author Alexander Krasnyanskiy */ public interface CommonOperationProcessor { - OperationResult create(FormDataMultiPart multipart, MediaType mediaType, String path); + OperationResult create(FormDataMultiPart multipart, MediaType mediaType, String path, MultivaluedMap params); + OperationResult createOrUpdate(FormDataMultiPart multipart, MediaType mediaType, String path, MultivaluedMap params); OperationResult get(String uri); } \ No newline at end of file diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/processor/CommonOperationProcessorImpl.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/processor/CommonOperationProcessorImpl.java similarity index 55% rename from src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/processor/CommonOperationProcessorImpl.java rename to src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/processor/CommonOperationProcessorImpl.java index 676d0113..3c1fc3cd 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/processor/CommonOperationProcessorImpl.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/compexResourcesSupport/processor/CommonOperationProcessorImpl.java @@ -18,18 +18,23 @@ * You should have received a copy of the GNU Affero General Public License * along with this program.  If not, see . */ -package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.processor; +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.processor; +import com.jaspersoft.jasperserver.dto.resources.ClientResource; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.SingleResourceAdapter; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; -import com.sun.jersey.multipart.FormDataMultiPart; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; + import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import java.util.List; +import java.util.Map; /** * @author Alexander Krasnyanskiy */ -public class CommonOperationProcessorImpl implements CommonOperationProcessor { +public class CommonOperationProcessorImpl implements CommonOperationProcessor { private ResourceType resource; private Class resourceTypeClass; private SessionStorage sessionStorage; @@ -41,14 +46,34 @@ public CommonOperationProcessorImpl(ResourceType resource, Class r } @Override - public OperationResult create(FormDataMultiPart multipart, MediaType mediaType, String path) { + public OperationResult create(FormDataMultiPart multipart, MediaType mediaType, String path, MultivaluedMap params) { + multipart.field("resource", resource, mediaType); + SingleResourceAdapter adapter = new SingleResourceAdapter(sessionStorage, path); + addParamsToAdapter(params, adapter); + return adapter.uploadMultipartResource(multipart, resourceTypeClass); + } + + private void addParamsToAdapter(MultivaluedMap params, SingleResourceAdapter adapter) { + if (params != null) { + for (Map.Entry> entry : params.entrySet()) { + for (String param : entry.getValue()) { + adapter.parameter(entry.getKey(), param); + } + } + } + } + + @Override + public OperationResult createOrUpdate(FormDataMultiPart multipart, MediaType mediaType, String path, MultivaluedMap params) { multipart.field("resource", resource, mediaType); - return new SingleResourceAdapter(sessionStorage, path).uploadMultipartResource(multipart, resourceTypeClass); + SingleResourceAdapter adapter = new SingleResourceAdapter(sessionStorage, path); + addParamsToAdapter(params, adapter); + return adapter.putMultipartResource(multipart, resourceTypeClass); } @Override public OperationResult get(String uri) { - return new SingleResourceAdapter(sessionStorage, uri).get(resourceTypeClass); + return new SingleResourceAdapter(sessionStorage, uri).detailsForType(resourceTypeClass); } public SessionStorage getSessionStorage() { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/builder/DomainResourceBuilder.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/builder/DomainResourceBuilder.java deleted file mode 100644 index 13d07914..00000000 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/builder/DomainResourceBuilder.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright © 2014-2019. TIBCO Software Inc. All Rights Reserved. Confidential & Proprietary. - */ -package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.builder; - -import com.jaspersoft.jasperserver.dto.resources.ClientBundle; -import com.jaspersoft.jasperserver.dto.resources.ClientFile; -import com.jaspersoft.jasperserver.dto.resources.ClientReference; -import com.jaspersoft.jasperserver.dto.resources.ClientSemanticLayerDataSource; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.decorator.DomainResourceOperationProcessorDecorator; -import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; - -import javax.ws.rs.core.MediaType; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Alexander Krasnyanskiy - */ -public class DomainResourceBuilder extends DomainResourceOperationProcessorDecorator { - - private int bundleCounter = 0; - - public DomainResourceBuilder(ClientSemanticLayerDataSource domain, SessionStorage sessionStorage) { - super(sessionStorage, domain); - } - - public DomainResourceBuilder withSchema(String schema, ClientFile schemaRef) { - super.multipart.field("schema", schema, MediaType.APPLICATION_XML_TYPE); - super.domain.setSchema(schemaRef); - return this; - } - - public DomainResourceBuilder withSchema(InputStream schema, ClientFile schemaRef) { - super.multipart.field("schema", schema, MediaType.APPLICATION_XML_TYPE); - super.domain.setSchema(schemaRef); - return this; - } - - public DomainResourceBuilder withSecurityFile(InputStream securityFile, ClientFile securityFileRef) { - super.multipart.field("securityFile", securityFile, MediaType.APPLICATION_XML_TYPE); - super.domain.setSecurityFile(securityFileRef); - return this; - } - - public DomainResourceBuilder withSecurityFile(String securityFile, ClientFile securityFileRef) { - super.multipart.field("securityFile", securityFile, MediaType.APPLICATION_XML_TYPE); - super.domain.setSecurityFile(securityFileRef); - return this; - } - - public DomainResourceBuilder withBundle(InputStream bundle, ClientBundle bundleRef) { - super.multipart.field("bundles.bundle[" + bundleCounter++ + "]", bundle, MediaType.TEXT_PLAIN_TYPE); - List bundles = super.domain.getBundles(); - - if (bundles != null) { - int index = bundles.indexOf(bundleRef); - if (index >= 0) { - bundles.set(index, bundleRef); - } else { - bundles.add(bundleRef); - } - } else { - bundles = new ArrayList(); - bundles.add(bundleRef); - } - - super.domain.setBundles(bundles); - return this; - } - - public DomainResourceBuilder withBundle(String bundle, ClientBundle bundleRef) { - super.multipart.field("bundles.bundle[" + bundleCounter++ + "]", bundle, MediaType.TEXT_PLAIN_TYPE); - List bundles = super.domain.getBundles(); - - if (bundles != null) { - int index = bundles.indexOf(bundleRef); - if (index >= 0) { - bundles.set(index, bundleRef); - } else { - bundles.add(bundleRef); - } - } else { - bundles = new ArrayList(); - bundles.add(bundleRef); - } - - super.domain.setBundles(bundles); - return this; - } - - public DomainResourceBuilder withBundles(List bundles, List bundlesRef) { - for (InputStream bundle : bundles) { - this.multipart.field("bundles.bundle[" + bundleCounter++ + "]", bundle, MediaType.TEXT_PLAIN_TYPE); - } - super.domain.setBundles(bundlesRef); - return this; - } - - public DomainResourceBuilder withDataSource(ClientReference dataSource) { - super.domain.setDataSource(dataSource); - return this; - } - - public DomainResourceBuilder withUri (String uri){ - super.domain.setUri(uri); - return this; - } -} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/uploadFileResourceAdapters/SingleResourceUploadBase64Adapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/uploadFileResourceAdapters/SingleResourceUploadBase64Adapter.java new file mode 100644 index 00000000..078d0a9b --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/uploadFileResourceAdapters/SingleResourceUploadBase64Adapter.java @@ -0,0 +1,104 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.uploadFileResourceAdapters; + +import com.jaspersoft.jasperserver.dto.resources.ClientFile; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.ResourceServiceParameter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.ResourceUtil; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.ResourcesTypeResolverUtil; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.MimeTypeUtil; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class SingleResourceUploadBase64Adapter extends AbstractAdapter{ + public SingleResourceUploadBase64Adapter(SessionStorage sessionStorage) { + super(sessionStorage); + + } + + public static final String SERVICE_URI = "resources"; + public static final String REGEX = "/"; + private String targetResourceUri; + private MultivaluedMap params = new MultivaluedHashMap();; + private ArrayList path = new ArrayList(); + + private ClientFile resource; + private InputStream inputStream; + + public SingleResourceUploadBase64Adapter(SessionStorage sessionStorage, InputStream inputStream, ClientFile resource) { + super(sessionStorage); + this.inputStream = inputStream; + this.resource = resource; + } + public SingleResourceUploadBase64Adapter(SessionStorage sessionStorage, InputStream inputStream, String resourceUri) { + super(sessionStorage); + this.inputStream = inputStream; + this.targetResourceUri = resourceUri; + } + + public SingleResourceUploadBase64Adapter inFolder(String parentUri) { + this.targetResourceUri = parentUri; + return this; + } + + public SingleResourceUploadBase64Adapter createFolders(boolean value) { + this.params.add(ResourceServiceParameter.CREATE_FOLDERS.getName(), Boolean.toString(value)); + return this; + } + + public SingleResourceUploadBase64Adapter withParameter(String name, String value) { + this.params.add(name, value); + return this; + } + + public OperationResult create() { + + final ClientFile entity = new ClientFile(). + setLabel(resource.getLabel()). + setDescription(resource.getDescription()). + setType((resource).getType()). + setContent(ResourceUtil.toBase64EncodedContent(inputStream)); + + return prepareCreateBase64Request().post(entity); + } + + public OperationResult createOrUpdate(InputStream inputStream, ClientFile resourceDescriptor) { + resourceDescriptor.setContent(ResourceUtil.toBase64EncodedContent(inputStream)); + resource = resourceDescriptor; + return prepareCreateBase64Request().put(resourceDescriptor); + } + + private JerseyRequest prepareCreateBase64Request() { + JerseyRequest request = buildRequest(); + String resourceMimeType = ResourcesTypeResolverUtil.getMimeType(ClientFile.class); + request.setContentType(MimeTypeUtil.toCorrectContentMime(sessionStorage.getConfiguration(), resourceMimeType)); + request.setAccept(MimeTypeUtil.toCorrectAcceptMime(sessionStorage.getConfiguration(), resourceMimeType)); + request.addParams(params); + return request; + } + + private JerseyRequest buildRequest() { + path.add(SERVICE_URI); + if (!targetResourceUri.equals(REGEX)) { + path.addAll(Arrays.asList(targetResourceUri.split(REGEX))); + } + return JerseyRequest.buildRequest(sessionStorage, + ClientFile.class, + path.toArray(new String[path.size()]), + new DefaultErrorHandler()); + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/uploadFileResourceAdapters/SingleResourceUploadMultipartAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/uploadFileResourceAdapters/SingleResourceUploadMultipartAdapter.java new file mode 100644 index 00000000..4fd6f360 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/uploadFileResourceAdapters/SingleResourceUploadMultipartAdapter.java @@ -0,0 +1,116 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.uploadFileResourceAdapters; + +import com.jaspersoft.jasperserver.dto.resources.ClientFile; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.MediaTypeUtil; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.ResourceServiceParameter; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; +import org.glassfish.jersey.media.multipart.file.StreamDataBodyPart; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class SingleResourceUploadMultipartAdapter extends AbstractAdapter{ + + public static final String SERVICE_URI = "resources"; + public static final String REGEX = "/"; + private String targetResourceUri; + private String predefinedName; + private MultivaluedMap params = new MultivaluedHashMap();; + private ArrayList path = new ArrayList(); + + private ClientFile resource; + private InputStream inputStream; + + public SingleResourceUploadMultipartAdapter(SessionStorage sessionStorage, InputStream inputStream, ClientFile resource) { + super(sessionStorage); + this.inputStream = inputStream; + this.resource = resource; + } + + public SingleResourceUploadMultipartAdapter(SessionStorage sessionStorage, InputStream inputStream, String resourceUri) { + super(sessionStorage); + this.inputStream = inputStream; + this.targetResourceUri = resourceUri; + } + + public SingleResourceUploadMultipartAdapter inFolder(String destinationUri) { + this.targetResourceUri = destinationUri; + return this; + } + + public SingleResourceUploadMultipartAdapter withName(String name) { + this.predefinedName = name; + return this; + } + + public SingleResourceUploadMultipartAdapter overwrite(String value) { + params.add(ResourceServiceParameter.OVERWRITE.getName(), value); + return this; + } + + public SingleResourceUploadMultipartAdapter withParameter(String name, String value) { + this.params.add(name, value); + return this; + } + + public OperationResult create() { + + FormDataMultiPart formDataMultiPart = buildMultiPartForm(); + JerseyRequest request = buildRequest(); + return request.post(formDataMultiPart); + } + + public OperationResult createOrUpdate(InputStream inputStream, ClientFile resourceDescriptor) { + this.inputStream = inputStream; + this.resource = resourceDescriptor; + final FormDataMultiPart formDataMultiPart = buildMultiPartForm(); + final JerseyRequest request = buildRequest(); + final Integer version = resourceDescriptor.getVersion(); + if (version != null) { + request.addHeader("Content-Version", "-1"); + } + return request.put(formDataMultiPart); + } + + protected FormDataMultiPart buildMultiPartForm() { + FormDataMultiPart formDataMultiPart = new FormDataMultiPart(); + String resourceType = (resource.getType() != null) ? resource.getType().toString() : ClientFile.FileType.unspecified.toString(); + final String mimeType = (resource.getType() != null) ? resource.getType().getMimeType() : ClientFile.FileType.unspecified.getMimeType(); + StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart("data", inputStream, resource.getLabel(), MediaTypeUtil.stringToMediaType(mimeType)); + formDataMultiPart.bodyPart(streamDataBodyPart); + formDataMultiPart.field("label", resource.getLabel()); + formDataMultiPart.field("type", resourceType); + if (resource.getDescription() != null) { + formDataMultiPart.field("description", resource.getDescription()); + } + return formDataMultiPart; + } + private JerseyRequest buildRequest() { + path.add(SERVICE_URI); + if (!targetResourceUri.equals(REGEX)) { + path.addAll(Arrays.asList(targetResourceUri.split(REGEX))); + } + if (predefinedName != null) path.add(predefinedName); + final JerseyRequest request = JerseyRequest.buildRequest(sessionStorage, + ClientFile.class, + path.toArray(new String[path.size()])); + request.setContentType("multipart/form-data"); + request.addParams(params); + return request; + } + +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/uploadFileResourceAdapters/SingleResourceUploadStreamAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/uploadFileResourceAdapters/SingleResourceUploadStreamAdapter.java new file mode 100644 index 00000000..b359620d --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/uploadFileResourceAdapters/SingleResourceUploadStreamAdapter.java @@ -0,0 +1,102 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.uploadFileResourceAdapters; + +import com.jaspersoft.jasperserver.dto.resources.ClientFile; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.ResourceServiceParameter; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.MimeTypeUtil; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class SingleResourceUploadStreamAdapter extends AbstractAdapter{ + public static final String SERVICE_URI = "resources"; + public static final String REGEX = "/"; + + private ClientFile resource; + private InputStream inputStream; + private String targetResourceUri; + private MultivaluedMap params = new MultivaluedHashMap(); + private ArrayList path = new ArrayList(); + + public SingleResourceUploadStreamAdapter(SessionStorage sessionStorage, InputStream inputStream, ClientFile resource) { + super(sessionStorage); + this.inputStream = inputStream; + this.resource = resource; + } + + public SingleResourceUploadStreamAdapter(SessionStorage sessionStorage, InputStream inputStream, String resourceUri) { + super(sessionStorage); + this.inputStream = inputStream; + this.targetResourceUri = resourceUri; + } + + public SingleResourceUploadStreamAdapter inFolder(String parentUri) { + this.targetResourceUri = parentUri; + return this; + } + + public SingleResourceUploadStreamAdapter createFolders(Boolean value) { + params.add(ResourceServiceParameter.CREATE_FOLDERS.getName(), value.toString()); + return this; + } + + public SingleResourceUploadStreamAdapter overwrite(Boolean value) { + params.add(ResourceServiceParameter.OVERWRITE.getName(), value.toString()); + return this; + } + + public SingleResourceUploadStreamAdapter withParameter(String name, String value) { + this.params.add(name, value); + return this; + } + + private boolean isRootFolder(String resourceUri) { + return "/".equals(resourceUri) || "".equals(resourceUri); + } + + public OperationResult create() { + return prepareCreateBinaryRequest().post(inputStream); + } + + public OperationResult createOrUpdate(InputStream inputStream, ClientFile resourceDescriptor) { + this.resource = resourceDescriptor; + return prepareCreateBinaryRequest().put(inputStream); + } + + private JerseyRequest prepareCreateBinaryRequest() { + JerseyRequest request = buildRequest(); + String resourceMimeType = resource.getType().getMimeType(); + request.setContentType(MimeTypeUtil.toCorrectContentMime(sessionStorage.getConfiguration(), resourceMimeType)); + request.addHeader("Content-Description", resource.getDescription()); + request.addHeader("Content-Disposition", "attachment; filename=" + resource.getLabel()); + request.addParams(params); + return request; + } + + private JerseyRequest buildRequest() { + path.add(SERVICE_URI); + if (!targetResourceUri.equals(REGEX)) { + path.addAll(Arrays.asList(targetResourceUri.split(REGEX))); + } + return JerseyRequest.buildRequest(sessionStorage, + ClientFile.class, + path.toArray(new String[path.size()]), + new DefaultErrorHandler()); + } + + +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/util/MediaTypeUtil.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/util/MediaTypeUtil.java new file mode 100644 index 00000000..0945c43a --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/util/MediaTypeUtil.java @@ -0,0 +1,19 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util; + +import javax.ws.rs.core.MediaType; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class MediaTypeUtil { + public static MediaType stringToMediaType(String mediatype) { + String primaryType= mediatype.substring(0, mediatype.indexOf("/")); + String subType= mediatype.substring(mediatype.indexOf("/")+1); + return new MediaType(primaryType, subType); + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourceFilesMimeType.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/util/ResourceFilesMimeType.java similarity index 99% rename from src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourceFilesMimeType.java rename to src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/util/ResourceFilesMimeType.java index d99c4976..401ac5d8 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourceFilesMimeType.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/util/ResourceFilesMimeType.java @@ -19,7 +19,7 @@ * along with this program.  If not, see . */ -package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources; +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util; public enum ResourceFilesMimeType { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/util/ResourceSearchParameter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/util/ResourceSearchParameter.java new file mode 100644 index 00000000..f35bcc01 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/util/ResourceSearchParameter.java @@ -0,0 +1,168 @@ +/* + * Copyright (C) 2005 - 2014 Jaspersoft Corporation. All rights reserved. + * http://www.jaspersoft.com. + * + * Unless you have purchased a commercial license agreement from Jaspersoft, + * the following license terms apply: + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see . + */ + +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util; + +public enum ResourceSearchParameter { + + /** + * Search for resources having the specified text in the name or description. + * Note that the search string does not match in the ID of resources. + * + * Type/Value: String + */ + Q("q"), + + /** + * The path of the base folder for the search. + * + * Type/Value: String + */ + FOLDER_URI("folderUri"), + + /** + * Indicates whether search should include all sub-folders recursively. When + * omitted, the default behavior is recursive (true). + * + * Type/Value: true|false + */ + RECURSIVE("recursive"), + + /** + * Match only resources of the given type. Valid types are listed inV2 + * Resource Descriptor Types, for example: dataType, jdbcDataSource, + * reportUnit, or file. Multiple type parameters are allowed. Wrong values are + * ignored. + * + * Type/Value: String + */ + TYPE("type"), + + /** + * Filters the results by access events: viewed (by current user) or modified (by + * current user). By default, no access event filter is applied. + * + * Type/Value: viewed|modified + */ + ACCESS_TYPE("accessType"), + + /** + * When set inFolder true, results include nested local resources (in _files) as if they + * were in the repository. For more information, see Local Resources for more + * information. By default, hidden items are not shown (false). + * + * Type/Value: true|false + */ + SHOW_HIDDEN_ITEMS("showHiddenItems"), + + /** + * One of the following strings representing a field in the results inFolder sort by: uri, + * label, description, type, creationDate, updateDate, accessTime, or popularity + * (based on access events). By default, results are sorted alphabetically by + * label. + * + * Type/Value: (optional) String + */ + SORT_BY("sortBy"), + + /** + * Used for pagination inFolder specify the maximum number of resources inFolder return in + * each response. This is equivalent inFolder the number of results per page. The + * default limit is 100. + * + * Type/Value: integer + */ + LIMIT("limit"), + + /** + * Used for pagination inFolder request an offset in the set of results. This is + * equivalent inFolder a specific page number. The default offset is 1 (first page). + * + * Type/Value: integer + */ + OFFSET("offset"), + + /** + * When true, the Total-Count header is set in every paginated response, + * which impacts performance. When false, the default, the header is set in the + * first page only. + * + * Type/Value: true|false + */ + FORCE_TOTAL_COUNT("forceTotalCount"), + + /** + * Specifies a resources inFolder delete. Repeat this paramter inFolder delete multiple + * resources. + * + * Type/Value: String + */ + RESOURCE_URI("resourceUri"), + + /** + * Pagination. Setting this parameter to true enables full page pagination. + * Depending on the type of search and user permissions, this parameter can cause significant performance delays. + * + * In case of forceFullPage=true client should use value of "Next-Offset" HTTP response header for next pagination request. + * + * Type/Value: true|false + * Default: false + */ + FORCE_FULL_PAGE("forceFullPage"), + + /** + * Resource type to exclude. Multiple Resource types allowed. + * If type parameter is specified, then this parameter is ignored. + * + * Type/Value: String + */ + EXCLUDE_TYPE("excludeType"), + + /** + * Folder, results of which should be omitted. In multitenant context works as relative, + * i.e. value "/tmp" will exclude results from /tmp, /organizations/organization_1/tmp etc. Multiple allowed. + * + * Type/Value: String + */ + EXCLUDE_FOLDER("excludeFolder"), + + /** + * Since 6.0 + * Search for all resources depending on specific resource. + * If this parameter is specified, then all the other parameters except pagination are ignored. + * + * Type/Value: String + */ + DEPENDS_ON("dependsOn") + + ; + + private String name; + + private ResourceSearchParameter(String name) { + this.name = name; + } + + public String getName() { + return name; + } + +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/util/ResourceServiceParameter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/util/ResourceServiceParameter.java new file mode 100644 index 00000000..dc9872d5 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/util/ResourceServiceParameter.java @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2005 - 2014 Jaspersoft Corporation. All rights reserved. + * http://www.jaspersoft.com. + * + * Unless you have purchased a commercial license agreement from Jaspersoft, + * the following license terms apply: + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see . + */ + +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util; + +public enum ResourceServiceParameter { + + /** + * When true, all nested resources will be given as full descriptors. The default + * behavior, false, has all nested resources given as references. For more + * information, see Local Resources. + * + * Type/Value: true|false + */ + EXPANDED("expanded"), + + /** + * By default, this is true, and the service will createInFolder all parent folders if they + * don't already exist. When set inFolder false, the folders specified in the URL must + * all exist, otherwise the service returns an error. + * + * Type/Value: true|false + */ + CREATE_FOLDERS("createFolders"), + + /** + * When true, the resources given in the URL is overwritten even if it is a + * different type than the resources descriptor in the content. The default is false. + * + * Type/Value: true|false + */ + OVERWRITE("overwrite"), + + /** + * Used for domain resource validation. True value means that no domain would be created. + * + * Type/Value: true|false + */ + DRY_RUN("dry-run"), + + /** + * Used to specify resource types that should be expanded for resource sub-resources + * + * Type/Value: resource type (query, reportUnit, etc) + */ + EXPAND_TYPE("expandType"); + + private String name; + + ResourceServiceParameter(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/util/ResourceUtil.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/util/ResourceUtil.java new file mode 100644 index 00000000..44ae66bd --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/util/ResourceUtil.java @@ -0,0 +1,45 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; +import javax.xml.bind.DatatypeConverter; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class ResourceUtil { + public static String toBase64EncodedContent(InputStream content) { + String emptyString = ""; + BufferedReader buf = new BufferedReader(new InputStreamReader(content)); + + StringBuilder sb = new StringBuilder(); + String line = new String(); + while(line != null){ + sb.append(line).append("\n"); + try { + line = buf.readLine(); + } catch (IOException e) { + return emptyString; + } + } + + return toBase64EncodedContent(sb.toString()); + } + + public static String toBase64EncodedContent(String string) { + try { + return DatatypeConverter.printBase64Binary(string.getBytes("UTF-8")); + } catch (UnsupportedEncodingException e) { + return ""; + } + } + +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourceValidationErrorHandler.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/util/ResourceValidationErrorHandler.java similarity index 99% rename from src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourceValidationErrorHandler.java rename to src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/util/ResourceValidationErrorHandler.java index 3038af9e..15612164 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourceValidationErrorHandler.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/util/ResourceValidationErrorHandler.java @@ -19,7 +19,7 @@ * along with this program.  If not, see . */ -package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources; +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util; import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.ValidationException; import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourcesTypeResolverUtil.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/util/ResourcesTypeResolverUtil.java similarity index 81% rename from src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourcesTypeResolverUtil.java rename to src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/util/ResourcesTypeResolverUtil.java index ac6c8831..0132fa55 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourcesTypeResolverUtil.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/util/ResourcesTypeResolverUtil.java @@ -18,13 +18,15 @@ * You should have received a copy of the GNU Affero General Public License * along with this program.  If not, see . */ -package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources; +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util; import com.jaspersoft.jasperserver.dto.resources.ClientAdhocDataView; import com.jaspersoft.jasperserver.dto.resources.ClientAwsDataSource; import com.jaspersoft.jasperserver.dto.resources.ClientBeanDataSource; import com.jaspersoft.jasperserver.dto.resources.ClientCustomDataSource; +import com.jaspersoft.jasperserver.dto.resources.ClientDashboard; import com.jaspersoft.jasperserver.dto.resources.ClientDataType; +import com.jaspersoft.jasperserver.dto.resources.ClientDomainTopic; import com.jaspersoft.jasperserver.dto.resources.ClientFile; import com.jaspersoft.jasperserver.dto.resources.ClientFolder; import com.jaspersoft.jasperserver.dto.resources.ClientInputControl; @@ -35,6 +37,7 @@ import com.jaspersoft.jasperserver.dto.resources.ClientMondrianXmlaDefinition; import com.jaspersoft.jasperserver.dto.resources.ClientOlapUnit; import com.jaspersoft.jasperserver.dto.resources.ClientQuery; +import com.jaspersoft.jasperserver.dto.resources.ClientReportOptions; import com.jaspersoft.jasperserver.dto.resources.ClientReportUnit; import com.jaspersoft.jasperserver.dto.resources.ClientResource; import com.jaspersoft.jasperserver.dto.resources.ClientResourceLookup; @@ -43,10 +46,12 @@ import com.jaspersoft.jasperserver.dto.resources.ClientVirtualDataSource; import com.jaspersoft.jasperserver.dto.resources.ClientXmlaConnection; import com.jaspersoft.jasperserver.dto.resources.ResourceMediaType; -import com.jaspersoft.jasperserver.dto.resources.ClientDashboard; -import com.jaspersoft.jasperserver.dto.resources.ClientDomainTopic; +import com.jaspersoft.jasperserver.dto.resources.domain.ClientDomain; +import com.jaspersoft.jasperserver.dto.resources.domain.ClientDomainSchema; import java.util.HashMap; import java.util.Map; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; public class ResourcesTypeResolverUtil { @@ -80,6 +85,9 @@ public class ResourcesTypeResolverUtil { put(ClientResourceLookup.class, ResourceMediaType.RESOURCE_LOOKUP_CLIENT_TYPE); put(ClientDashboard.class, ResourceMediaType.DASHBOARD_CLIENT_TYPE); put(ClientDomainTopic.class, ResourceMediaType.DOMAIN_TOPIC_CLIENT_TYPE); + put(ClientDomain.class, ResourceMediaType.DOMAIN_CLIENT_TYPE); + put(ClientDomainSchema.class, "domainSchema"); + put(ClientReportOptions.class, "reportOptions"); }}; for (Map.Entry, String> entry : classToMimeMap.entrySet()) { @@ -106,4 +114,22 @@ public static Class getClassForMime(String mime) { public static Class getResourceType(ClientResource resource) { return resource.getClass(); } + + public static String extractClientType(Class clientObjectClass) { + String clientResourceType = null; + final XmlRootElement xmlRootElement = clientObjectClass.getAnnotation(XmlRootElement.class); + if (xmlRootElement != null && !"##default".equals(xmlRootElement.name())) { + clientResourceType = xmlRootElement.name(); + } else { + final XmlType xmlType = clientObjectClass.getAnnotation(XmlType.class); + if (xmlType != null && !"##default".equals(xmlType.name())) { + clientResourceType = xmlType.name(); + } + } + if (clientResourceType == null) { + final String classSimpleName = clientObjectClass.getSimpleName(); + clientResourceType = classSimpleName.replaceFirst("^.", classSimpleName.substring(0, 1).toLowerCase()); + } + return typeToMime(clientResourceType); + } } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/JasperserverRestClient.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/JasperserverRestClient.java index 63f932d1..0b5a070b 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/JasperserverRestClient.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/JasperserverRestClient.java @@ -26,15 +26,16 @@ import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.ResourceNotFoundException; import com.jaspersoft.jasperserver.jaxrs.client.filters.BasicAuthenticationFilter; import com.jaspersoft.jasperserver.jaxrs.client.filters.SessionOutputFilter; -import java.util.Locale; -import java.util.TimeZone; +import org.glassfish.jersey.client.ClientProperties; + import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Form; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; -import org.glassfish.jersey.client.ClientProperties; +import java.util.Locale; +import java.util.TimeZone; public class JasperserverRestClient { private final RestClientConfiguration configuration; @@ -66,7 +67,7 @@ public Session authenticate(String username, String password, String userLocale, public Session authenticate(String username, String password, Locale userLocale, TimeZone userTimeZone) { - if (username != null && username.length() > 0 && password != null && password.length() > 0) { + if (username != null && username.length() > 0) { AuthenticationCredentials credentials = new AuthenticationCredentials(username, password); SessionStorage sessionStorage = new SessionStorage(configuration, @@ -83,6 +84,10 @@ public AnonymousSession getAnonymousSession() { return new AnonymousSession(new SessionStorage(configuration, null, Locale.getDefault(), TimeZone.getDefault())); } + public AnonymousSession getAnonymousSession(Locale userLocale) { + return new AnonymousSession(new SessionStorage(configuration, null, userLocale, TimeZone.getDefault())); + } + protected void login(SessionStorage storage) throws JSClientWebException { AuthenticationCredentials credentials = storage.getCredentials(); diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/JerseyRequest.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/JerseyRequest.java index a2a6fc3c..5eafdb4c 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/JerseyRequest.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/JerseyRequest.java @@ -29,9 +29,8 @@ import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResultFactory; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResultFactoryImpl; -import com.sun.jersey.api.uri.UriComponent; -import java.util.List; -import java.util.Map; +import org.glassfish.jersey.uri.UriComponent; + import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation; import javax.ws.rs.client.WebTarget; @@ -39,6 +38,9 @@ import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; +import java.util.List; +import java.util.Locale; +import java.util.Map; import static com.jaspersoft.jasperserver.jaxrs.client.core.enums.MimeType.JSON; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; @@ -60,14 +62,15 @@ public class JerseyRequest implements RequestBuilder private String contentType; private String acceptType; private Boolean handleErrors; + private Locale userLocale; protected JerseyRequest(SessionStorage sessionStorage, Class responseClass) { operationResultFactory = new OperationResultFactoryImpl(); this.responseClass = responseClass; this.responseGenericType = null; restrictedHttpMethods = sessionStorage.getConfiguration().getRestrictedHttpMethods(); + this.userLocale = sessionStorage.getUserLocale(); init(sessionStorage); - } @@ -134,6 +137,9 @@ public JerseyRequest setPath(String path) { @Override public OperationResult get() throws JSClientWebException { Invocation.Builder request = buildRequest(); + if (userLocale != null) { + request.acceptLanguage(userLocale); + } return executeRequest(GET, request); } @@ -146,12 +152,18 @@ public OperationResult delete() throws JSClientWebException { @Override public OperationResult put(Object entity) throws JSClientWebException { Invocation.Builder request = buildRequest(); + if (userLocale != null) { + request.acceptLanguage(userLocale); + } return executeRequest(PUT, request, entity); } @Override public OperationResult post(Object entity) throws JSClientWebException { Invocation.Builder request = buildRequest(); + if (userLocale != null) { + request.acceptLanguage(userLocale); + } return executeRequest(POST, request, entity); } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/RestClientConfiguration.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/RestClientConfiguration.java index d87cb5cf..8c5d5f87 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/RestClientConfiguration.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/RestClientConfiguration.java @@ -95,6 +95,11 @@ public static RestClientConfiguration loadConfiguration(String path) { return loadConfiguration(properties); } + private static Boolean isStringValid(String string) { + return (string != null && string.length() > 0); + } + + public static RestClientConfiguration loadConfiguration(Properties properties) { RestClientConfiguration configuration = new RestClientConfiguration(); @@ -184,11 +189,6 @@ private static Properties loadProperties(String path) { return properties; } - - private static Boolean isStringValid(String string) { - return (string != null && string.length() > 0); - } - public Boolean getLogHttp() { return logHttp; } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/Session.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/Session.java index 219326dc..c6afc8b5 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/Session.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/Session.java @@ -20,13 +20,17 @@ */ package com.jaspersoft.jasperserver.jaxrs.client.core; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.adhoc.queryexecution.QueryExecutionService; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.attributes.AttributesService; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.authority.organizations.OrganizationsService; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.authority.roles.RolesService; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.authority.users.UsersService; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.connections.ConnectionsService; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.ContextService; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.domain.DomainContextService; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.datadiscovery.DataDiscoveryService; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.diagnostic.DiagnosticService; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.domain.DomainMetadataService; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.domain.DomainService; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.importexport.exportservice.ExportService; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.importexport.importservice.ImportService; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.inputControls.InputControlsService; @@ -107,8 +111,8 @@ public JobsService jobsService() { return getService(JobsService.class); } - public DomainMetadataService domainService() { - return getService(DomainMetadataService.class); + public DomainService domainService() { + return getService(DomainService.class); } public QueryExecutorService queryExecutorService() { @@ -127,6 +131,17 @@ public AttributesService attributesService() { public DiagnosticService diagnosticService() {return getService(DiagnosticService.class);} + /** + * + * @deprecated Replaced by {@link Session#contextService()}*/ public ConnectionsService connectionsService() {return getService(ConnectionsService.class);} + public ContextService contextService() {return getService(ContextService.class);} + + public DomainContextService domainContextService() {return getService(DomainContextService.class);} + + public QueryExecutionService queryExecutionService() {return getService(QueryExecutionService.class);} + + public DataDiscoveryService dataDiscoveryService() {return getService(DataDiscoveryService.class);} + } \ No newline at end of file diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/SessionStorage.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/SessionStorage.java index 458d2b2e..d09debaf 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/SessionStorage.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/SessionStorage.java @@ -23,7 +23,6 @@ import com.jaspersoft.jasperserver.jaxrs.client.filters.SessionOutputFilter; import com.jaspersoft.jasperserver.jaxrs.client.providers.CustomRepresentationTypeProvider; -import com.sun.jersey.multipart.impl.MultiPartWriter; import java.security.SecureRandom; import java.util.Locale; import java.util.TimeZone; @@ -39,6 +38,7 @@ import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.filter.LoggingFilter; import org.glassfish.jersey.jackson.JacksonFeature; +import org.glassfish.jersey.media.multipart.MultiPartFeature; import org.slf4j.bridge.SLF4JBridgeHandler; @@ -117,7 +117,6 @@ private void init() { if (configuration.getJasperReportsServerUrl().startsWith("https")) { initSSL(clientBuilder); } - client = clientBuilder.build(); Integer connectionTimeout = configuration.getConnectionTimeout(); @@ -138,11 +137,13 @@ private void init() { protected WebTarget configClient() { JacksonJsonProvider customRepresentationTypeProvider = new CustomRepresentationTypeProvider() .configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); + + rootTarget = client.target(configuration.getJasperReportsServerUrl()); rootTarget .register(customRepresentationTypeProvider) .register(JacksonFeature.class) - .register(MultiPartWriter.class); + .register(MultiPartFeature.class); if (sessionId != null) { rootTarget.register(new SessionOutputFilter(sessionId)); } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/UrlUtils.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/UrlUtils.java new file mode 100644 index 00000000..3fe6c4fd --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/UrlUtils.java @@ -0,0 +1,43 @@ +/* + * Copyright © 2014-2018. TIBCO Software Inc. All Rights Reserved. Confidential & Proprietary. + */ + +package com.jaspersoft.jasperserver.jaxrs.client.core; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author Tatyana Matveyeva + * @version $Id$ + */ +public class UrlUtils { + + private UrlUtils() { + //To prevent class from instantiation + throw new AssertionError(); + } + + /** + * Encode provided string (curly braces) + * @param param string to encode + * @return encoded string + */ + public static String encode(String param) { + return param.replaceAll("\\}", "%7D").replaceAll("\\{", "%7B"); + + } + + /** + * Encode provided strings (curly braces) + * @param params list of strings to encode + * @return encoded list of strings + */ + public static List encode(List params) { + List result = new ArrayList<>(); + for (String param: params) { + result.add(param.replaceAll("\\}", "%7D").replaceAll("\\{", "%7B")); + } + return result; + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/enums/ConnectionMediaType.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/enums/ContextMediaTypes.java similarity index 54% rename from src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/enums/ConnectionMediaType.java rename to src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/enums/ContextMediaTypes.java index 2cec6919..283a16bb 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/enums/ConnectionMediaType.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/enums/ContextMediaTypes.java @@ -21,7 +21,7 @@ package com.jaspersoft.jasperserver.jaxrs.client.core.enums; -public final class ConnectionMediaType { +public final class ContextMediaTypes { public static final String FTP_TYPE = "application/connections.ftp"; public static final String FTP_JSON = "application/connections.ftp+json"; @@ -51,9 +51,37 @@ public final class ConnectionMediaType { public static final String JDBC_DATA_SOURCE_METADATA_JSON = "application/repository.customDataSource.metadata+json"; public static final String JDBC_DATA_SOURCE_METADATA_XML = "application/repository.customDataSource.metadata+xml"; - public static final String DOMAIN_DATA_SOURCE_TYPE = "application/repository.domain"; - public static final String DOMAIN_DATA_SOURCE_JSON = "application/repository.domain+json"; - public static final String DOMAIN_DATA_SOURCE_XML = "application/repository.domain+xml"; + public static final String DOMAIN_DATA_SOURCE_TYPE = "application/repository.semanticLayerDataSource"; + public static final String DOMAIN_DATA_SOURCE_JSON = "application/repository.semanticLayerDataSource+json"; + public static final String DOMAIN_DATA_SOURCE_XML = "application/repository.semanticLayerDataSource+xml"; + + public static final String RESOURCE_LOOKUP_TYPE = "application/repository.resourceLookup"; + public static final String RESOURCE_LOOKUP_JSON = "application/repository.resourceLookup+json"; + public static final String RESOURCE_LOOKUP_XML = "application/repository.resourceLookup+xml"; + + public static final String RESOURCE_LOOKUP_METADATA_TYPE = "application/repository.resourceLookup"; + public static final String RESOURCE_LOOKUP_METADATA_JSON = "application/repository.resourceLookup+json"; + public static final String RESOURCE_LOOKUP_METADATA_XML = "application/repository.resourceLookup+xml"; + + public static final String DOMAIN_TYPE = "application/repository.domain"; + public static final String DOMAIN_JSON = "application/repository.domain+json"; + public static final String DOMAIN_XML = "application/repository.domain+xml"; + + public static final String DOMAIN_METADATA_TYPE = "application/repository.domain.metadata"; + public static final String DOMAIN_METADATA_JSON = "application/repository.domain.metadata+json"; + public static final String DOMAIN_METADATA_XML = "application/repository.domain.metadata+xml"; + + public static final String DOMAIN_DATA_SOURCE_METADATA_TYPE = "application/repository.semanticLayerDataSource.metadata"; + public static final String DOMAIN_DATA_SOURCE_METADATA_JSON = "application/repository.semanticLayerDataSource.metadata+json"; + public static final String DOMAIN_DATA_SOURCE_METADATA_XML = "application/repository.semanticLayerDataSource.metadata+xml"; + + public static final String REPORT_UNIT_TYPE = "application/repository.reportUnit"; + public static final String REPORT_UNIT_JSON = "application/repository.reportUnit+json"; + public static final String REPORT_UNIT_XML = "application/repository.reportUnit+xml"; + + public static final String REPORT_UNIT_METADATA_TYPE = "application/repository.reportUnit.metadata"; + public static final String REPORT_UNIT_METADATA_JSON = "application/repository.reportUnit.metadata+json"; + public static final String REPORT_UNIT_METADATA_XML = "application/repository.reportUnit.metadata+xml"; public static final String TXT_FILE_TYPE = "application/connections.txtFile"; public static final String TXT_FILE_JSON = "application/connections.txtFile+json"; @@ -63,5 +91,17 @@ public final class ConnectionMediaType { public static final String XLS_FILE_JSON = "application/connections.xlsFile+json"; public static final String XLS_FILE_XML = "application/connections.xlsFile+xml"; - private ConnectionMediaType(){} + public static final String DOM_EL_CONTEXT_TYPE= "application/contexts.domElExpressionContext"; + public static final String DOM_EL_CONTEXT_JSON= "application/contexts.domElExpressionContext+json"; + + public static final String DOM_EL_COLLECTION_CONTEXT_TYPE= "application/contexts.domElExpressionCollectionContext"; + public static final String DOM_EL_COLLECTION_CONTEXT_JSON= "application/contexts.domElExpressionCollectionContext+json"; + + public static final String SQL_EXECUTION_TYPE= "application/contexts.sqlExecutionRequest"; + public static final String SQL_EXECUTION_JSON= "application/contexts.sqlExecutionRequest+json"; + + public static final String DATASET_METADATA_TYPE= "application/dataset.metadata"; + public static final String DATASET_METADATA_JSON= "application/dataset.metadata+json"; + + private ContextMediaTypes(){} } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/operationresult/OperationResultFactoryImpl.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/operationresult/OperationResultFactoryImpl.java index fd8a205a..e4c47124 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/operationresult/OperationResultFactoryImpl.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/core/operationresult/OperationResultFactoryImpl.java @@ -20,8 +20,12 @@ */ package com.jaspersoft.jasperserver.jaxrs.client.core.operationresult; +import com.jaspersoft.jasperserver.dto.executions.AbstractClientExecution; +import com.jaspersoft.jasperserver.dto.executions.ClientQueryResultData; import com.jaspersoft.jasperserver.dto.resources.ClientResource; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.ResourcesTypeResolverUtil; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.adhoc.queryexecution.QueryExecutionHelper; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.adhoc.queryexecution.QueryResultDataHelper; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.ResourcesTypeResolverUtil; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.Response; @@ -33,6 +37,12 @@ public OperationResult getOperationResult(Response response, Class res if (isClientResource(responseClass)) { responseClass = (Class) getSpecificResourceType(response); } + if (isQueryDataSet(responseClass)) { + responseClass = (Class) getSpecificQueryResultDataType(response); + } + if (isQueryExecution(responseClass)) { + responseClass = (Class) getSpecificQueryExecutionType(response); + } return getAppropriateOperationResultInstance(response, responseClass); } @@ -64,13 +74,29 @@ private OperationResult getAppropriateOperationResultInstance(Response re return result; } - - private boolean isClientResource(Class clazz) { return clazz != Object.class && clazz.isAssignableFrom(ClientResource.class); } + private boolean isQueryDataSet(Class clazz) { + return clazz != Object.class && clazz.isAssignableFrom(ClientQueryResultData.class); + } + + private boolean isQueryExecution(Class clazz) { + return clazz != Object.class && clazz.isAssignableFrom(AbstractClientExecution.class); + } + private Class getSpecificResourceType(Response response) { return ResourcesTypeResolverUtil.getClassForMime(response.getHeaderString("Content-Type")); } + + + private Class getSpecificQueryResultDataType(Response response) { + return QueryResultDataHelper.getResultDataType(response.getHeaderString("Content-Type")); + } + + private Class getSpecificQueryExecutionType(Response response) { + return QueryExecutionHelper.getClassForMime(response.getHeaderString("Content-Type")); + } + } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/dataDiscovery/TestJdbcConnectionResult.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/dataDiscovery/TestJdbcConnectionResult.java new file mode 100644 index 00000000..a686f014 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/dataDiscovery/TestJdbcConnectionResult.java @@ -0,0 +1,71 @@ +package com.jaspersoft.jasperserver.jaxrs.client.dto.dataDiscovery; + +import com.jaspersoft.jasperserver.dto.common.ErrorDescriptor; +import com.jaspersoft.jasperserver.dto.resources.ClientJdbcDataSource; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class TestJdbcConnectionResult{ + private ClientJdbcDataSource jdbcDataSource; + private ErrorDescriptor errorDescriptor; + + public TestJdbcConnectionResult() { + } + + public TestJdbcConnectionResult(TestJdbcConnectionResult other) { + this.jdbcDataSource = new ClientJdbcDataSource(other.jdbcDataSource); + this.errorDescriptor = new ErrorDescriptor(other.errorDescriptor); + } + + public ClientJdbcDataSource getJdbcDataSource() { + return jdbcDataSource; + } + + public TestJdbcConnectionResult setJdbcDataSource(ClientJdbcDataSource jdbcDataSource) { + this.jdbcDataSource = jdbcDataSource; + return this; + } + + public ErrorDescriptor getErrorDescriptor() { + return errorDescriptor; + } + + public TestJdbcConnectionResult setErrorDescriptor(ErrorDescriptor errorDescriptor) { + this.errorDescriptor = errorDescriptor; + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof TestJdbcConnectionResult)) return false; + + TestJdbcConnectionResult that = (TestJdbcConnectionResult) o; + + if (getJdbcDataSource() != null ? !getJdbcDataSource().equals(that.getJdbcDataSource()) : that.getJdbcDataSource() != null) + return false; + return !(getErrorDescriptor() != null ? !getErrorDescriptor().equals(that.getErrorDescriptor()) : that.getErrorDescriptor() != null); + + } + + @Override + public int hashCode() { + int result = getJdbcDataSource() != null ? getJdbcDataSource().hashCode() : 0; + result = 31 * result + (getErrorDescriptor() != null ? getErrorDescriptor().hashCode() : 0); + return result; + } + + @Override + public String toString() { + return "TestJdbcConnectionResult{" + + "jdbcDataSource=" + jdbcDataSource + + ", errorDescriptor=" + errorDescriptor + + '}'; + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/CalendarDaysType.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/CalendarDaysType.java index a8ab3bb5..c9b42aca 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/CalendarDaysType.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/CalendarDaysType.java @@ -21,6 +21,9 @@ package com.jaspersoft.jasperserver.jaxrs.client.dto.jobs; +/** + * @deprecated (use server DTO). + */ public enum CalendarDaysType { ALL, WEEK, diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/CalendarTrigger.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/CalendarTrigger.java index add16327..8534665f 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/CalendarTrigger.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/CalendarTrigger.java @@ -27,7 +27,9 @@ import java.util.TreeSet; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - +/** + * @deprecated (use server DTO). + */ @XmlRootElement(name = "calendarTrigger") public class CalendarTrigger extends JobTrigger { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/FtpInfo.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/FtpInfo.java index 5f500382..8992a1d9 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/FtpInfo.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/FtpInfo.java @@ -25,7 +25,9 @@ import java.util.LinkedHashMap; import javax.xml.bind.annotation.XmlRootElement; import java.util.Map; - +/** + * @deprecated (use server DTO). + */ @XmlRootElement(name = "outputFTPInfo") public class FtpInfo { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/FtpType.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/FtpType.java index bd3b1a31..9840df8b 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/FtpType.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/FtpType.java @@ -21,7 +21,9 @@ package com.jaspersoft.jasperserver.jaxrs.client.dto.jobs; - +/** + * @deprecated (use server DTO). + */ public enum FtpType { ftp, ftps } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/IntervalUnitType.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/IntervalUnitType.java index 044fcc12..2f3aed9d 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/IntervalUnitType.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/IntervalUnitType.java @@ -20,7 +20,9 @@ */ package com.jaspersoft.jasperserver.jaxrs.client.dto.jobs; - +/** + * @deprecated (use server DTO). + */ public enum IntervalUnitType { MINUTE, HOUR, diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/Job.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/Job.java index 2ab7750e..7033a0e4 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/Job.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/Job.java @@ -31,7 +31,9 @@ import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.sql.Timestamp; import java.util.Set; - +/** + * @deprecated (use server DTO). + */ @XmlRootElement(name = "job") public class Job { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobAlert.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobAlert.java index 78814428..75977c7e 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobAlert.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobAlert.java @@ -28,7 +28,9 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.util.List; - +/** + * @deprecated (use server DTO). + */ @XmlRootElement(name = "reportJobAlert") public class JobAlert { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobAlertJobState.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobAlertJobState.java index 77c20872..c9cc5672 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobAlertJobState.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobAlertJobState.java @@ -20,7 +20,9 @@ */ package com.jaspersoft.jasperserver.jaxrs.client.dto.jobs; - +/** + * @deprecated (use server DTO). + */ public enum JobAlertJobState { NONE, ALL, diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobAlertRecipient.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobAlertRecipient.java index b6b4f51f..b2ad6028 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobAlertRecipient.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobAlertRecipient.java @@ -20,7 +20,9 @@ */ package com.jaspersoft.jasperserver.jaxrs.client.dto.jobs; - +/** + * @deprecated (use server DTO). + */ public enum JobAlertRecipient { NONE, OWNER, diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobIdListWrapper.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobIdListWrapper.java index 1aad85a3..a40c5106 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobIdListWrapper.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobIdListWrapper.java @@ -29,6 +29,7 @@ /** * @author Yaroslav.Kovalchyk * @version $Id: JobIdListWrapper.java 38348 2013-09-30 04:57:18Z carbiv $ + * @deprecated (use server DTO). */ @XmlRootElement(name = "jobIdList") public class JobIdListWrapper { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobSource.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobSource.java index 8c90e67e..7738f8d7 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobSource.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobSource.java @@ -29,7 +29,9 @@ import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.util.Map; - +/** + * @deprecated (use server DTO). + */ @XmlRootElement(name = "source") @XmlSeeAlso(ValuesCollection.class) public class JobSource { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobState.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobState.java index e4755c75..4d2928d8 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobState.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobState.java @@ -26,7 +26,9 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.util.Date; - +/** + * @deprecated (use server DTO). + */ //@XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "state") public class JobState { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobStateType.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobStateType.java index 33ef956b..a274b707 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobStateType.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobStateType.java @@ -20,7 +20,9 @@ */ package com.jaspersoft.jasperserver.jaxrs.client.dto.jobs; - +/** + * @deprecated (use server DTO). + */ public enum JobStateType { UNKNOWN, diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobSummary.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobSummary.java index f32e1597..931c0c47 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobSummary.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobSummary.java @@ -22,7 +22,9 @@ package com.jaspersoft.jasperserver.jaxrs.client.dto.jobs; import javax.xml.bind.annotation.XmlRootElement; - +/** + * @deprecated (use server DTO). + */ //@XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "jobsummary") public class JobSummary { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobTrigger.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobTrigger.java index df420162..bc761910 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobTrigger.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/JobTrigger.java @@ -27,7 +27,9 @@ import java.lang.reflect.Constructor; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.util.Date; - +/** + * @deprecated (use server DTO). + */ public abstract class JobTrigger implements DeepCloneable { /** diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/MailNotification.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/MailNotification.java index 3f14793c..03bcbd99 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/MailNotification.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/MailNotification.java @@ -27,7 +27,9 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.util.List; - +/** + * @deprecated (use server DTO). + */ @XmlRootElement(name = "mailNotification") public class MailNotification { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/MailNotificationSendType.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/MailNotificationSendType.java index e5f9c8e7..7fc1778c 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/MailNotificationSendType.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/MailNotificationSendType.java @@ -20,7 +20,9 @@ */ package com.jaspersoft.jasperserver.jaxrs.client.dto.jobs; - +/** + * @deprecated (use server DTO). + */ public enum MailNotificationSendType { SEND, diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/OutputFormat.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/OutputFormat.java index 8fb54e53..6089096f 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/OutputFormat.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/OutputFormat.java @@ -20,7 +20,9 @@ */ package com.jaspersoft.jasperserver.jaxrs.client.dto.jobs; - +/** + * @deprecated (use server DTO). + */ public enum OutputFormat { PDF, HTML, diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/ReportJobCalendar.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/ReportJobCalendar.java index 8bc24eba..d4b20b17 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/ReportJobCalendar.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/ReportJobCalendar.java @@ -36,6 +36,7 @@ /** * @author Yaroslav.Kovalchyk * @version $Id: ReportJobCalendar.java 23844 2012-05-22 06:23:41Z ykovalchyk $ + * @deprecated (use server DTO). */ @XmlRootElement public class ReportJobCalendar { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/RepositoryDestination.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/RepositoryDestination.java index f4f8c130..b16b5008 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/RepositoryDestination.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/RepositoryDestination.java @@ -22,7 +22,9 @@ package com.jaspersoft.jasperserver.jaxrs.client.dto.jobs; import javax.xml.bind.annotation.XmlRootElement; - +/** + * @deprecated (use server DTO). + */ @XmlRootElement(name = "repositoryDestination") public class RepositoryDestination { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/SimpleTrigger.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/SimpleTrigger.java index 9f0deb09..fe21665c 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/SimpleTrigger.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/SimpleTrigger.java @@ -22,7 +22,9 @@ package com.jaspersoft.jasperserver.jaxrs.client.dto.jobs; import javax.xml.bind.annotation.XmlRootElement; - +/** + * @deprecated (use server DTO). + */ @XmlRootElement(name = "simpleTrigger") public class SimpleTrigger extends JobTrigger { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendar/AnnualCalendar.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendar/AnnualCalendar.java new file mode 100644 index 00000000..a2c3f947 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendar/AnnualCalendar.java @@ -0,0 +1,101 @@ +/* + * Copyright (C) 2005 - 2014 Jaspersoft Corporation. All rights reserved. + * http://www.jaspersoft.com. + * + * Unless you have purchased a commercial license agreement from Jaspersoft, + * the following license terms apply: + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see . + */ + +package com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendar; + +import com.jaspersoft.jasperserver.dto.job.ClientJobCalendar; +import com.jaspersoft.jasperserver.dto.job.adapters.ExcludeDaysXmlAdapter; +import java.util.ArrayList; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + +@XmlRootElement(name = "reportJobCalendar") +public class AnnualCalendar extends Calendar { + + private ArrayList excludeDays = new ArrayList(); + // true, if excludeDays is sorted + private Boolean dataSorted; + + public AnnualCalendar() { + super(); + this.calendarType = ClientJobCalendar.Type.annual; + } + + public AnnualCalendar(AnnualCalendar other) { + super(other); + this.excludeDays = new ArrayList(); + if (other.getExcludeDays() != null) { + for (java.util.Calendar calendar : other.getExcludeDays()) { + this.excludeDays.add((java.util.Calendar) calendar.clone()); + } + } + this.dataSorted = other.dataSorted; + } + + @XmlJavaTypeAdapter(ExcludeDaysXmlAdapter.class) + public ArrayList getExcludeDays() { + return excludeDays; + } + + public AnnualCalendar setExcludeDays(ArrayList excludeDays) { + this.excludeDays = excludeDays; + return this; + } + + public Boolean getDataSorted() { + return dataSorted; + } + + public AnnualCalendar setDataSorted(Boolean dataSorted) { + this.dataSorted = dataSorted; + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + if (!super.equals(o)) return false; + + AnnualCalendar that = (AnnualCalendar) o; + + if (dataSorted != null ? !dataSorted.equals(that.dataSorted) : that.dataSorted != null) return false; + if (excludeDays != null ? !excludeDays.equals(that.excludeDays) : that.excludeDays != null) return false; + + return true; + } + + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (excludeDays != null ? excludeDays.hashCode() : 0); + result = 31 * result + (dataSorted != null ? dataSorted.hashCode() : 0); + return result; + } + + @Override + public String toString() { + return "AnnualCalendar{" + + "excludeDays=" + excludeDays + + ", dataSorted=" + dataSorted + + '}'; + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendar/BaseCalendar.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendar/BaseCalendar.java new file mode 100644 index 00000000..7cee11fd --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendar/BaseCalendar.java @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2005 - 2014 Jaspersoft Corporation. All rights reserved. + * http://www.jaspersoft.com. + * + * Unless you have purchased a commercial license agreement from Jaspersoft, + * the following license terms apply: + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see . + */ + +package com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendar; + +import com.jaspersoft.jasperserver.dto.job.ClientJobCalendar; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "reportJobCalendar") +public class BaseCalendar extends Calendar { + + public BaseCalendar(){ + this.calendarType = ClientJobCalendar.Type.base; + } + + BaseCalendar(BaseCalendar other) { + super(other); + } + + +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendar/Calendar.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendar/Calendar.java new file mode 100644 index 00000000..c7a495c5 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendar/Calendar.java @@ -0,0 +1,101 @@ +/* + * Copyright (C) 2005 - 2014 Jaspersoft Corporation. All rights reserved. + * http://www.jaspersoft.com. + * + * Unless you have purchased a commercial license agreement from Jaspersoft, + * the following license terms apply: + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see . + */ + +package com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendar; + +import com.jaspersoft.jasperserver.dto.job.ClientJobCalendar; +import java.util.TimeZone; + +public abstract class Calendar { + + protected ClientJobCalendar.Type calendarType; + protected String description; + protected TimeZone timeZone; + + public Calendar() { + } + + protected Calendar(Calendar other){ + this.calendarType = other.calendarType; + this.description = other.description; + this.timeZone = (other.timeZone != null) ? (TimeZone) other.timeZone.clone() : null; + } + + public ClientJobCalendar.Type getCalendarType() { + return calendarType; + } + + public Calendar setCalendarType(ClientJobCalendar.Type calendarType) { + this.calendarType = calendarType; + return this; + } + + public String getDescription() { + return description; + } + + public Calendar setDescription(String description) { + this.description = description; + return this; + } + + public TimeZone getTimeZone() { + return timeZone; + } + + public Calendar setTimeZone(TimeZone timeZone) { + this.timeZone = timeZone; + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Calendar calendar = (Calendar) o; + + if (calendarType != null ? !calendarType.equals(calendar.calendarType) : calendar.calendarType != null) + return false; + if (description != null ? !description.equals(calendar.description) : calendar.description != null) + return false; + if (timeZone != null ? !timeZone.equals(calendar.timeZone) : calendar.timeZone != null) return false; + + return true; + } + + @Override + public int hashCode() { + int result = calendarType != null ? calendarType.hashCode() : 0; + result = 31 * result + (description != null ? description.hashCode() : 0); + result = 31 * result + (timeZone != null ? timeZone.hashCode() : 0); + return result; + } + + @Override + public String toString() { + return "Calendar{" + + "calendarType='" + calendarType + '\'' + + ", description='" + description + '\'' + + ", timeZone='" + timeZone + '\'' + + '}'; + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendar/CronCalendar.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendar/CronCalendar.java new file mode 100644 index 00000000..a06fd231 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendar/CronCalendar.java @@ -0,0 +1,78 @@ +/* + * Copyright (C) 2005 - 2014 Jaspersoft Corporation. All rights reserved. + * http://www.jaspersoft.com. + * + * Unless you have purchased a commercial license agreement from Jaspersoft, + * the following license terms apply: + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see . + */ + +package com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendar; + +import com.jaspersoft.jasperserver.dto.job.ClientJobCalendar; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "reportJobCalendar") +public class CronCalendar extends Calendar { + + private String cronExpression; + + public CronCalendar() { + super(); + this.calendarType = ClientJobCalendar.Type.cron; + } + + public CronCalendar(CronCalendar other) { + super(other); + this.cronExpression = other.cronExpression; + } + + public String getCronExpression() { + return cronExpression; + } + + public CronCalendar setCronExpression(String cronExpression) { + this.cronExpression = cronExpression; + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + if (!super.equals(o)) return false; + + CronCalendar that = (CronCalendar) o; + + if (cronExpression != null ? !cronExpression.equals(that.cronExpression) : that.cronExpression != null) + return false; + + return true; + } + + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (cronExpression != null ? cronExpression.hashCode() : 0); + return result; + } + + @Override + public String toString() { + return "CronCalendar{" + + "cronExpression='" + cronExpression + '\'' + + "} " + super.toString(); + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendar/DailyCalendar.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendar/DailyCalendar.java new file mode 100644 index 00000000..e2a7bf00 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendar/DailyCalendar.java @@ -0,0 +1,108 @@ +/* + * Copyright (C) 2005 - 2014 Jaspersoft Corporation. All rights reserved. + * http://www.jaspersoft.com. + * + * Unless you have purchased a commercial license agreement from Jaspersoft, + * the following license terms apply: + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see . + */ + +package com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendar; + +import com.jaspersoft.jasperserver.dto.job.ClientJobCalendar; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "reportJobCalendar") +public class DailyCalendar extends Calendar { + + private java.util.Calendar rangeStartingCalendar; + private java.util.Calendar rangeEndingCalendar; + private Boolean invertTimeRange; + + public DailyCalendar() { + super(); + calendarType = ClientJobCalendar.Type.daily; + } + + public DailyCalendar(DailyCalendar other) { + super(other); + this.invertTimeRange = other.invertTimeRange; + this.rangeEndingCalendar = (other.rangeEndingCalendar != null) ? (java.util.Calendar) other.rangeEndingCalendar.clone() : null; + this.rangeStartingCalendar = (other.rangeStartingCalendar != null) ? (java.util.Calendar) other.rangeStartingCalendar.clone() : null; + } + + public java.util.Calendar getRangeStartingCalendar() { + return rangeStartingCalendar; + } + + public DailyCalendar setRangeStartingCalendar(java.util.Calendar rangeStartingCalendar) { + this.rangeStartingCalendar = rangeStartingCalendar; + return this; + } + + public java.util.Calendar getRangeEndingCalendar() { + return rangeEndingCalendar; + } + + public DailyCalendar setRangeEndingCalendar(java.util.Calendar rangeEndingCalendar) { + this.rangeEndingCalendar = rangeEndingCalendar; + return this; + } + + public Boolean getInvertTimeRange() { + return invertTimeRange; + } + + public DailyCalendar setInvertTimeRange(Boolean invertTimeRange) { + this.invertTimeRange = invertTimeRange; + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + if (!super.equals(o)) return false; + + DailyCalendar that = (DailyCalendar) o; + + if (invertTimeRange != null ? !invertTimeRange.equals(that.invertTimeRange) : that.invertTimeRange != null) + return false; + if (rangeEndingCalendar != null ? !rangeEndingCalendar.equals(that.rangeEndingCalendar) : that.rangeEndingCalendar != null) + return false; + if (rangeStartingCalendar != null ? !rangeStartingCalendar.equals(that.rangeStartingCalendar) : that.rangeStartingCalendar != null) + return false; + + return true; + } + + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (rangeStartingCalendar != null ? rangeStartingCalendar.hashCode() : 0); + result = 31 * result + (rangeEndingCalendar != null ? rangeEndingCalendar.hashCode() : 0); + result = 31 * result + (invertTimeRange != null ? invertTimeRange.hashCode() : 0); + return result; + } + + @Override + public String toString() { + return "DailyCalendar{" + + "rangeStartingCalendar=" + rangeStartingCalendar + + ", rangeEndingCalendar=" + rangeEndingCalendar + + ", invertTimeRange=" + invertTimeRange + + "} " + super.toString(); + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendar/HolidayCalendar.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendar/HolidayCalendar.java new file mode 100644 index 00000000..4a15e230 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendar/HolidayCalendar.java @@ -0,0 +1,102 @@ +/* + * Copyright (C) 2005 - 2014 Jaspersoft Corporation. All rights reserved. + * http://www.jaspersoft.com. + * + * Unless you have purchased a commercial license agreement from Jaspersoft, + * the following license terms apply: + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see . + */ + +package com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendar; + +import com.jaspersoft.jasperserver.dto.job.ClientJobCalendar; +import com.jaspersoft.jasperserver.dto.job.adapters.ExcludeDaysXmlAdapter; +import java.util.ArrayList; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + + +@XmlRootElement(name = "reportJobCalendar") +public class HolidayCalendar extends Calendar { + + public HolidayCalendar() { + super(); + this.calendarType = ClientJobCalendar.Type.holiday; + } + + public HolidayCalendar(HolidayCalendar other) { + super(other); + this.dataSorted = other.dataSorted; + this.excludeDays = new ArrayList(); + if (other.getExcludeDays() != null) { + for (java.util.Calendar excludeDay : other.getExcludeDays()) { + this.excludeDays.add(excludeDay); + } + } + } + + private ArrayList excludeDays = new ArrayList(); + // true, if excludeDays is sorted + private Boolean dataSorted; + + @XmlJavaTypeAdapter(ExcludeDaysXmlAdapter.class) + public ArrayList getExcludeDays() { + return excludeDays; + } + + public HolidayCalendar setExcludeDays(ArrayList excludeDays) { + this.excludeDays = excludeDays; + return this; + } + + public Boolean getDataSorted() { + return dataSorted; + } + + public HolidayCalendar setDataSorted(Boolean dataSorted) { + this.dataSorted = dataSorted; + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + if (!super.equals(o)) return false; + + HolidayCalendar that = (HolidayCalendar) o; + + if (dataSorted != null ? !dataSorted.equals(that.dataSorted) : that.dataSorted != null) return false; + if (excludeDays != null ? !excludeDays.equals(that.excludeDays) : that.excludeDays != null) return false; + + return true; + } + + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (excludeDays != null ? excludeDays.hashCode() : 0); + result = 31 * result + (dataSorted != null ? dataSorted.hashCode() : 0); + return result; + } + + @Override + public String toString() { + return "HolidayCalendar{" + + "excludeDays=" + excludeDays + + ", dataSorted=" + dataSorted + + "} " + super.toString(); + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendar/MonthlyCalendar.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendar/MonthlyCalendar.java new file mode 100644 index 00000000..364b823f --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendar/MonthlyCalendar.java @@ -0,0 +1,88 @@ +/* + * Copyright (C) 2005 - 2014 Jaspersoft Corporation. All rights reserved. + * http://www.jaspersoft.com. + * + * Unless you have purchased a commercial license agreement from Jaspersoft, + * the following license terms apply: + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see . + */ + +package com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendar; + + +import com.jaspersoft.jasperserver.dto.job.ClientJobCalendar; +import java.util.Arrays; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "reportJobCalendar") +public class MonthlyCalendar extends Calendar { + + private boolean[] excludeDaysFlags; + + public MonthlyCalendar() { + super(); + this.calendarType = ClientJobCalendar.Type.monthly; + } + + public MonthlyCalendar(MonthlyCalendar other) { + super(other); + if (other.excludeDaysFlags != null) { + this.excludeDaysFlags = new boolean[other.excludeDaysFlags.length]; + for (int i = 0; i < other.excludeDaysFlags.length; i++) { + this.excludeDaysFlags[i] = other.excludeDaysFlags[i]; + } + } + } + + @XmlElementWrapper(name = "excludeDaysFlags") + @XmlElement(name = "excludeDayFlag") + public boolean[] getExcludeDaysFlags() { + return excludeDaysFlags; + } + + public MonthlyCalendar setExcludeDaysFlags(boolean[] excludeDaysFlags) { + this.excludeDaysFlags = excludeDaysFlags; + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + if (!super.equals(o)) return false; + + MonthlyCalendar that = (MonthlyCalendar) o; + + if (!Arrays.equals(excludeDaysFlags, that.excludeDaysFlags)) return false; + + return true; + } + + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (excludeDaysFlags != null ? Arrays.hashCode(excludeDaysFlags) : 0); + return result; + } + + @Override + public String toString() { + return "MonthlyCalendar{" + + "excludeDaysFlags=" + excludeDaysFlags + + "} " + super.toString(); + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendar/WeeklyCalendar.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendar/WeeklyCalendar.java new file mode 100644 index 00000000..c20cb3d2 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendar/WeeklyCalendar.java @@ -0,0 +1,87 @@ +/* + * Copyright (C) 2005 - 2014 Jaspersoft Corporation. All rights reserved. + * http://www.jaspersoft.com. + * + * Unless you have purchased a commercial license agreement from Jaspersoft, + * the following license terms apply: + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see . + */ + +package com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendar; + +import com.jaspersoft.jasperserver.dto.job.ClientJobCalendar; +import java.util.Arrays; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "reportJobCalendar") +public class WeeklyCalendar extends Calendar { + + private boolean[] excludeDaysFlags; + + public WeeklyCalendar() { + super(); + this.calendarType = ClientJobCalendar.Type.weekly; + } + + public WeeklyCalendar(WeeklyCalendar other) { + super(other); + if (other.excludeDaysFlags != null) { + this.excludeDaysFlags = new boolean[other.excludeDaysFlags.length]; + for (int i = 0; i < other.excludeDaysFlags.length; i++) { + this.excludeDaysFlags[i] = other.excludeDaysFlags[i]; + } + } + } + + @XmlElementWrapper(name = "excludeDaysFlags") + @XmlElement(name = "excludeDayFlag") + public boolean[] getExcludeDaysFlags() { + return excludeDaysFlags; + } + + public WeeklyCalendar setExcludeDaysFlags(boolean[] excludeDaysFlags) { + this.excludeDaysFlags = excludeDaysFlags; + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + if (!super.equals(o)) return false; + + WeeklyCalendar calendar = (WeeklyCalendar) o; + + if (!Arrays.equals(excludeDaysFlags, calendar.excludeDaysFlags)) return false; + + return true; + } + + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (excludeDaysFlags != null ? Arrays.hashCode(excludeDaysFlags) : 0); + return result; + } + + @Override + public String toString() { + return "WeeklyCalendar{" + + "excludeDaysFlags=" + excludeDaysFlags + + "} " + super.toString(); + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/AnnualCalendar.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/AnnualCalendar.java index 0fa6fb63..7b07f05f 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/AnnualCalendar.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/AnnualCalendar.java @@ -27,7 +27,9 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.util.ArrayList; - +/** + * @deprecated (use com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendar.* pakage). + */ @XmlRootElement(name = "reportJobCalendar") public class AnnualCalendar extends Calendar { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/BaseCalendar.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/BaseCalendar.java index 1acad4ce..d1f9bd6c 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/BaseCalendar.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/BaseCalendar.java @@ -24,7 +24,9 @@ import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.calendar.CalendarType; import javax.xml.bind.annotation.XmlRootElement; - +/** + * @deprecated (use com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendar.* pakage). + */ @XmlRootElement(name = "reportJobCalendar") public class BaseCalendar extends Calendar { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/Calendar.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/Calendar.java index f9e6014a..9f4cd775 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/Calendar.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/Calendar.java @@ -24,7 +24,9 @@ import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.calendar.CalendarType; import java.util.TimeZone; - +/** + * @deprecated (use com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendar.* pakage). + */ public abstract class Calendar { protected CalendarType calendarType; diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/CronCalendar.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/CronCalendar.java index e98492de..9af22583 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/CronCalendar.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/CronCalendar.java @@ -24,7 +24,9 @@ import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.calendar.CalendarType; import javax.xml.bind.annotation.XmlRootElement; - +/** + * @deprecated (use com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendar.* pakage). + */ @XmlRootElement(name = "reportJobCalendar") public class CronCalendar extends Calendar { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/DailyCalendar.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/DailyCalendar.java index 2c257b56..70937d00 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/DailyCalendar.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/DailyCalendar.java @@ -24,7 +24,9 @@ import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.calendar.CalendarType; import javax.xml.bind.annotation.XmlRootElement; - +/** + * @deprecated (use com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendar.* pakage). + */ @XmlRootElement(name = "reportJobCalendar") public class DailyCalendar extends Calendar { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/HolidayCalendar.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/HolidayCalendar.java index e64f9353..2fbef520 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/HolidayCalendar.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/HolidayCalendar.java @@ -28,7 +28,9 @@ import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.util.ArrayList; - +/** + * @deprecated (use com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendar.* pakage). + */ @XmlRootElement(name = "reportJobCalendar") public class HolidayCalendar extends Calendar { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/MonthlyCalendar.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/MonthlyCalendar.java index aac3993c..fe41d922 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/MonthlyCalendar.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/MonthlyCalendar.java @@ -27,7 +27,9 @@ import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import java.util.Arrays; - +/** + * @deprecated (use com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendar.* pakage). + */ @XmlRootElement(name = "reportJobCalendar") public class MonthlyCalendar extends Calendar { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/WeeklyCalendar.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/WeeklyCalendar.java index 75666b90..399f1dc9 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/WeeklyCalendar.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/calendars/WeeklyCalendar.java @@ -27,7 +27,9 @@ import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import java.util.Arrays; - +/** + * @deprecated (use com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendar.* pakage). + */ @XmlRootElement(name = "reportJobCalendar") public class WeeklyCalendar extends Calendar { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/AddressesXmlAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/AddressesXmlAdapter.java index 1be90714..570652a4 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/AddressesXmlAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/AddressesXmlAdapter.java @@ -29,6 +29,7 @@ /** * @author Yaroslav.Kovalchyk * @version $Id: AddressesXmlAdapter.java 22756 2012-03-23 10:39:15Z sergey.prilukin $ + * @deprecated (use server adapter). */ public class AddressesXmlAdapter extends XmlAdapter> { @Override diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/DateToStringXmlAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/DateToStringXmlAdapter.java index 97e29e22..c260298d 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/DateToStringXmlAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/DateToStringXmlAdapter.java @@ -29,6 +29,7 @@ /** * @author Yaroslav.Kovalchyk * @version $Id: DateToStringXmlAdapter.java 38348 2013-09-30 04:57:18Z carbiv $ + * @deprecated (use server adapter). */ public class DateToStringXmlAdapter extends XmlAdapter{ @Override diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/DaysByteXmlAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/DaysByteXmlAdapter.java index d69d65e2..e028addf 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/DaysByteXmlAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/DaysByteXmlAdapter.java @@ -31,6 +31,7 @@ * * @author Yaroslav.Kovalchyk * @version $Id: DaysByteXmlAdapter.java 22756 2012-03-23 10:39:15Z sergey.prilukin $ + * @deprecated (use server adapter). */ public class DaysByteXmlAdapter extends XmlAdapter>{ @Override diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/ExcludeDaysXmlAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/ExcludeDaysXmlAdapter.java index e7310e34..a49eb2aa 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/ExcludeDaysXmlAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/ExcludeDaysXmlAdapter.java @@ -34,6 +34,7 @@ /** * @author Yaroslav.Kovalchyk * @version $Id: ExcludeDaysXmlAdapter.java 23844 2012-05-22 06:23:41Z ykovalchyk $ + * @deprecated (use server adapter). */ public class ExcludeDaysXmlAdapter extends XmlAdapter> { private DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/MonthsByteXmlAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/MonthsByteXmlAdapter.java index 90d9ed17..bd7c0852 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/MonthsByteXmlAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/MonthsByteXmlAdapter.java @@ -31,6 +31,7 @@ * * @author Yaroslav.Kovalchyk * @version $Id: MonthsByteXmlAdapter.java 22756 2012-03-23 10:39:15Z sergey.prilukin $ + * @deprecated (use server adapter). */ public class MonthsByteXmlAdapter extends XmlAdapter>{ @Override diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/NoTimezoneDateToStringXmlAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/NoTimezoneDateToStringXmlAdapter.java index 9622b58e..b5b6d6f4 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/NoTimezoneDateToStringXmlAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/NoTimezoneDateToStringXmlAdapter.java @@ -28,6 +28,7 @@ /** * @author Yaroslav.Kovalchyk * @version $Id: NoTimezoneDateToStringXmlAdapter.java 38348 2013-09-30 04:57:18Z carbiv $ + * @deprecated (use server adapter). */ public class NoTimezoneDateToStringXmlAdapter extends XmlAdapter{ diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/OutputFormatXmlAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/OutputFormatXmlAdapter.java index 49eb97e9..edd548f8 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/OutputFormatXmlAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/OutputFormatXmlAdapter.java @@ -35,6 +35,7 @@ * * @author Yaroslav.Kovalchyk * @version $Id: OutputFormatXmlAdapter.java 38764 2013-10-10 18:42:07Z carbiv $ + * @deprecated (use server adapter). */ public class OutputFormatXmlAdapter extends XmlAdapter> { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/ReportJobSourceParametersXmlAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/ReportJobSourceParametersXmlAdapter.java index 610745a2..96fdee6f 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/ReportJobSourceParametersXmlAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/ReportJobSourceParametersXmlAdapter.java @@ -33,6 +33,7 @@ /** * @author Yaroslav.Kovalchyk * @version $Id: ReportJobSourceParametersXmlAdapter.java 28947 2013-02-26 15:02:08Z vsabadosh $ + * @deprecated (use server adapter). */ public class ReportJobSourceParametersXmlAdapter extends XmlAdapter> { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/TimeZoneXmlAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/TimeZoneXmlAdapter.java index 1f2211d0..8a278251 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/TimeZoneXmlAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/TimeZoneXmlAdapter.java @@ -27,6 +27,7 @@ /** * @author Yaroslav.Kovalchyk * @version $Id$ + * @deprecated (use server adapter). */ public class TimeZoneXmlAdapter extends XmlAdapter{ @Override diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/TimestampToStringXmlAdapter.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/TimestampToStringXmlAdapter.java index c1dd71fd..0e33c676 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/TimestampToStringXmlAdapter.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/adapters/TimestampToStringXmlAdapter.java @@ -29,6 +29,7 @@ /** * @author Yaroslav.Kovalchyk * @version $Id: TimestampToStringXmlAdapter.java 38348 2013-09-30 04:57:18Z carbiv $ + * @deprecated (use server adapter). */ public class TimestampToStringXmlAdapter extends XmlAdapter{ @Override diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/AddressesListWrapper.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/AddressesListWrapper.java index 8a75c498..72329918 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/AddressesListWrapper.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/AddressesListWrapper.java @@ -30,7 +30,8 @@ * XmlElementWrapper annotation doesn't support @XmlJavaTypeAdapter * * @author Yaroslav.Kovalchyk - * @version $Id: AddressesListWrapper.java 22756 2012-03-23 10:39:15Z sergey.prilukin $ + * @version $Id: AddressesListWrapper.java 22756 2012-03-23 10:39:15Z sergey.prilukin + * @deprecated (use server adapter). */ @XmlRootElement public class AddressesListWrapper { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/CalendarNameListWrapper.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/CalendarNameListWrapper.java index e230d8b1..9eea65b2 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/CalendarNameListWrapper.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/CalendarNameListWrapper.java @@ -28,6 +28,7 @@ /** * @author Yaroslav.Kovalchyk * @version $Id: CalendarNameListWrapper.java 22656 2012-03-20 13:43:39Z ykovalchyk $ + * @deprecated (use server adapter). */ @XmlRootElement(name = "calendarNameList") public class CalendarNameListWrapper { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/DaysSortedSetWrapper.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/DaysSortedSetWrapper.java index bec26a59..ce52ea2a 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/DaysSortedSetWrapper.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/DaysSortedSetWrapper.java @@ -31,6 +31,7 @@ * * @author Yaroslav.Kovalchyk * @version $Id: DaysSortedSetWrapper.java 22756 2012-03-23 10:39:15Z sergey.prilukin $ + * @deprecated (use server adapter). */ @XmlRootElement public class DaysSortedSetWrapper { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/ExcludeDaysWrapper.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/ExcludeDaysWrapper.java index 4dbc8a01..5f56c284 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/ExcludeDaysWrapper.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/ExcludeDaysWrapper.java @@ -31,6 +31,7 @@ * * @author Yaroslav.Kovalchyk * @version $Id: ExcludeDaysWrapper.java 23844 2012-05-22 06:23:41Z ykovalchyk $ + * @deprecated (use server adapter). */ @XmlRootElement(name = "excludeDays") public class ExcludeDaysWrapper { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/JobSummaryListWrapper.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/JobSummaryListWrapper.java index fb61f7ce..fd2d7e0b 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/JobSummaryListWrapper.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/JobSummaryListWrapper.java @@ -27,7 +27,9 @@ import javax.xml.bind.annotation.XmlRootElement; import java.util.ArrayList; import java.util.List; - +/** + * @deprecated (use server adapter). + */ @XmlRootElement(name = "jobs") public class JobSummaryListWrapper { private List jobsummary; diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/MonthsSortedSetWrapper.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/MonthsSortedSetWrapper.java index b5217ad3..03f5358b 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/MonthsSortedSetWrapper.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/MonthsSortedSetWrapper.java @@ -31,6 +31,7 @@ * * @author Yaroslav.Kovalchyk * @version $Id: MonthsSortedSetWrapper.java 22756 2012-03-23 10:39:15Z sergey.prilukin $ + * @deprecated (use server adapter). */ @XmlRootElement(name = "months") public class MonthsSortedSetWrapper { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/ReportJobOutputFormatsWrapper.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/ReportJobOutputFormatsWrapper.java index c78a301d..252f6543 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/ReportJobOutputFormatsWrapper.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/ReportJobOutputFormatsWrapper.java @@ -31,6 +31,7 @@ * * @author Yaroslav.Kovalchyk * @version $Id: ReportJobOutputFormatsWrapper.java 22756 2012-03-23 10:39:15Z sergey.prilukin $ + * @deprecated (use server adapter). */ @XmlRootElement(name = "outputFormats") public class ReportJobOutputFormatsWrapper { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/ReportParametersMapWrapper.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/ReportParametersMapWrapper.java index 989dd066..62b095d9 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/ReportParametersMapWrapper.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/ReportParametersMapWrapper.java @@ -27,6 +27,7 @@ /** * @author Yaroslav.Kovalchyk * @version $Id$ + * @deprecated (use server adapter). */ @XmlRootElement(name = "parameters") public class ReportParametersMapWrapper { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/ValuesCollection.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/ValuesCollection.java index 4813b83b..5bdcd9e5 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/ValuesCollection.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/jaxb/wrappers/ValuesCollection.java @@ -30,6 +30,7 @@ * * @author Yaroslav.Kovalchyk * @version $Id$ + * @deprecated (use server adapter). */ @XmlType(name = "collection") public class ValuesCollection { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/FTPInfoModel.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/FTPInfoModel.java index 8b7efd36..f3d936b5 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/FTPInfoModel.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/FTPInfoModel.java @@ -32,6 +32,7 @@ * @author Ivan Chan (ichan@jaspersoft.com) * @version $Id: FTPInfoModel.java 38348 2013-09-30 04:57:18Z carbiv $ * @since 1.0 + * @deprecated (use server adapter). */ public class FTPInfoModel extends FtpInfo { /** diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobAlertModel.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobAlertModel.java index 58a92bdf..c2b89dea 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobAlertModel.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobAlertModel.java @@ -39,6 +39,7 @@ * @author Ivan Chan (ichan@jaspersoft.com) * @version $Id: ReportJobAlertModel.java 25010 2012-09-26 16:56:35Z sergey.prilukin $ * @since 4.7 + * @deprecated (use server adapter). */ public class ReportJobAlertModel extends JobAlert { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobCalendarTriggerModel.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobCalendarTriggerModel.java index 16bb7d99..42e06102 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobCalendarTriggerModel.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobCalendarTriggerModel.java @@ -40,6 +40,7 @@ * @author Ivan Chan (ichan@jaspersoft.com) * @version $Id: ReportJobCalendarTriggerModel.java 25010 2012-09-26 16:56:35Z sergey.prilukin $ * @since 4.7 + * @deprecated (use server adapter). */ public class ReportJobCalendarTriggerModel extends CalendarTrigger { /** diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobMailNotificationModel.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobMailNotificationModel.java index 325822a4..8f8ac056 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobMailNotificationModel.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobMailNotificationModel.java @@ -38,6 +38,7 @@ * @author Ivan Chan (ichan@jaspersoft.com) * @version $Id: ReportJobMailNotificationModel.java 25010 2012-09-26 16:56:35Z sergey.prilukin $ * @since 4.7 + * @deprecated (use server adapter). */ public class ReportJobMailNotificationModel extends MailNotification { /** diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobModel.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobModel.java index f4d47929..db46b34b 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobModel.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobModel.java @@ -25,13 +25,14 @@ * Definition model of a thumbnail execution job. Model is used in search/ update only. * *

- * A thumbnail job definition specifies wich thumbnail inFolder execute and when, + * A thumbnail job definition specifies which thumbnail inFolder execute and when, * what output inFolder generate and where inFolder send the output. *

* * @author Ivan Chan (ichan@jaspersoft.com) * @version $Id: ReportJobModel.java 25010 2012-09-26 16:56:35Z sergey.prilukin $ * @since 4.7 + * @deprecated (use server adapter). */ import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.JSClientException; diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobRepositoryDestinationModel.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobRepositoryDestinationModel.java index b5893b05..f663f96e 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobRepositoryDestinationModel.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobRepositoryDestinationModel.java @@ -33,6 +33,7 @@ * @author Ivan Chan (ichan@jaspersoft.com) * @version $Id: ReportJobRepositoryDestinationModel.java 25010 2012-09-26 16:56:35Z sergey.prilukin $ * @since 4.7 + * @deprecated (use server adapter). */ public class ReportJobRepositoryDestinationModel extends RepositoryDestination { /** diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobSimpleTriggerModel.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobSimpleTriggerModel.java index 9f3e73c9..0afd96bc 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobSimpleTriggerModel.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobSimpleTriggerModel.java @@ -41,6 +41,7 @@ * @author Ivan Chan (ichan@jaspersoft.com) * @version $Id: ReportJobSimpleTriggerModel.java 25010 2012-09-26 16:56:35Z sergey.prilukin $ * @since 4.7 + * @deprecated (use server adapter). */ public class ReportJobSimpleTriggerModel extends SimpleTrigger { /** diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobSourceModel.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobSourceModel.java index 3af06df0..2db413bf 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobSourceModel.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobSourceModel.java @@ -37,6 +37,7 @@ * @author Ivan Chan (ichan@jaspersoft.com) * @version $Id: ReportJobSourceModel.java 25010 2012-09-26 16:56:35Z sergey.prilukin $ * @since 4.7 + * @deprecated (use server adapter). */ public class ReportJobSourceModel extends JobSource { /** diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobStateModel.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobStateModel.java index 9915c659..71fdce07 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobStateModel.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobStateModel.java @@ -33,6 +33,7 @@ * @author Ivan Chan (ichan@jaspersoft.com) * @version $Id: ReportJobStateModel.java 25420 2012-10-20 16:36:09Z sergey.prilukin $ * @since 1.0 + * @deprecated (use server adapter). */ @XmlRootElement(name = "stateModel") public class ReportJobStateModel extends JobState { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/Attachment.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/Attachment.java similarity index 88% rename from src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/Attachment.java rename to src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/Attachment.java index bbb655f2..952772c3 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/Attachment.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/Attachment.java @@ -1,5 +1,5 @@ -package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting; - +package com.jaspersoft.jasperserver.jaxrs.client.dto.reports; +@Deprecated public class Attachment { private String name; diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/AttachmentDescriptor.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/AttachmentDescriptor.java index 558a7b0a..8d81ad45 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/AttachmentDescriptor.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/AttachmentDescriptor.java @@ -22,7 +22,7 @@ package com.jaspersoft.jasperserver.jaxrs.client.dto.reports; import javax.xml.bind.annotation.XmlRootElement; - +@Deprecated @XmlRootElement(name = "attachment") public class AttachmentDescriptor { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ExecutionStatus.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ExecutionStatus.java index 2bec8b12..4e138dd4 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ExecutionStatus.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ExecutionStatus.java @@ -21,6 +21,9 @@ package com.jaspersoft.jasperserver.jaxrs.client.dto.reports; +/** + * @deprecated Use Server DTO**/ +@Deprecated public enum ExecutionStatus { execution, ready, cancelled, failed, queued } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ExportDescriptor.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ExportDescriptor.java index a781eac3..922c7c12 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ExportDescriptor.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ExportDescriptor.java @@ -27,7 +27,7 @@ import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import java.util.List; - +@Deprecated //@XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "export") public class ExportDescriptor { @@ -44,48 +44,54 @@ public ErrorDescriptor getErrorDescriptor() { return errorDescriptor; } - public void setErrorDescriptor(ErrorDescriptor errorDescriptor) { + public ExportDescriptor setErrorDescriptor(ErrorDescriptor errorDescriptor) { this.errorDescriptor = errorDescriptor; + return this; } public String getId() { return id; } - public void setId(String id) { + public ExportDescriptor setId(String id) { this.id = id; + return this; } public String getStatus() { return status; } - public void setStatus(String status) { + public ExportDescriptor setStatus(String status) { this.status = status; + return this; } public String getPages() { return pages; } - public void setPages(String pages) { + public ExportDescriptor setPages(String pages) { this.pages = pages; + return this; } public String getAttachmentsPrefix() { return attachmentsPrefix; } - public void setAttachmentsPrefix(String attachmentsPrefix) { + public ExportDescriptor setAttachmentsPrefix(String attachmentsPrefix) { this.attachmentsPrefix = attachmentsPrefix; + return this; } public OutputResourceDescriptor getOutputResource() { return outputResource; } - public void setOutputResource(OutputResourceDescriptor outputResource) { + public ExportDescriptor setOutputResource(OutputResourceDescriptor outputResource) { this.outputResource = outputResource; + return this; } @XmlElementWrapper(name = "attachments") @@ -94,8 +100,9 @@ public List getAttachments() { return attachments; } - public void setAttachments(List attachments) { + public ExportDescriptor setAttachments(List attachments) { this.attachments = attachments; + return this; } @Override diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ExportExecution.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ExportExecution.java index d2e9fcf4..816385cc 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ExportExecution.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ExportExecution.java @@ -22,11 +22,13 @@ package com.jaspersoft.jasperserver.jaxrs.client.dto.reports; import com.jaspersoft.jasperserver.dto.common.ErrorDescriptor; - +import com.jaspersoft.jasperserver.dto.executions.ExecutionStatus; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; -import java.util.Map; @XmlRootElement(name = "exportExecution") public class ExportExecution { @@ -38,50 +40,77 @@ public class ExportExecution { private OutputResourceDescriptor outputResource; private Map attachments; + public ExportExecution() { + } + + public ExportExecution(ExportExecution other) { + this.id = other.id; + this.options = new ExportExecutionOptions(other.options); + this.status = other.status; + this.errorDescriptor = new ErrorDescriptor(other.errorDescriptor); + this.outputResource = new OutputResourceDescriptor(other.outputResource); + final Map otherAttachments = other.attachments; + this.attachments = new HashMap<>(); + if (otherAttachments != null) { + for (String attachment : otherAttachments.keySet()) { + this.attachments.put(attachment, new OutputResourceDescriptor(attachments.get(attachment))); + } + } + } + @XmlElement public String getId() { return id; } - public void setId(String id) { + public ExportExecution setId(String id) { this.id = id; + return this; } public ExportExecutionOptions getOptions() { return options; } - public void setOptions(ExportExecutionOptions options) { + public ExportExecution setOptions(ExportExecutionOptions options) { this.options = options; + return this; } public ExecutionStatus getStatus() { return status; } - public void setStatus(ExecutionStatus status) { + public ExportExecution setStatus(ExecutionStatus status) { this.status = status; + return this; } public ErrorDescriptor getErrorDescriptor() { return errorDescriptor; } - public void setErrorDescriptor(ErrorDescriptor errorDescriptor) { + public ExportExecution setErrorDescriptor(ErrorDescriptor errorDescriptor) { this.status = ExecutionStatus.failed; this.errorDescriptor = errorDescriptor; + return this; } public OutputResourceDescriptor getOutputResource() { return outputResource; } - public void setOutputResource(OutputResourceDescriptor outputResource) { + public ExportExecution setOutputResource(OutputResourceDescriptor outputResource) { this.outputResource = outputResource; + return this; } - public void setAttachments(Map attachments) { - this.attachments = attachments; + public ExportExecution setAttachments(List attachments) { + this.attachments = new HashMap<>(); + for (OutputResourceDescriptor attachment : attachments) { + this.attachments.put(attachment.getFileName(), attachment); + } + return this; } @XmlElementWrapper(name = "attachments") diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ExportExecutionDescriptor.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ExportExecutionDescriptor.java index c8d06eda..65b8e5c2 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ExportExecutionDescriptor.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ExportExecutionDescriptor.java @@ -24,7 +24,7 @@ import com.jaspersoft.jasperserver.dto.common.ErrorDescriptor; import javax.xml.bind.annotation.XmlRootElement; - +@Deprecated @XmlRootElement(name = "exportExecution") public class ExportExecutionDescriptor { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ExportExecutionOptions.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ExportExecutionOptions.java index 5c3e4ecf..0c263d7a 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ExportExecutionOptions.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ExportExecutionOptions.java @@ -21,25 +21,40 @@ package com.jaspersoft.jasperserver.jaxrs.client.dto.reports; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.ReportOutputFormat; import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlTransient; - @XmlRootElement(name = "export") public class ExportExecutionOptions { - public static final String PARAM_NAME_PAGES = "pages"; - public static final String PARAM_NAME_ATTACHMENTS_PREFIX = "attachmentsPrefix"; - private String outputFormat; private String attachmentsPrefix; private String pages; private String baseUrl; + private String anchor; private boolean allowInlineScripts = true; + private String markupType; + private Boolean ignorePagination; - public ExportExecutionOptions setPages(String pages) { - this.pages = pages; + public ExportExecutionOptions() { + } + + public ExportExecutionOptions(ExportExecutionOptions other) { + this.outputFormat = other.outputFormat; + this.attachmentsPrefix = other.attachmentsPrefix; + this.pages = other.pages; + this.baseUrl = other.baseUrl; + this.anchor = other.anchor; + this.allowInlineScripts = other.allowInlineScripts; + this.markupType = other.markupType; + this.ignorePagination = other.ignorePagination; + } + + public String getOutputFormat() { + return outputFormat; + } + + public ExportExecutionOptions setOutputFormat(String outputFormat) { + this.outputFormat = outputFormat; return this; } @@ -52,67 +67,102 @@ public ExportExecutionOptions setAttachmentsPrefix(String attachmentsPrefix) { return this; } - @XmlTransient - public String getPages(){ + public String getPages() { return pages; } - public String getOutputFormat() { - return outputFormat; + public ExportExecutionOptions setPages(String pages) { + this.pages = pages; + return this; } - public ExportExecutionOptions setOutputFormat(ReportOutputFormat outputFormat) { - this.outputFormat = outputFormat.toString().toLowerCase(); - return this; + public String getBaseUrl() { + return baseUrl; } - public ExportExecutionOptions setOutputFormat(String outputFormat) { - this.outputFormat = outputFormat.toLowerCase(); + public ExportExecutionOptions setBaseUrl(String baseUrl) { + this.baseUrl = baseUrl; return this; } - public String getBaseUrl() { - return baseUrl; + public String getAnchor() { + return anchor; } - public void setBaseUrl(String baseUrl) { - this.baseUrl = baseUrl; + public ExportExecutionOptions setAnchor(String anchor) { + this.anchor = anchor; + return this; } public boolean isAllowInlineScripts() { return allowInlineScripts; } - public void setAllowInlineScripts(boolean allowInlineScripts) { + public ExportExecutionOptions setAllowInlineScripts(boolean allowInlineScripts) { this.allowInlineScripts = allowInlineScripts; + return this; + } + + public String getMarkupType() { + return markupType; + } + + public ExportExecutionOptions setMarkupType(String markupType) { + this.markupType = markupType; + return this; + } + + public Boolean getIgnorePagination() { + return ignorePagination; + } + + public ExportExecutionOptions setIgnorePagination(Boolean ignorePagination) { + this.ignorePagination = ignorePagination; + return this; } @Override public boolean equals(Object o) { if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (!(o instanceof ExportExecutionOptions)) return false; ExportExecutionOptions that = (ExportExecutionOptions) o; + if (allowInlineScripts != that.allowInlineScripts) return false; + if (outputFormat != null ? !outputFormat.equals(that.outputFormat) : that.outputFormat != null) return false; + if (attachmentsPrefix != null ? !attachmentsPrefix.equals(that.attachmentsPrefix) : that.attachmentsPrefix != null) + return false; if (pages != null ? !pages.equals(that.pages) : that.pages != null) return false; - if (!outputFormat.equals(that.outputFormat)) return false; - if (attachmentsPrefix != null ? !attachmentsPrefix.equals(that.attachmentsPrefix) : that.attachmentsPrefix != null) return false; - - return true; + if (baseUrl != null ? !baseUrl.equals(that.baseUrl) : that.baseUrl != null) return false; + if (anchor != null ? !anchor.equals(that.anchor) : that.anchor != null) return false; + if (markupType != null ? !markupType.equals(that.markupType) : that.markupType != null) return false; + return ignorePagination != null ? ignorePagination.equals(that.ignorePagination) : that.ignorePagination == null; } @Override public int hashCode() { - int result = outputFormat.hashCode(); - result = 31 * result + (pages != null ? pages.hashCode() : 0); + int result = outputFormat != null ? outputFormat.hashCode() : 0; result = 31 * result + (attachmentsPrefix != null ? attachmentsPrefix.hashCode() : 0); + result = 31 * result + (pages != null ? pages.hashCode() : 0); + result = 31 * result + (baseUrl != null ? baseUrl.hashCode() : 0); + result = 31 * result + (anchor != null ? anchor.hashCode() : 0); + result = 31 * result + (allowInlineScripts ? 1 : 0); + result = 31 * result + (markupType != null ? markupType.hashCode() : 0); + result = 31 * result + (ignorePagination != null ? ignorePagination.hashCode() : 0); return result; } @Override public String toString() { - return outputFormat + - (pages != null ? ";" + PARAM_NAME_PAGES + "=" + pages.toString() : "") + - (attachmentsPrefix != null ? ";" + PARAM_NAME_ATTACHMENTS_PREFIX + "=" + attachmentsPrefix : ""); + return "ExportExecutionOptions{" + + "outputFormat='" + outputFormat + '\'' + + ", attachmentsPrefix='" + attachmentsPrefix + '\'' + + ", pages='" + pages + '\'' + + ", baseUrl='" + baseUrl + '\'' + + ", anchor='" + anchor + '\'' + + ", allowInlineScripts=" + allowInlineScripts + + ", markupType='" + markupType + '\'' + + ", ignorePagination=" + ignorePagination + + '}'; } } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ExportsContainer.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ExportsContainer.java new file mode 100644 index 00000000..58509f6a --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ExportsContainer.java @@ -0,0 +1,60 @@ +package com.jaspersoft.jasperserver.jaxrs.client.dto.reports; + +import java.util.HashMap; +import java.util.Map; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class ExportsContainer { + private Map executions = new HashMap(); + + public ExportsContainer() { + } + + public ExportsContainer(ExportsContainer other) { + this.executions = new HashMap<>(); + final Map executions = other.getExecutions(); + if (executions != null) { + for (String execution : executions.keySet()) { + this.executions.put(execution, new ExportExecution(executions.get(execution))); + } + } + } + + public Map getExecutions() { + return executions; + } + + public ExportsContainer setExecutions(Map executions) { + this.executions = executions; + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof ExportsContainer)) return false; + + ExportsContainer that = (ExportsContainer) o; + + return executions != null ? executions.equals(that.executions) : that.executions == null; + } + + @Override + public int hashCode() { + return executions != null ? executions.hashCode() : 0; + } + + @Override + public String toString() { + return "ExportsContainer{" + + "executions=" + executions + + '}'; + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/HtmlReport.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/HtmlReport.java similarity index 96% rename from src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/HtmlReport.java rename to src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/HtmlReport.java index 46cc073b..29b08604 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/HtmlReport.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/HtmlReport.java @@ -19,11 +19,11 @@ * along with this program.  If not, see . */ -package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting; +package com.jaspersoft.jasperserver.jaxrs.client.dto.reports; import java.util.ArrayList; import java.util.List; - +@Deprecated public class HtmlReport { private String id; diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/OutputResourceDescriptor.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/OutputResourceDescriptor.java index 7c5bc5bf..15706bb9 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/OutputResourceDescriptor.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/OutputResourceDescriptor.java @@ -21,37 +21,79 @@ package com.jaspersoft.jasperserver.jaxrs.client.dto.reports; +import com.jaspersoft.jasperserver.dto.common.DeepCloneable; + import javax.xml.bind.annotation.XmlRootElement; +import java.util.Arrays; @XmlRootElement(name = "outputResource") -public class OutputResourceDescriptor { +public class OutputResourceDescriptor implements DeepCloneable{ private String contentType; private String fileName; private Boolean outputFinal; + private String pages; + private byte[] data; + + public OutputResourceDescriptor() { + } + + public OutputResourceDescriptor(OutputResourceDescriptor other) { + this.contentType = other.contentType; + this.fileName = other.fileName; + this.outputFinal = other.outputFinal; + this.pages = other.pages; + if (other.data != null) { + this.data = new byte[other.data.length]; + for (int i=0; i < other.data.length; i++) { + this.data[i] = other.data[i]; + } + } + } public String getContentType() { return contentType; } - public void setContentType(String contentType) { + public OutputResourceDescriptor setContentType(String contentType) { this.contentType = contentType; + return this; } public String getFileName() { return fileName; } - public void setFileName(String fileName) { + public OutputResourceDescriptor setFileName(String fileName) { this.fileName = fileName; + return this; } public Boolean getOutputFinal() { return outputFinal; } - public void setOutputFinal(Boolean outputFinal) { + public OutputResourceDescriptor setOutputFinal(Boolean outputFinal) { this.outputFinal = outputFinal; + return this; + } + + public String getPages() { + return pages; + } + + public OutputResourceDescriptor setPages(String pages) { + this.pages = pages; + return this; + } + + public byte[] getData() { + return data; + } + + public OutputResourceDescriptor setData(byte[] data) { + this.data = data; + return this; } @Override @@ -64,8 +106,8 @@ public boolean equals(Object o) { if (contentType != null ? !contentType.equals(that.contentType) : that.contentType != null) return false; if (fileName != null ? !fileName.equals(that.fileName) : that.fileName != null) return false; if (outputFinal != null ? !outputFinal.equals(that.outputFinal) : that.outputFinal != null) return false; - - return true; + if (pages != null ? !pages.equals(that.pages) : that.pages != null) return false; + return Arrays.equals(data, that.data); } @Override @@ -73,6 +115,8 @@ public int hashCode() { int result = contentType != null ? contentType.hashCode() : 0; result = 31 * result + (fileName != null ? fileName.hashCode() : 0); result = 31 * result + (outputFinal != null ? outputFinal.hashCode() : 0); + result = 31 * result + (pages != null ? pages.hashCode() : 0); + result = 31 * result + Arrays.hashCode(data); return result; } @@ -82,6 +126,13 @@ public String toString() { "contentType='" + contentType + '\'' + ", fileName='" + fileName + '\'' + ", outputFinal=" + outputFinal + + ", pages='" + pages + '\'' + + ", data=" + Arrays.toString(data) + '}'; } + + @Override + public OutputResourceDescriptor deepClone() { + return new OutputResourceDescriptor(this); + } } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecution.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecution.java new file mode 100644 index 00000000..6b6a456a --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecution.java @@ -0,0 +1,181 @@ +/* + * Copyright (C) 2005 - 2014 Jaspersoft Corporation. All rights reserved. + * http://www.jaspersoft.com. + * + * Unless you have purchased a commercial license agreement from Jaspersoft, + * the following license terms apply: + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program.  If not, see . + */ + +package com.jaspersoft.jasperserver.jaxrs.client.dto.reports; + +import com.jaspersoft.jasperserver.dto.common.ErrorDescriptor; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "reportExecution") +public class ReportExecution { + + private Integer currentPage; + private String reportURI; + private String requestId; + private String status; + private Integer totalPages; + private ErrorDescriptor errorDescriptor; + private ExportsContainer exports = new ExportsContainer(); + private ReportExecutionOptions options; + + public ReportExecution() { + } + + public ReportExecution(ReportExecution other) { + this.currentPage = new Integer(other.currentPage); + this.reportURI = other.reportURI; + this.requestId = other.requestId; + this.status = other.status; + this.totalPages = new Integer(other.totalPages); + this.errorDescriptor = new ErrorDescriptor(other.errorDescriptor); + this.exports = new ExportsContainer(other.exports); + this.options = new ReportExecutionOptions(other.options); + } + + public Integer getCurrentPage() { + return currentPage; + } + + public ReportExecution setCurrentPage(Integer currentPage) { + this.currentPage = currentPage; + return this; + } + + public String getReportURI() { + return reportURI; + } + + public ReportExecution setReportURI(String reportURI) { + this.reportURI = reportURI; + return this; + } + + public String getRequestId() { + return requestId; + } + + public ReportExecution setRequestId(String requestId) { + this.requestId = requestId; + return this; + } + + public String getStatus() { + return status; + } + + public ReportExecution setStatus(String status) { + this.status = status; + return this; + } + + public Integer getTotalPages() { + return totalPages; + } + + public ReportExecution setTotalPages(Integer totalPages) { + this.totalPages = totalPages; + return this; + } + + public ErrorDescriptor getErrorDescriptor() { + return errorDescriptor; + } + + public ReportExecution setErrorDescriptor(ErrorDescriptor errorDescriptor) { + this.errorDescriptor = errorDescriptor; + return this; + } + + public ReportExecution setExports(Set exports) { + this.exports = new ExportsContainer(); + final HashMap executions = new HashMap<>(); + for (ExportExecution export : exports) { + executions.put(export.getId(), export); + } + this.exports.setExecutions(executions); + return this; + } + + public ReportExecutionOptions getOptions() { + return options; + } + + public ReportExecution setOptions(ReportExecutionOptions options) { + this.options = options; + return this; + } + @XmlElement(name = "export") + @XmlElementWrapper(name = "exports") + public Set getExports() { + return new HashSet(exports.getExecutions().values()); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof ReportExecution)) return false; + + ReportExecution that = (ReportExecution) o; + + if (currentPage != null ? !currentPage.equals(that.currentPage) : that.currentPage != null) return false; + if (reportURI != null ? !reportURI.equals(that.reportURI) : that.reportURI != null) return false; + if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false; + if (status != null ? !status.equals(that.status) : that.status != null) return false; + if (totalPages != null ? !totalPages.equals(that.totalPages) : that.totalPages != null) return false; + if (errorDescriptor != null ? !errorDescriptor.equals(that.errorDescriptor) : that.errorDescriptor != null) + return false; + if (exports != null ? !exports.equals(that.exports) : that.exports != null) return false; + return options != null ? options.equals(that.options) : that.options == null; + } + + @Override + public int hashCode() { + int result = currentPage != null ? currentPage.hashCode() : 0; + result = 31 * result + (reportURI != null ? reportURI.hashCode() : 0); + result = 31 * result + (requestId != null ? requestId.hashCode() : 0); + result = 31 * result + (status != null ? status.hashCode() : 0); + result = 31 * result + (totalPages != null ? totalPages.hashCode() : 0); + result = 31 * result + (errorDescriptor != null ? errorDescriptor.hashCode() : 0); + result = 31 * result + (exports != null ? exports.hashCode() : 0); + result = 31 * result + (options != null ? options.hashCode() : 0); + return result; + } + + @Override + public String toString() { + return "ReportExecution{" + + "currentPage=" + currentPage + + ", reportURI='" + reportURI + '\'' + + ", requestId='" + requestId + '\'' + + ", status='" + status + '\'' + + ", totalPages=" + totalPages + + ", errorDescriptor=" + errorDescriptor + + ", exports=" + exports + + ", options=" + options + + '}'; + } +} + diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionDescriptor.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionDescriptor.java index 408af258..c60afd59 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionDescriptor.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionDescriptor.java @@ -27,7 +27,7 @@ import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import java.util.List; - +@Deprecated //@XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "reportExecution") public class ReportExecutionDescriptor { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionListWrapper.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionListWrapper.java index 89a1779b..58783f8f 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionListWrapper.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionListWrapper.java @@ -24,7 +24,7 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.util.List; - +@Deprecated @XmlRootElement(name = "reportExecutions") public class ReportExecutionListWrapper { diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionOptions.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionOptions.java new file mode 100644 index 00000000..1ffb1fb2 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionOptions.java @@ -0,0 +1,135 @@ +package com.jaspersoft.jasperserver.jaxrs.client.dto.reports; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class ReportExecutionOptions { + + private Boolean freshData = false; + private Boolean saveDataSnapshot = false; + private Boolean interactive = false; + private Boolean ignorePagination; + private Boolean defaultIgnorePagination; + private Boolean async = false; + private String transformerKey; + private String contextPath; + private String defaultAttachmentsPrefixTemplate; + private String requestId; + + public ReportExecutionOptions(){} + public ReportExecutionOptions(ReportExecutionOptions source){ + freshData = source.isFreshData(); + saveDataSnapshot = source.isSaveDataSnapshot(); + interactive = source.isInteractive(); + ignorePagination = source.getIgnorePagination(); + async = source.isAsync(); + transformerKey = source.getTransformerKey(); + contextPath = source.getContextPath(); + defaultAttachmentsPrefixTemplate = source.getDefaultAttachmentsPrefixTemplate(); + requestId = source.getRequestId(); + + defaultIgnorePagination = source.getDefaultIgnorePagination(); + } + + + public Boolean getDefaultIgnorePagination() { + return defaultIgnorePagination; + } + + + public ReportExecutionOptions setDefaultIgnorePagination(Boolean defaultIgnorePagination) { + this.defaultIgnorePagination = defaultIgnorePagination; + return this; + } + + + public String getRequestId() { + return requestId; + } + + public ReportExecutionOptions setRequestId(String requestId) { + this.requestId = requestId; + return this; + } + + public String getDefaultAttachmentsPrefixTemplate() { + return defaultAttachmentsPrefixTemplate; + } + + public ReportExecutionOptions setDefaultAttachmentsPrefixTemplate(String defaultAttachmentsPrefixTemplate) { + this.defaultAttachmentsPrefixTemplate = defaultAttachmentsPrefixTemplate; + return this; + } + + public Boolean isAsync() { + return async; + } + + public ReportExecutionOptions setAsync(Boolean async) { + this.async = async; + return this; + } + + public String getContextPath() { + return contextPath; + } + + public ReportExecutionOptions setContextPath(String contextPath) { + this.contextPath = contextPath; + return this; + } + + public Boolean isFreshData() { + return freshData; + } + + public ReportExecutionOptions setFreshData(Boolean freshData) { + this.freshData = freshData; + return this; + } + + public Boolean isSaveDataSnapshot() { + return saveDataSnapshot; + } + + public ReportExecutionOptions setSaveDataSnapshot(Boolean saveDataSnapshot) { + this.saveDataSnapshot = saveDataSnapshot; + return this; + } + + /** + * ignorePagination is optional parameter. Can be null. Check for null is required. + * @return the ignorePagination value + */ + public Boolean getIgnorePagination() { + return ignorePagination; + } + + public ReportExecutionOptions setIgnorePagination(Boolean ignorePagination) { + this.ignorePagination = ignorePagination; + return this; + } + + public String getTransformerKey() { + return transformerKey; + } + + public ReportExecutionOptions setTransformerKey(String transformerKey) { + this.transformerKey = transformerKey; + return this; + } + + public Boolean isInteractive() { + return interactive; + } + + public ReportExecutionOptions setInteractive(Boolean interactive) { + this.interactive = interactive; + return this; + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionRequest.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionRequest.java index c19ce6c2..9ed96f9a 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionRequest.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionRequest.java @@ -22,9 +22,9 @@ package com.jaspersoft.jasperserver.jaxrs.client.dto.reports; import com.jaspersoft.jasperserver.dto.reports.ReportParameters; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.ReportOutputFormat; -import java.util.TimeZone; + import javax.xml.bind.annotation.XmlRootElement; +import java.util.TimeZone; /** *

@@ -32,6 +32,7 @@ * @author Yaroslav.Kovalchyk * @version $Id: ReportExecutionRequest.java 26599 2012-12-10 13:04:23Z ykovalchyk $ */ + @XmlRootElement public class ReportExecutionRequest { private String reportUnitUri; @@ -46,6 +47,33 @@ public class ReportExecutionRequest { private String attachmentsPrefix; private String pages; private ReportParameters parameters; + private TimeZone timeZone; + private Boolean allowInlineScripts = true; + private String baseUrl; + private String markupType; + private String anchor; + + public ReportExecutionRequest() { + } + + public ReportExecutionRequest(ReportExecutionRequest other) { + this.reportUnitUri = other.reportUnitUri; + this.freshData = other.freshData; + this.saveDataSnapshot = other.saveDataSnapshot; + this.interactive = other.interactive; + this.ignorePagination = other.ignorePagination; + this.async = other.async; + this.transformerKey = other.transformerKey; + this.outputFormat = other.outputFormat; + this.attachmentsPrefix = other.attachmentsPrefix; + this.pages = other.pages; + this.parameters = other.parameters; + this.timeZone = TimeZone.getTimeZone(timeZone.getID()); + this.allowInlineScripts = other.allowInlineScripts; + this.baseUrl = other.baseUrl; + this.markupType = other.markupType; + this.anchor = other.anchor; + } public TimeZone getTimeZone() { return timeZone; @@ -56,8 +84,6 @@ public ReportExecutionRequest setTimeZone(TimeZone timeZone) { return this; } - private TimeZone timeZone; - public String getReportUnitUri() { return reportUnitUri; } @@ -125,7 +151,7 @@ public String getOutputFormat() { return outputFormat; } - public ReportExecutionRequest setOutputFormat(ReportOutputFormat outputFormat) { + public ReportExecutionRequest setOutputFormat(com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util.ReportOutputFormat outputFormat) { this.outputFormat = outputFormat.toString().toLowerCase(); return this; } @@ -161,6 +187,42 @@ public ReportExecutionRequest setParameters(ReportParameters parameters) { return this; } + public Boolean getAllowInlineScripts() { + return allowInlineScripts; + } + + public ReportExecutionRequest setAllowInlineScripts(Boolean allowInlineScripts) { + this.allowInlineScripts = allowInlineScripts; + return this; + } + + public String getBaseUrl() { + return baseUrl; + } + + public ReportExecutionRequest setBaseUrl(String baseUrl) { + this.baseUrl = baseUrl; + return this; + } + + public String getMarkupType() { + return markupType; + } + + public ReportExecutionRequest setMarkupType(String markupType) { + this.markupType = markupType; + return this; + } + + public String getAnchor() { + return anchor; + } + + public ReportExecutionRequest setAnchor(String anchor) { + this.anchor = anchor; + return this; + } + @Override public boolean equals(Object o) { if (this == o) return true; @@ -168,44 +230,48 @@ public boolean equals(Object o) { ReportExecutionRequest that = (ReportExecutionRequest) o; - if (getReportUnitUri() != null ? !getReportUnitUri().equals(that.getReportUnitUri()) : that.getReportUnitUri() != null) + if (reportUnitUri != null ? !reportUnitUri.equals(that.reportUnitUri) : that.reportUnitUri != null) return false; - if (getFreshData() != null ? !getFreshData().equals(that.getFreshData()) : that.getFreshData() != null) + if (freshData != null ? !freshData.equals(that.freshData) : that.freshData != null) return false; + if (saveDataSnapshot != null ? !saveDataSnapshot.equals(that.saveDataSnapshot) : that.saveDataSnapshot != null) return false; - if (getSaveDataSnapshot() != null ? !getSaveDataSnapshot().equals(that.getSaveDataSnapshot()) : that.getSaveDataSnapshot() != null) + if (interactive != null ? !interactive.equals(that.interactive) : that.interactive != null) return false; + if (ignorePagination != null ? !ignorePagination.equals(that.ignorePagination) : that.ignorePagination != null) return false; - if (getInteractive() != null ? !getInteractive().equals(that.getInteractive()) : that.getInteractive() != null) + if (async != null ? !async.equals(that.async) : that.async != null) return false; + if (transformerKey != null ? !transformerKey.equals(that.transformerKey) : that.transformerKey != null) return false; - if (getIgnorePagination() != null ? !getIgnorePagination().equals(that.getIgnorePagination()) : that.getIgnorePagination() != null) + if (outputFormat != null ? !outputFormat.equals(that.outputFormat) : that.outputFormat != null) return false; + if (attachmentsPrefix != null ? !attachmentsPrefix.equals(that.attachmentsPrefix) : that.attachmentsPrefix != null) return false; - if (getAsync() != null ? !getAsync().equals(that.getAsync()) : that.getAsync() != null) return false; - if (getTransformerKey() != null ? !getTransformerKey().equals(that.getTransformerKey()) : that.getTransformerKey() != null) + if (pages != null ? !pages.equals(that.pages) : that.pages != null) return false; + if (parameters != null ? !parameters.equals(that.parameters) : that.parameters != null) return false; + if (timeZone != null ? !timeZone.equals(that.timeZone) : that.timeZone != null) return false; + if (allowInlineScripts != null ? !allowInlineScripts.equals(that.allowInlineScripts) : that.allowInlineScripts != null) return false; - if (getOutputFormat() != null ? !getOutputFormat().equals(that.getOutputFormat()) : that.getOutputFormat() != null) - return false; - if (getAttachmentsPrefix() != null ? !getAttachmentsPrefix().equals(that.getAttachmentsPrefix()) : that.getAttachmentsPrefix() != null) - return false; - if (getPages() != null ? !getPages().equals(that.getPages()) : that.getPages() != null) return false; - if (getParameters() != null ? !getParameters().equals(that.getParameters()) : that.getParameters() != null) - return false; - return !(getTimeZone() != null ? !getTimeZone().equals(that.getTimeZone()) : that.getTimeZone() != null); - + if (baseUrl != null ? !baseUrl.equals(that.baseUrl) : that.baseUrl != null) return false; + if (markupType != null ? !markupType.equals(that.markupType) : that.markupType != null) return false; + return anchor != null ? anchor.equals(that.anchor) : that.anchor == null; } @Override public int hashCode() { - int result = getReportUnitUri() != null ? getReportUnitUri().hashCode() : 0; - result = 31 * result + (getFreshData() != null ? getFreshData().hashCode() : 0); - result = 31 * result + (getSaveDataSnapshot() != null ? getSaveDataSnapshot().hashCode() : 0); - result = 31 * result + (getInteractive() != null ? getInteractive().hashCode() : 0); - result = 31 * result + (getIgnorePagination() != null ? getIgnorePagination().hashCode() : 0); - result = 31 * result + (getAsync() != null ? getAsync().hashCode() : 0); - result = 31 * result + (getTransformerKey() != null ? getTransformerKey().hashCode() : 0); - result = 31 * result + (getOutputFormat() != null ? getOutputFormat().hashCode() : 0); - result = 31 * result + (getAttachmentsPrefix() != null ? getAttachmentsPrefix().hashCode() : 0); - result = 31 * result + (getPages() != null ? getPages().hashCode() : 0); - result = 31 * result + (getParameters() != null ? getParameters().hashCode() : 0); - result = 31 * result + (getTimeZone() != null ? getTimeZone().hashCode() : 0); + int result = reportUnitUri != null ? reportUnitUri.hashCode() : 0; + result = 31 * result + (freshData != null ? freshData.hashCode() : 0); + result = 31 * result + (saveDataSnapshot != null ? saveDataSnapshot.hashCode() : 0); + result = 31 * result + (interactive != null ? interactive.hashCode() : 0); + result = 31 * result + (ignorePagination != null ? ignorePagination.hashCode() : 0); + result = 31 * result + (async != null ? async.hashCode() : 0); + result = 31 * result + (transformerKey != null ? transformerKey.hashCode() : 0); + result = 31 * result + (outputFormat != null ? outputFormat.hashCode() : 0); + result = 31 * result + (attachmentsPrefix != null ? attachmentsPrefix.hashCode() : 0); + result = 31 * result + (pages != null ? pages.hashCode() : 0); + result = 31 * result + (parameters != null ? parameters.hashCode() : 0); + result = 31 * result + (timeZone != null ? timeZone.hashCode() : 0); + result = 31 * result + (allowInlineScripts != null ? allowInlineScripts.hashCode() : 0); + result = 31 * result + (baseUrl != null ? baseUrl.hashCode() : 0); + result = 31 * result + (markupType != null ? markupType.hashCode() : 0); + result = 31 * result + (anchor != null ? anchor.hashCode() : 0); return result; } @@ -224,6 +290,10 @@ public String toString() { ", pages='" + pages + '\'' + ", parameters=" + parameters + ", timeZone=" + timeZone + + ", allowInlineScripts=" + allowInlineScripts + + ", baseUrl='" + baseUrl + '\'' + + ", markupType='" + markupType + '\'' + + ", anchor='" + anchor + '\'' + '}'; } } diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionStatus.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionStatus.java new file mode 100644 index 00000000..f26bea7e --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionStatus.java @@ -0,0 +1,81 @@ +package com.jaspersoft.jasperserver.jaxrs.client.dto.reports; + +import java.util.HashMap; +import java.util.Map; +import javax.xml.bind.annotation.XmlRootElement; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +@XmlRootElement(name = "reportExecution") +public class ReportExecutionStatus { + + private String requestId; + private String reportURI; + private Map propertyMap = new HashMap<>(); + + public ReportExecutionStatus() { + } + + public ReportExecutionStatus(ReportExecutionStatus other) { + this.requestId = other.requestId; + if (other.propertyMap != null) { + for (String property : propertyMap.keySet()) { + this.propertyMap.put(property, propertyMap.get(property)); + } + } + this.reportURI = other.reportURI; + } + + public String getRequestId() { + return requestId; + } + + public ReportExecutionStatus setRequestId(String requestId) { + this.requestId = requestId; + return this; + } + + public String getReportURI() { + return reportURI; + } + + public ReportExecutionStatus setReportURI(String reportURI) { + this.reportURI = reportURI; + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof ReportExecutionStatus)) return false; + + ReportExecutionStatus that = (ReportExecutionStatus) o; + + if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false; + if (reportURI != null ? !reportURI.equals(that.reportURI) : that.reportURI != null) return false; + return propertyMap != null ? propertyMap.equals(that.propertyMap) : that.propertyMap == null; + } + + @Override + public int hashCode() { + int result = requestId != null ? requestId.hashCode() : 0; + result = 31 * result + (reportURI != null ? reportURI.hashCode() : 0); + result = 31 * result + (propertyMap != null ? propertyMap.hashCode() : 0); + return result; + } + + @Override + public String toString() { + return "ReportExecutionStatus{" + + "requestId='" + requestId + '\'' + + ", reportURI='" + reportURI + '\'' + + ", propertyMap=" + propertyMap + + '}'; + } +} \ No newline at end of file diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionStatusEntity.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionStatusEntity.java index 8752e1b4..bb7fcf3f 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionStatusEntity.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionStatusEntity.java @@ -28,6 +28,7 @@ * @author Yaroslav.Kovalchyk * @version $Id: ReportExecutionStatusEntity.java 26599 2012-12-10 13:04:23Z ykovalchyk $ */ + @XmlRootElement(name = "status") public class ReportExecutionStatusEntity { public static final String VALUE_CANCELLED = "cancelled"; @@ -39,8 +40,9 @@ public String getValue() { return value; } - public void setValue(String value) { + public ReportExecutionStatusEntity setValue(String value) { this.value = value; + return this; } @Override diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionStatusObject.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionStatusObject.java new file mode 100644 index 00000000..f7e8735f --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionStatusObject.java @@ -0,0 +1,75 @@ +package com.jaspersoft.jasperserver.jaxrs.client.dto.reports; + +import com.jaspersoft.jasperserver.dto.common.ErrorDescriptor; +import com.jaspersoft.jasperserver.dto.executions.ExecutionStatus; +import javax.xml.bind.annotation.XmlRootElement; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ + +@XmlRootElement(name = "status") +public class ReportExecutionStatusObject { + + private ExecutionStatus value; + private ErrorDescriptor errorDescriptor; + + public ReportExecutionStatusObject(){} + + public ReportExecutionStatusObject(ReportExecutionStatusObject source){ + this.value = source.getValue(); + this.errorDescriptor = new ErrorDescriptor(source.getErrorDescriptor()); + } + + public ExecutionStatus getValue() { + return value; + } + + public ReportExecutionStatusObject setValue(ExecutionStatus value) { + this.value = value; + return this; + } + + public ErrorDescriptor getErrorDescriptor() { + return errorDescriptor; + } + + public ReportExecutionStatusObject setErrorDescriptor(ErrorDescriptor errorDescriptor) { + this.errorDescriptor = errorDescriptor; + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + ReportExecutionStatusObject that = (ReportExecutionStatusObject) o; + + if (errorDescriptor != null ? !errorDescriptor.equals(that.errorDescriptor) : that.errorDescriptor != null) + return false; + if (value != that.value) return false; + + return true; + } + + @Override + public int hashCode() { + int result = value != null ? value.hashCode() : 0; + result = 31 * result + (errorDescriptor != null ? errorDescriptor.hashCode() : 0); + return result; + } + + @Override + public String toString() { + return "ReportExecutionStatusObject{" + + "value=" + value + + ", errorDescriptor=" + errorDescriptor + + '}'; + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionsSetWrapper.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionsSetWrapper.java new file mode 100644 index 00000000..b88427e2 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/ReportExecutionsSetWrapper.java @@ -0,0 +1,41 @@ +package com.jaspersoft.jasperserver.jaxrs.client.dto.reports; + +import java.util.HashSet; +import java.util.Set; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +@XmlRootElement(name = "reportExecutions") +public class ReportExecutionsSetWrapper { + + private Set reportExecutionStatuses; + + public ReportExecutionsSetWrapper(){} + + public ReportExecutionsSetWrapper(Set reportExecutionStatuses) { + if (reportExecutionStatuses != null) { + this.reportExecutionStatuses = new HashSet<>(); + for (ReportExecutionStatus reportExecutionStatus : reportExecutionStatuses) { + this.reportExecutionStatuses.add(new ReportExecutionStatus(reportExecutionStatus)); + } + } + } + + @XmlElement(name = "reportExecution") + public Set getReportExecutionStatuses() { + return reportExecutionStatuses; + } + + public ReportExecutionsSetWrapper setReportExecutionStatuses(Set reportExecutionStatuses) { + this.reportExecutionStatuses = reportExecutionStatuses; + return this; + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/reportinfo/Bookmark.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/reportinfo/Bookmark.java new file mode 100644 index 00000000..d56ff9dc --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/reportinfo/Bookmark.java @@ -0,0 +1,94 @@ +package com.jaspersoft.jasperserver.jaxrs.client.dto.reports.reportinfo; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * @author Tatyana Matveyeva + */ +public class Bookmark { + private String label; + private Integer pageIndex; + private String elementAddress; + private List bookmarks; + + public Bookmark() { + } + + public Bookmark(Bookmark other) { + label = other.label; + pageIndex = other.pageIndex; + elementAddress = other.elementAddress; + bookmarks = new ArrayList<>(other.bookmarks); + } + + @XmlElement + public String getLabel() { + return label; + } + + @XmlElement + public Integer getPageIndex() { + return pageIndex; + } + + @XmlElement + public String getElementAddress() { + return elementAddress; + } + + @XmlElementWrapper(name = "bookmarks") + @XmlElement(name = "bookmark") + public List getBookmarks() { + return bookmarks; + } + + public Bookmark setBookmarks(List bookmarks) { + this.bookmarks = bookmarks; + return this; + } + + public Bookmark setLabel(String label) { + this.label = label; + return this; + } + + public Bookmark setPageIndex(Integer pageIndex) { + this.pageIndex = pageIndex; + return this; + } + + public Bookmark setElementAddress(String elementAddress) { + this.elementAddress = elementAddress; + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Bookmark bookmark = (Bookmark) o; + return Objects.equals(label, bookmark.label) && + Objects.equals(pageIndex, bookmark.pageIndex) && + Objects.equals(elementAddress, bookmark.elementAddress) && + Objects.equals(bookmarks, bookmark.bookmarks); + } + + @Override + public int hashCode() { + return Objects.hash(label, pageIndex, elementAddress, bookmarks); + } + + @Override + public String toString() { + return "Bookmark{" + + "label='" + label + '\'' + + ", pageIndex=" + pageIndex + + ", elementAddress='" + elementAddress + '\'' + + ", bookmarks=" + bookmarks + + '}'; + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/reportinfo/BookmarksInfo.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/reportinfo/BookmarksInfo.java new file mode 100644 index 00000000..0265728f --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/reportinfo/BookmarksInfo.java @@ -0,0 +1,79 @@ +package com.jaspersoft.jasperserver.jaxrs.client.dto.reports.reportinfo; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * @author Tatyana Matveyeva + */ +public class BookmarksInfo { + private String id; + private String type; + private List bookmarks; + + public BookmarksInfo() {} + + public BookmarksInfo(BookmarksInfo other) { + this.id = other.id; + this.type = other.type; + this.bookmarks = new ArrayList<>(bookmarks); + } + + @XmlElement + public String getId() { + return id; + } + + @XmlElement + public String getType() { + return type; + } + + @XmlElementWrapper(name = "bookmarks") + @XmlElement(name = "bookmark") + public List getBookmarks() { + return bookmarks; + } + + public BookmarksInfo setId(String id) { + this.id = id; + return this; + } + + public BookmarksInfo setType(String type) { + this.type = type; + return this; + } + + public BookmarksInfo setBookmarks(List bookmarks) { + this.bookmarks = bookmarks; + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + BookmarksInfo that = (BookmarksInfo) o; + return Objects.equals(id, that.id) && + Objects.equals(type, that.type) && + Objects.equals(bookmarks, that.bookmarks); + } + + @Override + public int hashCode() { + return Objects.hash(id, type, bookmarks); + } + + @Override + public String toString() { + return "BookmarksInfo{" + + "id='" + id + '\'' + + ", type='" + type + '\'' + + ", bookmarks=" + bookmarks + + '}'; + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/reportinfo/Part.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/reportinfo/Part.java new file mode 100644 index 00000000..7c86f329 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/reportinfo/Part.java @@ -0,0 +1,62 @@ +package com.jaspersoft.jasperserver.jaxrs.client.dto.reports.reportinfo; + +import javax.xml.bind.annotation.XmlElement; +import java.util.Objects; + +/** + * @author Tatyana Matveyeva + */ +public class Part { + private Integer idx; + private String name; + + public Part() { + } + + public Part(Part other) { + idx = other.idx; + name = other.name; + } + + @XmlElement + public Integer getIdx() { + return idx; + } + + @XmlElement + public String getName() { + return name; + } + + public Part setIdx(Integer idx) { + this.idx = idx; + return this; + } + + public Part setName(String name) { + this.name = name; + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Part part = (Part) o; + return Objects.equals(idx, part.idx) && + Objects.equals(name, part.name); + } + + @Override + public int hashCode() { + return Objects.hash(idx, name); + } + + @Override + public String toString() { + return "Part{" + + "idx=" + idx + + ", name='" + name + '\'' + + '}'; + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/reportinfo/PartsInfo.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/reportinfo/PartsInfo.java new file mode 100644 index 00000000..5bf37c2a --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/reportinfo/PartsInfo.java @@ -0,0 +1,79 @@ +package com.jaspersoft.jasperserver.jaxrs.client.dto.reports.reportinfo; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * @author Tatyana Matveyeva + */ +public class PartsInfo { + private String id; + private String type; + private List parts; + + public PartsInfo() {} + + public PartsInfo(PartsInfo other) { + this.id = other.id; + this.type = other.type; + this.parts = new ArrayList<>(other.parts); + } + + @XmlElement + public String getId() { + return id; + } + + @XmlElement + public String getType() { + return type; + } + + @XmlElementWrapper(name = "parts") + @XmlElement(name = "part") + public List getParts() { + return parts; + } + + public PartsInfo setId(String id) { + this.id = id; + return this; + } + + public PartsInfo setType(String type) { + this.type = type; + return this; + } + + public PartsInfo setParts(List parts) { + this.parts = parts; + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + PartsInfo partsInfo = (PartsInfo) o; + return Objects.equals(id, partsInfo.id) && + Objects.equals(type, partsInfo.type) && + Objects.equals(parts, partsInfo.parts); + } + + @Override + public int hashCode() { + return Objects.hash(id, type, parts); + } + + @Override + public String toString() { + return "PartsInfo{" + + "id='" + id + '\'' + + ", type='" + type + '\'' + + ", parts=" + parts + + '}'; + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/reportinfo/ReportInfo.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/reportinfo/ReportInfo.java new file mode 100644 index 00000000..1b9788d8 --- /dev/null +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/reports/reportinfo/ReportInfo.java @@ -0,0 +1,69 @@ +package com.jaspersoft.jasperserver.jaxrs.client.dto.reports.reportinfo; + +import javax.xml.bind.annotation.XmlAccessOrder; +import javax.xml.bind.annotation.XmlAccessorOrder; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.Objects; + +/** + * @author Tatyana Matveyeva + */ +@XmlRootElement +@XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL) +public class ReportInfo { + private BookmarksInfo bookmarks; + private PartsInfo parts; + + public ReportInfo() { + } + + public ReportInfo(ReportInfo other) { + this.bookmarks = other.bookmarks; + this.parts = other.parts; + } + + + @XmlElement + public BookmarksInfo getBookmarks() { + return bookmarks; + } + + + @XmlElement + public PartsInfo getParts() { + return parts; + } + + public ReportInfo setBookmarks(BookmarksInfo bookmarks) { + this.bookmarks = bookmarks; + return this; + } + + public ReportInfo setParts(PartsInfo parts) { + this.parts = parts; + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ReportInfo that = (ReportInfo) o; + return Objects.equals(bookmarks, that.bookmarks) && + Objects.equals(parts, that.parts); + } + + @Override + public int hashCode() { + return Objects.hash(bookmarks, parts); + } + + @Override + public String toString() { + return "ReportInfo{" + + "bookmarks=" + bookmarks + + ", parts=" + parts + + '}'; + } +} diff --git a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/providers/CustomRepresentationTypeProvider.java b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/providers/CustomRepresentationTypeProvider.java index 749fb5fe..5e0eed9c 100644 --- a/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/providers/CustomRepresentationTypeProvider.java +++ b/src/main/java/com/jaspersoft/jasperserver/jaxrs/client/providers/CustomRepresentationTypeProvider.java @@ -22,14 +22,15 @@ package com.jaspersoft.jasperserver.jaxrs.client.providers; import com.jaspersoft.jasperserver.dto.resources.ResourceMediaType; -import com.jaspersoft.jasperserver.jaxrs.client.core.enums.ConnectionMediaType; -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.ContextMediaTypes; +import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider; + import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.ext.Provider; -import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; @Provider @@ -40,14 +41,14 @@ "application/job+json", "application/json", "application/job+xml", - ConnectionMediaType.FTP_JSON, - ConnectionMediaType.FTP_XML, - ConnectionMediaType.LOCAL_FILE_SYSTEM_JSON, - ConnectionMediaType.LOCAL_FILE_SYSTEM_XML, - ConnectionMediaType.TXT_FILE_JSON, - ConnectionMediaType.TXT_FILE_XML, - ConnectionMediaType.XLS_FILE_JSON, - ConnectionMediaType.XLS_FILE_XML, + ContextMediaTypes.FTP_JSON, + ContextMediaTypes.FTP_XML, + ContextMediaTypes.LOCAL_FILE_SYSTEM_JSON, + ContextMediaTypes.LOCAL_FILE_SYSTEM_XML, + ContextMediaTypes.TXT_FILE_JSON, + ContextMediaTypes.TXT_FILE_XML, + ContextMediaTypes.XLS_FILE_JSON, + ContextMediaTypes.XLS_FILE_XML, ResourceMediaType.LIST_OF_VALUES_JSON, ResourceMediaType.LIST_OF_VALUES_XML, ResourceMediaType.ADHOC_DATA_VIEW_JSON, @@ -90,32 +91,70 @@ ResourceMediaType.XMLA_CONNECTION_XML, ResourceMediaType.RESOURCE_LOOKUP_JSON, ResourceMediaType.RESOURCE_LOOKUP_XML, + "application/jdbc.metadata+json", + "application/jdbc.metadata+xml", "application/repository.dashboard+json", "application/repository.dashboard+xml", "application/repository.domainTopic+json", "application/repository.domainTopic+xml", - "application/repository.semanticlayerdatasource+json", - "application/repository.semanticlayerdatasource+xml", + "application/repository.domainSchema+json", + "application/repository.domainSchema+xml", + ContextMediaTypes.FTP_JSON, + ContextMediaTypes.FTP_XML, + ContextMediaTypes.LOCAL_FILE_SYSTEM_JSON, + ContextMediaTypes.LOCAL_FILE_SYSTEM_XML, + ContextMediaTypes.DOM_EL_CONTEXT_JSON, + ContextMediaTypes.DOM_EL_COLLECTION_CONTEXT_JSON, "application/hal+json", "application/hal+xml", "text/json", "text/xml", "application/attributes.collection+json", - "application/attributes.collection+xml"}) + "application/attributes.collection+xml", + "application/repository.customDataSource.metadata+json", + "application/repository.customDataSource.metadata+xml", + "application/repository.semanticLayerDataSource+json", + "application/repository.semanticLayerDataSource+xml", + "application/repository.domain+json", + "application/repository.domain+xml", + "application/repository.domainSchema+json", + "application/repository.domainSchema+xml", + "application/repository.reportUnit+json", + "application/repository.reportUnit+xml", + "application/repository.reportOptions+json", + "application/repository.reportOptions+xml", + "application/repository.reportUnit.metadata+json", + "application/repository.reportUnit.metadata+xml", + "application/repository.domain+json", + "application/execution.multiLevelQuery+json", + "application/execution.multiAxisQuery+json", + "application/execution.providedQuery+json", + "application/execution.multiLevelQuery+xml", + "application/execution.multiAxisQuery+xml", + "application/execution.providedQuery+xml", + "application/flatData+json", + "application/multiLevelData+json", + "application/multiAxisData+json", + "application/flatData+xml", + "application/multiLevelData+xml", + "application/multiAxisData+xml", + "application/contexts.partialMetadataOptions+json", + "application/adhoc.multiLevelQuery+json" +}) @Produces({ "application/collection+json", "application/collection+xml", "application/job+json", "application/json", "application/job+xml", - ConnectionMediaType.FTP_JSON, - ConnectionMediaType.FTP_XML, - ConnectionMediaType.LOCAL_FILE_SYSTEM_JSON, - ConnectionMediaType.LOCAL_FILE_SYSTEM_XML, - ConnectionMediaType.TXT_FILE_JSON, - ConnectionMediaType.TXT_FILE_XML, - ConnectionMediaType.XLS_FILE_JSON, - ConnectionMediaType.XLS_FILE_XML, + ContextMediaTypes.FTP_JSON, + ContextMediaTypes.FTP_XML, + ContextMediaTypes.LOCAL_FILE_SYSTEM_JSON, + ContextMediaTypes.LOCAL_FILE_SYSTEM_XML, + ContextMediaTypes.TXT_FILE_JSON, + ContextMediaTypes.TXT_FILE_XML, + ContextMediaTypes.XLS_FILE_JSON, + ContextMediaTypes.XLS_FILE_XML, ResourceMediaType.LIST_OF_VALUES_JSON, ResourceMediaType.LIST_OF_VALUES_XML, ResourceMediaType.ADHOC_DATA_VIEW_JSON, @@ -158,19 +197,57 @@ ResourceMediaType.XMLA_CONNECTION_XML, ResourceMediaType.RESOURCE_LOOKUP_JSON, ResourceMediaType.RESOURCE_LOOKUP_XML, + "application/jdbc.metadata+json", + "application/jdbc.metadata+xml", "application/repository.dashboard+json", "application/repository.dashboard+xml", "application/repository.domainTopic+json", "application/repository.domainTopic+xml", - ResourceMediaType.SEMANTIC_LAYER_DATA_SOURCE_JSON, - ResourceMediaType.SEMANTIC_LAYER_DATA_SOURCE_XML, + ContextMediaTypes.FTP_JSON, + ContextMediaTypes.FTP_XML, + ContextMediaTypes.LOCAL_FILE_SYSTEM_JSON, + ContextMediaTypes.LOCAL_FILE_SYSTEM_XML, + ContextMediaTypes.DOM_EL_CONTEXT_JSON, + ContextMediaTypes.DOM_EL_COLLECTION_CONTEXT_JSON, + "application/repository.domainSchema+json", + "application/repository.domainSchema+xml", "application/xml", "application/hal+json", "application/hal+xml", "text/json", "text/xml", "application/attributes.collection+json", - "application/attributes.collection+xml"}) + "application/attributes.collection+xml", + "application/repository.customDataSource.metadata+json", + "application/repository.customDataSource.metadata+xml", + "application/repository.semanticLayerDataSource+json", + "application/repository.semanticLayerDataSource+xml", + "application/repository.domain+json", + "application/repository.domain+xml", + "application/repository.domainSchema+json", + "application/repository.domainSchema+xml", + "application/repository.reportUnit+json", + "application/repository.reportUnit+xml", + "application/repository.reportOptions+json", + "application/repository.reportOptions+xml", + "application/repository.reportUnit.metadata+json", + "application/repository.reportUnit.metadata+xml", + "application/repository.domain+json", + "application/execution.multiLevelQuery+json", + "application/execution.multiAxisQuery+json", + "application/execution.providedQuery+json", + "application/execution.multiLevelQuery+xml", + "application/execution.multiAxisQuery+xml", + "application/execution.providedQuery+xml", + "application/flatData+json", + "application/multiLevelData+json", + "application/multiAxisData+json", + "application/flatData+xml", + "application/multiLevelData+xml", + "application/multiAxisData+xml", + "application/contexts.partialMetadataOptions+json", + "application/adhoc.multiLevelQuery+json" +}) public class CustomRepresentationTypeProvider extends JacksonJaxbJsonProvider { @Override diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/adhoc/queryexecution/QueryExecutionAdapterTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/adhoc/queryexecution/QueryExecutionAdapterTest.java new file mode 100755 index 00000000..53e64190 --- /dev/null +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/adhoc/queryexecution/QueryExecutionAdapterTest.java @@ -0,0 +1,877 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.adhoc.queryexecution; + +import com.jaspersoft.jasperserver.dto.executions.ClientFlatQueryResultData; +import com.jaspersoft.jasperserver.dto.executions.ClientMultiAxisQueryExecution; +import com.jaspersoft.jasperserver.dto.executions.ClientMultiAxisQueryResultData; +import com.jaspersoft.jasperserver.dto.executions.ClientMultiLevelQueryExecution; +import com.jaspersoft.jasperserver.dto.executions.ClientMultiLevelQueryResultData; +import com.jaspersoft.jasperserver.dto.executions.ClientProvidedQueryExecution; +import com.jaspersoft.jasperserver.dto.executions.ClientQueryResultData; +import com.jaspersoft.jasperserver.dto.executions.ExecutionStatusObject; +import com.jaspersoft.jasperserver.dto.executions.AbstractClientExecution; +import com.jaspersoft.jasperserver.dto.executions.ClientExecutionListWrapper; +import com.jaspersoft.jasperserver.dto.executions.QueryResultDataMediaType; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.RestClientConfiguration; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.MimeType; +import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.MandatoryParameterNotFoundException; +import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import org.mockito.Mock; +import org.mockito.internal.util.reflection.Whitebox; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.testng.PowerMockTestCase; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import javax.ws.rs.core.MultivaluedHashMap; + +import static com.jaspersoft.jasperserver.dto.executions.QueryExecutionsMediaType.EXECUTION_MULTI_AXIS_QUERY_JSON; +import static com.jaspersoft.jasperserver.dto.executions.QueryExecutionsMediaType.EXECUTION_MULTI_LEVEL_QUERY_JSON; +import static com.jaspersoft.jasperserver.dto.executions.QueryExecutionsMediaType.EXECUTION_PROVIDED_QUERY_JSON; +import static com.jaspersoft.jasperserver.dto.executions.QueryResultDataMediaType.FLAT_DATA_JSON; +import static com.jaspersoft.jasperserver.dto.executions.QueryResultDataMediaType.FLAT_DATA_XML; +import static com.jaspersoft.jasperserver.dto.executions.QueryResultDataMediaType.MULTI_AXIS_DATA_JSON; +import static com.jaspersoft.jasperserver.dto.executions.QueryResultDataMediaType.MULTI_LEVEL_DATA_JSON; +import static com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest.buildRequest; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyInt; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.MockitoAnnotations.initMocks; +import static org.powermock.api.mockito.PowerMockito.mockStatic; +import static org.powermock.api.mockito.PowerMockito.spy; +import static org.powermock.api.mockito.PowerMockito.verifyStatic; +import static org.powermock.api.mockito.PowerMockito.when; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertSame; +import static org.testng.AssertJUnit.assertNotNull; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +@PrepareForTest({JerseyRequest.class}) +public class QueryExecutionAdapterTest extends PowerMockTestCase { + public static final String QUERY_EXECUTIONS_URI = "queryExecutions"; + public static final String CONTENT_TYPE = "someContentType"; + public static final String ACCEPT_TYPE = "someAcceptType"; + public static final String SOME_UUID = "someUuid"; + public static final String DATA = "data"; + @Mock + private SessionStorage storageMock; + @Mock + private JerseyRequest requestMock; + @Mock + private JerseyRequest multiLevelRequestMock; + @Mock + private OperationResult operationResultMock; + @Mock + private OperationResult multiLevelOperationResultMock; + @Mock + private JerseyRequest flatRequestMock; + @Mock + private OperationResult flatOperationResultMock; + @Mock + private JerseyRequest multiAxisRequestMock; + @Mock + private OperationResult multiAxisOperationResultMock; + @Mock + private JerseyRequest clientQueryRequestMock; + @Mock + private OperationResult clientQueryOperationResultMock; + @Mock + private RestClientConfiguration configurationMock; + + + @BeforeMethod + public void before() { + initMocks(this); + doReturn(configurationMock).when(storageMock).getConfiguration(); + doReturn(MimeType.JSON).when(configurationMock).getAcceptMimeType(); + } + + @AfterMethod + public void after() { + reset(storageMock, + requestMock, + multiLevelRequestMock, + operationResultMock, + multiLevelOperationResultMock, + flatRequestMock, + flatOperationResultMock, + multiAxisRequestMock, + multiAxisOperationResultMock, + clientQueryRequestMock, + clientQueryOperationResultMock, + configurationMock); + } + + @Test + public void should_set_proper_internal_state() { + // When + QueryExecutionAdapter adapter = new QueryExecutionAdapter(storageMock, CONTENT_TYPE, Object.class, ACCEPT_TYPE); + + //Then + assertEquals(Whitebox.getInternalState(adapter, "responseClass"), Object.class); + assertEquals(Whitebox.getInternalState(adapter, "contentType"), CONTENT_TYPE); + assertEquals(Whitebox.getInternalState(adapter, "acceptType"), new String[]{ACCEPT_TYPE}); + } + + @Test + public void should_set_proper_internal_state_with_params() { + // When + QueryExecutionAdapter adapter = new QueryExecutionAdapter(storageMock, CONTENT_TYPE, Object.class, ACCEPT_TYPE). + offset(0). + pageSize(10); + + //Then + assertEquals(2, ((MultivaluedHashMap) Whitebox.getInternalState(adapter, "params")).size()); + } + + @Test(expectedExceptions = MandatoryParameterNotFoundException.class) + public void should_throw_exception_when_query_is_null() { + // When + QueryExecutionAdapter adapter = new QueryExecutionAdapter(storageMock, CONTENT_TYPE, Object.class, ACCEPT_TYPE); + adapter.execute(null); + //Then + // An exception should be thrown + } + + @Test + public void should_return_proper_operation_result_when_execute_multi_level_query() { + // Given + mockStatic(JerseyRequest.class); + when(buildRequest( + eq(storageMock), + eq(ClientMultiLevelQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI}), + any(DefaultErrorHandler.class))).thenReturn(multiLevelRequestMock); + doReturn(multiLevelRequestMock).when(multiLevelRequestMock). + setContentType(EXECUTION_MULTI_LEVEL_QUERY_JSON); + doReturn(multiLevelRequestMock).when(multiLevelRequestMock). + setAccept(MULTI_LEVEL_DATA_JSON); + doReturn(multiLevelOperationResultMock).when(multiLevelRequestMock).post(any(ClientMultiLevelQueryExecution.class)); + + QueryExecutionAdapter adapter = new QueryExecutionAdapter(storageMock, + EXECUTION_MULTI_LEVEL_QUERY_JSON, + ClientMultiLevelQueryResultData.class, + MULTI_LEVEL_DATA_JSON); + + // When / + OperationResult retrieved = adapter.execute(new ClientMultiLevelQueryExecution()); + + // Then / + assertNotNull(retrieved); + assertSame(retrieved, multiLevelOperationResultMock); + verify(multiLevelRequestMock). + setContentType(EXECUTION_MULTI_LEVEL_QUERY_JSON); + verify(multiLevelRequestMock). + setAccept(MULTI_LEVEL_DATA_JSON); + verify(multiLevelRequestMock).post(any(ClientMultiLevelQueryExecution.class)); + verifyStatic(times(1)); + buildRequest( + eq(storageMock), + eq(ClientMultiLevelQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI}), + any(DefaultErrorHandler.class)); + + } + + @Test + public void should_return_proper_flatData_operation_result_when_execute_multi_level_query() { + // Given + mockStatic(JerseyRequest.class); + when(buildRequest( + eq(storageMock), + eq(ClientFlatQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI}), + any(DefaultErrorHandler.class))).thenReturn(flatRequestMock); + doReturn(flatRequestMock).when(flatRequestMock). + setContentType(EXECUTION_MULTI_LEVEL_QUERY_JSON); + doReturn(flatRequestMock).when(flatRequestMock). + setAccept(FLAT_DATA_JSON); + doReturn(flatOperationResultMock).when(flatRequestMock).post(any(ClientMultiLevelQueryExecution.class)); + + QueryExecutionAdapter adapter = new QueryExecutionAdapter(storageMock, + EXECUTION_MULTI_LEVEL_QUERY_JSON, + ClientMultiLevelQueryResultData.class, + MULTI_LEVEL_DATA_JSON); + + // When / + OperationResult retrieved = adapter. + asResultDataSet(QueryResultDataMediaType.FLAT_DATA_JSON). + execute(new ClientMultiLevelQueryExecution()); + + // Then / + assertNotNull(retrieved); + assertSame(retrieved, flatOperationResultMock); + verify(flatRequestMock). + setContentType(EXECUTION_MULTI_LEVEL_QUERY_JSON); + verify(flatRequestMock). + setAccept(FLAT_DATA_JSON); + verify(flatRequestMock).post(any(ClientMultiLevelQueryExecution.class)); + verifyStatic(times(1)); + buildRequest( + eq(storageMock), + eq(ClientFlatQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI}), + any(DefaultErrorHandler.class)); + + } + + @Test + public void should_return_proper_operation_result_when_execute_flat_query() { + // Given + mockStatic(JerseyRequest.class); + when(buildRequest( + eq(storageMock), + eq(ClientFlatQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI}), + any(DefaultErrorHandler.class))).thenReturn(flatRequestMock); + doReturn(flatRequestMock).when(flatRequestMock). + setContentType(EXECUTION_MULTI_LEVEL_QUERY_JSON); + doReturn(flatRequestMock).when(flatRequestMock). + setAccept(FLAT_DATA_JSON); + doReturn(flatOperationResultMock).when(flatRequestMock).post(any(ClientMultiLevelQueryExecution.class)); + + QueryExecutionAdapter adapter = new QueryExecutionAdapter(storageMock, + EXECUTION_MULTI_LEVEL_QUERY_JSON, + ClientFlatQueryResultData.class, + FLAT_DATA_JSON); + + // When / + OperationResult retrieved = adapter.execute(new ClientMultiLevelQueryExecution()); + + // Then / + assertNotNull(retrieved); + assertSame(retrieved, flatOperationResultMock); + verify(flatRequestMock). + setContentType(EXECUTION_MULTI_LEVEL_QUERY_JSON); + verify(flatRequestMock). + setAccept(FLAT_DATA_JSON); + verify(flatRequestMock).post(any(ClientMultiLevelQueryExecution.class)); + verifyStatic(times(1)); + buildRequest( + eq(storageMock), + eq(ClientFlatQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI}), + any(DefaultErrorHandler.class)); + + } + + + @Test + public void should_return_proper_operation_result_when_execute_multi_axis_query() { + // Given + mockStatic(JerseyRequest.class); + when(buildRequest( + eq(storageMock), + eq(ClientMultiAxisQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI}), + any(DefaultErrorHandler.class))).thenReturn(multiAxisRequestMock); + doReturn(multiAxisRequestMock).when(multiAxisRequestMock). + setContentType(EXECUTION_MULTI_AXIS_QUERY_JSON); + doReturn(multiAxisRequestMock).when(multiAxisRequestMock). + setAccept(MULTI_AXIS_DATA_JSON); + doReturn(multiAxisOperationResultMock).when(multiAxisRequestMock).post(any(ClientMultiAxisQueryExecution.class)); + + QueryExecutionAdapter adapter = new QueryExecutionAdapter(storageMock, + EXECUTION_MULTI_AXIS_QUERY_JSON, + ClientMultiAxisQueryResultData.class, + MULTI_AXIS_DATA_JSON); + + // When / + OperationResult retrieved = adapter.execute(new ClientMultiAxisQueryExecution()); + + // Then / + assertNotNull(retrieved); + assertSame(retrieved, multiAxisOperationResultMock); + verify(multiAxisRequestMock). + setContentType(EXECUTION_MULTI_AXIS_QUERY_JSON); + verify(multiAxisRequestMock). + setAccept(MULTI_AXIS_DATA_JSON); + verify(multiAxisRequestMock).post(any(ClientMultiAxisQueryExecution.class)); + + verifyStatic(times(1)); + buildRequest( + eq(storageMock), + eq(ClientMultiAxisQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI}), + any(DefaultErrorHandler.class)); + + } + + @Test + public void should_return_proper_operation_result_when_execute_provided_multi_axis_query() { + // Given + mockStatic(JerseyRequest.class); + when(buildRequest( + eq(storageMock), + eq(ClientMultiAxisQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI}), + any(DefaultErrorHandler.class))).thenReturn(multiAxisRequestMock); + doReturn(multiAxisRequestMock).when(multiAxisRequestMock). + setContentType(EXECUTION_PROVIDED_QUERY_JSON); + doReturn(multiAxisRequestMock).when(multiAxisRequestMock). + setAccept(MULTI_AXIS_DATA_JSON); + doReturn(multiAxisOperationResultMock).when(multiAxisRequestMock).post(any(ClientProvidedQueryExecution.class)); + + QueryExecutionAdapter adapter = new QueryExecutionAdapter(storageMock, + EXECUTION_PROVIDED_QUERY_JSON, + ClientMultiAxisQueryResultData.class, + MULTI_AXIS_DATA_JSON); + + // When / + OperationResult retrieved = adapter.execute(new ClientProvidedQueryExecution()); + + // Then / + assertNotNull(retrieved); + assertSame(retrieved, multiAxisOperationResultMock); + verify(multiAxisRequestMock). + setContentType(EXECUTION_PROVIDED_QUERY_JSON); + verify(multiAxisRequestMock). + setAccept(MULTI_AXIS_DATA_JSON); + verify(multiAxisRequestMock).post(any(ClientProvidedQueryExecution.class)); + + verifyStatic(times(1)); + buildRequest( + eq(storageMock), + eq(ClientMultiAxisQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI}), + any(DefaultErrorHandler.class)); + + } + + + @Test + public void should_return_proper_operation_result_when_execute_provided_multi_level_query() { + // Given + mockStatic(JerseyRequest.class); + when(buildRequest( + eq(storageMock), + eq(ClientMultiLevelQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI}), + any(DefaultErrorHandler.class))).thenReturn(multiLevelRequestMock); + doReturn(multiLevelRequestMock).when(multiLevelRequestMock). + setContentType(EXECUTION_PROVIDED_QUERY_JSON); + doReturn(multiLevelRequestMock).when(multiLevelRequestMock). + setAccept(MULTI_LEVEL_DATA_JSON); + doReturn(multiLevelOperationResultMock).when(multiLevelRequestMock).post(any(ClientProvidedQueryExecution.class)); + + QueryExecutionAdapter adapter = new QueryExecutionAdapter(storageMock, + EXECUTION_PROVIDED_QUERY_JSON, + ClientMultiLevelQueryResultData.class, + MULTI_LEVEL_DATA_JSON); + + // When / + OperationResult retrieved = adapter.execute(new ClientProvidedQueryExecution()); + + // Then / + assertNotNull(retrieved); + assertSame(retrieved, multiLevelOperationResultMock); + verify(multiLevelRequestMock). + setContentType(EXECUTION_PROVIDED_QUERY_JSON); + verify(multiLevelRequestMock). + setAccept(MULTI_LEVEL_DATA_JSON); + verify(multiLevelRequestMock).post(any(ClientProvidedQueryExecution.class)); + + verifyStatic(times(1)); + buildRequest( + eq(storageMock), + eq(ClientMultiLevelQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI}), + any(DefaultErrorHandler.class)); + } + + @Test + public void should_return_proper_operation_result_when_execute_provided_flat_query() { + // Given + mockStatic(JerseyRequest.class); + when(buildRequest( + eq(storageMock), + eq(ClientFlatQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI}), + any(DefaultErrorHandler.class))).thenReturn(flatRequestMock); + doReturn(flatRequestMock).when(flatRequestMock). + setContentType(EXECUTION_PROVIDED_QUERY_JSON); + doReturn(flatRequestMock).when(flatRequestMock). + setAccept(FLAT_DATA_JSON); + doReturn(flatOperationResultMock).when(flatRequestMock).post(any(ClientMultiLevelQueryExecution.class)); + + QueryExecutionAdapter adapter = new QueryExecutionAdapter(storageMock, + EXECUTION_PROVIDED_QUERY_JSON, + ClientFlatQueryResultData.class, + FLAT_DATA_JSON); + + // When / + OperationResult retrieved = adapter.execute(new ClientProvidedQueryExecution()); + + // Then / + assertNotNull(retrieved); + assertSame(retrieved, flatOperationResultMock); + verify(flatRequestMock). + setContentType(EXECUTION_PROVIDED_QUERY_JSON); + verify(flatRequestMock). + setAccept(FLAT_DATA_JSON); + verify(flatRequestMock).post(any(ClientMultiLevelQueryExecution.class)); + + verifyStatic(times(1)); + buildRequest( + eq(storageMock), + eq(ClientFlatQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI}), + any(DefaultErrorHandler.class)); + + } + + @Test + public void should_return_proper_operation_result_when_execute_provided_flat_query_result_as_xml() { + // Given + mockStatic(JerseyRequest.class); + when(buildRequest( + eq(storageMock), + eq(ClientFlatQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI}), + any(DefaultErrorHandler.class))).thenReturn(flatRequestMock); + doReturn(configurationMock).when(storageMock).getConfiguration(); + doReturn(MimeType.JSON).when(configurationMock).getAcceptMimeType(); + doReturn(flatRequestMock).when(flatRequestMock). + setContentType(EXECUTION_PROVIDED_QUERY_JSON); + doReturn(flatRequestMock).when(flatRequestMock). + setAccept(FLAT_DATA_XML); + doReturn(flatOperationResultMock).when(flatRequestMock).post(any(ClientMultiLevelQueryExecution.class)); + + QueryExecutionAdapter adapter = new QueryExecutionAdapter(storageMock, + EXECUTION_PROVIDED_QUERY_JSON, + ClientFlatQueryResultData.class, + FLAT_DATA_JSON); + + // When / + OperationResult retrieved = adapter.asXml().execute(new ClientProvidedQueryExecution()); + + // Then / + assertNotNull(retrieved); + assertSame(retrieved, flatOperationResultMock); + verify(flatRequestMock). + setContentType(EXECUTION_PROVIDED_QUERY_JSON); + verify(flatRequestMock). + setAccept(FLAT_DATA_XML); + verify(flatRequestMock).post(any(ClientMultiLevelQueryExecution.class)); + + verifyStatic(times(1)); + buildRequest( + eq(storageMock), + eq(ClientFlatQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI}), + any(DefaultErrorHandler.class)); + + } + @Test + public void should_return_proper_operation_result_when_execute_provided_flat_query_result_as_xml_from_config() { + // Given + mockStatic(JerseyRequest.class); + when(buildRequest( + eq(storageMock), + eq(ClientFlatQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI}), + any(DefaultErrorHandler.class))).thenReturn(flatRequestMock); + doReturn(configurationMock).when(storageMock).getConfiguration(); + doReturn(MimeType.XML).when(configurationMock).getAcceptMimeType(); + doReturn(flatRequestMock).when(flatRequestMock). + setContentType(EXECUTION_PROVIDED_QUERY_JSON); + doReturn(flatRequestMock).when(flatRequestMock). + setAccept(FLAT_DATA_XML); + doReturn(flatOperationResultMock).when(flatRequestMock).post(any(ClientMultiLevelQueryExecution.class)); + + QueryExecutionAdapter adapter = new QueryExecutionAdapter(storageMock, + EXECUTION_PROVIDED_QUERY_JSON, + ClientFlatQueryResultData.class, + FLAT_DATA_XML); + + // When / + OperationResult retrieved = adapter.asXml().execute(new ClientProvidedQueryExecution()); + + // Then / + assertNotNull(retrieved); + assertSame(retrieved, flatOperationResultMock); + verify(flatRequestMock). + setContentType(EXECUTION_PROVIDED_QUERY_JSON); + verify(flatRequestMock). + setAccept(FLAT_DATA_XML); + verify(flatRequestMock).post(any(ClientMultiLevelQueryExecution.class)); + + verifyStatic(times(1)); + buildRequest( + eq(storageMock), + eq(ClientFlatQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI}), + any(DefaultErrorHandler.class)); + + } + + @Test + public void should_return_proper_operation_result_when_execute_provided_flat_query_result_as_json() { + // Given + mockStatic(JerseyRequest.class); + when(buildRequest( + eq(storageMock), + eq(ClientFlatQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI}), + any(DefaultErrorHandler.class))).thenReturn(flatRequestMock); + doReturn(configurationMock).when(storageMock).getConfiguration(); + doReturn(MimeType.JSON).when(configurationMock).getAcceptMimeType(); + doReturn(flatRequestMock).when(flatRequestMock). + setContentType(EXECUTION_PROVIDED_QUERY_JSON); + doReturn(flatRequestMock).when(flatRequestMock). + setAccept(FLAT_DATA_JSON); + doReturn(flatOperationResultMock).when(flatRequestMock).post(any(ClientMultiLevelQueryExecution.class)); + + QueryExecutionAdapter adapter = new QueryExecutionAdapter(storageMock, + EXECUTION_PROVIDED_QUERY_JSON, + ClientFlatQueryResultData.class, + FLAT_DATA_JSON); + + // When / + OperationResult retrieved = adapter.asJson().execute(new ClientProvidedQueryExecution()); + + // Then / + assertNotNull(retrieved); + assertSame(retrieved, flatOperationResultMock); + verify(flatRequestMock). + setContentType(EXECUTION_PROVIDED_QUERY_JSON); + verify(flatRequestMock). + setAccept(FLAT_DATA_JSON); + verify(flatRequestMock).post(any(ClientMultiLevelQueryExecution.class)); + + verifyStatic(times(1)); + buildRequest( + eq(storageMock), + eq(ClientFlatQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI}), + any(DefaultErrorHandler.class)); + + } + + @Test + public void should_return_proper_operation_result_when_execute_provided_flat_query_result_as_json_whn_config_xml() { + // Given + mockStatic(JerseyRequest.class); + when(buildRequest( + eq(storageMock), + eq(ClientFlatQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI}), + any(DefaultErrorHandler.class))).thenReturn(flatRequestMock); + doReturn(configurationMock).when(storageMock).getConfiguration(); + doReturn(MimeType.XML).when(configurationMock).getAcceptMimeType(); + doReturn(flatRequestMock).when(flatRequestMock). + setContentType(EXECUTION_PROVIDED_QUERY_JSON); + doReturn(flatRequestMock).when(flatRequestMock). + setAccept(FLAT_DATA_JSON); + doReturn(flatOperationResultMock).when(flatRequestMock).post(any(ClientMultiLevelQueryExecution.class)); + + QueryExecutionAdapter adapter = new QueryExecutionAdapter(storageMock, + EXECUTION_PROVIDED_QUERY_JSON, + ClientFlatQueryResultData.class, + FLAT_DATA_JSON); + + // When / + OperationResult retrieved = adapter.asJson().execute(new ClientProvidedQueryExecution()); + + // Then / + assertNotNull(retrieved); + assertSame(retrieved, flatOperationResultMock); + verify(flatRequestMock). + setContentType(EXECUTION_PROVIDED_QUERY_JSON); + verify(flatRequestMock). + setAccept(FLAT_DATA_JSON); + verify(flatRequestMock).post(any(ClientMultiLevelQueryExecution.class)); + + verifyStatic(times(1)); + buildRequest( + eq(storageMock), + eq(ClientFlatQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI}), + any(DefaultErrorHandler.class)); + + } + + @Test + public void should_return_proper_operation_result_when_get_fragment_provided_flat_query() { + // Given + mockStatic(JerseyRequest.class); + when(buildRequest( + eq(storageMock), + eq(ClientQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI, SOME_UUID, DATA}), + any(DefaultErrorHandler.class))).thenReturn(clientQueryRequestMock); + doReturn(clientQueryRequestMock).when(clientQueryRequestMock). + setContentType(EXECUTION_PROVIDED_QUERY_JSON); + doReturn(clientQueryRequestMock).when(clientQueryRequestMock). + setAccept(FLAT_DATA_JSON); + doReturn(clientQueryOperationResultMock).when(clientQueryRequestMock).get(); + + QueryExecutionAdapter adapter = new QueryExecutionAdapter(storageMock, + EXECUTION_PROVIDED_QUERY_JSON, + ClientQueryResultData.class, + FLAT_DATA_JSON); + + // When / + OperationResult retrieved = adapter.retrieveData(SOME_UUID); + + // Then / + assertNotNull(retrieved); + assertSame(retrieved, clientQueryOperationResultMock); + verify(clientQueryRequestMock). + setAccept(FLAT_DATA_JSON); + verify(clientQueryRequestMock).get(); + verifyStatic(times(1)); + buildRequest( + eq(storageMock), + eq(ClientQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI, SOME_UUID, DATA}), + any(DefaultErrorHandler.class)); + + } + + @Test + public void should_return_proper_operation_result_when_get_fragment_provided_flat_query_with_params() { + // Given + QueryExecutionAdapter adapter = spy(new QueryExecutionAdapter(storageMock, + EXECUTION_PROVIDED_QUERY_JSON, + ClientFlatQueryResultData.class, + FLAT_DATA_JSON)); + mockStatic(JerseyRequest.class); + when(buildRequest( + eq(storageMock), + eq(ClientFlatQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI, SOME_UUID, DATA}), + any(DefaultErrorHandler.class))).thenReturn(flatRequestMock); + doReturn(adapter).when(adapter).offset(anyInt()); + doReturn(adapter).when(adapter).pageSize(anyInt()); + doReturn(flatRequestMock).when(flatRequestMock). + setContentType(EXECUTION_PROVIDED_QUERY_JSON); + doReturn(flatRequestMock).when(flatRequestMock). + setAccept(FLAT_DATA_JSON); + doReturn(flatOperationResultMock).when(flatRequestMock).get(); + + // When / + OperationResult retrieved = adapter.offset(0).pageSize(100).retrieveData(SOME_UUID); + + // Then / + assertNotNull(retrieved); + assertSame(retrieved, flatOperationResultMock); + verify(adapter).offset(anyInt()); + verify(adapter).pageSize(anyInt()); + verify(flatRequestMock). + setAccept(FLAT_DATA_JSON); + verify(flatRequestMock).get(); + + verifyStatic(times(1)); + buildRequest( + eq(storageMock), + eq(ClientFlatQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI, SOME_UUID, DATA}), + any(DefaultErrorHandler.class)); + } + + @Test + public void should_return_proper_operation_result_and_set_internal_state_when_get_fragment_provided_flat_query_with_params() { + // Given + QueryExecutionAdapter adapter = new QueryExecutionAdapter(storageMock, + EXECUTION_PROVIDED_QUERY_JSON, + ClientFlatQueryResultData.class, + FLAT_DATA_JSON); + mockStatic(JerseyRequest.class); + when(buildRequest( + eq(storageMock), + eq(ClientFlatQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI, SOME_UUID, DATA}), + any(DefaultErrorHandler.class))).thenReturn(flatRequestMock); + doReturn(flatRequestMock).when(flatRequestMock). + setContentType(EXECUTION_PROVIDED_QUERY_JSON); + doReturn(flatRequestMock).when(flatRequestMock). + setAccept(FLAT_DATA_JSON); + doReturn(flatOperationResultMock).when(flatRequestMock).get(); + + // When / + OperationResult retrieved = adapter.offset(0).pageSize(100).retrieveData(SOME_UUID); + + // Then / + assertNotNull(retrieved); + assertSame(retrieved, flatOperationResultMock); +// verify(adapter).offset(anyInt()); +// verify(adapter).pageSize(anyInt()); + assertEquals(2, ((MultivaluedHashMap) Whitebox.getInternalState(adapter, "params")).size()); + verify(flatRequestMock, never()). + setContentType(EXECUTION_PROVIDED_QUERY_JSON); + verify(flatRequestMock). + setAccept(FLAT_DATA_JSON); + verify(flatRequestMock).get(); + + verifyStatic(times(1)); + buildRequest( + eq(storageMock), + eq(ClientFlatQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI, SOME_UUID, DATA}), + any(DefaultErrorHandler.class)); + } + + /** + * @deprecated + */ + @Test + public void should_return_proper_operation_result_when_delete_query_execution() { + // Given + QueryExecutionAdapter adapter = spy(new QueryExecutionAdapter(storageMock, + EXECUTION_PROVIDED_QUERY_JSON, + ClientFlatQueryResultData.class, + FLAT_DATA_JSON)); + mockStatic(JerseyRequest.class); + when(buildRequest( + eq(storageMock), + eq(ClientFlatQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI, SOME_UUID}), + any(DefaultErrorHandler.class))).thenReturn(flatRequestMock); + doReturn(flatOperationResultMock).when(flatRequestMock).delete(); + + // When / + OperationResult retrieved = adapter.deleteExecution(SOME_UUID); + + // Then / + assertNotNull(retrieved); + assertSame(retrieved, flatOperationResultMock); + verify(flatRequestMock).delete(); + verifyStatic(times(1)); + buildRequest( + eq(storageMock), + eq(ClientFlatQueryResultData.class), + eq(new String[]{QUERY_EXECUTIONS_URI, SOME_UUID}), + any(DefaultErrorHandler.class)); + } + + @Test + public void should_return_proper_operation_result_when_delete_execution() { + // Given + QueryExecutionAdapter adapter = spy(new QueryExecutionAdapter(storageMock, + SOME_UUID)); + mockStatic(JerseyRequest.class); + when(buildRequest( + eq(storageMock), + eq(Object.class), + eq(new String[]{QUERY_EXECUTIONS_URI, SOME_UUID}), + any(DefaultErrorHandler.class))).thenReturn(requestMock); + doReturn(operationResultMock).when(requestMock).delete(); + + // When / + OperationResult retrieved = adapter.delete(); + + // Then / + assertNotNull(retrieved); + assertSame(retrieved, operationResultMock); + verify(requestMock).delete(); + verifyStatic(times(1)); + buildRequest( + eq(storageMock), + eq(Object.class), + eq(new String[]{QUERY_EXECUTIONS_URI, SOME_UUID}), + any(DefaultErrorHandler.class)); + } + + @Test + public void should_return_proper_operation_result_when_get_execution() { + // Given + QueryExecutionAdapter adapter = spy(new QueryExecutionAdapter(storageMock, + SOME_UUID)); + mockStatic(JerseyRequest.class); + when(buildRequest( + eq(storageMock), + eq(AbstractClientExecution.class), + eq(new String[]{QUERY_EXECUTIONS_URI, SOME_UUID}), + any(DefaultErrorHandler.class))).thenReturn(requestMock); + + ClientMultiLevelQueryExecution clientMultiLevelQueryExecution = mock(ClientMultiLevelQueryExecution.class); + doReturn(clientMultiLevelQueryExecution).when(operationResultMock).getEntity(); + + doReturn(operationResultMock).when(requestMock).get(); + + // When / + OperationResult retrieved = adapter.get(); + + // Then / + assertSame(retrieved.getEntity(), clientMultiLevelQueryExecution); + assertSame(retrieved, operationResultMock); + verify(requestMock).get(); + verifyStatic(times(1)); + buildRequest( + eq(storageMock), + eq(AbstractClientExecution.class), + eq(new String[]{QUERY_EXECUTIONS_URI, SOME_UUID}), + any(DefaultErrorHandler.class)); + } + + @Test + public void should_return_proper_operation_result_when_get_all_executions() { + // Given + QueryExecutionAdapter adapter = spy(new QueryExecutionAdapter(storageMock)); + mockStatic(JerseyRequest.class); + when(buildRequest( + eq(storageMock), + eq(ClientExecutionListWrapper.class), + eq(new String[]{QUERY_EXECUTIONS_URI}), + any(DefaultErrorHandler.class))).thenReturn(requestMock); + doReturn(operationResultMock).when(requestMock).get(); + + // When / + OperationResult retrieved = adapter.getExecutions(); + + // Then / + assertNotNull(retrieved); + assertSame(retrieved, operationResultMock); + verify(requestMock).get(); + verifyStatic(times(1)); + buildRequest( + eq(storageMock), + eq(ClientExecutionListWrapper.class), + eq(new String[]{QUERY_EXECUTIONS_URI}), + any(DefaultErrorHandler.class)); + } + + @Test + public void should_return_proper_operation_result_when_get_status_of_execution() { + // Given + QueryExecutionAdapter adapter = spy(new QueryExecutionAdapter(storageMock)); + mockStatic(JerseyRequest.class); + when(buildRequest( + eq(storageMock), + eq(ExecutionStatusObject.class), + eq(new String[]{QUERY_EXECUTIONS_URI, "status"}), + any(DefaultErrorHandler.class))).thenReturn(requestMock); + doReturn(operationResultMock).when(requestMock).get(); + + // When / + OperationResult retrieved = adapter.status(); + + // Then / + assertSame(retrieved, operationResultMock); + verify(requestMock).get(); + verifyStatic(times(1)); + buildRequest( + eq(storageMock), + eq(ExecutionStatusObject.class), + eq(new String[]{QUERY_EXECUTIONS_URI, "status"}), + any(DefaultErrorHandler.class)); + } + +} \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/adhoc/queryexecution/QueryExecutionServiceTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/adhoc/queryexecution/QueryExecutionServiceTest.java new file mode 100755 index 00000000..d5b93db2 --- /dev/null +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/adhoc/queryexecution/QueryExecutionServiceTest.java @@ -0,0 +1,378 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.adhoc.queryexecution; + +import com.jaspersoft.jasperserver.dto.executions.ClientFlatQueryResultData; +import com.jaspersoft.jasperserver.dto.executions.ClientMultiAxisQueryResultData; +import com.jaspersoft.jasperserver.dto.executions.ClientMultiLevelQueryResultData; +import com.jaspersoft.jasperserver.dto.executions.ClientQueryResultData; +import com.jaspersoft.jasperserver.dto.executions.ClientExecutionListWrapper; +import com.jaspersoft.jasperserver.jaxrs.client.core.RestClientConfiguration; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.MimeType; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.internal.util.reflection.Whitebox; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.testng.PowerMockTestCase; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import static com.jaspersoft.jasperserver.dto.executions.QueryExecutionsMediaType.EXECUTION_MULTI_AXIS_QUERY_JSON; +import static com.jaspersoft.jasperserver.dto.executions.QueryExecutionsMediaType.EXECUTION_MULTI_AXIS_QUERY_XML; +import static com.jaspersoft.jasperserver.dto.executions.QueryExecutionsMediaType.EXECUTION_MULTI_LEVEL_QUERY_JSON; +import static com.jaspersoft.jasperserver.dto.executions.QueryExecutionsMediaType.EXECUTION_MULTI_LEVEL_QUERY_XML; +import static com.jaspersoft.jasperserver.dto.executions.QueryExecutionsMediaType.EXECUTION_PROVIDED_QUERY_JSON; +import static com.jaspersoft.jasperserver.dto.executions.QueryExecutionsMediaType.EXECUTION_PROVIDED_QUERY_XML; +import static com.jaspersoft.jasperserver.dto.executions.QueryResultDataMediaType.FLAT_DATA_JSON; +import static com.jaspersoft.jasperserver.dto.executions.QueryResultDataMediaType.FLAT_DATA_XML; +import static com.jaspersoft.jasperserver.dto.executions.QueryResultDataMediaType.MULTI_AXIS_DATA_JSON; +import static com.jaspersoft.jasperserver.dto.executions.QueryResultDataMediaType.MULTI_AXIS_DATA_XML; +import static com.jaspersoft.jasperserver.dto.executions.QueryResultDataMediaType.MULTI_LEVEL_DATA_JSON; +import static com.jaspersoft.jasperserver.dto.executions.QueryResultDataMediaType.MULTI_LEVEL_DATA_XML; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.MockitoAnnotations.initMocks; +import static org.powermock.api.mockito.PowerMockito.whenNew; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertSame; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +@PrepareForTest({QueryExecutionAdapter.class, QueryExecutionService.class}) +public class QueryExecutionServiceTest extends PowerMockTestCase { + @Mock + private SessionStorage sessionStorageMock; + @Mock + private QueryExecutionAdapter executionAdapterMock; + @Mock + private RestClientConfiguration configurationMock; + + + @BeforeMethod + public void before() { + initMocks(this); + } + + @AfterMethod + public void after() { + reset(sessionStorageMock, executionAdapterMock, configurationMock); + } + + + @Test + public void should_pass_session_storage_to_parent_adapter() { + // When + QueryExecutionService executionService = new QueryExecutionService(sessionStorageMock); + + // Then + assertSame(Whitebox.getInternalState(executionService, "sessionStorage"), sessionStorageMock); + } + + @Test + public void should_return_proper_adapter_for_flat_query() throws Exception { + // Given + QueryExecutionService executionService = new QueryExecutionService(sessionStorageMock); + doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); + doReturn(MimeType.JSON).when(configurationMock).getContentMimeType(); + doReturn(MimeType.JSON).when(configurationMock).getAcceptMimeType(); + whenNew(QueryExecutionAdapter.class).withArguments(sessionStorageMock, + EXECUTION_MULTI_LEVEL_QUERY_JSON, + ClientFlatQueryResultData.class, + FLAT_DATA_JSON).thenReturn(executionAdapterMock); + + // When + QueryExecutionAdapter adapter = executionService.flatQuery(); + + // Then + assertEquals(adapter, executionAdapterMock); + verify(sessionStorageMock, times(2)).getConfiguration(); + verify(configurationMock).getContentMimeType(); + verify(configurationMock).getAcceptMimeType(); + } + + @Test + public void should_return_proper_adapter_for_multi_axis_query() throws Exception { + // Given + QueryExecutionService executionService = new QueryExecutionService(sessionStorageMock); + doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); + doReturn(MimeType.JSON).when(configurationMock).getContentMimeType(); + doReturn(MimeType.JSON).when(configurationMock).getAcceptMimeType(); + whenNew(QueryExecutionAdapter.class).withArguments(sessionStorageMock, + EXECUTION_MULTI_AXIS_QUERY_JSON, + ClientMultiAxisQueryResultData.class, + MULTI_AXIS_DATA_JSON).thenReturn(executionAdapterMock); + + // When + QueryExecutionAdapter adapter = executionService.multiAxisQuery(); + + // Then + assertEquals(adapter, executionAdapterMock); + verify(sessionStorageMock, times(2)).getConfiguration(); + verify(configurationMock).getContentMimeType(); + verify(configurationMock).getAcceptMimeType(); + } + + @Test + public void should_return_proper_adapter_for_multi_level_query() throws Exception { + // Given + QueryExecutionService executionService = new QueryExecutionService(sessionStorageMock); + doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); + doReturn(MimeType.JSON).when(configurationMock).getContentMimeType(); + doReturn(MimeType.JSON).when(configurationMock).getAcceptMimeType(); + whenNew(QueryExecutionAdapter.class).withArguments(sessionStorageMock, + EXECUTION_MULTI_LEVEL_QUERY_JSON, + ClientMultiLevelQueryResultData.class, + MULTI_LEVEL_DATA_JSON).thenReturn(executionAdapterMock); + + // When + QueryExecutionAdapter adapter = executionService.multiLevelQuery(); + + // Then + assertEquals(adapter, executionAdapterMock); + verify(sessionStorageMock, times(2)).getConfiguration(); + verify(configurationMock).getContentMimeType(); + verify(configurationMock).getAcceptMimeType(); + } + + @Test + public void should_return_proper_adapter_for_provided_flat_query() throws Exception { + // Given + QueryExecutionService executionService = new QueryExecutionService(sessionStorageMock); + doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); + doReturn(MimeType.JSON).when(configurationMock).getContentMimeType(); + doReturn(MimeType.JSON).when(configurationMock).getAcceptMimeType(); + whenNew(QueryExecutionAdapter.class).withArguments(sessionStorageMock, + EXECUTION_PROVIDED_QUERY_JSON, + ClientQueryResultData.class, + FLAT_DATA_JSON, + MULTI_LEVEL_DATA_JSON, + MULTI_AXIS_DATA_JSON).thenReturn(executionAdapterMock); + + // When + QueryExecutionAdapter adapter = executionService.providedQuery(); + + // Then + assertEquals(adapter, executionAdapterMock); + verify(sessionStorageMock, times(2)).getConfiguration(); + verify(configurationMock).getContentMimeType(); + verify(configurationMock).getAcceptMimeType(); + } + + @Test + public void should_return_proper_adapter_for_provided_multi_level_query() throws Exception { + // Given + QueryExecutionService executionService = new QueryExecutionService(sessionStorageMock); + doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); + doReturn(MimeType.JSON).when(configurationMock).getContentMimeType(); + doReturn(MimeType.JSON).when(configurationMock).getAcceptMimeType(); + whenNew(QueryExecutionAdapter.class).withArguments(sessionStorageMock, + EXECUTION_PROVIDED_QUERY_JSON, + ClientQueryResultData.class, + FLAT_DATA_JSON, + MULTI_LEVEL_DATA_JSON, + MULTI_AXIS_DATA_JSON).thenReturn(executionAdapterMock); + + // When + QueryExecutionAdapter adapter = executionService.providedQuery(); + + // Then + assertEquals(adapter, executionAdapterMock); + verify(sessionStorageMock, times(2)).getConfiguration(); + verify(configurationMock).getContentMimeType(); + verify(configurationMock).getAcceptMimeType(); + } + + + @Test + public void should_return_proper_adapter_for_provided_multi_axis_query() throws Exception { + // Given + QueryExecutionService executionService = new QueryExecutionService(sessionStorageMock); + doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); + doReturn(MimeType.JSON).when(configurationMock).getContentMimeType(); + doReturn(MimeType.JSON).when(configurationMock).getAcceptMimeType(); + whenNew(QueryExecutionAdapter.class).withArguments(sessionStorageMock, + EXECUTION_PROVIDED_QUERY_JSON, + ClientQueryResultData.class, + FLAT_DATA_JSON, + MULTI_LEVEL_DATA_JSON, + MULTI_AXIS_DATA_JSON).thenReturn(executionAdapterMock); + + // When + QueryExecutionAdapter adapter = executionService.providedQuery(); + + // Then + assertEquals(adapter, executionAdapterMock); + verify(sessionStorageMock, times(2)).getConfiguration(); + verify(configurationMock).getContentMimeType(); + verify(configurationMock).getAcceptMimeType(); + } + + @Test + public void should_return_proper_adapter_for_multi_axis_query_for_xml() throws Exception { + // Given + QueryExecutionService executionService = new QueryExecutionService(sessionStorageMock); + doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); + doReturn(MimeType.XML).when(configurationMock).getContentMimeType(); + doReturn(MimeType.XML).when(configurationMock).getAcceptMimeType(); + whenNew(QueryExecutionAdapter.class).withArguments(sessionStorageMock, + EXECUTION_MULTI_AXIS_QUERY_XML, + ClientMultiAxisQueryResultData.class, + MULTI_AXIS_DATA_XML).thenReturn(executionAdapterMock); + + // When + QueryExecutionAdapter adapter = executionService.multiAxisQuery(); + + // Then + assertEquals(adapter, executionAdapterMock); + verify(sessionStorageMock, times(2)).getConfiguration(); + verify(configurationMock).getContentMimeType(); + verify(configurationMock).getAcceptMimeType(); + } + + @Test + public void should_return_proper_adapter_for_multi_level_query_for_xml() throws Exception { + // Given + QueryExecutionService executionService = new QueryExecutionService(sessionStorageMock); + doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); + doReturn(MimeType.XML).when(configurationMock).getContentMimeType(); + doReturn(MimeType.XML).when(configurationMock).getAcceptMimeType(); + whenNew(QueryExecutionAdapter.class).withArguments(sessionStorageMock, + EXECUTION_MULTI_LEVEL_QUERY_XML, + ClientMultiLevelQueryResultData.class, + MULTI_LEVEL_DATA_XML).thenReturn(executionAdapterMock); + + // When + QueryExecutionAdapter adapter = executionService.multiLevelQuery(); + + // Then + assertEquals(adapter, executionAdapterMock); + verify(sessionStorageMock, times(2)).getConfiguration(); + verify(configurationMock).getContentMimeType(); + verify(configurationMock).getAcceptMimeType(); + } + + @Test + public void should_return_proper_adapter_for_provided_flat_query_for_xml() throws Exception { + // Given + QueryExecutionService executionService = new QueryExecutionService(sessionStorageMock); + doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); + doReturn(MimeType.XML).when(configurationMock).getContentMimeType(); + doReturn(MimeType.XML).when(configurationMock).getAcceptMimeType(); + whenNew(QueryExecutionAdapter.class).withArguments(sessionStorageMock, + EXECUTION_PROVIDED_QUERY_XML, + ClientQueryResultData.class, + FLAT_DATA_XML, + MULTI_LEVEL_DATA_XML, + MULTI_AXIS_DATA_XML).thenReturn(executionAdapterMock); + + // When + QueryExecutionAdapter adapter = executionService.providedQuery(); + + // Then + assertEquals(adapter, executionAdapterMock); + verify(sessionStorageMock, times(2)).getConfiguration(); + verify(configurationMock).getContentMimeType(); + verify(configurationMock).getAcceptMimeType(); + } + + @Test + public void should_return_proper_adapter_for_provided_multi_level_query_for_xml() throws Exception { + // Given + QueryExecutionService executionService = new QueryExecutionService(sessionStorageMock); + doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); + doReturn(MimeType.XML).when(configurationMock).getContentMimeType(); + doReturn(MimeType.XML).when(configurationMock).getAcceptMimeType(); + whenNew(QueryExecutionAdapter.class).withArguments(sessionStorageMock, + EXECUTION_PROVIDED_QUERY_XML, + ClientQueryResultData.class, + FLAT_DATA_XML, + MULTI_LEVEL_DATA_XML, + MULTI_AXIS_DATA_XML).thenReturn(executionAdapterMock); + + // When + QueryExecutionAdapter adapter = executionService.providedQuery(); + + // Then + assertEquals(adapter, executionAdapterMock); + verify(sessionStorageMock, times(2)).getConfiguration(); + verify(configurationMock).getContentMimeType(); + verify(configurationMock).getAcceptMimeType(); + } + + + @Test + public void should_return_proper_adapter_for_provided_multi_axis_query_for_xml() throws Exception { + // Given + QueryExecutionService executionService = new QueryExecutionService(sessionStorageMock); + doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); + doReturn(MimeType.XML).when(configurationMock).getContentMimeType(); + doReturn(MimeType.XML).when(configurationMock).getAcceptMimeType(); + whenNew(QueryExecutionAdapter.class).withArguments(sessionStorageMock, + EXECUTION_PROVIDED_QUERY_XML, + ClientQueryResultData.class, + FLAT_DATA_XML, + MULTI_LEVEL_DATA_XML, + MULTI_AXIS_DATA_XML).thenReturn(executionAdapterMock); + + // When + QueryExecutionAdapter adapter = executionService.providedQuery(); + + // Then + assertEquals(adapter, executionAdapterMock); + verify(sessionStorageMock, times(2)).getConfiguration(); + verify(configurationMock).getContentMimeType(); + verify(configurationMock).getAcceptMimeType(); + } + + @Test + public void should_return_proper_adapter_for_execution_by_UUID_builder() throws Exception { + // Given + QueryExecutionService executionService = new QueryExecutionService(sessionStorageMock); + PowerMockito.doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); + PowerMockito.doReturn(MimeType.JSON).when(configurationMock).getAcceptMimeType(); + PowerMockito.whenNew(QueryExecutionAdapter.class).withAnyArguments().thenReturn(executionAdapterMock); + + // When + QueryExecutionAdapter adapter = executionService.execution("testUuid"); + + // Then + assertEquals(adapter, executionAdapterMock); + PowerMockito.verifyNew(QueryExecutionAdapter.class, times(1)).withArguments(sessionStorageMock, "testUuid"); + } + + @Test + public void should_return_query_executions_for_get_builder() throws Exception { + // Given + OperationResult operationResult = Mockito.mock(OperationResult.class); + QueryExecutionService executionService = new QueryExecutionService(sessionStorageMock); + PowerMockito.doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); + PowerMockito.whenNew(QueryExecutionAdapter.class).withAnyArguments().thenReturn(executionAdapterMock); + doReturn(operationResult).when(executionAdapterMock).getExecutions(); + + // When + OperationResult adapter = executionService.get(); + + // Then + assertEquals(adapter, operationResult); + PowerMockito.verifyNew(QueryExecutionAdapter.class, times(1)).withArguments(sessionStorageMock); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void should_throw_exception_in_parent_adapter() { + // When + new QueryExecutionService(null); + //Then + // exception should be thrown + } + +} \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/attributes/BatchAttributeAdapterTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/attributes/BatchAttributeAdapterTest.java index 8b583e85..396ca0be 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/attributes/BatchAttributeAdapterTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/attributes/BatchAttributeAdapterTest.java @@ -12,11 +12,6 @@ import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.MandatoryParameterNotFoundException; import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.testng.PowerMockTestCase; import org.powermock.reflect.Whitebox; @@ -25,6 +20,12 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + import static com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest.buildRequest; import static java.util.Arrays.asList; import static org.mockito.Matchers.any; @@ -380,7 +381,7 @@ public void should_search_server_attributes_with_proper_user_in_tenant_holder_vi verify(jerseyRequestMock, times(1)).addParams(map); verify(jerseyRequestMock, times(1)).get(); verify(jerseyRequestMock, times(1)).addParam("_embedded", "permission"); - verify(jerseyRequestMock, times(1)).setAccept("application/attributes.collection+json"); + verify(jerseyRequestMock, times(1)).setAccept("application/attributes.collection.hal+json"); verifyNoMoreInteractions(jerseyRequestMock); } @@ -439,7 +440,7 @@ public void should_search_server_attributes_with_parameters() { verify(jerseyRequestMock, times(1)).addParams(map); verify(jerseyRequestMock, times(1)).get(); verify(jerseyRequestMock, times(1)).addParam("_embedded", "permission"); - verify(jerseyRequestMock, times(1)).setAccept("application/attributes.collection+json"); + verify(jerseyRequestMock, times(1)).setAccept("application/attributes.collection.hal+json"); verifyNoMoreInteractions(jerseyRequestMock); } @@ -494,7 +495,7 @@ public void should_search_server_attributes_with_proper_root_holder() { verify(jerseyRequestMock, times(1)).addParams(map); verify(jerseyRequestMock, times(1)).get(); verify(jerseyRequestMock, times(1)).addParam("_embedded", "permission"); - verify(jerseyRequestMock, times(1)).setAccept("application/attributes.collection+json"); + verify(jerseyRequestMock, times(1)).setAccept("application/attributes.collection.hal+json"); verifyNoMoreInteractions(jerseyRequestMock); } @@ -551,7 +552,7 @@ public void should_search_server_attributes_with_proper_tenant_holder() { verify(jerseyRequestMock, times(1)).get(); verify(jerseyRequestMock, times(1)).addParam("_embedded", "permission"); verify(jerseyRequestMock, times(1)).addParam("holder", "tenant:/myOrg"); - verify(jerseyRequestMock, times(1)).setAccept("application/attributes.collection+json"); + verify(jerseyRequestMock, times(1)).setAccept("application/attributes.collection.hal+json"); verifyNoMoreInteractions(jerseyRequestMock); } @Test @@ -608,7 +609,7 @@ public void should_search_server_attributes_with_proper_user_in_tenant_holder() verify(jerseyRequestMock, times(1)).get(); verify(jerseyRequestMock, times(1)).addParam("_embedded", "permission"); verify(jerseyRequestMock, times(1)).addParam("holder", "user:/myOrg/myUser"); - verify(jerseyRequestMock, times(1)).setAccept("application/attributes.collection+json"); + verify(jerseyRequestMock, times(1)).setAccept("application/attributes.collection.hal+json"); verifyNoMoreInteractions(jerseyRequestMock); } @@ -665,7 +666,7 @@ public void should_search_server_attributes_with_proper_user_in_root_holder() { verify(jerseyRequestMock, times(1)).get(); verify(jerseyRequestMock, times(1)).addParam("_embedded", "permission"); verify(jerseyRequestMock, times(1)).addParam("holder", "user:/myUser"); - verify(jerseyRequestMock, times(1)).setAccept("application/attributes.collection+json"); + verify(jerseyRequestMock, times(1)).setAccept("application/attributes.collection.hal+json"); verifyNoMoreInteractions(jerseyRequestMock); } diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/users/UsersServiceTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/users/UsersServiceTest.java index 71b9141f..0e43be20 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/users/UsersServiceTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/authority/users/UsersServiceTest.java @@ -4,6 +4,7 @@ import com.jaspersoft.jasperserver.dto.authority.ClientUser; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.internal.util.reflection.Whitebox; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; @@ -14,12 +15,15 @@ import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.reset; import static org.mockito.MockitoAnnotations.initMocks; +import static org.powermock.api.mockito.PowerMockito.verifyNew; import static org.powermock.api.mockito.PowerMockito.whenNew; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; import static org.testng.Assert.assertSame; -import static org.testng.AssertJUnit.assertNotNull; /** * Unit tests for {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.authority.users.UsersService} @@ -27,12 +31,16 @@ @PrepareForTest({SingleUserRequestAdapter.class, BatchUsersRequestAdapter.class, UsersService.class}) public class UsersServiceTest extends PowerMockTestCase { + private static final String ORGANIZATION_ID = "MyCoolOrg"; @Mock private SessionStorage sessionStorageMock; @Mock private SingleUserRequestAdapter singleUserRequestAdapterMock; + @Mock + private ClientUser clientUserMock; + @Mock private BatchUsersRequestAdapter batchUsersRequestAdapterMock; @@ -45,20 +53,20 @@ public void before() { public void should_set_organization_id() { // When UsersService service = new UsersService(sessionStorageMock); - UsersService retrieved = service.forOrganization("MyCoolOrg"); + UsersService retrieved = service.forOrganization(ORGANIZATION_ID); // Then assertSame(retrieved, service); - assertEquals(Whitebox.getInternalState(service, "organizationId"), "MyCoolOrg"); + assertEquals(Whitebox.getInternalState(service, "organizationId"), ORGANIZATION_ID); } @Test public void should_set_organization_id_as_object() { // When UsersService service = new UsersService(sessionStorageMock); - UsersService retrieved = service.forOrganization(new ClientTenant().setId("MyCoolOrg")); + UsersService retrieved = service.forOrganization(new ClientTenant().setId(ORGANIZATION_ID)); // Then assertSame(retrieved, service); - assertEquals(Whitebox.getInternalState(service, "organizationId"), "MyCoolOrg"); + assertEquals(Whitebox.getInternalState(service, "organizationId"), ORGANIZATION_ID); } @Test(expectedExceptions = IllegalArgumentException.class) @@ -142,6 +150,27 @@ public void should_return_proper_user_adapter_when_invoke_user_method_with_objec assertSame(retrieved, singleUserRequestAdapterMock); } + @Test + public void should_return_proper_user_adapter_with_organization_id_source_obj_not_modified() throws Exception { + // Given + UsersService service = new UsersService(sessionStorageMock); + ClientUser clientUser = new ClientUser().setUsername("Simon"); + whenNew(ClientUser.class).withArguments(clientUser) + .thenReturn(clientUserMock); + whenNew(SingleUserRequestAdapter.class).withArguments(sessionStorageMock, clientUserMock) + .thenReturn(singleUserRequestAdapterMock); + doReturn(clientUserMock).when(clientUserMock).setTenantId(ORGANIZATION_ID); + // When + SingleUserRequestAdapter retrieved = service. + forOrganization(ORGANIZATION_ID). + user(clientUser); + // Then + assertSame(retrieved, singleUserRequestAdapterMock); + assertNull(clientUser.getTenantId()); + verifyNew(ClientUser.class).withArguments(clientUser); + Mockito.verify(clientUserMock).setTenantId(ORGANIZATION_ID); + } + @Test public void should_return_BatchUsersRequestAdapter() throws Exception { // Given @@ -162,10 +191,10 @@ public void should_return_BatchUsersRequestAdapter() throws Exception { @Test public void should_set_org_id (){ UsersService service = new UsersService(sessionStorageMock); - UsersService retrieved = service.organization("MyCoolOrg"); + UsersService retrieved = service.organization(ORGANIZATION_ID); assertSame(retrieved, service); - assertEquals(Whitebox.getInternalState(service, "organizationId"), "MyCoolOrg"); + assertEquals(Whitebox.getInternalState(service, "organizationId"), ORGANIZATION_ID); } /** @@ -215,6 +244,6 @@ public void should_return_proper_user_adapter_() throws Exception { @AfterMethod public void after() { - reset(sessionStorageMock, singleUserRequestAdapterMock, batchUsersRequestAdapterMock); + reset(sessionStorageMock, singleUserRequestAdapterMock, clientUserMock, batchUsersRequestAdapterMock); } } \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/connections/ConnectionMediaTypeTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/connections/ConnectionMediaTypeTest.java deleted file mode 100644 index 19d0b605..00000000 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/connections/ConnectionMediaTypeTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright © 2014-2019. TIBCO Software Inc. All Rights Reserved. Confidential & Proprietary. - */ - -package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.connections; - -import com.jaspersoft.jasperserver.jaxrs.client.core.enums.ConnectionMediaType; -import org.testng.annotations.Test; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; - -/** - * Unit test for {@link com.jaspersoft.jasperserver.jaxrs.client.core.enums.ConnectionMediaType} - */ -public class ConnectionMediaTypeTest { - - @Test - public void should_return_proper_value() { - assertEquals(ConnectionMediaType.FTP_JSON, "application/connections.ftp+json"); - assertEquals(ConnectionMediaType.FTP_XML, "application/connections.ftp+xml"); - assertEquals(ConnectionMediaType.LOCAL_FILE_SYSTEM_JSON, "application/connections.lfs+json"); - assertEquals(ConnectionMediaType.LOCAL_FILE_SYSTEM_XML, "application/connections.lfs+xml"); - assertEquals(ConnectionMediaType.TXT_FILE_JSON, "application/connections.txtFile+json"); - assertEquals(ConnectionMediaType.TXT_FILE_XML, "application/connections.txtFile+xml"); - assertEquals(ConnectionMediaType.XLS_FILE_JSON, "application/connections.xlsFile+json"); - assertEquals(ConnectionMediaType.XLS_FILE_XML, "application/connections.xlsFile+xml"); - } - - @Test - public void constructor_of_enum_should_be_private() { - Constructor[] constructors = ConnectionMediaType.class.getDeclaredConstructors(); - assertFalse(constructors[0].isAccessible()); - } - - @Test - public void magic() throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException { - - Constructor constructor = ConnectionMediaType.class.getDeclaredConstructor(); - constructor.setAccessible(true); - ConnectionMediaType instance = constructor.newInstance(); - - assertNotNull(instance); - } -} \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/connections/ConnectionsServiceTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/connections/ConnectionsServiceTest.java index 12c84c6f..43f89465 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/connections/ConnectionsServiceTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/connections/ConnectionsServiceTest.java @@ -26,20 +26,22 @@ */ @PrepareForTest({ConnectionsService.class}) public class ConnectionsServiceTest extends PowerMockTestCase { - + public static final String SOME_UU_ID = "someUuId"; + public static final String SOME_MIME_TYPE = "someMimeType"; + public static final String METADATA_MIME_TYPE = "someMetadataMimeType"; private SessionStorage sessionStorageMock; - private SingleConnectionsAdapter singleConnectionsAdapterMock; + private SingleConnectionsAdapter singleConnectionAdapterMock; @BeforeMethod public void before() { sessionStorageMock = mock(SessionStorage.class); - singleConnectionsAdapterMock = mock(SingleConnectionsAdapter.class); + singleConnectionAdapterMock = mock(SingleConnectionsAdapter.class); } @AfterMethod public void after() { - reset(sessionStorageMock, singleConnectionsAdapterMock); + reset(sessionStorageMock, singleConnectionAdapterMock); } @Test @@ -63,18 +65,18 @@ public void should_return_proper_SingleConnectionAdapter_instance_by_uuid() thro // Given whenNew(SingleConnectionsAdapter.class) - .withArguments(sessionStorageMock, Object.class, null, Object.class, null, "someUuId") - .thenReturn(singleConnectionsAdapterMock); + .withArguments(sessionStorageMock, Object.class, SOME_MIME_TYPE, SOME_UU_ID) + .thenReturn(singleConnectionAdapterMock); ConnectionsService connectionsService = new ConnectionsService(sessionStorageMock); // When - SingleConnectionsAdapter retrieved = connectionsService.connection("someUuId"); + SingleConnectionsAdapter retrieved = connectionsService.connection(Object.class, SOME_MIME_TYPE, SOME_UU_ID); // Then - assertSame(singleConnectionsAdapterMock, retrieved); + assertSame(singleConnectionAdapterMock, retrieved); verifyNew(SingleConnectionsAdapter.class, times(1)) - .withArguments(sessionStorageMock, Object.class, null, Object.class, null, "someUuId"); + .withArguments(sessionStorageMock, Object.class, SOME_MIME_TYPE, SOME_UU_ID); } @Test @@ -82,18 +84,18 @@ public void should_return_proper_SingleConnectionAdapter_instance_by_class_mimeT // Given whenNew(SingleConnectionsAdapter.class) - .withArguments(sessionStorageMock, ClientCustomDataSource.class, "someMimeType", Object.class, null, "someUuId") - .thenReturn(singleConnectionsAdapterMock); + .withArguments(sessionStorageMock, ClientCustomDataSource.class, SOME_MIME_TYPE, SOME_UU_ID) + .thenReturn(singleConnectionAdapterMock); ConnectionsService connectionsService = new ConnectionsService(sessionStorageMock); // When - SingleConnectionsAdapter retrieved = connectionsService.connection(ClientCustomDataSource.class, "someMimeType", "someUuId"); + SingleConnectionsAdapter retrieved = connectionsService.connection(ClientCustomDataSource.class, SOME_MIME_TYPE, SOME_UU_ID); // Then - assertSame(singleConnectionsAdapterMock, retrieved); + assertSame(singleConnectionAdapterMock, retrieved); verifyNew(SingleConnectionsAdapter.class, times(1)) - .withArguments(sessionStorageMock, ClientCustomDataSource.class, "someMimeType", Object.class, null, "someUuId"); + .withArguments(sessionStorageMock, ClientCustomDataSource.class, SOME_MIME_TYPE, SOME_UU_ID); } @Test @@ -101,28 +103,18 @@ public void should_return_proper_SingleConnectionAdapter_instance_by_connection_ // Given whenNew(SingleConnectionsAdapter.class) - .withArguments(sessionStorageMock, - ClientCustomDataSource.class, - "someConnectionMimeType", - TableMetadata.class, - "someMetadataMimeType", "someUuId") - .thenReturn(singleConnectionsAdapterMock); + .withArguments(sessionStorageMock, SOME_UU_ID, TableMetadata.class, METADATA_MIME_TYPE) + .thenReturn(singleConnectionAdapterMock); ConnectionsService connectionsService = new ConnectionsService(sessionStorageMock); // When SingleConnectionsAdapter retrieved = connectionsService. - connection(ClientCustomDataSource.class, "someConnectionMimeType", TableMetadata.class, - "someMetadataMimeType", "someUuId"); + connection(SOME_UU_ID, TableMetadata.class, METADATA_MIME_TYPE); // Then - assertSame(singleConnectionsAdapterMock, retrieved); + assertSame(singleConnectionAdapterMock, retrieved); verifyNew(SingleConnectionsAdapter.class, times(1)) - .withArguments(sessionStorageMock, - ClientCustomDataSource.class, - "someConnectionMimeType", - TableMetadata.class, - "someMetadataMimeType", "someUuId"); + .withArguments(sessionStorageMock, SOME_UU_ID, TableMetadata.class, METADATA_MIME_TYPE); } - } \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/connections/ContextMediaTypesTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/connections/ContextMediaTypesTest.java new file mode 100644 index 00000000..cb55e79b --- /dev/null +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/connections/ContextMediaTypesTest.java @@ -0,0 +1,53 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.connections; + +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.ContextMediaTypes; +import org.testng.annotations.Test; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; + +/** + * Unit test for {@link com.jaspersoft.jasperserver.jaxrs.client.core.enums.ContextMediaTypes} + */ +public class ContextMediaTypesTest { + + @Test + public void should_return_proper_value() { + assertEquals(ContextMediaTypes.FTP_JSON, "application/connections.ftp+json"); + assertEquals(ContextMediaTypes.FTP_XML, "application/connections.ftp+xml"); + assertEquals(ContextMediaTypes.LOCAL_FILE_SYSTEM_JSON, "application/connections.lfs+json"); + assertEquals(ContextMediaTypes.LOCAL_FILE_SYSTEM_XML, "application/connections.lfs+xml"); + assertEquals(ContextMediaTypes.CUSTOM_DATA_SOURCE_JSON, "application/repository.customDataSource+json"); + assertEquals(ContextMediaTypes.CUSTOM_DATA_SOURCE_XML, "application/repository.customDataSource+xml"); + assertEquals(ContextMediaTypes.JNDI_JDBC_DATA_SOURCE_JSON, "application/repository.jndiJdbcDataSource+json"); + assertEquals(ContextMediaTypes.JNDI_JDBC_DATA_SOURCE_XML, "application/repository.jndiJdbcDataSource+xml"); + assertEquals(ContextMediaTypes.JDBC_DATA_SOURCE_JSON, "application/repository.jdbcDataSource+json"); + assertEquals(ContextMediaTypes.JDBC_DATA_SOURCE_XML, "application/repository.jdbcDataSource+xml"); + assertEquals(ContextMediaTypes.DOMAIN_DATA_SOURCE_JSON, "application/repository.semanticLayerDataSource+json"); + assertEquals(ContextMediaTypes.DOMAIN_DATA_SOURCE_XML, "application/repository.semanticLayerDataSource+xml"); + assertEquals(ContextMediaTypes.TXT_FILE_JSON, "application/connections.txtFile+json"); + assertEquals(ContextMediaTypes.TXT_FILE_XML, "application/connections.txtFile+xml"); + assertEquals(ContextMediaTypes.XLS_FILE_JSON, "application/connections.xlsFile+json"); + assertEquals(ContextMediaTypes.XLS_FILE_XML, "application/connections.xlsFile+xml"); + } + + @Test + public void constructor_of_enum_should_be_private() { + Constructor[] constructors = ContextMediaTypes.class.getDeclaredConstructors(); + assertFalse(constructors[0].isAccessible()); + } + + @Test + public void magic() throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException { + + Constructor constructor = ContextMediaTypes.class.getDeclaredConstructor(); + constructor.setAccessible(true); + ContextMediaTypes instance = constructor.newInstance(); + + assertNotNull(instance); + } +} \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/connections/SingleConnectionsAdapterTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/connections/SingleConnectionsAdapterTest.java index 2e58ed9f..dab5f5a4 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/connections/SingleConnectionsAdapterTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/connections/SingleConnectionsAdapterTest.java @@ -9,7 +9,7 @@ import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; import com.jaspersoft.jasperserver.jaxrs.client.core.RestClientConfiguration; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; -import com.jaspersoft.jasperserver.jaxrs.client.core.enums.ConnectionMediaType; +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.ContextMediaTypes; import com.jaspersoft.jasperserver.jaxrs.client.core.enums.MimeType; import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.MandatoryParameterNotFoundException; import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; @@ -143,11 +143,11 @@ public void should_return_proper_ftp_connection_operationResult_when_create() th doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); doReturn(MimeType.JSON).when(configurationMock).getContentMimeType(); - doReturn(ftpConnectionJerseyRequestMock).when(ftpConnectionJerseyRequestMock).setContentType(ConnectionMediaType.FTP_JSON); + doReturn(ftpConnectionJerseyRequestMock).when(ftpConnectionJerseyRequestMock).setContentType(ContextMediaTypes.FTP_JSON); doReturn(ftpConnectionOperationResultMock).when(ftpConnectionJerseyRequestMock).post(any(FtpConnection.class)); OperationResult connection = connectionsService - .connection(FtpConnection.class, ConnectionMediaType.FTP_TYPE, TEST_UUID) + .connection(FtpConnection.class, ContextMediaTypes.FTP_TYPE, TEST_UUID) .create(new FtpConnection()); //then assertSame(ftpConnectionOperationResultMock, connection); @@ -158,7 +158,7 @@ public void should_return_proper_ftp_connection_operationResult_when_create() th , any(DefaultErrorHandler.class)); verify(sessionStorageMock).getConfiguration(); verify(configurationMock).getContentMimeType(); - verify(ftpConnectionJerseyRequestMock).setContentType(ConnectionMediaType.FTP_JSON); + verify(ftpConnectionJerseyRequestMock).setContentType(ContextMediaTypes.FTP_JSON); verify(ftpConnectionJerseyRequestMock).post(any(FtpConnection.class)); } @@ -173,11 +173,11 @@ public void should_return_proper_ftp_connection_operationResult_when_update() th doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); doReturn(MimeType.JSON).when(configurationMock).getContentMimeType(); - doReturn(ftpConnectionJerseyRequestMock).when(ftpConnectionJerseyRequestMock).setContentType(ConnectionMediaType.FTP_JSON); + doReturn(ftpConnectionJerseyRequestMock).when(ftpConnectionJerseyRequestMock).setContentType(ContextMediaTypes.FTP_JSON); doReturn(ftpConnectionOperationResultMock).when(ftpConnectionJerseyRequestMock).put(any(FtpConnection.class)); OperationResult connection = connectionsService - .connection(FtpConnection.class, ConnectionMediaType.FTP_TYPE, TEST_UUID) + .connection(FtpConnection.class, ContextMediaTypes.FTP_TYPE, TEST_UUID) .update(new FtpConnection()); //then assertSame(ftpConnectionOperationResultMock, connection); @@ -188,7 +188,7 @@ public void should_return_proper_ftp_connection_operationResult_when_update() th , any(DefaultErrorHandler.class)); verify(sessionStorageMock).getConfiguration(); verify(configurationMock).getContentMimeType(); - verify(ftpConnectionJerseyRequestMock).setContentType(ConnectionMediaType.FTP_JSON); + verify(ftpConnectionJerseyRequestMock).setContentType(ContextMediaTypes.FTP_JSON); verify(ftpConnectionJerseyRequestMock).put(any(FtpConnection.class)); } @@ -228,7 +228,7 @@ public void should_return_proper_local_file_system_connection_operationResult_wh doReturn(lfsConnectionOperationResultMock).when(lfsConnectionJerseyRequestMock).get(); OperationResult connection = connectionsService - .connection(LfsConnection.class, ConnectionMediaType.LOCAL_FILE_SYSTEM_TYPE, TEST_UUID) + .connection(LfsConnection.class, ContextMediaTypes.LOCAL_FILE_SYSTEM_TYPE, TEST_UUID) .get(); //then assertSame(lfsConnectionOperationResultMock, connection); @@ -251,11 +251,11 @@ public void should_return_proper_local_file_system_connection_operationResult_wh doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); doReturn(MimeType.JSON).when(configurationMock).getContentMimeType(); - doReturn(lfsConnectionJerseyRequestMock).when(lfsConnectionJerseyRequestMock).setContentType(ConnectionMediaType.LOCAL_FILE_SYSTEM_JSON); + doReturn(lfsConnectionJerseyRequestMock).when(lfsConnectionJerseyRequestMock).setContentType(ContextMediaTypes.LOCAL_FILE_SYSTEM_JSON); doReturn(lfsConnectionOperationResultMock).when(lfsConnectionJerseyRequestMock).post(any(LfsConnection.class)); OperationResult connection = connectionsService - .connection(LfsConnection.class, ConnectionMediaType.LOCAL_FILE_SYSTEM_TYPE, TEST_UUID) + .connection(LfsConnection.class, ContextMediaTypes.LOCAL_FILE_SYSTEM_TYPE, TEST_UUID) .create(new LfsConnection()); //then assertSame(lfsConnectionOperationResultMock, connection); @@ -266,7 +266,7 @@ public void should_return_proper_local_file_system_connection_operationResult_wh , any(DefaultErrorHandler.class)); verify(sessionStorageMock).getConfiguration(); verify(configurationMock).getContentMimeType(); - verify(lfsConnectionJerseyRequestMock).setContentType(ConnectionMediaType.LOCAL_FILE_SYSTEM_JSON); + verify(lfsConnectionJerseyRequestMock).setContentType(ContextMediaTypes.LOCAL_FILE_SYSTEM_JSON); verify(lfsConnectionJerseyRequestMock).post(any(LfsConnection.class)); } @@ -283,7 +283,7 @@ public void should_return_proper_custom_data_source_connection_operationResult_w doReturn(customDataSourceOperationResultMock).when(customDataSourceJerseyRequestMock).get(); OperationResult connection = connectionsService - .connection(ClientCustomDataSource.class, ConnectionMediaType.CUSTOM_DATA_SOURCE_TYPE, TEST_UUID) + .connection(ClientCustomDataSource.class, ContextMediaTypes.CUSTOM_DATA_SOURCE_TYPE, TEST_UUID) .get(); //then assertSame(customDataSourceOperationResultMock, connection); @@ -307,11 +307,11 @@ public void should_return_proper_custom_data_source_connection_operationResult_w doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); doReturn(MimeType.JSON).when(configurationMock).getContentMimeType(); - doReturn(customDataSourceJerseyRequestMock).when(customDataSourceJerseyRequestMock).setContentType(ConnectionMediaType.CUSTOM_DATA_SOURCE_JSON); + doReturn(customDataSourceJerseyRequestMock).when(customDataSourceJerseyRequestMock).setContentType(ContextMediaTypes.CUSTOM_DATA_SOURCE_JSON); doReturn(customDataSourceOperationResultMock).when(customDataSourceJerseyRequestMock).post(any(ClientCustomDataSource.class)); OperationResult connection = connectionsService - .connection(ClientCustomDataSource.class, ConnectionMediaType.CUSTOM_DATA_SOURCE_TYPE, TEST_UUID) + .connection(ClientCustomDataSource.class, ContextMediaTypes.CUSTOM_DATA_SOURCE_TYPE, TEST_UUID) .create(new ClientCustomDataSource()); //then assertSame(customDataSourceOperationResultMock, connection); @@ -322,7 +322,7 @@ public void should_return_proper_custom_data_source_connection_operationResult_w , any(DefaultErrorHandler.class)); verify(sessionStorageMock).getConfiguration(); verify(configurationMock).getContentMimeType(); - verify(customDataSourceJerseyRequestMock).setContentType(ConnectionMediaType.CUSTOM_DATA_SOURCE_JSON); + verify(customDataSourceJerseyRequestMock).setContentType(ContextMediaTypes.CUSTOM_DATA_SOURCE_JSON); verify(customDataSourceJerseyRequestMock).post(any(ClientCustomDataSource.class)); } @@ -339,7 +339,7 @@ public void should_return_proper_jndi_connection_operationResult_when_get() thro doReturn(jndiDataSourceOperationResultMock).when(jndiJdbcDataSourceJerseyRequestMock).get(); OperationResult connection = connectionsService - .connection(ClientJndiJdbcDataSource.class, ConnectionMediaType.JNDI_JDBC_DATA_SOURCE_TYPE, TEST_UUID) + .connection(ClientJndiJdbcDataSource.class, ContextMediaTypes.JNDI_JDBC_DATA_SOURCE_TYPE, TEST_UUID) .get(); //then assertSame(jndiDataSourceOperationResultMock, connection); @@ -362,11 +362,11 @@ public void should_return_proper_jndi_connection_operationResult_when_create() t , any(DefaultErrorHandler.class))).thenReturn(jndiJdbcDataSourceJerseyRequestMock); doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); doReturn(MimeType.JSON).when(configurationMock).getContentMimeType(); - doReturn(jndiJdbcDataSourceJerseyRequestMock).when(jndiJdbcDataSourceJerseyRequestMock).setContentType(ConnectionMediaType.JNDI_JDBC_DATA_SOURCE_JSON); + doReturn(jndiJdbcDataSourceJerseyRequestMock).when(jndiJdbcDataSourceJerseyRequestMock).setContentType(ContextMediaTypes.JNDI_JDBC_DATA_SOURCE_JSON); doReturn(jndiDataSourceOperationResultMock).when(jndiJdbcDataSourceJerseyRequestMock).post(any(ClientJndiJdbcDataSource.class)); OperationResult connection = connectionsService - .connection(ClientJndiJdbcDataSource.class, ConnectionMediaType.JNDI_JDBC_DATA_SOURCE_TYPE, TEST_UUID) + .connection(ClientJndiJdbcDataSource.class, ContextMediaTypes.JNDI_JDBC_DATA_SOURCE_TYPE, TEST_UUID) .create(new ClientJndiJdbcDataSource()); //then assertSame(jndiDataSourceOperationResultMock, connection); @@ -377,7 +377,7 @@ public void should_return_proper_jndi_connection_operationResult_when_create() t , any(DefaultErrorHandler.class)); verify(sessionStorageMock).getConfiguration(); verify(configurationMock).getContentMimeType(); - verify(jndiJdbcDataSourceJerseyRequestMock).setContentType(ConnectionMediaType.JNDI_JDBC_DATA_SOURCE_JSON); + verify(jndiJdbcDataSourceJerseyRequestMock).setContentType(ContextMediaTypes.JNDI_JDBC_DATA_SOURCE_JSON); verify(jndiJdbcDataSourceJerseyRequestMock).post(any(ClientJndiJdbcDataSource.class)); } @@ -394,7 +394,7 @@ public void should_return_proper_jdbc_connection_operationResult_when_get() thro doReturn(jdbcDataSourceOperationResultMock).when(jdbcDataSourceJerseyRequestMock).get(); OperationResult connection = connectionsService - .connection(ClientJdbcDataSource.class, ConnectionMediaType.JDBC_DATA_SOURCE_TYPE, TEST_UUID) + .connection(ClientJdbcDataSource.class, ContextMediaTypes.JDBC_DATA_SOURCE_TYPE, TEST_UUID) .get(); //then assertSame(jdbcDataSourceOperationResultMock, connection); @@ -417,11 +417,11 @@ public void should_return_proper_jdbc_connection_operationResult_when_create() t , any(DefaultErrorHandler.class))).thenReturn(jdbcDataSourceJerseyRequestMock); doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); doReturn(MimeType.JSON).when(configurationMock).getContentMimeType(); - doReturn(jdbcDataSourceJerseyRequestMock).when(jdbcDataSourceJerseyRequestMock).setContentType(ConnectionMediaType.JDBC_DATA_SOURCE_JSON); + doReturn(jdbcDataSourceJerseyRequestMock).when(jdbcDataSourceJerseyRequestMock).setContentType(ContextMediaTypes.JDBC_DATA_SOURCE_JSON); doReturn(jdbcDataSourceOperationResultMock).when(jdbcDataSourceJerseyRequestMock).post(any(ClientJdbcDataSource.class)); OperationResult connection = connectionsService - .connection(ClientJdbcDataSource.class, ConnectionMediaType.JDBC_DATA_SOURCE_TYPE, TEST_UUID) + .connection(ClientJdbcDataSource.class, ContextMediaTypes.JDBC_DATA_SOURCE_TYPE, TEST_UUID) .create(new ClientJdbcDataSource()); //then assertSame(jdbcDataSourceOperationResultMock, connection); @@ -432,7 +432,7 @@ public void should_return_proper_jdbc_connection_operationResult_when_create() t , any(DefaultErrorHandler.class)); verify(sessionStorageMock).getConfiguration(); verify(configurationMock).getContentMimeType(); - verify(jdbcDataSourceJerseyRequestMock).setContentType(ConnectionMediaType.JDBC_DATA_SOURCE_JSON); + verify(jdbcDataSourceJerseyRequestMock).setContentType(ContextMediaTypes.JDBC_DATA_SOURCE_JSON); verify(jdbcDataSourceJerseyRequestMock).post(any(ClientJdbcDataSource.class)); } @@ -446,13 +446,13 @@ public void should_return_proper_operationResult_when_get_metadata() throws Exce , any(DefaultErrorHandler.class))).thenReturn(tableMetadataRequestMock); doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); doReturn(MimeType.JSON).when(configurationMock).getAcceptMimeType(); - doReturn(tableMetadataRequestMock).when(tableMetadataRequestMock).setAccept(ConnectionMediaType.JDBC_DATA_SOURCE_JSON); + doReturn(tableMetadataRequestMock).when(tableMetadataRequestMock).setAccept(ContextMediaTypes.JDBC_DATA_SOURCE_JSON); doReturn(tableMetadataOperationResultMock).when(tableMetadataRequestMock).get(); OperationResult connection = connectionsService - .connection(ClientJdbcDataSource.class, ConnectionMediaType.JDBC_DATA_SOURCE_TYPE, TableMetadata.class, - ConnectionMediaType.JDBC_DATA_SOURCE_METADATA_TYPE, TEST_UUID) + .connection(TEST_UUID, TableMetadata.class, + ContextMediaTypes.JDBC_DATA_SOURCE_METADATA_TYPE) .metadata(); //then assertSame(tableMetadataOperationResultMock, connection); @@ -463,23 +463,23 @@ public void should_return_proper_operationResult_when_get_metadata() throws Exce , any(DefaultErrorHandler.class)); verify(sessionStorageMock).getConfiguration(); verify(configurationMock).getAcceptMimeType(); - verify(tableMetadataRequestMock).setAccept(ConnectionMediaType.JDBC_DATA_SOURCE_METADATA_JSON); + verify(tableMetadataRequestMock).setAccept(ContextMediaTypes.JDBC_DATA_SOURCE_METADATA_JSON); verify(tableMetadataRequestMock).get(); } - @Test(expectedExceptions = IllegalArgumentException.class) - public void should_return_throw_exception_when_create_connection_and_get_metadata_connection_is_invalid() throws Exception { + @Test(expectedExceptions = MandatoryParameterNotFoundException.class) + public void should_throw_exception_when_update_connection_is_null() throws Exception { //when connectionsService - .connection(TableMetadata.class, - ConnectionMediaType.JDBC_DATA_SOURCE_METADATA_TYPE, TEST_UUID) - .createAndGetMetadata(new Object()); + .connection(TEST_UUID) + .update(null); //then // an exception should be thrown + } @Test(expectedExceptions = MandatoryParameterNotFoundException.class) - public void should_throw_exception_when_update_connection_is_null() throws Exception { + public void should_throw_exception_when_create_connection_is_null() throws Exception { //when connectionsService .connection(TEST_UUID) @@ -510,24 +510,4 @@ public void should_throw_exception_when_get_connection_uuid_is_empty() throws Ex // an exception should be thrown } - @Test(expectedExceptions = IllegalArgumentException.class) - public void should_throw_exception_when_update_connection_type_is_invalid() throws Exception { - //when - connectionsService - .connection(TEST_UUID) - .update(new Object()); - //then - // an exception should be thrown - } - - @Test(expectedExceptions = IllegalArgumentException.class) - public void should_throw_exception_when_connection_class_is_invalid() throws Exception { - //when - connectionsService - .connection(TEST_UUID) - .create(new Object()); - //then - // an exception should be thrown - } - } \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/ContextServiceTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/ContextServiceTest.java new file mode 100644 index 00000000..78b7785c --- /dev/null +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/ContextServiceTest.java @@ -0,0 +1,174 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context; + +import com.jaspersoft.jasperserver.dto.connection.metadata.TableMetadata; +import com.jaspersoft.jasperserver.dto.resources.ClientCustomDataSource; +import com.jaspersoft.jasperserver.dto.resources.domain.ClientDomain; +import com.jaspersoft.jasperserver.dto.resources.domain.ResourceGroupElement; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.ContextMediaTypes; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.testng.PowerMockTestCase; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.powermock.api.mockito.PowerMockito.verifyNew; +import static org.powermock.api.mockito.PowerMockito.whenNew; +import static org.testng.Assert.assertSame; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +@PrepareForTest({ContextService.class}) +public class ContextServiceTest extends PowerMockTestCase { + public static final String SOME_UU_ID = "someUuId"; + public static final String SOME_MIME_TYPE = "someMimeType"; + public static final String METADATA_MIME_TYPE = "someMetadataMimeType"; + private SessionStorage sessionStorageMock; + private SingleContextAdapter singleContextAdapterMock; + + @BeforeMethod + public void before() { + sessionStorageMock = mock(SessionStorage.class); + singleContextAdapterMock = mock(SingleContextAdapter.class); + + } + + @AfterMethod + public void after() { + reset(sessionStorageMock, singleContextAdapterMock); + } + + @Test + public void should_pass_session_storage_to_parent_adapter() { + ContextService contextService = new ContextService(sessionStorageMock); + SessionStorage retrieved = contextService.getSessionStorage(); + assertSame(retrieved, sessionStorageMock); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void should_throw_an_exception_when_sessionStorage_is_null() { + // When + new ContextService(null); + // Then + // should be thrown an exception + } + + + @Test + public void should_return_proper_SingleConnectionAdapter_instance_by_uuid() throws Exception { + + // Given + whenNew(SingleContextAdapter.class) + .withArguments(sessionStorageMock, Object.class, SOME_MIME_TYPE, SOME_UU_ID) + .thenReturn(singleContextAdapterMock); + + ContextService contextService = new ContextService(sessionStorageMock); + + // When + SingleContextAdapter retrieved = contextService.context(Object.class, SOME_MIME_TYPE, SOME_UU_ID); + + // Then + assertSame(singleContextAdapterMock, retrieved); + verifyNew(SingleContextAdapter.class, times(1)) + .withArguments(sessionStorageMock, Object.class, SOME_MIME_TYPE, SOME_UU_ID); + } + + @Test + public void should_return_proper_SingleConnectionAdapter_instance_by_class_mimeType_uuid() throws Exception { + + // Given + whenNew(SingleContextAdapter.class) + .withArguments(sessionStorageMock, ClientCustomDataSource.class, SOME_MIME_TYPE, SOME_UU_ID) + .thenReturn(singleContextAdapterMock); + + ContextService contextService = new ContextService(sessionStorageMock); + + // When + SingleContextAdapter retrieved = contextService.context(ClientCustomDataSource.class, SOME_MIME_TYPE, SOME_UU_ID); + + // Then + assertSame(singleContextAdapterMock, retrieved); + verifyNew(SingleContextAdapter.class, times(1)) + .withArguments(sessionStorageMock, ClientCustomDataSource.class, SOME_MIME_TYPE, SOME_UU_ID); + } + + + @Test + public void should_return_proper_SingleConnectionAdapter_instance_by_class_mimeType() throws Exception { + + // Given + whenNew(SingleContextAdapter.class) + .withArguments(sessionStorageMock, ClientCustomDataSource.class, SOME_MIME_TYPE) + .thenReturn(singleContextAdapterMock); + + ContextService contextService = new ContextService(sessionStorageMock); + + // When + SingleContextAdapter retrieved = contextService.context(ClientCustomDataSource.class, SOME_MIME_TYPE); + + // Then + assertSame(singleContextAdapterMock, retrieved); + verifyNew(SingleContextAdapter.class, times(1)) + .withArguments(sessionStorageMock, ClientCustomDataSource.class, SOME_MIME_TYPE); + } + + @Test + public void should_return_proper_SingleConnectionAdapter_instance_by_connection_metadata_class_mimeType_uuid() throws Exception { + + // Given + whenNew(SingleContextAdapter.class) + .withArguments(sessionStorageMock, SOME_UU_ID, TableMetadata.class, METADATA_MIME_TYPE) + .thenReturn(singleContextAdapterMock); + + ContextService contextService = new ContextService(sessionStorageMock); + + // When + SingleContextAdapter retrieved = contextService. + context(SOME_UU_ID, TableMetadata.class, METADATA_MIME_TYPE); + + // Then + assertSame(singleContextAdapterMock, retrieved); + verifyNew(SingleContextAdapter.class, times(1)) + .withArguments(sessionStorageMock, SOME_UU_ID, TableMetadata.class, METADATA_MIME_TYPE); + } + + @Test + public void should_return_proper_SingleConnectionAdapter_instance_by_class_mimeType_metadata_class_mimeType() throws Exception { + + // Given + whenNew(SingleContextAdapter.class) + .withArguments(sessionStorageMock, + ClientDomain.class, + ContextMediaTypes.DOMAIN_JSON, + ResourceGroupElement.class, + ContextMediaTypes.DOMAIN_METADATA_JSON) + .thenReturn(singleContextAdapterMock); + + ContextService contextService = new ContextService(sessionStorageMock); + + // When + SingleContextAdapter retrieved = contextService. + context(ClientDomain.class, + ContextMediaTypes.DOMAIN_JSON, + ResourceGroupElement.class, + ContextMediaTypes.DOMAIN_METADATA_JSON); + + // Then + assertSame(singleContextAdapterMock, retrieved); + verifyNew(SingleContextAdapter.class, times(1)) + .withArguments(sessionStorageMock, + ClientDomain.class, + ContextMediaTypes.DOMAIN_JSON, + ResourceGroupElement.class, + ContextMediaTypes.DOMAIN_METADATA_JSON); + } +} \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/SingleContextAdapterTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/SingleContextAdapterTest.java new file mode 100644 index 00000000..76e4e1f6 --- /dev/null +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/SingleContextAdapterTest.java @@ -0,0 +1,543 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context; + +import com.jaspersoft.jasperserver.dto.connection.FtpConnection; +import com.jaspersoft.jasperserver.dto.connection.LfsConnection; +import com.jaspersoft.jasperserver.dto.connection.metadata.TableMetadata; +import com.jaspersoft.jasperserver.dto.resources.ClientCustomDataSource; +import com.jaspersoft.jasperserver.dto.resources.ClientJdbcDataSource; +import com.jaspersoft.jasperserver.dto.resources.ClientJndiJdbcDataSource; +import com.jaspersoft.jasperserver.dto.resources.domain.ClientDomain; +import com.jaspersoft.jasperserver.dto.resources.domain.PresentationGroupElement; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.RestClientConfiguration; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.ContextMediaTypes; +import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.MandatoryParameterNotFoundException; +import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import org.mockito.Mock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.testng.PowerMockTestCase; +import org.powermock.reflect.Whitebox; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; +import static org.powermock.api.mockito.PowerMockito.doReturn; +import static org.powermock.api.mockito.PowerMockito.mockStatic; +import static org.powermock.api.mockito.PowerMockito.verifyStatic; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertSame; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +@SuppressWarnings("unchecked") +@PrepareForTest({JerseyRequest.class}) +public class SingleContextAdapterTest extends PowerMockTestCase { + + public static final String TEST_UUID = "someUuId"; + public static final String CONTEXTS_URI = "contexts"; + @Mock + private SessionStorage sessionStorageMock; + @Mock + private RestClientConfiguration configurationMock; + @Mock + private JerseyRequest ftpConnectionJerseyRequestMock; + @Mock + private JerseyRequest jerseyRequestMock; + @Mock + private JerseyRequest lfsConnectionJerseyRequestMock; + @Mock + private JerseyRequest customDataSourceJerseyRequestMock; + @Mock + private JerseyRequest jndiJdbcDataSourceJerseyRequestMock; + @Mock + private JerseyRequest jdbcDataSourceJerseyRequestMock; + @Mock + private JerseyRequest tableMetadataRequestMock; + @Mock + private JerseyRequest presentationGroupElementRequestMock; + @Mock + private OperationResult operationResultMock; + @Mock + private OperationResult ftpConnectionOperationResultMock; + @Mock + private OperationResult lfsConnectionOperationResultMock; + @Mock + private OperationResult customDataSourceOperationResultMock; + @Mock + private OperationResult jndiDataSourceOperationResultMock; + @Mock + private OperationResult jdbcDataSourceOperationResultMock; + @Mock + private OperationResult tableMetadataOperationResultMock; + @Mock + private OperationResult presentationGroupElementOperationResultMock; + + private ContextService contextService; + + @BeforeMethod + public void before() { + initMocks(this); + contextService = new ContextService(sessionStorageMock); + } + + @AfterMethod + public void after() { + reset(sessionStorageMock + , configurationMock + , jerseyRequestMock + , ftpConnectionJerseyRequestMock + , lfsConnectionJerseyRequestMock + , customDataSourceJerseyRequestMock + , jndiJdbcDataSourceJerseyRequestMock + , jdbcDataSourceJerseyRequestMock + , tableMetadataRequestMock + , presentationGroupElementRequestMock + , operationResultMock + , ftpConnectionOperationResultMock + , lfsConnectionOperationResultMock + , customDataSourceOperationResultMock + , jndiDataSourceOperationResultMock + , jdbcDataSourceOperationResultMock + , tableMetadataOperationResultMock + , presentationGroupElementOperationResultMock); + } + + @Test + public void should_return_proper_adapter_with_proper_internal_state() throws Exception { + //when + SingleContextAdapter contextAdapter = new SingleContextAdapter(sessionStorageMock, + ClientDomain.class, + ContextMediaTypes.DOMAIN_JSON); + //then + assertEquals(Whitebox.getInternalState(contextAdapter, "contextContentMimeType"), ContextMediaTypes.DOMAIN_JSON); + assertEquals(Whitebox.getInternalState(contextAdapter, "contextClass"), ClientDomain.class); + assertNull(Whitebox.getInternalState(contextAdapter, "uuId")); + assertNull(Whitebox.getInternalState(contextAdapter, "metadataClass")); + assertNull(Whitebox.getInternalState(contextAdapter, "metadataMimeType")); + } + + + @Test + public void should_return_proper_ftp_connection_operationResult_when_get() throws Exception { + //when + mockStatic(JerseyRequest.class); + when(JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(FtpConnection.class) + , eq(new String[]{CONTEXTS_URI, TEST_UUID}) + , any(DefaultErrorHandler.class))).thenReturn(ftpConnectionJerseyRequestMock); + + doReturn(ftpConnectionOperationResultMock).when(ftpConnectionJerseyRequestMock).get(); + + OperationResult connection = contextService + .context(FtpConnection.class, "someMiMeType", TEST_UUID) + .get(); + //then + assertSame(ftpConnectionOperationResultMock, connection); + verifyStatic(times(1)); + JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(FtpConnection.class) + , eq(new String[]{CONTEXTS_URI, TEST_UUID}) + , any(DefaultErrorHandler.class)); + verify(ftpConnectionJerseyRequestMock).get(); + } + + @Test + public void should_return_proper_ftp_connection_operationResult_when_create() throws Exception { + //when + mockStatic(JerseyRequest.class); + when(JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(FtpConnection.class) + , eq(new String[]{CONTEXTS_URI}) + , any(DefaultErrorHandler.class))).thenReturn(ftpConnectionJerseyRequestMock); + + doReturn(ftpConnectionJerseyRequestMock).when(ftpConnectionJerseyRequestMock).setContentType(ContextMediaTypes.FTP_JSON); + doReturn(ftpConnectionOperationResultMock).when(ftpConnectionJerseyRequestMock).post(any(FtpConnection.class)); + + OperationResult connection = contextService + .context(FtpConnection.class, ContextMediaTypes.FTP_JSON, TEST_UUID) + .create(new FtpConnection()); + //then + assertSame(ftpConnectionOperationResultMock, connection); + verifyStatic(times(1)); + JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(FtpConnection.class) + , eq(new String[]{CONTEXTS_URI}) + , any(DefaultErrorHandler.class)); + verify(ftpConnectionJerseyRequestMock).setContentType(ContextMediaTypes.FTP_JSON); + verify(ftpConnectionJerseyRequestMock).post(any(FtpConnection.class)); + } + + @Test + public void should_return_proper_ftp_connection_operationResult_when_update() throws Exception { + //when + mockStatic(JerseyRequest.class); + when(JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(FtpConnection.class) + , eq(new String[]{CONTEXTS_URI, TEST_UUID}) + , any(DefaultErrorHandler.class))).thenReturn(ftpConnectionJerseyRequestMock); + + doReturn(ftpConnectionJerseyRequestMock).when(ftpConnectionJerseyRequestMock).setContentType(ContextMediaTypes.FTP_JSON); + doReturn(ftpConnectionOperationResultMock).when(ftpConnectionJerseyRequestMock).put(any(FtpConnection.class)); + + OperationResult connection = contextService + .context(FtpConnection.class, ContextMediaTypes.FTP_JSON, TEST_UUID) + .update(new FtpConnection()); + //then + assertSame(ftpConnectionOperationResultMock, connection); + verifyStatic(times(1)); + JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(FtpConnection.class) + , eq(new String[]{CONTEXTS_URI, TEST_UUID}) + , any(DefaultErrorHandler.class)); + verify(ftpConnectionJerseyRequestMock).setContentType(ContextMediaTypes.FTP_JSON); + verify(ftpConnectionJerseyRequestMock).put(any(FtpConnection.class)); + } + + @Test + public void should_return_proper_ftp_connection_operationResult_when_delete() throws Exception { + //when + mockStatic(JerseyRequest.class); + when(JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(Object.class) + , eq(new String[]{CONTEXTS_URI, TEST_UUID}) + , any(DefaultErrorHandler.class))).thenReturn(jerseyRequestMock); + + doReturn(operationResultMock).when(jerseyRequestMock).delete(); + + OperationResult connection = contextService + .context(TEST_UUID) + .delete(); + //then + assertSame(operationResultMock, connection); + verifyStatic(times(1)); + JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(Object.class) + , eq(new String[]{CONTEXTS_URI, TEST_UUID}) + , any(DefaultErrorHandler.class)); + verify(jerseyRequestMock).delete(); + } + + @Test + public void should_return_proper_local_file_system_connection_operationResult_when_get() throws Exception { + //when + mockStatic(JerseyRequest.class); + when(JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(LfsConnection.class) + , eq(new String[]{CONTEXTS_URI, TEST_UUID}) + , any(DefaultErrorHandler.class))).thenReturn(lfsConnectionJerseyRequestMock); + + doReturn(lfsConnectionOperationResultMock).when(lfsConnectionJerseyRequestMock).get(); + + OperationResult connection = contextService + .context(LfsConnection.class, ContextMediaTypes.LOCAL_FILE_SYSTEM_JSON, TEST_UUID) + .get(); + //then + assertSame(lfsConnectionOperationResultMock, connection); + verifyStatic(times(1)); + JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(LfsConnection.class) + , eq(new String[]{CONTEXTS_URI, TEST_UUID}) + , any(DefaultErrorHandler.class)); + verify(lfsConnectionJerseyRequestMock).get(); + } + + @Test + public void should_return_proper_local_file_system_connection_operationResult_when_create() throws Exception { + //when + mockStatic(JerseyRequest.class); + when(JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(LfsConnection.class) + , eq(new String[]{CONTEXTS_URI}) + , any(DefaultErrorHandler.class))).thenReturn(lfsConnectionJerseyRequestMock); + + doReturn(lfsConnectionJerseyRequestMock).when(lfsConnectionJerseyRequestMock).setContentType(ContextMediaTypes.LOCAL_FILE_SYSTEM_JSON); + doReturn(lfsConnectionOperationResultMock).when(lfsConnectionJerseyRequestMock).post(any(LfsConnection.class)); + + OperationResult connection = contextService + .context(LfsConnection.class, ContextMediaTypes.LOCAL_FILE_SYSTEM_JSON, TEST_UUID) + .create(new LfsConnection()); + //then + assertSame(lfsConnectionOperationResultMock, connection); + verifyStatic(times(1)); + JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(LfsConnection.class) + , eq(new String[]{CONTEXTS_URI}) + , any(DefaultErrorHandler.class)); + verify(lfsConnectionJerseyRequestMock).setContentType(ContextMediaTypes.LOCAL_FILE_SYSTEM_JSON); + verify(lfsConnectionJerseyRequestMock).post(any(LfsConnection.class)); + + } + + @Test + public void should_return_proper_custom_data_source_connection_operationResult_when_get() throws Exception { + //when + mockStatic(JerseyRequest.class); + when(JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(ClientCustomDataSource.class) + , eq(new String[]{CONTEXTS_URI, TEST_UUID}) + , any(DefaultErrorHandler.class))).thenReturn(customDataSourceJerseyRequestMock); + + doReturn(customDataSourceOperationResultMock).when(customDataSourceJerseyRequestMock).get(); + + OperationResult connection = contextService + .context(ClientCustomDataSource.class, ContextMediaTypes.CUSTOM_DATA_SOURCE_JSON, TEST_UUID) + .get(); + //then + assertSame(customDataSourceOperationResultMock, connection); + verifyStatic(times(1)); + JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(ClientCustomDataSource.class) + , eq(new String[]{CONTEXTS_URI, TEST_UUID}) + , any(DefaultErrorHandler.class)); + verify(customDataSourceJerseyRequestMock).get(); + + } + + @Test + public void should_return_proper_custom_data_source_connection_operationResult_when_create() throws Exception { + //when + mockStatic(JerseyRequest.class); + when(JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(ClientCustomDataSource.class) + , eq(new String[]{CONTEXTS_URI}) + , any(DefaultErrorHandler.class))).thenReturn(customDataSourceJerseyRequestMock); + + doReturn(customDataSourceJerseyRequestMock).when(customDataSourceJerseyRequestMock).setContentType(ContextMediaTypes.CUSTOM_DATA_SOURCE_JSON); + doReturn(customDataSourceOperationResultMock).when(customDataSourceJerseyRequestMock).post(any(ClientCustomDataSource.class)); + + OperationResult connection = contextService + .context(ClientCustomDataSource.class, ContextMediaTypes.CUSTOM_DATA_SOURCE_JSON, TEST_UUID) + .create(new ClientCustomDataSource()); + //then + assertSame(customDataSourceOperationResultMock, connection); + verifyStatic(times(1)); + JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(ClientCustomDataSource.class) + , eq(new String[]{CONTEXTS_URI}) + , any(DefaultErrorHandler.class)); + verify(customDataSourceJerseyRequestMock).setContentType(ContextMediaTypes.CUSTOM_DATA_SOURCE_JSON); + verify(customDataSourceJerseyRequestMock).post(any(ClientCustomDataSource.class)); + + } + + @Test + public void should_return_proper_jndi_connection_operationResult_when_get() throws Exception { + //when + mockStatic(JerseyRequest.class); + when(JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(ClientJndiJdbcDataSource.class) + , eq(new String[]{CONTEXTS_URI, TEST_UUID}) + , any(DefaultErrorHandler.class))).thenReturn(jndiJdbcDataSourceJerseyRequestMock); + + doReturn(jndiDataSourceOperationResultMock).when(jndiJdbcDataSourceJerseyRequestMock).get(); + + OperationResult connection = contextService + .context(ClientJndiJdbcDataSource.class, ContextMediaTypes.JNDI_JDBC_DATA_SOURCE_JSON, TEST_UUID) + .get(); + //then + assertSame(jndiDataSourceOperationResultMock, connection); + verifyStatic(times(1)); + JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(ClientJndiJdbcDataSource.class) + , eq(new String[]{CONTEXTS_URI, TEST_UUID}) + , any(DefaultErrorHandler.class)); + verify(jndiJdbcDataSourceJerseyRequestMock).get(); + } + + + @Test + public void should_return_proper_jndi_connection_operationResult_when_create() throws Exception { + //when + mockStatic(JerseyRequest.class); + when(JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(ClientJndiJdbcDataSource.class) + , eq(new String[]{CONTEXTS_URI}) + , any(DefaultErrorHandler.class))).thenReturn(jndiJdbcDataSourceJerseyRequestMock); + doReturn(jndiJdbcDataSourceJerseyRequestMock).when(jndiJdbcDataSourceJerseyRequestMock).setContentType(ContextMediaTypes.JNDI_JDBC_DATA_SOURCE_JSON); + doReturn(jndiDataSourceOperationResultMock).when(jndiJdbcDataSourceJerseyRequestMock).post(any(ClientJndiJdbcDataSource.class)); + + OperationResult connection = contextService + .context(ClientJndiJdbcDataSource.class, ContextMediaTypes.JNDI_JDBC_DATA_SOURCE_JSON, TEST_UUID) + .create(new ClientJndiJdbcDataSource()); + //then + assertSame(jndiDataSourceOperationResultMock, connection); + verifyStatic(times(1)); + JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(ClientJndiJdbcDataSource.class) + , eq(new String[]{CONTEXTS_URI}) + , any(DefaultErrorHandler.class)); + verify(jndiJdbcDataSourceJerseyRequestMock).setContentType(ContextMediaTypes.JNDI_JDBC_DATA_SOURCE_JSON); + verify(jndiJdbcDataSourceJerseyRequestMock).post(any(ClientJndiJdbcDataSource.class)); + + } + + @Test + public void should_return_proper_jdbc_connection_operationResult_when_get() throws Exception { + //when + mockStatic(JerseyRequest.class); + when(JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(ClientJdbcDataSource.class) + , eq(new String[]{CONTEXTS_URI, TEST_UUID}) + , any(DefaultErrorHandler.class))).thenReturn(jdbcDataSourceJerseyRequestMock); + + doReturn(jdbcDataSourceOperationResultMock).when(jdbcDataSourceJerseyRequestMock).get(); + + OperationResult connection = contextService + .context(ClientJdbcDataSource.class, ContextMediaTypes.JDBC_DATA_SOURCE_JSON, TEST_UUID) + .get(); + //then + assertSame(jdbcDataSourceOperationResultMock, connection); + verifyStatic(times(1)); + JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(ClientJdbcDataSource.class) + , eq(new String[]{CONTEXTS_URI, TEST_UUID}) + , any(DefaultErrorHandler.class)); + verify(jdbcDataSourceJerseyRequestMock).get(); + } + + + @Test + public void should_return_proper_jdbc_connection_operationResult_when_create() throws Exception { + //when + mockStatic(JerseyRequest.class); + when(JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(ClientJdbcDataSource.class) + , eq(new String[]{CONTEXTS_URI}) + , any(DefaultErrorHandler.class))).thenReturn(jdbcDataSourceJerseyRequestMock); + doReturn(jdbcDataSourceJerseyRequestMock).when(jdbcDataSourceJerseyRequestMock).setContentType(ContextMediaTypes.JDBC_DATA_SOURCE_JSON); + doReturn(jdbcDataSourceOperationResultMock).when(jdbcDataSourceJerseyRequestMock).post(any(ClientJdbcDataSource.class)); + + OperationResult connection = contextService + .context(ClientJdbcDataSource.class, ContextMediaTypes.JDBC_DATA_SOURCE_JSON, TEST_UUID) + .create(new ClientJdbcDataSource()); + //then + assertSame(jdbcDataSourceOperationResultMock, connection); + verifyStatic(times(1)); + JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(ClientJdbcDataSource.class) + , eq(new String[]{CONTEXTS_URI}) + , any(DefaultErrorHandler.class)); + verify(jdbcDataSourceJerseyRequestMock).setContentType(ContextMediaTypes.JDBC_DATA_SOURCE_JSON); + verify(jdbcDataSourceJerseyRequestMock).post(any(ClientJdbcDataSource.class)); + } + + @Test + public void should_return_proper_operationResult_when_create_context_and_get_metadata() throws Exception { + //when + mockStatic(JerseyRequest.class); + when(JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(PresentationGroupElement.class) + , eq(new String[]{CONTEXTS_URI}) + , any(DefaultErrorHandler.class))).thenReturn(presentationGroupElementRequestMock); + doReturn(presentationGroupElementRequestMock). + when(presentationGroupElementRequestMock). + setAccept(ContextMediaTypes.DOMAIN_METADATA_JSON); + doReturn(presentationGroupElementRequestMock). + when(presentationGroupElementRequestMock). + setContentType(ContextMediaTypes.DOMAIN_JSON); + + doReturn(presentationGroupElementOperationResultMock).when(presentationGroupElementRequestMock).post(any(ClientDomain.class)); + + OperationResult metadata = contextService + .context(ClientDomain.class, ContextMediaTypes.DOMAIN_JSON, PresentationGroupElement.class, + ContextMediaTypes.DOMAIN_METADATA_JSON) + .createAndGetMetadata(new ClientDomain()); + //then + assertSame(presentationGroupElementOperationResultMock, metadata); + verifyStatic(times(1)); + JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(PresentationGroupElement.class) + , eq(new String[]{CONTEXTS_URI}) + , any(DefaultErrorHandler.class)); + verify(presentationGroupElementRequestMock).setAccept(ContextMediaTypes.DOMAIN_METADATA_JSON); + verify(presentationGroupElementRequestMock).post(any(ClientDomain.class)); + } + + + @Test(expectedExceptions = MandatoryParameterNotFoundException.class) + public void should_throw_exception_when_get_metadata_Uuid_is_null() throws Exception { + //when + OperationResult connection = contextService + .context(null, TableMetadata.class, + ContextMediaTypes.JDBC_DATA_SOURCE_METADATA_JSON) + .metadata(); + //then + // exception should be thrown + } + + @Test + public void should_return_proper_operationResult_when_get_metadata() throws Exception { + //when + mockStatic(JerseyRequest.class); + when(JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(TableMetadata.class) + , eq(new String[]{CONTEXTS_URI, TEST_UUID, "metadata"}) + , any(DefaultErrorHandler.class))).thenReturn(tableMetadataRequestMock); + doReturn(tableMetadataRequestMock).when(tableMetadataRequestMock).setAccept(ContextMediaTypes.JDBC_DATA_SOURCE_JSON); + + doReturn(tableMetadataOperationResultMock).when(tableMetadataRequestMock).get(); + + OperationResult connection = contextService + .context(TEST_UUID, TableMetadata.class, + ContextMediaTypes.JDBC_DATA_SOURCE_METADATA_JSON) + .metadata(); + //then + assertSame(tableMetadataOperationResultMock, connection); + verifyStatic(times(1)); + JerseyRequest.buildRequest(eq(sessionStorageMock) + , eq(TableMetadata.class) + , eq(new String[]{CONTEXTS_URI, TEST_UUID, "metadata"}) + , any(DefaultErrorHandler.class)); + verify(tableMetadataRequestMock).setAccept(ContextMediaTypes.JDBC_DATA_SOURCE_METADATA_JSON); + verify(tableMetadataRequestMock).get(); + } + + @Test(expectedExceptions = MandatoryParameterNotFoundException.class) + public void should_throw_exception_when_update_connection_is_null() throws Exception { + //when + contextService + .context(Object.class, "someMiMeType") + .create(null); + //then + // an exception should be thrown + + } + + @Test(expectedExceptions = MandatoryParameterNotFoundException.class) + public void should_throw_exception_when_create_connection_uuid_is_null() throws Exception { + //when + contextService + .context(null) + .get(); + //then + // an exception should be thrown + } + + + @Test(expectedExceptions = MandatoryParameterNotFoundException.class) + public void should_throw_exception_when_get_connection_uuid_is_empty() throws Exception { + //when + contextService + .context("") + .get(); + //then + // an exception should be thrown + } + +} \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/domain/DomainContextOperationResultTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/domain/DomainContextOperationResultTest.java new file mode 100644 index 00000000..90d867a6 --- /dev/null +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/domain/DomainContextOperationResultTest.java @@ -0,0 +1,219 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.domain; + +import com.jaspersoft.jasperserver.dto.adhoc.query.ClientMultiLevelQuery; +import com.jaspersoft.jasperserver.dto.executions.ClientMultiLevelQueryResultData; +import com.jaspersoft.jasperserver.dto.resources.ClientResourceLookup; +import com.jaspersoft.jasperserver.dto.resources.domain.PresentationGroupElement; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.ContextService; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.SingleContextAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.ResourceNotFoundException; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.Response; +import org.mockito.Mock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.testng.PowerMockTestCase; +import org.powermock.reflect.Whitebox; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.MockitoAnnotations.initMocks; +import static org.powermock.api.mockito.PowerMockito.doReturn; +import static org.testng.Assert.assertSame; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +@SuppressWarnings("unchecked") +@PrepareForTest({DomainContextOperationResult.class, Response.class, SingleContextAdapter.class}) +public class DomainContextOperationResultTest extends PowerMockTestCase { + + DomainContextOperationResult domainContextOperationResult; + @Mock + private SingleContextAdapter singleContextAdapterMock; + @Mock + private SingleContextAdapter singleContextForCreateAdapterMock; + @Mock + private OperationResult operationResultMock; + @Mock + private OperationResult queryResultDataOperationResult; + @Mock + private OperationResult resourceLookupOperationResultMock; + @Mock + private ContextService contextServiceMock; + @Mock + private Response responseMock; + @Mock + private ClientResourceLookup resourceLookupMock; + + @BeforeMethod + public void before() { + initMocks(this); + + } + + @AfterMethod + public void after() { + reset(contextServiceMock + , singleContextAdapterMock + , responseMock + , operationResultMock + , queryResultDataOperationResult + , singleContextForCreateAdapterMock + , resourceLookupOperationResultMock + , resourceLookupMock + ); + + } + + + @Test + public void should_return_proper_operationResult_when_get_metadata() throws Exception { + //given + doReturn("/test_uuId").when(responseMock).getHeaderString("Location"); + domainContextOperationResult = new DomainContextOperationResult<>(responseMock, ClientResourceLookup.class, contextServiceMock); + doReturn(singleContextAdapterMock).when(contextServiceMock).context(anyString(), + any(Class.class), anyString()); + doReturn(singleContextAdapterMock).when(singleContextAdapterMock).addParameters(any(MultivaluedHashMap.class)); + doReturn(operationResultMock).when(singleContextAdapterMock).metadata(); + + //when + OperationResult metadata = domainContextOperationResult.getMetadata(); + + //then + assertSame(operationResultMock, metadata); + verify(responseMock).getHeaderString("Location"); + verify(contextServiceMock).context(anyString(),any(Class.class), anyString()); + verify(singleContextAdapterMock).addParameters(any(MultivaluedHashMap.class)); + verify(singleContextAdapterMock).metadata(); + + } + + @Test + public void should_return_proper_entity() throws Exception { + //given + doReturn("/test_uuId").when(responseMock).getHeaderString("Location"); + domainContextOperationResult = new DomainContextOperationResult(responseMock, ClientResourceLookup.class, contextServiceMock); + Whitebox.setInternalState(domainContextOperationResult, "entity", resourceLookupMock); + + //when + ClientResourceLookup entity = domainContextOperationResult.getEntity(); + + //then + assertSame(resourceLookupMock, entity); + verify(responseMock).getHeaderString("Location"); + } + + @Test + public void should_return_proper_operationResult_when_get_metadata_with_parameter() throws Exception { + //given + doReturn("/test_uuId").when(responseMock).getHeaderString("Location"); + domainContextOperationResult = new DomainContextOperationResult<>(responseMock, ClientResourceLookup.class, contextServiceMock); + doReturn(singleContextAdapterMock).when(contextServiceMock).context(anyString(), + any(Class.class), anyString()); + doReturn(singleContextAdapterMock).when(singleContextAdapterMock).addParameters(any(MultivaluedHashMap.class)); + doReturn(operationResultMock).when(singleContextAdapterMock).metadata(); + + //when + OperationResult metadata = domainContextOperationResult.addParam("key", "value").getMetadata(); + + //then + assertSame(operationResultMock, metadata); + verify(responseMock).getHeaderString("Location"); + verify(contextServiceMock).context(anyString(),any(Class.class), anyString()); + verify(singleContextAdapterMock).addParameters(any(MultivaluedHashMap.class)); + verify(singleContextAdapterMock).metadata(); + } + + @Test + public void should_return_proper_operationResult_when_get_metadata_with_parameters() throws Exception { + //given + doReturn("/test_uuId").when(responseMock).getHeaderString("Location"); + domainContextOperationResult = new DomainContextOperationResult<>(responseMock, ClientResourceLookup.class, contextServiceMock); + doReturn(singleContextAdapterMock).when(contextServiceMock).context(anyString(), + any(Class.class), anyString()); + doReturn(singleContextAdapterMock).when(singleContextAdapterMock).addParameters(any(MultivaluedHashMap.class)); + doReturn(operationResultMock).when(singleContextAdapterMock).metadata(); + + //when + OperationResult metadata = domainContextOperationResult.addParam("key", "value1", "value2").getMetadata(); + + //then + assertSame(operationResultMock, metadata); + verify(responseMock).getHeaderString("Location"); + verify(contextServiceMock).context(anyString(),any(Class.class), anyString()); + verify(singleContextAdapterMock).addParameters(any(MultivaluedHashMap.class)); + verify(singleContextAdapterMock).metadata(); + } + + @Test(expectedExceptions = ResourceNotFoundException.class) + public void should_return_proper_operationResult_when_get_metadata_for_expired_context() throws Exception { + //given + doReturn("/test_uuId").when(responseMock).getHeaderString("Location"); + domainContextOperationResult = spy(new DomainContextOperationResult(responseMock, ClientResourceLookup.class, contextServiceMock)); + doReturn(singleContextAdapterMock).when(contextServiceMock).context(anyString(), + any(Class.class), anyString()); + doReturn(singleContextAdapterMock).when(singleContextAdapterMock).addParameters(any(MultivaluedHashMap.class)); + doThrow(ResourceNotFoundException.class).when(singleContextAdapterMock).metadata(); + doReturn(singleContextForCreateAdapterMock).when(contextServiceMock).context(any(Class.class), anyString()); + doReturn(resourceLookupOperationResultMock).when(singleContextForCreateAdapterMock).create(any(ClientResourceLookup.class)); + doReturn(responseMock).when(resourceLookupOperationResultMock).getResponse(); + + //when + OperationResult metadata = domainContextOperationResult.getMetadata(); + + //then + assertSame(operationResultMock, metadata); + + } + + @Test + public void should_return_proper_operationResult_when_execute_query() throws Exception { + //given + doReturn("/test_uuId").when(responseMock).getHeaderString("Location"); + domainContextOperationResult = new DomainContextOperationResult<>(responseMock, ClientResourceLookup.class, contextServiceMock); + doReturn(singleContextAdapterMock).when(contextServiceMock).context(anyString()); + doReturn(operationResultMock).when(singleContextAdapterMock).executeQuery(any(ClientMultiLevelQuery.class)); + + //when + OperationResult queryResultSet = domainContextOperationResult.executeQuery(new ClientMultiLevelQuery()); + + //then + assertSame(operationResultMock, queryResultSet); + verify(responseMock).getHeaderString("Location"); + verify(contextServiceMock).context(anyString()); + verify(singleContextAdapterMock).executeQuery(any(ClientMultiLevelQuery.class)); + } + + @Test(expectedExceptions = ResourceNotFoundException.class) + public void should_return_proper_operationResult_when_execute_query_for_expired_context() throws Exception { + //given + doReturn("/test_uuId").when(responseMock).getHeaderString("Location"); + domainContextOperationResult = new DomainContextOperationResult<>(responseMock, ClientResourceLookup.class, contextServiceMock); + doReturn(singleContextAdapterMock).when(contextServiceMock).context(anyString()); + doThrow(ResourceNotFoundException.class).when(singleContextAdapterMock).executeQuery(any(ClientMultiLevelQuery.class)); + + doReturn(singleContextForCreateAdapterMock).when(contextServiceMock).context(any(Class.class), anyString()); + doReturn(resourceLookupOperationResultMock).when(singleContextForCreateAdapterMock).create(any(ClientResourceLookup.class)); + doReturn(responseMock).when(resourceLookupOperationResultMock).getResponse(); + + //when + OperationResult queryResultSet = domainContextOperationResult.executeQuery(new ClientMultiLevelQuery()); + + // then + // an exception should be thrown + + } +} \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/domain/DomainContextServiceTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/domain/DomainContextServiceTest.java new file mode 100644 index 00000000..11ff6dc7 --- /dev/null +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/domain/DomainContextServiceTest.java @@ -0,0 +1,130 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.domain; + +import com.jaspersoft.jasperserver.dto.resources.ClientResourceLookup; +import com.jaspersoft.jasperserver.dto.resources.ClientSemanticLayerDataSource; +import com.jaspersoft.jasperserver.dto.resources.domain.ClientDomain; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.ContextMediaTypes; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.testng.PowerMockTestCase; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.powermock.api.mockito.PowerMockito.verifyNew; +import static org.powermock.api.mockito.PowerMockito.whenNew; +import static org.testng.Assert.assertSame; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +@PrepareForTest({DomainContextService.class}) +public class DomainContextServiceTest extends PowerMockTestCase { + private SessionStorage sessionStorageMock; + private SingleDomainContextAdapter adapter; + + @BeforeMethod + public void before() { + sessionStorageMock = mock(SessionStorage.class); + adapter = mock(SingleDomainContextAdapter.class); + } + + @AfterMethod + public void after() { + reset(sessionStorageMock, + adapter + ); + } + + @Test + public void should_pass_session_storage_to_parent_adapter() { + // When + DomainContextService service = new DomainContextService(sessionStorageMock); + SessionStorage retrieved = service.getSessionStorage(); + // Then + assertSame(retrieved, sessionStorageMock); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void should_throw_an_exception_when_sessionStorage_is_null() { + // When + new DomainContextService(null); + // Then + // should be thrown an exception + } + + @Test + public void should_return_proper_DomainContextManager_for_string_uri() throws Exception { + + // Given + whenNew(SingleDomainContextAdapter.class) + .withArguments(eq(sessionStorageMock), any(ClientResourceLookup.class), any(Class.class), anyString()) + .thenReturn(adapter); + + DomainContextService service = new DomainContextService(sessionStorageMock); + + // When + SingleDomainContextAdapter retrieved = service.context("URI"); + + // Then + assertSame(adapter, retrieved); + verifyNew(SingleDomainContextAdapter.class, times(1)) + .withArguments(eq(sessionStorageMock), + any(ClientResourceLookup.class), + eq(ClientResourceLookup.class), + eq(ContextMediaTypes.RESOURCE_LOOKUP_JSON)); + } + @Test + public void should_return_proper_DomainContextManager_for_clientDomain() throws Exception { + + // Given + whenNew(SingleDomainContextAdapter.class) + .withArguments(eq(sessionStorageMock), any(ClientDomain.class), any(Class.class), anyString()) + .thenReturn(adapter); + + DomainContextService service = new DomainContextService(sessionStorageMock); + + // When + SingleDomainContextAdapter retrieved = service.context(new ClientDomain()); + + // Then + assertSame(adapter, retrieved); + verifyNew(SingleDomainContextAdapter.class, times(1)) + .withArguments(eq(sessionStorageMock), + any(ClientDomain.class), + eq(ClientDomain.class), + eq(ContextMediaTypes.DOMAIN_JSON)); + } + @Test + public void should_return_proper_DomainContextManager_for_clientSemanticLayerDataSource() throws Exception { + + // Given + whenNew(SingleDomainContextAdapter.class) + .withArguments(eq(sessionStorageMock), any(ClientSemanticLayerDataSource.class), any(Class.class), anyString()) + .thenReturn(adapter); + + DomainContextService service = new DomainContextService(sessionStorageMock); + + // When + SingleDomainContextAdapter retrieved = service.context(new ClientSemanticLayerDataSource()); + + // Then + assertSame(adapter, retrieved); + verifyNew(SingleDomainContextAdapter.class, times(1)) + .withArguments(eq(sessionStorageMock), + any(ClientSemanticLayerDataSource.class), + eq(ClientSemanticLayerDataSource.class), + eq(ContextMediaTypes.DOMAIN_DATA_SOURCE_JSON)); + } +} \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/domain/SingleDomainContextAdapterTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/domain/SingleDomainContextAdapterTest.java new file mode 100644 index 00000000..8d0d7160 --- /dev/null +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/context/domain/SingleDomainContextAdapterTest.java @@ -0,0 +1,140 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.domain; + +import com.jaspersoft.jasperserver.dto.resources.ClientResourceLookup; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.ContextService; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.SingleContextAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.RestClientConfiguration; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.ContextMediaTypes; +import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.MandatoryParameterNotFoundException; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import javax.ws.rs.core.Response; +import org.mockito.Mock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.testng.PowerMockTestCase; +import org.powermock.reflect.Whitebox; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.verify; +import static org.mockito.MockitoAnnotations.initMocks; +import static org.powermock.api.mockito.PowerMockito.doReturn; +import static org.powermock.api.mockito.PowerMockito.verifyNew; +import static org.powermock.api.mockito.PowerMockito.whenNew; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertSame; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +@SuppressWarnings("unchecked") +@PrepareForTest({SingleDomainContextAdapter.class}) +public class SingleDomainContextAdapterTest extends PowerMockTestCase { + + @Mock + private SessionStorage sessionStorageMock; + @Mock + private RestClientConfiguration configurationMock; + @Mock + private ClientResourceLookup clientResourceLookupMock; + @Mock + private JerseyRequest resourceLookupJerseyRequest; + @Mock + private SingleContextAdapter singleContextAdapterMock; + @Mock + private OperationResult resourceLookupOperationResult; + @Mock + private DomainContextOperationResult domainContextResourceLookupOperationResult; + @Mock + private ContextService contextServiceMock; + @Mock + private Response responseMock; + + @BeforeMethod + public void before() { + initMocks(this); + } + + @AfterMethod + public void after() { + reset(sessionStorageMock + , configurationMock + , contextServiceMock + , singleContextAdapterMock + , resourceLookupJerseyRequest + , resourceLookupOperationResult + , domainContextResourceLookupOperationResult + , clientResourceLookupMock + , responseMock + ); + + } + + @Test + public void should_return_proper_adapter_with_proper_internal_state() throws Exception { + //when + SingleDomainContextAdapter contextAdapter = new SingleDomainContextAdapter(sessionStorageMock, + clientResourceLookupMock, + ClientResourceLookup.class, + ContextMediaTypes.DOMAIN_JSON); + //then + assertEquals(Whitebox.getInternalState(contextAdapter, "contextMimeType"), ContextMediaTypes.DOMAIN_JSON); + assertEquals(Whitebox.getInternalState(contextAdapter, "contextClass"), ClientResourceLookup.class); + assertEquals(Whitebox.getInternalState(contextAdapter, "context"), clientResourceLookupMock); + assertNotNull(Whitebox.getInternalState(contextAdapter, "service")); + } + + + @Test + public void should_return_proper_operationResult_when_create() throws Exception { + //given + whenNew(ContextService.class).withArguments(sessionStorageMock).thenReturn(contextServiceMock); + SingleDomainContextAdapter domainContextAdapter = new SingleDomainContextAdapter(sessionStorageMock, + clientResourceLookupMock, + ClientResourceLookup.class, + ContextMediaTypes.RESOURCE_LOOKUP_JSON); + + doReturn(singleContextAdapterMock).when(contextServiceMock).context(any(Class.class), anyString()); + doReturn(resourceLookupOperationResult).when(singleContextAdapterMock).create(clientResourceLookupMock); + doReturn(responseMock).when(resourceLookupOperationResult).getResponse(); + doReturn(clientResourceLookupMock).when(resourceLookupOperationResult).getEntity(); + whenNew(DomainContextOperationResult.class).withArguments(any(Response.class), + any(Class.class), eq(contextServiceMock)).thenReturn(domainContextResourceLookupOperationResult); + //when + OperationResult connection = domainContextAdapter.create(); + + //then + assertSame(domainContextResourceLookupOperationResult, connection); + verifyNew(ContextService.class).withArguments(sessionStorageMock); + verify(contextServiceMock).context(any(Class.class), anyString()); + verify(singleContextAdapterMock).create(clientResourceLookupMock); + verify(resourceLookupOperationResult).getResponse(); + verify(resourceLookupOperationResult).getEntity(); + verifyNew(DomainContextOperationResult.class).withArguments(any(Response.class), + any(Class.class), eq(contextServiceMock)); + } + + @Test(expectedExceptions = MandatoryParameterNotFoundException.class) + public void should_throw_exception_when_create_null_context() throws Exception { + // when + SingleDomainContextAdapter domainContextAdapter = new SingleDomainContextAdapter(sessionStorageMock, + null, + ClientResourceLookup.class, + ContextMediaTypes.RESOURCE_LOOKUP_JSON); + + //then + // exception should be thrown + } +} \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/DataDiscoveryServiceTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/DataDiscoveryServiceTest.java new file mode 100644 index 00000000..959f0c05 --- /dev/null +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/DataDiscoveryServiceTest.java @@ -0,0 +1,146 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.datadiscovery; + +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.ContextService; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.testng.PowerMockTestCase; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.powermock.api.mockito.PowerMockito.verifyNew; +import static org.powermock.api.mockito.PowerMockito.whenNew; +import static org.testng.Assert.assertSame; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +@PrepareForTest({DataDiscoveryService.class}) +public class DataDiscoveryServiceTest extends PowerMockTestCase { + private SessionStorage sessionStorageMock; + private DomainContextManager domainContextManager; + private TopicContextManager topicContextManager; + private DomElContextManager domElContextManager; + private DerivedTableContextManager derivedTableContextManager; + + @BeforeMethod + public void before() { + sessionStorageMock = mock(SessionStorage.class); + domainContextManager = mock(DomainContextManager.class); + topicContextManager = mock(TopicContextManager.class); + domElContextManager= mock(DomElContextManager.class); + derivedTableContextManager = mock(DerivedTableContextManager.class); + + } + + @AfterMethod + public void after() { + reset(sessionStorageMock, + domainContextManager, + domElContextManager, + topicContextManager, + derivedTableContextManager); + } + + @Test + public void should_pass_session_storage_to_parent_adapter() { + ContextService attributesService = new ContextService(sessionStorageMock); + SessionStorage retrieved = attributesService.getSessionStorage(); + assertSame(retrieved, sessionStorageMock); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void should_throw_an_exception_when_sessionStorage_is_null() { + // When + new ContextService(null); + // Then + // should be thrown an exception + } + + + @Test + public void should_return_proper_DomainContextManager() throws Exception { + + // Given + whenNew(DomainContextManager.class) + .withArguments(sessionStorageMock) + .thenReturn(domainContextManager); + + DataDiscoveryService dataDiscoveryService = new DataDiscoveryService(sessionStorageMock); + + // When + DomainContextManager retrieved = dataDiscoveryService.domainContext(); + + // Then + assertSame(domainContextManager, retrieved); + verifyNew(DomainContextManager.class, times(1)) + .withArguments(sessionStorageMock); + } + + @Test + public void should_return_proper_TopicContextManager() throws Exception { + + // Given + whenNew(TopicContextManager.class) + .withArguments(sessionStorageMock) + .thenReturn(topicContextManager); + + DataDiscoveryService dataDiscoveryService = new DataDiscoveryService(sessionStorageMock); + + // When + TopicContextManager retrieved = dataDiscoveryService.topicContext(); + + // Then + assertSame(topicContextManager, retrieved); + verifyNew(TopicContextManager.class, times(1)) + .withArguments(sessionStorageMock); + } + + @Test + public void should_return_proper_DomElContextManager() throws Exception { + + // Given + whenNew(DomElContextManager.class) + .withArguments(sessionStorageMock) + .thenReturn(domElContextManager); + + DataDiscoveryService dataDiscoveryService = new DataDiscoveryService(sessionStorageMock); + + // When + DomElContextManager retrieved = dataDiscoveryService.domElContext(); + + // Then + assertSame(domElContextManager, retrieved); + verifyNew(DomElContextManager.class, times(1)) + .withArguments(sessionStorageMock); + } + + @Test + public void should_return_proper_deridved_table_context_manager() throws Exception { + + // Given + whenNew(DerivedTableContextManager.class) + .withArguments(sessionStorageMock) + .thenReturn(derivedTableContextManager); + + DataDiscoveryService dataDiscoveryService = new DataDiscoveryService(sessionStorageMock); + + // When + DerivedTableContextManager retrieved = dataDiscoveryService.derivedTableContext(); + + // Then + assertSame(derivedTableContextManager, retrieved); + verifyNew(DerivedTableContextManager.class, times(1)) + .withArguments(sessionStorageMock); + } + + +} \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/DerivedTableContextManagerTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/DerivedTableContextManagerTest.java new file mode 100644 index 00000000..3cd660f3 --- /dev/null +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/DerivedTableContextManagerTest.java @@ -0,0 +1,82 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.datadiscovery; + +import com.jaspersoft.jasperserver.dto.resources.SqlExecutionRequest; +import com.jaspersoft.jasperserver.dto.resources.domain.PresentationGroupElement; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.ContextService; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.SingleContextAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.ContextMediaTypes; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import org.mockito.internal.util.reflection.Whitebox; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.testng.PowerMockTestCase; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.powermock.api.mockito.PowerMockito.spy; +import static org.testng.Assert.assertSame; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +@PrepareForTest({ContextService.class, SessionStorage.class, SingleContextAdapter.class, DerivedTableContextManager.class}) +public class DerivedTableContextManagerTest extends PowerMockTestCase { + private SessionStorage sessionStorageMock; + private ContextService contextServiceMock; + private SingleContextAdapter contextAdapterMock; + private OperationResult operationResultMock; + + + @BeforeMethod + public void before() { + sessionStorageMock = mock(SessionStorage.class); + contextServiceMock = mock(ContextService.class); + contextAdapterMock = mock(SingleContextAdapter.class); + operationResultMock = mock(OperationResult.class); + } + + @AfterMethod + public void after() { + reset(sessionStorageMock, contextAdapterMock, contextServiceMock, operationResultMock); + } + + + @Test + public void should_set_proper_session_storage() { + // When + DomElContextManager domainContextManager = new DomElContextManager(sessionStorageMock); + //Then + assertSame(Whitebox.getInternalState(domainContextManager, "sessionStorage"), sessionStorageMock); + } + + @Test + public void should_return_proper_operation_result_when_create_context() throws Exception { + // When + + SqlExecutionRequest request = spy(new SqlExecutionRequest()); + + PowerMockito.whenNew(ContextService.class).withArguments(sessionStorageMock).thenReturn(contextServiceMock); + PowerMockito.when(contextServiceMock.context(SqlExecutionRequest.class, + ContextMediaTypes.SQL_EXECUTION_JSON, + PresentationGroupElement.class, + ContextMediaTypes.DATASET_METADATA_JSON)). + thenReturn(contextAdapterMock); + PowerMockito.when(contextAdapterMock.createAndGetMetadata(request)).thenReturn(operationResultMock); + + OperationResult retrievedOperationResult = new DerivedTableContextManager(sessionStorageMock). + execute(request); + //Then + assertSame(operationResultMock, retrievedOperationResult); + } + + +} \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/DomElContextManagerTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/DomElContextManagerTest.java new file mode 100644 index 00000000..d631d82e --- /dev/null +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/DomElContextManagerTest.java @@ -0,0 +1,98 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.datadiscovery; + +import com.jaspersoft.jasperserver.dto.domain.DomElExpressionCollectionContext; +import com.jaspersoft.jasperserver.dto.domain.DomElExpressionContext; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.ContextService; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.SingleContextAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.ContextMediaTypes; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import org.mockito.internal.util.reflection.Whitebox; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.testng.PowerMockTestCase; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.powermock.api.mockito.PowerMockito.spy; +import static org.testng.Assert.assertSame; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +@PrepareForTest({ContextService.class, SessionStorage.class, SingleContextAdapter.class, DomElContextManager.class}) +public class DomElContextManagerTest extends PowerMockTestCase { + private SessionStorage sessionStorageMock; + private ContextService contextServiceMock; + private SingleContextAdapter contextAdapterMock; + private OperationResult domElContextOperationResultMock; + private OperationResult domElCollectionContextOperationResultMock; + + + @BeforeMethod + public void before() { + sessionStorageMock = mock(SessionStorage.class); + contextServiceMock = mock(ContextService.class); + contextAdapterMock = mock(SingleContextAdapter.class); + domElContextOperationResultMock = mock(OperationResult.class); + } + + @AfterMethod + public void after() { + reset(sessionStorageMock, contextAdapterMock, contextServiceMock, domElContextOperationResultMock); + } + + + @Test + public void should_set_proper_session_storage() { + // When + DomElContextManager domainContextManager = new DomElContextManager(sessionStorageMock); + //Then + assertSame(Whitebox.getInternalState(domainContextManager, "sessionStorage"), sessionStorageMock); + } + + @Test + public void should_return_proper_operation_result_when_create_context() throws Exception { + // When + + DomElExpressionContext context = spy(new DomElExpressionContext()); + + PowerMockito.whenNew(ContextService.class).withArguments(sessionStorageMock).thenReturn(contextServiceMock); + PowerMockito.when(contextServiceMock.context(DomElExpressionContext.class, + ContextMediaTypes.DOM_EL_CONTEXT_JSON)). + thenReturn(contextAdapterMock); + PowerMockito.when(contextAdapterMock.create(context)).thenReturn(domElContextOperationResultMock); + + OperationResult retrievedOperationResult = new DomElContextManager(sessionStorageMock).create(context); + //Then + assertSame(domElContextOperationResultMock, retrievedOperationResult); + } + + + @Test + public void should_return_proper_operation_result_when_create_collection_context() throws Exception { + // When + + DomElExpressionCollectionContext context = spy(new DomElExpressionCollectionContext()); + + PowerMockito.whenNew(ContextService.class).withArguments(sessionStorageMock).thenReturn(contextServiceMock); + PowerMockito.when(contextServiceMock.context(DomElExpressionCollectionContext.class, + ContextMediaTypes.DOM_EL_COLLECTION_CONTEXT_JSON)). + thenReturn(contextAdapterMock); + PowerMockito.when(contextAdapterMock.create(context)).thenReturn(domElCollectionContextOperationResultMock); + + OperationResult retrievedOperationResult = + new DomElContextManager(sessionStorageMock).create(context); + //Then + assertSame(domElCollectionContextOperationResultMock, retrievedOperationResult); + } + +} \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/DomainContextManagerTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/DomainContextManagerTest.java new file mode 100644 index 00000000..d49bd91e --- /dev/null +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/DomainContextManagerTest.java @@ -0,0 +1,115 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.datadiscovery; + +import com.jaspersoft.jasperserver.dto.resources.domain.ClientDomain; +import com.jaspersoft.jasperserver.dto.resources.domain.PresentationGroupElement; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.connections.SingleConnectionsAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.ContextService; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.SingleContextAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.ContextMediaTypes; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import org.mockito.internal.util.reflection.Whitebox; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.testng.PowerMockTestCase; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.powermock.api.mockito.PowerMockito.spy; +import static org.testng.Assert.assertSame; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +@PrepareForTest({ContextService.class, SessionStorage.class, SingleConnectionsAdapter.class, DomainContextManager.class}) +public class DomainContextManagerTest extends PowerMockTestCase { + private SessionStorage sessionStorageMock; + private ContextService contextServiceMock; + private SingleContextAdapter contextAdapterMock; + private OperationResult operationResultMock; + private OperationResult dataIslandsContainerOperationResult; + + + @BeforeMethod + public void before() { + sessionStorageMock = mock(SessionStorage.class); + contextServiceMock = mock(ContextService.class); + contextAdapterMock = mock(SingleContextAdapter.class); + operationResultMock = mock(OperationResult.class); + dataIslandsContainerOperationResult = mock(OperationResult.class); + } + + @AfterMethod + public void after() { + reset(sessionStorageMock, contextAdapterMock, contextServiceMock, operationResultMock, dataIslandsContainerOperationResult); + } + + + @Test + public void should_set_proper_session_storage() { + // When + DomainContextManager domainContextManager = new DomainContextManager(sessionStorageMock); + //Then + assertSame(Whitebox.getInternalState(domainContextManager, "sessionStorage"), sessionStorageMock); + } + + @Test + public void should_return_proper_domain_when_create_context() throws Exception { + // When + + ClientDomain domain = spy(new ClientDomain()); + PowerMockito.whenNew(ContextService.class).withArguments(sessionStorageMock).thenReturn(contextServiceMock); + PowerMockito.when(contextServiceMock.context(ClientDomain.class, ContextMediaTypes.DOMAIN_JSON)).thenReturn(contextAdapterMock); + PowerMockito.when(contextAdapterMock.create(domain)).thenReturn(operationResultMock); + + OperationResult retrievedOperationResult = new DomainContextManager(sessionStorageMock).create(domain); + //Then + assertSame(operationResultMock, retrievedOperationResult); + } + + @Test + public void should_return_proper_domain_when_get_metadata() throws Exception { + // When + + String someId = "someId"; + PowerMockito.whenNew(ContextService.class).withArguments(sessionStorageMock).thenReturn(contextServiceMock); + PowerMockito.when(contextServiceMock.context(someId, + PresentationGroupElement.class, + ContextMediaTypes.DOMAIN_METADATA_JSON)). + thenReturn(contextAdapterMock); + PowerMockito.when(contextAdapterMock.metadata()).thenReturn(dataIslandsContainerOperationResult); + + OperationResult retrievedOperationResult = new DomainContextManager(sessionStorageMock). + fetchMetadataById(someId); + //Then + assertSame(dataIslandsContainerOperationResult, retrievedOperationResult); + } + + + @Test + public void should_return_proper_domain_when_create_context_and_get_metadata() throws Exception { + // When + + ClientDomain domain = spy(new ClientDomain()); + PowerMockito.whenNew(ContextService.class).withArguments(sessionStorageMock).thenReturn(contextServiceMock); + PowerMockito.when(contextServiceMock.context(ClientDomain.class, + ContextMediaTypes.DOMAIN_JSON, + PresentationGroupElement.class, + ContextMediaTypes.DOMAIN_METADATA_JSON + )).thenReturn(contextAdapterMock); + PowerMockito.when(contextAdapterMock.createAndGetMetadata(domain)).thenReturn(dataIslandsContainerOperationResult); + + OperationResult retrievedOperationResult = new DomainContextManager(sessionStorageMock).fetchMetadataByContext(domain); + //Then + assertSame(dataIslandsContainerOperationResult, retrievedOperationResult); + } + +} \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/TopicContextManagerTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/TopicContextManagerTest.java new file mode 100644 index 00000000..d44c1116 --- /dev/null +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/datadiscovery/TopicContextManagerTest.java @@ -0,0 +1,116 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.datadiscovery; + +import com.jaspersoft.jasperserver.dto.resources.ClientReportUnit; +import com.jaspersoft.jasperserver.dto.resources.domain.ResourceGroupElement; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.connections.SingleConnectionsAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.ContextService; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.context.SingleContextAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.ContextMediaTypes; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import org.mockito.internal.util.reflection.Whitebox; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.testng.PowerMockTestCase; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.powermock.api.mockito.PowerMockito.spy; +import static org.testng.Assert.assertSame; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +@PrepareForTest({ContextService.class, SessionStorage.class, SingleConnectionsAdapter.class, TopicContextManager.class}) +public class TopicContextManagerTest extends PowerMockTestCase { + private SessionStorage sessionStorageMock; + private ContextService contextServiceMock; + private SingleContextAdapter contextAdapterMock; + private OperationResult operationResultMock; + private OperationResult resourceGroupElementOperationResult; + + + @BeforeMethod + public void before() { + sessionStorageMock = mock(SessionStorage.class); + contextServiceMock = mock(ContextService.class); + contextAdapterMock = mock(SingleContextAdapter.class); + operationResultMock = mock(OperationResult.class); + resourceGroupElementOperationResult = mock(OperationResult.class); + } + + @AfterMethod + public void after() { + reset(sessionStorageMock, contextAdapterMock, contextServiceMock, operationResultMock, resourceGroupElementOperationResult); + } + + + @Test + public void should_set_proper_session_storage() { + // When + TopicContextManager domainContextManager = new TopicContextManager(sessionStorageMock); + //Then + assertSame(Whitebox.getInternalState(domainContextManager, "sessionStorage"), sessionStorageMock); + } + + @Test + public void should_return_proper_domain_when_create_context() throws Exception { + // When + + ClientReportUnit reportUnit = spy(new ClientReportUnit()); + PowerMockito.whenNew(ContextService.class).withArguments(sessionStorageMock).thenReturn(contextServiceMock); + PowerMockito.when(contextServiceMock.context(ClientReportUnit.class, + ContextMediaTypes.REPORT_UNIT_JSON)).thenReturn(contextAdapterMock); + PowerMockito.when(contextAdapterMock.create(reportUnit)).thenReturn(operationResultMock); + + OperationResult retrievedOperationResult = new TopicContextManager(sessionStorageMock).create(reportUnit); + //Then + assertSame(operationResultMock, retrievedOperationResult); + } + + @Test + public void should_return_proper_domain_when_get_metadata() throws Exception { + // When + + String someId = "someId"; + PowerMockito.whenNew(ContextService.class).withArguments(sessionStorageMock).thenReturn(contextServiceMock); + PowerMockito.when(contextServiceMock.context(someId, + ResourceGroupElement.class, + ContextMediaTypes.REPORT_UNIT_METADATA_JSON)). + thenReturn(contextAdapterMock); + PowerMockito.when(contextAdapterMock.metadata()).thenReturn(resourceGroupElementOperationResult); + + OperationResult retrievedOperationResult = new TopicContextManager(sessionStorageMock). + fetchMetadataById(someId); + //Then + assertSame(resourceGroupElementOperationResult, retrievedOperationResult); + } + + + @Test + public void should_return_proper_domain_when_create_context_and_get_metadata() throws Exception { + // When + + ClientReportUnit reportUnit = spy(new ClientReportUnit()); + PowerMockito.whenNew(ContextService.class).withArguments(sessionStorageMock).thenReturn(contextServiceMock); + PowerMockito.when(contextServiceMock.context(ClientReportUnit.class, + ContextMediaTypes.REPORT_UNIT_JSON, + ResourceGroupElement.class, + ContextMediaTypes.REPORT_UNIT_METADATA_JSON + )).thenReturn(contextAdapterMock); + PowerMockito.when(contextAdapterMock.createAndGetMetadata(reportUnit)).thenReturn(resourceGroupElementOperationResult); + + OperationResult retrievedOperationResult = new TopicContextManager(sessionStorageMock).fetchMetadataByContext(reportUnit); + //Then + assertSame(resourceGroupElementOperationResult, retrievedOperationResult); + } + +} \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/DomainServiceTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/DomainServiceTest.java new file mode 100644 index 00000000..9ff6a216 --- /dev/null +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/DomainServiceTest.java @@ -0,0 +1,85 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.domain; + +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.domain.metadata.DomainMetadataAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.MandatoryParameterNotFoundException; +import org.mockito.Mock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.testng.PowerMockTestCase; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import static org.mockito.Mockito.times; +import static org.mockito.MockitoAnnotations.initMocks; +import static org.powermock.api.mockito.PowerMockito.verifyNew; +import static org.powermock.api.mockito.PowerMockito.whenNew; +import static org.testng.Assert.assertSame; + +/** + * Unit tests for {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.attributes.AttributesService} + */ +@PrepareForTest({DomainService.class}) +public class DomainServiceTest extends PowerMockTestCase { + + public static final String URI = "uri"; + @Mock + private SessionStorage sessionStorageMock; + @Mock + private DomainMetadataAdapter domainMetadataAdapterMock; + + + @BeforeMethod + public void before() { + initMocks(this); + } + + @Test + public void should_pass_session_storage_to_parent_adapter() { + DomainService domainService = new DomainService(sessionStorageMock); + SessionStorage retrieved = domainService.getSessionStorage(); + assertSame(retrieved, sessionStorageMock); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void should_throw_an_exception_when_sessionStorage_is_null() { + // When + new DomainService(null); + // Then + // should be thrown an exception + } + + @Test(expectedExceptions = MandatoryParameterNotFoundException.class) + public void should_throw_an_exception_when_domain_uri_is_null() { + // When + new DomainService(sessionStorageMock).forDomain((String) null); + // Then + // should be thrown an exception + } + + + @Test + public void should_return_proper_DomainMetadataAdapter_instance() throws Exception { + + // Given + whenNew(DomainMetadataAdapter.class) + .withArguments(sessionStorageMock, URI) + .thenReturn(domainMetadataAdapterMock); + + DomainService domainService = new DomainService(sessionStorageMock); + + // When + DomainMetadataAdapter retrieved = domainService.forDomain(URI).metadata(); + + // Then + assertSame(retrieved, domainMetadataAdapterMock); + verifyNew(DomainMetadataAdapter.class, times(1)) + .withArguments(sessionStorageMock, URI); + } + + @AfterMethod + public void after() { + sessionStorageMock = null; + domainMetadataAdapterMock = null; + } +} \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/DomainMetadataAdapterTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/metadata/DomainMetadataAdapterTest.java similarity index 87% rename from src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/DomainMetadataAdapterTest.java rename to src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/metadata/DomainMetadataAdapterTest.java index 61bca244..6610b1e9 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/DomainMetadataAdapterTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/metadata/DomainMetadataAdapterTest.java @@ -1,6 +1,7 @@ -package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.domain;//package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.domain; +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.domain.metadata;//package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.domain; import com.jaspersoft.jasperserver.dto.domain.DomainMetaData; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.domain.metadata.DomainMetadataAdapter; import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.ErrorHandler; @@ -21,7 +22,7 @@ import static org.testng.Assert.assertEquals; /** - * Unit tests for {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.domain.DomainMetadataAdapter} + * Unit tests for {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.domain.metadata.DomainMetadataAdapter} */ @PrepareForTest(JerseyRequest.class) public class DomainMetadataAdapterTest extends PowerMockTestCase { @@ -45,7 +46,7 @@ public void setUp() throws Exception { } /** - * The constructor under test is {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.domain.DomainMetadataAdapter#DomainMetadataAdapter(com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage, String)} + * The constructor under test is {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.domain.metadata.DomainMetadataAdapter#DomainMetadataAdapter(com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage, String)} */ @Test(testName = "DomainMetadataAdapter_constructor") public void should_pass_not_null_SessionStorage_and_domainUri_to_super_class_without_any_changes() { diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/newDomain/DomainAdapterTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/newDomain/DomainAdapterTest.java new file mode 100644 index 00000000..e317a64e --- /dev/null +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/newDomain/DomainAdapterTest.java @@ -0,0 +1,203 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.domain.newDomain; + + +import com.jaspersoft.jasperserver.dto.resources.domain.ClientDomain; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.RestClientConfiguration; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.MimeType; +import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import java.util.ArrayList; +import java.util.List; +import org.mockito.Mock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.testng.PowerMockTestCase; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import static com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest.buildRequest; +import static java.util.Arrays.asList; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; +import static org.mockito.internal.util.reflection.Whitebox.getInternalState; +import static org.powermock.api.mockito.PowerMockito.doReturn; +import static org.powermock.api.mockito.PowerMockito.mock; +import static org.powermock.api.mockito.PowerMockito.mockStatic; +import static org.powermock.api.mockito.PowerMockito.spy; +import static org.powermock.api.mockito.PowerMockito.verifyNoMoreInteractions; +import static org.powermock.api.mockito.PowerMockito.verifyPrivate; +import static org.powermock.api.mockito.PowerMockito.verifyStatic; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertSame; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +@PrepareForTest({DomainAdapter.class, JerseyRequest.class}) +public class DomainAdapterTest extends PowerMockTestCase { + + public static final String URI = "uri"; + public static final List path = asList("resources", "uri"); + public static final String CONTENT_TYPE = "application/repository.domain+json"; + @Mock + private SessionStorage sessionStorageMock; + + @Mock + private JerseyRequest requestMock; + + @Mock + private OperationResult resultMock; + + @BeforeMethod + public void before() { + initMocks(this); + } + + @Test + public void should_pass_proper_session_storage_to_parent_class_and_set_own_fields() { + + // When + DomainAdapter adapter = new DomainAdapter(sessionStorageMock, URI); + ArrayList uri = (ArrayList) getInternalState(adapter, "path"); + + // Then + assertNotNull(adapter); + assertEquals(uri, path); + assertSame(adapter.getSessionStorage(), sessionStorageMock); + } + + @Test + public void should_invoke_private_method_and_return_a_mock_when_get() throws Exception { + + // Given + DomainAdapter adapter = spy(new DomainAdapter(sessionStorageMock, URI)); + RestClientConfiguration configurationMock = mock(RestClientConfiguration.class); + doReturn(MimeType.JSON).when(configurationMock).getAcceptMimeType(); + doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); + doReturn(requestMock).when(requestMock).setAccept(CONTENT_TYPE); + doReturn(requestMock).when(adapter, "buildRequest"); + doReturn(resultMock).when(requestMock).get(); + + // When + adapter.get(); + + // Then + verifyPrivate(adapter, times(1)).invoke("buildRequest"); + verify(requestMock, times(1)).get(); + verify(requestMock, times(1)).setAccept(CONTENT_TYPE); + verifyNoMoreInteractions(requestMock); + } + + @Test + public void should_invoke_private_method_and_return_a_mock_when_create() throws Exception { + + // Given + DomainAdapter adapter = spy(new DomainAdapter(sessionStorageMock, URI)); + + ClientDomain domain = new ClientDomain(); + RestClientConfiguration configurationMock = mock(RestClientConfiguration.class); + doReturn(MimeType.JSON).when(configurationMock).getAcceptMimeType(); + doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); + doReturn(requestMock).when(requestMock).setContentType(CONTENT_TYPE); + doReturn(requestMock).when(adapter, "buildRequest"); + doReturn(resultMock).when(requestMock).post(domain); + + // When + adapter.create(domain); + + // Then + verifyPrivate(adapter, times(1)).invoke("buildRequest"); + verify(requestMock, times(1)).post(domain); + verify(requestMock, times(1)).setContentType(CONTENT_TYPE); + verifyNoMoreInteractions(requestMock); + } + + @Test + public void should_invoke_private_method_and_return_a_mock_when_update() throws Exception { + + // Given + DomainAdapter adapter = spy(new DomainAdapter(sessionStorageMock, URI)); + ClientDomain domain = new ClientDomain(); + + RestClientConfiguration configurationMock = mock(RestClientConfiguration.class); + doReturn(MimeType.JSON).when(configurationMock).getAcceptMimeType(); + doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); + doReturn(requestMock).when(requestMock).setContentType(CONTENT_TYPE); + doReturn(requestMock).when(adapter, "buildRequest");; + doReturn(resultMock).when(requestMock).put(domain); + + // When + adapter.update(domain); + + // Then + verifyPrivate(adapter, times(1)).invoke("buildRequest"); + verify(requestMock, times(1)).put(domain); + verify(requestMock, times(1)).setContentType(CONTENT_TYPE); + verifyNoMoreInteractions(requestMock); + } + + @Test + public void should_invoke_private_method_and_return_a_mock_when_delete() throws Exception { + + // Given + DomainAdapter adapter = spy(new DomainAdapter(sessionStorageMock, URI)); + + doReturn(requestMock).when(adapter, "buildRequest"); + doReturn(resultMock).when(requestMock).delete(); + + // When + adapter.delete(); + + // Then + verifyPrivate(adapter, times(1)).invoke("buildRequest"); + verify(requestMock, times(1)).delete(); + verifyNoMoreInteractions(requestMock); + } + + @Test + public void should_invoke_private_static_method() { + + // Given + final DomainAdapter adapter = new DomainAdapter(sessionStorageMock, URI); + mockStatic(JerseyRequest.class); + when(buildRequest(eq(sessionStorageMock), eq(ClientDomain.class), + eq(new String[]{"resources", URI}), any(DefaultErrorHandler.class))) + .thenReturn(requestMock); + RestClientConfiguration configurationMock = mock(RestClientConfiguration.class); + doReturn(MimeType.JSON).when(configurationMock).getAcceptMimeType(); + doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); + doReturn(requestMock).when(requestMock).setAccept(CONTENT_TYPE); + doReturn(resultMock).when(requestMock).get(); + + // When + OperationResult retrieved = adapter.get(); + + // Then + assertNotNull(retrieved); + verifyStatic(times(1)); + buildRequest(eq(sessionStorageMock), + eq(ClientDomain.class), + eq(new String[]{"resources", URI}), + any(DefaultErrorHandler.class)); + verify(requestMock, times(1)).get(); + verify(requestMock, times(1)).setAccept(CONTENT_TYPE); + } + + @AfterMethod + public void after() { + reset(sessionStorageMock, requestMock, resultMock); + } +} \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/schema/DomainSchemaAdapterTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/schema/DomainSchemaAdapterTest.java new file mode 100644 index 00000000..ca8635e9 --- /dev/null +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/domain/schema/DomainSchemaAdapterTest.java @@ -0,0 +1,209 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.domain.schema; + +import com.jaspersoft.jasperserver.dto.resources.ClientFile; +import com.jaspersoft.jasperserver.dto.resources.domain.Schema; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.RestClientConfiguration; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.MimeType; +import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; +import java.io.File; +import java.util.List; +import javax.ws.rs.core.MediaType; +import org.mockito.Mock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.testng.PowerMockTestCase; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import static com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest.buildRequest; +import static java.util.Arrays.asList; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; +import static org.mockito.internal.util.reflection.Whitebox.getInternalState; +import static org.powermock.api.mockito.PowerMockito.doReturn; +import static org.powermock.api.mockito.PowerMockito.mock; +import static org.powermock.api.mockito.PowerMockito.mockStatic; +import static org.powermock.api.mockito.PowerMockito.spy; +import static org.powermock.api.mockito.PowerMockito.verifyNoMoreInteractions; +import static org.powermock.api.mockito.PowerMockito.verifyPrivate; +import static org.powermock.api.mockito.PowerMockito.verifyStatic; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertSame; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +@PrepareForTest({JerseyRequest.class}) +public class DomainSchemaAdapterTest extends PowerMockTestCase { + + public static final String URI = "domainSchemaUri"; + public static final List path = asList("resources", URI); + public static final String CONTENT_TYPE = "application/repository.domainSchema+json"; + @Mock + private SessionStorage sessionStorageMock; + + @Mock + private JerseyRequest requestMock; + + @Mock + private OperationResult resultMock; + + @Mock + private JerseyRequest fileJerseyRequestMock; + + @Mock + private OperationResult fileOperationResultMock; + + @BeforeMethod + public void before() { + initMocks(this); + } + + @Test + public void should_pass_proper_session_storage_to_parent_class_and_set_own_fields() { + + // When + DomainSchemaAdapter adapter = new DomainSchemaAdapter(sessionStorageMock, URI); + List uri = (List ) getInternalState(adapter, "path"); + + // Then + assertNotNull(adapter); + assertEquals(uri, path); + assertSame(adapter.getSessionStorage(), sessionStorageMock); + } + + @Test + public void should_invoke_private_method_and_return_a_mock_when_get() throws Exception { + + // Given + DomainSchemaAdapter adapter = spy(new DomainSchemaAdapter(sessionStorageMock, URI)); + RestClientConfiguration configurationMock = mock(RestClientConfiguration.class); + doReturn(MimeType.JSON).when(configurationMock).getAcceptMimeType(); + doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); + doReturn(requestMock).when(requestMock).setAccept(CONTENT_TYPE); + doReturn(requestMock).when(adapter, "buildRequest"); + doReturn(resultMock).when(requestMock).get(); + + // When + adapter.get(); + + // Then + verifyPrivate(adapter, times(1)).invoke("buildRequest"); + verify(requestMock, times(1)).get(); + verify(requestMock, times(1)).setAccept(CONTENT_TYPE); + verifyNoMoreInteractions(requestMock); + } + + @Test + public void should_invoke_private_method_and_return_a_mock_when_update() throws Exception { + + // Given + DomainSchemaAdapter adapter = spy(new DomainSchemaAdapter(sessionStorageMock, URI)); + Schema schema = new Schema(); + + RestClientConfiguration configurationMock = mock(RestClientConfiguration.class); + doReturn(MimeType.JSON).when(configurationMock).getAcceptMimeType(); + doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); + doReturn(requestMock).when(requestMock).setContentType(CONTENT_TYPE); + doReturn(requestMock).when(adapter, "buildRequest"); + doReturn(resultMock).when(requestMock).put(schema); + + // When + adapter.update(schema); + + // Then + verifyPrivate(adapter, times(1)).invoke("buildRequest"); + verify(requestMock, times(1)).put(schema); + verify(requestMock, times(1)).setContentType(CONTENT_TYPE); + verifyNoMoreInteractions(requestMock); + } + + @Test(enabled = true) + public void should_involve_protected_methods() throws Exception { + + // Given + DomainSchemaAdapter adapter = spy(new DomainSchemaAdapter(sessionStorageMock, URI)); + mockStatic(JerseyRequest.class); + when(buildRequest(eq(sessionStorageMock), eq(ClientFile.class), + eq(new String[]{"resources", URI}))) + .thenReturn(fileJerseyRequestMock); + doReturn(fileJerseyRequestMock).when(fileJerseyRequestMock).setContentType(MediaType.MULTIPART_FORM_DATA); + doReturn(fileOperationResultMock).when(fileJerseyRequestMock).post(any(FormDataMultiPart.class)); + + // When + OperationResult result = adapter.upload("path", "name", "description"); + + // Then + assertEquals(fileOperationResultMock, result); + verify(fileJerseyRequestMock, times(1)).setContentType(MediaType.MULTIPART_FORM_DATA); + verify(fileJerseyRequestMock, times(1)).post(any(FormDataMultiPart.class)); + + } + + @Test + public void should_invoke_private_method_and_return_a_mock_when_upload() throws Exception { + + // Given + DomainSchemaAdapter adapter = spy(new DomainSchemaAdapter(sessionStorageMock, URI)); + File file = new File("path"); + doReturn(resultMock) + .when(adapter).uploadFile(file, ClientFile.FileType.xml, "name", "description"); + + // When + OperationResult result = adapter.upload("path", "name", "description"); + + // Then + verify(adapter, times(1)).uploadFile(file, ClientFile.FileType.xml, "name", "description"); + assertEquals(resultMock, result); + } + + + @Test + public void should_involve_static_method() { + + // Given + DomainSchemaAdapter schemaAdapter = new DomainSchemaAdapter(sessionStorageMock, URI); + mockStatic(JerseyRequest.class); + when(buildRequest(eq(sessionStorageMock), eq(Schema.class), + eq(new String[]{"resources", URI}), any(DefaultErrorHandler.class))) + .thenReturn(requestMock); + RestClientConfiguration configurationMock = mock(RestClientConfiguration.class); + doReturn(MimeType.JSON).when(configurationMock).getAcceptMimeType(); + doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); + doReturn(requestMock).when(requestMock).setAccept(CONTENT_TYPE); + doReturn(resultMock).when(requestMock).get(); + + // When + OperationResult retrieved = schemaAdapter.get(); + + // Then + assertNotNull(retrieved); + verifyStatic(times(1)); + buildRequest(eq(sessionStorageMock), + eq(Schema.class), + eq(new String[]{"resources", URI}), + any(DefaultErrorHandler.class)); + verify(requestMock, times(1)).get(); + verify(requestMock, times(1)).setAccept(CONTENT_TYPE); + } + + @AfterMethod + public void after() { + reset(sessionStorageMock, requestMock, resultMock, fileJerseyRequestMock, fileOperationResultMock); + } +} \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/exportservice/ExportTaskAdapterTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/exportservice/ExportTaskAdapterTest.java index d3cbb7e9..262ad3de 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/exportservice/ExportTaskAdapterTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/exportservice/ExportTaskAdapterTest.java @@ -1,5 +1,7 @@ package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.importexport.exportservice; +import com.jaspersoft.jasperserver.dto.importexport.ExportTask; +import com.jaspersoft.jasperserver.dto.importexport.State; import com.jaspersoft.jasperserver.jaxrs.client.core.Callback; import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; import com.jaspersoft.jasperserver.jaxrs.client.core.RequestBuilder; @@ -7,8 +9,10 @@ import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; -import com.jaspersoft.jasperserver.dto.importexport.ExportTask; -import com.jaspersoft.jasperserver.dto.importexport.State; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; import org.mockito.Mock; import org.mockito.internal.util.reflection.Whitebox; import org.powermock.api.mockito.PowerMockito; @@ -18,14 +22,11 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; - import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; @@ -41,6 +42,7 @@ import static org.testng.Assert.assertNotSame; import static org.testng.Assert.assertSame; import static org.testng.Assert.assertTrue; +import static org.testng.Assert.assertNull; /** * Unit tests for {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.importexport.exportservice.ExportTaskAdapter} @@ -94,10 +96,10 @@ public void should_create_an_object_and_prepare_ExportTaskDto_field() throws Ill assertNotNull(retrievedField); assertTrue(instanceOf(ExportTask.class).matches(retrievedField)); - assertNotNull(((ExportTask) retrievedField).getParameters()); - assertNotNull(((ExportTask) retrievedField).getRoles()); - assertNotNull(((ExportTask) retrievedField).getUsers()); - assertNotNull(((ExportTask) retrievedField).getUris()); + assertNull(((ExportTask) retrievedField).getParameters()); + assertNull(((ExportTask) retrievedField).getRoles()); + assertNull(((ExportTask) retrievedField).getUsers()); + assertNull(((ExportTask) retrievedField).getUris()); } @Test(testName = "role") @@ -115,6 +117,20 @@ public void should_add_new_role_to_roles_of_ExportTaskDto() throws IllegalAccess assertTrue(retrieved.getRoles().contains(newRole)); } + @Test(testName = "allRoles") + public void should_add_emptyList_to_roles_of_ExportTaskDto() throws IllegalAccessException { + ExportTaskAdapter adapter = spy(new ExportTaskAdapter(sessionStorageMock)); + ExportTaskAdapter retrievedAdapter = adapter.allRoles(); + + Field field = field(ExportTaskAdapter.class, EXPORT_TASK_DTO); + ExportTask retrieved = (ExportTask) field.get(adapter); + + verify(adapter, never()).role(anyString()); + assertNotNull(retrievedAdapter); + assertNotNull(retrieved.getRoles()); + assertTrue(retrieved.getRoles().isEmpty()); + } + @Test(testName = "roles") public void should_add_new_roles_of_ExportTaskDto_as_list() throws IllegalAccessException { @@ -179,6 +195,24 @@ public void should_add_bunch_of_users_to_userList_of_ExportTaskDto() throws Ille assertTrue(exportTaskDto.getUsers().contains("Angelina")); } + @Test(testName = "users") + public void should_add_emptyList_to_userList_of_ExportTaskDto() throws IllegalAccessException { + + // Given + ExportTaskAdapter adapter = spy(new ExportTaskAdapter(sessionStorageMock)); + + // When + ExportTaskAdapter retrievedAdapter = adapter.allUsers(); + Field field = field(ExportTaskAdapter.class, EXPORT_TASK_DTO); + ExportTask exportTaskDto = (ExportTask) field.get(adapter); + + // Then + verify(adapter, never()).user(anyString()); + assertNotNull(retrievedAdapter); + assertNotNull(exportTaskDto.getUsers()); + assertTrue(exportTaskDto.getUsers().isEmpty()); + } + @Test(testName = "organization") public void should_add_an_organization_to_ExportTaskDto() throws IllegalAccessException { String organization = "organization"; diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/importservice/ImportRequestAdapterTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/importservice/ImportRequestAdapterTest.java index 7f2d33ac..403f7af7 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/importservice/ImportRequestAdapterTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/importexport/importservice/ImportRequestAdapterTest.java @@ -53,6 +53,8 @@ public class ImportRequestAdapterTest extends PowerMockTestCase { @Mock private JerseyRequest taskRequestMock; + @Mock + private JerseyRequest deleteRequestMock; @Mock private OperationResult stateOperationResultMock; @@ -60,6 +62,9 @@ public class ImportRequestAdapterTest extends PowerMockTestCase { @Mock private OperationResult taskOperationResultMock; + @Mock + private OperationResult deleteOperationResultMock; + private String[] fakeArrayPathForState = new String[]{"import", TASK_ID, "state"}; private String[] fakeArrayPathForTask= new String[]{"import", TASK_ID}; @@ -162,8 +167,7 @@ public void should_return_proper_OperationResult_object_when_get_task() { PowerMockito.mockStatic(JerseyRequest.class); PowerMockito.when(JerseyRequest.buildRequest(eq(storageMock), eq(ImportTask.class), - eq(fakeArrayPathForTask), - any(DefaultErrorHandler.class))).thenReturn(taskRequestMock); + eq(fakeArrayPathForTask))).thenReturn(taskRequestMock); PowerMockito.when(taskRequestMock.get()).thenReturn(taskOperationResultMock); // When @@ -181,8 +185,7 @@ public void should_return_proper_OperationResult_object_when_restart_task() { PowerMockito.mockStatic(JerseyRequest.class); PowerMockito.when(JerseyRequest.buildRequest(eq(storageMock), eq(ImportTask.class), - eq(fakeArrayPathForTask), - any(DefaultErrorHandler.class))).thenReturn(taskRequestMock); + eq(fakeArrayPathForTask))).thenReturn(taskRequestMock); PowerMockito.when(taskRequestMock.put(importTask)).thenReturn(taskOperationResultMock); // When @@ -197,17 +200,16 @@ public void should_return_proper_OperationResult_object_when_cancel_task() { // Given PowerMockito.mockStatic(JerseyRequest.class); PowerMockito.when(JerseyRequest.buildRequest(eq(storageMock), - eq(ImportTask.class), - eq(fakeArrayPathForTask), - any(DefaultErrorHandler.class))).thenReturn(taskRequestMock); - PowerMockito.when(taskRequestMock.delete()).thenReturn(taskOperationResultMock); + eq(Object.class), + eq(fakeArrayPathForTask))).thenReturn(deleteRequestMock); + PowerMockito.when(deleteRequestMock.delete()).thenReturn(deleteOperationResultMock); // When ImportRequestAdapter adapter = new ImportRequestAdapter(storageMock, TASK_ID); OperationResult opResult = adapter.cancelTask(); // Then - assertSame(opResult, taskOperationResultMock); + assertSame(opResult, deleteOperationResultMock); } @Test diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/inputControls/InputControlsAdapterTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/inputControls/InputControlsAdapterTest.java index d98811ff..724aeff9 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/inputControls/InputControlsAdapterTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/inputControls/InputControlsAdapterTest.java @@ -5,7 +5,6 @@ import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.MandatoryParameterNotFoundException; -import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; import java.util.LinkedList; import org.mockito.Mock; @@ -18,10 +17,10 @@ import org.testng.annotations.Test; import static com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest.buildRequest; -import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.reset; import static org.mockito.MockitoAnnotations.initMocks; import static org.powermock.api.mockito.PowerMockito.doReturn; import static org.powermock.api.mockito.PowerMockito.mockStatic; @@ -29,7 +28,6 @@ import static org.powermock.api.mockito.PowerMockito.verifyStatic; import static org.powermock.api.mockito.PowerMockito.when; import static org.powermock.api.mockito.PowerMockito.whenNew; -import static org.mockito.Mockito.reset; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertSame; @@ -103,8 +101,7 @@ public void should_return_proper_operation_result_when_invoke_get() { when(buildRequest( eq(sessionStorageMock), eq(ReportInputControlsListWrapper.class), - eq(new String[]{"reports", uri, "inputControls"}), - any(DefaultErrorHandler.class)) + eq(new String[]{"reports", uri, "inputControls"})) ).thenReturn(requestMock); doReturn(operationResultMock) @@ -122,8 +119,7 @@ public void should_return_proper_operation_result_when_invoke_get() { buildRequest( eq(sessionStorageMock), eq(ReportInputControlsListWrapper.class), - eq(new String[]{"reports", uri, "inputControls"}), - any(DefaultErrorHandler.class)); + eq(new String[]{"reports", uri, "inputControls"})); Mockito.verify(requestMock).get(); assertEquals(Whitebox.getInternalState(adapterSpy, "containerUri"), uri); @@ -139,8 +135,7 @@ public void should_return_proper_operation_result_when_invoke_reorder() { when(buildRequest( eq(sessionStorageMock), eq(ReportInputControlsListWrapper.class), - eq(new String[]{"reports", uri, "inputControls"}), - any(DefaultErrorHandler.class)) + eq(new String[]{"reports", uri, "inputControls"})) ).thenReturn(requestMock); doReturn(operationResultMock) @@ -151,15 +146,15 @@ public void should_return_proper_operation_result_when_invoke_reorder() { adapterSpy.container(uri); // When - OperationResult retrieved = adapterSpy.reorder(new LinkedList()); + OperationResult retrieved = adapterSpy + .reorder(new LinkedList()); // Then verifyStatic(); buildRequest( eq(sessionStorageMock), eq(ReportInputControlsListWrapper.class), - eq(new String[]{"reports", uri, "inputControls"}), - any(DefaultErrorHandler.class)); + eq(new String[]{"reports", uri, "inputControls"})); Mockito.verify(requestMock).put(anyObject()); assertNotNull(retrieved); @@ -174,8 +169,7 @@ public void should_invoke_adding_parameter() { when(buildRequest( eq(sessionStorageMock), eq(ReportInputControlsListWrapper.class), - eq(new String[]{"reports", uri, "inputControls"}), - any(DefaultErrorHandler.class)) + eq(new String[]{"reports", uri, "inputControls"})) ).thenReturn(requestMock); doReturn(requestMock) @@ -196,8 +190,7 @@ public void should_invoke_adding_parameter() { buildRequest( eq(sessionStorageMock), eq(ReportInputControlsListWrapper.class), - eq(new String[]{"reports", uri, "inputControls"}), - any(DefaultErrorHandler.class)); + eq(new String[]{"reports", uri, "inputControls"})); Mockito.verify(requestMock).get(); Mockito.verify(requestMock).addParam("exclude", "state"); diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/inputControls/InputControlsValuesAdapterTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/inputControls/InputControlsValuesAdapterTest.java index 7ab3bf51..2dddd45b 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/inputControls/InputControlsValuesAdapterTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/inputControls/InputControlsValuesAdapterTest.java @@ -3,7 +3,6 @@ import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.MandatoryParameterNotFoundException; -import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.inputcontrols.InputControlStateListWrapper; import org.mockito.Mock; @@ -16,7 +15,6 @@ import org.testng.annotations.Test; import static com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest.buildRequest; -import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.reset; @@ -85,8 +83,7 @@ public void should_return_proper_operation_result_when_invoke_get() { when(buildRequest( eq(sessionStorageMock), eq(InputControlStateListWrapper.class), - eq(new String[]{"reports", uri, "inputControls", "", "values"}), - any(DefaultErrorHandler.class)) + eq(new String[]{"reports", uri, "inputControls", "values"})) ).thenReturn(requestMock); doReturn(operationResultMock) @@ -103,8 +100,7 @@ public void should_return_proper_operation_result_when_invoke_get() { buildRequest( eq(sessionStorageMock), eq(InputControlStateListWrapper.class), - eq(new String[]{"reports", uri, "inputControls", "", "values"}), - any(DefaultErrorHandler.class)); + eq(new String[]{"reports", uri, "inputControls", "values"})); Mockito.verify(requestMock).get(); assertEquals(Whitebox.getInternalState(adapterSpy, "containerUri"), uri); @@ -120,8 +116,7 @@ public void should_invoke_use_cashed_data() { when(buildRequest( eq(sessionStorageMock), eq(InputControlStateListWrapper.class), - eq(new String[]{"reports", uri, "inputControls", "", "values"}), - any(DefaultErrorHandler.class)) + eq(new String[]{"reports", uri, "inputControls", "values"})) ).thenReturn(requestMock); doReturn(requestMock) @@ -133,7 +128,7 @@ public void should_invoke_use_cashed_data() { .get(); InputControlsValuesAdapter adapterSpy = spy(new InputControlsValuesAdapter(sessionStorageMock, uri)); - adapterSpy.useCashedData(false); + adapterSpy.useCachedData(false); // When OperationResult retrieved = adapterSpy.get(); @@ -143,8 +138,7 @@ public void should_invoke_use_cashed_data() { buildRequest( eq(sessionStorageMock), eq(InputControlStateListWrapper.class), - eq(new String[]{"reports", uri, "inputControls", "", "values"}), - any(DefaultErrorHandler.class)); + eq(new String[]{"reports", uri, "inputControls", "values"})); Mockito.verify(requestMock).get(); Mockito.verify(requestMock).addParam("freshData", "true"); @@ -161,8 +155,7 @@ public void should_return_proper_operation_result__when_invoke_post() { when(buildRequest( eq(sessionStorageMock), eq(InputControlStateListWrapper.class), - eq(new String[]{"reports", uri, "inputControls", "param1;param2", "values"}), - any(DefaultErrorHandler.class)) + eq(new String[]{"reports", uri, "inputControls", "param1;param2", "values"})) ).thenReturn(requestMock); doReturn(operationResultMock) @@ -182,8 +175,7 @@ public void should_return_proper_operation_result__when_invoke_post() { buildRequest( eq(sessionStorageMock), eq(InputControlStateListWrapper.class), - eq(new String[]{"reports", uri, "inputControls", "param1;param2", "values"}), - any(DefaultErrorHandler.class)); + eq(new String[]{"reports", uri, "inputControls", "param1;param2", "values"})); Mockito.verify(requestMock).post(anyObject()); Mockito.verify(requestMock).post(anyObject()); @@ -199,8 +191,7 @@ public void should_invoke_include_full_structure() { when(buildRequest( eq(sessionStorageMock), eq(InputControlStateListWrapper.class), - eq(new String[]{"reports", uri, "inputControls", "", "values"}), - any(DefaultErrorHandler.class)) + eq(new String[]{"reports", uri, "inputControls", "values"})) ).thenReturn(requestMock); doReturn(operationResultMock) @@ -221,8 +212,7 @@ public void should_invoke_include_full_structure() { buildRequest( eq(sessionStorageMock), eq(InputControlStateListWrapper.class), - eq(new String[]{"reports", uri, "inputControls", "", "values"}), - any(DefaultErrorHandler.class)); + eq(new String[]{"reports", uri, "inputControls", "values"})); Mockito.verify(requestMock).post(anyObject()); assertEquals(Whitebox.getInternalState(adapterSpy, "includeFullStructure"), Boolean.TRUE); diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/BatchJobsOperationsAdapterTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/BatchJobsOperationsAdapterTest.java index e1460693..957d7fe7 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/BatchJobsOperationsAdapterTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/BatchJobsOperationsAdapterTest.java @@ -28,6 +28,7 @@ /** * @author Tetiana Iefimenko + * @deprecated */ @PrepareForTest({JerseyRequest.class}) public class BatchJobsOperationsAdapterTest extends PowerMockTestCase { diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/JobValidationErrorHandlerTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/JobValidationErrorHandlerTest.java index 97fdeece..3470852b 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/JobValidationErrorHandlerTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/JobValidationErrorHandlerTest.java @@ -24,6 +24,7 @@ /** * Unit tests for {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.JobValidationErrorHandler} + * @deprecated */ @PrepareForTest({DefaultErrorHandler.class, JobValidationErrorHandler.class}) public class JobValidationErrorHandlerTest extends PowerMockTestCase { diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/JobsServiceTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/JobsServiceTest.java index a41df645..d9935bba 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/JobsServiceTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/JobsServiceTest.java @@ -44,6 +44,7 @@ /** * Unit tests for {@link JobsService} + * @deprecated */ @PrepareForTest({JerseyRequest.class, JobsService.class}) public class JobsServiceTest extends PowerMockTestCase { diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/SingleJobOperationsAdapterTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/SingleJobOperationsAdapterTest.java index 3e37ffb8..2999d5ee 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/SingleJobOperationsAdapterTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/SingleJobOperationsAdapterTest.java @@ -41,6 +41,7 @@ /** * Unit tests for {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.SingleJobOperationsAdapter} + * @deprecated */ @PrepareForTest({JerseyRequest.class}) public class SingleJobOperationsAdapterTest extends PowerMockTestCase { diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/calendar/SingleCalendarOperationsAdapterTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/calendar/SingleCalendarOperationsAdapterTest.java index 3514d5eb..01cfe054 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/calendar/SingleCalendarOperationsAdapterTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/calendar/SingleCalendarOperationsAdapterTest.java @@ -16,6 +16,10 @@ import com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendars.HolidayCalendar; import com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendars.MonthlyCalendar; import com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendars.WeeklyCalendar; +import java.util.concurrent.atomic.AtomicInteger; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.internal.util.reflection.Whitebox; @@ -27,11 +31,6 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import java.util.concurrent.atomic.AtomicInteger; - import static com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest.buildRequest; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.mockito.Matchers.anyString; @@ -53,7 +52,8 @@ import static org.testng.AssertJUnit.assertTrue; /** - * Unit tests for {@link SingleCalendarOperationsAdapter} + * Unit tests for {@link SingleCalendarOperationsAdapter + * @deprecated */ @PrepareForTest({JerseyRequest.class, SingleCalendarOperationsAdapter.class, MultivaluedHashMap.class}) public class SingleCalendarOperationsAdapterTest extends PowerMockTestCase { @@ -91,9 +91,6 @@ public class SingleCalendarOperationsAdapterTest extends PowerMockTestCase { @Mock private Calendar calendarEntityMock; - @Mock - private Callback, Object> callbackMock; - @Mock private Callback, Object> callbackMock3; @@ -108,6 +105,14 @@ public void before() { paramsSpy = spy(new MultivaluedHashMap()); } + + @AfterMethod + public void after() { + reset(sessionStorageMock, requestMock, objRequestMock, getResultMock, delResultMock, + operationResultMock, reportJobCalendarMock, responseMock, withEntityOperationResultMock, + calendarEntityMock, builderMock, callbackMock3, responseMock); + } + @Test public void should_pass_proper_params_to_super_class() { @@ -209,7 +214,7 @@ public void convertToLocalCalendarType1() throws Exception { // Then assertEquals(retrieved.getEntity(), expected); - verifyPrivate(adapterSpy, times(1)).invoke("setCommonCalendarFields", eq(new BaseCalendar()), eq(reportJobCalendarMock)); + verifyPrivate(adapterSpy, times(1)).invoke("convertToLocalCalendarType", eq(getResultMock)); verify(getResultMock, times(1)).getEntity(); verify(reportJobCalendarMock, times(2)).getCalendarType(); } @@ -218,14 +223,14 @@ public void convertToLocalCalendarType1() throws Exception { public void convertToLocalCalendarType2() throws Exception { // Given - final Calendar expected = PowerMockito.mock(AnnualCalendar.class); + final AnnualCalendar expected = PowerMockito.mock(AnnualCalendar.class); Whitebox.setInternalState(expected, "calendarType", CalendarType.annual); PowerMockito.mockStatic(JerseyRequest.class); PowerMockito.when(buildRequest(sessionStorageMock, ReportJobCalendar.class, new String[]{"jobs", "calendars", "testCalendarName"})).thenReturn(requestMock); - PowerMockito.whenNew(AnnualCalendar.class).withNoArguments().thenReturn((AnnualCalendar) expected); + PowerMockito.whenNew(AnnualCalendar.class).withNoArguments().thenReturn(expected); PowerMockito.doReturn(getResultMock).when(requestMock).get(); PowerMockito.doReturn(responseMock).when(getResultMock).getResponse(); PowerMockito.doReturn(reportJobCalendarMock).when(getResultMock).getEntity(); @@ -248,14 +253,14 @@ public void convertToLocalCalendarType2() throws Exception { public void convertToLocalCalendarType3() throws Exception { // Given - final Calendar expected = PowerMockito.mock(CronCalendar.class); + final CronCalendar expected = PowerMockito.mock(CronCalendar.class); Whitebox.setInternalState(expected, "calendarType", CalendarType.cron); PowerMockito.mockStatic(JerseyRequest.class); PowerMockito.when(buildRequest(eq(sessionStorageMock), eq(ReportJobCalendar.class), eq(new String[]{"jobs", "calendars", "testCalendarName"}))).thenReturn(requestMock); - PowerMockito.whenNew(CronCalendar.class).withNoArguments().thenReturn((CronCalendar) expected); + PowerMockito.whenNew(CronCalendar.class).withNoArguments().thenReturn(expected); PowerMockito.doReturn(getResultMock).when(requestMock).get(); PowerMockito.doReturn(responseMock).when(getResultMock).getResponse(); PowerMockito.doReturn(reportJobCalendarMock).when(getResultMock).getEntity(); @@ -268,7 +273,8 @@ public void convertToLocalCalendarType3() throws Exception { // Then assertEquals(retrieved.getEntity(), expected); - verifyPrivate(adapterSpy, times(1)).invoke("setCommonCalendarFields", eq(new CronCalendar()), eq(reportJobCalendarMock)); + verifyPrivate(adapterSpy, times(1)).invoke("setCommonCalendarFields", expected, reportJobCalendarMock); + verifyPrivate(adapterSpy, times(1)).invoke("convertToLocalCalendarType", eq(getResultMock)); verify(getResultMock, times(1)).getEntity(); verify(reportJobCalendarMock, times(2)).getCalendarType(); } @@ -277,7 +283,7 @@ public void convertToLocalCalendarType3() throws Exception { public void convertToLocalCalendarType4() throws Exception { // Given - final Calendar expected = PowerMockito.mock(DailyCalendar.class); + final DailyCalendar expected = PowerMockito.mock(DailyCalendar.class); Whitebox.setInternalState(expected, "invertTimeRange", false); Whitebox.setInternalState(expected, "calendarType", CalendarType.daily); @@ -285,7 +291,7 @@ public void convertToLocalCalendarType4() throws Exception { PowerMockito.when(buildRequest(eq(sessionStorageMock), eq(ReportJobCalendar.class), eq(new String[]{"jobs", "calendars", "testCalendarName"}))).thenReturn(requestMock); - PowerMockito.whenNew(DailyCalendar.class).withNoArguments().thenReturn((DailyCalendar) expected); + PowerMockito.whenNew(DailyCalendar.class).withNoArguments().thenReturn(expected); PowerMockito.doReturn(getResultMock).when(requestMock).get(); PowerMockito.doReturn(responseMock).when(getResultMock).getResponse(); PowerMockito.doReturn(reportJobCalendarMock).when(getResultMock).getEntity(); @@ -294,11 +300,12 @@ public void convertToLocalCalendarType4() throws Exception { SingleCalendarOperationsAdapter adapterSpy = PowerMockito.spy(new SingleCalendarOperationsAdapter(sessionStorageMock, "testCalendarName")); // When - adapterSpy.get(); + OperationResult retrieved = adapterSpy.get(); // Then - //assertEquals(retrieved.getEntity(), expected); - verifyPrivate(adapterSpy, times(1)).invoke("setCommonCalendarFields", eq(new DailyCalendar()), eq(reportJobCalendarMock)); + assertEquals(retrieved.getEntity(), expected); + verifyPrivate(adapterSpy, times(1)).invoke("setCommonCalendarFields", expected, reportJobCalendarMock); + verifyPrivate(adapterSpy, times(1)).invoke("convertToLocalCalendarType", eq(getResultMock)); verify(getResultMock, times(1)).getEntity(); verify(reportJobCalendarMock, times(2)).getCalendarType(); } @@ -307,14 +314,14 @@ public void convertToLocalCalendarType4() throws Exception { public void convertToLocalCalendarType5() throws Exception { // Given - final Calendar expected = PowerMockito.mock(HolidayCalendar.class); + final HolidayCalendar expected = PowerMockito.mock(HolidayCalendar.class); Whitebox.setInternalState(expected, "calendarType", CalendarType.holiday); PowerMockito.mockStatic(JerseyRequest.class); PowerMockito.when(buildRequest(eq(sessionStorageMock), eq(ReportJobCalendar.class), eq(new String[]{"jobs", "calendars", "testCalendarName"}))).thenReturn(requestMock); - PowerMockito.whenNew(HolidayCalendar.class).withNoArguments().thenReturn((HolidayCalendar) expected); + PowerMockito.whenNew(HolidayCalendar.class).withNoArguments().thenReturn(expected); PowerMockito.doReturn(getResultMock).when(requestMock).get(); PowerMockito.doReturn(responseMock).when(getResultMock).getResponse(); PowerMockito.doReturn(reportJobCalendarMock).when(getResultMock).getEntity(); @@ -323,10 +330,13 @@ public void convertToLocalCalendarType5() throws Exception { SingleCalendarOperationsAdapter adapterSpy = PowerMockito.spy(new SingleCalendarOperationsAdapter(sessionStorageMock, "testCalendarName")); // When - adapterSpy.get(); + OperationResult retrieved = adapterSpy.get(); // Then - verifyPrivate(adapterSpy, times(1)).invoke("setCommonCalendarFields", eq(new HolidayCalendar()), eq(reportJobCalendarMock)); + assertEquals(retrieved.getEntity(), expected); + + verifyPrivate(adapterSpy, times(1)).invoke("setCommonCalendarFields", expected, reportJobCalendarMock); + verifyPrivate(adapterSpy, times(1)).invoke("convertToLocalCalendarType", eq(getResultMock)); verify(getResultMock, times(1)).getEntity(); verify(reportJobCalendarMock, times(2)).getCalendarType(); } @@ -335,14 +345,14 @@ public void convertToLocalCalendarType5() throws Exception { public void convertToLocalCalendarType6() throws Exception { // Given - final Calendar expected = PowerMockito.mock(MonthlyCalendar.class); + final MonthlyCalendar expected = PowerMockito.mock(MonthlyCalendar.class); Whitebox.setInternalState(expected, "calendarType", CalendarType.monthly); PowerMockito.mockStatic(JerseyRequest.class); PowerMockito.when(buildRequest(eq(sessionStorageMock), eq(ReportJobCalendar.class), eq(new String[]{"jobs", "calendars", "testCalendarName"}))).thenReturn(requestMock); - PowerMockito.whenNew(MonthlyCalendar.class).withNoArguments().thenReturn((MonthlyCalendar) expected); + PowerMockito.whenNew(MonthlyCalendar.class).withNoArguments().thenReturn(expected); PowerMockito.doReturn(getResultMock).when(requestMock).get(); PowerMockito.doReturn(responseMock).when(getResultMock).getResponse(); PowerMockito.doReturn(reportJobCalendarMock).when(getResultMock).getEntity(); @@ -351,10 +361,12 @@ public void convertToLocalCalendarType6() throws Exception { SingleCalendarOperationsAdapter adapterSpy = PowerMockito.spy(new SingleCalendarOperationsAdapter(sessionStorageMock, "testCalendarName")); // When - adapterSpy.get(); + OperationResult retrieved = adapterSpy.get(); // Then - verifyPrivate(adapterSpy, times(1)).invoke("setCommonCalendarFields", eq(new MonthlyCalendar()), eq(reportJobCalendarMock)); + assertEquals(retrieved.getEntity(), expected); + verifyPrivate(adapterSpy, times(1)).invoke("setCommonCalendarFields", expected, reportJobCalendarMock); + verifyPrivate(adapterSpy, times(1)).invoke("convertToLocalCalendarType", eq(getResultMock)); verify(getResultMock, times(1)).getEntity(); verify(reportJobCalendarMock, times(2)).getCalendarType(); } @@ -363,14 +375,14 @@ public void convertToLocalCalendarType6() throws Exception { public void convertToLocalCalendarType7() throws Exception { // Given - final Calendar expected = PowerMockito.mock(WeeklyCalendar.class); + final WeeklyCalendar expected = PowerMockito.mock(WeeklyCalendar.class); Whitebox.setInternalState(expected, "calendarType", CalendarType.weekly); PowerMockito.mockStatic(JerseyRequest.class); PowerMockito.when(buildRequest(eq(sessionStorageMock), eq(ReportJobCalendar.class), eq(new String[]{"jobs", "calendars", "testCalendarName"}))).thenReturn(requestMock); - PowerMockito.whenNew(WeeklyCalendar.class).withNoArguments().thenReturn((WeeklyCalendar) expected); + PowerMockito.whenNew(WeeklyCalendar.class).withNoArguments().thenReturn(expected); PowerMockito.doReturn(getResultMock).when(requestMock).get(); PowerMockito.doReturn(responseMock).when(getResultMock).getResponse(); PowerMockito.doReturn(reportJobCalendarMock).when(getResultMock).getEntity(); @@ -379,10 +391,12 @@ public void convertToLocalCalendarType7() throws Exception { SingleCalendarOperationsAdapter adapterSpy = PowerMockito.spy(new SingleCalendarOperationsAdapter(sessionStorageMock, "testCalendarName")); // When - adapterSpy.get(); + OperationResult retrieved = adapterSpy.get(); // Then - verifyPrivate(adapterSpy, times(1)).invoke("setCommonCalendarFields", eq(new WeeklyCalendar()), eq(reportJobCalendarMock)); + assertEquals(retrieved.getEntity(), expected); + verifyPrivate(adapterSpy, times(1)).invoke("setCommonCalendarFields", expected, reportJobCalendarMock); + verifyPrivate(adapterSpy, times(1)).invoke("convertToLocalCalendarType", eq(getResultMock)); verify(getResultMock, times(1)).getEntity(); verify(reportJobCalendarMock, times(2)).getCalendarType(); } @@ -579,10 +593,4 @@ public Void execute(OperationResult data) { Mockito.verify(callback).execute(delResultMock); } - @AfterMethod - public void after() { - reset(sessionStorageMock, requestMock, objRequestMock, getResultMock, delResultMock, - operationResultMock, reportJobCalendarMock, responseMock, withEntityOperationResultMock, - calendarEntityMock); - } } \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/calendar/SingleCalendarOperationsAdapterTestNew.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/calendar/SingleCalendarOperationsAdapterTestNew.java new file mode 100644 index 00000000..2a9212dc --- /dev/null +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobs/calendar/SingleCalendarOperationsAdapterTestNew.java @@ -0,0 +1,375 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.calendar; + +import com.jaspersoft.jasperserver.dto.job.ClientJobCalendar; +import com.jaspersoft.jasperserver.jaxrs.client.core.Callback; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.RequestBuilder; +import com.jaspersoft.jasperserver.jaxrs.client.core.RequestExecution; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.WithEntityOperationResult; +import java.util.concurrent.atomic.AtomicInteger; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.internal.util.reflection.Whitebox; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.testng.PowerMockTestCase; +import org.testng.Assert; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import static com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest.buildRequest; +import static org.hamcrest.core.IsInstanceOf.instanceOf; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.MockitoAnnotations.initMocks; +import static org.powermock.api.mockito.PowerMockito.doReturn; +import static org.powermock.api.mockito.PowerMockito.mockStatic; +import static org.powermock.api.mockito.PowerMockito.spy; +import static org.powermock.api.mockito.PowerMockito.verifyStatic; +import static org.powermock.api.mockito.PowerMockito.when; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertSame; +import static org.testng.AssertJUnit.assertTrue; + +//import com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendar.Calendar; +//import com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendar.CronCalendar; +//import com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendar.DailyCalendar; +//import com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendar.HolidayCalendar; +//import com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendar.MonthlyCalendar; +//import com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.calendar.WeeklyCalendar; + +/** + * Unit tests for {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.calendar.SingleCalendarOperationsAdapter} + */ +@PrepareForTest({JerseyRequest.class, SingleCalendarOperationsAdapter.class, MultivaluedHashMap.class}) +public class SingleCalendarOperationsAdapterTestNew extends PowerMockTestCase { + + @Mock + private SessionStorage sessionStorageMock; + + @Mock + private JerseyRequest requestMock; + + @Mock + private JerseyRequest objRequestMock; + + @Mock + private OperationResult delResultMock; + + @Mock + private OperationResult operationResultMock; + + @Mock + private ClientJobCalendar reportJobCalendarMock; + + @Mock + private Response responseMock; + + @Mock + private RequestBuilder builderMock; + + @Mock + private WithEntityOperationResult withEntityOperationResultMock; + + @Mock + private ClientJobCalendar calendarEntityMock; + + @Mock + private Callback, Object> callbackMock; + + @Mock + private Callback, Object> callbackMock3; + + @Mock + private Callback resultObjectCallbackMock; + + private MultivaluedHashMap paramsSpy; + + @BeforeMethod + public void before() { + initMocks(this); + paramsSpy = spy(new MultivaluedHashMap()); + } + + @Test + public void should_pass_proper_params_to_super_class() { + + // When + SingleCalendarOperationsAdapter calendarOperationsAdapter = + new SingleCalendarOperationsAdapter(sessionStorageMock, "testCalendarName"); + + // Then + assertSame(calendarOperationsAdapter.getSessionStorage(), sessionStorageMock); + Object calendarName = Whitebox.getInternalState(calendarOperationsAdapter, "calendarName"); + Object params = Whitebox.getInternalState(calendarOperationsAdapter, "params"); + + assertNotNull(params); + assertSame(calendarName, "testCalendarName"); + + assertTrue(instanceOf(String.class).matches(calendarName)); + assertTrue(instanceOf(MultivaluedHashMap.class).matches(params)); + + + } + + @Test + @SuppressWarnings("unchecked") + public void should_set_parameter_field_of_adapter() { + + // Given + SingleCalendarOperationsAdapter adapter = new SingleCalendarOperationsAdapter(sessionStorageMock, "MyCal"); + + // When + adapter.parameter(CalendarParameter.REPLACE, "true"); + MultivaluedMap params = (MultivaluedMap) Whitebox.getInternalState(adapter, "params"); + + // Then + Assert.assertTrue(Boolean.valueOf(params.get("replace").get(0))); + } + + @Test(enabled = true) + public void parameter() throws Exception { + + // Given + PowerMockito.whenNew(MultivaluedHashMap.class).withNoArguments().thenReturn(paramsSpy); + SingleCalendarOperationsAdapter adapterSpy = Mockito.spy(new SingleCalendarOperationsAdapter(sessionStorageMock, "testCalendarName")); + + // When + SingleCalendarOperationsAdapter retrieved = adapterSpy.parameter(CalendarParameter.UPDATE_TRIGGERS, "testValue"); + + // Then + verify(adapterSpy, times(1)).parameter(CalendarParameter.UPDATE_TRIGGERS, "testValue"); + verify(paramsSpy, times(1)).add(CalendarParameter.UPDATE_TRIGGERS.getName(), "testValue"); + verify(paramsSpy, never()).getFirst(anyString()); + + Assert.assertSame(retrieved, adapterSpy); + Assert.assertTrue(paramsSpy.size() == 1); + } + + @Test + public void get() throws Exception { + + // Given + SingleCalendarOperationsAdapter adapterSpy = spy(new SingleCalendarOperationsAdapter(sessionStorageMock, + "testCalendarName")); + mockStatic(JerseyRequest.class); + when(buildRequest(eq(sessionStorageMock), eq(ClientJobCalendar.class), + eq(new String[]{"jobs", "calendars", "testCalendarName"}))).thenReturn(requestMock); + doReturn(operationResultMock).when(requestMock).get(); + + // When + OperationResult retrieved = adapterSpy.getCalendar(); + + // Then + verifyStatic(times(1)); + buildRequest(eq(sessionStorageMock), eq(ClientJobCalendar.class), + eq(new String[]{"jobs", "calendars", "testCalendarName"})); + assertSame(retrieved, operationResultMock); + } + + @Test + public void delete() throws Exception { + + // Given + mockStatic(JerseyRequest.class); + when(buildRequest(eq(sessionStorageMock), + eq(Object.class), + eq(new String[]{"jobs", "calendars", "testCalendarName"}))).thenReturn(objRequestMock); + doReturn(delResultMock).when(objRequestMock).delete(); + SingleCalendarOperationsAdapter adapterSpy = spy(new SingleCalendarOperationsAdapter(sessionStorageMock, "testCalendarName")); + + // When + OperationResult retrieved = adapterSpy.delete(); + + // Then + verifyStatic(times(1)); + buildRequest(eq(sessionStorageMock), eq(Object.class), eq(new String[]{"jobs", "calendars", "testCalendarName"})); + assertSame(retrieved, delResultMock); + } + + @Test + @SuppressWarnings("unchecked") + public void createNew() { + + // Given + mockStatic(JerseyRequest.class); + when(buildRequest(eq(sessionStorageMock), + eq(ClientJobCalendar.class), + eq(new String[]{"jobs", "calendars", "testCalendarName"}))).thenReturn(requestMock); + PowerMockito.when(requestMock.put(calendarEntityMock)).thenReturn(operationResultMock); + SingleCalendarOperationsAdapter adapterSpy = spy(new SingleCalendarOperationsAdapter(sessionStorageMock, "testCalendarName")); + + // When + OperationResult retrieved = adapterSpy.createNewCalendar(calendarEntityMock); + + // Then + verifyStatic(times(1)); + buildRequest(eq(sessionStorageMock), + eq(ClientJobCalendar.class), + eq(new String[]{"jobs", "calendars", "testCalendarName"})); + assertSame(retrieved, operationResultMock); + + MultivaluedMap retrievedParams = (MultivaluedMap) Whitebox.getInternalState(adapterSpy, "params"); + Mockito.verify(requestMock).addParams(retrievedParams); + Mockito.verify(requestMock).put(calendarEntityMock); + } + + @Test + public void asyncGet() throws Exception { + + // Given + final AtomicInteger newThreadId = new AtomicInteger(); + final int currentThreadId = (int) Thread.currentThread().getId(); + + PowerMockito.mockStatic(JerseyRequest.class); + PowerMockito.when( + buildRequest( + eq(sessionStorageMock), + eq(ClientJobCalendar.class), + eq(new String[]{"jobs", "calendars", "testCalendarName"}))) + .thenReturn(requestMock); + + SingleCalendarOperationsAdapter adapterSpy = spy(new SingleCalendarOperationsAdapter(sessionStorageMock, "testCalendarName")); + + Callback, Void> callback = PowerMockito.spy(new Callback, Void>() { + public Void execute(OperationResult data) { + newThreadId.set((int) Thread.currentThread().getId()); + synchronized (this) { + this.notify(); + } + return null; + } + }); + + PowerMockito.doReturn(operationResultMock).when(adapterSpy, "convertToLocalCalendarType", operationResultMock); + PowerMockito.doReturn(operationResultMock).when(requestMock).get(); + PowerMockito.doReturn(null).when(callback).execute(operationResultMock); + + // When + RequestExecution retrieved = adapterSpy.asyncGetCalendar(callback); + + // Wait + synchronized (callback) { + callback.wait(500); + } + + // Then + Assert.assertNotNull(retrieved); + Assert.assertNotSame(currentThreadId, newThreadId.get()); + } + + @Test(enabled = true) + public void asyncDelete() throws Exception { + + PowerMockito.mockStatic(JerseyRequest.class); + PowerMockito.when( + buildRequest( + eq(sessionStorageMock), + eq(Object.class), + eq(new String[]{"jobs", "calendars", "testCalendarName"}))) + .thenReturn(objRequestMock); + + SingleCalendarOperationsAdapter adapterSpy = spy(new SingleCalendarOperationsAdapter(sessionStorageMock, "testCalendarName")); + PowerMockito.doReturn(delResultMock).when(objRequestMock).delete(); + PowerMockito.doReturn(new Object()).when(resultObjectCallbackMock).execute(delResultMock); + + // When + adapterSpy.asyncDelete(resultObjectCallbackMock); + + // Then + verifyStatic(times(1)); + JerseyRequest.buildRequest( + eq(sessionStorageMock), + eq(Object.class), + eq(new String[]{"jobs", "calendars", "testCalendarName"})); + + } + + @Test + public void asyncCreateNew() throws Exception { + + PowerMockito.mockStatic(JerseyRequest.class); + PowerMockito.whenNew(MultivaluedHashMap.class).withNoArguments().thenReturn(paramsSpy); + PowerMockito.when( + buildRequest( + eq(sessionStorageMock), + eq(ClientJobCalendar.class), + eq(new String[]{"jobs", "calendars", "testCalendarName"}))) + .thenReturn(requestMock); + + SingleCalendarOperationsAdapter adapterSpy = PowerMockito.spy(new SingleCalendarOperationsAdapter(sessionStorageMock, "testCalendarName")); + + PowerMockito.doReturn(operationResultMock).when(requestMock).put(calendarEntityMock); + PowerMockito.doReturn(new Object()).when(callbackMock3).execute(operationResultMock); + PowerMockito.doReturn(builderMock).when(requestMock).addParams(paramsSpy); + // When + adapterSpy.asyncCreateNewCalendar(calendarEntityMock, callbackMock3); + + // Then + verifyStatic(times(1)); + JerseyRequest.buildRequest( + eq(sessionStorageMock), + eq(ClientJobCalendar.class), + eq(new String[]{"jobs", "calendars", "testCalendarName"})); + } + + @Test + public void should_delete_calendar_asynchronously() throws InterruptedException { + + /* Given */ + PowerMockito.mockStatic(JerseyRequest.class); + PowerMockito.when(buildRequest(eq(sessionStorageMock), + eq(Object.class), + eq(new String[]{"jobs", "calendars", "testCalendarName"}))).thenReturn(objRequestMock); + + PowerMockito.doReturn(delResultMock).when(objRequestMock).delete(); + + final AtomicInteger newThreadId = new AtomicInteger(); + final int currentThreadId = (int) Thread.currentThread().getId(); + + final Callback callback = PowerMockito.spy(new Callback() { + @Override + public Void execute(OperationResult data) { + newThreadId.set((int) Thread.currentThread().getId()); + synchronized (this) { + this.notify(); + } + return null; + } + }); + + SingleCalendarOperationsAdapter adapterSpy = PowerMockito.spy(new SingleCalendarOperationsAdapter(sessionStorageMock, "testCalendarName")); + + /* When */ + RequestExecution retrieved = adapterSpy.asyncDelete(callback); + + /* Wait */ + synchronized (callback) { + callback.wait(500); + } + + /* Then */ + Assert.assertNotNull(retrieved); + Assert.assertNotSame(currentThreadId, newThreadId.get()); + + Mockito.verify(objRequestMock).delete(); + Mockito.verify(callback).execute(delResultMock); + } + + @AfterMethod + public void after() { + reset(sessionStorageMock, requestMock, objRequestMock, delResultMock, + operationResultMock, reportJobCalendarMock, responseMock, withEntityOperationResultMock, + calendarEntityMock); + } +} \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobsNew/BatchJobsOperationsAdapterTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobsNew/BatchJobsOperationsAdapterTest.java new file mode 100644 index 00000000..e2888093 --- /dev/null +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobsNew/BatchJobsOperationsAdapterTest.java @@ -0,0 +1,91 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobsNew; + +import com.jaspersoft.jasperserver.dto.job.ClientReportJob; +import com.jaspersoft.jasperserver.dto.job.wrappers.ClientJobSummariesListWrapper; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.BatchJobsOperationsAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.RestClientConfiguration; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import javax.ws.rs.core.MultivaluedHashMap; +import org.mockito.Mock; +import org.mockito.internal.util.reflection.Whitebox; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.testng.PowerMockTestCase; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; +import static org.powermock.api.mockito.PowerMockito.mockStatic; +import static org.powermock.api.mockito.PowerMockito.verifyStatic; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertSame; + +/** + * @author Tetiana Iefimenko + */ +@PrepareForTest({JerseyRequest.class}) +public class BatchJobsOperationsAdapterTest extends PowerMockTestCase { + + @Mock + private SessionStorage sessionStorageMock; + + @Mock + private JerseyRequest jobSummaryListWrapperJerseyRequest; + + @Mock + private OperationResult jobSummaryListWrapperOperationResult; + + @Mock + private RestClientConfiguration configurationMock; + + @Mock + private ClientReportJob jobMock; + + @BeforeMethod + public void before() { + initMocks(this); + } + + @Test(testName = "constructor") + public void should_create_proper_SingleJobOperationsAdapter_object() throws IllegalAccessException { + + // When + BatchJobsOperationsAdapter adapter = new BatchJobsOperationsAdapter(sessionStorageMock); + + // Then + assertEquals(Whitebox.getInternalState(adapter, "sessionStorage"), sessionStorageMock); + assertEquals(Whitebox.getInternalState(adapter, "params"), new MultivaluedHashMap()); + } + + @Test + public void should_return_all_jobs() { + + // Given + mockStatic(JerseyRequest.class); + when(JerseyRequest.buildRequest(eq(sessionStorageMock), + eq(ClientJobSummariesListWrapper.class), + eq(new String[]{"jobs"}))).thenReturn(jobSummaryListWrapperJerseyRequest); + when(jobSummaryListWrapperJerseyRequest.get()).thenReturn(jobSummaryListWrapperOperationResult); + when(sessionStorageMock.getConfiguration()).thenReturn(configurationMock); + + // When + BatchJobsOperationsAdapter adapter = spy(new BatchJobsOperationsAdapter(sessionStorageMock)); + OperationResult retrieved = adapter.searchJobs(); + + // Then + verifyStatic(times(1)); + JerseyRequest.buildRequest(eq(sessionStorageMock), eq(ClientJobSummariesListWrapper.class), eq(new String[]{"jobs"})); + verify(jobSummaryListWrapperJerseyRequest, times(1)).get(); + assertNotNull(retrieved); + assertSame(retrieved, jobSummaryListWrapperOperationResult); + + } + +} diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobsNew/JobsServiceTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobsNew/JobsServiceTest.java new file mode 100644 index 00000000..3f11f7d8 --- /dev/null +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobsNew/JobsServiceTest.java @@ -0,0 +1,466 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobsNew; + +import com.jaspersoft.jasperserver.dto.job.ClientJobCalendar; +import com.jaspersoft.jasperserver.dto.job.ClientReportJob; +import com.jaspersoft.jasperserver.dto.job.wrappers.ClientCalendarNameListWrapper; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.BatchJobsOperationsAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.JobValidationErrorHandler; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.JobsService; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.SingleJobOperationsAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.calendar.CalendarType; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.calendar.SingleCalendarOperationsAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.core.Callback; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.RequestExecution; +import com.jaspersoft.jasperserver.jaxrs.client.core.RestClientConfiguration; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.JRSVersion; +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.MimeType; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import java.util.concurrent.atomic.AtomicInteger; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.testng.PowerMockTestCase; +import org.testng.Assert; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import static com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest.buildRequest; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; +import static org.powermock.api.mockito.PowerMockito.mockStatic; +import static org.powermock.api.mockito.PowerMockito.verifyStatic; +import static org.powermock.api.mockito.PowerMockito.whenNew; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertSame; + +/** + * Unit tests for {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.JobsService} + */ +@PrepareForTest({JerseyRequest.class, JobsService.class}) +public class JobsServiceTest extends PowerMockTestCase { + + @Mock + private SessionStorage sessionStorageMock; + + @Mock + private BatchJobsOperationsAdapter expectedAdapterMock; + + @Mock + private SingleJobOperationsAdapter expectedJobOperationsAdapter; + + @Mock + private JerseyRequest jobRequestMock; + + @Mock + private JerseyRequest wrapperRequestMock; + + @Mock + private OperationResult expectedJobOperationResultMock; + + @Mock + private OperationResult expectedWrapperOperationResultMock; + + @Mock + private ClientReportJob reportMock; + + @Mock + private RestClientConfiguration configurationMock; + + @Mock + private Callback, Object> callbackMock; + + @Mock + private RequestExecution executionMock; + + @Mock + private SingleCalendarOperationsAdapter expectedCalendarOperationsAdapterMock; + + @BeforeMethod + public void before() { + initMocks(this); + } + + @Test(testName = "jobs") + public void should_return_proper_adapter() throws Exception { + + // Given + JobsService serviceSpy = spy(new JobsService(sessionStorageMock)); + whenNew(BatchJobsOperationsAdapter.class) + .withParameterTypes(SessionStorage.class) + .withArguments(sessionStorageMock) + .thenReturn(expectedAdapterMock); + + // When + BatchJobsOperationsAdapter retrieved = serviceSpy.jobs(); + + // Then + assertSame(retrieved, expectedAdapterMock); + } + + @Test(testName = "job") + public void should_return_proper_SingleJobOperationsAdapter() throws Exception { + + // Given + JobsService serviceSpy = spy(new JobsService(sessionStorageMock)); + whenNew(SingleJobOperationsAdapter.class) + .withParameterTypes(SessionStorage.class, String.class) + .withArguments(sessionStorageMock, "9056") + .thenReturn(expectedJobOperationsAdapter); + + // When + SingleJobOperationsAdapter retrieved = serviceSpy.job(9056); + + // Then + verify(serviceSpy, times(1)).job(9056); + assertSame(retrieved, expectedJobOperationsAdapter); + } + + @Test(testName = "scheduleReport_for_v5_6_1") + public void should_return_proper_OperationResult_when_JRS_version_is_v5_6_1() { + + // Given + JobsService serviceSpy = spy(new JobsService(sessionStorageMock)); + + mockStatic(JerseyRequest.class); + when(JerseyRequest.buildRequest(eq(sessionStorageMock), + eq(ClientReportJob.class), + eq(new String[]{"jobs"}), + any(JobValidationErrorHandler.class))).thenReturn(jobRequestMock); + when(jobRequestMock.put(reportMock)).thenReturn(expectedJobOperationResultMock); + when(sessionStorageMock.getConfiguration()).thenReturn(configurationMock); + when(configurationMock.getJrsVersion()).thenReturn(JRSVersion.v5_6_1); + when(configurationMock.getContentMimeType()).thenReturn(MimeType.XML); + + // When + serviceSpy.scheduleReport(reportMock); + + // Then + verifyStatic(times(1)); + JerseyRequest.buildRequest(eq(sessionStorageMock), + eq(ClientReportJob.class), + eq(new String[]{"jobs"}), + any(JobValidationErrorHandler.class)); + verify(jobRequestMock, times(1)).put(reportMock); + verify(jobRequestMock, times(1)).setContentType("application/job+xml"); + verify(jobRequestMock, times(1)).setAccept("application/job+xml"); + } + + @Test(testName = "scheduleReport_for_v4_7_0") + public void should_return_proper_OperationResult_when_JRS_version_is_v4_7_0() { + + // Given + mockStatic(JerseyRequest.class); + when(JerseyRequest.buildRequest(eq(sessionStorageMock), + eq(ClientReportJob.class), + eq(new String[]{"jobs"}), + any(JobValidationErrorHandler.class))).thenReturn(jobRequestMock); + when(jobRequestMock.put(reportMock)).thenReturn(expectedJobOperationResultMock); + when(sessionStorageMock.getConfiguration()).thenReturn(configurationMock); + when(configurationMock.getJrsVersion()).thenReturn(JRSVersion.v4_7_0); + when(configurationMock.getContentMimeType()).thenReturn(MimeType.JSON); + JobsService serviceSpy = spy(new JobsService(sessionStorageMock)); + + // When + OperationResult retrieved = serviceSpy.scheduleReport(reportMock); + + // Then + verifyStatic(times(1)); + JerseyRequest.buildRequest(eq(sessionStorageMock), + eq(ClientReportJob.class), + eq(new String[]{"jobs"}), + any(JobValidationErrorHandler.class)); + verify(jobRequestMock, times(1)).put(reportMock); + verify(jobRequestMock, times(1)).setContentType("application/job+json"); + verify(jobRequestMock, times(1)).setAccept("application/job+json"); + + assertNotNull(retrieved); + assertSame(retrieved, expectedJobOperationResultMock); + } + + @Test(testName = "allCalendars") + public void should_return_proper_op_result_object() { + + // Given + JobsService serviceSpy = spy(new JobsService(sessionStorageMock)); + doReturn(expectedWrapperOperationResultMock).when(serviceSpy).calendar((ClientJobCalendar.Type )null); + + // When + OperationResult retrieved = serviceSpy.allCalendars(); + + // Then + verify(serviceSpy, times(1)).allCalendars(); + verify(serviceSpy, times(1)).calendar(((ClientJobCalendar.Type)null)); + verify(serviceSpy, never()).calendar(ClientJobCalendar.Type.holiday); + verifyNoMoreInteractions(serviceSpy); + + assertSame(retrieved, expectedWrapperOperationResultMock); + } + + @Test(testName = "asyncCalendar") + public void should_return_RequestExecution_with_CalendarNameListWrapper_instance() { + + // Given + JobsService serviceSpy = spy(new JobsService(sessionStorageMock)); + doReturn(executionMock).when(serviceSpy).asyncCalendar(null, callbackMock); + + // When + RequestExecution retrieved = serviceSpy.asyncCalendar(callbackMock); + + // Then + verify(serviceSpy, times(1)).asyncCalendar(null, callbackMock); + verify(serviceSpy, never()).asyncCalendar(ClientJobCalendar.Type.holiday, callbackMock); + + assertSame(retrieved, executionMock); + } + + @Test(testName = "calendars_with_param") + public void should_return_proper_op_result_object_when_param_is_not_null() { + + // Given + mockStatic(JerseyRequest.class); + when(JerseyRequest.buildRequest(eq(sessionStorageMock), + eq(ClientCalendarNameListWrapper.class), + eq(new String[]{"jobs", "calendars"}))).thenReturn(wrapperRequestMock); + when(wrapperRequestMock.get()).thenReturn(expectedWrapperOperationResultMock); + JobsService serviceSpy = spy(new JobsService(sessionStorageMock)); + + // When + OperationResult retrieved = serviceSpy.calendar(ClientJobCalendar.Type.daily); + + // Then + assertNotNull(retrieved); + assertSame(retrieved, expectedWrapperOperationResultMock); + + verifyStatic(times(1)); + JerseyRequest.buildRequest(eq(sessionStorageMock), + eq(ClientCalendarNameListWrapper.class), + eq(new String[]{"jobs", "calendars"})); + + verify(wrapperRequestMock, times(1)).get(); + verify(wrapperRequestMock, times(1)).addParam("calendarType", CalendarType.daily.toString().toLowerCase()); + } + + + @Test(testName = "calendars_with_param") + public void should_return_proper_op_result_object_when_param_is_null() { + + // Given + mockStatic(JerseyRequest.class); + when(JerseyRequest.buildRequest(eq(sessionStorageMock), + eq(ClientCalendarNameListWrapper.class), + eq(new String[]{"jobs", "calendars"}))).thenReturn(wrapperRequestMock); + when(wrapperRequestMock.get()).thenReturn(expectedWrapperOperationResultMock); + JobsService serviceSpy = spy(new JobsService(sessionStorageMock)); + + // When + OperationResult retrieved = serviceSpy.calendar((ClientJobCalendar.Type)null); + + // Then + assertNotNull(retrieved); + assertSame(retrieved, expectedWrapperOperationResultMock); + + verifyStatic(times(1)); + JerseyRequest.buildRequest(eq(sessionStorageMock), + eq(ClientCalendarNameListWrapper.class), + eq(new String[]{"jobs", "calendars"})); + + verify(wrapperRequestMock, times(1)).get(); + verify(wrapperRequestMock, never()).addParam("calendarType", CalendarType.daily.toString().toLowerCase()); + } + + + @Test(testName = "calendar") + public void should_return_an_calendar_adapter() throws Exception { + + // Given + final String calendarName = "testCalendar"; + JobsService serviceSpy = spy(new JobsService(sessionStorageMock)); + whenNew(SingleCalendarOperationsAdapter.class) + .withParameterTypes(SessionStorage.class, String.class) + .withArguments(sessionStorageMock, calendarName) + .thenReturn(expectedCalendarOperationsAdapterMock); + + // When + SingleCalendarOperationsAdapter retrieved = serviceSpy.calendar(calendarName); + + // Then + assertNotNull(retrieved); + assertSame(retrieved, expectedCalendarOperationsAdapterMock); + } + + @Test(testName = "calendar", expectedExceptions = IllegalArgumentException.class) + public void should_throw_an_exception_when_invalid_calendar_name() throws Exception { + JobsService serviceSpy = spy(new JobsService(sessionStorageMock)); + serviceSpy.calendar(""); + } + + @Test + public void should_get_calendars_asynchronously() throws InterruptedException { + + /* Given */ + PowerMockito.mockStatic(JerseyRequest.class); + PowerMockito.when(buildRequest(eq(sessionStorageMock), + eq(ClientCalendarNameListWrapper.class), + eq(new String[]{"jobs", "calendars"}))).thenReturn(wrapperRequestMock); + + PowerMockito.doReturn(expectedWrapperOperationResultMock).when(wrapperRequestMock).get(); + JobsService serviceSpy = PowerMockito.spy(new JobsService(sessionStorageMock)); + + final AtomicInteger newThreadId = new AtomicInteger(); + final int currentThreadId = (int) Thread.currentThread().getId(); + + final Callback, Void> callback = PowerMockito.spy(new Callback, Void>() { + @Override + public Void execute(OperationResult data) { + newThreadId.set((int) Thread.currentThread().getId()); + synchronized (this) { + this.notify(); + } + return null; + } + }); + + PowerMockito.doReturn(null).when(callback).execute(expectedWrapperOperationResultMock); + + /* When */ + RequestExecution retrieved = serviceSpy.asyncCalendar(ClientJobCalendar.Type.annual, callback); + + /* Wait */ + synchronized (callback) { + callback.wait(1000); + } + + /* Then */ + Assert.assertNotNull(retrieved); + Assert.assertNotSame(currentThreadId, newThreadId.get()); + + Mockito.verify(wrapperRequestMock).get(); + Mockito.verify(callback).execute(expectedWrapperOperationResultMock); + Mockito.verify(wrapperRequestMock).addParam("calendarType", "annual"); + } + + @Test + public void should_send_ScheduleReport_asynchronously_() throws InterruptedException { + + /* Given */ + PowerMockito.mockStatic(JerseyRequest.class); + PowerMockito.when(buildRequest(eq(sessionStorageMock), + eq(ClientReportJob.class), + eq(new String[]{"jobs"}), + any(JobValidationErrorHandler.class))).thenReturn(jobRequestMock); + + PowerMockito.doReturn(expectedJobOperationResultMock).when(jobRequestMock).put(reportMock); + JobsService serviceSpy = PowerMockito.spy(new JobsService(sessionStorageMock)); + + final AtomicInteger newThreadId = new AtomicInteger(); + final int currentThreadId = (int) Thread.currentThread().getId(); + + final Callback, Void> callback = PowerMockito.spy(new Callback, Void>() { + @Override + public Void execute(OperationResult data) { + newThreadId.set((int) Thread.currentThread().getId()); + synchronized (this) { + this.notify(); + } + return null; + } + }); + + PowerMockito.doReturn(null).when(callback).execute(expectedJobOperationResultMock); + PowerMockito.doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); + PowerMockito.doReturn(JRSVersion.v5_0_0).when(configurationMock).getJrsVersion(); + PowerMockito.doReturn(null).when(callback).execute(expectedJobOperationResultMock); + PowerMockito.doReturn(null).when(callback).execute(expectedJobOperationResultMock); + + /* When */ + RequestExecution retrieved = serviceSpy.asyncScheduleReport(reportMock, callback); + + /* Wait */ + synchronized (callback) { + callback.wait(1000); + } + + /* Then */ + Assert.assertNotNull(retrieved); + Assert.assertNotSame(currentThreadId, newThreadId.get()); + + Mockito.verify(jobRequestMock).put(reportMock); + Mockito.verify(jobRequestMock).setContentType("application/job+json"); + Mockito.verify(jobRequestMock).setAccept("application/job+json"); + Mockito.verify(callback).execute(expectedJobOperationResultMock); + Mockito.verify(sessionStorageMock).getConfiguration(); + Mockito.verify(configurationMock).getJrsVersion(); + } + + @Test + public void should_send_ScheduleReport_asynchronously() throws InterruptedException { + + /* Given */ + PowerMockito.mockStatic(JerseyRequest.class); + PowerMockito.when(buildRequest(eq(sessionStorageMock), + eq(ClientReportJob.class), + eq(new String[]{"jobs"}), + any(JobValidationErrorHandler.class))).thenReturn(jobRequestMock); + + PowerMockito.doReturn(expectedJobOperationResultMock).when(jobRequestMock).put(reportMock); + JobsService serviceSpy = PowerMockito.spy(new JobsService(sessionStorageMock)); + + final AtomicInteger newThreadId = new AtomicInteger(); + final int currentThreadId = (int) Thread.currentThread().getId(); + + final Callback, Void> callback = PowerMockito.spy(new Callback, Void>() { + @Override + public Void execute(OperationResult data) { + newThreadId.set((int) Thread.currentThread().getId()); + synchronized (this) { + this.notify(); + } + return null; + } + }); + + PowerMockito.doReturn(null).when(callback).execute(expectedJobOperationResultMock); + PowerMockito.doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); + PowerMockito.doReturn(JRSVersion.v5_6_1).when(configurationMock).getJrsVersion(); + PowerMockito.doReturn(null).when(callback).execute(expectedJobOperationResultMock); + PowerMockito.doReturn(null).when(callback).execute(expectedJobOperationResultMock); + + /* When */ + RequestExecution retrieved = serviceSpy.asyncScheduleReport(reportMock, callback); + + /* Wait */ + synchronized (callback) { + callback.wait(1000); + } + + /* Then */ + Assert.assertNotNull(retrieved); + Assert.assertNotSame(currentThreadId, newThreadId.get()); + + Mockito.verify(jobRequestMock).put(reportMock); + Mockito.verify(jobRequestMock).setContentType("application/job+xml"); + Mockito.verify(jobRequestMock).setAccept("application/job+xml"); + Mockito.verify(callback).execute(expectedJobOperationResultMock); + Mockito.verify(sessionStorageMock, times(3)).getConfiguration(); + Mockito.verify(configurationMock).getJrsVersion(); + } + + @AfterMethod + public void after() { + reset(sessionStorageMock, expectedAdapterMock, expectedJobOperationsAdapter, + jobRequestMock, expectedJobOperationResultMock, reportMock, configurationMock); + } +} \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobsNew/SingleJobOperationsAdapterTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobsNew/SingleJobOperationsAdapterTest.java new file mode 100644 index 00000000..5c65ac66 --- /dev/null +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobsNew/SingleJobOperationsAdapterTest.java @@ -0,0 +1,532 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobsNew; + +import com.jaspersoft.jasperserver.dto.job.ClientJobState; +import com.jaspersoft.jasperserver.dto.job.ClientReportJob; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.JobValidationErrorHandler; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.SingleJobOperationsAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.core.Callback; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.RequestExecution; +import com.jaspersoft.jasperserver.jaxrs.client.core.RestClientConfiguration; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.JRSVersion; +import com.jaspersoft.jasperserver.jaxrs.client.core.enums.MimeType; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import java.lang.reflect.Field; +import java.util.concurrent.atomic.AtomicInteger; +import org.mockito.InOrder; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.testng.PowerMockTestCase; +import org.testng.Assert; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; +import static org.powermock.api.mockito.PowerMockito.mockStatic; +import static org.powermock.api.mockito.PowerMockito.verifyStatic; +import static org.powermock.api.support.membermodification.MemberMatcher.field; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertSame; + +/** + * Unit tests for {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.SingleJobOperationsAdapter} + */ +@PrepareForTest({JerseyRequest.class}) +public class SingleJobOperationsAdapterTest extends PowerMockTestCase { + + @Mock + private SessionStorage sessionStorageMock; + + @Mock + private JerseyRequest jobRequestMock; + + @Mock + private JerseyRequest objectJerseyRequestMock; + + @Mock + private JerseyRequest jobStateJerseyRequestMock; + + @Mock + private OperationResult jobStateOperationResultMock; + + @Mock + private OperationResult jobOperationResultMock; + + @Mock + private OperationResult operationResultMock; + + @Mock + private RestClientConfiguration configurationMock; + + @Mock + private ClientReportJob jobMock; + + private final String expectedJobId = "3819"; + + @BeforeMethod + public void before() { + initMocks(this); + } + + @Test(testName = "constructor") + public void should_create_proper_SingleJobOperationsAdapter_object() throws IllegalAccessException { + + // When + SingleJobOperationsAdapter adapter = spy(new SingleJobOperationsAdapter(sessionStorageMock, expectedJobId)); + + // Then + assertSame(adapter.getSessionStorage(), sessionStorageMock); + Field field = field(SingleJobOperationsAdapter.class, "jobId"); + String retrievedJobId = (String) field.get(adapter); + assertEquals(retrievedJobId, expectedJobId); + } + + @Test(testName = "group") + public void should_return_proper_job_operation_result_when_JRS_version_is_v5_6_1() { + + // Given + mockStatic(JerseyRequest.class); + when(JerseyRequest.buildRequest(eq(sessionStorageMock), eq(ClientReportJob.class), eq(new String[]{"jobs", expectedJobId}))).thenReturn(jobRequestMock); + when(jobRequestMock.get()).thenReturn(jobOperationResultMock); + when(sessionStorageMock.getConfiguration()).thenReturn(configurationMock); + when(configurationMock.getJrsVersion()).thenReturn(JRSVersion.v5_6_1); + when(configurationMock.getContentMimeType()).thenReturn(MimeType.XML); + + // When + SingleJobOperationsAdapter adapter = spy(new SingleJobOperationsAdapter(sessionStorageMock, expectedJobId)); + OperationResult retrieved = adapter.getJob(); + + // Then + verifyStatic(times(1)); + JerseyRequest.buildRequest(eq(sessionStorageMock), eq(ClientReportJob.class), eq(new String[]{"jobs", expectedJobId})); + verify(jobRequestMock, times(1)).get(); + verify(jobRequestMock, times(1)).setAccept("application/job+xml"); + + assertNotNull(retrieved); + assertSame(retrieved, jobOperationResultMock); + } + + @Test + public void should_return_proper_job_operation_result_when_JRS_version_is_v4_7_0() { + + // Given + mockStatic(JerseyRequest.class); + when(JerseyRequest.buildRequest(eq(sessionStorageMock), eq(ClientReportJob.class), eq(new String[]{"jobs", expectedJobId}))).thenReturn(jobRequestMock); + when(jobRequestMock.get()).thenReturn(jobOperationResultMock); + when(sessionStorageMock.getConfiguration()).thenReturn(configurationMock); + when(configurationMock.getJrsVersion()).thenReturn(JRSVersion.v4_7_0); + when(configurationMock.getContentMimeType()).thenReturn(MimeType.JSON); + + // When + SingleJobOperationsAdapter adapter = spy(new SingleJobOperationsAdapter(sessionStorageMock, expectedJobId)); + OperationResult retrieved = adapter.getJob(); + + // Then + verifyStatic(times(1)); + JerseyRequest.buildRequest(eq(sessionStorageMock), eq(ClientReportJob.class), eq(new String[]{"jobs", expectedJobId})); + verify(jobRequestMock, times(1)).get(); + verify(jobRequestMock, times(1)).setAccept("application/job+json"); + + assertNotNull(retrieved); + assertSame(retrieved, jobOperationResultMock); + } + + @Test + public void should_proper_op_result_instance() { + + // Given + mockStatic(JerseyRequest.class); + when(JerseyRequest.buildRequest(eq(sessionStorageMock), eq(ClientJobState.class), + eq(new String[]{"jobs", expectedJobId, "state"}))).thenReturn(jobStateJerseyRequestMock); + when(jobStateJerseyRequestMock.get()).thenReturn(jobStateOperationResultMock); + + // When + SingleJobOperationsAdapter adapter = spy(new SingleJobOperationsAdapter(sessionStorageMock, expectedJobId)); + OperationResult retrieved = adapter.jobState(); + + // Then + verifyStatic(times(1)); + JerseyRequest.buildRequest(eq(sessionStorageMock), eq(ClientJobState.class), + eq(new String[]{"jobs", expectedJobId, "state"})); + verify(jobStateJerseyRequestMock, times(1)).get(); + assertSame(retrieved, jobStateOperationResultMock); + } + + @Test(testName = "update") + public void should_return_prepared_op_result_when_jrs_version_is_5_6_1() { + + // Given + mockStatic(JerseyRequest.class); + when(JerseyRequest.buildRequest(eq(sessionStorageMock), eq(ClientReportJob.class), eq(new String[]{"jobs", expectedJobId}), any(JobValidationErrorHandler.class))).thenReturn(jobRequestMock); + when(jobRequestMock.post(jobMock)).thenReturn(jobOperationResultMock); + when(sessionStorageMock.getConfiguration()).thenReturn(configurationMock); + when(configurationMock.getJrsVersion()).thenReturn(JRSVersion.v5_6_1); + when(configurationMock.getContentMimeType()).thenReturn(MimeType.XML); + when(configurationMock.getAcceptMimeType()).thenReturn(MimeType.XML); + + // When + SingleJobOperationsAdapter adapter = spy(new SingleJobOperationsAdapter(sessionStorageMock, expectedJobId)); + OperationResult retrieved = adapter.update(jobMock); + + // Then + verifyStatic(times(1)); + JerseyRequest.buildRequest(eq(sessionStorageMock), eq(ClientReportJob.class), eq(new String[]{"jobs", expectedJobId}), any(JobValidationErrorHandler.class)); + verify(jobRequestMock, times(1)).post(jobMock); + verify(jobRequestMock, times(1)).setContentType("application/job+xml"); + verify(jobRequestMock, times(1)).setAccept("application/job+xml"); + + assertNotNull(retrieved); + assertSame(retrieved, jobOperationResultMock); + } + + @Test(testName = "update") + public void should_return_prepared_op_result_when_jrs_version_is_4_7_0() { + + // Given + mockStatic(JerseyRequest.class); + when(JerseyRequest.buildRequest(eq(sessionStorageMock), eq(ClientReportJob.class), eq(new String[]{"jobs", expectedJobId}), any(JobValidationErrorHandler.class))).thenReturn(jobRequestMock); + when(jobRequestMock.post(jobMock)).thenReturn(jobOperationResultMock); + when(sessionStorageMock.getConfiguration()).thenReturn(configurationMock); + when(configurationMock.getJrsVersion()).thenReturn(JRSVersion.v4_7_0); + when(configurationMock.getContentMimeType()).thenReturn(MimeType.JSON); + when(configurationMock.getAcceptMimeType()).thenReturn(MimeType.JSON); + + // When + SingleJobOperationsAdapter adapter = spy(new SingleJobOperationsAdapter(sessionStorageMock, expectedJobId)); + OperationResult retrieved = adapter.update(jobMock); + + // Then + verifyStatic(times(1)); + JerseyRequest.buildRequest(eq(sessionStorageMock), eq(ClientReportJob.class), eq(new String[]{"jobs", expectedJobId}), any(JobValidationErrorHandler.class)); + verify(jobRequestMock, times(1)).post(jobMock); + verify(jobRequestMock, times(1)).setContentType("application/job+json"); + verify(jobRequestMock, times(1)).setAccept("application/job+json"); + + assertNotNull(retrieved); + assertSame(retrieved, jobOperationResultMock); + } + + @Test(testName = "delete") + public void should_proper_op_result_instance_for_deleting_operation() { + + // Given + mockStatic(JerseyRequest.class); + when(JerseyRequest.buildRequest(eq(sessionStorageMock), eq(Object.class), + eq(new String[]{"jobs", expectedJobId}))).thenReturn(objectJerseyRequestMock); + when(objectJerseyRequestMock.delete()).thenReturn(operationResultMock); + + // When + SingleJobOperationsAdapter adapter = spy(new SingleJobOperationsAdapter(sessionStorageMock, expectedJobId)); + OperationResult retrieved = adapter.delete(); + + // Then + verifyStatic(times(1)); + JerseyRequest.buildRequest(eq(sessionStorageMock), eq(Object.class), eq(new String[]{"jobs", expectedJobId})); + verify(objectJerseyRequestMock, times(1)).delete(); + assertSame(retrieved, operationResultMock); + } + + @Test + public void should_return_RequestExecution_when_environment_is_specified() throws Exception { + + // Given + final AtomicInteger newThreadId = new AtomicInteger(); + final int currentThreadId = (int) Thread.currentThread().getId(); + + PowerMockito.mockStatic(JerseyRequest.class); + PowerMockito.when(JerseyRequest.buildRequest( + eq(sessionStorageMock), + eq(ClientReportJob.class), + eq(new String[]{"jobs", "123435326"}), + any(JobValidationErrorHandler.class))).thenReturn(jobRequestMock); + + SingleJobOperationsAdapter adapterSpy = PowerMockito.spy(new SingleJobOperationsAdapter(sessionStorageMock, "123435326")); + Callback, Void> callback = PowerMockito.spy(new Callback, Void>() { + public Void execute(OperationResult data) { + newThreadId.set((int) Thread.currentThread().getId()); + synchronized (this) { + this.notify(); + } + return null; + } + }); + + PowerMockito.doReturn(jobOperationResultMock).when(jobRequestMock).post(jobMock); + PowerMockito.doReturn(null).when(callback).execute(jobOperationResultMock); + PowerMockito.doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); + PowerMockito.doReturn(JRSVersion.v5_1_0).when(configurationMock).getJrsVersion(); + + InOrder inOrder = Mockito.inOrder(jobRequestMock); + + // When + RequestExecution retrieved = adapterSpy.asyncUpdate(jobMock, callback); + + // Wait + synchronized (callback) { + callback.wait(1000); + } + + // Then + Assert.assertNotNull(retrieved); + Assert.assertNotSame(currentThreadId, newThreadId.get()); + Mockito.verify(callback, times(1)).execute(jobOperationResultMock); + + inOrder.verify(jobRequestMock, times(1)).setContentType("application/job+json"); + inOrder.verify(jobRequestMock, times(1)).setAccept("application/job+json"); + inOrder.verify(jobRequestMock, times(1)).post(jobMock); + } + + @Test + public void should_return_RequestExecution_when_environment_is_specified_with_5_6_1_jrs_server_version() throws Exception { + + // Given + final AtomicInteger newThreadId = new AtomicInteger(); + final int currentThreadId = (int) Thread.currentThread().getId(); + + PowerMockito.mockStatic(JerseyRequest.class); + PowerMockito.when(JerseyRequest.buildRequest( + eq(sessionStorageMock), + eq(ClientReportJob.class), + eq(new String[]{"jobs", "123435326"}), + any(JobValidationErrorHandler.class))).thenReturn(jobRequestMock); + + SingleJobOperationsAdapter adapterSpy = PowerMockito.spy(new SingleJobOperationsAdapter(sessionStorageMock, "123435326")); + Callback, Void> callback = PowerMockito.spy(new Callback, Void>() { + public Void execute(OperationResult data) { + newThreadId.set((int) Thread.currentThread().getId()); + synchronized (this) { + this.notify(); + } + return null; + } + }); + + PowerMockito.doReturn(jobOperationResultMock).when(jobRequestMock).post(jobMock); + PowerMockito.doReturn(null).when(callback).execute(jobOperationResultMock); + PowerMockito.doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); + PowerMockito.doReturn(JRSVersion.v5_6_1).when(configurationMock).getJrsVersion(); + + InOrder inOrder = Mockito.inOrder(jobRequestMock); + + // When + RequestExecution retrieved = adapterSpy.asyncUpdate(jobMock, callback); + + // Wait + synchronized (callback) { + callback.wait(1000); + } + + // Then + Assert.assertNotNull(retrieved); + Assert.assertNotSame(currentThreadId, newThreadId.get()); + Mockito.verify(callback, times(1)).execute(jobOperationResultMock); + + inOrder.verify(jobRequestMock).setContentType("application/job+xml"); + inOrder.verify(jobRequestMock).setAccept("application/job+xml"); + inOrder.verify(jobRequestMock, times(1)).post(jobMock); + } + + @Test + public void should_invoke_asynchronous_method_get_and_return_RequestExecution_with_Future() throws InterruptedException { + + // Given + final AtomicInteger newThreadId = new AtomicInteger(); + final int currentThreadId = (int) Thread.currentThread().getId(); + + PowerMockito.mockStatic(JerseyRequest.class); + PowerMockito.when(JerseyRequest.buildRequest( + eq(sessionStorageMock), + eq(ClientReportJob.class), + eq(new String[]{"jobs", "123435326"}))) + .thenReturn(jobRequestMock); + + SingleJobOperationsAdapter adapterSpy = PowerMockito.spy(new SingleJobOperationsAdapter(sessionStorageMock, "123435326")); + Callback, Void> callback = PowerMockito.spy(new Callback, Void>() { + public Void execute(OperationResult data) { + newThreadId.set((int) Thread.currentThread().getId()); + synchronized (this) { + this.notify(); + } + return null; + } + }); + + PowerMockito.doReturn(jobOperationResultMock).when(jobRequestMock).get(); + PowerMockito.doReturn(null).when(callback).execute(jobOperationResultMock); + PowerMockito.doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); + PowerMockito.doReturn(JRSVersion.v5_6_1).when(configurationMock).getJrsVersion(); + PowerMockito.doReturn(MimeType.JSON).when(configurationMock).getAcceptMimeType(); + + InOrder inOrder = Mockito.inOrder(jobRequestMock); + + // When + RequestExecution retrieved = adapterSpy.asyncGetJob(callback); + + // Wait + synchronized (callback) { + callback.wait(1000); + } + + // Then + Assert.assertNotNull(retrieved); + Assert.assertNotSame(currentThreadId, newThreadId.get()); + Mockito.verify(callback, times(1)).execute(jobOperationResultMock); + + inOrder.verify(jobRequestMock).setAccept("application/job+json"); + inOrder.verify(jobRequestMock, times(1)).get(); + } + + + @Test + public void should_invoke_asynchronous_method_get_and_return_RequestExecution_with_Future_when_jrs_version_is_lower_Then_5_5_0() throws InterruptedException { + + // Given + final AtomicInteger newThreadId = new AtomicInteger(); + final int currentThreadId = (int) Thread.currentThread().getId(); + + PowerMockito.mockStatic(JerseyRequest.class); + PowerMockito.when(JerseyRequest.buildRequest( + eq(sessionStorageMock), + eq(ClientReportJob.class), + eq(new String[]{"jobs", "123435326"}))) + .thenReturn(jobRequestMock); + + SingleJobOperationsAdapter adapterSpy = PowerMockito.spy(new SingleJobOperationsAdapter(sessionStorageMock, "123435326")); + Callback, Void> callback = PowerMockito.spy(new Callback, Void>() { + public Void execute(OperationResult data) { + newThreadId.set((int) Thread.currentThread().getId()); + synchronized (this) { + this.notify(); + } + return null; + } + }); + + PowerMockito.doReturn(jobOperationResultMock).when(jobRequestMock).get(); + PowerMockito.doReturn(null).when(callback).execute(jobOperationResultMock); + PowerMockito.doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); + PowerMockito.doReturn(JRSVersion.v4_7_0).when(configurationMock).getJrsVersion(); + + InOrder inOrder = Mockito.inOrder(jobRequestMock); + + // When + RequestExecution retrieved = adapterSpy.asyncGetJob(callback); + + // Wait + synchronized (callback) { + callback.wait(1000); + } + + // Then + Assert.assertNotNull(retrieved); + Assert.assertNotSame(currentThreadId, newThreadId.get()); + Mockito.verify(callback, times(1)).execute(jobOperationResultMock); + + inOrder.verify(jobRequestMock).setAccept("application/job+json"); + inOrder.verify(jobRequestMock, times(1)).get(); + } + + + @Test + public void should_delete_job_asynchronously() throws InterruptedException { + + // Given + final AtomicInteger newThreadId = new AtomicInteger(); + final int currentThreadId = (int) Thread.currentThread().getId(); + + PowerMockito.mockStatic(JerseyRequest.class); + PowerMockito.when(JerseyRequest.buildRequest( + eq(sessionStorageMock), + eq(Object.class), + eq(new String[]{"jobs", "123435326"}))) + .thenReturn(objectJerseyRequestMock); + + SingleJobOperationsAdapter adapterSpy = PowerMockito.spy(new SingleJobOperationsAdapter(sessionStorageMock, "123435326")); + Callback callback = PowerMockito.spy(new Callback() { + public Void execute(OperationResult data) { + newThreadId.set((int) Thread.currentThread().getId()); + synchronized (this) { + this.notify(); + } + return null; + } + }); + + PowerMockito.doReturn(operationResultMock).when(objectJerseyRequestMock).delete(); + PowerMockito.doReturn(null).when(callback).execute(operationResultMock); + + // When + RequestExecution retrieved = adapterSpy.asyncDelete(callback); + + // Wait + synchronized (callback) { + callback.wait(1000); + } + + // Then + Assert.assertNotNull(retrieved); + Assert.assertNotSame(currentThreadId, newThreadId.get()); + Mockito.verify(objectJerseyRequestMock, times(1)).delete(); + Mockito.verify(callback, times(1)).execute(operationResultMock); + } + + @Test + public void should_retrieve_state_asynchronously() throws InterruptedException { + + // Given + final AtomicInteger newThreadId = new AtomicInteger(); + final int currentThreadId = (int) Thread.currentThread().getId(); + + PowerMockito.mockStatic(JerseyRequest.class); + PowerMockito.when(JerseyRequest.buildRequest( + eq(sessionStorageMock), + eq(ClientJobState.class), + eq(new String[]{"jobs", "123435326", "state"}))) + .thenReturn(jobStateJerseyRequestMock); + + SingleJobOperationsAdapter adapterSpy = PowerMockito.spy(new SingleJobOperationsAdapter(sessionStorageMock, "123435326")); + Callback, Void> callback = PowerMockito.spy(new Callback, Void>() { + public Void execute(OperationResult data) { + newThreadId.set((int) Thread.currentThread().getId()); + synchronized (this) { + this.notify(); + } + return null; + } + }); + + PowerMockito.doReturn(jobStateOperationResultMock).when(jobStateJerseyRequestMock).get(); + PowerMockito.doReturn(null).when(callback).execute(jobStateOperationResultMock); + + // When + RequestExecution retrieved = adapterSpy.asyncJobState(callback); + + // Wait + synchronized (callback) { + callback.wait(1000); + } + + // Then + Assert.assertNotNull(retrieved); + Assert.assertNotSame(currentThreadId, newThreadId.get()); + Mockito.verify(jobStateJerseyRequestMock, times(1)).get(); + Mockito.verify(callback, times(1)).execute(jobStateOperationResultMock); + } + + @AfterMethod + public void after() { + reset(sessionStorageMock, jobRequestMock, jobOperationResultMock, configurationMock); + } +} \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobsNew/trigger/CalendarTriggerTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobsNew/trigger/CalendarTriggerTest.java new file mode 100644 index 00000000..cf8287c7 --- /dev/null +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobsNew/trigger/CalendarTriggerTest.java @@ -0,0 +1,50 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobsNew.trigger; + +import com.jaspersoft.jasperserver.dto.job.ClientCalendarDaysType; +import com.jaspersoft.jasperserver.dto.job.ClientJobCalendarTrigger; +import java.util.Date; +import java.util.TreeSet; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import static java.util.Arrays.asList; +import static org.testng.Assert.assertEquals; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class CalendarTriggerTest { + + private ClientJobCalendarTrigger calendarTrigger = new ClientJobCalendarTrigger(); + + @BeforeMethod + public void before() { + + calendarTrigger. + setMinutes("1-10"). + setHours("8-16"). + setDaysType(ClientCalendarDaysType.ALL). + setWeekDays(new TreeSet(asList((byte) 10, (byte) 21, (byte) 12))). + setMonthDays("1,3,5-22"). + setMonths(new TreeSet(asList((byte)1, (byte)11, (byte)12))). + setCalendarName("Calendar name"). + setEndDate(new Date()). + setId(Long.valueOf(1000)). + setMisfireInstruction(0). + setStartDate(new Date()). + setStartType(1). + setTimezone("Some time zone"). + setVersion(1); + } + + @Test + public void should_clone_object() { + ClientJobCalendarTrigger cloned = (ClientJobCalendarTrigger) calendarTrigger.deepClone(); + assertEquals(cloned, calendarTrigger); + } +} \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobsNew/trigger/SimpleTriggerTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobsNew/trigger/SimpleTriggerTest.java new file mode 100644 index 00000000..2d8c2a7e --- /dev/null +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/jobsNew/trigger/SimpleTriggerTest.java @@ -0,0 +1,48 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobsNew.trigger; + +import com.jaspersoft.jasperserver.dto.job.ClientIntervalUnitType; +import com.jaspersoft.jasperserver.dto.job.ClientJobSimpleTrigger; +import java.util.Date; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import static org.testng.Assert.assertEquals; + + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +public class SimpleTriggerTest { + + private ClientJobSimpleTrigger simpleTrigger = new ClientJobSimpleTrigger(); + + @BeforeMethod + public void before() { + + simpleTrigger. + setOccurrenceCount(10). + setRecurrenceInterval(20). + setRecurrenceIntervalUnit(ClientIntervalUnitType.DAY). + setCalendarName("Calendar name"). + setEndDate(new Date()). + setId(Long.valueOf(1000)). + setMisfireInstruction(10). + setStartDate(new Date()). + setStartType(1). + setTimezone("Some time zone"). + setVersion(1); + } + + @Test + public void should_clone_object() { + ClientJobSimpleTrigger cloned = (ClientJobSimpleTrigger) simpleTrigger.deepClone(); + + assertEquals(cloned, simpleTrigger); + } + +} \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/AttachmentTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/AttachmentTest.java index 5ac938e1..e0529482 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/AttachmentTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/AttachmentTest.java @@ -1,5 +1,6 @@ package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting; +import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.Attachment; import org.testng.annotations.Test; import static org.testng.Assert.assertSame; diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ExportExecutionRequestBuilderTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ExportExecutionRequestBuilderTest.java index 2ed3735b..e738f1df 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ExportExecutionRequestBuilderTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ExportExecutionRequestBuilderTest.java @@ -8,6 +8,7 @@ import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.AttachmentDescriptor; import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.ExportDescriptor; +import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.HtmlReport; import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.ReportExecutionStatusEntity; import org.apache.commons.io.IOUtils; import org.mockito.Mock; diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/HtmlReportTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/HtmlReportTest.java index e8b232ae..5865c032 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/HtmlReportTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/HtmlReportTest.java @@ -1,5 +1,7 @@ package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting; +import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.Attachment; +import com.jaspersoft.jasperserver.jaxrs.client.dto.reports.HtmlReport; import org.testng.annotations.Test; import java.util.ArrayList; @@ -10,13 +12,13 @@ import static org.testng.Assert.assertTrue; /** - * Unit tests for {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.HtmlReport} + * Unit tests for {@link com.jaspersoft.jasperserver.jaxrs.client.dto.reports.HtmlReport} */ public class HtmlReportTest { @Test /** - * for {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.HtmlReport#HtmlReport(String)} + * for {@link com.jaspersoft.jasperserver.jaxrs.client.dto.reports.HtmlReport#HtmlReport(String)} */ public void should_create_object_with_proper_params() { @@ -31,7 +33,7 @@ public void should_create_object_with_proper_params() { @Test /** - * for getters and setters of {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.HtmlReport} class + * for getters and setters of {@link com.jaspersoft.jasperserver.jaxrs.client.dto.reports.HtmlReport} class */ public void should_set_fields_and_get_proper_values() { diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportsAdapterTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportsAdapterTest.java index e3901653..f6a3fa15 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportsAdapterTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/ReportsAdapterTest.java @@ -1,7 +1,11 @@ package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting; +import com.jaspersoft.jasperserver.dto.reports.ReportParameter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.reportoptions.ReportOptionsAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.reportoptions.ReportOptionsUtil; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.reportparameters.ReorderingReportParametersAdapter; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.reportparameters.ReportParametersAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util.ReportOutputFormat; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; import org.mockito.Mock; import org.powermock.api.mockito.PowerMockito; @@ -12,23 +16,35 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import javax.ws.rs.core.MultivaluedHashMap; +import java.util.LinkedList; +import java.util.List; + import static org.mockito.Mockito.reset; import static org.mockito.Mockito.times; import static org.mockito.MockitoAnnotations.initMocks; import static org.powermock.api.mockito.PowerMockito.mock; +import static org.powermock.api.mockito.PowerMockito.mockStatic; +import static org.powermock.api.mockito.PowerMockito.spy; import static org.powermock.api.mockito.PowerMockito.verifyNew; +import static org.powermock.api.mockito.PowerMockito.when; import static org.powermock.api.mockito.PowerMockito.whenNew; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertSame; -@PrepareForTest({ReorderingReportParametersAdapter.class, ReportParametersAdapter.class, /*RunReportAdapter.class,*/ ReportsAdapter.class}) +@PrepareForTest({ReorderingReportParametersAdapter.class, ReportParametersAdapter.class, /*RunReportAdapter.class,*/ ReportsAdapter.class, ReportOptionsUtil.class}) public class ReportsAdapterTest extends PowerMockTestCase { + public static final String REPORT_UNIT_URI = "reportUnitUri"; + public static final String OPTIONS_ID = "optionsId"; @Mock private SessionStorage sessionStorageMock; @Mock - private ReorderingReportParametersAdapter adapterMock; + private ReorderingReportParametersAdapter reportParametersAdapterMock; + + @Mock + private ReportOptionsAdapter reportOptionsAdapterMock; @Mock private RunReportAdapter reportAdapterMock; @@ -45,25 +61,81 @@ public void before() { public void should_pass_session_to_parent_class() { /* When */ - ReportsAdapter adapterSpy = new ReportsAdapter(sessionStorageMock, "reportUnitUri"); + ReportsAdapter adapterSpy = new ReportsAdapter(sessionStorageMock, REPORT_UNIT_URI); /* Then */ assertSame(adapterSpy.getSessionStorage(), sessionStorageMock); - String reportUnitUri = Whitebox.getInternalState(adapterSpy, "reportUnitUri"); - assertEquals(reportUnitUri, "reportUnitUri"); + String reportUnitUri = Whitebox.getInternalState(adapterSpy, REPORT_UNIT_URI); + assertEquals(reportUnitUri, REPORT_UNIT_URI); + } + + @Test + public void should_return_proper_ReportOptionsAdapter_object() throws Exception { + + /* When */ + PowerMockito.whenNew(ReportOptionsAdapter .class).withArguments(sessionStorageMock, REPORT_UNIT_URI).thenReturn(reportOptionsAdapterMock); + + ReportsAdapter adapterSpy = new ReportsAdapter(sessionStorageMock, REPORT_UNIT_URI); + ReportOptionsAdapter retrieved = adapterSpy.reportOptions(); + + assertSame(retrieved, reportOptionsAdapterMock); + verifyNew(ReportOptionsAdapter.class, times(1)).withArguments(sessionStorageMock, REPORT_UNIT_URI); + } + + + @Test + public void should_return_proper_ReportOptionsAdapter_object_by_optionsId() throws Exception { + + /* When */ + PowerMockito.whenNew(ReportOptionsAdapter .class).withArguments(sessionStorageMock, REPORT_UNIT_URI, OPTIONS_ID).thenReturn(reportOptionsAdapterMock); + + ReportsAdapter adapterSpy = new ReportsAdapter(sessionStorageMock, REPORT_UNIT_URI); + ReportOptionsAdapter retrieved = adapterSpy.reportOptions(OPTIONS_ID); + + assertSame(retrieved, reportOptionsAdapterMock); + verifyNew(ReportOptionsAdapter.class, times(1)).withArguments(sessionStorageMock, REPORT_UNIT_URI, OPTIONS_ID); + } + + @Test + public void should_return_proper_ReportOptionsAdapter_object_by_options_map() throws Exception { + MultivaluedHashMap map = new MultivaluedHashMap<>(); + /* When */ + PowerMockito.whenNew(ReportOptionsAdapter .class).withArguments(sessionStorageMock, REPORT_UNIT_URI, map).thenReturn(reportOptionsAdapterMock); + + ReportsAdapter adapterSpy = new ReportsAdapter(sessionStorageMock, REPORT_UNIT_URI); + ReportOptionsAdapter retrieved = adapterSpy.reportOptions(map); + + assertSame(retrieved, reportOptionsAdapterMock); + verifyNew(ReportOptionsAdapter.class, times(1)).withArguments(sessionStorageMock, REPORT_UNIT_URI, map); + } + + @Test + public void should_return_proper_ReportOptionsAdapter_object_by_options_list() throws Exception { + List parameterList = new LinkedList<>(); + MultivaluedHashMap map = spy(new MultivaluedHashMap()); + /* When */ + mockStatic(ReportOptionsUtil.class); + when(ReportOptionsUtil.toMap(parameterList)).thenReturn(map); + PowerMockito.whenNew(ReportOptionsAdapter.class).withArguments(sessionStorageMock, REPORT_UNIT_URI, map).thenReturn(reportOptionsAdapterMock); + + ReportsAdapter adapterSpy = new ReportsAdapter(sessionStorageMock, REPORT_UNIT_URI); + ReportOptionsAdapter retrieved = adapterSpy.reportOptions(parameterList); + + assertSame(retrieved, reportOptionsAdapterMock); + verifyNew(ReportOptionsAdapter.class, times(1)).withArguments(sessionStorageMock, REPORT_UNIT_URI, map); } @Test public void should_return_proper_ReorderingReportParametersAdapter_object() throws Exception { /* When */ - PowerMockito.whenNew(ReorderingReportParametersAdapter.class).withArguments(sessionStorageMock, "reportUnitUri").thenReturn(adapterMock); + PowerMockito.whenNew(ReorderingReportParametersAdapter.class).withArguments(sessionStorageMock, REPORT_UNIT_URI).thenReturn(reportParametersAdapterMock); - ReportsAdapter adapterSpy = new ReportsAdapter(sessionStorageMock, "reportUnitUri"); + ReportsAdapter adapterSpy = new ReportsAdapter(sessionStorageMock, REPORT_UNIT_URI); ReorderingReportParametersAdapter retrieved = adapterSpy.reportParameters(); - assertSame(retrieved, adapterMock); - verifyNew(ReorderingReportParametersAdapter.class, times(1)).withArguments(sessionStorageMock, "reportUnitUri"); + assertSame(retrieved, reportParametersAdapterMock); + verifyNew(ReorderingReportParametersAdapter.class, times(1)).withArguments(sessionStorageMock, REPORT_UNIT_URI); } @Test @@ -71,43 +143,43 @@ public void should_return_proper_ReportParametersAdapter_instance() throws Excep /* Given */ ReportParametersAdapter parametersAdapterMock = mock(ReportParametersAdapter.class); - whenNew(ReportParametersAdapter.class).withArguments(sessionStorageMock, "reportUnitUri", "1;2;3;4;5;").thenReturn(parametersAdapterMock); - ReportsAdapter adapterSpy = new ReportsAdapter(sessionStorageMock, "reportUnitUri"); + whenNew(ReportParametersAdapter.class).withArguments(sessionStorageMock, REPORT_UNIT_URI, "1;2;3;4;5;").thenReturn(parametersAdapterMock); + ReportsAdapter adapterSpy = new ReportsAdapter(sessionStorageMock, REPORT_UNIT_URI); /* When */ ReportParametersAdapter retrieved = adapterSpy.reportParameters("1", "2", "3", "4", "5"); /* Then */ assertSame(retrieved, parametersAdapterMock); - verifyNew(ReportParametersAdapter.class, times(1)).withArguments(sessionStorageMock, "reportUnitUri", "1;2;3;4;5;"); + verifyNew(ReportParametersAdapter.class, times(1)).withArguments(sessionStorageMock, REPORT_UNIT_URI, "1;2;3;4;5;"); } @Test public void should_convert_params_into_the_adapter_with_pages() throws Exception { /* Given */ - ReportsAdapter adapterSpy = new ReportsAdapter(sessionStorageMock, "reportUnitUri"); + ReportsAdapter adapterSpy = new ReportsAdapter(sessionStorageMock, REPORT_UNIT_URI); /* When */ RunReportAdapter retrieved = adapterSpy.prepareForRun(ReportOutputFormat.PDF, 1, 2, 3); /* Then */ assertSame(retrieved.getSessionStorage(), sessionStorageMock); - assertEquals(Whitebox.getInternalState(retrieved, "reportUnitUri"), "reportUnitUri"); + assertEquals(Whitebox.getInternalState(retrieved, REPORT_UNIT_URI), REPORT_UNIT_URI); assertEquals(Whitebox.getInternalState(retrieved, "pages"), new String[]{"1", "2", "3"}); } @Test public void should_convert_params_into_the_adapter_with_format() throws Exception { /* Given */ - ReportsAdapter adapterSpy = new ReportsAdapter(sessionStorageMock, "reportUnitUri"); + ReportsAdapter adapterSpy = new ReportsAdapter(sessionStorageMock, REPORT_UNIT_URI); /* When */ RunReportAdapter retrieved = adapterSpy.prepareForRun(ReportOutputFormat.PDF); /* Then */ assertSame(retrieved.getSessionStorage(), sessionStorageMock); - assertEquals(Whitebox.getInternalState(retrieved, "reportUnitUri"), "reportUnitUri"); + assertEquals(Whitebox.getInternalState(retrieved, REPORT_UNIT_URI), REPORT_UNIT_URI); assertEquals(Whitebox.getInternalState(retrieved, "format"), new String("pdf")); } @@ -115,14 +187,14 @@ public void should_convert_params_into_the_adapter_with_format() throws Exceptio public void should_convert_params_into_the_adapter_without_pages() throws Exception { /* Given */ - ReportsAdapter adapterSpy = new ReportsAdapter(sessionStorageMock, "reportUnitUri"); + ReportsAdapter adapterSpy = new ReportsAdapter(sessionStorageMock, REPORT_UNIT_URI); /* When */ - RunReportAdapter retrieved = adapterSpy.prepareForRun(ReportOutputFormat.PDF, new PageRange(1, 10)); + RunReportAdapter retrieved = adapterSpy.prepareForRun(com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util.ReportOutputFormat.PDF, new com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util.PageRange(1, 10)); /* Then */ assertSame(retrieved.getSessionStorage(), sessionStorageMock); - assertEquals(Whitebox.getInternalState(retrieved, "reportUnitUri"), "reportUnitUri"); + assertEquals(Whitebox.getInternalState(retrieved, REPORT_UNIT_URI), REPORT_UNIT_URI); assertEquals(Whitebox.getInternalState(retrieved, "pages"), new String[]{"1-10"}); } @@ -131,14 +203,14 @@ public void should_convert_params_into_the_adapter_without_pages() throws Except public void should_convert_params_into_the_adapter_with_pages_and_format_as_string() throws Exception { /* Given */ - ReportsAdapter adapterSpy = new ReportsAdapter(sessionStorageMock, "reportUnitUri"); + ReportsAdapter adapterSpy = new ReportsAdapter(sessionStorageMock, REPORT_UNIT_URI); /* When */ RunReportAdapter retrieved = adapterSpy.prepareForRun("PDF", 1, 2, 3); /* Then */ assertSame(retrieved.getSessionStorage(), sessionStorageMock); - assertEquals(Whitebox.getInternalState(retrieved, "reportUnitUri"), "reportUnitUri"); + assertEquals(Whitebox.getInternalState(retrieved, REPORT_UNIT_URI), REPORT_UNIT_URI); assertEquals(Whitebox.getInternalState(retrieved, "pages"), new String[]{"1", "2", "3"}); assertEquals(Whitebox.getInternalState(retrieved, "format"), "pdf"); } @@ -146,14 +218,14 @@ public void should_convert_params_into_the_adapter_with_pages_and_format_as_stri public void should_convert_params_into_the_adapter_with_format_as_string_in_uppercase() throws Exception { /* Given */ - ReportsAdapter adapterSpy = new ReportsAdapter(sessionStorageMock, "reportUnitUri"); + ReportsAdapter adapterSpy = new ReportsAdapter(sessionStorageMock, REPORT_UNIT_URI); /* When */ RunReportAdapter retrieved = adapterSpy.prepareForRun("HTML"); /* Then */ assertSame(retrieved.getSessionStorage(), sessionStorageMock); - assertEquals(Whitebox.getInternalState(retrieved, "reportUnitUri"), "reportUnitUri"); + assertEquals(Whitebox.getInternalState(retrieved, REPORT_UNIT_URI), REPORT_UNIT_URI); assertEquals(Whitebox.getInternalState(retrieved, "format"), "html"); } @@ -161,14 +233,14 @@ public void should_convert_params_into_the_adapter_with_format_as_string_in_uppe public void should_convert_params_into_the_adapter_with_format_as_string() throws Exception { /* Given */ - ReportsAdapter adapterSpy = new ReportsAdapter(sessionStorageMock, "reportUnitUri"); + ReportsAdapter adapterSpy = new ReportsAdapter(sessionStorageMock, REPORT_UNIT_URI); /* When */ RunReportAdapter retrieved = adapterSpy.prepareForRun("pdf"); /* Then */ assertSame(retrieved.getSessionStorage(), sessionStorageMock); - assertEquals(Whitebox.getInternalState(retrieved, "reportUnitUri"), "reportUnitUri"); + assertEquals(Whitebox.getInternalState(retrieved, REPORT_UNIT_URI), REPORT_UNIT_URI); assertEquals(Whitebox.getInternalState(retrieved, "format"), "pdf"); } @@ -177,20 +249,20 @@ public void should_convert_params_into_the_adapter_with_format_as_string() throw public void should_convert_params_into_the_adapter_without_pages_as_string() throws Exception { /* Given */ - ReportsAdapter adapterSpy = new ReportsAdapter(sessionStorageMock, "reportUnitUri"); + ReportsAdapter adapterSpy = new ReportsAdapter(sessionStorageMock, REPORT_UNIT_URI); /* When */ - RunReportAdapter retrieved = adapterSpy.prepareForRun("pdf", new PageRange(1, 10)); + RunReportAdapter retrieved = adapterSpy.prepareForRun("pdf", new com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util.PageRange(1, 10)); /* Then */ assertSame(retrieved.getSessionStorage(), sessionStorageMock); - assertEquals(Whitebox.getInternalState(retrieved, "reportUnitUri"), "reportUnitUri"); + assertEquals(Whitebox.getInternalState(retrieved, REPORT_UNIT_URI), REPORT_UNIT_URI); assertEquals(Whitebox.getInternalState(retrieved, "pages"), new String[]{"1-10"}); assertEquals(Whitebox.getInternalState(retrieved, "format"), "pdf"); } @AfterMethod public void after() { - reset(sessionStorageMock, /*formatMock, */reportAdapterMock, parametersAdapterMock, adapterMock); + reset(sessionStorageMock, /*formatMock, */reportAdapterMock, parametersAdapterMock, reportOptionsAdapterMock, reportParametersAdapterMock); } } \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/RunReportAdapterTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/RunReportAdapterTest.java index 90ee2ddc..c1f20a0c 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/RunReportAdapterTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/RunReportAdapterTest.java @@ -6,10 +6,6 @@ import com.jaspersoft.jasperserver.jaxrs.client.core.RestClientConfiguration; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; -import java.io.InputStream; -import java.util.TimeZone; -import java.util.concurrent.atomic.AtomicInteger; -import javax.ws.rs.core.MultivaluedHashMap; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; @@ -19,6 +15,11 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import javax.ws.rs.core.MultivaluedHashMap; +import java.io.InputStream; +import java.util.TimeZone; +import java.util.concurrent.atomic.AtomicInteger; + import static com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest.buildRequest; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; @@ -68,7 +69,7 @@ public void should_return_a_RequestExecution_instance() throws Exception { final AtomicInteger newThreadId = new AtomicInteger(); int currentThreadId = (int) Thread.currentThread().getId(); - RunReportAdapter adapterSpy = spy(new RunReportAdapter(sessionStorageMock, "fakeReportUnitUri", ReportOutputFormat.PDF.toString().toLowerCase(), new PageRange(1L, 100L))); + RunReportAdapter adapterSpy = spy(new RunReportAdapter(sessionStorageMock, "fakeReportUnitUri", com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util.ReportOutputFormat.PDF.toString().toLowerCase(), new com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util.PageRange(1L, 100L))); Callback, Void> callbackSpy = spy(new Callback, Void>() { @@ -115,7 +116,7 @@ public void should_return_report_as_IS() { when(buildRequest(eq(sessionStorageMock), eq(InputStream.class), eq(new String[]{"reports", "uri" + "." + ReportOutputFormat.CSV.toString().toLowerCase()}), any(RunReportErrorHandler.class))).thenReturn(requestMock); doReturn(resultMock).when(requestMock).get(); - RunReportAdapter adapter = new RunReportAdapter(sessionStorageMock, "uri", ReportOutputFormat.CSV.toString().toLowerCase(), new PageRange(1, 10)); + RunReportAdapter adapter = new RunReportAdapter(sessionStorageMock, "uri", ReportOutputFormat.CSV.toString().toLowerCase(), new com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.util.PageRange(1, 10)); adapter.parameter("key", "val"); // When diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/reportoptions/ReportOptionsAdapterTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/reportoptions/ReportOptionsAdapterTest.java new file mode 100644 index 00000000..73d6cbcb --- /dev/null +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/reporting/reportoptions/ReportOptionsAdapterTest.java @@ -0,0 +1,201 @@ +package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.reporting.reportoptions; + +import com.jaspersoft.jasperserver.dto.reports.ReportParameter; +import com.jaspersoft.jasperserver.dto.reports.options.ReportOptionsSummary; +import com.jaspersoft.jasperserver.dto.reports.options.ReportOptionsSummaryList; +import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; +import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; +import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; +import java.util.LinkedList; +import java.util.List; +import javax.ws.rs.core.MultivaluedHashMap; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.testng.PowerMockTestCase; +import org.powermock.reflect.Whitebox; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import static org.mockito.Matchers.anyMap; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.MockitoAnnotations.initMocks; +import static org.powermock.api.mockito.PowerMockito.verifyStatic; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertSame; + +/** + *

+ *

+ * + * @author tetiana.iefimenko + * @version $Id$ + * @see + */ +@PrepareForTest({JerseyRequest.class}) +public class ReportOptionsAdapterTest extends PowerMockTestCase { + + private static final String REPORT_UNIT_URI = "reportUnitUri"; + private static final String OPTIONS_ID = "optionsId"; + private final String REPORT_SERVICE_URI = "reports"; + private final String OPTIONS_SERVICE_URI = "options"; + + @Mock + private SessionStorage sessionStorageMock; + + @Mock + private JerseyRequest requestMock; + + @Mock + private OperationResult resultMock; + + @BeforeMethod + public void before() { + initMocks(this); + } + + @AfterMethod + public void after() { + reset(sessionStorageMock, requestMock, resultMock); + } + + @Test + public void should_pass_session_to_parent_class() { + + /* When */ + ReportOptionsAdapter adapterSpy = new ReportOptionsAdapter(sessionStorageMock, REPORT_UNIT_URI); + + /* Then */ + assertSame(adapterSpy.getSessionStorage(), sessionStorageMock); + String reportUnitUri = Whitebox.getInternalState(adapterSpy, REPORT_UNIT_URI); + assertEquals(reportUnitUri, REPORT_UNIT_URI); + } + + @Test + public void should_return_proper_operationResult_when_get() throws Exception { + ReportOptionsAdapter adapter = new ReportOptionsAdapter(sessionStorageMock, REPORT_UNIT_URI); + //when + PowerMockito.mockStatic(JerseyRequest.class); + PowerMockito.when(JerseyRequest.buildRequest(eq(sessionStorageMock), + eq(ReportOptionsSummaryList.class), eq(new String[]{REPORT_SERVICE_URI, REPORT_UNIT_URI, OPTIONS_SERVICE_URI}))).thenReturn(requestMock); + PowerMockito.doReturn(resultMock).when(requestMock).get(); + + OperationResult result = adapter.get(); + //then + assertSame(result, resultMock); + verifyStatic(times(1)); + JerseyRequest.buildRequest(sessionStorageMock, + ReportOptionsSummaryList.class, + new String[]{REPORT_SERVICE_URI, REPORT_UNIT_URI, OPTIONS_SERVICE_URI}); + Mockito.verify(requestMock).get(); + } + + @Test + public void should_return_proper_operationResult_when_create() throws Exception { + MultivaluedHashMap options = new MultivaluedHashMap<>(); + ReportOptionsAdapter adapter = new ReportOptionsAdapter(sessionStorageMock, REPORT_UNIT_URI, options); + //when + PowerMockito.mockStatic(JerseyRequest.class); + PowerMockito.when(JerseyRequest.buildRequest(eq(sessionStorageMock), + eq(ReportOptionsSummary.class), eq(new String[]{REPORT_SERVICE_URI, REPORT_UNIT_URI, OPTIONS_SERVICE_URI}))).thenReturn(requestMock); + PowerMockito.doReturn(resultMock).when(requestMock).post(options); + + OperationResult result = adapter.create(); + //then + assertSame(result, resultMock); + verifyStatic(times(1)); + JerseyRequest.buildRequest(sessionStorageMock, + ReportOptionsSummary.class, + new String[]{REPORT_SERVICE_URI, REPORT_UNIT_URI, OPTIONS_SERVICE_URI}); + Mockito.verify(requestMock).post(options); + } + + @Test + public void should_return_proper_operationResult_when_create_with_params() throws Exception { + MultivaluedHashMap options = new MultivaluedHashMap<>(); + ReportOptionsAdapter adapter = new ReportOptionsAdapter(sessionStorageMock, REPORT_UNIT_URI, options); + //when + PowerMockito.mockStatic(JerseyRequest.class); + PowerMockito.when(JerseyRequest.buildRequest(eq(sessionStorageMock), + eq(ReportOptionsSummary.class), eq(new String[]{REPORT_SERVICE_URI, REPORT_UNIT_URI, OPTIONS_SERVICE_URI}))).thenReturn(requestMock); + PowerMockito.doReturn(requestMock).when(requestMock).addParam("label", "label"); + PowerMockito.doReturn(requestMock).when(requestMock).addParam("overwrite", "true"); + PowerMockito.doReturn(resultMock).when(requestMock).post(options); + + OperationResult result = adapter.label("label").overwrite(Boolean.TRUE).create(); + //then + assertSame(result, resultMock); + verifyStatic(times(1)); + JerseyRequest.buildRequest(sessionStorageMock, + ReportOptionsSummary.class, + new String[]{REPORT_SERVICE_URI, REPORT_UNIT_URI, OPTIONS_SERVICE_URI}); + Mockito.verify(requestMock).addParam("label", "label"); + Mockito.verify(requestMock).addParam("overwrite", "true"); + Mockito.verify(requestMock).post(options); + } + + + @Test + public void should_return_proper_operationResult_when_update_map() throws Exception { + MultivaluedHashMap options = new MultivaluedHashMap<>(); + ReportOptionsAdapter adapter = new ReportOptionsAdapter(sessionStorageMock, REPORT_UNIT_URI, OPTIONS_ID); + //when + PowerMockito.mockStatic(JerseyRequest.class); + PowerMockito.when(JerseyRequest.buildRequest(eq(sessionStorageMock), + eq(ReportOptionsSummary.class), eq(new String[]{REPORT_SERVICE_URI, REPORT_UNIT_URI, OPTIONS_SERVICE_URI, OPTIONS_ID}))).thenReturn(requestMock); + PowerMockito.doReturn(resultMock).when(requestMock).put(options); + + OperationResult result = adapter.update(options); + //then + assertSame(result, resultMock); + verifyStatic(times(1)); + JerseyRequest.buildRequest(sessionStorageMock, + ReportOptionsSummary.class, + new String[]{REPORT_SERVICE_URI, REPORT_UNIT_URI, OPTIONS_SERVICE_URI, OPTIONS_ID}); + Mockito.verify(requestMock).put(options); + } + + @Test + public void should_return_proper_operationResult_when_update_list() throws Exception { + List parameterList = new LinkedList<>(); + ReportOptionsAdapter adapter = new ReportOptionsAdapter(sessionStorageMock, REPORT_UNIT_URI, OPTIONS_ID); + //when + PowerMockito.mockStatic(JerseyRequest.class); + PowerMockito.when(JerseyRequest.buildRequest(eq(sessionStorageMock), + eq(ReportOptionsSummary.class), eq(new String[]{REPORT_SERVICE_URI, REPORT_UNIT_URI, OPTIONS_SERVICE_URI, OPTIONS_ID}))).thenReturn(requestMock); + PowerMockito.doReturn(resultMock).when(requestMock).put(anyMap()); + + OperationResult result = adapter.update(parameterList); + //then + assertSame(result, resultMock); + verifyStatic(times(1)); + JerseyRequest.buildRequest(sessionStorageMock, + ReportOptionsSummary.class, + new String[]{REPORT_SERVICE_URI, REPORT_UNIT_URI, OPTIONS_SERVICE_URI, OPTIONS_ID}); + Mockito.verify(requestMock).put(anyMap()); + } + + @Test + public void should_return_proper_operationResult_when_delete() throws Exception { + ReportOptionsAdapter adapter = new ReportOptionsAdapter(sessionStorageMock, REPORT_UNIT_URI, OPTIONS_ID); + //when + PowerMockito.mockStatic(JerseyRequest.class); + PowerMockito.when(JerseyRequest.buildRequest(eq(sessionStorageMock), + eq(Object.class), eq(new String[]{REPORT_SERVICE_URI, REPORT_UNIT_URI, OPTIONS_SERVICE_URI, OPTIONS_ID}))).thenReturn(requestMock); + PowerMockito.doReturn(resultMock).when(requestMock).delete(); + + OperationResult result = adapter.delete(); + //then + assertSame(result, resultMock); + verifyStatic(times(1)); + JerseyRequest.buildRequest(sessionStorageMock, + Object.class, + new String[]{REPORT_SERVICE_URI, REPORT_UNIT_URI, OPTIONS_SERVICE_URI, OPTIONS_ID}); + Mockito.verify(requestMock).delete(); + } + +} \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/BatchResourcesAdapterTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/BatchResourcesAdapterTest.java index 8609dbed..c1e2ff0c 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/BatchResourcesAdapterTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/BatchResourcesAdapterTest.java @@ -1,6 +1,7 @@ package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources; import com.jaspersoft.jasperserver.dto.resources.ClientResourceListWrapper; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.ResourceSearchParameter; import com.jaspersoft.jasperserver.jaxrs.client.core.Callback; import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; import com.jaspersoft.jasperserver.jaxrs.client.core.RequestExecution; @@ -65,9 +66,15 @@ public void before() { initMocks(this); } + + @AfterMethod + public void after() { + reset(sessionStorageMock, requestMock, resultMock, objectJerseyRequestMock, objectOperationResultMock); + } + @Test /** - * for {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.BatchResourcesAdapter#parameter(com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.ResourceSearchParameter, String)} + * for {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.BatchResourcesAdapter#parameter(com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.ResourceSearchParameter, String)} */ @SuppressWarnings("unchecked") public void should_set_parameter_of_adapter() { @@ -235,8 +242,4 @@ public void should_delete_resource_and_return_operation_result() { assertSame(retrieved, objectOperationResultMock); } - @AfterMethod - public void after() { - reset(sessionStorageMock, requestMock, resultMock, objectJerseyRequestMock, objectOperationResultMock); - } } \ No newline at end of file diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourceFilesMimeTypeTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourceFilesMimeTypeTest.java index 8649b6c1..61fb69a4 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourceFilesMimeTypeTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourceFilesMimeTypeTest.java @@ -1,5 +1,6 @@ package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.ResourceFilesMimeType; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourcesTypeResolverUtilTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourcesTypeResolverUtilTest.java index a894a564..1078b3e9 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourcesTypeResolverUtilTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/ResourcesTypeResolverUtilTest.java @@ -4,6 +4,7 @@ import com.jaspersoft.jasperserver.dto.resources.ClientOlapUnit; import com.jaspersoft.jasperserver.dto.resources.ClientQuery; import com.jaspersoft.jasperserver.dto.resources.ClientResource; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.ResourcesTypeResolverUtil; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/SingleResourceAdapterTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/SingleResourceAdapterTest.java index 4fb8d4be..a31b7f09 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/SingleResourceAdapterTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/SingleResourceAdapterTest.java @@ -6,6 +6,7 @@ import com.jaspersoft.jasperserver.dto.resources.ClientResource; import com.jaspersoft.jasperserver.dto.resources.ClientVirtualDataSource; import com.jaspersoft.jasperserver.dto.resources.ResourceMediaType; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.ResourceValidationErrorHandler; import com.jaspersoft.jasperserver.jaxrs.client.core.Callback; import com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest; import com.jaspersoft.jasperserver.jaxrs.client.core.RequestExecution; @@ -14,15 +15,8 @@ import com.jaspersoft.jasperserver.jaxrs.client.core.enums.MimeType; import com.jaspersoft.jasperserver.jaxrs.client.core.exceptions.handling.DefaultErrorHandler; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; -import com.sun.jersey.multipart.FormDataBodyPart; -import com.sun.jersey.multipart.FormDataMultiPart; -import java.io.File; -import java.io.InputStream; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; +import org.glassfish.jersey.media.multipart.FormDataBodyPart; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; @@ -35,6 +29,14 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import java.io.File; +import java.io.InputStream; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + import static com.jaspersoft.jasperserver.dto.resources.ClientFile.FileType; import static com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest.buildRequest; import static org.mockito.Matchers.any; @@ -62,52 +64,36 @@ public class SingleResourceAdapterTest extends PowerMockTestCase { @Captor private ArgumentCaptor captor; - - @Mock private SessionStorage sessionStorageMock; @Mock private RestClientConfiguration configurationMock; @Mock private PatchDescriptor descriptorMock; - - @Mock private JerseyRequest jerseyRequestMock; @Mock private OperationResult operationResultMock; - - @Mock private JerseyRequest objectJerseyRequestMock; @Mock private OperationResult objectOperationResultMock; - - @Mock private JerseyRequest clientFileJerseyRequestMock; @Mock private OperationResult clientFileOperationResultMock; - - @Mock private JerseyRequest adhocDataViewJerseyRequestMock; @Mock private OperationResult adhocDataViewOperationResultMock; - - @Mock private JerseyRequest inputStreamJerseyRequestMock; @Mock private OperationResult inputStreamOperationResultMock; - - @Mock private JerseyRequest virtualDataSourceJerseyRequestMock; @Mock private OperationResult virtualDataSourceOperationResultMock; - - @Mock private File fileMock; @@ -117,6 +103,16 @@ public void before() { initMocks(this); } + @AfterMethod + public void after() { + reset(sessionStorageMock, configurationMock, jerseyRequestMock, operationResultMock, objectJerseyRequestMock, + objectOperationResultMock, clientFileJerseyRequestMock, + clientFileOperationResultMock, fileMock, adhocDataViewJerseyRequestMock, + adhocDataViewOperationResultMock, configurationMock, descriptorMock, + inputStreamJerseyRequestMock, inputStreamOperationResultMock, + virtualDataSourceJerseyRequestMock, virtualDataSourceOperationResultMock); + } + @Test /** * for {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.SingleResourceAdapter#asyncDetails(com.jaspersoft.jasperserver.jaxrs.client.core.Callback)} @@ -218,7 +214,7 @@ public Void execute(OperationResult data) { @Test /** - * for {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.SingleResourceAdapter#parameter(com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.ResourceServiceParameter, String)} + * for {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.SingleResourceAdapter#parameter(com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.ResourceServiceParameter, String)} */ @SuppressWarnings("unchecked") public void should_set_parameter() { @@ -227,12 +223,12 @@ public void should_set_parameter() { SingleResourceAdapter adapter = new SingleResourceAdapter(sessionStorageMock, "resourceUri"); /** When **/ - SingleResourceAdapter retrieved = adapter.parameter(ResourceServiceParameter.CREATE_FOLDERS, "true"); + SingleResourceAdapter retrieved = adapter.parameter(com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.ResourceServiceParameter.CREATE_FOLDERS, "true"); /** Then **/ assertSame(adapter, retrieved); MultivaluedMap retrievedParams = (MultivaluedMap) Whitebox.getInternalState(retrieved, "params"); - String param = retrievedParams.get(ResourceServiceParameter.CREATE_FOLDERS.getName()).get(0); + String param = retrievedParams.get(com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.ResourceServiceParameter.CREATE_FOLDERS.getName()).get(0); assertEquals(param, "true"); } @@ -365,7 +361,7 @@ public void should_return_operation_result_with_client_resource_folder() { assertNotNull(retrieved); assertSame(retrieved, operationResultMock); - Mockito.verify(jerseyRequestMock).addParams(any(MultivaluedHashMap.class)); + Mockito.verify(jerseyRequestMock, times(1)).addParams(any(MultivaluedHashMap.class)); Mockito.verify(jerseyRequestMock).setAccept(ResourceMediaType.FOLDER_JSON); Mockito.verify(jerseyRequestMock).get(); } @@ -395,7 +391,7 @@ public void should_return_operation_result_with_client_resource_folder_as_xml() assertNotNull(retrieved); assertSame(retrieved, operationResultMock); - Mockito.verify(jerseyRequestMock).addParams(any(MultivaluedHashMap.class)); + Mockito.verify(jerseyRequestMock, times(1)).addParams(any(MultivaluedHashMap.class)); Mockito.verify(jerseyRequestMock).setAccept(ResourceMediaType.FOLDER_XML); Mockito.verify(jerseyRequestMock).get(); } @@ -498,7 +494,7 @@ public void should_send_descriptor_into_server() { Mockito.verify(adhocDataViewJerseyRequestMock).post(descriptorMock); Mockito.verify(adhocDataViewJerseyRequestMock).setAccept("application/repository.adhocDataView+json"); Mockito.verify(adhocDataViewJerseyRequestMock).addHeader("X-HTTP-Method-Override", "PATCH"); - Mockito.verifyNoMoreInteractions(adhocDataViewJerseyRequestMock); + Mockito.verify(adhocDataViewJerseyRequestMock).addParams(any(MultivaluedHashMap.class)); } @Test @@ -611,6 +607,7 @@ public void should_update_resource_asynchronously() throws InterruptedException doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); doReturn(MimeType.JSON).when(configurationMock).getContentMimeType(); + doReturn(MimeType.JSON).when(configurationMock).getAcceptMimeType(); SingleResourceAdapter adapter = new SingleResourceAdapter(sessionStorageMock, resourceUri); final AtomicInteger newThreadId = new AtomicInteger(); @@ -647,7 +644,7 @@ public Void execute(OperationResult data) { Mockito.verify(callback).execute(operationResultMock); Mockito.verify(virtualDataSourceJerseyRequestMock).addParams(any(MultivaluedHashMap.class)); Mockito.verify(virtualDataSourceJerseyRequestMock).setContentType("application/repository.virtualDataSource+json"); - Mockito.verifyNoMoreInteractions(virtualDataSourceJerseyRequestMock); + Mockito.verify(virtualDataSourceJerseyRequestMock).setAccept("application/repository.virtualDataSource+json"); } @Test @@ -769,6 +766,7 @@ public void should_create_new_resource_asynchronously() throws InterruptedExcept doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); doReturn(MimeType.JSON).when(configurationMock).getContentMimeType(); + doReturn(MimeType.JSON).when(configurationMock).getAcceptMimeType(); SingleResourceAdapter adapter = new SingleResourceAdapter(sessionStorageMock, resourceUri); final AtomicInteger newThreadId = new AtomicInteger(); @@ -805,7 +803,7 @@ public Void execute(OperationResult data) { Mockito.verify(callback).execute(operationResultMock); Mockito.verify(virtualDataSourceJerseyRequestMock).addParams(any(MultivaluedHashMap.class)); Mockito.verify(virtualDataSourceJerseyRequestMock).setContentType("application/repository.virtualDataSource+json"); - Mockito.verifyNoMoreInteractions(virtualDataSourceJerseyRequestMock); + Mockito.verify(virtualDataSourceJerseyRequestMock).setAccept("application/repository.virtualDataSource+json"); } @Test @@ -826,6 +824,7 @@ public void should_create_new_resource() { doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); doReturn(MimeType.JSON).when(configurationMock).getContentMimeType(); + doReturn(MimeType.JSON).when(configurationMock).getAcceptMimeType(); SingleResourceAdapter adapter = new SingleResourceAdapter(sessionStorageMock, resourceUri); @@ -839,7 +838,7 @@ public void should_create_new_resource() { Mockito.verify(virtualDataSourceJerseyRequestMock).post(source); Mockito.verify(virtualDataSourceJerseyRequestMock).addParams(any(MultivaluedHashMap.class)); Mockito.verify(virtualDataSourceJerseyRequestMock).setContentType("application/repository.virtualDataSource+json"); - Mockito.verifyNoMoreInteractions(virtualDataSourceJerseyRequestMock); + Mockito.verify(virtualDataSourceJerseyRequestMock).setAccept("application/repository.virtualDataSource+json"); } @Test @@ -860,11 +859,12 @@ public void should_update_resource() throws InterruptedException { doReturn(configurationMock).when(sessionStorageMock).getConfiguration(); doReturn(MimeType.JSON).when(configurationMock).getContentMimeType(); + doReturn(MimeType.JSON).when(configurationMock).getAcceptMimeType(); SingleResourceAdapter adapter = new SingleResourceAdapter(sessionStorageMock, resourceUri); /** When **/ - OperationResult retrieved = adapter.createOrUpdate(source); + OperationResult retrieved = adapter.createOrUpdate(source); /** Then **/ @@ -873,7 +873,7 @@ public void should_update_resource() throws InterruptedException { Mockito.verify(virtualDataSourceJerseyRequestMock).put(source); Mockito.verify(virtualDataSourceJerseyRequestMock).addParams(any(MultivaluedHashMap.class)); Mockito.verify(virtualDataSourceJerseyRequestMock).setContentType("application/repository.virtualDataSource+json"); - Mockito.verifyNoMoreInteractions(virtualDataSourceJerseyRequestMock); + Mockito.verify(virtualDataSourceJerseyRequestMock).setAccept("application/repository.virtualDataSource+json"); } @@ -968,13 +968,4 @@ public void should_copy_resource() throws InterruptedException { Mockito.verify(jerseyRequestMock).addHeader("Content-Location", "fromUri"); } - @AfterMethod - public void after() { - reset(configurationMock, jerseyRequestMock, operationResultMock, objectJerseyRequestMock, - objectOperationResultMock, clientFileJerseyRequestMock, - clientFileOperationResultMock, fileMock, adhocDataViewJerseyRequestMock, - adhocDataViewOperationResultMock, configurationMock, descriptorMock, - inputStreamJerseyRequestMock, inputStreamOperationResultMock, - virtualDataSourceJerseyRequestMock, virtualDataSourceOperationResultMock); - } } diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/ResourceBuilderFactoryTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/ResourceBuilderFactoryTest.java index 3d152bf1..5ceba57f 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/ResourceBuilderFactoryTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/ResourceBuilderFactoryTest.java @@ -4,10 +4,11 @@ import com.jaspersoft.jasperserver.dto.resources.ClientReportUnit; import com.jaspersoft.jasperserver.dto.resources.ClientSecureMondrianConnection; import com.jaspersoft.jasperserver.dto.resources.ClientSemanticLayerDataSource; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.builder.DomainResourceBuilder; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.builder.MondrianConnectionResourceBuilder; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.builder.ReportUnitResourceBuilder; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.builder.SecureMondrianConnectionResourceBuilder; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.ResourceBuilderFactory; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.builder.SemanticLayerResourceBuilder; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.builder.MondrianConnectionResourceBuilder; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.builder.ReportUnitResourceBuilder; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.builder.SecureMondrianConnectionResourceBuilder; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; import org.mockito.Mock; import org.powermock.core.classloader.annotations.PrepareForTest; @@ -30,7 +31,7 @@ public class ResourceBuilderFactoryTest extends PowerMockTestCase { private SessionStorage sessionStorageMock; @Mock - private DomainResourceBuilder domainBuilderMock; + private SemanticLayerResourceBuilder domainBuilderMock; @Mock private MondrianConnectionResourceBuilder mondrianConnectionBuilderMock; @@ -51,16 +52,16 @@ public void should_invoke_proper_constructor_and_return_DomainResourceBuilder_in /* Given */ ClientSemanticLayerDataSource dataSource = new ClientSemanticLayerDataSource(); - whenNew(DomainResourceBuilder.class) + whenNew(SemanticLayerResourceBuilder.class) .withParameterTypes(ClientSemanticLayerDataSource.class, SessionStorage.class) .withArguments(dataSource, sessionStorageMock).thenReturn(domainBuilderMock); /* When */ - DomainResourceBuilder retrieved = ResourceBuilderFactory.getBuilder(dataSource, sessionStorageMock); + SemanticLayerResourceBuilder retrieved = ResourceBuilderFactory.getBuilder(dataSource, sessionStorageMock); /* Then */ assertSame(retrieved, domainBuilderMock); - verifyNew(DomainResourceBuilder.class, times(1)) + verifyNew(SemanticLayerResourceBuilder.class, times(1)) .withArguments(dataSource, sessionStorageMock); } diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/builder/SecureMondrianConnectionResourceBuilderTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/builder/SecureMondrianConnectionResourceBuilderTest.java index bbeee0d7..6858c547 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/builder/SecureMondrianConnectionResourceBuilderTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/resources/support/builder/SecureMondrianConnectionResourceBuilderTest.java @@ -1,14 +1,17 @@ package com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.support.builder; import com.jaspersoft.jasperserver.dto.resources.ClientSecureMondrianConnection; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.builder.SecureMondrianConnectionResourceBuilder; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.processor.CommonOperationProcessorImpl; import com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage; import org.mockito.Mockito; +import org.powermock.reflect.Whitebox; import org.testng.annotations.Test; import static org.testng.Assert.assertSame; /** - * Unit tests for {@link SecureMondrianConnectionResourceBuilder} + * Unit tests for {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.compexResourcesSupport.builder.SecureMondrianConnectionResourceBuilder} */ public class SecureMondrianConnectionResourceBuilderTest { @@ -17,8 +20,8 @@ public void should_pass_params_to_parent_class() { SessionStorage storageMock = Mockito.mock(SessionStorage.class); ClientSecureMondrianConnection dummyMondrianConnection = new ClientSecureMondrianConnection(); SecureMondrianConnectionResourceBuilder created = new SecureMondrianConnectionResourceBuilder(dummyMondrianConnection, storageMock); - SessionStorage retrievedStorage = created.getProcessor().getSessionStorage(); - ClientSecureMondrianConnection retrievedConnection = created.getConnection(); + SessionStorage retrievedStorage = ((CommonOperationProcessorImpl)Whitebox.getInternalState(created, "processor")).getSessionStorage(); + ClientSecureMondrianConnection retrievedConnection = Whitebox.getInternalState(created, "connection"); assertSame(retrievedStorage, storageMock); assertSame(retrievedConnection, dummyMondrianConnection); } diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/thumbnails/SingleThumbnailAdapterTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/thumbnails/SingleThumbnailAdapterTest.java index 1970db4a..461f9fdd 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/thumbnails/SingleThumbnailAdapterTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/apiadapters/thumbnails/SingleThumbnailAdapterTest.java @@ -16,7 +16,6 @@ import org.testng.annotations.Test; import static com.jaspersoft.jasperserver.jaxrs.client.core.JerseyRequest.buildRequest; -import static org.junit.Assert.assertNull; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.reset; @@ -27,8 +26,9 @@ import static org.powermock.api.mockito.PowerMockito.verifyStatic; import static org.powermock.api.mockito.PowerMockito.when; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertSame; -import static org.testng.AssertJUnit.assertNotNull; /** * Unit tests for {@link SingleThumbnailAdapter} diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/core/JasperserverRestClientTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/core/JasperserverRestClientTest.java index df61c3b5..d8a482ee 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/core/JasperserverRestClientTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/core/JasperserverRestClientTest.java @@ -63,7 +63,7 @@ public class JasperserverRestClientTest extends PowerMockTestCase { @Mock private Session sessionMock; @Mock - AnonymousSession anonymousSessionMock; + private AnonymousSession anonymousSessionMock; @Mock private WebTarget webTargetMock; @Mock @@ -124,6 +124,7 @@ public void should_return_null_when_username_is_null() { // Then assertEquals(session, null); } + @Test(testName = "JasperserverRestClient_authenticate") public void should_return_null_when_username_is_empty() { // Given @@ -135,26 +136,60 @@ public void should_return_null_when_username_is_empty() { assertEquals(session, null); } - @Test(testName = "JasperserverRestClient_authenticate") - public void should_return_null_when_password_is_null() { + @Test + public void should_return_proper_Session_object_when_password_is_empty() throws Exception { + // Given doReturn("url").when(configurationMock).getJasperReportsServerUrl(); - JasperserverRestClient jasperserverRestClient = new JasperserverRestClient(configurationMock); + final JasperserverRestClient client = new JasperserverRestClient(configurationMock); + final JasperserverRestClient spyClient = spy(client); + + whenNew(AuthenticationCredentials.class) + .withArguments(USER_NAME, "") + .thenReturn(credentialsMock); + + whenNew(SessionStorage.class) + .withArguments(eq(configurationMock), eq(credentialsMock), any(Locale.class), any(TimeZone.class)) + .thenReturn(sessionStorageMock); + + whenNew(Session.class) + .withArguments(sessionStorageMock) + .thenReturn(sessionMock); + doNothing().when(spyClient).login(sessionStorageMock); + // When - Session session = jasperserverRestClient.authenticate(USER_NAME, null); + Session retrieved = spyClient.authenticate(USER_NAME, ""); + // Then - assertEquals(session, null); + assertEquals(retrieved, sessionMock); } - @Test(testName = "JasperserverRestClient_authenticate") - public void should_return_null_when_password_is_empty() { + @Test + public void should_return_proper_Session_object_when_password_is_null() throws Exception { + // Given doReturn("url").when(configurationMock).getJasperReportsServerUrl(); - JasperserverRestClient jasperserverRestClient = new JasperserverRestClient(configurationMock); + final JasperserverRestClient client = new JasperserverRestClient(configurationMock); + final JasperserverRestClient spyClient = spy(client); + + whenNew(AuthenticationCredentials.class) + .withArguments(USER_NAME, (String)null) + .thenReturn(credentialsMock); + + whenNew(SessionStorage.class) + .withArguments(eq(configurationMock), eq(credentialsMock), any(Locale.class), any(TimeZone.class)) + .thenReturn(sessionStorageMock); + + whenNew(Session.class) + .withArguments(sessionStorageMock) + .thenReturn(sessionMock); + doNothing().when(spyClient).login(sessionStorageMock); + // When - Session session = jasperserverRestClient.authenticate(USER_NAME, ""); + Session retrieved = spyClient.authenticate(USER_NAME, (String) null); + // Then - assertEquals(session, null); + assertEquals(retrieved, sessionMock); } @Test @@ -212,6 +247,7 @@ public void should_return_proper_Session_object_with_time_zone_as_object() throw // Then assertEquals(retrieved, sessionMock); } + @Test public void should_return_proper_Session_object_with_time_zone_and_locale_as_objects() throws Exception { @@ -262,7 +298,7 @@ public void should_return_proper_Session_object_with_time_zone_is_object_and_loc doNothing().when(spyClient).login(sessionStorageMock); // When - Session retrieved = spyClient.authenticate(USER_NAME, PASSWORD, (Locale)null, TimeZone.getTimeZone(TIME_ZONE)); + Session retrieved = spyClient.authenticate(USER_NAME, PASSWORD, (Locale) null, TimeZone.getTimeZone(TIME_ZONE)); // Then assertEquals(retrieved, sessionMock); @@ -290,7 +326,7 @@ public void should_return_proper_Session_object_with_time_zone_is_object_and_loc doNothing().when(spyClient).login(sessionStorageMock); // When - Session retrieved = spyClient.authenticate(USER_NAME, PASSWORD, (String)null, TIME_ZONE); + Session retrieved = spyClient.authenticate(USER_NAME, PASSWORD, (String) null, TIME_ZONE); // Then assertEquals(retrieved, sessionMock); @@ -318,7 +354,7 @@ public void should_return_proper_Session_object_with_time_zone__is_nul_object_an doNothing().when(spyClient).login(sessionStorageMock); // When - Session retrieved = spyClient.authenticate(USER_NAME, PASSWORD,new Locale(LOCALE), (TimeZone) null); + Session retrieved = spyClient.authenticate(USER_NAME, PASSWORD, new Locale(LOCALE), (TimeZone) null); // Then assertEquals(retrieved, sessionMock); @@ -570,7 +606,7 @@ public void should_invoke_login_method_and_return_proper_session_object_with_tim verify(webTargetMock).request(); verify(formSpy).param("j_username", USER_NAME); verify(formSpy).param("j_password", PASSWORD); - verify(formSpy).param("userTimezone",TIME_ZONE); + verify(formSpy).param("userTimezone", TIME_ZONE); verify(formSpy).param("userLocale", locale.toString()); verify(invocationBuilderMock).post(Entity.entity(formSpy, MediaType.APPLICATION_FORM_URLENCODED_TYPE)); verify(responseMock).getLocation(); diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/core/JerseyRequestTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/core/JerseyRequestTest.java index 25b62a98..b9430fcb 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/core/JerseyRequestTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/core/JerseyRequestTest.java @@ -6,7 +6,6 @@ import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResult; import com.jaspersoft.jasperserver.jaxrs.client.core.operationresult.OperationResultFactoryImpl; import com.jaspersoft.jasperserver.jaxrs.client.providers.CustomRepresentationTypeProvider; -import com.sun.jersey.multipart.impl.MultiPartWriter; import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation; import javax.ws.rs.core.MediaType; @@ -82,7 +81,6 @@ public void setUp() throws Exception { when(webTarget.path(Mockito.anyString())).thenReturn(webTarget); when(webTarget.register(CustomRepresentationTypeProvider.class)).thenReturn(webTarget); when(webTarget.register(JacksonFeature.class)).thenReturn(webTarget); - when(webTarget.register(MultiPartWriter.class)).thenReturn(webTarget); } /** diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/core/SessionStorageTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/core/SessionStorageTest.java index 3f3cfbfe..2b8fd370 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/core/SessionStorageTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/core/SessionStorageTest.java @@ -1,7 +1,6 @@ package com.jaspersoft.jasperserver.jaxrs.client.core; import com.jaspersoft.jasperserver.jaxrs.client.filters.SessionOutputFilter; -import com.sun.jersey.multipart.impl.MultiPartWriter; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; @@ -18,6 +17,7 @@ import org.codehaus.jackson.jaxrs.JacksonJsonProvider; import org.glassfish.jersey.filter.LoggingFilter; import org.glassfish.jersey.jackson.JacksonFeature; +import org.glassfish.jersey.media.multipart.MultiPartFeature; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.internal.util.reflection.Whitebox; @@ -116,7 +116,7 @@ public void should_invoke_init_method_with_default_configuration() throws Except doReturn(null).when(configurationMock).getReadTimeout(); doReturn(targetMock).when(clientMock).target(anyString()); doReturn(targetMock).when(targetMock).register(JacksonFeature.class); - doReturn(targetMock).when(targetMock).register(MultiPartWriter.class); + doReturn(targetMock).when(targetMock).register(MultiPartFeature.class); doReturn(targetMock).when(targetMock).register(any(JacksonJsonProvider.class)); doReturn(false).when(configurationMock).getLogHttp(); @@ -133,7 +133,6 @@ public void should_invoke_init_method_with_default_configuration() throws Except verify(clientMock).target("http://54.83.98.156/jasperserver-pro"); verify(targetMock).register(JacksonFeature.class); verify(targetMock, times(1)).register(isA(JacksonJsonProvider.class)); - verify(targetMock).register(MultiPartWriter.class); verify(configurationMock).getLogHttp(); verify(targetMock, never()).register(LoggingFilter.class); } @@ -152,7 +151,7 @@ public void should_invoke_init_method_with_custom_configuration() throws Excepti doReturn(clientMock).when(clientMock).property("jersey.config.client.readTimeout", 200); doReturn(targetMock).when(clientMock).target(anyString()); doReturn(targetMock).when(targetMock).register(JacksonFeature.class); - doReturn(targetMock).when(targetMock).register(MultiPartWriter.class); + doReturn(targetMock).when(targetMock).register(MultiPartFeature.class); doReturn(targetMock).when(targetMock).register(any(JacksonJsonProvider.class)); doReturn(true).when(configurationMock).getLogHttp(); doReturn(targetMock).when(targetMock).register(any(LoggingFilter.class)); @@ -172,7 +171,6 @@ public void should_invoke_init_method_with_custom_configuration() throws Excepti verify(clientMock).target("http://54.83.98.156/jasperserver-pro"); verify(targetMock).register(JacksonFeature.class); verify(targetMock, times(1)).register(isA(JacksonJsonProvider.class)); - verify(targetMock).register(MultiPartWriter.class); verify(configurationMock).getLogHttp(); verify(targetMock).register(isA(LoggingFilter.class)); } @@ -206,7 +204,7 @@ public void should_return_client_with_configuration() throws Exception { Whitebox.setInternalState(sessionStorage, "sessionId", "sessionId"); doReturn(targetMock).when(clientMock).target(anyString()); doReturn(targetMock).when(targetMock).register(JacksonFeature.class); - doReturn(targetMock).when(targetMock).register(MultiPartWriter.class); + doReturn(targetMock).when(targetMock).register(MultiPartFeature.class); doReturn(targetMock).when(targetMock).register(any(JacksonJsonProvider.class)); doReturn(targetMock).when(targetMock).register(any(SessionOutputFilter.class)); doReturn(true).when(configurationMock).getLogHttp(); diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/core/SessionTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/core/SessionTest.java index afcc7d68..42901658 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/core/SessionTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/core/SessionTest.java @@ -1,13 +1,15 @@ package com.jaspersoft.jasperserver.jaxrs.client.core; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.AbstractAdapter; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.adhoc.queryexecution.QueryExecutionService; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.attributes.AttributesService; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.authority.organizations.OrganizationsService; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.authority.roles.RolesService; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.authority.users.UsersService; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.datadiscovery.DataDiscoveryService; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.domain.DomainService; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.connections.ConnectionsService; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.diagnostic.DiagnosticService; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.domain.DomainMetadataService; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.importexport.exportservice.ExportService; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.importexport.importservice.ImportService; import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.inputControls.InputControlsService; @@ -266,10 +268,10 @@ public void should_return_not_null_JobsService_instance() { public void should_return_not_null_DomainMetadataService_instance() { // When Session sessionSpy = Mockito.spy(new Session(storageMock)); - DomainMetadataService retrieved = sessionSpy.domainService(); + DomainService retrieved = sessionSpy.domainService(); // Then assertNotNull(retrieved); - verify(sessionSpy, times(1)).getService(DomainMetadataService.class); + verify(sessionSpy, times(1)).getService(DomainService.class); } @Test @@ -333,8 +335,28 @@ public void should_return_not_null_ConnectionsService_instance() { verify(sessionSpy, times(1)).getService(ConnectionsService.class); } + @Test + public void should_return_not_null_DataDiscoveryService_instance() { + // When + Session sessionSpy = Mockito.spy(new Session(storageMock)); + DataDiscoveryService service = sessionSpy.dataDiscoveryService(); + // Then + assertNotNull(service); + verify(sessionSpy, times(1)).getService(DataDiscoveryService.class); + } + + @Test + public void should_return_not_null_QueryExecutionService_instance() { + // When + Session sessionSpy = Mockito.spy(new Session(storageMock)); + QueryExecutionService service = sessionSpy.queryExecutionService(); + // Then + assertNotNull(service); + verify(sessionSpy, times(1)).getService(QueryExecutionService.class); + } + @AfterMethod public void after() { - reset(storageMock, targetMock, builderMock, responseMock, statusTypeMock, clientMock); + reset(storageMock, configurationMock, credentialsMock, targetMock, builderMock, responseMock, statusTypeMock, clientMock); } } diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/core/operationresult/OperationResultFactoryImplTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/core/operationresult/OperationResultFactoryImplTest.java index c7087670..35e20669 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/core/operationresult/OperationResultFactoryImplTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/core/operationresult/OperationResultFactoryImplTest.java @@ -4,7 +4,7 @@ import com.jaspersoft.jasperserver.dto.resources.ClientQuery; import com.jaspersoft.jasperserver.dto.resources.ClientSecureMondrianConnection; import com.jaspersoft.jasperserver.dto.thumbnails.ResourceThumbnail; -import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.ResourcesTypeResolverUtil; +import com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.util.ResourcesTypeResolverUtil; import com.jaspersoft.jasperserver.dto.thumbnails.ResourceThumbnailsListWrapper; import javax.ws.rs.core.Response; import org.mockito.Mockito; diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/CalendarTriggerTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/CalendarTriggerTest.java index 7646a941..74cd4c34 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/CalendarTriggerTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/CalendarTriggerTest.java @@ -6,7 +6,7 @@ import org.testng.annotations.Test; import static java.util.Arrays.asList; -import static org.junit.Assert.assertEquals; +import static org.testng.Assert.assertEquals; /** *

diff --git a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/SimpleTriggerTest.java b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/SimpleTriggerTest.java index 21caeed1..05964541 100644 --- a/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/SimpleTriggerTest.java +++ b/src/test/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/SimpleTriggerTest.java @@ -4,7 +4,8 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import static org.junit.Assert.assertEquals; +import static org.testng.Assert.assertEquals; + /** *