Search in sources :

Example 6 with XmlUtilitiesException

use of com.axway.ats.agent.core.templateactions.exceptions.XmlUtilitiesException in project ats-framework by Axway.

the class XmlUtilities method verifyResponseHeaders.

/**
 * Headers are read in the following way(the next overwrites the previous):
 *  - headers from XML
 *  - globally disabled headers
 *  - headers from test case
 *
 * @param actionName
 * @param stepIndex
 * @param expectedHeaderMatchers
 * @param actualHttpResponseNode
 * @throws XmlUtilitiesException
 * @throws InvalidMatcherException
 */
private void verifyResponseHeaders(String actionName, int stepIndex, List<HeaderMatcher> expectedHeaderMatchers, ActionParser actualHttpResponse, TemplateActionsResponseVerificationConfigurator verificationConfigurator) throws XmlUtilitiesException, InvalidMatcherException {
    Node[] actualHeaderNodes = getChildrenNodes(actualHttpResponse.getActionNodeWithoutBody(), TOKEN_HTTP_HEADER);
    // Collect all header matchers from the XML file and the test code.
    // We keep them in a map, so if same header is specified in the XML and the test, the one coming
    // from the test will get precedence
    Map<String, HeaderMatcher> headerMatchersMap = new HashMap<String, HeaderMatcher>();
    // Collect all matchers coming from the static XML file
    for (HeaderMatcher headerMatcher : expectedHeaderMatchers) {
        headerMatchersMap.put(headerMatcher.getHeaderName(), headerMatcher);
    }
    // Collect all global header matchers, this is coming from the test case
    for (HeaderMatcher globalHeaderMatcher : verificationConfigurator.getGlobalHeaderMatchers()) {
        // header matcher from global rule so we assume it is not significant if not already existing - forceOptionalHeaderIfNotAlreadyExisting=true
        headerMatchersMap = addHeaderMatcherToMap(headerMatchersMap, globalHeaderMatcher, true);
    }
    // Collect all matchers coming from the test case
    // We do not check if this is an important header, this way user can specify to check a header for
    // this action step even if it is classified globally as a not important header
    TemplateActionResponseVerificator responseVerificator = verificationConfigurator.getActionVerificator(actionName);
    if (responseVerificator != null) {
        List<HeaderMatcher> headerMatchers = responseVerificator.getStepHeaderMatchers(stepIndex);
        for (HeaderMatcher headerMatcher : headerMatchers) {
            // header matcher from Java test code so we assume it is significant - forceOptionalHeaderIfNotAlreadyExisting=false
            headerMatchersMap = addHeaderMatcherToMap(headerMatchersMap, headerMatcher, false);
        }
    }
    // Now try to match all available header matchers for this action step
    boolean[] processedHeaderNodes = new boolean[actualHeaderNodes.length];
    for (HeaderMatcher headerMatcher : headerMatchersMap.values()) {
        for (int i = 0; i < actualHeaderNodes.length; i++) {
            String actualHeaderName = getNodeAttribute(actualHeaderNodes[i], TOKEN_HEADER_NAME_ATTRIBUTE);
            if (actualHeaderName.equals(headerMatcher.getHeaderName())) {
                // mark the header node as processed
                processedHeaderNodes[i] = true;
                // try to match this header
                String actualHeaderValue = getNodeAttribute(actualHeaderNodes[i], TOKEN_HEADER_VALUE_ATTRIBUTE);
                if (!headerMatcher.performMatch(null, actualHeaderValue)) {
                    // header did not match
                    String causeMsg = "Did not match header value '" + actualHeaderValue + "' for " + headerMatcher.toString() + ".";
                    logActualResponse(causeMsg, actionName, stepIndex, actualHttpResponse, true);
                    throw new XmlUtilitiesException(causeMsg);
                }
                break;
            }
        }
    }
    // this means some expected header was not received
    for (HeaderMatcher headerMatcher : headerMatchersMap.values()) {
        if (!headerMatcher.wasProcessed() && !headerMatcher.isOptionalHeader()) {
            String causeMsg = "Did not receive the expected header for " + headerMatcher.toString() + ".";
            logActualResponse(causeMsg, actionName, stepIndex, actualHttpResponse, true);
            throw new XmlUtilitiesException(causeMsg);
        }
    }
}
Also used : HeaderMatcher(com.axway.ats.agent.core.templateactions.model.matchers.HeaderMatcher) HashMap(java.util.HashMap) XmlUtilitiesException(com.axway.ats.agent.core.templateactions.exceptions.XmlUtilitiesException) Node(org.w3c.dom.Node)

Example 7 with XmlUtilitiesException

use of com.axway.ats.agent.core.templateactions.exceptions.XmlUtilitiesException in project ats-framework by Axway.

the class XmlUtilities method xmlNodeToString.

/**
 * Pretty print XML Node
 * @param node
 * @return
 * @throws XmlUtilitiesException
 */
public String xmlNodeToString(Node node) throws XmlUtilitiesException {
    StringWriter sw = new StringWriter();
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "4");
        transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_LINE_SEPARATOR, "\n");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(new DOMSource(node), new StreamResult(sw));
    } catch (TransformerException te) {
        throw new XmlUtilitiesException("Error transforming XML node to String", te);
    }
    return sw.toString().trim();
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Transformer(javax.xml.transform.Transformer) StringWriter(java.io.StringWriter) StreamResult(javax.xml.transform.stream.StreamResult) XmlUtilitiesException(com.axway.ats.agent.core.templateactions.exceptions.XmlUtilitiesException) TransformerException(javax.xml.transform.TransformerException)

Example 8 with XmlUtilitiesException

use of com.axway.ats.agent.core.templateactions.exceptions.XmlUtilitiesException in project ats-framework by Axway.

the class XmlReader method loadXmlFile.

private void loadXmlFile() throws XmlReaderException, XmlUtilitiesException {
    // FIXME: performance: different actionsXml files could be loaded concurrently but extensive synchronization is needed
    synchronized (actionNodesMap) {
        if (!actionNodesMap.containsKey(actionsXml)) {
            // load the document
            BufferedReader br = null;
            FileChunkReader fileChunkReader = null;
            try {
                // load the action nodes and add them to the map
                actionNodes = new ArrayList<ActionObject>();
                br = new BufferedReader(new InputStreamReader(new FileInputStream(actionsXml)));
                fileChunkReader = new FileChunkReader();
                StringBuilder request = new StringBuilder(1000);
                // if the response doesn't contain parameters we will keep it without the response body part
                StringBuilder responseWoBodyBuilder = new StringBuilder(1000);
                String response = null;
                boolean inRequest = false;
                boolean inResponse = false;
                boolean hasParametersInResponse = false;
                int currentLineNumber = 0;
                int startLineMarker = 0;
                String line;
                while ((line = br.readLine()) != null) {
                    currentLineNumber++;
                    if (line.contains("<HTTP_ACTION>")) {
                        inResponse = false;
                        inRequest = false;
                        continue;
                    } else if (line.contains("</HTTP_ACTION>")) {
                        actionNodes.add(new ActionObject(actionsXml, request.toString(), response));
                        continue;
                    } else if (line.contains("<HTTP_REQUEST ") || line.contains("<HTTP_REQUEST>")) {
                        // the normal case is "<HTTP_REQUEST ",
                        // but we also handle here the "<HTTP_REQUEST>" in case the HTTP method attribute is missing
                        // sometime later an appropriate exception will be thrown
                        // clear old request data
                        request.delete(0, request.length());
                        inRequest = true;
                    } else if (line.contains("</HTTP_REQUEST>")) {
                        request.append(line + AtsSystemProperties.SYSTEM_LINE_SEPARATOR);
                        inRequest = false;
                        continue;
                    } else if (line.contains("<HTTP_RESPONSE>")) {
                        startLineMarker = currentLineNumber;
                        // clear old response data
                        responseWoBodyBuilder.delete(0, responseWoBodyBuilder.length());
                        responseWoBodyBuilder.append(line + AtsSystemProperties.SYSTEM_LINE_SEPARATOR);
                        inResponse = true;
                        continue;
                    } else if (line.contains("</HTTP_RESPONSE>")) {
                        responseWoBodyBuilder.append(line + AtsSystemProperties.SYSTEM_LINE_SEPARATOR);
                        // optimization - do not store body if there are no variables in the body
                        if (hasParametersInResponse) {
                            response = fileChunkReader.readChunk(startLineMarker, currentLineNumber);
                        } else {
                            response = responseWoBodyBuilder.toString();
                        }
                        inResponse = false;
                        hasParametersInResponse = false;
                        continue;
                    }
                    if (inRequest) {
                        request.append(line + AtsSystemProperties.SYSTEM_LINE_SEPARATOR);
                    } else if (inResponse) {
                        // search for parameters in the response
                        if (!hasParametersInResponse && line.contains("${") && line.matches(".*\\$\\{.+\\}.*")) {
                            hasParametersInResponse = true;
                        }
                        // collect the response data without the response body
                        if (line.contains("<HTTP_HEADER ") || line.contains("<HTTP_RESOURCE_FILE") || line.contains("<HTTP_RESPONSE_RESULT>")) {
                            responseWoBodyBuilder.append(line + AtsSystemProperties.SYSTEM_LINE_SEPARATOR);
                        }
                    }
                }
                actionNodesMap.put(actionsXml, actionNodes);
            } catch (Exception e) {
                throw new XmlReaderException(actionsXml, e);
            } finally {
                IoUtils.closeStream(fileChunkReader);
                IoUtils.closeStream(br);
            }
        } else {
            actionNodes = actionNodesMap.get(actionsXml);
        }
        iActionNodes = -1;
    }
}
Also used : XmlReaderException(com.axway.ats.agent.core.templateactions.exceptions.XmlReaderException) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) FileInputStream(java.io.FileInputStream) XmlReaderException(com.axway.ats.agent.core.templateactions.exceptions.XmlReaderException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) XmlUtilitiesException(com.axway.ats.agent.core.templateactions.exceptions.XmlUtilitiesException) ActionObject(com.axway.ats.agent.core.templateactions.model.objects.ActionObject)

Aggregations

XmlUtilitiesException (com.axway.ats.agent.core.templateactions.exceptions.XmlUtilitiesException)8 TransformerException (javax.xml.transform.TransformerException)3 InvalidMatcherException (com.axway.ats.agent.core.templateactions.exceptions.InvalidMatcherException)2 Node (org.w3c.dom.Node)2 XmlReaderException (com.axway.ats.agent.core.templateactions.exceptions.XmlReaderException)1 HeaderMatcher (com.axway.ats.agent.core.templateactions.model.matchers.HeaderMatcher)1 ResponseMatcher (com.axway.ats.agent.core.templateactions.model.matchers.ResponseMatcher)1 XPathBodyMatcher (com.axway.ats.agent.core.templateactions.model.matchers.XPathBodyMatcher)1 ActionObject (com.axway.ats.agent.core.templateactions.model.objects.ActionObject)1 ActionParser (com.axway.ats.agent.core.templateactions.model.objects.ActionParser)1 ActionResponseObject (com.axway.ats.agent.core.templateactions.model.objects.ActionResponseObject)1 LocalFileSystemOperations (com.axway.ats.core.filesystem.LocalFileSystemOperations)1 BufferedReader (java.io.BufferedReader)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 FileInputStream (java.io.FileInputStream)1 FileNotFoundException (java.io.FileNotFoundException)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 StringWriter (java.io.StringWriter)1 ArrayList (java.util.ArrayList)1