About the Class
The JasperReports Server PHP Client is a wrapper for the JasperReports Server REST API. This client abstracts the details behind the communications with the server into simple-to-use functions representative of their functionality on the server. Developers do not have to deal with parsing and creating JSON data, but rather deal with objects that represent resources within the server.
By using JasperReports Server PHP Client, developers can focus on their logic and implementation rather than detailed communications with JasperReports Server.
Getting Started
Invoking the Client
In your project, you must include the autoloader so that classes can be loaded as needed. If you have not generated the autoloader file, please follow the instructions in the README for installation. Then you must initialize a client with your login credentials.
require_once __DIR__ . "/vendor/autoload.php";use JaspersoftClientClient;$c = new Client( "http://localhost:8080/jasperserver-pro", "jasperadmin", "jasperadmin", "organization_1" );
Usage Patterns
There are several way to invoke the functions of the client:
// Store service for several calls$js = $c->jobService();$js->getJobs("/reports/samples/AllAccounts");// Or access service methods directly$c->jobService()->getJobs("/reports/samples/AllAccounts");
Note that all examples on this page assume you are importing objects using the PHP 'use' keyword. If you are not, you must refer to the objects using the full qualified namespace.
Altering the Request Timeout
If you are having issues with requests timing out, you can alter the amount of time the client waits for a response before timing out. The default timeout is 30 seconds.
// Let the client wait one whole minute before timing out$c->setRequestTimeout(60);
Server Information
The client class can also return data about the sever it is connecting to. This data includes date formats, license information and other info about the server's configruation. It is returned in an associative array format.
$info = $c->serverInfo();print_r($info);
Repository and Resource Services
repositoryService()
Searching the Repository
You can search the repository by using a RepositorySearchCriteria
object to define your search parameters. If no criteria is provided, the entire repository will be returned.
Results are returned as a SearchResourcesResult
object. Each result is contained in the items element of the result object.
// Returns entire repository$repo = $c->repositoryService()->searchResources();// Search for specific items in repository$criteria = new RepositorySearchCriteria();$criteria->q = "logo";$results = $c->repositoryService()->searchResources($criteria);foreach ($results->items as $res) { echo $res->label . "<br>";}
Creating a Resource
Many types of resources can be created. See the namespace JaspersoftDtoResource
to see the types you may work with. Note: CompositeResource
and Resource
are abstract classes and are not expected to be insantisted or used with any 'CRUD' operations.
$folder = new Folder;$folder->label = "ImageFolder";$folder->description = "A folder for storing images";$c->repositoryService()->createResource($folder, "/");
Working with Composite Resources
Some resources can reference or define subresources, these resources are known as composite resources. When dealing with such resources while using the PHP Client, you can decide to provide a reference to an existing resource, or define the resource locally.
For example, when you create a ReportUnit object, you can set the datasource
field to either of the following:
- A string representing the path to a data source in the repository. This will create a reference to the designated resource.
- A concrete
DataSource
object with all the required fields. This will create a local definition of the data source.
The following example defines a ReportUnit that references a data source and a query in the repository. The array of input controls includes both referenced resources and a locally defined InputControl
structure.
$report_shop = new JaspersoftDTOResourceReportUnit();$city_control = new JaspersoftDTOResourceInputControl();$city_control->query = "/queries/cityQuery";$city_control->label = "city";$city_control->type = 7;$city_control->visible = true;$city_control->visibleColumns = ["city", "country", "zipcode"];$city_control->valueColumn = "city";$report_shop->label = "All Accounts Report of Shops";$report_shop->description = "AllAccounts style report derived from the shops JDBC datasource";$report_shop->uri = "/my_reports/allaccount_shop";$report_shop->dataSource = "/datasources/shopJDBC";$report_shop->inputControls = array( "/inputcontrols/age", "/inputcontrols/state", $city_control);$report_shop->query = "/queries/shop_accounts";$report_shop->jrxml = "/jrxml/allaccounts";
Creating Binary Resources
The repository service is capable of uploading binary files as well. These must be handled differently than other types of resources.
The following example shows how to upload an image to the JasperReports Server repository.
$file = new File;$file->description = "JPG of company logo";$file->label = "logo";$c->repositoryService()->createFileResource( $file, file_get_contents("/home/user/logo.jpg"), "/ImageFolder", );
Note: If your instance of JRS employs custom file types, you must define the mapping of the server type to the proper MIME type in the JaspersoftToolMimeMapper object which contains an associative array of JRS file types mapped to their relevant MIME type.
Requesting Binary Content
The following example shows how to request an image and display it in inline HTML using base64 encoding.
$image = $c->repositoryService()->getResource("/ImageFolder/logo");$image_data = $c->repositoryService()->getBinaryFileData($image);echo "<img src="data:image/jpeg;base64,".base64_encode($image_data).""><br><h1> Example Corporation </h1>";
Deleting a Resource
The deleteResources
function removes resources from the repository, either one at a time or several at a time. When deleting a folder, all folder contents are deleted, including recursive subfolders and their contents, provided the user credentials have delete permission on all folders and resources.
$c->repositoryService()->deleteResources("/ImageFolder/logo");$c->repositoryService()->deleteResources("/ImageFolder/logo2");// or$c->repositoryService()->deleteResources(array("/ImageFolder/logo", "/ImageFolder/logo2"));
Moving a Resource
Resources can be moved from one location to another within the Repository. Note that the moveResource
function does not rename the resource, only changes its parent. The following example moves the folder "/ImageFolder" to "/MyReports/ImageFolder":
$c->repositoryService()->moveResource("/ImageFolder", "/MyReports");
Copying a Resource
Resources can be copied from one location to another within the Repository. The following example copies the folder "/MyReports/ImageFolder" to "/SharedReports/ImageFolder". By setting the last argument to true, folders that do not exist in the new parent's path will be created.
$c->repositoryService()->copyResource("/MyReports/ImageFolder", "/SharedReports", true);
permissionService()
Searching Permissions
You can search for user permissions to a give resource in the repository by using the searchRepositoryPermissions
function. Provide the URI for the resource as the first argument. Other arguments are available to filter the results as needed. The following example lists all the set permission recipients for "/reports/samples/AllAccounts":
$permissions = $c->permissionService()->searchRepositoryPermissions("/reports/samples/AllAccounts");foreach($permissions as $p) echo $p->recipient . "<br>";
Updating Permissions
To update permissions, you must retrieve existing permissions, modify them, and then pass them to the updateRepositoryPermissions
function. The following example retrieves permissions for a report, alters the first one to have no access, and updates it on the server.
$perms = $c->permissionService()->searchRepositoryPermissions("/reports/samples/AllAccounts");$perms[0]->mask = 0;$c->permissionService()->updateRepositoryPermissions("/reports/samples/AllAccounts", $perms);
Updating a Single Permission
You can update one permission at a time as shown in the following code example. It is also possible to create a new permission object from scratch and use it to update a single permission if desired.
$perms = $c->permissionService()->searchRepositoryPermissions("/reports/samples/AllAccounts");$perms[0]->mask = 0;$c->permissionService()->updateRepositoryPermission($perms[0]);
Creating Permissions
Permissions can be created by first describing the permissions in Permission objects, then passing them to the server. The following example creates a new permisison for joeuser in organization_1 to administer the AllAccounts report.
$p = new RepositoryPermission("/reports/samples/AllAccounts", "user:/organization_1/joeuser", 1);$p2 = new RepositoryPermission("/reports/samples/AllAccounts", "user:/organization_1/janeuser", 32);$c->permissionService()->createRepositoryPermissions(array($p, $p2));// Likewise, you can create a single permission using the non-plural version$c->permissionService()->createRepositoryPermission($p);
Deleting Permissions
Removing permissions is possible by passing the permission to the deleteRepositoryPermissions function. The example below will delete the permission created in the previous example.
$p = $c->permissionService()->searchRepositoryPermissions("/reports/samples/AllACcounts", null, null, "user:/organization_1/joeuser");$c->permissionService()->deleteRepositoryPermission($p[0]);
importExportService()
Exporting Resources
Using this service, you can export data from the server to store or import to another server. You must set the user credentials to a system admin (superuser
by default) when calling this service. Data is compressed as a zip archive and sent as binary data. First construct an ExportTask
object that defines what data is to be extracted, then pass it to the startExportTask
function. Data can then be stored using PHP file I/O functions, or streamed to a browser by preparing the proper headers and echoing the binary data.
The following example requests an export, then refreshes the status of the export every 10 seconds. When it is finished, it downloads the data as a zip file, stores it in a file (export.zip), and offers a link to download the file.
header('Content-Type: text/html; charset=utf-8');// The export service can take longer than 60 seconds to execute, so it is necessary to change the server execution time limitset_time_limit(0);$request->users[] = "jasperadmin";$metadata = $c->importExportService()->startExportTask($request);$decline = true;while ($decline) { $state = $c->importExportService()->getExportState($metadata->id); if ($state->phase == "finished") { $decline = false; echo "<br>Export task complete, downloading...."; } else { echo "Export in progress...<br>"; @flush(); @ob_flush(); sleep(10); }}$f = fopen('export.zip', 'w');$data = $c->importExportService()->fetchExport($metadata->id);fwrite($f, $data);fclose($f);echo "<br><br>Export catalog available for download <a href='export.zip'>here</a>.";
Importing Resources
The import service allows you to import data that was previously exported. There are various flags that can be set to alter what data is imported; see the REST API documentation for specific examples of such flags.
The following example submits an import from the file "import_data.zip" assumed to be stored in the same folder as the PHP file. It displays "Import in progress..." and checks the status every 10 seconds until it is complete. Then it announces that the import has completed.
$request = new ImportTask;$request->update = true;$metadata = $c->importExportService()->startImportTask($request, file_get_contents('import_data.zip'));$continue = true;while($continue) { $state = $c->importExportService()->getImportState($metadata->id); if ($state->phase == 'finished') { $continue = false; echo "<br><br>Import complete!"; } else { echo "Import in progress...<br>"; @ob_flush(); @flush(); sleep(10); }}
Reporting Services
reportService()
Running a Report
The following code example requests the AllAccounts report in HTML format. Since the data is HTML, we can simply echo it, and the report will be presented in the web page. You can do many things with the binary data, including offering the file to be downloaded or storing it to a file.
$report = $c->reportService()->runReport('/reports/samples/AllAccounts', 'html');echo $report;
Downloading a Report in a Binary Report
By setting the proper headers before calling the runReport
function, you can serve binary data to a browser as a download.
$report = $c->reportService()->runReport('/reports/samples/AllAccounts', 'pdf');header('Cache-Control: must-revalidate');header('Pragma: public');header('Content-Description: File Transfer');header('Content-Disposition: attachment; filename=report.pdf');header('Content-Transfer-Encoding: binary');header('Content-Length: ' . strlen($report));header('Content-Type: application/pdf');echo $report;
Running a Report with Input Controls
The following example shows how to run a report with various input controls.
$controls = array( 'Country_multi_select' => array('USA', 'Mexico'), 'Cascading_state_multi_select' => array('CA', 'OR') );$report = $c->reportService()->runReport('/reports/samples/Cascading_multi_select_report', 'html', null, null, $controls);echo $report;
Retrieving Input Control Values
You can retrieve the input controls defined for a report, their possible values, and other metadata about controls. The following example lists each control and its corresponding values.
$input_controls = $c->reportService()->getReportInputControls('/reports/samples/Cascading_multi_select_report');foreach($input_controls as $ic) { printf('Key: %s <br />', $ic->id); foreach ($ic->options as $ico) { printf(' -- Value: %s <br />', $ico['label']); }}
optionsService()
Listing Report Options
A report option is a set of saved input control values for a given report. You can view the different stored options for your reports using the getReportOptions
function. It takes the URI of a report that has options, and returns an array of objects representing each report option. The following example shows how to request all the ReportOptions
objects, iterate through them and print the labels of each one.
$report_options = $c->optionsService()->getReportOptions('/reports/samples/Cascading_multi_select_report');foreach($report_options as $ro) { echo $ro->label . "<br />";}
Creating and Updating Report Options
The updateReportOptions
function can be used both to create new report options or to update existing ones. The following example shows how to create a new report option that makes selections for existing input controls.
$success = $c->optionsService()->updateReportOptions( '/reports/samples/Cascading_multi_select_report', array('Country_multi_select' => array('Canada', 'USA'), 'Cascading_state_multi_select' => array('OR', 'WA', 'BC')), 'CanadaUSA', 'true');if ($success) { echo "Created new report option successfully";}
Deleting Report Options
To delete a report option, specify the URI of the report, and provide the label of the report option.
If your report options has whitespace in the label, the current version of this function may not handle it well. Instead, use the deleteResources
function to delete the report option.
try { $c->optionsService()->deleteReportOptions('/reports/samples/Cascading_multi_select_report', 'CanadaUSA');} catch (Exception $e) { printf("An exception was thrown: ", $e->getMessage());}
jobService()
Searching for Jobs
The searchJobs
function has various options that can be set to filter your results. With no options set, it returns all existing jobs on the server. All results are JobSummary
objects that contain the ID of the job. The following example searches for all jobs scheduled for a given report.
$allAccountsJobs = $c->jobService()->searchJobs("/reports/samples/AllAccounts");print_r($allAccountsJobs);
Getting Job Details
Once you know the ID of a job, you can request the specific details of that job. The getJob
function returns a Job
object describing the job.
$allAccountsJobs = $c->jobService()->searchJobs("/reports/samples/AllAccounts");$first_job_details = $c->jobService()->getJob($allAccountsJobs[0]->id);
Creating a Job
To create a job, first create a well-defined Job
object. The Job
object contains subclasses that define the behaviour of the scheduled job. The response to a successful job creation contains the ID of the new job.
// SimpleTrigger$trigger = new SimpleTrigger();$trigger->timezone = "America/Los_Angeles";$trigger->startType = 2;$trigger->startDate = "2025-10-26 10:00";$trigger->occurrenceCount = 1;// Source$source = new Source();$source->reportUnitURI = "/adhoc/topics/Cascading_multi_select_topic";$source->parameters = array("Country_multi_select" => array("Mexico"), "Country_name_single_select" => array("Chin-Lovell Engineering Associates"), "Country_state_multi_select" => array("DF", "Jalisco", "Mexico"));// Repository Destination$repoDest = new RepositoryDestination();$repoDest->folderURI = $f->uri;$job = new Job("Sample Job Name", $trigger, $source, "Cascading_multi_select_test", array("PDF", "XLS"), $repoDest);$job->description = "Sample Description";try { $c->jobService()->createJob($job);} catch (Exception e) { printf('Caught Exception: %s', $e->getMessage());}
Updating a Job
To update a scheduled job, request its Job
object from the server, modify it, and then call the updateJob
function.
The Job
class uses properties and arrays to manage its data; this is different from the other objects that use only properties. This means you do not use get/set methods to alter the data in a Job object, but rather set the properties as if they were variables. If a property refers to a nested element of the Job
class, use array functions to manipulate the arrays.
$allAccountsJobs = $c->jobService()->searchJobs("/reports/samples/AllAccounts");$job = $c->jobService()->getJob($allAccountsJobs[0]->id);$job->label = "New label";$c->jobService()->updateJob($job);
Pausing a Job
When a job is paused, it does not run any reports. The only argument to the pauseJob
function is either a single job ID as an integer or an array of job IDs. If no argument is provided, this function pauses all jobs to which the user has access.
$c->jobService()->pauseJob();
Resuming a Job
To resume a job, pass the job ID to the resumeJob
function. For convenience, you may also pass an array of job IDs. As with the pauseJob
function, this function resumes all jobs if no argument is provided.
$c->jobService()->resumeJob();
Deleting Job
To delete a job, search for the job by name or URI, then pass its ID to the deleteJob
function.
$c->jobService()->deleteJob('90210');
queryService()
Executing a Query
This service allows you to execute a query on a data source or Domain. Pass the URI of the data source or Domain and a properly written query string as parameters. The executeQuery
function returns an associative array representing the names and values in the query results.
$query = <<<EOF<query> <queryFields> <queryField id="public_opportunities.amount"/> <queryField id="public_opportunities.name"/> </queryFields></query>EOF;$result = $c->queryService()->executeQuery('/Domains/Simple_Domain', $query);print_r($result);
Administration Services
organizationService()
Searching for Organizations
Use the searchOrganization
function to search for organizations by ID.
$found = $c->organizationService()->searchOrganization('org');foreach ($found as $result) printf('<br>Organization Found: %s', $result->id);
Getting Organization Details
Once you know the full ID of a specific organization, use the getOrganization
function to request its detailed information. This function returns an Organization
object.
$org_one = $c->organizationService()->getOrganization("organization_1");// Print the details of the $org_one Organization objectvar_dump($org_one);
Creating an Organization
To create a new organization, define a new Organization
object and pass it to the createOrganization
function.
$new_organization = new Organization( 'test_organization', // alias 'test_organization', // id 'organization_1', // parent organization 'Test Organization'); // organization nametry { $c->organizationService()->createOrganization($new_organization);} catch (Exception $e) { printf('Creating organization failed: %s', $e->getMessage());}
Updating an Organization
To modify an organization, obtain its Organization
object with the searchOrganization
or getOrganization
functions. Then modify the fields you wish to update and pass it to the updateOrganization
function.
$search = $c->organizationService()->searchOrganization('test_organization');$organization = $search[0];$organization->tenantDesc = "My test organization";try { $c->organizationService()->updateOrganization($organization);} catch (Exception $e) { printf('Unable to modify organization: %s', $e->getMessage());}
Deleting Organizations
To delete an organization, obtain its Organization
object with the searchOrganization
or getOrganization
functions, and pass it to the deleteOrganization
function.
$search = $c->organizationService()->searchOrganizations('test_organization');$organization = $search[0];try { $c->organizationService->deleteOrganization($organization);} catch (Exception $e) { printf('Organization deletion failure: %s', $e->getMessage());}
roleService()
Searching for Roles
Use the the searchRoles
function to request all the roles of an organization, or all roles on the server. Optionally, you can search based on specific criteria for roles. The following example returns all roles on the server.
$server_roles = $c->roleService()->searchRoles();
Getting a Specific Role
If you know the name of the role, you can request it specifically using the getRole
function. This function returns a Role
object.
$user_role = $c->roleService()->getRole("ROLE_USER");
Creating a Role
To create a role, describe it in a Role
object, then pass it to the createRole
function. The following example creates a new role in organization_1.
$robot_role = new Role("ROLE_ROBOT", "organization_1");$c->roleService()->createRole($robot_role);
Updating a Role
To upate a role, pass an updated Role
object to the updateRole
function. If you change the name of the role, you must pass the old name of the role as the second argument.
$robot_role = $c->roleService()->getRole("ROLE_ROBOT", "organization_1");$old_name = $robot_role->roleName;$robot_role->roleName = "ROLE_HUMAN";$c->roleService()->updateRole($robot_role, $old_name);
Deleting a Role
To delete a role, first retrieve the Role
object representing the role you wish to remove, then pass it to the deleteRole
function.
$role_human = $c->roleService()->getRole("ROLE_HUMAN", "organization_1");$c->roleService()->deleteRole($role_human);
userService()
Searching for Users
Using the searchUsers
function you can search for several users based on various critera. This function returns an array of UserLookup
objects that can be used with the getUserByLookup
function to retrieve their fully described User
objects.
The example below finds all users of organization_1 containing 'j' in their username, and prints out the roles assigned to each user.
$results = $c->userService()->searchUsers('j', 'organization_1');foreach ($results as $userLookup) { $user = $c->userService()->getUserByLookup($userLookup); printf('<br>Found user: %s', $user->fullName); foreach ($user->roles as $role) printf('<br> %10s User has role: %s', ' ', $role->roleName);}
Creating a User
To create a user, define a User
object that fully describes the user, and pass it to the addOrUpdateUser
function.
$newUser = new User( 'BI_User', 'superSTRENGTHpassw0rd', 'clever@email.com', 'Business Intelligence User', 'organization_1', 'true'); $role = new Role('ROLE_USER', null, 'false');$newUser->addRole($role);try { $c->userService()->addOrUpdateUser($newUser);} catch (Exception $e) { printf('Could not add new user: %s', $e->getMessage());}
Updating a User
To update a user, pass an updated User
object to the addOrUpdateUser
function.
$search = $c->userService()->searchUsers('californiaUser', 'organization_1');$californiaUser = $c->userService()->getUserByLookup($search[0]);$californiaUser->emailAddress('sanfrancisco-oakland@example.com');$californiaUser->password('SUPERstrongPASSWORD###!!!');try { $c->userService()->addOrUpdateUser($californiaUser);} catch (Exception $e) { printf('Attempt to modify the user failed with error: %s', $e->getMessage());}
Delete User
To delete a user, first retrieve the User
object representing the user you wish to remove, then pass it to the deleteUser
function.
$user = $c->userService()->getUserByLookup( $c->userService()->searchUsers('jane', 'organization_1')[0]);$c->userService()->deleteUser($user);
Reading Attributes
User attributes are name-value pairs that administrators can assign to any user. To read the attributes on a given user, pass a User
object to the getAttributes
function. You can also specifiy specific attributes that you wish to read, otherwise all attributes for the user will be returned.
$californiaUser = $c->userService()->getUser("CaliforniaUser", "organization_1");$attributes = $c->userService()->getAttributes($californiaUser);
Adding or Updating Attributes
Use addOrUpdateAttribute
function to create or update an attribute for a user. Specify the name and value in an Attribute
object. If the attribute name matches an existing attribute, its value is updated. If the attribute name does not exist for the given user, the attribute is added to the user.
$CAuser = $c->userService()->getUser("CaliforniaUser", "organization_1");$animal_attr = new Attribute("Favorite Animal", "Bear");$c->userService()->addOrUpdateAttribute($CAuser, $animal_attr);
Deleting Attributes
To remove attributes from a user, pass a User
object and an array of attribute names (not Attribute
objects) to the deleteAttributes
function. If no attribute names are given, all attributes are removed.
$joeUser = $c->userService()->getUser("joeuser", "organization_1");$c->userService()->deleteAttributes($joeUser);
- 1
Recommended Comments
There are no comments to display.