Package com.xmlcalabash.core

Examples of com.xmlcalabash.core.XProcException


        File temp;
        try {
            temp = File.createTempFile(prefix, suffix);
        } catch (IOException ioe) {
            throw new XProcException(step.getNode(), "Failed to create temporary file for CSS");
        }

        temp.deleteOnExit();

        try {
            PrintStream cssout = new PrintStream(temp);
            cssout.print(stylesheet);
            cssout.close();
        } catch (FileNotFoundException fnfe) {
            throw new XProcException(step.getNode(), "Failed to write to temporary CSS file");
        }

        if (primarySS == null) {
            primarySS = temp.toURI().toASCIIString();
        } else {
View Full Code Here


        }
    }

    public void format(XdmNode doc, OutputStream out, String contentType) {
        if (contentType != null && !"application/pdf".equals(contentType)) {
            throw new XProcException(step.getNode(), "Unsupported content-type on p:css-formatter: " + contentType);
        }

        try {
            if (primarySS != null) {
                prince.addStyleSheet(primarySS);
            }

            for (String uri : userSS) {
                prince.addStyleSheet(uri);
            }

            ByteArrayInputStream bis = new ByteArrayInputStream(doc.toString().getBytes("UTF-8"));
            prince.convert(bis, out);
        } catch (IOException e) {
            logger.debug(e.getMessage(), e);
            throw new XProcException(e);
        }
    }
View Full Code Here

        result = pipe;
    }

    public void setParameter(QName name, RuntimeValue value) {
        if (!"".equals(name.getNamespaceURI())) {
            throw new XProcException(step.getNode(), "The p:xsl-formatter parameters are in no namespace: " + name + " (" + name.getNamespaceURI() + ")");
        }
        options.setProperty(name.getLocalName(), value.getString());
    }
View Full Code Here

                }
            }
        }

        if (provider == null) {
            throw new XProcException(step.getNode(), "Failed to instantiate FO provider", pexcept);
        }

        final String contentType;
        if (getOption(_content_type) != null) {
            contentType = getOption(_content_type).getString();
        } else {
            contentType = "application/octet-stream";
        }

        String base = getOption(_href).getBaseURI().toASCIIString();
        String href = getOption(_href).getString();

        try {
            final FoProcessor processor = provider;
            DataStore store = runtime.getDataStore();
            URI id = store.writeEntry(href, base, contentType, new DataWriter() {
                public void store(OutputStream content) throws IOException {
                    OutputStream out = new BufferedOutputStream(content);
                    try {
                        processor.format(source.read(),out,contentType);
                    } catch (SaxonApiException e) {
                        throw new XProcException(step.getNode(), "Failed to process FO document", e);
                    } finally {
                        out.close();
                    }
                }
            });

            TreeWriter tree = new TreeWriter(runtime);
            tree.startDocument(step.getNode().getBaseURI());
            tree.addStartElement(XProcConstants.c_result);
            tree.startContent();
            tree.addText(id.toASCIIString());
            tree.addEndElement();
            tree.endDocument();
            result.write(tree.getResult());
        } catch (XProcException e) {
            throw e;
        } catch (Exception e) {
            throw new XProcException(step.getNode(), "Failed to process FO document", e);
        }
    }
View Full Code Here

            doc = source.read();
            docBaseURI = doc.getBaseURI();

            if (verifier != null && !verifier.verify(S9apiUtils.xdmToInputSource(runtime, doc))) {
                throw new XProcException(XProcException.err_E0001, "Document is not valid");
            }

            result.write(doc);
        } catch (VerifierConfigurationException ex) {
            logger.debug(ex.getMessage(), ex);
            throw new XProcException(ex);
        } catch (SAXException sx) {
            // Assume the only error is validity failed?
            if (getOption(_assert_valid,false)) {
                throw XProcException.stepError(53);
            }
            result.write(doc);
        } catch (IOException ioe) {
            logger.debug(ioe.getMessage(), ioe);
            throw new XProcException(ioe);
        }
    }
View Full Code Here

        if (XProcConstants.xs_QName.equals(type)) {
            try {
                QName name = new QName(value, node);
            } catch (Exception e) {
                throw new XProcException(error, e);
            }
            return;
        }

        ItemTypeFactory typeFactory = new ItemTypeFactory(runtime.getProcessor());

        ItemType itype = null;

        try {
            itype = typeFactory.getAtomicType(type);
        } catch (SaxonApiException sae) {
            throw new XProcException("Unexpected type: " + type);
        }

        // FIXME: There's probably a less expensive expensive way to do this
        try {
            XdmAtomicValue avalue = new XdmAtomicValue(value, itype);
        } catch (SaxonApiException sae) {
            throw new XProcException(error, sae);
        }
    }   
View Full Code Here

                    || _auth_method.equals(name) || _send_authorization.equals(name)
                    || _override_content_type.equals(name)) {
                // nop
            } else {
                if (XMLConstants.DEFAULT_NS_PREFIX.equals(name.getNamespaceURI())) {
                    throw new XProcException(step.getNode(), "Unsupported attribute on c:request for p:http-request: " + name);
                }
            }
        }

        String send = step.getExtensionAttribute(cx_send_binary);
        encodeBinary = !"true".equals(send);

        method = start.getAttributeValue(_method);
        statusOnly = "true".equals(start.getAttributeValue(_status_only));
        detailed = "true".equals(start.getAttributeValue(_detailed));
        overrideContentType = start.getAttributeValue(_override_content_type);

        if (method == null) {
            throw XProcException.stepError(6);
        }

        if (statusOnly && !detailed) {
            throw XProcException.stepError(4);
        }

        if (start.getAttributeValue(_href) == null) {
            throw new XProcException(step.getNode(), "The 'href' attribute must be specified on c:request for p:http-request");
        }

        requestURI = start.getBaseURI().resolve(start.getAttributeValue(_href));

        String scheme = requestURI.getScheme();
        if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
            doFile(start.getAttributeValue(_href), start.getBaseURI().toASCIIString());
            return;
        }

        HttpParams params = new BasicHttpParams();
        HttpContext localContext = new BasicHttpContext();

        // The p:http-request step should follow redirect requests if they are returned by the server.
        params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);

        // What about cookies
        String saveCookieKey = step.getExtensionAttribute(cx_save_cookies);
        String useCookieKeys = step.getExtensionAttribute(cx_use_cookies);
        String cookieKey = step.getExtensionAttribute(cx_cookies);

        if (saveCookieKey == null) {
            saveCookieKey = cookieKey;
        }

        if (useCookieKeys == null) {
            useCookieKeys = cookieKey;
        }

        // If a redirect response includes cookies, those cookies should be forwarded
        // as appropriate to the redirected location when the redirection is followed.
        CookieStore cookieStore = new BasicCookieStore();
        if (useCookieKeys != null && useCookieKeys.equals(saveCookieKey)) {
            cookieStore = runtime.getCookieStore(useCookieKeys);
        } else if (useCookieKeys != null) {
            CookieStore useCookieStore = runtime.getCookieStore(useCookieKeys);
            for (Cookie cookie : useCookieStore.getCookies()) {
                cookieStore.addCookie(cookie);
            }
        }
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        // FIXME: Is browser compatability the right thing? It's the right thing for my unit test...
        params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

        String timeOutStr = step.getExtensionAttribute(cx_timeout);
        if (timeOutStr != null) {
            params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, Integer.parseInt(timeOutStr));
        }

        if (start.getAttributeValue(_username) != null) {
            String user = start.getAttributeValue(_username);
            String pass = start.getAttributeValue(_password);
            String meth = start.getAttributeValue(_auth_method);

            List<String> authpref;
            if ("basic".equalsIgnoreCase(meth)) {
                authpref = Collections.singletonList(AuthPolicy.BASIC);
            } else if ("digest".equalsIgnoreCase(meth)) {
                authpref = Collections.singletonList(AuthPolicy.DIGEST);
            } else {
                throw XProcException.stepError(3, "Unsupported auth-method: " + meth);
            }

            String host = requestURI.getHost();
            int port = requestURI.getPort();
            AuthScope scope = new AuthScope(host,port);

            UsernamePasswordCredentials cred = new UsernamePasswordCredentials(user, pass);

            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(scope, cred);
            localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
            params.setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, true);
            params.setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);
        }

        iter = start.axisIterator(Axis.CHILD);
        XdmNode body = null;
        while (iter.hasNext()) {
            XdmNode event = (XdmNode) iter.next();
            // FIXME: What about non-whitespace text nodes?
            if (event.getNodeKind() == XdmNodeKind.ELEMENT) {
                if (body != null) {
                    throw new UnsupportedOperationException("Elements follow c:multipart or c:body");
                }

                if (XProcConstants.c_header.equals(event.getNodeName())) {
                    String name = event.getAttributeValue(_name);
                    if (name == null) {
                        continue; // this can't happen, right?
                    }
                    if (name.toLowerCase().equals("content-type")) {
                        // We'll deal with the content-type header later
                        headerContentType = event.getAttributeValue(_value).toLowerCase();
                    } else {
                        headers.add(new BasicHeader(event.getAttributeValue(_name), event.getAttributeValue(_value)));
                    }
                } else if (XProcConstants.c_multipart.equals(event.getNodeName())
                           || XProcConstants.c_body.equals(event.getNodeName())) {
                    body = event;
                } else {
                    throw new UnsupportedOperationException("Unexpected request element: " + event.getNodeName());
                }
            }
        }

        String lcMethod = method.toLowerCase();

        // You can only have a body on PUT or POST
        if (body != null && !("put".equals(lcMethod) || "post".equals(lcMethod))) {
            throw XProcException.stepError(5);
        }

        HttpUriRequest httpRequest;
        HttpResponse httpResult = null;
        if ("get".equals(lcMethod)) {
            httpRequest = doGet();
        } else if ("post".equals(lcMethod)) {
            httpRequest = doPost(body);
        } else if ("put".equals(lcMethod)) {
            httpRequest = doPut(body);
        } else if ("head".equals(lcMethod)) {
            httpRequest = doHead();
        } else if ("delete".equals(lcMethod)) {
            httpRequest = doDelete();
        } else {
            throw new UnsupportedOperationException("Unrecognized http method: " + method);
        }

        TreeWriter tree = new TreeWriter(runtime);

        try {
            // Execute the method.
            HttpClient httpClient = runtime.getHttpClient();
            if (httpClient == null) {
                throw new XProcException("HTTP requests have been disabled");
            }
            httpRequest.setParams(params);
            httpResult = httpClient.execute(httpRequest, localContext);
            int statusCode = httpResult.getStatusLine().getStatusCode();
            HttpHost host = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST);
            URI root = new URI(host.getSchemeName(), null, host.getHostName(), host.getPort(), "/", null, null);
            tree.startDocument(root.resolve(req.getURI()));

            // Deal with cookies
            if (saveCookieKey != null) {
                runtime.setCookieStore(saveCookieKey, cookieStore);
            }

            String contentType = getContentType(httpResult);
            if (overrideContentType != null) {
                if ((xmlContentType(contentType) && overrideContentType.startsWith("image/"))
                    || (contentType.startsWith("text/") && overrideContentType.startsWith("image/"))
                    || (contentType.startsWith("image/") && xmlContentType(overrideContentType))
                    || (contentType.startsWith("image/") && overrideContentType.startsWith("text/"))
                    || (contentType.startsWith("multipart/") && !overrideContentType.startsWith("multipart/"))
                    || (!contentType.startsWith("multipart/") && overrideContentType.startsWith("multipart/"))) {
                    throw XProcException.stepError(30);
                }

                //System.err.println(overrideContentType + " overrides " + contentType);
                contentType = overrideContentType;
            }

            if (detailed) {
                tree.addStartElement(XProcConstants.c_response);
                tree.addAttribute(_status, "" + statusCode);
                tree.startContent();

                for (Header header : httpResult.getAllHeaders()) {
                    // I don't understand why/how HeaderElement parsing works. I get very weird results.
                    // So I'm just going to go the long way around...
                    String h = header.toString();
                    int cp = h.indexOf(":");
                    String name = header.getName();
                    String value = h.substring(cp+1).trim();

                    tree.addStartElement(XProcConstants.c_header);
                    tree.addAttribute(_name, name);
                    tree.addAttribute(_value, value);
                    tree.startContent();
                    tree.addEndElement();
                }

                if (statusOnly) {
                    // Skip reading the result
                } else if (httpResult.getEntity() != null) {
                    // Read the response body.
                    InputStream bodyStream = httpResult.getEntity().getContent();
                    if (bodyStream != null) {
                        readBodyContent(tree, bodyStream, httpResult);
                    }
                }

                tree.addEndElement();
            } else {
                if (statusOnly) {
                    // Skip reading the result
                } else {
                    // Read the response body.
                    if (httpResult.getEntity() != null) {
                        InputStream bodyStream = httpResult.getEntity().getContent();
                        readBodyContent(tree, bodyStream, httpResult);
                    } else {
                        throw XProcException.dynamicError(6);
                    }
                }
            }
        } catch (XProcException e) {
            throw e;
        } catch (Exception e) {
            throw new XProcException(e);
        } finally {
            // Release the connection.
            if (httpResult != null) {
                EntityUtils.consumeQuietly(httpResult.getEntity());
            }
View Full Code Here

        // ATTENTION: This doesn't handle multipart, that's done entirely separately

        // Check for consistency of content-type
        contentType = body.getAttributeValue(_content_type);
        if (contentType == null) {
            throw new XProcException(step.getNode(), "Content-type on c:body is required.");
        }

        String bodyId = body.getAttributeValue(_id);
        String bodyDescription = body.getAttributeValue(_description);
        String bodyDisposition = body.getAttributeValue(_disposition);

        boolean descriptionHeader = false;
        boolean idHeader = false;
        boolean dispositionHeader = false;

        if (bodyDescription != null) {
            for (Header header : headers) {
                if (header.getName().toLowerCase().equals("content-description")) {
                    String headDescription = header.getValue();
                    descriptionHeader = true;
                    if (!bodyDescription.equals(headDescription)) {
                        throw XProcException.stepError(20);
                    }
                }
            }

            if (!descriptionHeader) {
                headers.add(new BasicHeader("Content-Description", bodyDescription));
            }
        }

        if (bodyId != null) {
            for (Header header : headers) {
                if (header.getName().toLowerCase().equals("content-id")) {
                    String headId = header.getValue();
                    idHeader = true;
                    if (!bodyId.equals(headId)) {
                        throw XProcException.stepError(20);
                    }
                }
            }

            if (!idHeader) {
                headers.add(new BasicHeader("Content-Id", bodyId));
            }
        }

        if (bodyDisposition != null) {
            for (Header header : headers) {
                if (header.getName().toLowerCase().equals("content-disposition")) {
                    String headDisposition = header.getValue();
                    dispositionHeader = true;
                    if (!bodyDisposition.equals(headDisposition)) {
                        throw XProcException.stepError(20);
                    }
                }
            }

            if (!dispositionHeader) {
                headers.add(new BasicHeader("Content-Disposition", bodyDisposition));
            }
        }

        if (headerContentType != null && !headerContentType.equals(contentType.toLowerCase())) {
            throw XProcException.stepError(20);
        }

        for (Header header : headers) {
            method.addHeader(header);
        }

        // FIXME: This sucks rocks. I want to write the data to be posted, not provide some way to read it
        String postContent = null;
        String encoding = body.getAttributeValue(_encoding);

        if (encoding != null && !"base64".equals(encoding)) {
            throw XProcException.stepError(52);
        }

        try {
            if ("base64".equals(encoding)) {
                String charset = body.getAttributeValue(_charset);
                // FIXME: is utf-8 the right default?
                if (charset == null) { charset = "utf-8"; }

                // Make sure it's all characters
                XdmSequenceIterator iter = body.axisIterator(Axis.CHILD);
                while (iter.hasNext()) {
                    XdmNode node = (XdmNode) iter.next();
                    if (node.getNodeKind() != XdmNodeKind.TEXT) {
                        throw XProcException.stepError(28);
                    }
                }

                String escapedContent = decodeBase64(body, charset);
                StringWriter writer = new StringWriter();
                writer.write(escapedContent);
                writer.close();
                postContent = writer.toString();
            } else {
                if (jsonContentType(contentType)) {
                    postContent = XMLtoJSON.convert(body);
                } else if (xmlContentType(contentType)) {
                    Serializer serializer = makeSerializer();

                    try {
                        S9apiUtils.assertDocumentContent(body.axisIterator(Axis.CHILD));
                    } catch (XProcException xe) {
                        throw XProcException.stepError(22);
                    }

                    Vector<XdmNode> content = new Vector<XdmNode> ();
                    XdmSequenceIterator iter = body.axisIterator(Axis.CHILD);
                    while (iter.hasNext()) {
                        XdmNode node = (XdmNode) iter.next();
                        content.add(node);
                    }

                    // FIXME: set serializer properties appropriately!
                    StringWriter writer = new StringWriter();
                    serializer.setOutputWriter(writer);
                    S9apiUtils.serialize(runtime, content, serializer);
                    writer.close();
                    postContent = writer.toString();
                } else {
                    StringWriter writer = new StringWriter();
                    XdmSequenceIterator iter = body.axisIterator(Axis.CHILD);
                    while (iter.hasNext()) {
                        XdmNode node = (XdmNode) iter.next();
                        if (node.getNodeKind() != XdmNodeKind.TEXT) {
                            throw XProcException.stepError(28);
                        }
                        writer.write(node.getStringValue());
                    }
                    writer.close();
                    postContent = writer.toString();
                }
            }

            StringEntity requestEntity = new StringEntity(postContent, ContentType.create(contentType, "UTF-8"));
            method.setEntity(requestEntity);

        } catch (IOException ioe) {
            throw new XProcException(ioe);
        } catch (SaxonApiException sae) {
            throw new XProcException(sae);
        }
    }
View Full Code Here

        }

        String boundary = multipart.getAttributeValue(_boundary);

        if (boundary == null) {
            throw new XProcException(step.getNode(), "A boundary value must be specified on c:multipart");
        }

        if (boundary.startsWith("--")) {
            throw XProcException.stepError(2);
        }

        String q = "\"";
        if (boundary.contains(q)) {
            q = "'";
        }
        if (boundary.contains(q)) {
            q = "";
        }

        String multipartContentType = contentType + "; boundary=" + q + boundary + q;

        // FIXME: This sucks rocks. I want to write the data to be posted, not provide some way to read it
        MessageBytes byteContent = new MessageBytes();
        byteContent.append("This is a multipart message.\r\n");
        //String postContent = "This is a multipart message.\r\n";
        for (XdmNode body : new AxisNodes(multipart, Axis.CHILD, AxisNodes.SIGNIFICANT)) {
            if (!XProcConstants.c_body.equals(body.getNodeName())) {
                throw new XProcException(step.getNode(), "A c:multipart may only contain c:body elements.");
            }

            String bodyContentType = body.getAttributeValue(_content_type);
            if (bodyContentType == null) {
                throw new XProcException(step.getNode(), "Content-type on c:body is required.");
            }

            String bodyId = body.getAttributeValue(_id);
            String bodyDescription = body.getAttributeValue(_description);
            String bodyDisposition = body.getAttributeValue(_disposition);

            String bodyCharset = HttpUtils.getCharset(bodyContentType);

            if (bodyContentType.contains(";")) {
                int pos = bodyContentType.indexOf(";");
                bodyContentType = bodyContentType.substring(0, pos);
            }

            String bodyEncoding = body.getAttributeValue(_encoding);
            if (bodyEncoding != null && !"base64".equals(bodyEncoding)) {
                throw new UnsupportedOperationException("The '" + bodyEncoding + "' encoding is not supported");
            }

            if (bodyCharset != null) {
                bodyContentType += "; charset=" + bodyCharset;
            } else {
                // Is utf-8 the right default? What about the image/ case?
                bodyContentType += "; charset=utf-8";
            }

            //postContent += "--" + boundary + "\r\n";
            //postContent += "Content-Type: " + bodyContentType + "\r\n";
            byteContent.append("--" + boundary + "\r\n");
            byteContent.append("Content-Type: " + bodyContentType + "\r\n");

            if (bodyDescription != null) {
                //postContent += "Content-Description: " + bodyDescription + "\r\n";
                byteContent.append("Content-Description: " + bodyDescription + "\r\n");
            }
            if (bodyId != null) {
                //postContent += "Content-ID: " + bodyId + "\r\n";
                byteContent.append("Content-ID: " + bodyId + "\r\n");
            }
            if (bodyDisposition != null) {
                //postContent += "Content-Disposition: " + bodyDisposition + "\r\n";
                byteContent.append("Content-Disposition: " + bodyDisposition + "\r\n");
            }
            if (bodyEncoding != null) {
                //postContent += "Content-Transfer-Encoding: " + bodyEncoding + "\r\n";
                if (encodeBinary) {
                    byteContent.append("Content-Transfer-Encoding: " + bodyEncoding + "\r\n");
                }
            }
            //postContent += "\r\n";
            byteContent.append("\r\n");

            try {
                if (xmlContentType(bodyContentType)) {
                    Serializer serializer = makeSerializer();

                    Vector<XdmNode> content = new Vector<XdmNode> ();
                    XdmSequenceIterator iter = body.axisIterator(Axis.CHILD);
                    while (iter.hasNext()) {
                        XdmNode node = (XdmNode) iter.next();
                        content.add(node);
                    }

                    // FIXME: set serializer properties appropriately!
                    StringWriter writer = new StringWriter();
                    serializer.setOutputWriter(writer);
                    S9apiUtils.serialize(runtime, content, serializer);
                    writer.close();
                    //postContent += writer.toString();
                    byteContent.append(writer.toString());
                } else if (jsonContentType(contentType)) {
                    byteContent.append(XMLtoJSON.convert(body));
                } else if (!encodeBinary && "base64".equals(bodyEncoding)) {
                    byte[] decoded = Base64.decode(body.getStringValue());
                    byteContent.append(decoded, decoded.length);
                } else {
                    StringWriter writer = new StringWriter();
                    XdmSequenceIterator iter = body.axisIterator(Axis.CHILD);
                    while (iter.hasNext()) {
                        XdmNode node = (XdmNode) iter.next();
                        if (node.getNodeKind() != XdmNodeKind.TEXT) {
                            throw XProcException.stepError(28);
                        }
                        writer.write(node.getStringValue());
                    }
                    writer.close();
                    //postContent += writer.toString();
                    byteContent.append(writer.toString());
                }

                //postContent += "\r\n";
                byteContent.append("\r\n");
            } catch (IOException ioe) {
                throw new XProcException(ioe);
            } catch (SaxonApiException sae) {
                throw new XProcException(sae);
            }
        }

        //postContent += "--" + boundary + "--\r\n";
        byteContent.append("--" + boundary + "--\r\n");
View Full Code Here

                        tree.endDocument();

                        XdmNode doc = tree.getResult();
                        result.write(doc);
                    } catch (SaxonApiException sae) {
                        throw new XProcException(sae);
                    }
                }
            });
        } catch (FileNotFoundException fnfe) {
            throw new XProcException(fnfe);
        } catch (IOException ioe) {
            throw new XProcException(ioe);
        }
    }
View Full Code Here

TOP

Related Classes of com.xmlcalabash.core.XProcException

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.