package net.ihe.xcpd.init.transport; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringReader; import java.io.StringWriter; import java.net.HttpURLConnection; import java.net.URL; import javax.mail.MessagingException; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMultipart; import javax.mail.util.ByteArrayDataSource; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import net.ihe.gazelle.simulator.common.model.ApplicationConfiguration; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.w3c.dom.Document; public class SOAPSender2 { /** * * @param inUrl * @param messageToSend * @return */ public static String sendToUrlAndGetResponse(String inUrl, String messageToSend) throws Exception { URL url; InputStream inputStream; try { url = new URL(inUrl); if (inUrl.startsWith("https")) { inputStream = sendOverHttps(url, messageToSend); } else { inputStream = sendOverHttp(url, messageToSend); } BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); if (in != null) { StringBuffer response = new StringBuffer(); String line = null; response.append(in.readLine()); while((line = in.readLine()) != null) { response.append(line); } in.close(); return response.toString(); } else { return null; } } catch (Exception e) { System.out.println("ERROR: an error occurred when sending the message to " + inUrl + ": " + e.getMessage()); e.printStackTrace(); throw e; } } /** * * @param inString * @return */ public static org.dom4j.Document stringToXmlTransformer(String inString) { org.dom4j.Document document = null; try{ document = DocumentHelper.parseText(inString); }catch(DocumentException e){ e.printStackTrace(); return null; } return document; } private static InputStream sendOverHttp(URL inUrl, String inMessageToSend) throws IOException { //System.out.println("inMessageToSend = " + inMessageToSend); java.net.HttpURLConnection connection = (HttpURLConnection) inUrl.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestProperty("Content-Type","application/soap+xml; charset=UTF-8;action=\"urn:hl7-org:v3:PRPA_IN201305UV02:CrossGatewayPatientDiscovery\""); connection.setRequestProperty("SOAPAction", "urn:hl7-org:v3:PRPA_IN201305UV02:CrossGatewayPatientDiscovery"); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.writeBytes(inMessageToSend); out.flush(); out.close(); int responseCode = connection.getResponseCode(); String r = connection.getContentType(); System.out.println("ct = " + r); InputStream inputStream; if (responseCode == HttpURLConnection.HTTP_OK) { System.out.println("code = normal"); inputStream = connection.getInputStream(); } else { System.out.println("code = error"); inputStream = connection.getErrorStream(); } return inputStream; } private static InputStream sendOverHttps(URL inUrl, String inMessageToSend) throws IOException { String keystorePath = ApplicationConfiguration.getValueOfVariable("keystore_path"); System.setProperty("javax.net.ssl.keyStore",keystorePath); System.setProperty("javax.net.ssl.keyStorePassword", "gazelle"); System.setProperty("javax.net.ssl.trustStore", keystorePath); System.setProperty("javax.net.ssl.trustStorePassword", "gazelle"); HttpsURLConnection connection = (HttpsURLConnection) inUrl.openConnection(); HostnameVerifier verifier = new CustomizedHostnameVerifier(); connection.setHostnameVerifier(verifier); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestProperty("Content-Type", "application/soap+xml"); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.writeBytes(inMessageToSend); out.flush(); out.close(); int responseCode = connection.getResponseCode(); InputStream inputStream; if (responseCode == HttpURLConnection.HTTP_OK) { inputStream = connection.getInputStream(); } else { inputStream = connection.getErrorStream(); } return inputStream; } /** * This class is used to avoid java.security.cert.CertificateException: No name matching "hostname" found exception * @author aberge * */ private static class CustomizedHostnameVerifier implements HostnameVerifier { public boolean verify(String hostname, SSLSession session) { return true; } } /** * * @param document * @return */ public static String xmlToStringTransformer(Document document) { if (document == null) return null; try { Source source = new DOMSource(document); StringWriter stringWriter = new StringWriter(); Result result = new StreamResult(stringWriter); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(source, result); return stringWriter.getBuffer().toString(); }catch(Exception e){ System.out.println("error when converting XML to String: " + e.getMessage()); e.printStackTrace(); return null; } } public static String prettyFormat(String input) { try{ Source xmlInput = new StreamSource(new StringReader(input)); StringWriter stringWriter = new StringWriter(); StreamResult output = new StreamResult(stringWriter); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(4)); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(xmlInput, output); return output.getWriter().toString(); }catch(Exception e){ return input; } } public static void getMimeParts(byte[] response) { ByteArrayDataSource ds = new ByteArrayDataSource(response, null); try { MimeMultipart multipart = new MimeMultipart(ds); System.out.println("nb of parts in multipart mime: " + multipart.getCount()); Integer nbOfParts = multipart.getCount(); if (nbOfParts != null && nbOfParts > 0) { for(Integer index = 0; index < nbOfParts; index ++) { MimeBodyPart body = (MimeBodyPart) multipart.getBodyPart(index); InputStream is = body.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuffer buffer = new StringBuffer(); String line = null; buffer.append(reader.readLine()); while((line = reader.readLine()) != null) { buffer.append(line); } reader.close(); String part = buffer.toString(); String type = body.getContentType(); System.out.println(index + " : " + type + "--"+ part); } } } catch (MessagingException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static String transformXmlToHtml(String documentContent) { if (documentContent == null || documentContent.length() == 0) return null; try { String xslPath = ApplicationConfiguration.getValueOfVariable("cda_xsl_path"); if (xslPath == null || xslPath.length() == 0) return null; Source xmlInput = new StreamSource(new StringReader(documentContent)); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(new javax.xml.transform.stream.StreamSource(xslPath)); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); StreamResult out = new StreamResult(baos); transformer.transform(xmlInput, out); String tmp = new String (baos.toByteArray()) ; return tmp; } catch (Exception e) { e.printStackTrace( ); return "The document cannot be displayed using this stylesheet"; } } }