source: trunk/autoquest-plugin-http/src/main/java/de/ugoe/cs/autoquest/plugin/http/SOAPUtils.java @ 1929

Last change on this file since 1929 was 1929, checked in by sherbold, 9 years ago
  • refactored and commented UMLUtils
  • created UTPUtils
  • moved DOM related methods from UMLUtils to SOAPUtils
  • Property svn:mime-type set to text/plain
File size: 11.2 KB
Line 
1//   Copyright 2012 Georg-August-Universität Göttingen, Germany
2//
3//   Licensed under the Apache License, Version 2.0 (the "License");
4//   you may not use this file except in compliance with the License.
5//   You may obtain a copy of the License at
6//
7//       http://www.apache.org/licenses/LICENSE-2.0
8//
9//   Unless required by applicable law or agreed to in writing, software
10//   distributed under the License is distributed on an "AS IS" BASIS,
11//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//   See the License for the specific language governing permissions and
13//   limitations under the License.
14
15package de.ugoe.cs.autoquest.plugin.http;
16
17import java.io.StringWriter;
18import java.util.ArrayList;
19import java.util.Iterator;
20import java.util.LinkedList;
21import java.util.List;
22
23import javax.xml.transform.Transformer;
24import javax.xml.transform.TransformerException;
25import javax.xml.transform.TransformerFactory;
26import javax.xml.transform.TransformerFactoryConfigurationError;
27import javax.xml.transform.dom.DOMSource;
28import javax.xml.transform.stream.StreamResult;
29
30import org.w3c.dom.Attr;
31import org.w3c.dom.Element;
32import org.w3c.dom.Node;
33import org.w3c.dom.NodeList;
34
35import de.ugoe.cs.autoquest.eventcore.Event;
36import de.ugoe.cs.autoquest.plugin.http.eventcore.SOAPEventType;
37import de.ugoe.cs.autoquest.plugin.http.eventcore.SimpleSOAPEventType;
38
39/**
40 * <p>
41 * Utilities for working with SOAP events. Their main task is to simply working with
42 * {@link SimpleSOAPEventType} and {@link SOAPEventType}.
43 * </p>
44 *
45 * @author Steffen Herbold
46 */
47public class SOAPUtils {
48
49    /**
50     * <p>
51     * Replaces events with a {@link SOAPEventType} with new events of {@link SimpleSOAPEventType}
52     * and no target.
53     * </p>
54     *
55     * @param sequence
56     *            sequence where the events are replaced
57     * @param keepOnlySOAPEvents
58     *            if true, all events that are not of SOAPEventType or SimpleSOAPEventType are
59     *            removed
60     * @return sequence with {@link SimpleSOAPEventType}s instead of {@link SOAPEventType}s
61     */
62    public static List<Event> convertToSimpleSOAPEvent(List<Event> sequence,
63                                                       boolean keepOnlySOAPEvents)
64    {
65        List<Event> newSequence = null;
66        if (sequence != null) {
67            newSequence = new LinkedList<>();
68            for (Event event : sequence) {
69                if (event.getType() instanceof SOAPEventType) {
70                    SOAPEventType eventType = (SOAPEventType) event.getType();
71                    newSequence.add(new Event(new SimpleSOAPEventType(eventType.getCalledMethod(),
72                                                                      eventType.getServiceName(),
73                                                                      eventType.getClientName(),
74                                                                      eventType
75                                                                          .getSoapRequestBody())));
76                }
77                else {
78                    if (!keepOnlySOAPEvents || event.getType() instanceof SimpleSOAPEventType) {
79                        newSequence.add(event);
80                    }
81                }
82            }
83        }
84        return newSequence;
85    }
86
87    /**
88     * <p>
89     * Removes all non SOAP events from a sequence. Warning: this change is performed in-place!
90     * </p>
91     *
92     * @param sequence
93     *            sequence where the events are replaced
94     */
95    public static void removeNonSOAPEvents(List<Event> sequence) {
96        for (Iterator<Event> eventIter = sequence.iterator(); eventIter.hasNext();) {
97            Event event = eventIter.next();
98            if (!(event.getType() instanceof SOAPEventType)) {
99                eventIter.remove();
100            }
101        }
102    }
103
104    /**
105     * <p>
106     * Helper function to get the name of a service from a SOAP event.
107     * </p>
108     *
109     * @param event
110     *            event for which the service name is retrieved
111     * @return service name
112     */
113    public static String getServiceNameFromEvent(Event event) {
114        if (event.getType() instanceof SOAPEventType) {
115            return ((SOAPEventType) event.getType()).getServiceName();
116        }
117        else if (event.getType() instanceof SimpleSOAPEventType) {
118            return ((SimpleSOAPEventType) event.getType()).getServiceName();
119        }
120        else {
121            throw new RuntimeException(
122                                       "Wrong event type. Only SOAPEventType and SimpleSOAPEventType supported but was: " +
123                                           event.getType().getClass().getName());
124        }
125    }
126
127    /**
128     *
129     * <p>
130     * Helper function to get the called method from a SOAP event
131     * </p>
132     *
133     * @param event
134     *            event for which the called method is retrieved
135     * @return called method
136     */
137    public static String getCalledMethodFromEvent(Event event) {
138        if (event.getType() instanceof SOAPEventType) {
139            return ((SOAPEventType) event.getType()).getCalledMethod();
140        }
141        else if (event.getType() instanceof SimpleSOAPEventType) {
142            return ((SimpleSOAPEventType) event.getType()).getCalledMethod();
143        }
144        else {
145            throw new RuntimeException(
146                                       "Wrong event type. Only SOAPEventType and SimpleSOAPEventType supported but was: " +
147                                           event.getType().getClass().getName());
148        }
149    }
150
151    /**
152     * <p>
153     * Helper function to get the name of a client from a SOAP event.
154     * </p>
155     *
156     * @param event
157     *            event for which the client name is retrieved
158     * @return service name
159     */
160    public static String getClientNameFromEvent(Event event) {
161        if (event.getType() instanceof SOAPEventType) {
162            return ((SOAPEventType) event.getType()).getClientName();
163        }
164        else if (event.getType() instanceof SimpleSOAPEventType) {
165            return ((SimpleSOAPEventType) event.getType()).getClientName();
166        }
167        else {
168            throw new RuntimeException(
169                                       "Wrong event type. Only SOAPEventType and SimpleSOAPEventType supported but was: " +
170                                           event.getType().getClass().getName());
171        }
172    }
173
174    /**
175     * <p>
176     * Helper function to get the body of a SOAP request.
177     * </p>
178     *
179     * @param event
180     *            event for which the SOAP request body is retrieved
181     * @return body of the SOAP event
182     */
183    public static Element getSoapRequestBodyFromEvent(Event event) {
184        Element requestBody = null;
185        if (event.getType() instanceof SOAPEventType) {
186            requestBody = ((SOAPEventType) event.getType()).getSoapRequestBody();
187        }
188        else if (event.getType() instanceof SimpleSOAPEventType) {
189            requestBody = ((SimpleSOAPEventType) event.getType()).getSoapRequestBody();
190        }
191        return requestBody;
192    }
193
194    /**
195     * <p>
196     * returns the XML serialization of a DOM node; located here because it is used for SOAP request
197     * bodies
198     * </p>
199     *
200     * @param node
201     *            DOM node that is serialized
202     * @return XML serialization as String; null if node is null
203     */
204    public static String getSerialization(Node node) {
205        if (node == null) {
206            return null;
207        }
208        try {
209            StringWriter writer = new StringWriter();
210            Transformer transformer = TransformerFactory.newInstance().newTransformer();
211            transformer.transform(new DOMSource(node), new StreamResult(writer));
212            return writer.toString();
213        }
214        catch (TransformerFactoryConfigurationError | TransformerException e) {
215            throw new IllegalArgumentException(
216                                               "could not create serialization for SOAP request body.",
217                                               e);
218        }
219    }
220
221    /**
222     * <p>
223     * Fetches all {@link Element}s that are direct children of the parent node, whose name matches
224     * the given name.
225     * </p>
226     *
227     * @param typeNameRaw
228     *            name of elements that are looked for
229     * @param parentNode
230     *            DOM node in which the elements are searched for
231     * @return found {@link Element}s
232     */
233    public static List<Element> getMatchingChildNode(String typeNameRaw, Element parentNode) {
234        List<Element> matchingNodes = new ArrayList<>();
235        Node parameterNode = null;
236        if (parentNode != null) {
237            NodeList parameterNodes = parentNode.getChildNodes();
238            String[] typeNameSplit = typeNameRaw.split(":");
239            String typeName = typeNameSplit[typeNameSplit.length - 1];
240            for (int i = 0; i < parameterNodes.getLength(); i++) {
241                parameterNode = parameterNodes.item(i);
242                if (parameterNode.getNodeType() == Node.ELEMENT_NODE) {
243                    String[] parameterNodeSplit = parameterNode.getNodeName().split(":");
244                    String parameterNodeName = parameterNodeSplit[parameterNodeSplit.length - 1];
245                    if (typeName.equals(parameterNodeName)) {
246                        matchingNodes.add((Element) parameterNode);
247                    }
248                }
249            }
250        }
251        return matchingNodes;
252    }
253
254    /**
255     * <p>
256     * Returns the values found in a currentNode for a defined valueName. To this aim, this methods
257     * first determines if there is an attribute with the name "valueName". If this is the case, the
258     * value of this attribute is returned. Otherwise, the methods looks for {@link Element}s that
259     * are direct children of the provided DOM node with the given name and returns the text content
260     * of those nodes.
261     * </p>
262     * <p>
263     * In case no values can be found, an empty list is returned
264     *
265     * @param valueName
266     *            name of the value that is retrieved
267     * @param node
268     *            node for which the value is retrieved
269     * @return list of the found values.
270     */
271    public static List<String> getValuesFromElement(String valueName, Element node) {
272        List<String> attributeValues = new LinkedList<>();
273
274        if (node != null) {
275            // first check attributes of the node
276            Attr attribute = node.getAttributeNode(valueName);
277            if (attribute != null) {
278                attributeValues.add(attribute.getValue());
279            }
280            else {
281                // now check elements
282                List<Element> elements = getMatchingChildNode(valueName, node);
283                for (Element element : elements) {
284                    attributeValues.add(element.getTextContent());
285                }
286            }
287        }
288
289        return attributeValues;
290    }
291
292    /**
293     * <p>
294     * prevent instantiation
295     * </p>
296     */
297    private SOAPUtils() {}
298}
Note: See TracBrowser for help on using the repository browser.