Android Studio 2.1.2
I am trying to test getJsonFromResource which calls loadNewsFeed.
I want to be able to test 2 cases 1 where loadNewsFeed will return an empty string and the other where it will return some json string.
So I am trying to mock the loadNewsFeed function to return an empty string. However, when the concrete getJsonFromResource is called it will call the real loadNewsFeed and cause a null pointer exception.
This is what I have tried in my test comments explaining what I am doing:
#Test
public void shouldFailIfJSONStringIsEmpty() throws Exception {
/* Mock Context class */
Context context = mock(Context.class);
/* initialize the concrete parseNewsFeed passing in the fake context */
ParseNewsFeed parseNewsFeed = new ParseNewsFeed(context);
/* Create a mock of the parseNewsFeed so a fake call to loadNewsFeed will return an empty string */
ParseNewsFeed mockParseNewsFeed = mock(ParseNewsFeed.class);
/* Mock the events that will be verified */
ParseNewsFeedContract.Events<Status> mockEvents = mock(ParseNewsFeedContract.Events.class);
/* Return an empty string when loadNewsFeed is called */
when(mockParseNewsFeed.loadNewsFeed()).thenReturn("");
/* Called the concrete getJsonFromResource */
parseNewsFeed.getJsonFromResource(mockEvents);
/* verify that onNewsFailure was called once and onNewsSuccess was never called */
verify(mockEvents, times(1)).onNewsFailure(anyString());
verify(mockEvents, never()).onNewsSuccess(any(Status.class));
}
This is the class I am trying to test.
public class ParseNewsFeed implements ParseNewsFeedContract {
private Context mContext;
public ParseNewsFeed(Context context) {
if(context != null) {
Timber.d("mContext != null");
mContext = context;
}
}
/**
* Get the json from the local resource file and add to the cache to save loading each time
* #return the json in string representation
*/
#Override
public void getJsonFromResource(Events<Status> events) {
/* Get the json in string format */
final String jsonString = loadNewsFeed();
/* Check that is contains something */
if(!jsonString.isEmpty()) {
try {
final Status status = new Gson().fromJson(jsonString, Status.class);
if(status != null) {
Timber.d("url: %s", status.getResults().get(0).getMultimedia().get(0).getUrl());
events.onNewsSuccess(status);
}
else {
Timber.e("status == null");
events.onNewsFailure("Failed to get results from json");
}
}
catch (JsonSyntaxException e) {
Timber.e("Invalid JSON: %s", e.getMessage());
events.onNewsFailure(e.getMessage());
}
}
}
/**
* Opens and reads from the news_list and writes to a buffer
* #return return the json representation as a string or a empty string for failure
*/
public String loadNewsFeed() {
InputStream inputStream = mContext.getResources().openRawResource(R.raw.news_list);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
InputStreamReader inputReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferReader = new BufferedReader(inputReader);
int n;
while ((n = bufferReader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
inputStream.close();
}
catch (IOException ioException) {
return "";
}
return writer.toString();
}
}
First of all, the reason why your original code doesn't work is because there's no relationship between your two objects parseNewsFeed and mockParseNewsFeed, hence the stubbing that you do for the mockParseNewsFeed doesn't have any effect when you invoke parseNewsFeed.getJsonFromResource(mockEvents). Using spy as David Wallace suggested would work, but if I were you, I would rewrite the code a bit differently to make it even easier to test.
One observation is that the code in loadNewsFeed() method doesn't seem to have a strong relationship with the ParseNewsFeed class, so I'd extract this code into an object (e.g. NewsFeedLoader), and then have this object as a dependency of ParseNewsFeed class. Then you can mock this Loader easily (return "" or any string that you want when passing a Context and possibly the R.raw.news_list id as well). With this Loader class, you can even unit test it separately from the ParseNewsFeed, and being able to improve the Loader however you want to (e.g. a better way to read a raw resource) without affecting the ParseNewsFeed class.
Use when() and then() methods of your mocked context. It is actually described in example of official tutorial here.
#Mock
Context mMockContext;
#Test
public void readStringFromContext_LocalizedString() {
// Given a mocked Context injected into the object under test...
when(mMockContext.getString(R.string.hello_word))
.thenReturn(FAKE_STRING);
ClassUnderTest myObjectUnderTest = new ClassUnderTest(mMockContext);
// ...when the string is returned from the object under test...
String result = myObjectUnderTest.getHelloWorldString();
// ...then the result should be the expected one.
assertThat(result, is(FAKE_STRING));
It looks like you want to have a ParseNewsFeed object where the loadNewsFeed method has been stubbed, but other methods work correctly. The simplest way to get that would probably be to create a spy, something like
ParseNewsFeed spyParseNewsFeed = Mockito.spy(new ParseNewsFeed(context));
Mockito.doReturn("").when(spyParseNewsFeed).loadNewsFeed();
Related
How can I call this C# method from Java then return the string value?
public string getTest () { return "test"; }
This is what I've tried:
String str = UnityPlayer.UnitySendMessage("ProfileSave", "getTest","");
I am getting the below error
String str=UnityPlayer.UnitySendMessage("ProfileSave", "getTest","");
^
required: String
found: void
UnityPlayer.UnitySendMessage is a void function and does not return a value. Take a look at the UnitySendMessageExtension function implementation below. It is similar to turnipinindia's answer but it returns a value. It only returns a string so you have to convert that string to whatever variable type you are working with.
Java:
public final class MyPlugin
{
//Make class static variable so that the callback function is sent to one instance of this class.
public static MyPlugin testInstance;
public static MyPlugin instance()
{
if(testInstance == null)
{
testInstance = new MyPlugin();
}
return testInstance;
}
string result = "";
public string UnitySendMessageExtension(string gameObject, string functionName, string funcParam)
{
UnityPlayer.UnitySendMessage(gameObject, functionName, funcParam);
string tempResult = result;
return tempResult;
}
//Receives result from C# and saves it to result variable
void receiveResult(string value)
{
result = "";//Clear old data
result = value; //Get new one
}
}
C#:
class TestScript: MonoBehaviour
{
//Sends the data from PlayerPrefs to the receiveResult function in Java
void sendResultToJava(float value)
{
using(AndroidJavaClass javaPlugin = new AndroidJavaClass("com.company.product.MyPlugin"))
{
AndroidJavaObject pluginInstance = javaPlugin.CallStatic("instance");
pluginInstance.Call("receiveResult",value.ToString());
}
}
//Called from Java to get the saved PlayerPrefs
void testFunction(string key)
{
float value = PlayerPrefs.GetFloat(key) //Get the saved value from key
sendResultToJava(value); //Send the value to Java
}
}
Usage from Java:
String str = UnitySendMessageExtension("ProfileLoad", "testFunction","highScore");
This will work with any C# function. Just make sure that you call sendResultToJava function at the end of the C# function like we did in the testFunction function, if you want it to return value.
UnitySendMessage cannot return anything to Android.
One way you could do this is implement another method in Android that Unity will pass the value back to when requested.
So for example, first in android you request the data:
UnityPlayer.UnitySendMessage("ProfileSave", "getData");
In unity you have a method that receives that request and sends the data back to android:
public void getData () {
string dataString = "exampleData";
//code to send data back to ReceiveData method in Android, something like this probably:
AndroidJavaClass myAndroidClass = new AndroidJavaClass ("com.myCompany.myApplication.myClass");
myAndroidClass.CallStatic ("ReceiveData",dataString);
}
Then in android you have a method waiting to receive the data (most likely a static method):
public static void ReceiveData(string data){
//do stuff with data
}
I have developed an Android application which prints a photo using either PrintHelper or Hp mobile print SDK. However, when before the printing process, Android print Dialog comes up on the screen.
How can I skip the android print dialog, when the application prints the photo ?
I have already come across below questions. Briefly, the answers are "there is no way to do this."
Print without print dialog Android
Print from android without system dialog
Is it possible to directly print content to a wifi-connnected printer without user interaction in android programming?
https://code.google.com/p/android/issues/detail?id=160908
However, I have tried to use HP ePrint android application to print any photo. In this application, there is no any Android Print Dialog, It can print any document directly, without displaying Android Print Dialog on the screen.
So that means, there is a way to print a doc directly.
It is possible for printint to PDF by calling print adapter lifecycle methods. However as callbacks are non public abstract classes and system throws segfault if null is supplied, you need to use DexMaker to implement them. I have implemented for webView adapter like this:
#Override
protected void onPreExecute() {
super.onPreExecute();
printAdapter = webView.createPrintDocumentAdapter();
}
#Override
protected Void doInBackground(Void... voids) {
File file = new File(pdfPath);
if (file.exists()) {
file.delete();
}
try {
file.createNewFile();
// get file descriptor
descriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_WRITE);
// create print attributes
PrintAttributes attributes = new PrintAttributes.Builder()
.setMediaSize(PrintAttributes.MediaSize.ISO_A4)
.setResolution(new PrintAttributes.Resolution("id", PRINT_SERVICE, 300, 300))
.setColorMode(PrintAttributes.COLOR_MODE_COLOR)
.setMinMargins(new PrintAttributes.Margins(0, 0, 0, 0))
.build();
ranges = new PageRange[]{new PageRange(1, numberPages)};
// dexmaker cache folder
cacheFolder = new File(context.getFilesDir() +"/etemp/");
printAdapter.onStart();
printAdapter.onLayout(attributes, attributes, new CancellationSignal(), getLayoutResultCallback(new InvocationHandler() {
#Override
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
if (method.getName().equals("onLayoutFinished")) {
onLayoutSuccess();
} else {
Log.e(TAG, "Layout failed");
pdfCallback.onPdfFailed();
}
return null;
}
}, cacheFolder), new Bundle());
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, e != null ? e.getMessage() : "PrintPdfTask unknown error");
}
return null;
}
private void onLayoutSuccess() throws IOException {
PrintDocumentAdapter.WriteResultCallback callback = getWriteResultCallback(new InvocationHandler() {
#Override
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
if (method.getName().equals("onWriteFinished")) {
pdfCallback.onPdfCreated();
} else {
Log.e(TAG, "Layout failed");
pdfCallback.onPdfFailed();
}
return null;
}
}, cacheFolder);
printAdapter.onWrite(ranges, descriptor, new CancellationSignal(), callback);
}
/**
* Implementation of non public abstract class LayoutResultCallback obtained via DexMaker
* #param invocationHandler
* #param dexCacheDir
* #return LayoutResultCallback
* #throws IOException
*/
public static PrintDocumentAdapter.LayoutResultCallback getLayoutResultCallback(InvocationHandler invocationHandler,
File dexCacheDir) throws IOException {
return ProxyBuilder.forClass(PrintDocumentAdapter.LayoutResultCallback.class)
.dexCache(dexCacheDir)
.handler(invocationHandler)
.build();
}
/**
* Implementation of non public abstract class WriteResultCallback obtained via DexMaker
* #param invocationHandler
* #param dexCacheDir
* #return LayoutResultCallback
* #throws IOException
*/
public static PrintDocumentAdapter.WriteResultCallback getWriteResultCallback(InvocationHandler invocationHandler,
File dexCacheDir) throws IOException {
return ProxyBuilder.forClass(PrintDocumentAdapter.WriteResultCallback.class)
.dexCache(dexCacheDir)
.handler(invocationHandler)
.build();
}
It seems that I am unable to set arbitrary query parameters to a #Get declaration
My endpoint looks like
http://api.lmiforall.org.uk/api/v1/ashe/estimateHours?soc=2349&coarse=true
There are a non trivial amount of parameters to this query, is there a declaration I can use to indicate this to the #Rest interface?
I tried declaring it as this, but it complains about fields being unused.
#Get("estimateHours")
ASHEFilterInfo GetEstimateHours( int soc, boolean coarse, String filters, String breakdown);
java: #org.androidannotations.annotations.rest.Get annotated method has only url variables in the method parameters
Look at AA cookbook.
Try this (not tested):
#Rest(rootUrl = "http://api.lmiforall.org.uk/api/v1/ashe")
public interface MyService {
#Get("/estimateHours?soc={soc}&coarse={coarse}&breakdown={breakdonw}&filters={filters}")
ASHEFilterInfo GetEstimateHoursFiltered( int soc, boolean coarse, String filters, String breakdown);
#Get("/estimateHours?soc={soc}&coarse={coarse}&breakdown={breakdonw}")
ASHEFilterInfo GetEstimateHours( int soc, boolean coarse, String breakdown);
}
When I needed to create #Get request with many dynamic parameteres, and some of them could be duplicated, I had resolved that problem so:
#Rest(rootUrl = "http://example.com:9080/",
converters = { GsonHttpMessageConverter.class },
interceptors = { ApiInterceptor.class })
public interface ExampleApi {
#Get("content/home/product-type/list?{filters}&domain={domain}") //filters is String like "param1=value1¶m1=value2¶m3=value3"
ProductTypeListResponse getProductTypeList(int domain, String filters);
}
public class ApiInterceptor implements ClientHttpRequestInterceptor {
private static final String TAG = ApiInterceptor.class.getSimpleName();
#Override
public ClientHttpResponse intercept(final HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
final QueryMultiParamsHttpRequest modifiedRequest = new QueryMultiParamsHttpRequest(request);
return execution.execute(modifiedRequest, body);
}
}
public class QueryMultiParamsHttpRequest implements HttpRequest {
private static final String TAG = QueryParametersBuilder.class.getSimpleName();
private HttpRequest httpRequest;
public QueryMultiParamsHttpRequest(final HttpRequest httpRequest) {
this.httpRequest = httpRequest;
}
#Override
public HttpMethod getMethod() {
return httpRequest.getMethod();
}
#Override
public URI getURI() {
final URI originalURI = httpRequest.getURI();
final String query = originalURI.getQuery() != null ? originalURI.getQuery().replace("%3D", "=").replace("%26", "&") : null;
URI newURI = null;
try {
newURI = new URI(originalURI.getScheme(), originalURI.getUserInfo(), originalURI.getHost(), originalURI.getPort(), originalURI.getPath(),
query, originalURI.getFragment());
} catch (URISyntaxException e) {
Log.e(TAG, "Error while creating URI of QueryMultiParamsHttpRequest", e);
}
return newURI;
}
#Override
public HttpHeaders getHeaders() {
return httpRequest.getHeaders();
}
}
So, I created a wrapper for HttpRequest, that can decode symbols "=" and "&". And this wrapper replaces original HttpRequest in ApiInterceptor. This is a little hacky solution, but it works.
I ran into this same issue and came up with a another solution that while far from ideal, works. The particular problem I was trying to solve was handling "HATEOAS" links.
What I ended up doing was creating a separate class called HATEOASClient to contain endpoint methods that would not escape the HATEOAS links passed in as params. To do that I basically just looked at an auto generated endpoint method and coped/tweaked the body in my implementation.
These methods use the same RestTemplate instance AndroidAnnotations sets up so you still get access to all the general setup you do on the RestTemplate.
For example:
public ResponseEntity<Foo> postFoo(Foo foo) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set(RestHeader.AUTH_TOKEN_HEADER, getClient().getHeader(RestHeader.AUTH_TOKEN_HEADER));
httpHeaders.set(RestHeader.ACCEPT_LANGUAGE_HEADER, getClient().getHeader(RestHeader.ACCEPT_LANGUAGE_HEADER));
httpHeaders.setAuthorization(authentication);
HttpEntity<Foo> requestEntity = new HttpEntity<>(null, httpHeaders);
HashMap<String, Object> urlVariables = new HashMap<>();
urlVariables.put("link", foo.getLinks().getFooCreate().getHref());
URI expanded = new UriTemplate(getClient().getRootUrl().
concat(API_VERSION + "{link}")).expand(urlVariables);
final String url;
try {
url = URLDecoder.decode(expanded.toString(), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return getClient().getRestTemplate().
exchange(url, HttpMethod.POST, requestEntity, Foo.class, urlVariables);
}
If all parameters is required you can use #Path annotation.
#Rest(rootUrl = "http://api.lmiforall.org.uk/api/v1/ashe")
public interface MyService {
#Get("/estimateHours?soc={soc}&coarse={coarse}&breakdown={breakdown}&filters={filters}")
ASHEFilterInfo GetEstimateHours(#Path int soc, #Path boolean coarse, #Path String breakdown, #Path String filters);
}
If one of the parameters is optional, there isn't yet a solution that can you can easily pass parameters using Android Annotations. But anybody can contribute to better Android Annotations.
if you define the params for each method then you need to provide them in each request. I thought this was sort of over kill too so what I did was just make a generic get/post request in my api client then just manually enter the values, if you don't define the root url I suppose you could use the QueryStringBuilder class and build the uri that way.
#Rest(rootUrl = "https://path/to/api/", converters = { FormHttpMessageConverter.class,
GsonHttpMessageConverter.class, ByteArrayHttpMessageConverter.class })
public interface ApiClient {
#Get("{uri}")
JsonElement apiGet(String uri);
#Post("{uri}")
JsonObject apiPost(String uri,MultiValueMap data);
RestTemplate getRestTemplate();
void setRootUrl(String rootUrl);
void setRestTemplate(RestTemplate restTemplate);
}
Example usage
JsonElement resp = apiClient.apiGet("method/?random_param=1&another_param=test);
It's not as clean but can be dynamic
I have a doubt about the possibility of repeating an AsyncTask in an application for Android. I would like to repeat some operations, the download of a file from a server for example, n times if it is impossible for some reasons download the file. There is a quick way to do this?
You cannot repeat an AsyncTask but you could repeat the operations it executes.
I've made this little helper class that you might want to extend in place of AsyncTask, the only big difference is that you will use repeatInBackground instead of doInBackground and that onPostExecute will have a new parameter, the eventual Exception thrown.
Anything inside repeatInBackground will be repeated automatically until result is different from null / exception is not thrown and there are been less than maxTries.
The last exception thrown inside the loop will be returned in the onPostExecute(Result, Exception).
You can set max tries using the RepeatableAsyncTask(int retries) constructor.
public abstract class RepeatableAsyncTask<A, B, C> extends AsyncTask<A, B, C> {
private static final String TAG = "RepeatableAsyncTask";
public static final int DEFAULT_MAX_RETRY = 5;
private int mMaxRetries = DEFAULT_MAX_RETRY;
private Exception mException = null;
/**
* Default constructor
*/
public RepeatableAsyncTask() {
super();
}
/**
* Constructs an AsyncTask that will repeate itself for max Retries
* #param retries Max Retries.
*/
public RepeatableAsyncTask(int retries) {
super();
mMaxRetries = retries;
}
/**
* Will be repeated for max retries while the result is null or an exception is thrown.
* #param inputs Same as AsyncTask's
* #return Same as AsyncTask's
*/
protected abstract C repeatInBackground(A...inputs);
#Override
protected final C doInBackground(A...inputs) {
int tries = 0;
C result = null;
/* This is the main loop, repeatInBackground will be repeated until result will not be null */
while(tries++ < mMaxRetries && result == null) {
try {
result = repeatInBackground(inputs);
} catch (Exception exception) {
/* You might want to log the exception everytime, do it here. */
mException = exception;
}
}
return result;
}
/**
* Like onPostExecute but will return an eventual Exception
* #param c Result same as AsyncTask
* #param exception Exception thrown in the loop, even if the result is not null.
*/
protected abstract void onPostExecute(C c, Exception exception);
#Override
protected final void onPostExecute(C c) {
super.onPostExecute(c);
onPostExecute(c, mException);
}
}
You cannot reuse the same AsyncTask object as, according to the AsyncTask Docs
The task can be executed only once (an exception will be thrown if a second execution is attempted.)
But you can create however many new objects of that class you need inside of a loop. However a better way you be to do the download operation n number of times inside your doInBackground().
If this doesn't answer your question then please be more specific as to your problem
I did it that way. It can try and try until (tries == MAX_RETRY) or the result is not null. A slightly modified code from accepted answer, better for me.
private class RssReaderTask extends AsyncTask<String, Void, ArrayList<RssItem>> {
// max number of tries when something is wrong
private static final int MAX_RETRY = 3;
#Override
protected ArrayList<RssItem> doInBackground(String... params) {
ArrayList<RssItem> result = null;
int tries = 0;
while(tries++ < MAX_RETRY && result == null) {
try {
Log.i("RssReaderTask", "********** doInBackground: Processing... Trial: " + tries);
URL url = new URL(params[0]);
RssFeed feed = RssReader.read(url);
result = feed.getRssItems();
} catch (Exception ex) {
Log.i("RssReaderTask", "********** doInBackground: Feed error!");
}
}
return result;
}
#Override
protected void onPostExecute(ArrayList<RssItem> result) {
// deal with result
}
}
I was working on capturing the order of elements contained in tag. Here is all the code:
League.java:
#Root
#Convert(value = LeagueConverter.class)
public class League
{
#Attribute
private String name;
#Element(name="headlines", required = false)
private Headlines headlines;
#Element(name="scores", required = false)
private Scores scores;
#Element(name="standings", required = false)
private Standing standings;
#Element(name="statistics", required = false)
private LeagueStatistics statistics;
public List<String> order = new ArrayList<String>();
// get methods for all variables
}
LeagueConverter.java:
public class LeagueConverter implements Converter<League>
{
#Override
public League read(InputNode node) throws Exception
{
League league = new League();
InputNode next = node.getNext();
while( next != null )
{
String tag = next.getName();
if(tag.equalsIgnoreCase("headlines"))
{
league.order.add("headlines");
}
else if(tag.equalsIgnoreCase("scores"))
{
league.order.add("scores");
}
else if(tag.equalsIgnoreCase("statistics"))
{
league.order.add("statistics");
}
else if(tag.equalsIgnoreCase("standings"))
{
league.order.add("standings");
}
next = node.getNext();
}
return league;
}
#Override
public void write(OutputNode arg0, League arg1) throws Exception
{
throw new UnsupportedOperationException("Not supported yet.");
}
}
Exampe of XML:
<android>
<leagues>
<league name ="A">
<Headlines></Headlines>
<Scores></Scores>
...
</league>
<league name ="B">...</league>
</leagues>
</android>
How I'm calling it and expecting it to behave: (Snippet)
Android android = null;
Serializer serial = new Persister(new AnnotationStrategy());
android = serial.read(Android.class, source);
Log.i("Number of leagues found ",tsnAndroid.getLeagueCount() + ""); // prints fine
League nhl = tsnAndroid.getLeagues().get(0); // works fine
// DOES NOT WORK throws NullPointerEx
League nhl2 = tsnAndroid.getLeagueByName("A");
// DOES NOT WORK throws NullPointerEx
for(String s : nhl.getOrder())
{
Log.i("ORDER>>>>>", s);
}
The problem:
android.getLeagueByName() (Works with #Attribute name) suddenly stops working when I have the converter set, so its like the following from League.java, never gets set.
#Attribute
private String name; // not being set
However, when I comment out the converter declaration in League.java - Every league has an attribute called name and android.getLeagueByName() starts working fine...
Does #Convert for League somehow interfere with #Attribute in League?
Even though this question is outrageously old (as is the SimpleXML library), I will give my two cents.
#Convert annotation works only with #Element, but it does not have any effect on #Attribute. I'm not sure if that's a bug or a feature, but there is another way of handling custom serialized objects - called Transform with Matcher, and it works both with Attributes and with Elements. Instead of using the Converters, you define a Transform class that handles serialization and deserialization:
import java.util.UUID;
import org.simpleframework.xml.transform.Transform;
public class UUIDTransform implements Transform<UUID> {
#Override
public UUID read(String value) throws Exception {
return value != null ? UUID.fromString(value) : null;
}
#Override
public String write(UUID value) throws Exception {
return value != null ? value.toString() : null;
}
}
As you can see, it is more straight-forward than implementing the Convert interface!
Create a similar class for all your objects that require custom de/serialization.
Now instantiate a RegistryMatcher object and register there your custom classes with their corresponding Transform classes. This is a thread-safe object that internally uses a cache, so it might be a good idea to keep it as a singleton.
private static final RegistryMatcher REGISTRY_MATCHER = new RegistryMatcher();
static {
try {
REGISTRY_MATCHER.bind(UUID.class, UUIDTransform.class);
// register all your Transform classes here...
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Finally, you can create a Persister class each time before a conversion and pass it the AnnotationStrategy together with your RegistryMatcher instance. In this factory method below, we will also use an indenting formatter:
private static Persister createPersister(int indent) {
return new Persister(new AnnotationStrategy(), REGISTRY_MATCHER, new Format(indent));
}
Now you can make your serialization/deserialization methods:
public static String objectToXml(Object object, int indent) throws MyObjectConversionException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
Persister p = createPersister(indent);
try {
p.write(object, out, "UTF-8");
return out.toString("UTF-8");
} catch (Exception e) {
throw new MyObjectConversionException("Cannot serialize object " + object + " to XML: " + e.getMessage(), e);
}
}
public static <T> T xmlToObject(String xml, final Class<T> clazz) throws MyObjectConversionException {
Persister p = createPersister(0);
try {
return (T) p.read(clazz, xml);
} catch (Exception e) {
throw new MyObjectConversionException(
"Cannot deserialize XML to object of type " + clazz + ": " + e.getMessage(), e);
}
}
The only issue with this approach is when you want to have different formatting for the same object - e.g. once you want the java.util.Date to have just the date component, while later on you also want to have the time component. Then just extend the Date class, calling it DateWithTime, and make a different Transform for it.
#ElementListUnion will capture the order of elements
The #Convert annotation works only on #Element fields. I am struggling against converting #Attribute fields too but with no success for now...