PHP / Java Bridge

karena tuntutan profesi, keterbatasan budget saya mau tak mau harus belajar PHP. untungnya secara garis besar mirip dengan JAVA, jadi gak lama belajar syntaxnya aja. namun ada masalah yaitu report, bingung nih. akhirnya cari-cari ke mbah google, dapet jawaban gimana menggabungkan PHP dg report kedemenan dan andalan saya selama ini JASPER REPORTS!!

saya copy dari ….
http://firdah.wordpress.com/2008/01/17/php-java-bride-langkah-menuju-php-jasper-report/

Requirement PHP-Java Bridge (Yang aku pake berdasarkan…..Aku lupa linknya😀 )

  1. php-5.1.6-Win32
  2. apache_2.0.59-win32-x86-openssl-0.9.7j.msi
  3. php-java-bridge_3.2.1b_j2ee.zip (http://sourceforge.net/project/showfiles.php?group_id=117793)
  4. JDK 1.6.0-b105.exe
  5. iReport-2.0.2-windows-installer.exe(buat design reportnya)

Langkah2 setting PHP-Java Bridge (Aku nyontek di http://www.dsl.uow.edu.au/~sk33/php5java.htm )

  1. Install Apache,PHP,Java (langkah2nya ga aku sebutin..dgn asumsi semua dah pada bisa)
  2. Unzip php-java-bridge_3.2.1b_j2ee.zip
  3. Open with Winrar file JavaBridge.war
  4. Copy file JavaBridge.jar pada folder JavaBridge.war\WEB-INF\lib ke Folder C:\PHP\lib\ext
  5. Copy file java-x86-windows.dll pada folder JavaBridge.war\WEB-INF\cgi kemudian remane menjadi php_java.dll
  6. Setting php.ini, tambahkan extension=php_java.dll
    [java]
    java.java_home = "C:\Program Files\Java\jdk1.6.0\bin"
    java.java ="C:\Program Files\Java\jdk1.6.0\bin\javaw.exe "
    java.class.path =" c:\php\ext\JavaBridge.jar "
    java.library.path =" c:\php\ext "
    java.library ="C:\Program Files\Java\jdk1.6.0\jre\bin\server\jvm.dll"
    ;java.hosts ="127.0.0.1:8080?
    ;java.servlet = One
    java.log_level = 2

    Save PHP.ini

  7. Restart Apache kemudian coba lihat phpinfo nya….(<?php phpinfo(); ?>)
  8. Jika dah ada Java Enabled??
  9. Test apakah PHP anda sudah support Java Jalankan script ini :
    <?php
    
    // get instance of Java class java.lang.System in PHP
    $system = new Java(‘java.lang.System’);
    
    // demonstrate property access
    echo ‘Java version=’ . $system->getProperty(‘java.version’) . ‘<br/>’;
    echo ‘Java vendor=’ . $system->getProperty(‘java.vendor’) . ‘<br/>’;
    echo ‘OS=’ . $system->getProperty(‘os.name’) . ‘ ‘ .
    $system->getProperty(‘os.version’) . ‘ on ‘ .
    $system->getProperty(‘os.arch’) . ‘ <br/>’;
    
    // java.util.Date example
    $formatter = new Java(‘java.text.SimpleDateFormat’,
    "EEEE, MMMM dd, yyyy ‘at’ h:mm:ss a zzzz");
    
    echo $formatter->format(new Java(‘java.util.Date’));
    
    ?>

Jika dilayar dah muncul Java Version bla..bla..maka Anda sukses setting PHP-Java Bridge..Selamat..selamat…

http://www.rjohnson.id.au/wordpress/2007/10/27/bullet-proof-jasper-reports-and-php/

Bullet-Proof Jasper Reports and PHP

Okay, so I got a fair bit of traffic about my last entry where I attempted to explain how I managed to get PHP to talk to Jasper through use of the PHP/Java Bridge instead of having to resort to running external programs through exec, which is undesirable for a number of reasons (including parameter passing and performance).

I’ve done a bit more work with Jasper using PHP and I can say that a few simple steps can make life infinitely easier.

First of all: Setting up and using the PHP/Java Bridge.

You don’t need to use the extension, there is a library written in pure PHP that you can use as a fall-back. When populating a report with Jasper, you don’t use that many Java calls so the reduced performance should not impact on your application too much. If you are calling a fair bit of Java from PHP, I would attempt to get the extension working as the performance is increased dramatically.

Here is a nice little function from the PHP/Java Bridge examples that detects if the extension is loaded and falls back to the native bridge if it isn’t available:

/**
 * see if the java extension was loaded.
 */
function checkJavaExtension()
{
    if(!extension_loaded('java'))
    {
        $sapi_type = php_sapi_name();
        $port = (isset($_SERVER['SERVER_PORT']) 
        && (($_SERVER['SERVER_PORT'])>1024)) 
        ? $_SERVER['SERVER_PORT'] : '8080';
         if ($sapi_type == "cgi" || $sapi_type == "cgi-fcgi" 
         || $sapi_type == "cli")
         {
             if(!(PHP_SHLIB_SUFFIX=="so" && @dl('java.so'))
             &&!(PHP_SHLIB_SUFFIX=="dll" 
             && @dl('php_java.dll'))
             &&!(@include_once("java/Java.inc"))
             &&!(require_once("http://127.0.0.1:$port/java/Java.inc")))
             {
                 return "java extension not installed.";
             }
         }
         else
         {
             if(!(@include_once("java/Java.inc")))
             {
                 require_once("http://127.0.0.1:$port/java/Java.inc");
             }
         }
     }
     if(!function_exists("java_get_server_name"))
     {
         return "The loaded java extension is not the PHP/Java Bridge";
     }

     return true;
 }

/** * see if the java extension was loaded. */ function checkJavaExtension() 
	{ 
		if(!extension_loaded('java')) { $sapi_type = php_sapi_name(); 
		$port = (isset($_SERVER['SERVER_PORT']) 
		&& (($_SERVER['SERVER_PORT'])>1024)) 
		? $_SERVER['SERVER_PORT'] : '8080'; 
		if ($sapi_type == "cgi" || $sapi_type == "cgi-fcgi" 
		|| $sapi_type == "cli") { 
		if(!(PHP_SHLIB_SUFFIX=="so" && @dl('java.so'))
		&&!(PHP_SHLIB_SUFFIX=="dll" 
		&& @dl('php_java.dll'))&&!(@include_once("java/Java.inc"))
		&&!(require_once("http://127.0.0.1:$port/java/Java.inc"))) { 
			return "java extension not installed."; 
			} 
		} 
		else { 
		 if(!(@include_once("java/Java.inc"))) { 
		  require_once("http://127.0.0.1:$port/java/Java.inc"); 
		 } 
		} 
	} if(!function_exists("java_get_server_name")) { 
		return 
		 "The loaded java extension is not the PHP/Java Bridge"; 
	} 
	return true; }

It assumes that you have the PHP implementation in the “java” directory. See the guide below for downloading this.

Second: Classpath is still screwy.

There is something about the bridge that I cannot figure out. Regardless of environment variables, they way you use java_require, settings in php.ini or any other setting this still seems to stuff up. There is one solution that I attempted to steer away from as I did not see it as ideal, however please believe me when I say that this single step will save you hours, if not days of frustration.

Put all the Jasper libraries into your jre lib/ext directory. Trust me.

I have got things tantalisingly close to working with other methods of making the libraries available to the bridge, and even succeeded on the odd occasion. However this is the only reproducible guaranteed way to get rid of those class woes once and for all.

By using the PHP implementation of the bridge and putting your jars into the lib/ext directory, you should be able to get this to work on any platform. I have got it working on Windows and Linux, but by removing any reliance on external settings this should work on pretty much any platform.

Third: Use the JDT compiler.

This little tid-bit of gold was dropped on my blog by Lucian, one of the primary contributors to Jasper’s continued development (thank you).

If you have the jdt-compiler jar in your lib/ext folder as well, the problem of java having a different running directory to that of PHP becomes a non-issue. Most importantly however, this removes the need to set environment variables!

With my previous approach to getting jasper working, I resorted to writing a wrapper class primarily because you can not set the “jasper.reports.compile.temp” and “jasper.reports.compile.class.path” through the bridge (it doesn’t work). Setting these gave the javac compiler the information it needed to compile the report, without them it failed horribly. The JDT compiler does all this stuff in memory, it is hot.

Lastly, the easiest way to get all the libraries required for running Jasper is to download and install iReport then grab them from the lib directory. Please pay attention to the licensing! Some of these libraries like the mysql connector are under the GPL so distributing it with a non-GPL product will be frowned upon.

Putting it all together.

After this work, compiling and running a report from PHP becomes a simple exercise in translating from the Java examples to PHP:

  1. $compileManager = new JavaClass("net.sf.jasperreports.engine.JasperCompileManager");
  2. $report = $compileManager->compileReport(realpath("test.jrxml"));
  3. $fillManager = new JavaClass("net.sf.jasperreports.engine.JasperFillManager");
  4. $params = new Java("java.util.HashMap");
  5. $emptyDataSource = new Java("net.sf.jasperreports.engine.JREmptyDataSource");
  6. $jasperPrint = $fillManager->fillReport($report, $params, $emptyDataSource);
  7. $exportManager = new JavaClass("net.sf.jasperreports.engine.JasperExportManager");
  8. $outputPath = realpath(".")."/"."output.pdf";
  9. $exportManager->exportReportToPdfFile($jasperPrint, $outputPath);
$compileManager = 
new JavaClass("net.sf.jasperreports.engine.JasperCompileManager"); 
$report = $compileManager->compileReport(realpath("test.jrxml")); 
$fillManager = 
new JavaClass("net.sf.jasperreports.engine.JasperFillManager"); 
$params = new Java("java.util.HashMap"); 
$emptyDataSource = 
new Java("net.sf.jasperreports.engine.JREmptyDataSource"); 
$jasperPrint = 
$fillManager->fillReport($report, $params, $emptyDataSource); 
$exportManager = 
new JavaClass("net.sf.jasperreports.engine.JasperExportManager"); 
$outputPath = realpath(".")."/"."output.pdf"; 
$exportManager->exportReportToPdfFile($jasperPrint, $outputPath);

Note that you still need to use complete class names, otherwise you will get Class Not Found problems.

Okay, a quick guide to running Jasper from PHP:

  1. Setup the environment as per normal with PHP and Java (I use WAMP on Windows);
  2. Download the latest iReport software and install it on your workstation;
  3. Grab all of the files from “C:\Program Files\JasperSoft\iReport-2.0.2\lib” (version number will change) and copy them into your java’s lib/ext directory;
  4. Download the latest version of the PHP/Java Bridge with source and unzip it;
  5. Unzip the src.zip file (should be included in the download) and copy the contents of the “java” directory to your PHP app.
  6. If you want to use the stand-alone Java Server (easiest), grab the JavaBridge.jar from the ext directory (in the download) and copy it into the “java” directory you just placed in your PHP app.For production, you will probably want to use the Java extension and configure it to come up with your web server. There are a few configuration options here (including J2EE back-ends and the like), and the PHP/Java Bridge website explains how to get working with them.
  7. Start the Java backend (java –jar JavaBridge.jar). This will usually bring up a dialog asking what port to use, however you have command-line options as well if you are running headless.
  8. Try it out!!

Here is an example report: test.jrxml
And some example PHP code to compile, run it and send it to your browser: index.php.txt

Other things to note:

* Please cache the compiled version of your reports; otherwise you will be waiting for the report to compile every time you run one. I have some example code for doing this in my ReportGenerator class I used in my previous post.

Hopefully people will find this approach a little more straight-forward.

  1. Install and download php and java into your system.
  2. Download the latest iReport software from here, and install it. Please download the software, not the netbeans plugin.
  3. Copy all files from [iReport home]/ireport/modules/ext/ to JAVA_HOME/jre/lib/ext/
  4. Download the latest version of the PHP/Java Bridge with source from here and extract it.
  5. Unzip the src.zip file (should be included in the download) and copy the contents of the “java” directory to your PHP application.
  6. Find JavaBridge.war and place it in some directory.
  7. Run the bridge with java -jar JavaBridge.war TestInstallation, FYI, i stop this bridge using pkill.:mrgreen:
  8. Here is Richard Johnson sample application and his sample report created by iReport so you can try your installation.

sample application

<?php
/**
 * see if the java extension was loaded.
 */
function checkJavaExtension()
{
    if(!extension_loaded('java'))
    {
        $sapi_type = php_sapi_name();
        $port = (isset($_SERVER['SERVER_PORT']) 
        && (($_SERVER['SERVER_PORT'])>1024)) 
        ? $_SERVER['SERVER_PORT'] : '8080';
        if ($sapi_type == "cgi" || $sapi_type == "cgi-fcgi" 
        || $sapi_type == "cli")
        {
            if(!(PHP_SHLIB_SUFFIX=="so" 
            && @dl('java.so'))
            &&!(PHP_SHLIB_SUFFIX=="dll" 
            && @dl('php_java.dll'))
            &&!(@include_once("java/Java.inc"))
            &&!(
            require_once("http://127.0.0.1:$port/java/Java.inc")))
            {
                return "java extension not installed.";
            }
        }
        else
        {
            if(!(@include_once("java/Java.inc")))
            {
                require_once("http://127.0.0.1:$port/java/Java.inc");
            }
        }
    }
    if(!function_exists("java_get_server_name"))
    {
        return "The loaded java extension is not the PHP/Java Bridge";
    }

    return true;
}

/**
 * convert a php value to a java one...
 * @param string $value
 * @param string $className
 * @returns boolean success
 */
function convertValue($value, $className)
{
    // if we are a string, just use the normal conversion
    // methods from the java extension...
    try
    {
        if ($className == 'java.lang.String')
        {
            $temp = new Java('java.lang.String', $value);
            return $temp;
        }
        else if ($className == 'java.lang.Boolean' ||
            $className == 'java.lang.Integer' ||
            $className == 'java.lang.Long' ||
            $className == 'java.lang.Short' ||
            $className == 'java.lang.Double' ||
            $className == 'java.math.BigDecimal')
        {
            $temp = new Java($className, $value);
            return $temp;
        }
        else if ($className == 'java.sql.Timestamp' ||
            $className == 'java.sql.Time')
        {
            $temp = new Java($className);
            $javaObject = $temp->valueOf($value);
            return $javaObject;
        }
    }
    catch (Exception $err)
    {
        echo (  'unable to convert value, ' . $value .
                ' could not be converted to ' . $className);
        return false;
    }

    echo (  'unable to convert value, class name '.$className.
            ' not recognised');
    return false;
}

checkJavaExtension();

$compileManager = 
new JavaClass("net.sf.jasperreports.engine.JasperCompileManager");
$report = $compileManager->compileReport(realpath("test.jrxml"));

$fillManager = 
new JavaClass("net.sf.jasperreports.engine.JasperFillManager");

$params = new Java("java.util.HashMap");
$params->put("text", "This is a test string");
$params->put("number", 3.00);
$params->put("date", convertValue("2007-12-31 0:0:0", "java.sql.Timestamp"));

$emptyDataSource = new Java("net.sf.jasperreports.engine.JREmptyDataSource");
$jasperPrint = $fillManager->fillReport($report, $params, $emptyDataSource);

$outputPath = realpath(".")."/"."output.pdf";

$exportManager = 
new JavaClass("net.sf.jasperreports.engine.JasperExportManager");
$exportManager->
exportReportToPdfFile($jasperPrint, $outputPath);

header("Content-type: application/pdf");
readfile($outputPath);

unlink($outputPath);

?>

sample report

<?xml version="1.0" encoding="UTF-8"  ?>
<!-- Created with iReport - A designer for JasperReports -->
<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN" 
"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport
		 name="test"
		 columnCount="1"
		 printOrder="Vertical"
		 orientation="Portrait"
		 pageWidth="595"
		 pageHeight="842"
		 columnWidth="535"
		 columnSpacing="0"
		 leftMargin="30"
		 rightMargin="30"
		 topMargin="20"
		 bottomMargin="20"
		 whenNoDataType="NoPages"
		 isTitleNewPage="false"
		 isSummaryNewPage="false">
	<property name="ireport.scriptlethandling" value="0" />
	<property name="ireport.encoding" value="UTF-8" />
	<import value="java.util.*" />
	<import value="net.sf.jasperreports.engine.*" />
	<import value="net.sf.jasperreports.engine.data.*" />

	<parameter name="text" isForPrompting="false" 
	class="java.lang.String">
		<defaultValueExpression ><![CDATA[""]]>
		</defaultValueExpression>
	</parameter>
	<parameter name="number" isForPrompting="false" 
	class="java.lang.Double">
		<defaultValueExpression >
		<![CDATA[new java.lang.Double(0)]]>
		</defaultValueExpression>
	</parameter>
	<parameter name="date" isForPrompting="false" 
	class="java.util.Date"/>

		<background>
			<band height="0"  isSplitAllowed="true" >
			</band>
		</background>
		<title>
			<band height="50"  isSplitAllowed="true" >
			</band>
		</title>
		<pageHeader>
			<band height="50"  isSplitAllowed="true" >
			</band>
		</pageHeader>
		<columnHeader>
			<band height="30"  isSplitAllowed="true" >
			</band>
		</columnHeader>
		<detail>
			<band height="223"  isSplitAllowed="true" >
				<textField isStretchWithOverflow="false" 
				isBlankWhenNull="false" 
				evaluationTime="Now" hyperlinkType="None"  
				hyperlinkTarget="Self" >
					<reportElement
						x="75"
						y="17"
						width="312"
						height="100"
						key="textField-1"/>
					<box topBorder="None" 
					topBorderColor="#000000" 
					leftBorder="None" 
					leftBorderColor="#000000" 
					rightBorder="None" 
					rightBorderColor="#000000" 
					bottomBorder="None" 
					bottomBorderColor="#000000"/>
					<textElement>
						<font size="18"/>
					</textElement>
				<textFieldExpression   
				class="java.lang.String">
				<![CDATA["Passed Text: "+$P{text}]]>
				</textFieldExpression>
				</textField>
				<textField isStretchWithOverflow="false" 
				isBlankWhenNull="false" 
				evaluationTime="Now" hyperlinkType="None"  
				hyperlinkTarget="Self" >
					<reportElement
						x="78"
						y="130"
						width="316"
						height="32"
						key="textField-2"/>
					<box topBorder="None" 
					topBorderColor="#000000" 
					leftBorder="None" 
					leftBorderColor="#000000" 
					rightBorder="None" 
					rightBorderColor="#000000" 
					bottomBorder="None" 
					bottomBorderColor="#000000"/>
					<textElement>
						<font size="12"/>
					</textElement>
				<textFieldExpression   
				class="java.lang.String">
				<![CDATA["And a number: "+$P{number}]]>
				</textFieldExpression>
				</textField>
				<textField isStretchWithOverflow="false" 
				isBlankWhenNull="false" 
				evaluationTime="Now" hyperlinkType="None"  
				hyperlinkTarget="Self" >
					<reportElement
						x="75"
						y="174"
						width="316"
						height="32"
						key="textField-3"/>
					<box topBorder="None" 
					topBorderColor="#000000" 
					leftBorder="None" 
					leftBorderColor="#000000" 
					rightBorder="None" 
					rightBorderColor="#000000" 
					bottomBorder="None" 
					bottomBorderColor="#000000"/>
					<textElement>
						<font size="12"/>
					</textElement>
				<textFieldExpression   
class="java.lang.String"> <![CDATA["And a date: "+$P{date}]]> </textFieldExpression> </textField> </band> </detail> <columnFooter> <band height="30" isSplitAllowed="true" > </band> </columnFooter> <pageFooter> <band height="50" isSplitAllowed="true" > </band> </pageFooter> <lastPageFooter> <band height="50" isSplitAllowed="true" > </band> </lastPageFooter> <summary> <band height="50" isSplitAllowed="true" > </band> </summary> </jasperReport>

About upmar102wong

Seorang Planner, Pengatur strategi, negosiator, consular, advisor, mentor, mediator. bangga dg istri yg cantik, pandai, solihah. dia seorang dokter. sekarang saya seorang Development Manager di suatu IT Consulting. Saya suka banget sama kungfu, saya belajar Pa'chi chuan dan Taichi chuan sejak 1998 dari seorang shifu dan seorang guru. saya suka main catur igo, suka baca, nonton film juga. suka bersahabat dg banyak org.
This entry was posted in Information Technologies. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s