Java tutorial
package ru.cti.gosuslugi.service.client; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.apache.commons.io.IOUtils; import org.apache.velocity.app.VelocityEngine; import org.eclipse.jetty.http.HttpException; import org.eclipse.jetty.io.ByteArrayBuffer; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Component; import org.springframework.ui.velocity.VelocityEngineUtils; import org.springframework.ws.client.core.WebServiceTemplate; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import ru.cti.gosuslugi.model.penalty.registry.OffenceInfoForProgrammaticSystems; import ru.cti.gosuslugi.service.OffenceInfoService; import ru.cti.gosuslugi.ws.SoapSigner; import org.eclipse.jetty.client.*; import org.eclipse.jetty.client.HttpClient; @Component public class OffenceInfoServiceClient implements OffenceInfoService, InitializingBean { private WebServiceTemplate webServiceTemplate; private static final Logger logger = LoggerFactory.getLogger(OffenceInfoServiceClient.class); private VelocityEngine velocityEngine; private SoapSigner soapSigner; private static JAXBContext jaxbContext; private int timeout; private int maxConnectionsPerAddress; private boolean contentExchange; private int maxThreadPool; private static Transformer serializer; private HttpClient httpClient; public boolean isContentExchange() { return contentExchange; } public void setContentExchange(boolean contentExchange) { this.contentExchange = contentExchange; } public int getMaxThreadPool() { return maxThreadPool; } public void setMaxThreadPool(int maxThreadPool) { this.maxThreadPool = maxThreadPool; } public int getMaxConnectionsPerAddress() { return maxConnectionsPerAddress; } public void setMaxConnectionsPerAddress(int maxConnectionsPerAddress) { this.maxConnectionsPerAddress = maxConnectionsPerAddress; } public OffenceInfoServiceClient(WebServiceTemplate webServiceTemplate) { this.webServiceTemplate = webServiceTemplate; } public void setVelocityEngine(VelocityEngine velocityEngine) { this.velocityEngine = velocityEngine; } public SoapSigner getSoapSigner() { return soapSigner; } public void setSoapSigner(SoapSigner soapSigner) { this.soapSigner = soapSigner; } public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } protected List<String> vehicleStsNumber; protected String drivingLicenseSeries; protected String drivingLicenseNumber; @Override public OffenceInfoForProgrammaticSystems getOffenceInfo(String drivingLicenseSeries, String drivingLicenseNumber, List<String> vehicleStsNumber) throws HttpException, IOException { OffenceInfoForProgrammaticSystems res = null; logger.debug( "offence info service client request, drivingLicenseSeries:{}, drivingLicenseNumber:{}, vehicleStsNumbers:{} ", new Object[] { drivingLicenseSeries, drivingLicenseNumber, vehicleStsNumber }); Map<String, Object> model = new HashMap<String, Object>(); model.put("drivingLicenseSeries", drivingLicenseSeries); model.put("drivingLicenseNumber", drivingLicenseNumber); if (vehicleStsNumber != null && !vehicleStsNumber.isEmpty()) { model.put("vehicleStsNumber", vehicleStsNumber.get(0)); } else { model.put("vehicleStsNumber", ""); } String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "ru/cti/gosuslugi/soap-templates/offence-info.vm", "UTF-8", model); logger.debug("original message: {}", text); String signedMessage = soapSigner.signMessage(text); logger.debug("signed message: {}", signedMessage); logger.debug("try to send on {}", webServiceTemplate.getDefaultUri()); String responseText = sendPost(signedMessage, webServiceTemplate.getDefaultUri()); logger.debug("response text: {}", responseText); try { res = getOffenceInfoList(responseText); } catch (Exception e) { logger.error("error on parse xml document", e); } //OffenceInfoForProgrammaticSystems response = (OffenceInfoForProgrammaticSystems)webServiceTemplate.marshalSendAndReceive(request); return res;//response.getData(); } private String sendPost(String message, String url) throws HttpException, IOException { String responseText = ""; try { if (!httpClient.isStarted()) { httpClient.start(); } ContentExchange exchange = new ContentExchange(contentExchange); exchange.setURL(url); exchange.setMethod("POST"); exchange.setRequestHeader("Content-Type", "text/xml"); exchange.setRequestHeader("SOAPAction", ""); exchange.setRequestHeader("charset", "UTF-8"); exchange.setRequestContent(new ByteArrayBuffer(message.getBytes())); httpClient.send(exchange); int exchangeState = exchange.waitForDone(); if (exchangeState == HttpExchange.STATUS_COMPLETED) { responseText = exchange.getResponseContent(); } else if (exchangeState == HttpExchange.STATUS_EXCEPTED) { } else if (exchangeState == HttpExchange.STATUS_EXPIRED) { } } catch (Exception e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } return responseText; } private OffenceInfoForProgrammaticSystems getOffenceInfoList(String response) throws IOException, SAXException, ParserConfigurationException, XPathExpressionException, TransformerFactoryConfigurationError, TransformerException, JAXBException { Document responseDocument = buildXmlDocumentFromString(response); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); NodeList nodeList = (NodeList) xpath.evaluate("//Body/*", responseDocument, XPathConstants.NODESET); StringWriter sw = new StringWriter(); if (serializer == null) serializer = TransformerFactory.newInstance().newTransformer(); serializer.transform(new DOMSource(nodeList.item(0)), new StreamResult(sw)); String res = sw.toString(); logger.debug("offence body: {}", res); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); return (OffenceInfoForProgrammaticSystems) unmarshaller .unmarshal(new ByteArrayInputStream(res.getBytes("UTF-8"))); } private static Document buildXmlDocumentFromString(String responce) throws IOException, SAXException, ParserConfigurationException { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = domFactory.newDocumentBuilder(); return builder.parse(new InputSource(new StringReader(responce))); } @Override public void afterPropertiesSet() throws Exception { jaxbContext = JAXBContext.newInstance("ru.cti.gosuslugi.model.penalty.registry"); if (httpClient == null) { httpClient = new HttpClient(); httpClient.setMaxConnectionsPerAddress(maxConnectionsPerAddress); httpClient.setThreadPool(new QueuedThreadPool(maxThreadPool)); httpClient.setTimeout(timeout); httpClient.setConnectorType(HttpClient.CONNECTOR_SELECT_CHANNEL); } } }