Search code examples
restjasper-reportsjasperserver

Inject a datasource using jrs-rest-java-client to a report


I am using JasperReports Server with its jrs-rest-java-client API. When I access the remote server I want to inject the datasource (in my case it is a database) that the report should use. I do not know if it is possible to do it using this API.


Solution

  • Yes, it is possible. This is how I do it in JasperReports Server v6.2.1 with the jrs-rest-java-client v6.2.3:

    // build configuration object
    RestClientConfiguration configuration = new RestClientConfiguration("http://localhost:8080/jasperserver");
    configuration.setContentMimeType(MimeType.JSON);
    configuration.setAcceptMimeType(MimeType.JSON);
    configuration.setAuthenticationType(AuthenticationType.SPRING);
    configuration.setLogHttp(true);
    configuration.setLogHttpEntity(true);
    
    // build client and authenticate
    JasperserverRestClient client = new JasperserverRestClient(configuration);
    Session session = client.authenticate("jasperadmin", "jasperadmin");
    
    String reportUnitUri = "/path/to/reportUnit";
    
    // first get the version of the reportUnit to prevent update conflicts from optimistic locking
    OperationResult<ClientReportUnit> reportUnitOperationResult = session.resourcesService().resource(reportUnitUri).get(ClientReportUnit.class);
    Integer reportUnitVersion = reportUnitOperationResult.getEntity().getVersion();
    
    // build patchDescriptor with the dataSource field
    PatchDescriptor patchDescriptor = new PatchDescriptor();
    patchDescriptor.setVersion(reportUnitVersion);
    patchDescriptor.field("dataSource", "/path/to/repository/dataSource");
    
    // apply the patchDescriptor
    session.resourcesService().resource(reportUnitUri).patchResource(ClientReportUnit.class, patchDescriptor);