Example usage for org.xml.sax Attributes getValue

List of usage examples for org.xml.sax Attributes getValue

Introduction

In this page you can find the example usage for org.xml.sax Attributes getValue.

Prototype

public abstract String getValue(String qName);

Source Link

Document

Look up an attribute's value by XML qualified (prefixed) name.

Usage

From source file:Main.java

public static String attributesToString(Attributes attributes) {

    // (use StringBuffer for J2SE 1.4 compatibility)

    StringBuffer buffer = new StringBuffer();

    for (int loop = 0, length = attributes.getLength(); loop < length; loop++) {
        buffer.append(" ");
        buffer.append(attributes.getLocalName(loop));
        buffer.append("=\"");
        buffer.append(attributes.getValue(loop));
        buffer.append("\"");
    }/* w  w  w .  j a v  a 2  s. c o m*/

    return buffer.toString();

}

From source file:jcurl.core.io.SetupSaxDeSer.java

private static DimVal getDim(final Attributes atts) {
    final String val = atts.getValue("val");
    final Dim dim = Dim.find(atts.getValue("dim"));
    return new DimVal(Double.parseDouble(val), dim);
}

From source file:Main.java

public static String serializeOpenTag(String nsUri, String qname, Map<String, String> nsMappings,
        Attributes attrs, boolean optimizeNs) {
    String result = "<" + qname;
    if (nsUri != null && nsUri.length() > 0) {
        int idx = Math.max(qname.indexOf(':'), 0);
        nsMappings.put(qname.substring(0, idx), nsUri);
    }// w w w. j a  va  2 s.  co m
    for (int i = 0; i < attrs.getLength(); i++) {
        result += " " + attrs.getQName(i) + "=\"" + attrs.getValue(i) + "\"";
    }
    for (String key : nsMappings.keySet()) {
        if (optimizeNs) {
            boolean found = key.isEmpty() && qname.indexOf(':') == -1
                    || key.length() > 0 && qname.startsWith(key + ":");
            for (int i = 0; i < attrs.getLength(); i++) {
                String aqn = attrs.getQName(i);
                if (aqn.startsWith("xml")) {
                    continue;
                }
                if (key.isEmpty() && aqn.indexOf(':') == -1 || key.length() > 0 && aqn.startsWith(key + ":")) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                continue;
            }
        }

        if (key.isEmpty()) {
            String value = nsMappings.get(key);
            result += " xmlns=\"" + value + "\"";
        } else {
            result += " xmlns:" + key + "=\"" + nsMappings.get(key) + "\"";
        }
    }
    result += ">";
    return result;
}

From source file:Main.java

/**
 * Convert a XML starting tag to a String
 *//*  ww w .  j av a  2 s .  c  o  m*/
static String convertStartTagToString(String p_localName, Attributes p_attrs) {
    StringBuffer output = new StringBuffer(START_TAG_STRING_BUFFER_LENGTH);

    output.append("<");
    output.append(p_localName);

    if (p_attrs != null) {
        int size = p_attrs.getLength();
        for (int i = 0; i < size; i++) {
            output.append(" ");
            output.append(p_attrs.getQName(i));
            output.append("=\"");
            output.append(p_attrs.getValue(i));
            output.append("\"");
        }
    }

    output.append(">");

    return output.toString();
}

From source file:com.microsoft.tfs.core.clients.workitem.internal.form.WIFormParseHandler.java

public static String readStringValue(final Attributes attributes, final String attributeName) {
    for (int i = 0; i < attributes.getLength(); i++) {
        final String name = attributes.getQName(i);
        if (name != null && name.equalsIgnoreCase(attributeName)) {
            return attributes.getValue(i);
        }//from www.  j ava  2  s .  c  o m
    }

    return null;
}

From source file:no.kantega.commons.util.XMLHelper.java

public static AttributesImpl getAttributesImpl(Attributes attributes) {
    AttributesImpl impl = new AttributesImpl();

    for (int i = 0; i < attributes.getLength(); i++) {
        impl.addAttribute(attributes.getURI(i), attributes.getLocalName(i), attributes.getQName(i),
                attributes.getType(i), attributes.getValue(i));
    }/*from ww  w . j  a v a 2  s.  c  o m*/
    return impl;
}

From source file:com.sap.prd.mobile.ios.mios.VersionInfoManager.java

private static String getSchemaVersion(final File f) throws SAXException, IOException {

    class StopParsingException extends SAXException {
        private static final long serialVersionUID = -7499102356648608429L;
    }/*from   w ww .j a v a  2 s .c  o  m*/
    ;

    XMLReader xmlReader = XMLReaderFactory.createXMLReader();

    final InputStream s = new FileInputStream(f);

    final String[] result = new String[1];

    try {

        xmlReader.setContentHandler(new ContentHandler() {

            boolean repositoryTagFound = false;

            @Override
            public void startPrefixMapping(String prefix, String uri) throws SAXException {
            }

            @Override
            public void startElement(String uri, String localName, String qName, Attributes atts)
                    throws SAXException {
                if (localName.equals("versions")) {
                    result[0] = atts.getValue("schemaVersion");

                    if (result[0] != null)
                        throw new StopParsingException();
                }

                if (localName.equals("repository")) {
                    repositoryTagFound = true;
                }
            }

            @Override
            public void startDocument() throws SAXException {
            }

            @Override
            public void skippedEntity(String name) throws SAXException {
            }

            @Override
            public void setDocumentLocator(Locator locator) {
            }

            @Override
            public void processingInstruction(String target, String data) throws SAXException {
            }

            @Override
            public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
            }

            @Override
            public void endPrefixMapping(String prefix) throws SAXException {
            }

            @Override
            public void endElement(String uri, String localName, String qName) throws SAXException {
            }

            @Override
            public void endDocument() throws SAXException {
                if (!repositoryTagFound && result[0] == null)
                    result[0] = "1.2.0";
            }

            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
            }
        });

        try {
            xmlReader.parse(new InputSource(s));
        } catch (StopParsingException ex) {
            //OK, StopParsingException is thrown when we know all we need from the document.
        }
    } finally {
        IOUtils.closeQuietly(s);
    }
    return result[0];
}

From source file:cn.fql.utility.ClassUtility.java

/**
 * Import value to object according specified  <code>org.xml.sax.Attributes</code>
 *
 * @param obj  specified object instance
 * @param atts <code>org.xml.sax.Attributes</code>
 */// ww w .  j a v a  2  s.c o m
public static void importValueFromAttribute(Object obj, org.xml.sax.Attributes atts) {
    if (atts != null) {
        PropertyDescriptor[] pds;
        try {
            pds = exportPropertyDesc(obj.getClass());
            if (pds != null && pds.length > 0) {
                for (int i = 0; i < pds.length; i++) {
                    PropertyDescriptor pd = pds[i];
                    String strValue = atts.getValue(pd.getName());
                    if (strValue != null) {
                        Method setter = pd.getWriteMethod();
                        if (setter != null) {
                            Object value = ConvertUtils.convert(strValue, pd.getPropertyType());
                            Object[] params = { value };
                            setter.invoke(obj, params);
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

From source file:com.abstratt.mdd.core.util.MDDUtil.java

public static boolean isGenerated(java.net.URI uri) {
    if (cachedParserFactory == null) {
        cachedParserFactory = SAXParserFactory.newInstance();
    }//ww  w.  ja va2  s. c o  m
    SAXParser xmlParser;
    try {
        xmlParser = cachedParserFactory.newSAXParser();
    } catch (ParserConfigurationException e) {
        if (Platform.inDebugMode())
            LogUtils.logError(MDDCore.PLUGIN_ID, "Error creating XML parser", e);
        return false;
    } catch (SAXException e) {
        if (Platform.inDebugMode())
            LogUtils.logError(MDDCore.PLUGIN_ID, "Error creating XML parser", e);
        return false;
    }
    final boolean[] generated = { false };
    final boolean[] aborted = { false };
    InputStream stream = null;
    try {
        stream = new BufferedInputStream(uri.toURL().openStream());
        xmlParser.parse(stream, new DefaultHandler() {
            private boolean skipping = true;

            @Override
            public void startElement(String uri, String localName, String name, Attributes attributes)
                    throws SAXException {
                if (name.equalsIgnoreCase("eAnnotations"))
                    if (GENERATED.equals(attributes.getValue("source"))) {
                        generated[0] = true;
                        aborted[0] = true;
                        throw new SAXParseException("", null);
                    } else
                        return;
                if (!skipping) {
                    // should have seen the annotation by now
                    aborted[0] = true;
                    throw new SAXParseException("", null);
                }
                if (name.startsWith("uml"))
                    skipping = false;
            }
        });
    } catch (SAXException e) {
        if (!aborted[0] && Platform.inDebugMode())
            LogUtils.logError(MDDCore.PLUGIN_ID, "Error parsing " + uri, e);
    } catch (IOException e) {
        if (Platform.inDebugMode())
            LogUtils.logError(MDDCore.PLUGIN_ID, "Error parsing " + uri, e);
    } finally {
        if (stream != null)
            try {
                stream.close();
            } catch (IOException e) {
                // no biggie
            }
    }
    return generated[0];
}

From source file:com.taobao.android.tpatch.utils.SmaliUtils.java

/**
 * dex?smali/*from www  .j a  v  a 2  s .c  o  m*/
 * @param dex
 * @param outputDir
 * @param includeClasses ??
 */
public static boolean disassembleDexFile(File dex, File outputDir, final Set<String> includeClasses)
        throws IOException {
    final baksmaliOptions options = createBaksmaliOptions();
    if (!outputDir.exists()) {
        outputDir.mkdirs();
    }
    DexFile dexFile = DexFileFactory.loadDexFile(dex, DEFAULT_API_LEVEL, true);
    options.outputDirectory = outputDir.getAbsolutePath();
    //1. 
    options.jobs = 3;
    if (options.registerInfo != 0 || options.deodex) {
        try {
            Iterable<String> extraClassPathEntries;
            if (options.extraClassPathEntries != null) {
                extraClassPathEntries = options.extraClassPathEntries;
            } else {
                extraClassPathEntries = ImmutableList.of();
            }

            options.classPath = ClassPath.fromClassPath(options.bootClassPathDirs,
                    Iterables.concat(options.bootClassPathEntries, extraClassPathEntries), dexFile,
                    options.apiLevel, options.checkPackagePrivateAccess, options.experimental);

            if (options.customInlineDefinitions != null) {
                options.inlineResolver = new CustomInlineMethodResolver(options.classPath,
                        options.customInlineDefinitions);
            }
        } catch (Exception ex) {
            System.err.println("\n\nError occurred while loading boot class path files. Aborting.");
            ex.printStackTrace(System.err);
            return false;
        }
    }

    if (options.resourceIdFileEntries != null) {
        class PublicHandler extends DefaultHandler {

            String prefix = null;

            public PublicHandler(String prefix) {
                super();
                this.prefix = prefix;
            }

            public void startElement(String uri, String localName, String qName, Attributes attr)
                    throws SAXException {
                if (qName.equals("public")) {
                    String type = attr.getValue("type");
                    String name = attr.getValue("name").replace('.', '_');
                    Integer public_key = Integer.decode(attr.getValue("id"));
                    String public_val = new StringBuffer().append(prefix).append(".").append(type).append(".")
                            .append(name).toString();
                    options.resourceIds.put(public_key, public_val);
                }
            }
        }
        ;

        for (Map.Entry<String, String> entry : options.resourceIdFileEntries.entrySet()) {
            try {
                SAXParser saxp = SAXParserFactory.newInstance().newSAXParser();
                String prefix = entry.getValue();
                saxp.parse(entry.getKey(), new PublicHandler(prefix));
            } catch (ParserConfigurationException e) {
                continue;
            } catch (SAXException e) {
                continue;
            } catch (IOException e) {
                continue;
            }
        }
    }

    File outputDirectoryFile = new File(options.outputDirectory);
    if (!outputDirectoryFile.exists()) {
        if (!outputDirectoryFile.mkdirs()) {
            System.err.println("Can't create the output directory " + options.outputDirectory);
            return false;
        }
    }

    // sort the classes, so that if we're on a case-insensitive file system and need to handle classes with file
    // name collisions, then we'll use the same name for each class, if the dex file goes through multiple
    // baksmali/smali cycles for some reason. If a class with a colliding name is added or removed, the filenames
    // may still change of course
    List<? extends ClassDef> classDefs = Ordering.natural().sortedCopy(dexFile.getClasses());

    if (!options.noAccessorComments) {
        options.syntheticAccessorResolver = new SyntheticAccessorResolver(classDefs);
    }

    final ClassFileNameHandler fileNameHandler = new ClassFileNameHandler(outputDirectoryFile, ".smali");

    ExecutorService executor = Executors.newFixedThreadPool(options.jobs);
    List<Future<Boolean>> tasks = Lists.newArrayList();

    for (final ClassDef classDef : classDefs) {
        tasks.add(executor.submit(new Callable<Boolean>() {

            @Override
            public Boolean call() throws Exception {
                String className = getDalvikClassName(classDef.getType());
                if (null != includeClasses) {
                    if (includeClasses.contains(className)) {
                        BakSmali.disassembleClass(classDef, fileNameHandler, options);
                    }
                    return true;
                } else {
                    return BakSmali.disassembleClass(classDef, fileNameHandler, options);
                }
            }
        }));
    }

    boolean errorOccurred = false;
    try {
        for (Future<Boolean> task : tasks) {
            while (true) {
                try {
                    if (!task.get()) {
                        errorOccurred = true;
                    }
                } catch (InterruptedException ex) {
                    continue;
                } catch (ExecutionException ex) {
                    throw new RuntimeException(ex);
                }
                break;
            }
        }
    } finally {
        executor.shutdown();
    }
    return !errorOccurred;
}