/*
* Created on Jun 21, 2008
*/
package com.skaringa.javaxml.example;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import com.skaringa.javaxml.DeserializerException;
import com.skaringa.javaxml.NoImplementationException;
import com.skaringa.javaxml.ObjectTransformer;
import com.skaringa.javaxml.ObjectTransformerFactory;
import com.skaringa.javaxml.SerializerException;
/**
* Demonstrate the usage of the JSON serializer and deserializer to interoperate with PHP.
*/
public class JsonPhpExample {
/**
* MAIN.
* @param args Program arguments (not used).
*/
public static void main(String[] args) {
// Construct a Person.
Person fred = new Person(102, "Fred", "Feuerstein", "ff@email.com");
try {
// Get an ObjectTransformer.
// The ObjectTransformer interface offers all needed methods.
ObjectTransformer trans = ObjectTransformerFactory.getInstance()
.getImplementation();
// Serialize the Person object into a string.
String json = trans.serializeToJsonString(fred);
// Call PHP.
// The script converts the JSON string into an object, sets the attribute 'firstName' to 'Horst'
// and converts the object back to JSON string
InputStream convertedJson = execPHP("$person = json_decode($_ARGV[0]);$person->firstName = 'Horst'; fwrite(STDOUT, json_encode($person));", json);
// Read JSON from PHP back into person
Person horst = (Person) trans.deserializeFromJson(convertedJson, Person.class);
convertedJson.close();
// Check the result.
if ("Horst".equals(horst.getFirstName())) {
System.out.println("Horst OK");
} else {
System.out.println("ERROR: " + horst.getFirstName());
}
} catch (NoImplementationException e) {
System.err.println(e);
} catch (SerializerException e) {
System.err.println(e);
} catch (DeserializerException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
}
}
private static InputStream execPHP(String script, String arg) throws IOException {
String[] command = new String[] {"php", "-r", script, arg};
Process php = Runtime.getRuntime().exec(command);
InputStream in = new BufferedInputStream(php.getInputStream(), 10000);
try {
int status = php.waitFor();
if (status != 0) {
throw new IOException("php terminated with status " + status);
}
} catch (InterruptedException e) {
throw new IOException(e.toString());
}
return in;
}
}