List of usage examples for org.xml.sax.helpers AttributesImpl AttributesImpl
public AttributesImpl()
From source file:net.javacrumbs.json2xml.JsonSaxAdapter.java
protected Attributes getTypeAttributes() { if (addTypeAttributes) { String currentTokenType = getCurrentTokenType(); if (currentTokenType != null) { AttributesImpl attributes = new AttributesImpl(); attributes.addAttribute("", "type", "type", "string", currentTokenType); return attributes; } else {/*from w w w.ja v a2 s . com*/ return EMPTY_ATTRIBUTES; } } else { return EMPTY_ATTRIBUTES; } }
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.jkoolcloud.tnt4j.streams.configure.sax.ConfigParserHandlerTest.java
@Test public void processFieldTest() throws Exception { ConfigParserHandler test = Mockito.mock(ConfigParserHandler.class, Mockito.CALLS_REAL_METHODS); test.startDocument();//w w w . j a v a2 s . c o m AttributesImpl attrs = new AttributesImpl(); attrs.addAttribute("", "", "name", "", "Stream attr name"); // NON-NLS attrs.addAttribute("", "", "radix", "", "555"); // NON-NLS attrs.addAttribute("", "", "required", "", "Requered"); // NON-NLS attrs.addAttribute("", "", "locator", "", ""); // NON-NLS attrs.addAttribute("", "", "value", "", "555"); // NON-NLS attrs.addAttribute("", "", "units", "", "Units"); // NON-NLS attrs.addAttribute("", "", "format", "", "YYYY-mm-dd HH:mm:ss"); // NON-NLS attrs.addAttribute("", "", "locale", "", "lt_LT"); // NON-NLS attrs.addAttribute("", "", "timezone", "", "Europe/Vilnius"); // 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.adobe.acs.commons.rewriter.impl.VersionedClientlibsTransformerFactoryTest.java
@Test public void testJavaScriptClientLibrary() throws Exception { when(htmlLibraryManager.getLibrary(eq(LibraryType.JS), eq(PATH))).thenReturn(htmlLibrary); 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.jkoolcloud.tnt4j.streams.configure.sax.ConfigParserHandlerTest.java
@Test(expected = SAXParseException.class) public void processFieldExceptionTest() throws Exception { ConfigParserHandler test = Mockito.mock(ConfigParserHandler.class, Mockito.CALLS_REAL_METHODS); AttributesImpl attrs = new AttributesImpl(); test.startElement("TEST_URL", "TEST_LOCALNAME", "field", attrs); // NON-NLS }
From source file:nl.architolk.ldt.processors.HttpClientProcessor.java
public void generateData(PipelineContext context, ContentHandler contentHandler) throws SAXException { try {/*from ww w .j a v a 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.mirth.connect.model.converters.NCPDPReader.java
private void parseSegment(String segment, ContentHandler contentHandler) throws SAXException { if (StringUtils.isBlank(segment)) { return;/* w w w . j a v a 2 s .co m*/ } boolean inCounter = false; boolean inCount = false; boolean hasMoreFields = true; String segmentId = StringUtils.EMPTY; String subSegment = StringUtils.EMPTY; Stack<String> fieldStack = new Stack<String>(); int fieldDelimeterIndex = segment.indexOf(fieldDelimeter); if (fieldDelimeterIndex == 0) { segment = segment.substring(fieldDelimeterIndex + fieldDelimeter.length()); fieldDelimeterIndex = segment.indexOf(fieldDelimeter); } if (fieldDelimeterIndex == -1) { logger.warn("Empty segment with no field seperators. Make sure batch file processing is disabled."); hasMoreFields = false; segmentId = segment; } else { segmentId = segment.substring(0, fieldDelimeterIndex); subSegment = segment.substring(fieldDelimeterIndex + fieldDelimeter.length(), segment.length()); } contentHandler.startElement("", NCPDPReference.getInstance().getSegment(segmentId, version), "", null); while (hasMoreFields) { fieldDelimeterIndex = subSegment.indexOf(fieldDelimeter); // not last field String field; if (fieldDelimeterIndex != -1) { field = subSegment.substring(0, subSegment.indexOf(fieldDelimeter)); subSegment = subSegment.substring(fieldDelimeterIndex + fieldDelimeter.length()); } else { field = subSegment; hasMoreFields = false; } String fieldId = field.substring(0, 2); String fieldDescription = NCPDPReference.getInstance().getDescription(fieldId, version); String fieldMessage = field.substring(2); if (inCount && !isRepeatingField(fieldDescription) && !fieldDescription.endsWith("Count")) { // if we are were in count field then end the element contentHandler.endElement("", fieldStack.pop(), ""); if (fieldStack.size() == 0) { inCount = false; } } if (fieldDescription.endsWith("Counter")) { if (inCounter) { contentHandler.endElement("", fieldStack.pop(), ""); } inCounter = true; AttributesImpl attr = new AttributesImpl(); attr.addAttribute("", "counter", "counter", "", fieldMessage); contentHandler.startElement("", fieldDescription, "", attr); fieldStack.push(fieldDescription); } else if (fieldDescription.endsWith("Count")) { // count field, add complex element inCount = true; AttributesImpl attr = new AttributesImpl(); attr.addAttribute("", fieldDescription, fieldDescription, "", fieldMessage); // start the repeating field element contentHandler.startElement("", fieldDescription, "", attr); fieldStack.push(fieldDescription); } else { contentHandler.startElement("", fieldDescription, "", null); contentHandler.characters(fieldMessage.toCharArray(), 0, fieldMessage.length()); contentHandler.endElement("", fieldDescription, ""); } } while (fieldStack.size() > 0) { // close remaining count and counters contentHandler.endElement("", fieldStack.pop(), ""); } contentHandler.endElement("", NCPDPReference.getInstance().getSegment(segmentId, version), ""); }
From source file:com.jkoolcloud.tnt4j.streams.configure.sax.ConfigParserHandlerTest.java
@Test(expected = SAXParseException.class) public void missingAttributeTest() throws Exception { ConfigParserHandler test = Mockito.mock(ConfigParserHandler.class, Mockito.CALLS_REAL_METHODS); AttributesImpl attrs = new AttributesImpl(); test.startDocument();/*from w w w. ja v a 2 s. c o m*/ attrs.addAttribute("", "", "name", "", "Stream name 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 attrs.addAttribute("", "", "name", "", ""); // NON-NLS test.startElement("TEST_URL", "TEST_LOCALNAME", "field", attrs); // NON-NLS }
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.ibm.xsp.webdav.DavXMLResponse.java
/** * Starts a new XML document and inserts the correct starting tag with name * spaces// w ww. ja v a 2s .co 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"); } }