Documentation for JasperReports Server PHP Client

Jaspersoft Corporation, © 2014

Code highlighting for this page provided by highlight.js, written by Ivan Sagalaev (license/authors).

About the class

The JasperReports PHP Client is a wrapper for the JasperReports Web Services 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. Users do not have to deal with parsing and creating JSON data, but rather deal with objects that represent objects within the server.
Use of this wrapper is intented to allow users to focus on their logic and implementation rather than detailed communications with a server.

Preparing the class

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. In addition, please note that the examples below 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.

require_once __DIR__ . "/vendor/autoload.php";

use Jaspersoft\Client\Client;

$c = new Client(
				"http://localhost:8080/jasperserver-pro",
				"jasperadmin",
				"jasperadmin",
				"organization_1"
			);		
		

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);    		
		

Available Services

List of Services

There are many services exposed through the client. Each can be requested as an object or accessed through the client itself each time.

// Store service for several calls
$js = $c->jobService();
$js->getJobs("/reports/samples/AllAccounts");

// Or access service methods directly
$c->jobService()->getJobs("/reports/samples/AllAccounts");		
		

Administration Services

User Service

Search User

Using the searchUsers method you can search for several users based on various critera. This method will return an array of UserLookup objects that can be used with the getUserByLookup() function to retrieve their fully described User objects. The example below grabs all users containing 'j' in their username, and that are members of organization_1 and prints out the roles assigned to that 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', '&nbsp;', $role->roleName);
}        
		

Create User

To create a user, define a user object which fully describes the user, use it with 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());
}        
		

Update User

To update a user, you can also use 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, obtain its user object from the server, then pass it to the deleteUser function.

$user = $c->userService()->getUserByLookup(
    $c->userService()->searchUsers('california', 'organization_1')[0]
);

$c->userService()->deleteUser($user);        
		

Get Attributes

Using this function, you can request the attributes of a user. You are able to specifiy specific attributes that you wish to get, otherwise all attributes for user will be returned. You must supply a User object representing the user you wish to find the attributes of.

$californiaUser = $c->userService()->getUser("CaliforniaUser", "organization_1");
$attributes = $c->userService()->getAttributes($californiaUser);		
		

Add Attributes

addOrUpdateAttribute can be used to create or update an attribute for a user.

$joeUser = $c->userService()->getUser("joeuser", "organization_1");

$animal_attr = new Attribute("Favorite Animal", "Bear");
$c->userService()->addOrUpdateAttribute($joeUser, $animal_attr);		
		

Delete Attributes

To remove attributes of a user, you must supply a User object of the user to remove from, and an array of the names of the attributes (Not attribute objects) If no attribute names are given, all attributes will be removed.

$joeUser = $c->userService()->getUser("joeuser", "organization_1");
$c->userService()->deleteAttributes($joeUser);		
		

Organization Service

Create Organization

Creating a new organization requires constructing a new Organization object and sending it using the createOrganization function.

$new_organization = new Organization(
      'test_organization',	// alias
      'test_organization',	// id
      'organization_1',	// parent organization
      'test_organization');	// tenantName

try {
   $c->organizationService()->createOrganization($new_organization);
} catch (Exception $e) {
   printf('Creating organization failed: %s', $e->getMessage());
}        
		

Searching Organizations

Using the searchOrganization function you can search for organizations by ID.

$find = $c->organizationService()->searchOrganization('org');
foreach ($find as $result)
    printf('<br>Organization Found: %s', $result->id);        
		

Get Organization

Using the getOrganization function you can request the data about a specific organization for which you know the ID of.

$org_one = $c->organizationService()->getOrganization("organization_1");

// Print the details of the $org_one Organization object
var_dump($org_one);            
            

Deleting Organizations

An organization may be deleted by providing the Organization Object that correlates to the organization that is to be deleted. This can be retrieved as shown below by using the searchOrganizations() method.

$search = $c->organizationService()->searchOrganizations('test_organization');
$organization = $search[0];

try {
   $c->organizationService->deleteOrganization($organization);
} catch (Exception $e) {
   printf('Organization deletion failure: %s', $e->getMessage());
}        
		

Updating Organizations

Modifying an organization is done in a similar fashion to modifying a user. The organization object needs to be obtained with the searchOrganization method, modified, and then return it back to the server as shown below.

$search = $c->organizationService()->searchOrganization('organization_wave');
$organization = $search[0];
$organization->tenantDesc = "Wave producing organization";

try {
    $c->organizationService()->updateOrganization($organization);
} catch (Exception $e) {
    printf('Unable to modify organization: %s', $e->getMessage());
}        
		

Role Service

Get Many Roles

You can request all the roles of an organization, or of the server using this function. The example below will request all roles on the server. Optionally, you can search based on specific criteria for roles.

$server_roles = $c->roleService()->searchRoles();        
		

Get a Specific Role

If you know the name of the role, you can request it specifically using this function. The example below will request the ROLE_USER data.

$user_role = $c->roleService()->getRole("ROLE_USER");        
		

Create Role

Creating a role requires you to describe the role with an object, then pass it to the server. The example below will create a new role for organization_1.

$robot_role = new Role("ROLE_ROBOT", "organization_1");
$c->roleService()->createRole($robot_role);        
		

Update Role

Updating a role requires you to provide an updated model of the new role. If changing 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);
        
		

Delete Role

Removing a role requires you to 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);        
		

Reporting Services

Job Service

Search Jobs

Using the searchJobs function, you can search for existing jobs. There are various options that can be set to filter your results. With no options set, you will recieve all existing jobs on the server. The example below will search for all jobs schedule for the report at the URI "/reports/samples/AllAccounts"

$allJobs = $c->jobService()->searchJobs("/reports/samples/AllAccounts");
print_r($allJobs);		
		

Get Job by ID

If you know the ID of a job, you can request the specific details of that job. All results for searchJobs are JobSummary objects which contain IDs. Also when you create a new job, the ID will be returned in the response data. You can use these IDs with this function to request the details of the jobs.

$allJobs = $c->jobService()->searchJobs("/reports/samples/AllAccounts");
$first_job_details = $c->jobService()->getJob($allJobs[0]->id);		
		

Create Job

Creating a job requires you to create a well-defined Job object. Job objects consist of subclasses that define the behaviour of the scheduled 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 Job

To update a scheduled job, simply request the old job object from the server, modify it, and then use the updateJob() function to reupload it to the server to be updated. The Job class utilizes properties and arrays to manage its data, which is different from the other objects which use only properties. This means you will 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.

$allJobs = $c->jobService()->searchJobs("/reports/samples/AllAccounts");
$job = $c->jobService()->getJob($allJobs[0]->id);

$job->label = "new label";
$c->jobService()->updateJob($job);		
		

Pause Job

Jobs can be paused using the pauseJob function. The only argument for this function accepts either a single job ID as an integer, an array of job IDs; or, if no argument is provided all jobs will be paused.

$c->jobService()->pauseJob();		
		

Resume Job

To resume a job, pass the job's ID to the resumeJob function. For convenience you may also pass an array of job IDs. Similarly, all jobs will be resumed if no IDs are provided.

$c->jobService()->resumeJob();		
		

Delete Job

To delete a job, search for the job by name or URI, then hand its ID to the deleteJob function. The example below will delete all scheduled jobs on the server.

$c->jobService()->deleteJob('90210');		
		

Options Service

Get Report Options

You can view the different stored options for your reports that have input controls using this function. Simply provide the URI of the report that has options, and an array of objects representing each report option will be returned. The example below shows you how to request all the ReportOptions objects, iterate through them and print the Labels of each of them.

$report_options = $c->optionsService()->getReportOptions('/reports/samples/Cascading_multi_select_report');

foreach($report_options as $ro) {
   echo $ro->label . "<br />";
}		
		

Update/Create Report Options

The updateReportOptions function can be used both to create new, or update existing report options. The example below shows how to create a new report 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";
}		
		

Delete Report Options

To delete report options, you must retrieve the URI for the report containing the options, and provide the label for the option setting. If your report options has whitespace in the label, currently this function may not handle it well. Instead use the deleteResources() function to delete the Report Option. The example below will remove the report options created in the example above.

try {
  $c->optionsService()->deleteReportOptions('/reports/samples/Cascading_multi_select_report', 'CanadaUSA');
} catch (Exception $e) {
  printf("An exception was thrown: ", $e->getMessage());
}		
		

Query Executor Service

Execute Query

This service allows you to execute a query on a data source or domain. Pass the URI and a properly written query string as parameters. An associative array representing the names and values of the query passed will be returned to you.

$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);  		
		

Report Service

Running a Report

The following code will request the AllAccounts sample report in HTML format. Since the data is HTML, we can simply echo it and the report will be presented in a webpage. 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;		
		

Running a Report with Input Controls

The following example displays how a report can be ran with various input controls set.

$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;			
		

Offering a Binary Report to Download

By offering the proper headers before anything else is sent by the script, we 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;		
		

Retrieving the Input Controls and Values for a Report

You can retrieve the input controls defined for a report, their possible values, and other metadata about controls with the report service. The example below will list 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']);
    }
}		
		

Repository & Resource Services

Repository Service

Searching the Repository

The repository can be searched for items, 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 = "pitbull";

$results = $c->repositoryService()->searchResources($criteria);

foreach ($results->items as $res) {
    echo $res->label . "<br>";
}		
		

Create Resource

Many types of resources can be created. See the namespace \Jaspersoft\Dto\Resource 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, if you create a ReportUnit object, and wish to link to a datasource you can set the fie "datasource" to a string or a concrete DataSource object which will create a reference or a local definition respectively.

In the example below, a ReportUnit is defined with a reference to a datasource, and query.

In addition, the Input Controls are set to an array of both referenced and locally defined input controls.

$report_shop = new \Jaspersoft\DTO\Resource\ReportUnit();
$city_control = new \Jaspersoft\DTO\Resource\InputControl();

$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";
            
            

Create Binary Resource

The repository service is capable of uploading binary files as well. These must be handled differently than other types of resources. This example will explain how you can upload an image to your repository. Note: If your isntance of JRS employs custom file types, you must define the mapping of the server type to the proper MIME type in the Jaspersoft\Tool\MimeMapper object which contains an associative array of JRS file types mapped to their relevant MIME type.

$file = new File;

$file->description = "Image of a Pitbull";
$file->label = "pitbull";

$c->repositoryService()->createFileResource(
		$file,
		file_get_contents("/home/grant/pitbull.jpg"),
		"/ImageFolder",
		);

		
		

Requesting Binary Content

The example below will show how you can request an image, and display it in inline HTML using base64 encoding.

$image = $c->repositoryService()->getResource("/ImageFolder/pitbull");
$image_data = $c->repositoryService()->getBinaryFileData($image);

echo "<h1> Its a pitbull! </h1><br><img src=\"data:image/jpeg;base64,".base64_encode($image_data)."\">";		
		

Delete Resource

You can remove resources from the repository, either one at a time, or several at a time. Using deleteResources.

$c->repositoryService()->deleteResources("/ImageFolder/pitbull");

// OR!

$c->repositoryService()->deleteResources(array("/ImageFolder/pitbull", "/ImageFolder"));
		
		

Move Resource

Resources can be moved from one location to another within the Repository. The example below will move the folder "/ImageFolder/anchorsteam" to "/anchorsteam"

$c->repositoryService()->moveResource("/ImageFolder/anchorsteam", "/");		
		

Copy Resource

Resources can be copied from one location to another within the Repository. The example below will copy the folder "/anchorsteam" to the new location "/ImageFolder/anchorsteam". By setting the last argument to true, folders which do not exist will be created when copying the file.

$c->repositoryService()->copyResource("/anchorsteam", "/ImageFolder", true);		
		

Permission Service

Searching Permissions

You can search for user permissions in regards to a 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 example below will list 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 return them to the server. The example below will retrieve permissions for a report, alter the first one to have no access, and update it.

$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 in using the following code. 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 example below will create 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/otheruser", 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]);        
		

Superuser Services

Import/Export Service

Import Service

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 more specific examples of such flags. The example below will submit an import from the file "import_data.zip" assumed to be stored in the same folder as the PHP file. It will repeat "Still importing..." and check the status every 10 seconds until it is complete. Then it will announce 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 "Still importing...<br>";
        @ob_flush();
        @flush();
        sleep(10);
    }
}        
		

Export Service

Using this service you can export data from the server to store or import to another server. You must be authorized as the superuesr to use 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 example below will request an export, then refresh the status of the export every 10 seconds. When it is finished, it will download the data as a zip file, and then store it in a file (export.zip) and offer 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 limit
set_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 not yet completed...<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>File available for download <a href='export.zip'>here</a>";