/*
   * @see com.painiu.core.service.api.ResponseFormat#format(java.io.Writer, java.lang.Object)
   */
  public void format(Writer out, Object object) throws IOException {
    XmlRpcResponseProcessor processor = new XmlRpcResponseProcessor();

    String result = null;

    if (object instanceof ApiException) {
      ApiException apiEx = (ApiException) object;
      Exception e = apiEx;

      if (apiEx.getCall() != null) {
        e = new DebuggableApiException(apiEx);
      }

      result =
          new String(
              processor.encodeException(e, ENCODING, Integer.parseInt(apiEx.getCode())), ENCODING);

    } else if (object == null || object instanceof ApiObject) {
      String restResult = null;

      if (object == null) {
        restResult = "";
      } else {
        Document doc = createDocument();
        Element root = doc.addElement("rsp");
        createElement(root, (ApiObject) object);

        restResult = root.asXML();

        restResult = restResult.substring(5, restResult.length() - 6);
      }

      try {
        result = new String(processor.encodeResponse(restResult, ENCODING), ENCODING);
      } catch (Exception e) {
        // should not happen
        e.printStackTrace();
      }

    } else {
      throw new IllegalArgumentException("unsupported object");
    }

    out.write(result);
  }
 /*
  * @see java.lang.Throwable#toString()
  */
 @Override
 public String toString() {
   StringWriter out = new StringWriter();
   try {
     writeError(out, exception);
   } catch (IOException e) {
     return exception.toString();
   }
   return out.getBuffer().toString();
 }