View Javadoc
1   /*
2    * Copyright 2010 James Pether Sörling
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   *
16   *	$Id$
17   *  $HeadURL$
18  */
19  package com.hack23.cia.service.external.common.impl;
20  
21  import java.io.BufferedReader;
22  import java.io.ByteArrayInputStream;
23  import java.io.IOException;
24  import java.io.InputStream;
25  import java.io.InputStreamReader;
26  import java.io.Reader;
27  import java.net.URL;
28  import java.net.URLConnection;
29  import java.nio.charset.StandardCharsets;
30  import java.util.Locale;
31  
32  import javax.xml.transform.Source;
33  import javax.xml.transform.stream.StreamSource;
34  
35  import org.apache.http.client.fluent.Request;
36  import org.jdom2.Document;
37  import org.jdom2.Namespace;
38  import org.jdom2.input.SAXBuilder;
39  import org.jdom2.input.sax.XMLReaderSAX2Factory;
40  import org.jdom2.transform.JDOMSource;
41  import org.slf4j.Logger;
42  import org.slf4j.LoggerFactory;
43  import org.springframework.oxm.Unmarshaller;
44  import org.springframework.stereotype.Service;
45  
46  import com.hack23.cia.service.external.common.api.XmlAgent;
47  
48  /**
49   * The Class XmlAgentImpl.
50   */
51  @Service
52  final class XmlAgentImpl implements XmlAgent {
53  
54  	/** The Constant LOGGER. */
55  	private static final Logger LOGGER = LoggerFactory
56  			.getLogger(XmlAgentImpl.class);
57  
58  	/**
59  	 * Instantiates a new xml agent impl.
60  	 */
61  	public XmlAgentImpl() {
62  		super();
63  	}
64  
65  	/**
66  	 * Read with string buffer.
67  	 *
68  	 * @param fr
69  	 *            the fr
70  	 * @return the string
71  	 * @throws IOException
72  	 *             Signals that an I/O exception has occurred.
73  	 */
74  	private static String readWithStringBuffer(final Reader fr) throws IOException {
75  
76  		final BufferedReader br = new BufferedReader(fr);
77  		String line;
78  		final StringBuilder result = new StringBuilder();
79  		while ((line = br.readLine()) != null) {
80  			result.append(line);
81  		}
82  
83  		return result.toString();
84  	}
85  
86  	@Override
87  	public String retriveContent(final String accessUrl) throws Exception {
88  		final URL url = new URL(accessUrl.replace(" ",""));
89  
90  		final BufferedReader inputStream = new BufferedReader(new InputStreamReader(
91  				url.openStream(),StandardCharsets.UTF_8));
92  
93  		return readWithStringBuffer(inputStream);
94  	}
95  
96  	/**
97  	 * Sets the name space on xml stream.
98  	 *
99  	 * @param in
100 	 *            the in
101 	 * @param nameSpace
102 	 *            the name space
103 	 * @return the source
104 	 * @throws Exception
105 	 *             the exception
106 	 */
107 	private static Source setNameSpaceOnXmlStream(final InputStream in, final String nameSpace)
108 			throws Exception {
109 		final SAXBuilder sb = new SAXBuilder(new XMLReaderSAX2Factory(false));
110 		final Document doc = sb.build(in);
111 		doc.getRootElement().setNamespace(Namespace.getNamespace(nameSpace));
112 		return new JDOMSource(doc);
113 	}
114 
115 
116 	@Override
117 	public Object unmarshallXml(final Unmarshaller unmarshaller, final String accessUrl) throws Exception {
118 		return unmarshallXml(unmarshaller, accessUrl,null,null,null);
119 	}
120 
121 	@Override
122 	public Object unmarshallXml(final Unmarshaller unmarshaller, final String accessUrl,
123 			final String nameSpace,final String replace, final String with) throws Exception {
124 
125 		LOGGER.info("Calls {}", accessUrl);
126 
127 		final boolean isWeb = accessUrl.toLowerCase(Locale.ENGLISH).startsWith("http://") || accessUrl.toLowerCase(Locale.ENGLISH).startsWith("https://");
128 
129 		String xmlContent;
130 		if (isWeb) {
131 			xmlContent = Request.Get(accessUrl.replace(" ","")).execute().returnContent().asString(StandardCharsets.UTF_8);
132 		} else {
133 			xmlContent = readInputStream(accessUrl.replace(" ",""));
134 		}
135 
136 		if (replace != null) {
137 			xmlContent = xmlContent.replace(replace, with);
138 		}
139 
140 		final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
141 				xmlContent.getBytes(StandardCharsets.UTF_8));
142 
143 		Source source;
144 		if (nameSpace != null) {
145 			source = setNameSpaceOnXmlStream(byteArrayInputStream, nameSpace);
146 		} else {
147 			source = new StreamSource(byteArrayInputStream);
148 		}
149 
150 		return unmarshaller.unmarshal(source);
151 	}
152 
153 	/**
154 	 * Read input stream.
155 	 *
156 	 * @param accessUrl
157 	 *            the access url
158 	 * @return the string
159 	 * @throws Exception
160 	 *             the exception
161 	 */
162 	private static String readInputStream(final String accessUrl) throws Exception{
163 		final URL url = new URL(accessUrl.replace(" ",""));
164 
165 		final URLConnection connection = url.openConnection();
166 
167 		final InputStream stream = connection.getInputStream();
168 
169 
170 		final BufferedReader inputStream = new BufferedReader(new InputStreamReader(
171 				stream,StandardCharsets.UTF_8));
172 
173 		return readWithStringBuffer(inputStream);
174 	}
175 }