private void fetchTasks(TracksAction act) {
    final String server = _prefs.getString(PreferenceConstants.SERVER, null);
    final boolean badcert = _prefs.getBoolean(PreferenceConstants.BADCERT, false);
    final String username = _prefs.getString(PreferenceConstants.USERNAME, null);
    final String password = _prefs.getString(PreferenceConstants.PASSWORD, null);

    Log.d(TAG, "Fetching tasks");

    Handler replyTo = act.notify;

    if (server == null || username == null || password == null) {
      Message.obtain(replyTo, PREFS_FAIL_CODE).sendToTarget();
      return;
    }

    HttpResponse r;
    InputStream[] ret = new InputStream[3];

    Message.obtain(replyTo, FETCH_CODE).sendToTarget();

    try {
      r =
          HttpConnection.get(
              PreferenceUtils.getUri(_prefs, "contexts.xml"), username, password, badcert);
      ret[0] = r.getEntity().getContent();

      r =
          HttpConnection.get(
              PreferenceUtils.getUri(_prefs, "projects.xml"), username, password, badcert);
      ret[1] = r.getEntity().getContent();

      r =
          HttpConnection.get(
              PreferenceUtils.getUri(_prefs, "todos.xml"), username, password, badcert);
      ret[2] = r.getEntity().getContent();
    } catch (Exception e) {
      Log.w(TAG, "Failed to fetch tasks!", e);
      Message.obtain(replyTo, FETCH_FAIL_CODE).sendToTarget();
      return;
    }

    Message.obtain(replyTo, PARSE_CODE).sendToTarget();

    try {
      Xml.parse(ret[0], Xml.Encoding.UTF_8, new ContextXmlHandler());
      Xml.parse(ret[1], Xml.Encoding.UTF_8, new ProjectXmlHandler());
      Xml.parse(ret[2], Xml.Encoding.UTF_8, new TaskXmlHandler());
    } catch (IOException e) {
      Log.w(TAG, "Failed to read XML!", e);
      Message.obtain(replyTo, FETCH_FAIL_CODE).sendToTarget();
      return;
    } catch (SAXException e) {
      Log.w(TAG, "Failed to parse XML!", e);
      Message.obtain(replyTo, PARSE_FAIL_CODE).sendToTarget();
      return;
    }

    Message.obtain(replyTo, SUCCESS_CODE).sendToTarget();
  }
Ejemplo n.º 2
0
    /**
     * Create a key with the given top-left coordinate and extract its attributes from the XML
     * parser.
     *
     * @param res resources associated with the caller's context
     * @param parent the row that this key belongs to. The row must already be attached to a {@link
     *     Keyboard}.
     * @param x the x coordinate of the top-left
     * @param y the y coordinate of the top-left
     * @param parser the XML parser containing the attributes for this key
     */
    public Key(
        Context askContext,
        Resources res,
        Row parent,
        KeyboardDimens keyboardDimens,
        int x,
        int y,
        XmlResourceParser parser) {
      this(parent, keyboardDimens);
      final Resources askResources = askContext.getResources();
      SparseIntArray attributeIdMap = parent.parent.attributeIdMap;
      this.x = x;
      this.y = y;

      // setting up some defaults
      width = Math.min(keyboardDimens.getKeyMaxWidth(), parent.defaultWidth);
      height =
          KeyboardSupport.getKeyHeightFromHeightCode(
              keyboardDimens,
              parent.defaultHeightCode,
              askResources.getConfiguration().orientation);
      gap = parent.defaultHorizontalGap;
      codes = null;
      iconPreview = null;
      popupCharacters = null;
      popupResId = 0;
      repeatable = false;
      showPreview = true;
      dynamicEmblem = KEY_EMBLEM_NONE;
      modifier = false;
      sticky = false;

      // loading data from XML
      int[] remoteKeyboardLayoutStyleable = parent.parent.remoteKeyboardLayoutStyleable;
      TypedArray a =
          res.obtainAttributes(Xml.asAttributeSet(parser), remoteKeyboardLayoutStyleable);
      int n = a.getIndexCount();
      for (int i = 0; i < n; i++) {
        final int remoteIndex = a.getIndex(i);
        final int localAttrId = attributeIdMap.get(remoteKeyboardLayoutStyleable[remoteIndex]);
        setDataFromTypedArray(parent, keyboardDimens, askResources, a, remoteIndex, localAttrId);
      }
      a.recycle();
      this.x += gap;

      int[] remoteKeyboardKeyLayoutStyleable = parent.parent.remoteKeyboardKeyLayoutStyleable;
      a = res.obtainAttributes(Xml.asAttributeSet(parser), remoteKeyboardKeyLayoutStyleable);
      n = a.getIndexCount();
      for (int i = 0; i < n; i++) {
        final int remoteIndex = a.getIndex(i);
        final int localAttrId = attributeIdMap.get(remoteKeyboardKeyLayoutStyleable[remoteIndex]);
        setDataFromTypedArray(parent, keyboardDimens, askResources, a, remoteIndex, localAttrId);
      }
      externalResourcePopupLayout = popupResId != 0;
      if (codes == null && !TextUtils.isEmpty(label)) {
        codes = new int[] {label.charAt(0)};
      }
      a.recycle();
    }
Ejemplo n.º 3
0
 public Row(Context askContext, Resources res, Keyboard parent, XmlResourceParser parser) {
   this.parent = parent;
   // some defaults
   defaultWidth = parent.mDefaultWidth;
   defaultHeightCode = parent.mDefaultHeightCode;
   defaultHorizontalGap = parent.mDefaultHorizontalGap;
   verticalGap = parent.getVerticalGap();
   // now reading from the XML
   SparseIntArray attributeIdMap = parent.attributeIdMap;
   int[] remoteKeyboardLayoutStyleable = parent.remoteKeyboardLayoutStyleable;
   TypedArray a =
       res.obtainAttributes(Xml.asAttributeSet(parser), remoteKeyboardLayoutStyleable);
   int n = a.getIndexCount();
   for (int i = 0; i < n; i++) {
     final int remoteIndex = a.getIndex(i);
     final int localAttrId = attributeIdMap.get(remoteKeyboardLayoutStyleable[remoteIndex]);
     try {
       switch (localAttrId) {
         case android.R.attr.keyWidth:
           defaultWidth =
               getDimensionOrFraction(
                   a, remoteIndex, parent.mDisplayWidth, parent.mDefaultWidth);
           break;
         case android.R.attr.keyHeight:
           defaultHeightCode = getKeyHeightCode(a, remoteIndex, parent.mDefaultHeightCode);
           break;
         case android.R.attr.horizontalGap:
           defaultHorizontalGap =
               getDimensionOrFraction(
                   a, remoteIndex, parent.mDisplayWidth, parent.mDefaultHorizontalGap);
           break;
       }
     } catch (Exception e) {
       Log.w(TAG, "Failed to set data from XML!", e);
     }
   }
   a.recycle();
   int[] remoteKeyboardRowLayoutStyleable = parent.remoteKeyboardRowLayoutStyleable;
   a = res.obtainAttributes(Xml.asAttributeSet(parser), remoteKeyboardRowLayoutStyleable);
   n = a.getIndexCount();
   for (int i = 0; i < n; i++) {
     final int remoteIndex = a.getIndex(i);
     final int localAttrId = attributeIdMap.get(remoteKeyboardRowLayoutStyleable[remoteIndex]);
     try {
       switch (localAttrId) {
         case android.R.attr.rowEdgeFlags:
           rowEdgeFlags = a.getInt(remoteIndex, 0);
           break;
         case android.R.attr.keyboardMode:
           mode = a.getResourceId(remoteIndex, 0);
           break;
       }
     } catch (Exception e) {
       Log.w(TAG, "Failed to set data from XML!", e);
     }
   }
   a.recycle();
 }
Ejemplo n.º 4
0
  /**
   * Execute this {@link HttpUriRequest}, passing a valid response through {@link
   * XmlHandler#parseAndApply(XmlPullParser, ContentResolver)}.
   */
  private static void execute(
      HttpUriRequest request, HttpClient httpClient, ContentHandler handler, boolean isZipFile)
      throws SAXException {
    try {
      final HttpResponse resp = httpClient.execute(request);
      final int status = resp.getStatusLine().getStatusCode();
      if (status != HttpStatus.SC_OK) {
        throw new SAXException(
            "Unexpected server response "
                + resp.getStatusLine()
                + " for "
                + request.getRequestLine());
      }

      final InputStream input = resp.getEntity().getContent();
      if (isZipFile) {
        // We downloaded the compressed file from TheTVDB
        final ZipInputStream zipin = new ZipInputStream(input);
        zipin.getNextEntry();
        try {
          Xml.parse(zipin, Xml.Encoding.UTF_8, handler);
        } catch (SAXException e) {
          throw new SAXException("Malformed response for " + request.getRequestLine(), e);
        } catch (IOException ioe) {
          throw new SAXException(
              "Problem reading remote response for " + request.getRequestLine(), ioe);
        } finally {
          if (zipin != null) {
            zipin.close();
          }
        }
      } else {
        try {
          Xml.parse(input, Xml.Encoding.UTF_8, handler);
        } catch (SAXException e) {
          throw new SAXException("Malformed response for " + request.getRequestLine(), e);
        } catch (IOException ioe) {
          throw new SAXException(
              "Problem reading remote response for " + request.getRequestLine(), ioe);
        } finally {
          if (input != null) {
            input.close();
          }
        }
      }
    } catch (AssertionError ae) {
      // looks like Xml.parse is throwing AssertionErrors instead of
      // IOExceptions
      throw new SAXException("Problem reading remote response for " + request.getRequestLine());
    } catch (Exception e) {
      throw new SAXException("Problem reading remote response for " + request.getRequestLine(), e);
    }
  }
 private Intent parseAlias(XmlPullParser xmlpullparser)
     throws XmlPullParserException, IOException
 {
     android.util.AttributeSet attributeset = Xml.asAttributeSet(xmlpullparser);
     Intent intent = null;
     int i;
     do
         i = xmlpullparser.next();
     while (i != 1 && i != 2);
     String s = xmlpullparser.getName();
     if (!"alias".equals(s))
         throw new RuntimeException((new StringBuilder()).append("Alias meta-data must start with <alias> tag; found").append(s).append(" at ").append(xmlpullparser.getPositionDescription()).toString());
     int j = xmlpullparser.getDepth();
     do
     {
         int k;
         do
         {
             k = xmlpullparser.next();
             if (k == 1 || k == 3 && xmlpullparser.getDepth() <= j)
                 return intent;
         } while (k == 3 || k == 4);
         if ("intent".equals(xmlpullparser.getName()))
         {
             Intent intent1 = Intent.parseIntent(getResources(), xmlpullparser, attributeset);
             if (intent == null)
                 intent = intent1;
         } else
         {
             XmlUtils.skipCurrentTag(xmlpullparser);
         }
     } while (true);
 }
  public static String createXMLSensorRecordInfo(List<String> fields) {
    XmlSerializer serializer = Xml.newSerializer();
    StringWriter writer = new StringWriter();

    try {
      serializer.setOutput(writer);
      serializer.startDocument("UTF-8", false);

      final String nns = null; // no namespace
      final String ns = "urn:schemas-upnp-org:smgt:srecinfo";

      serializer.setPrefix("xsi", "http://www.w3.org/2001/XMLSchema-instance");
      serializer.setPrefix("", ns);
      serializer.startTag(ns, XMLSENSORRECORDINFO);
      serializer.attribute(
          "http://www.w3.org/2001/XMLSchema-instance",
          "schemaLocation",
          "urn:schemas-upnp-org:smgt:srecinfo http://www.upnp.org/schemas/ds/drecs-v1.xsd");

      serializer.startTag(nns, XMLSENSORRECORD);
      for (String field : fields) {

        serializer.startTag(nns, XMLFIELD);
        serializer.attribute(nns, XMLNAME, field);
        serializer.endTag(nns, XMLFIELD);
      }
      serializer.endTag(nns, XMLSENSORRECORD);
      serializer.endTag(ns, XMLSENSORRECORDINFO);
      serializer.endDocument();
      return writer.toString();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Ejemplo n.º 7
0
 private void parseKeyStyle(final XmlPullParser parser, final boolean skip)
     throws XmlPullParserException, IOException {
   final AttributeSet attr = Xml.asAttributeSet(parser);
   final TypedArray keyStyleAttr =
       mResources.obtainAttributes(attr, R.styleable.Keyboard_KeyStyle);
   final TypedArray keyAttrs = mResources.obtainAttributes(attr, R.styleable.Keyboard_Key);
   try {
     if (!keyStyleAttr.hasValue(R.styleable.Keyboard_KeyStyle_styleName)) {
       throw new XmlParseUtils.ParseException(
           "<" + TAG_KEY_STYLE + "/> needs styleName attribute", parser);
     }
     if (DEBUG) {
       startEndTag(
           "<%s styleName=%s />%s",
           TAG_KEY_STYLE,
           keyStyleAttr.getString(R.styleable.Keyboard_KeyStyle_styleName),
           skip ? " skipped" : "");
     }
     if (!skip) {
       mParams.mKeyStyles.parseKeyStyleAttributes(keyStyleAttr, keyAttrs, parser);
     }
   } finally {
     keyStyleAttr.recycle();
     keyAttrs.recycle();
   }
   XmlParseUtils.checkEndTag(TAG_KEY_STYLE, parser);
 }
  public String WriteXmlString(List<Employee> employees) throws IOException {

    String Tag_employees = "employees";
    String Tag_employee = "employee";
    String Tag_id = "id";
    String Tag_name = "name";
    String Tag_department = "department";
    String Tag_type = "type";
    String Tag_email = "email";

    // order of Tags: employees , employee, id, name, department, email

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

    xmlSerializer.setOutput(stringWriter);

    // start Document
    xmlSerializer.startDocument("UTF-8", true);
    // tag: employees
    xmlSerializer.startTag("", Tag_employees);

    for (int i = 0; i < employees.size(); i++) {

      // tag: employee
      xmlSerializer.startTag("", Tag_employee);

      // tag: id
      xmlSerializer.startTag("", Tag_id);
      xmlSerializer.text(Integer.toString(employees.get(i).getId()));
      xmlSerializer.endTag("", Tag_id);

      // tag: name
      xmlSerializer.startTag("", Tag_name);
      xmlSerializer.text(employees.get(i).getName());
      xmlSerializer.endTag("", Tag_name);

      // tag: department
      xmlSerializer.startTag("", Tag_department);
      xmlSerializer.text(employees.get(i).getDepartment());
      xmlSerializer.endTag("", Tag_department);

      // tag: type
      xmlSerializer.startTag("", Tag_type);
      xmlSerializer.text(employees.get(i).getType());
      xmlSerializer.endTag("", Tag_type);

      // tag: email
      xmlSerializer.startTag("", Tag_email);
      xmlSerializer.text(employees.get(i).getEmail());
      xmlSerializer.endTag("", Tag_email);

      xmlSerializer.endTag("", Tag_employee);
    }

    // end Document
    xmlSerializer.endDocument();

    return stringWriter.toString();
  }
Ejemplo n.º 9
0
  public Map<String, String> decodeXml(String content) {

    try {
      Map<String, String> xml = new HashMap<String, String>();
      XmlPullParser parser = Xml.newPullParser();
      parser.setInput(new StringReader(content));
      int event = parser.getEventType();
      while (event != XmlPullParser.END_DOCUMENT) {

        String nodeName = parser.getName();
        switch (event) {
          case XmlPullParser.START_DOCUMENT:
            break;
          case XmlPullParser.START_TAG:
            if ("xml".equals(nodeName) == false) {
              // 实例化student对象
              xml.put(nodeName, parser.nextText());
            }
            break;
          case XmlPullParser.END_TAG:
            break;
        }
        event = parser.next();
      }

      return xml;
    } catch (Exception e) {
      Log.e("orion", e.toString());
    }
    return null;
  }
Ejemplo n.º 10
0
  public static UpdataInfo getUpdataInfo(InputStream is) throws Exception {

    XmlPullParser parser = Xml.newPullParser();

    parser.setInput(is, "utf-8");

    int type = parser.getEventType();

    UpdataInfo info = new UpdataInfo();

    while (type != XmlPullParser.END_DOCUMENT) {

      switch (type) {
        case XmlPullParser.START_TAG:
          if ("version".equals(parser.getName())) {

            info.setVersion(parser.nextText());

          } else if ("url".equals(parser.getName())) {

            info.setUrl(parser.nextText());

          } else if ("description".equals(parser.getName())) {

            info.setDescription(parser.nextText());
          }

          break;
      }

      type = parser.next();
    }

    return info;
  }
Ejemplo n.º 11
0
  public String createNewUserXML(
      String login,
      String firstName,
      String lastName,
      String email,
      String timezone,
      boolean admin,
      String password)
      throws IllegalArgumentException, IllegalStateException, IOException {

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

    serializer.startDocument("UTF-8", null);
    serializer.startTag("", "user");

    addLogin(login);
    addFirstName(firstName);
    addLastName(lastName);
    addEmail(email);
    addTimezone(timezone);
    addAdmin(admin ? "1" : "");
    addPassword(password);

    serializer.endTag("", "user");
    serializer.endDocument();
    return writer.toString();
  }
Ejemplo n.º 12
0
  private void openIfRequired() throws IOException {
    String state = Environment.getExternalStorageState();
    if (mSerializer == null) {
      String fileName = mReportFile;
      if (mMultiFile) {
        fileName = fileName.replace("$(suite)", "test");
      }
      if (mReportDir == null) {
        if (Environment.MEDIA_MOUNTED.equals(state)
            && !Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
          File f = mContext.getExternalFilesDir("testng");
          mOutputStream = new FileOutputStream(new File(f, fileName));
        } else {
          mOutputStream = mTargetContext.openFileOutput(fileName, 0);
        }
      } else {
        mOutputStream = new FileOutputStream(new File(mReportDir, fileName));
      }

      mSerializer = Xml.newSerializer();
      mSerializer.setOutput(mOutputStream, ENCODING_UTF_8);
      mSerializer.startDocument(ENCODING_UTF_8, true);
      if (!mMultiFile) {
        mSerializer.startTag("", TAG_SUITES);
      }
    }
  }
Ejemplo n.º 13
0
 /**
  * 将服务器返回的错误XML串,转化成RenrenError.
  *
  * @param JSON�? * @return
  */
 private static RenrenError parseXml(String xmlResponse) {
   XmlPullParser parser = Xml.newPullParser();
   RenrenError error = null;
   try {
     parser.setInput(new StringReader(xmlResponse));
     int evtCode = parser.getEventType();
     int errorCode = -1;
     String errorMsg = null;
     while (evtCode != XmlPullParser.END_DOCUMENT) {
       switch (evtCode) {
         case XmlPullParser.START_TAG:
           if ("error_code".equals(parser.getName())) {
             errorCode = Integer.parseInt(parser.nextText());
           }
           if ("error_msg".equals(parser.getName())) {
             errorMsg = parser.nextText();
           }
           break;
       }
       if (errorCode > -1 && errorMsg != null) {
         error = new RenrenError(errorCode, errorMsg, xmlResponse);
         break;
       }
       evtCode = parser.next();
     }
   } catch (Exception e) {
     throw new RuntimeException(e.getMessage(), e);
   }
   return error;
 }
Ejemplo n.º 14
0
    @Override
    protected String doInBackground(OsmPoint... points) {
      FileOutputStream out = null;
      try {
        out = new FileOutputStream(osmchange);
        XmlSerializer sz = Xml.newSerializer();

        sz.setOutput(out, "UTF-8");
        sz.startDocument("UTF-8", true);
        sz.startTag("", "osmChange");
        sz.attribute("", "generator", "OsmAnd");
        sz.attribute("", "version", "0.6");
        sz.startTag("", "create");
        writeContent(sz, points, OsmPoint.Action.CREATE);
        sz.endTag("", "create");
        sz.startTag("", "modify");
        writeContent(sz, points, OsmPoint.Action.MODIFY);
        sz.endTag("", "modify");
        sz.startTag("", "delete");
        writeContent(sz, points, OsmPoint.Action.DELETE);
        sz.endTag("", "delete");
        sz.endTag("", "osmChange");
        sz.endDocument();
      } catch (Exception e) {
        return e.getMessage();
      } finally {
        try {
          if (out != null) out.close();
        } catch (IOException e) {
        }
      }

      return null;
    }
Ejemplo n.º 15
0
	public static String XMLContent(List<Book> books, Writer writer)
	{
		XmlSerializer serializer = Xml.newSerializer();
		try {
			serializer.setOutput(writer);
			serializer.startDocument("UTF-8", true);
			serializer.startTag("", "books");
			for (Book book : books) {
				serializer.startTag("", "book");
				serializer.attribute("", "id", String.valueOf(book.getId()));
				serializer.startTag("", "name");
				serializer.text(book.getName());
				serializer.endTag("", "name");
				serializer.startTag("", "price");
				serializer.text(String.valueOf(book.getPrice()));
				serializer.endTag("", "price");
				serializer.endTag("", "book");
			}
			serializer.endTag("", "books");
			serializer.endDocument();
			return writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
Ejemplo n.º 16
0
  /**
   * Takes a list of feeds and a writer and writes those into an OPML document.
   *
   * @throws IOException
   * @throws IllegalStateException
   * @throws IllegalArgumentException
   */
  public void writeDocument(List<Feed> feeds, Writer writer)
      throws IllegalArgumentException, IllegalStateException, IOException {
    if (AppConfig.DEBUG) Log.d(TAG, "Starting to write document");
    XmlSerializer xs = Xml.newSerializer();
    xs.setOutput(writer);

    xs.startDocument(ENCODING, false);
    xs.startTag(null, OpmlSymbols.OPML);
    xs.attribute(null, OpmlSymbols.VERSION, OPML_VERSION);

    xs.startTag(null, OpmlSymbols.HEAD);
    xs.startTag(null, OpmlSymbols.TITLE);
    xs.text(OPML_TITLE);
    xs.endTag(null, OpmlSymbols.TITLE);
    xs.endTag(null, OpmlSymbols.HEAD);

    xs.startTag(null, OpmlSymbols.BODY);
    for (Feed feed : feeds) {
      xs.startTag(null, OpmlSymbols.OUTLINE);
      xs.attribute(null, OpmlSymbols.TEXT, feed.getTitle());
      if (feed.getType() != null) {
        xs.attribute(null, OpmlSymbols.TYPE, feed.getType());
      }
      xs.attribute(null, OpmlSymbols.XMLURL, feed.getDownload_url());
      if (feed.getLink() != null) {
        xs.attribute(null, OpmlSymbols.HTMLURL, feed.getLink());
      }
      xs.endTag(null, OpmlSymbols.OUTLINE);
    }
    xs.endTag(null, OpmlSymbols.BODY);
    xs.endTag(null, OpmlSymbols.OPML);
    xs.endDocument();
    if (AppConfig.DEBUG) Log.d(TAG, "Finished writing document");
  }
Ejemplo n.º 17
0
  private String serialize(Element e, int intent) {

    try {

      XmlSerializer s = Xml.newSerializer();
      StringWriter sw = new StringWriter();

      s.setOutput(sw);
      s.startDocument("utf-8", null);

      String spaces = null;
      if (intent > 0) {
        char[] chars = new char[intent];
        Arrays.fill(chars, ' ');
        spaces = new String(chars);
      }

      serialize(root, s, 0, spaces);
      s.endDocument();

      return sw.toString();
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    return null;
  }
Ejemplo n.º 18
0
  public String createModifyServerXML(Server server)
      throws IllegalArgumentException, IllegalStateException, IOException {
    serializer = Xml.newSerializer();
    writer = new StringWriter();
    serializer.setOutput(writer);

    serializer.startDocument("UTF-8", null);
    serializer.startTag("", "release_server");

    // TODO refactor for better performance
    addName(server.getName());
    addLocalPath(server.getLocalPath());
    addRemotePath(server.getRemotePath());
    addRemoteAddr(server.getRemoteAddr());
    addProtocol(server.getProtocol());
    addPort(server.getPort());
    addLogin(server.getLogin());
    addPassword(server.getPassword());
    addUseActiveMode(server.isUseActiveMode());
    addAuthenticateByKey(server.isAuthenticateByKey());
    addUseFeat(server.isUseFeat());
    addPreReleaseHook(server.getPreReleaseHook());
    addPostReleaseHook(server.getPostReleaseHook());

    serializer.endTag("", "release_server");
    serializer.endDocument();
    return writer.toString();
  }
  public static AnimatedVectorDrawable create(Context c, Resources resources, int rid) {
    try {
      final XmlPullParser parser = resources.getXml(rid);
      final AttributeSet attrs = Xml.asAttributeSet(parser);
      int type;
      while ((type = parser.next()) != XmlPullParser.START_TAG
          && type != XmlPullParser.END_DOCUMENT) {
        // Empty loop
      }
      if (type != XmlPullParser.START_TAG) {
        throw new XmlPullParserException("No start tag found");
      } else if (!ANIMATED_VECTOR.equals(parser.getName())) {
        throw new IllegalArgumentException("root node must start with: " + ANIMATED_VECTOR);
      }

      final AnimatedVectorDrawable drawable = new AnimatedVectorDrawable();
      drawable.inflate(c, resources, parser, attrs, null);

      return drawable;
    } catch (XmlPullParserException e) {
      Log.e(LOGTAG, "parser error", e);
    } catch (IOException e) {
      Log.e(LOGTAG, "parser error", e);
    }
    return null;
  }
Ejemplo n.º 20
0
 public void readStateLocked() {
   if (!PERSISTENCE_MANAGER_ENABLED) {
     return;
   }
   FileInputStream in = null;
   try {
     in = mStatePersistFile.openRead();
   } catch (FileNotFoundException e) {
     Log.i(LOG_TAG, "No existing print spooler state.");
     return;
   }
   try {
     XmlPullParser parser = Xml.newPullParser();
     parser.setInput(in, null);
     parseState(parser);
   } catch (IllegalStateException ise) {
     Slog.w(LOG_TAG, "Failed parsing ", ise);
   } catch (NullPointerException npe) {
     Slog.w(LOG_TAG, "Failed parsing ", npe);
   } catch (NumberFormatException nfe) {
     Slog.w(LOG_TAG, "Failed parsing ", nfe);
   } catch (XmlPullParserException xppe) {
     Slog.w(LOG_TAG, "Failed parsing ", xppe);
   } catch (IOException ioe) {
     Slog.w(LOG_TAG, "Failed parsing ", ioe);
   } catch (IndexOutOfBoundsException iobe) {
     Slog.w(LOG_TAG, "Failed parsing ", iobe);
   } finally {
     IoUtils.closeQuietly(in);
   }
 }
Ejemplo n.º 21
0
 /**
  * Read a HashMap from an InputStream containing XML. The stream can previously have been written
  * by writeMapXml().
  *
  * @param in The InputStream from which to read.
  * @return HashMap The resulting map.
  * @see #readListXml
  * @see #readValueXml
  * @see #readThisMapXml #see #writeMapXml
  */
 @SuppressWarnings("unchecked")
 public static HashMap<String, ?> readMapXml(InputStream in)
     throws XmlPullParserException, java.io.IOException {
   XmlPullParser parser = Xml.newPullParser();
   parser.setInput(in, null);
   return (HashMap<String, ?>) readValueXml(parser, new String[1]);
 }
Ejemplo n.º 22
0
  protected String getEnrolmentBodyXml(SIP5060ProvisioningRequest req) {

    SharedPreferences settings =
        getSharedPreferences(RegisterAccount.PREFS_FILE, Context.MODE_PRIVATE);

    String enrolmentNum = settings.getString(RegisterAccount.PREF_PHONE_NUMBER, "");

    XmlSerializer serializer = Xml.newSerializer();
    StringWriter writer = new StringWriter();
    try {
      serializer.setOutput(writer);
      serializer.startDocument("UTF-8", true);
      String ns = RegistrationUtil.NS;
      serializer.startTag(ns, "enrolment");

      RegistrationUtil.serializeProperty(serializer, ns, "phoneNumber", enrolmentNum);
      RegistrationUtil.serializeProperty(serializer, ns, "secret", req.getAuthPassword());
      RegistrationUtil.serializeProperty(serializer, ns, "firstName", "");
      RegistrationUtil.serializeProperty(serializer, ns, "lastName", "");
      RegistrationUtil.serializeProperty(serializer, ns, "emailAddress", "");
      RegistrationUtil.serializeProperty(serializer, ns, "language", getLanguage());

      serializer.endTag(ns, "enrolment");
      serializer.endDocument();
      return writer.toString();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
 @SuppressWarnings("unchecked")
 public synchronized T inflate(XmlPullParser parser, P root, boolean attachToRoot) {
   final AttributeSet attrs = Xml.asAttributeSet(parser);
   T result = (T) root;
   try {
     int type;
     while ((type = parser.next()) != XmlPullParser.START_TAG
         && type != XmlPullParser.END_DOCUMENT) {;
     }
     if (type != XmlPullParser.START_TAG) {
       throw new InflateException(parser.getPositionDescription() + ": No start tag found!");
     }
     T xmlRoot = createItemFromTag(parser, parser.getName(), attrs);
     result = (T) onMergeRoots(root, attachToRoot, (P) xmlRoot);
     rInflate(parser, result, attrs);
   } catch (InflateException e) {
     throw e;
   } catch (XmlPullParserException e) {
     InflateException ex = new InflateException(e.getMessage());
     ex.initCause(e);
     throw ex;
   } catch (IOException e) {
     InflateException ex =
         new InflateException(parser.getPositionDescription() + ": " + e.getMessage());
     ex.initCause(e);
     throw ex;
   }
   return result;
 }
Ejemplo n.º 24
0
  public String buildFormSubmissionXMLString(String formName, Long recordId) {
    try {
      Document document = getXMLModelTemplateForFormName(formName);

      XmlSerializer serializer = Xml.newSerializer();
      StringWriter writer = new StringWriter();
      serializer.setOutput(writer);
      serializer.startDocument("UTF-8", true);

      // <model><instance>
      Element el = (Element) document.getElementsByTagName("model").item(0).getFirstChild();
      NodeList entries = el.getChildNodes();
      int num = entries.getLength();
      for (int i = 0; i < num; i++) {
        Element node = (Element) entries.item(i);
        writeXML(node, serializer, recordId);
      }

      serializer.endDocument();

      String xml = writer.toString();
      // xml = xml.replaceAll("<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>","");//56
      // !!!this ain't working
      xml = xml.substring(56);
      System.out.println(xml);

      return xml;

    } catch (Exception e) {
      e.printStackTrace();
    }

    return "";
  }
Ejemplo n.º 25
0
  public void onClick1(View v) {
    try {
      String filename = "file.txt";

      FileOutputStream fos;
      fos = openFileOutput(filename, MODE_PRIVATE);

      XmlSerializer serializer = Xml.newSerializer();
      serializer.setOutput(fos, "UTF-8");
      serializer.startDocument(null, Boolean.valueOf(true));
      serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);

      serializer.startTag(null, "root");

      for (int j = 0; j < 3; j++) {

        serializer.startTag(null, "record");

        serializer.text(String.valueOf(j));

        serializer.endTag(null, "record");
      }
      serializer.endTag(null, "root");
      serializer.endDocument();

      serializer.flush();

      fos.close();

      // display file saved message
      Toast.makeText(getBaseContext(), "File xml saved successfully!", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public byte[] encode(int offset, int count) throws UnsupportedEncodingException {
    StringWriter sw = new StringWriter();
    XmlSerializer xmlMsgElement = Xml.newSerializer();
    int i, stopIndex;
    if (offset > subFolders.size())
      throw new IllegalArgumentException("FolderListingEncode: offset > subFolders.size()");

    stopIndex = offset + count;
    if (stopIndex > subFolders.size()) stopIndex = subFolders.size();

    try {
      xmlMsgElement.setOutput(sw);
      xmlMsgElement.startDocument(null, null);
      xmlMsgElement.text("\n");
      xmlMsgElement.startTag("", "folder-listing");
      xmlMsgElement.attribute("", "version", "1.0");
      for (i = offset; i < stopIndex; i++) {
        xmlMsgElement.startTag("", "folder");
        xmlMsgElement.attribute("", "name", subFolders.get(i).getName());
        xmlMsgElement.endTag("", "folder");
      }
      xmlMsgElement.endTag("", "folder-listing");
      xmlMsgElement.endDocument();
    } catch (IllegalArgumentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalStateException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return sw.toString().getBytes("UTF-8");
  }
Ejemplo n.º 27
0
  public static synchronized String createXMLContentPathList(List<String> paths) {
    XmlSerializer serializer = Xml.newSerializer();
    StringWriter writer = new StringWriter();

    try {
      serializer.setOutput(writer);
      serializer.startDocument("UTF-8", false);

      final String nns = null; // no namespace
      final String ns = "urn:schemas-upnp-org:dm:cms";

      serializer.setPrefix("xsi", "http://www.w3.org/2001/XMLSchema-instance");
      serializer.setPrefix("cms", ns);

      serializer.startTag(ns, XMLCONTENTPATHLIST);
      serializer.attribute(
          "http://www.w3.org/2001/XMLSchema-instance",
          "schemaLocation",
          "urn:schemas-upnp-org:dm:cms http://www.upnp.org/schemas/dm/cms.xsd");

      for (String path : paths) {
        serializer.startTag(nns, XMLCONTENTPATH);
        serializer.text(path);
        serializer.endTag(nns, XMLCONTENTPATH);
      }

      serializer.endTag(ns, XMLCONTENTPATHLIST);

      serializer.endDocument();
      return writer.toString();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  /**
   * Parses the conference event package XML file and returns an {@link
   * com.android.ims.ImsConferenceState} instance containing the participants described in the XML
   * file.
   *
   * @return The {@link com.android.ims.ImsConferenceState} instance.
   */
  public ImsConferenceState parse() {
    ImsConferenceState conferenceState = new ImsConferenceState();

    XmlPullParser parser;
    try {
      parser = Xml.newPullParser();
      parser.setInput(mInputStream, null);
      parser.nextTag();

      int outerDepth = parser.getDepth();
      while (XmlUtils.nextElementWithin(parser, outerDepth)) {
        if (parser.getName().equals(PARTICIPANT_TAG)) {
          Log.v(LOG_TAG, "Found participant.");
          Bundle participant = parseParticipant(parser);
          conferenceState.mParticipants.put(
              participant.getString(ImsConferenceState.ENDPOINT), participant);
        }
      }
    } catch (IOException | XmlPullParserException e) {
      Log.e(LOG_TAG, "Failed to read test conference event package from XML file", e);
      return null;
    } finally {
      try {
        mInputStream.close();
      } catch (IOException e) {
        Log.e(LOG_TAG, "Failed to close test conference event package InputStream", e);
        return null;
      }
    }

    return conferenceState;
  }
Ejemplo n.º 29
0
  private void doTasksExport(String output) throws IOException {
    File xmlFile = new File(output);
    xmlFile.createNewFile();
    FileOutputStream fos = new FileOutputStream(xmlFile);
    xml = Xml.newSerializer();
    xml.setOutput(fos, BackupConstants.XML_ENCODING);

    xml.startDocument(null, null);
    xml.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);

    xml.startTag(null, BackupConstants.ASTRID_TAG);
    xml.attribute(
        null,
        BackupConstants.ASTRID_ATTR_VERSION,
        Integer.toString(preferences.getLastSetVersion()));
    xml.attribute(null, BackupConstants.ASTRID_ATTR_FORMAT, Integer.toString(FORMAT));

    serializeTasks();
    serializeTagDatas();

    xml.endTag(null, BackupConstants.ASTRID_TAG);
    xml.endDocument();
    xml.flush();
    fos.close();
  }
Ejemplo n.º 30
0
  public void testCompletedTasksAreCompletedWhenParsed() {
    XmlPullParser xmlParser = Xml.newPullParser();

    try {
      xmlParser.setInput(
          new StringReader(
              "<todo>"
                  + "<completed-at type=\"datetime\" nil=\"true\"/>"
                  + "<context-id type=\"integer\">3711</context-id>"
                  + "<created-at type=\"datetime\">2009-10-26T22:23:42+01:00</created-at>"
                  + "<description>Läs getting things done igen</description>"
                  + "<due type=\"datetime\" nil=\"true\"/>"
                  + "<id type=\"integer\">25076</id>"
                  + "<ip-address>90.232.35.15</ip-address>"
                  + "<notes>Primärt kring idéer och projekt</notes>"
                  + "<project-id type=\"integer\">4558</project-id>"
                  + "<recurring-todo-id type=\"integer\" nil=\"true\"/>"
                  + "<show-from type=\"datetime\" nil=\"true\"/>"
                  + "<state>completed</state>"
                  + "<updated-at type=\"datetime\">2010-02-03T10:37:19+01:00</updated-at>"
                  + "</todo>"));
    } catch (XmlPullParserException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    TaskParser parser = CreateSUT();
    Task task = parser.parseSingle(xmlParser).getResult();
    assertEquals("completed date isn't parsed correctly", true, task.isComplete());
  }