Example usage for org.xml.sax.helpers AttributesImpl addAttribute

List of usage examples for org.xml.sax.helpers AttributesImpl addAttribute

Introduction

In this page you can find the example usage for org.xml.sax.helpers AttributesImpl addAttribute.

Prototype

public void addAttribute(String uri, String localName, String qName, String type, String value) 

Source Link

Document

Add an attribute to the end of the list.

Usage

From source file:com.adobe.acs.commons.rewriter.impl.VersionedClientlibsTransformerFactoryTest.java

@Test
public void testJavaScriptClientLibraryWithDot() throws Exception {
    final String path = PATH + ".foo";

    when(htmlLibraryManager.getLibrary(eq(LibraryType.JS), eq(path))).thenReturn(htmlLibrary);
    when(htmlLibrary.getLibraryPath()).thenReturn(path);

    final AttributesImpl in = new AttributesImpl();
    in.addAttribute("", "src", "", "CDATA", path + ".js");
    in.addAttribute("", "type", "", "CDATA", "text/javascript");

    transformer.startElement(null, "script", null, in);

    ArgumentCaptor<Attributes> attributesCaptor = ArgumentCaptor.forClass(Attributes.class);

    verify(handler, only()).startElement(isNull(String.class), eq("script"), isNull(String.class),
            attributesCaptor.capture());

    assertEquals(path + "." + FAKE_STREAM_CHECKSUM + ".js", attributesCaptor.getValue().getValue(0));
}

From source file:com.adobe.acs.commons.rewriter.impl.VersionedClientlibsTransformerFactoryTest.java

@Test
public void testCssClientLibraryWithDot() throws Exception {
    final String path = PATH + ".foo";

    when(htmlLibraryManager.getLibrary(eq(LibraryType.CSS), eq(path))).thenReturn(htmlLibrary);
    when(htmlLibrary.getLibraryPath()).thenReturn(path);

    final AttributesImpl in = new AttributesImpl();
    in.addAttribute("", "href", "", "CDATA", path + ".css");
    in.addAttribute("", "type", "", "CDATA", "text/css");
    in.addAttribute("", "rel", "", "CDATA", "stylesheet");

    transformer.startElement(null, "link", null, in);

    ArgumentCaptor<Attributes> attributesCaptor = ArgumentCaptor.forClass(Attributes.class);

    verify(handler, only()).startElement(isNull(String.class), eq("link"), isNull(String.class),
            attributesCaptor.capture());

    assertEquals(path + "." + FAKE_STREAM_CHECKSUM + ".css", attributesCaptor.getValue().getValue(0));
}

From source file:com.adobe.acs.commons.rewriter.impl.VersionedClientlibsTransformerFactoryTest.java

@Test
public void testMinifiedCssClientLibraryWithEnforceMd5() throws Exception {
    PrivateAccessor.setField(factory, "enforceMd5", true);

    when(htmlLibraryManager.getLibrary(eq(LibraryType.CSS), eq(PATH))).thenReturn(htmlLibrary);

    final AttributesImpl in = new AttributesImpl();
    in.addAttribute("", "href", "", "CDATA", PATH + ".min.css");
    in.addAttribute("", "type", "", "CDATA", "text/css");
    in.addAttribute("", "rel", "", "CDATA", "stylesheet");

    transformer.startElement(null, "link", null, in);

    ArgumentCaptor<Attributes> attributesCaptor = ArgumentCaptor.forClass(Attributes.class);

    verify(handler, only()).startElement(isNull(String.class), eq("link"), isNull(String.class),
            attributesCaptor.capture());

    assertEquals(PATH + ".min.ACSHASH" + FAKE_STREAM_CHECKSUM + ".css",
            attributesCaptor.getValue().getValue(0));
}

From source file:com.ibm.xsp.webdav.DavXMLResponse.java

/**
 * Starts a new XML document and inserts the correct starting tag with name
 * spaces//from  w w w.  ja  v  a  2 s . c o  m
 * 
 * @param tagName
 */
private void startNewResponseBody(String tagName) {

    // this.out = new ByteArrayOutputStream();
    this.out = new StringWriter();

    if (this.out != null) {
        this.streamResult = new StreamResult(out);
        this.body = this.getSAXOutputObject(streamResult);

        try {
            // Start the document
            this.body.startDocument();

            // Stylesheet if we have one and we are on extended results
            if (this.xmlStyleSheet != null && this.extendedResult) {
                this.body.processingInstruction("xml-stylesheet",
                        "type=\"text/xsl\" href=\"" + this.xmlStyleSheet + "\"");
            }

            // First tag with correct namespaces
            AttributesImpl attr = new AttributesImpl();
            String nsShort = DAV_PREFIX.substring(0, (DAV_PREFIX.length() - 1));
            String auxShort = AUX_PREFIX.substring(0, (AUX_PREFIX.length() - 1));
            attr.addAttribute("", nsShort, "xmlns:" + nsShort, "String", DAV_NAMESPACE);
            if (this.extendedResult) {
                attr.addAttribute("", auxShort, "xmlns:" + auxShort, "String", AUX_NAMESPACE);
            }
            this.body.startElement("", tagName, DAV_PREFIX + tagName, attr);
            this.xmlTagStack.push(tagName);
            this.rootElementWritten = true; // We memorize that

            // If there are defered commends process them
            if (this.deferedComments != null) {
                for (String curComment : this.deferedComments) {
                    this.addComment(curComment);
                }
            }

        } catch (SAXException e) {
            LOGGER.error(e);
        }

    } else {
        LOGGER.error("Can't start an XML body for the response");
    }

}

From source file:nl.architolk.ldt.processors.HttpClientProcessor.java

public void generateData(PipelineContext context, ContentHandler contentHandler) throws SAXException {

    try {/*from  w w  w. j  a va 2 s  .co m*/
        CloseableHttpClient httpclient = HttpClientProperties.createHttpClient();

        try {
            // Read content of config pipe
            Document configDocument = readInputAsDOM4J(context, INPUT_CONFIG);
            Node configNode = configDocument.selectSingleNode("//config");

            URL theURL = new URL(configNode.valueOf("url"));

            if (configNode.valueOf("auth-method").equals("basic")) {
                HttpHost targetHost = new HttpHost(theURL.getHost(), theURL.getPort(), theURL.getProtocol());
                //Authentication support
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                        configNode.valueOf("username"), configNode.valueOf("password")));
                // logger.info("Credentials: "+configNode.valueOf("username")+"/"+configNode.valueOf("password"));
                // Create AuthCache instance
                AuthCache authCache = new BasicAuthCache();
                authCache.put(targetHost, new BasicScheme());

                // Add AuthCache to the execution context
                httpContext = HttpClientContext.create();
                httpContext.setCredentialsProvider(credsProvider);
                httpContext.setAuthCache(authCache);
            } else if (configNode.valueOf("auth-method").equals("form")) {
                //Sign in. Cookie will be remembered bij httpclient
                HttpPost authpost = new HttpPost(configNode.valueOf("auth-url"));
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("userName", configNode.valueOf("username")));
                nameValuePairs.add(new BasicNameValuePair("password", configNode.valueOf("password")));
                authpost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                CloseableHttpResponse httpResponse = httpclient.execute(authpost);
                // logger.info("Signin response:"+Integer.toString(httpResponse.getStatusLine().getStatusCode()));
            }

            CloseableHttpResponse response;
            if (configNode.valueOf("method").equals("post")) {
                // POST
                HttpPost httpRequest = new HttpPost(configNode.valueOf("url"));
                setBody(httpRequest, context, configNode);
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("put")) {
                // PUT
                HttpPut httpRequest = new HttpPut(configNode.valueOf("url"));
                setBody(httpRequest, context, configNode);
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("delete")) {
                //DELETE
                HttpDelete httpRequest = new HttpDelete(configNode.valueOf("url"));
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("head")) {
                //HEAD
                HttpHead httpRequest = new HttpHead(configNode.valueOf("url"));
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("options")) {
                //OPTIONS
                HttpOptions httpRequest = new HttpOptions(configNode.valueOf("url"));
                response = executeRequest(httpRequest, httpclient);
            } else {
                //Default = GET
                HttpGet httpRequest = new HttpGet(configNode.valueOf("url"));
                String acceptHeader = configNode.valueOf("accept");
                if (!acceptHeader.isEmpty()) {
                    httpRequest.addHeader("accept", configNode.valueOf("accept"));
                }
                //Add proxy route if needed
                HttpClientProperties.setProxy(httpRequest, theURL.getHost());
                response = executeRequest(httpRequest, httpclient);
            }

            try {
                contentHandler.startDocument();

                int status = response.getStatusLine().getStatusCode();
                AttributesImpl statusAttr = new AttributesImpl();
                statusAttr.addAttribute("", "status", "status", "CDATA", Integer.toString(status));
                contentHandler.startElement("", "response", "response", statusAttr);
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    Header contentType = response.getFirstHeader("Content-Type");
                    if (entity != null && contentType != null) {
                        //logger.info("Contenttype: " + contentType.getValue());
                        //Read content into inputstream
                        InputStream inStream = entity.getContent();

                        // output-type = json means: response is json, convert to xml
                        if (configNode.valueOf("output-type").equals("json")) {
                            //TODO: net.sf.json.JSONObject might nog be the correct JSONObject. javax.json.JsonObject might be better!!!
                            //javax.json contains readers to read from an inputstream
                            StringWriter writer = new StringWriter();
                            IOUtils.copy(inStream, writer, "UTF-8");
                            JSONObject json = JSONObject.fromObject(writer.toString());
                            parseJSONObject(contentHandler, json);
                            // output-type = xml means: response is xml, keep it
                        } else if (configNode.valueOf("output-type").equals("xml")) {
                            try {
                                XMLReader saxParser = XMLParsing
                                        .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false));
                                saxParser.setContentHandler(new ParseHandler(contentHandler));
                                saxParser.parse(new InputSource(inStream));
                            } catch (Exception e) {
                                throw new OXFException(e);
                            }
                            // output-type = jsonld means: reponse is json-ld, (a) convert to nquads; (b) convert to xml
                        } else if (configNode.valueOf("output-type").equals("jsonld")) {
                            try {
                                Object jsonObject = JsonUtils.fromInputStream(inStream, "UTF-8"); //TODO: UTF-8 should be read from response!
                                Object nquads = JsonLdProcessor.toRDF(jsonObject, new NQuadTripleCallback());

                                Any23 runner = new Any23();
                                DocumentSource source = new StringDocumentSource((String) nquads,
                                        configNode.valueOf("url"));
                                ByteArrayOutputStream out = new ByteArrayOutputStream();
                                TripleHandler handler = new RDFXMLWriter(out);
                                try {
                                    runner.extract(source, handler);
                                } finally {
                                    handler.close();
                                }
                                ByteArrayInputStream inJsonStream = new ByteArrayInputStream(out.toByteArray());
                                XMLReader saxParser = XMLParsing
                                        .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false));
                                saxParser.setContentHandler(new ParseHandler(contentHandler));
                                saxParser.parse(new InputSource(inJsonStream));
                            } catch (Exception e) {
                                throw new OXFException(e);
                            }
                            // output-type = rdf means: response is some kind of rdf (except json-ld...), convert to xml
                        } else if (configNode.valueOf("output-type").equals("rdf")) {
                            try {
                                Any23 runner = new Any23();

                                DocumentSource source;
                                //If contentType = text/html than convert from html to xhtml to handle non-xml style html!
                                logger.info("Contenttype: " + contentType.getValue());
                                if (configNode.valueOf("tidy").equals("yes")
                                        && contentType.getValue().startsWith("text/html")) {
                                    org.jsoup.nodes.Document doc = Jsoup.parse(inStream, "UTF-8",
                                            configNode.valueOf("url")); //TODO UTF-8 should be read from response!

                                    RDFCleaner cleaner = new RDFCleaner();
                                    org.jsoup.nodes.Document cleandoc = cleaner.clean(doc);
                                    cleandoc.outputSettings().escapeMode(Entities.EscapeMode.xhtml);
                                    cleandoc.outputSettings()
                                            .syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml);
                                    cleandoc.outputSettings().charset("UTF-8");

                                    source = new StringDocumentSource(cleandoc.html(),
                                            configNode.valueOf("url"), contentType.getValue());
                                } else {
                                    source = new ByteArrayDocumentSource(inStream, configNode.valueOf("url"),
                                            contentType.getValue());
                                }

                                ByteArrayOutputStream out = new ByteArrayOutputStream();
                                TripleHandler handler = new RDFXMLWriter(out);
                                try {
                                    runner.extract(source, handler);
                                } finally {
                                    handler.close();
                                }
                                ByteArrayInputStream inAnyStream = new ByteArrayInputStream(out.toByteArray());
                                XMLReader saxParser = XMLParsing
                                        .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false));
                                saxParser.setContentHandler(new ParseHandler(contentHandler));
                                saxParser.parse(new InputSource(inAnyStream));

                            } catch (Exception e) {
                                throw new OXFException(e);
                            }
                        } else {
                            CharArrayWriter writer = new CharArrayWriter();
                            IOUtils.copy(inStream, writer, "UTF-8");
                            contentHandler.characters(writer.toCharArray(), 0, writer.size());
                        }
                    }
                }
                contentHandler.endElement("", "response", "response");

                contentHandler.endDocument();
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    } catch (Exception e) {
        throw new OXFException(e);
    }

}

From source file:com.jkoolcloud.tnt4j.streams.configure.sax.ConfigParserHandlerTest.java

@Test
public void locatorSplitingEmptyElementTest() throws Exception {
    ConfigParserHandler test = Mockito.mock(ConfigParserHandler.class, Mockito.CALLS_REAL_METHODS);
    test.startDocument();/*from   w  w w . j a  va 2s.  c om*/
    AttributesImpl attrs = new AttributesImpl();
    attrs.addAttribute("", "", "name", "", "Stream attr name"); // NON-NLS
    attrs.addAttribute("", "", "locator", "", "|555"); // NON-NLS
    attrs.addAttribute("", "", "value", "", ""); // NON-NLS
    attrs.addAttribute("", "", "class", "", "com.jkoolcloud.tnt4j.streams.parsers.ActivityTokenParser"); // NON-NLS
    test.startElement("TEST_URL", "TEST_LOCALNAME", "parser", attrs); // NON-NLS
    test.startElement("TEST_URL", "TEST_LOCALNAME", "field", attrs); // NON-NLS
}

From source file:com.jkoolcloud.tnt4j.streams.configure.sax.ConfigParserHandlerTest.java

@Test(expected = SAXParseException.class)
public void processFieldLocatorExceptionTest() throws Exception {
    ConfigParserHandler test = Mockito.mock(ConfigParserHandler.class, Mockito.CALLS_REAL_METHODS);
    test.startDocument();//from   w w  w .ja  v  a 2s  . co  m
    AttributesImpl attrs = new AttributesImpl();
    attrs.addAttribute("", "", "name", "", "Stream attr name"); // NON-NLS
    attrs.addAttribute("", "", "class", "", "com.jkoolcloud.tnt4j.streams.parsers.ActivityTokenParser"); // NON-NLS
    attrs.addAttribute("", "", "datatype", "", "DateTime"); // NON-NLS
    attrs.addAttribute("", "", "format", "", null);
    test.startElement("TEST_URL", "TEST_LOCALNAME", "parser", attrs); // NON-NLS//NON-NLS
    test.startElement("TEST_URL", "TEST_LOCALNAME", "field", attrs); // NON-NLS
    attrs.addAttribute("", "", "value", "", ""); // NON-NLS
    test.startElement("TEST_URL", "TEST_LOCALNAME", "field-locator", attrs); // NON-NLS
}

From source file:com.jkoolcloud.tnt4j.streams.configure.sax.ConfigParserHandlerTest.java

@Test
public void processFieldLocatorNotNullFromatTest() throws Exception {
    ConfigParserHandler test = Mockito.mock(ConfigParserHandler.class, Mockito.CALLS_REAL_METHODS);
    test.startDocument();//  w w  w .ja va2  s .c  o  m
    AttributesImpl attrs = new AttributesImpl();
    attrs.addAttribute("", "", "name", "", "Stream attr name");// NON-NLS
    attrs.addAttribute("", "", "class", "", "com.jkoolcloud.tnt4j.streams.parsers.ActivityTokenParser"); // NON-NLS
    attrs.addAttribute("", "", "datatype", "", "DateTime"); // NON-NLS
    attrs.addAttribute("", "", "format", "", "YYYY-mm-dd"); // NON-NLS
    test.startElement("TEST_URL", "TEST_LOCALNAME", "parser", attrs); // NON-NLS
    test.startElement("TEST_URL", "TEST_LOCALNAME", "field", attrs); // NON-NLS
    attrs.addAttribute("", "", "value", "", null); // NON-NLS
    test.startElement("TEST_URL", "TEST_LOCALNAME", "field-locator", attrs); // NON-NLS
}

From source file:com.jkoolcloud.tnt4j.streams.configure.sax.ConfigParserHandlerTest.java

@Test(expected = SAXParseException.class)
public void processFieldMapSourceExceptionTest() throws Exception {
    ConfigParserHandler test = Mockito.mock(ConfigParserHandler.class, Mockito.CALLS_REAL_METHODS);
    test.startDocument();/*  ww  w. jav a  2  s  .c  o m*/
    AttributesImpl attrs = new AttributesImpl();
    attrs.addAttribute("", "", "name", "", "Stream attr name"); // NON-NLS
    attrs.addAttribute("", "", "source", "", null); // NON-NLS
    attrs.addAttribute("", "", "target", "", "Stream target value"); // NON-NLS
    attrs.addAttribute("", "", "value", "", ""); // NON-NLS
    attrs.addAttribute("", "", "class", "", "com.jkoolcloud.tnt4j.streams.parsers.ActivityTokenParser"); // NON-NLS
    test.startElement("TEST_URL", "TEST_LOCALNAME", "parser", attrs); // NON-NLS
    test.startElement("TEST_URL", "TEST_LOCALNAME", "field", attrs); // NON-NLS
    test.startElement("TEST_URL", "TEST_LOCALNAME", "field-map", attrs); // NON-NLS
}

From source file:com.jkoolcloud.tnt4j.streams.configure.sax.ConfigParserHandlerTest.java

@Test(expected = SAXParseException.class)
public void processFieldMapTargetExceptionTest() throws Exception {
    ConfigParserHandler test = Mockito.mock(ConfigParserHandler.class, Mockito.CALLS_REAL_METHODS);
    test.startDocument();//from   w w w .  j a va 2s  . c  o m
    AttributesImpl attrs = new AttributesImpl();
    attrs.addAttribute("", "", "name", "", "Stream attr name"); // NON-NLS
    attrs.addAttribute("", "", "source", "", "Stream source value"); // NON-NLS
    attrs.addAttribute("", "", "target", "", null); // NON-NLS
    attrs.addAttribute("", "", "value", "", ""); // NON-NLS
    attrs.addAttribute("", "", "class", "", "com.jkoolcloud.tnt4j.streams.parsers.ActivityTokenParser"); // NON-NLS
    test.startElement("TEST_URL", "TEST_LOCALNAME", "parser", attrs); // NON-NLS
    test.startElement("TEST_URL", "TEST_LOCALNAME", "field", attrs); // NON-NLS
    test.startElement("TEST_URL", "TEST_LOCALNAME", "field-map", attrs); // NON-NLS
}