Example usage for android.util Xml newSerializer

List of usage examples for android.util Xml newSerializer

Introduction

In this page you can find the example usage for android.util Xml newSerializer.

Prototype

public static XmlSerializer newSerializer() 

Source Link

Document

Creates a new xml serializer.

Usage

From source file:org.addhen.smssync.util.DataFormatUtil.java

public static String makeXMLString(List<NameValuePair> pairs, String parentNode, String charset)
        throws IOException {
    XmlSerializer serializer = Xml.newSerializer();
    StringWriter writer = new StringWriter();
    serializer.setOutput(writer);//  www  .  jav  a  2  s  . com
    serializer.startDocument(charset, true);
    serializer.startTag("", parentNode);
    for (NameValuePair pair : pairs) {
        serializer.startTag("", pair.getName());
        serializer.text(pair.getValue());
        serializer.endTag("", pair.getName());
    }
    serializer.endTag("", parentNode);
    serializer.endDocument();
    return writer.toString();
}

From source file:pl.wasat.smarthma.utils.xml.OpmlBuilder.java

/**
 * Build xml string./*from   w  w  w  .j  av  a  2s.  c  o m*/
 *
 * @param opml the opml
 * @return the string
 */
public String buildXml(Opml opml) {
    XmlSerializer serializer = Xml.newSerializer();
    StringWriter writer = new StringWriter();
    List<Outline> outlines = opml.getBody().getOutline();
    try {
        serializer.setOutput(writer);
        serializer.startDocument("UTF-8", true);
        serializer.startTag("", Opml.class.getSimpleName());
        serializer.attribute("", "version", opml.getVersion());

        serializer.startTag("", Head.class.getSimpleName());
        for (Field headField : opml.getHead().getClass().getDeclaredFields()) {
            serializer.startTag("", headField.getName());
            String value = String.valueOf(FieldUtils.readField(opml.getHead(), headField.getName(), true));
            serializer.text(value);
            serializer.endTag("", headField.getName());
        }
        serializer.endTag("", Head.class.getSimpleName());

        serializer.startTag("", Body.class.getSimpleName());
        for (Outline outline : outlines) {
            serializer.startTag("", Outline.class.getSimpleName());
            for (Field field : Outline.class.getDeclaredFields()) {
                String value = String.valueOf(FieldUtils.readField(outline, field.getName(), true));
                serializer.attribute("", field.getName(), value);
            }
            serializer.endTag("", Outline.class.getSimpleName());
        }
        serializer.endTag("", Body.class.getSimpleName());
        serializer.endTag("", Opml.class.getSimpleName());
        serializer.endDocument();
        //String xml = writer.toString();
        //Log.i("XML", xml);
        return writer.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:de.gobro.andreas.pa.pa_cleint_java.SendTouch.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_send_touch);
    View v = findViewById(R.id.main_view);
    v.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);

    maxPoints = 10;// ww  w . j av a2s  .  co  m

    size = new Point();

    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);

    size.x = metrics.widthPixels;
    size.y = metrics.heightPixels;

    serializer = Xml.newSerializer();

    new Thread() {
        public void run() {
            try {
                Intent intent = getIntent();
                //clientSocket = new Socket("192.168.43.245",15000);
                clientSocket = new Socket(intent.getStringExtra(MainActivity.IP_FIELD), 15000);
                //TODO checkt, if connection is etabished

                out = clientSocket.getOutputStream();
                //            xml with
                //            http://www.ibm.com/developerworks/opensource/library/x-android/index.html#N102B3

                serializer.setOutput(out, "UTF-8");

                serializer.startTag("", "pa_smart_gui");
                serializer.startTag("", "init");
                serializer.startTag("", "maxTouch");
                serializer.text(maxPoints.toString());
                serializer.endTag("", "maxTouch");
                serializer.endTag("", "init");
                serializer.flush();

            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                Log.d("net", "some error !!!!2");
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                Log.d("net", "some conection error");
                e.printStackTrace();
                finish();

            }

        }
    }.start();
}

From source file:org.adblockplus.android.CrashReportDialog.java

public void onOk(View v) {
    String comment = ((EditText) findViewById(R.id.comments)).getText().toString();

    try {/*from   ww w .  j a  v a  2  s  .c om*/
        String[] reportLines = report.split(System.getProperty("line.separator"));
        int api = Integer.parseInt(reportLines[0]);
        int build = Integer.parseInt(reportLines[1]);

        XmlSerializer xmlSerializer = Xml.newSerializer();
        StringWriter writer = new StringWriter();

        xmlSerializer.setOutput(writer);
        xmlSerializer.startDocument("UTF-8", true);
        xmlSerializer.startTag("", "crashreport");
        xmlSerializer.attribute("", "version", "1");
        xmlSerializer.attribute("", "api", String.valueOf(api));
        xmlSerializer.attribute("", "build", String.valueOf(build));
        xmlSerializer.startTag("", "error");
        xmlSerializer.attribute("", "type", reportLines[2]);
        xmlSerializer.startTag("", "message");
        xmlSerializer.text(reportLines[3]);
        xmlSerializer.endTag("", "message");
        xmlSerializer.startTag("", "stacktrace");
        Pattern p = Pattern.compile("\\|");
        boolean hasCause = false;
        int i = 4;
        while (i < reportLines.length) {
            if ("cause".equals(reportLines[i])) {
                xmlSerializer.endTag("", "stacktrace");
                xmlSerializer.startTag("", "cause");
                hasCause = true;
                i++;
                xmlSerializer.attribute("", "type", reportLines[i]);
                i++;
                xmlSerializer.startTag("", "message");
                xmlSerializer.text(reportLines[i]);
                i++;
                xmlSerializer.endTag("", "message");
                xmlSerializer.startTag("", "stacktrace");
                continue;
            }
            Log.e(TAG, "Line: " + reportLines[i]);
            String[] element = TextUtils.split(reportLines[i], p);
            xmlSerializer.startTag("", "frame");
            xmlSerializer.attribute("", "class", element[0]);
            xmlSerializer.attribute("", "method", element[1]);
            xmlSerializer.attribute("", "isnative", element[2]);
            xmlSerializer.attribute("", "file", element[3]);
            xmlSerializer.attribute("", "line", element[4]);
            xmlSerializer.endTag("", "frame");
            i++;
        }
        xmlSerializer.endTag("", "stacktrace");
        if (hasCause)
            xmlSerializer.endTag("", "cause");
        xmlSerializer.endTag("", "error");
        xmlSerializer.startTag("", "comment");
        xmlSerializer.text(comment);
        xmlSerializer.endTag("", "comment");
        xmlSerializer.endTag("", "crashreport");
        xmlSerializer.endDocument();

        String xml = writer.toString();
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(getString(R.string.crash_report_url));
        httppost.setHeader("Content-Type", "text/xml; charset=UTF-8");
        httppost.addHeader("X-Adblock-Plus", "yes");
        httppost.setEntity(new StringEntity(xml));
        HttpResponse httpresponse = httpclient.execute(httppost);
        StatusLine statusLine = httpresponse.getStatusLine();
        Log.e(TAG, statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());
        Log.e(TAG, EntityUtils.toString(httpresponse.getEntity()));
        if (statusLine.getStatusCode() != 200)
            throw new ClientProtocolException();
        String response = EntityUtils.toString(httpresponse.getEntity());
        if (!"saved".equals(response))
            throw new ClientProtocolException();
        deleteFile(CrashHandler.REPORT_FILE);
    } catch (ClientProtocolException e) {
        Log.e(TAG, "Failed to submit a crash", e);
        Toast.makeText(this, R.string.msg_crash_submission_failure, Toast.LENGTH_LONG).show();
    } catch (IOException e) {
        Log.e(TAG, "Failed to submit a crash", e);
        Toast.makeText(this, R.string.msg_crash_submission_failure, Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        Log.e(TAG, "Failed to create report", e);
        // Assuming corrupted report file, just silently deleting it
        deleteFile(CrashHandler.REPORT_FILE);
    }
    finish();
}

From source file:net.fabiszewski.ulogger.GpxExportService.java

/**
 * Handle intent/*w  ww.  ja  v a 2 s .  c  om*/
 *
 * @param intent Intent
 */
@Override
protected void onHandleIntent(Intent intent) {

    if (!hasWritePermission()) {
        // no permission to write
        if (Logger.DEBUG) {
            Log.d(TAG, "[export gpx no permission]");
        }
        sendBroadcast(BROADCAST_WRITE_PERMISSION_DENIED, null);
        return;
    }
    if (!isExternalStorageWritable()) {
        // no access to external storage
        if (Logger.DEBUG) {
            Log.d(TAG, "[export gpx not writable]");
        }
        sendBroadcast(BROADCAST_EXPORT_FAILED, getString(R.string.e_external_not_writable));
        return;
    }

    FileOutputStream fileOutputStream = null;
    try {
        String trackName = db.getTrackName();
        if (trackName == null) {
            trackName = getString(R.string.unknown_track);
        }
        File dir = getDir();
        if (dir == null) {
            if (Logger.DEBUG) {
                Log.d(TAG, "[export gpx failed to create output folder]");
            }
            sendBroadcast(BROADCAST_EXPORT_FAILED, getString(R.string.e_output_dir));
            return;
        }
        File file = getFile(dir, trackName);
        int i = 0;
        while (file.exists()) {
            file = getFile(dir, trackName + "_" + (++i));
        }

        fileOutputStream = new FileOutputStream(file);

        XmlSerializer serializer = Xml.newSerializer();
        StringWriter writer = new StringWriter();

        serializer.setOutput(writer);

        // header
        serializer.startDocument("UTF-8", true);
        serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
        serializer.setPrefix("xsi", ns_xsi);
        serializer.startTag("", "gpx");
        serializer.attribute(null, "xmlns", ns_gpx);
        serializer.attribute(ns_xsi, "schemaLocation", schemaLocation);
        serializer.attribute(null, "version", "1.1");
        String creator = getString(R.string.app_name) + " " + BuildConfig.VERSION_NAME;
        serializer.attribute(null, "creator", creator);

        // metadata
        long trackTimestamp = db.getFirstTimestamp();
        String trackTime = DateFormat.format("yyyy-MM-ddThh:mm:ss", trackTimestamp * 1000).toString();
        serializer.startTag(null, "metadata");
        writeTag(serializer, "name", trackName);
        writeTag(serializer, "time", trackTime);
        serializer.endTag(null, "metadata");

        // track
        serializer.startTag(null, "trk");
        writeTag(serializer, "name", trackName);
        writePositions(serializer);
        serializer.endTag(null, "trk");

        serializer.endTag("", "gpx");
        serializer.endDocument();
        serializer.flush();

        String dataWrite = writer.toString();
        fileOutputStream.write(dataWrite.getBytes());
        fileOutputStream.flush();

        if (Logger.DEBUG) {
            Log.d(TAG, "[export gpx file written to " + file.getPath());
        }
        sendBroadcast(BROADCAST_EXPORT_DONE, null);
    } catch (IOException | IllegalArgumentException | IllegalStateException e) {
        if (Logger.DEBUG) {
            Log.d(TAG, "[export gpx exception: " + e + "]");
        }
        sendBroadcast(BROADCAST_EXPORT_FAILED, e.getMessage());
    } finally {
        if (fileOutputStream != null) {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                if (Logger.DEBUG) {
                    Log.d(TAG, "[export gpx exception: " + e + "]");
                }
                sendBroadcast(BROADCAST_EXPORT_FAILED, e.getMessage());
            }
        }
    }

}

From source file:fr.arnaudguyon.xmltojsonlib.JsonToXml.java

private String nodeToXML(Node node) {
    XmlSerializer serializer = Xml.newSerializer();
    StringWriter writer = new StringWriter();
    try {//from   w w  w  .ja va  2 s  .c o  m
        serializer.setOutput(writer);
        serializer.startDocument("UTF-8", true);

        nodeToXml(serializer, node);

        serializer.endDocument();
        return writer.toString();
    } catch (IOException e) {
        throw new RuntimeException(e); // TODO: do my own
    }
}

From source file:io.appium.uiautomator2.core.AccessibilityNodeInfoDumper.java

private InputStream toStream() throws IOException {
    final long startTime = SystemClock.uptimeMillis();
    try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
        serializer = Xml.newSerializer();
        shouldAddDisplayInfo = root == null;
        serializer.setOutput(outputStream, XML_ENCODING);
        serializer.startDocument(XML_ENCODING, true);
        serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
        final UiElement<?, ?> xpathRoot = root == null
                ? rebuildForNewRoot(currentActiveWindowRoot(),
                        NotificationListener.getInstance().getToastMessage())
                : rebuildForNewRoot(root, null);
        serializeUiElement(xpathRoot, 0);
        serializer.endDocument();/*from  w  w  w.java  2  s .c  o  m*/
        Logger.debug(String.format("The source XML tree (%s bytes) has been fetched in %sms",
                outputStream.size(), SystemClock.uptimeMillis() - startTime));
        return new ByteArrayInputStream(outputStream.toByteArray());
    }
}

From source file:org.runnerup.export.JoggSE.java

private void saveGPX(final Writer wr, final String gpx)
        throws IllegalArgumentException, IllegalStateException, IOException {
    final XmlSerializer mXML = Xml.newSerializer();
    mXML.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
    mXML.setOutput(wr);//from w  w w  .  j  a v  a2 s .  com
    mXML.startDocument("UTF-8", true);
    mXML.startTag("", "soap12:Envelope");
    mXML.attribute("", "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    mXML.attribute("", "xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
    mXML.attribute("", "xmlns:soap12", "http://www.w3.org/2003/05/soap-envelope");
    mXML.startTag("", "soap12:Body");
    mXML.startTag("", "SaveGpx");
    mXML.attribute("", "xmlns", "http://jogg.se/IphoneService");

    mXML.startTag("", "gpx");
    mXML.text(android.util.Base64.encodeToString(gpx.getBytes(), Base64.NO_WRAP));
    mXML.endTag("", "gpx");

    mXML.startTag("", "user");
    mXML.startTag("", "Email");
    mXML.text(username);
    mXML.endTag("", "Email");
    mXML.startTag("", "Password");
    mXML.text(password);
    mXML.endTag("", "Password");
    mXML.endTag("", "user");

    mXML.startTag("", "credentials");
    mXML.startTag("", "MasterUser");
    mXML.text(MASTER_USER);
    mXML.endTag("", "MasterUser");
    mXML.startTag("", "MasterKey");
    mXML.text(MASTER_KEY);
    mXML.endTag("", "MasterKey");
    mXML.endTag("", "credentials");
    mXML.endTag("", "SaveGpx");
    mXML.endTag("", "soap12:Body");
    mXML.endTag("", "soap12:Envelope");
    mXML.endDocument();
    mXML.flush();
}

From source file:org.transdroid.daemon.Vuze.VuzeXmlOverHttpClient.java

protected Map<String, Object> callXMLRPC(Long object, String method, Object[] params, Long connectionID,
        boolean paramsAreVuzeObjects) throws DaemonException {
    try {/*w w w . j  a v a2 s  .c o  m*/

        // prepare POST body
        XmlSerializer serializer = Xml.newSerializer();
        StringWriter bodyWriter = new StringWriter();
        serializer.setOutput(bodyWriter);
        serializer.startDocument(null, null);
        serializer.startTag(null, TAG_REQUEST);

        // set object
        if (object != null) {
            serializer.startTag(null, TAG_OBJECT).startTag(null, TAG_OBJECT_ID).text(object.toString())
                    .endTag(null, TAG_OBJECT_ID).endTag(null, TAG_OBJECT);
        }

        // set method
        serializer.startTag(null, TAG_METHOD).text(method).endTag(null, TAG_METHOD);
        if (params != null && params.length != 0) {
            // set method params
            serializer.startTag(null, TAG_PARAMS);
            Integer entryIndex = 0;
            for (Object param : params) {
                serializer.startTag(null, TAG_ENTRY).attribute(null, TAG_INDEX, entryIndex.toString());
                if (paramsAreVuzeObjects) {
                    serializer.startTag(null, TAG_OBJECT).startTag(null, TAG_OBJECT_ID);
                }
                serializer.text(serialize(param));
                if (paramsAreVuzeObjects) {
                    serializer.endTag(null, TAG_OBJECT_ID).endTag(null, TAG_OBJECT);
                }
                serializer.endTag(null, TAG_ENTRY);
                entryIndex++;
            }
            serializer.endTag(null, TAG_PARAMS);
        }

        // set connection id
        if (connectionID != null) {
            serializer.startTag(null, TAG_CONNECTION_ID).text(connectionID.toString()).endTag(null,
                    TAG_CONNECTION_ID);
        }
        // set request id, which for this purpose is always a random number
        Integer randomRequestID = new Integer(random.nextInt());
        serializer.startTag(null, TAG_REQUEST_ID).text(randomRequestID.toString()).endTag(null, TAG_REQUEST_ID);

        serializer.endTag(null, TAG_REQUEST);
        serializer.endDocument();

        // set POST body
        HttpEntity entity = new StringEntity(bodyWriter.toString());
        postMethod.setEntity(entity);

        // Force preemptive authentication
        // This makes sure there is an 'Authentication: ' header being send before trying and failing and retrying 
        // by the basic authentication mechanism of DefaultHttpClient
        postMethod.addHeader("Authorization",
                "Basic " + Base64.encodeBytes((username + ":" + password).getBytes()));

        // execute HTTP POST request
        HttpResponse response = client.execute(postMethod);

        // check status code
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            throw new DaemonException(ExceptionType.AuthenticationFailure, "HTTP " + HttpStatus.SC_UNAUTHORIZED
                    + " response (so no user or password or incorrect ones)");
        } else if (statusCode != HttpStatus.SC_OK) {
            throw new DaemonException(ExceptionType.ConnectionError,
                    "HTTP status code: " + statusCode + " != " + HttpStatus.SC_OK);
        }

        // parse response stuff
        //
        // setup pull parser
        XmlPullParser pullParser = XmlPullParserFactory.newInstance().newPullParser();
        entity = response.getEntity();
        //String temp = HttpHelper.ConvertStreamToString(entity.getContent());         
        //Reader reader = new StringReader(temp);
        Reader reader = new InputStreamReader(entity.getContent());
        pullParser.setInput(reader);

        // lets start pulling...
        pullParser.nextTag();
        pullParser.require(XmlPullParser.START_TAG, null, TAG_RESPONSE);

        // build list of returned values
        int next = pullParser.nextTag(); // skip to first start tag in list
        String name = pullParser.getName(); // get name of the first start tag

        // Empty response?
        if (next == XmlPullParser.END_TAG && name.equals(TAG_RESPONSE)) {

            return null;

        } else if (name.equals(TAG_ERROR)) {

            // Error
            String errorText = pullParser.nextText(); // the value of the ERROR
            entity.consumeContent();
            throw new DaemonException(ExceptionType.ConnectionError, errorText);

        } else {

            // Consume a list of ENTRYs?
            if (name.equals(TAG_ENTRY)) {

                Map<String, Object> entries = new HashMap<String, Object>();
                for (int i = 0; name.equals(TAG_ENTRY); i++) {
                    entries.put(TAG_ENTRY + i, consumeEntry(pullParser));
                    name = pullParser.getName();
                }
                entity.consumeContent();
                return entries;

            } else {

                // Only a single object was returned, not an entry listing
                return consumeObject(pullParser);
            }

        }

    } catch (IOException e) {
        throw new DaemonException(ExceptionType.ConnectionError, e.toString());
    } catch (XmlPullParserException e) {
        throw new DaemonException(ExceptionType.ParsingFailed, e.toString());
    }
}

From source file:net.gromgull.android.bibsonomyposter.BibsonomyPosterActivity.java

public void bookmark(String url, String title) throws ClientProtocolException, IOException {
    CredentialsProvider credProvider = new BasicCredentialsProvider();

    credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST,

            AuthScope.ANY_PORT, AuthScope.ANY_REALM), new UsernamePasswordCredentials(username, apikey));

    StringWriter sw = new StringWriter();

    XmlSerializer x = Xml.newSerializer();
    x.setOutput(sw);/* w ww .  jav a2  s  . c om*/
    x.startDocument(null, null);
    x.startTag(null, "bibsonomy");
    x.startTag(null, "post");
    x.attribute(null, "description", "a bookmark");

    x.startTag(null, "user");
    x.attribute(null, "name", username);
    x.endTag(null, "user");

    x.startTag(null, "tag");
    x.attribute(null, "name", "from_android");
    x.endTag(null, "tag");

    x.startTag(null, "group");
    x.attribute(null, "name", "public");
    x.endTag(null, "group");

    x.startTag(null, "bookmark");
    x.attribute(null, "url", url);
    x.attribute(null, "title", title);
    x.endTag(null, "bookmark");

    x.endTag(null, "post");
    x.endTag(null, "bibsonomy");

    x.endDocument();

    Log.v(LOGTAG, "XML: " + sw.toString());

    HttpPost httppost = new HttpPost("http://www.bibsonomy.org/api/users/" + username + "/posts");
    StringEntity e = new StringEntity(sw.toString());
    e.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/xml"));
    httppost.setEntity(e);

    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.setCredentialsProvider(credProvider);
    HttpResponse response = httpclient.execute(httppost);
    Log.i(LOGTAG, "Bibsonomy said :" + response.getStatusLine());
    if (response.getStatusLine().getStatusCode() != 201) {
        HttpEntity re = response.getEntity();
        byte b[] = new byte[(int) re.getContentLength()];
        re.getContent().read(b);
        Log.v(LOGTAG, "Bibsonomy said: " + new String(b));
        throw new IOException("Bibsonomy said :" + response.getStatusLine());

    }
}