Jump to content
We've recently updated our Privacy Statement, available here ×

Using REST service from php


montexristos

Recommended Posts

Hello,

I am trying to create a PHP app that will use REST in order to retrieve reports.

I have used the following code to authenticate, extract the sessionId and create a report and everything seems to be working fine.

But when I try to use GET to fetch the created report I get an error "Report not found (uuid not found in session)"

In the documentation I read that you need either to pass the sessionId in the header of each request (I did it like this:$header = array('Cookie: $Version=0; '.$jsession.'; $Path=/jasperserver'); ) or use HTTP basic authentication (which I also tried).

The weird thing is that when I look at tomcat's logs there is a message that says :" authentication success ... sessionId: null"

Am I doing anything  wrong in authentication?

Code:
 $jasperserver_url = "http://localhost:8080/jasperserver/rest/";    $uri = $jasperserver_url.'login?j_username='.$username.'&j_password='.$password;    $ch = curl_init($uri);    //$data = array("request" => $op_xml );    curl_setopt($ch, CURLOPT_URL, $uri);    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);    curl_setopt($ch, CURLOPT_USERPWD, "xxx:xxx");    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");    curl_setopt($ch, CURLOPT_HEADER, 1);    $response =curl_exec($ch);    preg_match('/^Set-Cookie: (.*?);/m', $response, $m);    //$m[1] holds the jsession variable    if(!$response) {        return false;    }    $jsession = $m[1];$cookie = 'Cookie: $Version=0; '.$jsession.'; $Path=/jasperserver';    $header = array($cookie);    $uri = 'http://localhost:8080/jasperserver/rest/report/reports/samples/AllAccounts';    $ch = curl_init($uri);    $op_xml = '<resourceDescriptor name="report" wsType="reportUnit"    uriString="/reports/samples/AllAccounts" isNew="false">    <label>JServer Jdbc data source</label>    <description>JServer Jdbc data source</description>    <resourceProperty name="PROP_PARENT_FOLDER">    <value>/reports/samples</value>    </resourceProperty>    <resourceProperty name="RUN_OUTPUT_FORMAT">    <value>PDF</value>    </resourceProperty>    </resourceDescriptor>';    //$data = array("request" => $op_xml );        curl_setopt($ch, CURLOPT_HTTPHEADER, $header); // Set headers to above array    curl_setopt($ch, CURLOPT_URL, $uri);    curl_setopt($ch, CURLOPT_POST, 1);    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);    curl_setopt($ch, CURLOPT_USERPWD, "xxx:xxx");    curl_setopt($ch, CURLOPT_POSTFIELDS,$op_xml);    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");    $response =curl_exec($ch);    $uuid = simplexml_load_string($response)->uuid;    /**     * Now we perform the GET request that returns the report     *      */    $url = 'http://localhost:8080/jasperserver/rest/report/';    $uri = $url.'*'.$uuid.'*';    echo $uri;$headers = array('Content-Type' => 'text/xml', 'Cookie'=>$cookie);        $ch2 = curl_init($uri);    curl_setopt($ch2, CURLOPT_HTTPHEADER, $headers); // Set headers to above array    curl_setopt($ch2, CURLOPT_COOKIE, 'Cookie: $Version=0; '.$jsession.'; $Path=/jasperserver');    curl_setopt($ch2, CURLOPT_VERBOSE, true); // Display communication with server    curl_setopt($ch2, CURLOPT_URL, $uri);    curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);    curl_setopt($ch2, CURLOPT_USERPWD, "xxx:xxx");    curl_setopt($ch2, CURLOPT_HTTPGET, true);    curl_setopt($ch2, CURLOPT_CUSTOMREQUEST, "GET");    $response = curl_exec($ch2);    echo $response;
Link to comment
Share on other sites

  • 3 weeks later...
  • Replies 5
  • Created
  • Last Reply

Top Posters In This Topic

Hi,

 I am not so familiar with PHP and can not fully understand the code snippit.

 

Lets distinguish between 2 things:

Getting a report where you will get the JRXML and if you want all the binaries it contains

Or getting the PDF which is a redered report.

 

If you want the first option than you dont need a session just send a GET request to the report URI and you will get it.

If you want the rendered report than you need to first Create this new resource. Meaning you need to send a PUT request which will add the redered report hashcode in the session and when you will follow it with a GET request you will get the rendered report in the response.

Let me know if you have more problems,


Link to comment
Share on other sites

I can only confirm montexristos´ results:

* i wrote a small script that successfully logs into my local jasperserver

* it then creates a report from the Employee-example using PUT and using the session cookie i got from step 1 (seems to work, because I get back a uuid)

* the script then tries to GET the report (still using session cookie)

the last step fails saying "Report not found (uuid not found in session)"

I have no idea what goes wrong. Below you find the tomcat logs for the three steps

(btw: the log looks strange to me, when it has a error level ERROR or WARN for actions that seen to have success.,,,)

Any idea or working sample code?

I could post my php code, if you like,,,

Thanks, Markus

Code:
2012-01-05 04:17:46,233  WARN LoggerListener,http-8080-2:60 - Authentication event AuthenticationSuccessEvent: jasperadmin; details: org.springframework.security.ui.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null2012-01-05 04:17:46,394 ERROR GetService,http-8080-3:234 - Exporter params: [is Using Images To Align, Images URI, Images Map Object, JasperPrint Object, OutputStream Object]2012-01-05 04:17:46,394 ERROR GetService,http-8080-3:356 - Format requested: HTML  HTML2012-01-05 04:17:46,394 ERROR GetService,http-8080-3:364 - imagesMap : [img_0_0_0]2012-01-05 04:17:46,394 ERROR GetService,http-8080-3:375 - Adding image for HTML: img_0_0_0, type: image/png
Link to comment
Share on other sites

 Hi montexristos,

The problem that you are having is the stars (*) that you are adding in the the UUID on the report GET request.

So change the line:

 $uri = $url.'*'.$uuid.'*';

to:

$uri = $url . $uuid ;

And it should work fine.

The problem comes from a typo in the Web Services Guide. Around Page 39, where it says  
" http://<host>:<port>/jasperserver[-pro]/rest/report/*d7bf6c9-9077-41f7-a2d4-8682e74b637e*" 
the "*" at the beginning and end of the UUID are not needed (if you add them you receive an error), so ignore those and you should be fine.

Also, there is a nice PHP class that uses cURL and provides a wrapper for RESTful services called PEST, that will help you.

Check it out here, http://github.com/educoder/pest. It is very useful, below is a an example on using this class to do the requests, as you can see is very clean and also it will give you the request body in a smpleXML object.

 

Best,

Mariano 

 


 

 

Code:
<?phprequire_once 'PEST/PestXML.php';$JSRest = new Pest(http://localhost:8080/jasperserver/rest/);$JSRest->curl_opts[CURLOPT_HEADER] = true;$restData = array(	  'j_username' => $_POST['username'],	  'j_password' => $_POST['password']);	try {		    	$body = $JSRest->post('login', $restData);	$response = $JSRest->last_response;	if ($response['meta']['http_code'] == '200') {		// Respose code 200 -> All OK		// Extract the Cookie and save the string in my session for further requests.		preg_match('/^Set-Cookie: (.*?)$/sm', $body, $cookie);		$_SESSION["JSCookie"] = '$Version=0; ' . str_replace('Path', '$Path', $cookie[1]);				// Now just go                header("location: home.php");                exit();	} else {		$errorMessage = "Unauthorized HTTP Code: " . $response['meta']['http_code'];	}} catch (Exception $e) {	    $errorMessage =  "Unauthorized Exception: " .  $e->getMessage() . "<br>";	}?>
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...