Java Code Examples for org.kxml2.io.KXmlParser

The following examples show how to use org.kxml2.io.KXmlParser. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@VisibleForTesting
static boolean hasLayoutParams(@NonNull Reader reader)
        throws XmlPullParserException, IOException {
    KXmlParser parser = new KXmlParser();
    parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
    parser.setInput(reader);

    while (true) {
        int event = parser.next();
        if (event == XmlPullParser.START_TAG) {
            for (int i = 0; i < parser.getAttributeCount(); i++) {
                if (parser.getAttributeName(i).startsWith(ATTR_LAYOUT_RESOURCE_PREFIX)) {
                    String prefix = parser.getAttributePrefix(i);
                    if (prefix != null && !prefix.isEmpty() &&
                            ANDROID_URI.equals(parser.getNamespace(prefix))) {
                        return true;
                    }
                }
            }

            return false;
        } else if (event == XmlPullParser.END_DOCUMENT) {
            return false;
        }
    }
}
 
Example 2
public static ParseResult parse(InputStream is)
    throws XmlPullParserException, IOException, Exception {
  XmlPullParser p = new KXmlParser();
  p.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
  p.setInput(new InputStreamReader(is));
  ParseResult rs = null;

  for (int  e = p.getEventType();
            e != XmlPullParser.END_DOCUMENT;
            e = p.next()) {
    if (e == XmlPullParser.START_TAG && "repository".equals(p.getName())) {
      rs = parseRepository(p);
    }
  }
  return rs;
}
 
Example 3
public SoapObject GetSoapObject(Element detailElement) {
	try {
		XmlSerializer xmlSerializer = XmlPullParserFactory.newInstance().newSerializer();
		StringWriter writer = new StringWriter();
		xmlSerializer.setOutput(writer);
		detailElement.write(xmlSerializer);
		xmlSerializer.flush();

		XmlPullParser xpp = new KXmlParser();
		xpp.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);

		xpp.setInput(new StringReader(writer.toString()));
		xpp.nextTag();
		SoapObject soapObj = new SoapObject(detailElement.getNamespace(), detailElement.getName());
		readSerializable(xpp, soapObj);
		return soapObj;
	} catch (Exception ex) {
		ex.printStackTrace();
	}
	return null;
}
 
Example 4
Source Project: commcare-android   Source File: FormUploadUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static String parseProcessingFailureResponse(InputStream responseStream)
        throws IOException, InvalidStructureException, UnfullfilledRequirementsException,
        XmlPullParserException {

    KXmlParser baseParser = ElementParser.instantiateParser(responseStream);
    ElementParser<String> responseParser = new ElementParser<String>(baseParser) {
        @Override
        public String parse() throws InvalidStructureException, IOException,
                XmlPullParserException, UnfullfilledRequirementsException {
            checkNode("OpenRosaResponse");
            nextTag("message");
            String natureOfResponse = parser.getAttributeValue(null, "nature");
            if ("processing_failure".equals(natureOfResponse)) {
                return parser.nextText();
            } else {
                throw new UnfullfilledRequirementsException(
                        "<message> for 422 response did not contain expected content");
            }
        }
    };
    return responseParser.parse();
}
 
Example 5
Source Project: commcare-android   Source File: FormRecordProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private boolean attemptXmlScan(FormRecord r, File recordFile, StringBuilder reporter) {
    KXmlParser parser = new KXmlParser();
    InputStream is = null;
    try {
        Cipher decrypter = FormUploadUtil.getDecryptCipher((new SecretKeySpec(r.getAesKey(), "AES")));
        is = new CipherInputStream(new FileInputStream(recordFile), decrypter);

        parser.setInput(is, "UTF-8");
        parser.setFeature(KXmlParser.FEATURE_PROCESS_NAMESPACES, true);
        while (parser.next() != KXmlParser.END_DOCUMENT) {
            //nothing
        }
        reporter.append("PASS: Instance file reads as valid XML\n");
        return true;
    } catch (Exception e) {
        reporter.append("FAILURE: XML Instance file could not be validated\n").append(ForceCloseLogger.getStackTrace(e));
        return false;
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException ioe) {
        }
    }
}
 
Example 6
/**
 * Used to load Saved Forms from HQ into our local file system
 *
 * @param namespaces A mapping from an installed form's namespace its install path.
 */

public void initFormInstanceParser(Hashtable<String, String> namespaces) {
    this.formInstanceNamespaces = namespaces;

    formInstanceParser = new TransactionParserFactory() {
        FormInstanceXmlParser created = null;

        @Override
        public TransactionParser getParser(KXmlParser parser) {
            if (created == null) {
                //TODO: We really don't wanna keep using fsPath eventually
                created = new FormInstanceXmlParser(parser,
                        Collections.unmodifiableMap(formInstanceNamespaces),
                        CommCareApplication.instance().getCurrentApp().fsPath(GlobalConstants.FILE_CC_FORMS));
            }

            return created;
        }
    };
}
 
Example 7
@Override
public TransactionParserFactory getNormalCaseParser() {
    return new TransactionParserFactory() {
        AndroidCaseXmlParser created = null;

        @Override
        public AndroidCaseXmlParser getParser(KXmlParser parser) {
            if (created == null) {
                created = new AndroidCaseXmlParser(parser, true, sandbox.getCaseStorage(), generator) {

                    @Override
                    public void onIndexDisrupted(String caseId) {
                        caseIndexesWereDisrupted = true;
                    }

                    @Override
                    protected void onCaseCreateUpdate(String caseId) {
                        createdAndUpdatedCases.add(caseId);
                    }
                };
            }

            return created;
        }
    };
}
 
Example 8
@Override
public TransactionParserFactory getBulkCaseParser() {
    return new TransactionParserFactory() {
        AndroidBulkCaseXmlParser created = null;

        @Override
        public AndroidBulkCaseXmlParser getParser(KXmlParser parser) {
            if (created == null) {
                created = new AndroidBulkCaseXmlParser(parser, (SqlStorage<ACase>)sandbox.getCaseStorage()) {

                    @Override
                    public void onIndexDisrupted(String caseId) {
                        caseIndexesWereDisrupted = true;
                    }

                    @Override
                    protected void onCaseCreateUpdate(String caseId) {
                        createdAndUpdatedCases.add(caseId);
                    }
                };
            }

            return created;
        }
    };
}
 
Example 9
Source Project: commcare-android   Source File: AvailableAppsParser.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<AppAvailableToInstall> parse() throws InvalidStructureException, IOException,
        XmlPullParserException, UnfullfilledRequirementsException {
    checkNode(APPS_TAG);
    List<AppAvailableToInstall> appsList = new ArrayList<>();

    parser.next();
    int eventType = parser.getEventType();
    do {
        if (eventType == KXmlParser.START_TAG) {
            String tagName = parser.getName().toLowerCase();
            if (APP_TAG.equals(tagName)) {
                String domain = parser.getAttributeValue(null, DOMAIN_TAG);
                String appName = parser.getAttributeValue(null, APP_NAME_TAG);
                String profileRef = parser.getAttributeValue(null, PROFILE_REF_TAG);
                String mediaProfileRef = parser.getAttributeValue(null, MEDIA_PROFILE_REF_TAG);
                appsList.add(new AppAvailableToInstall(domain, appName, profileRef, mediaProfileRef));
            }
        }
        eventType = parser.next();
    } while (eventType != KXmlParser.END_DOCUMENT);

    commit(appsList);
    return appsList;
}
 
Example 10
Source Project: android_9.0.0_r45   Source File: Xml.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new pull parser with namespace support.
 */
public static XmlPullParser newPullParser() {
    try {
        KXmlParser parser = new KXmlParser();
        parser.setFeature(XmlPullParser.FEATURE_PROCESS_DOCDECL, true);
        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
        return parser;
    } catch (XmlPullParserException e) {
        throw new AssertionError();
    }
}
 
Example 11
private boolean parse(String path, KXmlParser parser)
        throws XmlPullParserException, IOException {
    boolean checkForErrors = !mIsFramework && !mContext.needsFullAapt();

    while (true) {
        int event = parser.next();
        if (event == XmlPullParser.START_TAG) {
            for (int i = 0, n = parser.getAttributeCount(); i < n; i++) {
                String attribute = parser.getAttributeName(i);
                String value = parser.getAttributeValue(i);
                assert value != null : attribute;

                if (checkForErrors) {
                    String uri = parser.getAttributeNamespace(i);
                    if (!mContext.checkValue(uri, attribute, value)) {
                        mContext.requestFullAapt();
                        return false;
                    }
                }
            }
        } else if (event == XmlPullParser.END_DOCUMENT) {
            break;
        }
    }

    return true;
}
 
Example 12
Source Project: java-n-IDE-for-Android   Source File: IdResourceParser.java    License: Apache License 2.0 5 votes vote down vote up
private boolean parse(ResourceType type, String path, KXmlParser parser)
        throws XmlPullParserException, IOException {
    boolean valid = true;
    boolean checkForErrors = !mIsFramework && !mContext.needsFullAapt();

    while (true) {
        int event = parser.next();
        if (event == XmlPullParser.START_TAG) {
            for (int i = 0, n = parser.getAttributeCount(); i < n; i++) {
                String attribute = parser.getAttributeName(i);
                String value = parser.getAttributeValue(i);
                assert value != null : attribute;

                if (checkForErrors) {
                    String uri = parser.getAttributeNamespace(i);
                    if (!mContext.checkValue(uri, attribute, value)) {
                        mContext.requestFullAapt();
                        checkForErrors = false;
                        valid = false;
                    }
                }

                if (value.startsWith("@+")) {       //$NON-NLS-1$
                    // Strip out the @+id/ or @+android:id/ section
                    String id = value.substring(value.indexOf('/') + 1);
                    ResourceValue newId = new ResourceValue(ResourceType.ID, id,
                            mIsFramework);
                    mRepository.addResourceValue(newId);
                }
            }
        } else if (event == XmlPullParser.END_DOCUMENT) {
            break;
        }
    }

    return valid;
}
 
Example 13
private boolean parse(String path, KXmlParser parser)
        throws XmlPullParserException, IOException {
    boolean checkForErrors = !mIsFramework && !mContext.needsFullAapt();

    while (true) {
        int event = parser.next();
        if (event == XmlPullParser.START_TAG) {
            for (int i = 0, n = parser.getAttributeCount(); i < n; i++) {
                String attribute = parser.getAttributeName(i);
                String value = parser.getAttributeValue(i);
                assert value != null : attribute;

                if (checkForErrors) {
                    String uri = parser.getAttributeNamespace(i);
                    if (!mContext.checkValue(uri, attribute, value)) {
                        mContext.requestFullAapt();
                        return false;
                    }
                }
            }
        } else if (event == XmlPullParser.END_DOCUMENT) {
            break;
        }
    }

    return true;
}
 
Example 14
Source Project: javaide   Source File: IdResourceParser.java    License: GNU General Public License v3.0 5 votes vote down vote up
private boolean parse(ResourceType type, String path, KXmlParser parser)
        throws XmlPullParserException, IOException {
    boolean valid = true;
    boolean checkForErrors = !mIsFramework && !mContext.needsFullAapt();

    while (true) {
        int event = parser.next();
        if (event == XmlPullParser.START_TAG) {
            for (int i = 0, n = parser.getAttributeCount(); i < n; i++) {
                String attribute = parser.getAttributeName(i);
                String value = parser.getAttributeValue(i);
                assert value != null : attribute;

                if (checkForErrors) {
                    String uri = parser.getAttributeNamespace(i);
                    if (!mContext.checkValue(uri, attribute, value)) {
                        mContext.requestFullAapt();
                        checkForErrors = false;
                        valid = false;
                    }
                }

                if (value.startsWith("@+")) {       //$NON-NLS-1$
                    // Strip out the @+id/ or @+android:id/ section
                    String id = value.substring(value.indexOf('/') + 1);
                    ResourceValue newId = new ResourceValue(ResourceType.ID, id,
                            mIsFramework);
                    mRepository.addResourceValue(newId);
                }
            }
        } else if (event == XmlPullParser.END_DOCUMENT) {
            break;
        }
    }

    return valid;
}
 
Example 15
Source Project: NBANDROID-V2   Source File: ValidatingResourceParser.java    License: Apache License 2.0 5 votes vote down vote up
private boolean parse(String path, KXmlParser parser)
        throws XmlPullParserException, IOException {
    boolean checkForErrors = !mIsFramework && !mContext.needsFullAapt();

    while (true) {
        int event = parser.next();
        if (event == XmlPullParser.START_TAG) {
            for (int i = 0, n = parser.getAttributeCount(); i < n; i++) {
                String attribute = parser.getAttributeName(i);
                String value = parser.getAttributeValue(i);
                assert value != null : attribute;

                if (checkForErrors) {
                    String uri = parser.getAttributeNamespace(i);
                    if (!mContext.checkValue(uri, attribute, value)) {
                        mContext.requestFullAapt();
                        return false;
                    }
                }
            }
        } else if (event == XmlPullParser.END_DOCUMENT) {
            break;
        }
    }

    return true;
}
 
Example 16
Source Project: NBANDROID-V2   Source File: IdResourceParser.java    License: Apache License 2.0 5 votes vote down vote up
private boolean parse(ResourceType type, String path, KXmlParser parser)
        throws XmlPullParserException, IOException {
    boolean valid = true;
    boolean checkForErrors = !mIsFramework && !mContext.needsFullAapt();

    while (true) {
        int event = parser.next();
        if (event == XmlPullParser.START_TAG) {
            for (int i = 0, n = parser.getAttributeCount(); i < n; i++) {
                String attribute = parser.getAttributeName(i);
                String value = parser.getAttributeValue(i);
                assert value != null : attribute;

                if (checkForErrors) {
                    String uri = parser.getAttributeNamespace(i);
                    if (!mContext.checkValue(uri, attribute, value)) {
                        mContext.requestFullAapt();
                        checkForErrors = false;
                        valid = false;
                    }
                }

                if (value.startsWith("@+")) {       //$NON-NLS-1$
                    // Strip out the @+id/ or @+android:id/ section
                    String id = value.substring(value.indexOf('/') + 1);
                    ResourceValue newId =
                            new ResourceValueImpl(
                                    new ResourceReference(ResourceType.ID, id, mIsFramework),
                                    null);
                    mRepository.addResourceValue(newId);
                }
            }
        } else if (event == XmlPullParser.END_DOCUMENT) {
            break;
        }
    }

    return valid;
}
 
Example 17
Source Project: commcare-android   Source File: FormRecordCleanupTask.java    License: Apache License 2.0 5 votes vote down vote up
private static TransactionParser buildCaseParser(String namespace,
                                                 KXmlParser parser,
                                                 final String[] caseIDs) {
    //If we have a proper 2.0 namespace, good.
    if (CaseXmlParser.CASE_XML_NAMESPACE.equals(namespace)) {
        return new AndroidCaseXmlParser(parser, CommCareApplication.instance().getUserStorage(ACase.STORAGE_KEY, ACase.class)) {
            @Override
            public void commit(Case parsed) throws IOException {
                String incoming = parsed.getCaseId();
                if (incoming != null && !"".equals(incoming)) {
                    caseIDs[0] = incoming;
                }
            }

            @Override
            protected ACase retrieve(String entityId) {
                caseIDs[0] = entityId;
                ACase c = new ACase("", "");
                c.setCaseId(entityId);
                return c;
            }
        };
    } else {
        // Otherwise, this gets more tricky. Ideally we'd want to
        // skip this block for compatibility purposes, but we can
        // at least try to get a caseID (which is all we want)
        return new BestEffortBlockParser(parser, new String[]{"case_id"}) {
            @Override
            public void commit(Hashtable<String, String> values) {
                if (values.containsKey("case_id")) {
                    caseIDs[0] = values.get("case_id");
                }
            }
        };
    }
}
 
Example 18
Source Project: commcare-android   Source File: FormRecordCleanupTask.java    License: Apache License 2.0 5 votes vote down vote up
private static TransactionParser buildMetaParser(final String[] uuid,
                                                 final Date[] modified,
                                                 KXmlParser parser) {
    return new MetaDataXmlParser(parser) {
        @Override
        public void commit(String[] meta) throws IOException {
            if (meta[0] != null) {
                modified[0] = DateUtils.parseDateTime(meta[0]);
            }
            uuid[0] = meta[1];
        }
    };
}
 
Example 19
Source Project: commcare-android   Source File: AsyncRestoreHelper.java    License: Apache License 2.0 5 votes vote down vote up
private boolean parseProgressFromRetryResult(RemoteDataPullResponse response) {
    InputStream stream = null;
    try {
        stream = response.writeResponseToCache(syncTask.context).retrieveCache();
        KXmlParser parser = ElementParser.instantiateParser(stream);
        parser.next();
        int eventType = parser.getEventType();
        do {
            if (eventType == KXmlParser.START_TAG) {
                if (parser.getName().toLowerCase().equals("progress")) {
                    serverProgressCompletedSoFar = Integer.parseInt(
                            parser.getAttributeValue(null, "done"));
                    serverProgressTotal = Integer.parseInt(
                            parser.getAttributeValue(null, "total"));
                    return true;
                }
            }
            eventType = parser.next();
        } while (eventType != KXmlParser.END_DOCUMENT);
    } catch (IOException | XmlPullParserException e) {
        Logger.log(LogTypes.TYPE_USER,
                "Error while parsing progress values of retry result");
    } finally {
        StreamsUtil.closeStream(stream);
    }
    return false;
}
 
Example 20
Source Project: commcare-android   Source File: InstallFromListActivity.java    License: Apache License 2.0 5 votes vote down vote up
private void processResponseIntoAppsList(InputStream responseData) {
    try {
        KXmlParser baseParser = ElementParser.instantiateParser(responseData);
        List<AppAvailableToInstall> apps = (new AvailableAppsParser(baseParser)).parse();
        availableApps.addAll(apps);
    } catch (IOException | InvalidStructureException | XmlPullParserException | UnfullfilledRequirementsException e) {
        Logger.log(LogTypes.TYPE_RESOURCES, "Error encountered while parsing apps available for install");
    }
}
 
Example 21
@Override
public TransactionParser getParser(KXmlParser parser) {
    String namespace = parser.getNamespace();
    if (namespace != null && formInstanceNamespaces != null && formInstanceNamespaces.containsKey(namespace)) {
        req();
        return formInstanceParser.getParser(parser);
    }
    return super.getParser(parser);
}
 
Example 22
public void initUserParser(final byte[] wrappedKey) {
    userParser = new TransactionParserFactory() {
        AndroidUserXmlParser created = null;

        @Override
        public TransactionParser getParser(KXmlParser parser) {
            if (created == null) {
                created = new AndroidUserXmlParser(parser, sandbox.getUserStorage(), wrappedKey);
            }

            return created;
        }
    };
}
 
Example 23
Source Project: commcare-android   Source File: AndroidCaseXmlParser.java    License: Apache License 2.0 5 votes vote down vote up
public AndroidCaseXmlParser(KXmlParser parser, boolean acceptCreateOverwrites,
                            IStorageUtilityIndexed<Case> storage,
                            CommcareRequestEndpoints generator) {
    super(parser, acceptCreateOverwrites, storage);
    this.generator = generator;
    mEntityCache = new EntityStorageCache("case");
    mCaseIndexTable = new AndroidCaseIndexTable();
}
 
Example 24
Source Project: commcare-android   Source File: AndroidBulkCaseXmlParser.java    License: Apache License 2.0 5 votes vote down vote up
public AndroidBulkCaseXmlParser(KXmlParser parser,
                                SqlStorage<ACase> storage,
                                EntityStorageCache entityStorageCache,
                                AndroidCaseIndexTable indexTable) {
    super(parser);
    mEntityCache = entityStorageCache;
    mCaseIndexTable = indexTable;
    this.storage = storage;
}
 
Example 25
Source Project: commcare-android   Source File: FormInstanceXmlParser.java    License: Apache License 2.0 5 votes vote down vote up
public FormInstanceXmlParser(KXmlParser parser,
                             Map<String, String> namespaceToInstallPath,
                             String destination) {
    super(parser);
    this.namespaceToInstallPath = namespaceToInstallPath;
    this.rootInstanceDir = destination;
}
 
Example 26
Source Project: UltimateAndroid   Source File: SvgToPath.java    License: Apache License 2.0 5 votes vote down vote up
private static PathInfo parse(InputStream in, boolean ignoreDefs, float dpi)  {
    try {
        XmlPullParser xr = new KXmlParser();
        SvgToPath svgHandler = new SvgToPath(xr);
        svgHandler.setDpi(dpi);

        if (ignoreDefs) {
            xr.setInput(new InputStreamReader(in));
            svgHandler.processSvg();
        } else {
            CopyInputStream cin = new CopyInputStream(in);

            XmlPullParser ids = new KXmlParser();
            ids.setInput(new InputStreamReader(cin.getCopy()));
            IdHandler idHandler = new IdHandler(ids);
            idHandler.processIds();
            svgHandler.idXml = idHandler.idXml;

            xr.setInput(new InputStreamReader(cin.getCopy()));
            svgHandler.processSvg();
        }

        return svgHandler.pathInfo;
    } catch (Exception e) {
        Log.w(TAG, "Parse error: " + e);
        throw new RuntimeException(e);
    }
}
 
Example 27
Source Project: UltimateAndroid   Source File: SvgToPath.java    License: Apache License 2.0 5 votes vote down vote up
private static PathInfo parse(InputStream in, boolean ignoreDefs, float dpi)  {
    try {
        XmlPullParser xr = new KXmlParser();
        SvgToPath svgHandler = new SvgToPath(xr);
        svgHandler.setDpi(dpi);

        if (ignoreDefs) {
            xr.setInput(new InputStreamReader(in));
            svgHandler.processSvg();
        } else {
            CopyInputStream cin = new CopyInputStream(in);

            XmlPullParser ids = new KXmlParser();
            ids.setInput(new InputStreamReader(cin.getCopy()));
            IdHandler idHandler = new IdHandler(ids);
            idHandler.processIds();
            svgHandler.idXml = idHandler.idXml;

            xr.setInput(new InputStreamReader(cin.getCopy()));
            svgHandler.processSvg();
        }

        return svgHandler.pathInfo;
    } catch (Exception e) {
        Log.w(TAG, "Parse error: " + e);
        throw new RuntimeException(e);
    }
}
 
Example 28
Source Project: bletools   Source File: TestUtils.java    License: MIT License 5 votes vote down vote up
public static XmlPullParser createXmlPullParser(String resourceName) {
	try {
		InputStream inputStream = TestUtils.class.getClassLoader().getResourceAsStream(resourceName);
		KXmlParser parser = new KXmlParser();
		parser.setInput(inputStream, "utf8");
		return parser;
	}
	catch (XmlPullParserException e) {
		throw new RuntimeException(e);
	}
}
 
Example 29
Source Project: lams   Source File: KXml2Driver.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected XmlPullParser createParser() {
    return new KXmlParser();
}
 
Example 30
Source Project: lams   Source File: KXml2DomDriver.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected XmlPullParser createParser() {
    return new KXmlParser();
}