Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (c) 2005 Henri Sivonen
   * Copyright (c) 2007-2015 Mozilla Foundation
   *
   * Permission is hereby granted, free of charge, to any person obtaining a 
   * copy of this software and associated documentation files (the "Software"), 
   * to deal in the Software without restriction, including without limitation 
   * the rights to use, copy, modify, merge, publish, distribute, sublicense, 
   * and/or sell copies of the Software, and to permit persons to whom the 
  * Software is furnished to do so, subject to the following conditions:
  *
  * The above copyright notice and this permission notice shall be included in 
  * all copies or substantial portions of the Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
  * DEALINGS IN THE SOFTWARE.
  */
 
 package nu.validator.xml;
 
 
 
 

Author(s):
hsivonen
Version:
$Id: PrudentHttpEntityResolver.java,v 1.1 2005/01/08 08:11:26 hsivonen Exp $
 
 @SuppressWarnings("deprecation")
 public class PrudentHttpEntityResolver implements EntityResolver {
 
     private static final Logger log4j = Logger.getLogger(PrudentHttpEntityResolver.class);
 
 
     private static final HttpClient client = new HttpClient();
 
     private static int maxRequests;
 
     private long sizeLimit;
 
     private final ErrorHandler errorHandler;
 
     private int requestsLeft;
 
     private boolean laxContentType;
 
     private boolean allowRnc = false;
 
     private boolean allowHtml = false;
 
     private boolean allowXhtml = false;
 
     private boolean acceptAllKnownXmlTypes = false;
 
     private boolean allowGenericXml = true;
 
     private final ContentTypeParser contentTypeParser;
 
     static {
         if ("true".equals(System.getProperty(
                 "nu.validator.xml.promiscuous-ssl""false"))) {
             Protocol.registerProtocol("https"new Protocol("https",
                     new PromiscuousSSLProtocolSocketFactory(), 443));
         }
     }

    
Sets the timeouts of the HTTP client.

Parameters:
connectionTimeout timeout until connection established in milliseconds. Zero means no timeout.
socketTimeout timeout for waiting for data in milliseconds. Zero means no timeout.
    public static void setParams(int connectionTimeoutint socketTimeout,
            int maxRequests) {
        hcmp.setConnectionTimeout(connectionTimeout);
        hcmp.setSoTimeout(socketTimeout);
                maxRequests);
        hcmp.setMaxTotalConnections(200); // XXX take this from a property
        . = maxRequests;
        HttpClientParams hcp = .getParams();
        hcp.setIntParameter(., 20); // Gecko
        // default
    }
    public static void setUserAgent(String ua) {
        .getParams().setParameter("http.useragent"ua);
    }

    

Parameters:
sizeLimit
laxContentType
errorHandler
    public PrudentHttpEntityResolver(long sizeLimitboolean laxContentType,
            ErrorHandler errorHandler) {
        this. = sizeLimit;
        this. = ;
        this. = laxContentType;
        this. = errorHandler;
        this. = new ContentTypeParser(errorHandler,
                laxContentTypethis.this.this.,
                this.this.);
    }

    
    public InputSource resolveEntity(String publicIdString systemId)
            throws SAXExceptionIOException {
        if ( > -1) {
            if ( == 0) {
                throw new IOException(
                        "Number of permitted HTTP requests exceeded.");
            } else {
                --;
            }
        }
        GetMethod m = null;
        try {
            URL url;
            try {
                url = URL.parse(systemId);
            } catch (GalimatiasParseException e) {
                IOException ioe = (IOExceptionnew IOException(e.getMessage()).initCause(e);
                SAXParseException spe = new SAXParseException(e.getMessage(),
                        publicIdsystemId, -1, -1, ioe);
                if ( != null) {
                    .fatalError(spe);
                }
                throw spe;
            }
            String scheme = url.scheme();
            if (!("http".equals(scheme) || "https".equals(scheme))) {
                String msg = "Unsupported URI scheme: \u201C" + scheme
                        + "\u201D.";
                SAXParseException spe = new SAXParseException(msgpublicId,
                        systemId, -1, -1, new IOException(msg));
                if ( != null) {
                    .fatalError(spe);
                }
                throw spe;
            }
            systemId = url.toString();
            try {
                m = new GetMethod(systemId);
            } catch (IllegalArgumentException e) {
                SAXParseException spe = new SAXParseException(
                        e.getMessage(),
                        publicId,
                        systemId,
                        -1,
                        -1,
                        (IOExceptionnew IOException(e.getMessage()).initCause(e));
                if ( != null) {
                    .fatalError(spe);
                }
                throw spe;
            }
            m.setFollowRedirects(true);
            m.addRequestHeader("Accept"buildAccept());
            m.addRequestHeader("Accept-Encoding""gzip");
            .info(systemId);
            .executeMethod(m);
            int statusCode = m.getStatusCode();
            if (statusCode != 200) {
                String msg = "HTTP resource not retrievable. The HTTP status from the remote server was: "
                        + statusCode + ".";
                SAXParseException spe = new SAXParseException(msgpublicId,
                        m.getURI().toString(), -1, -1, new IOException(msg));
                if ( != null) {
                    .fatalError(spe);
                }
                throw spe;
            }
            long len = m.getResponseContentLength();
            if ( > -1 && len > ) {
                SAXParseException spe = new SAXParseException(
                        "Resource size exceeds limit.",
                        publicId,
                        m.getURI().toString(),
                        -1,
                        -1,
                        new StreamBoundException("Resource size exceeds limit."));
                if ( != null) {
                    .fatalError(spe);
                }
                throw spe;
            }
            TypedInputSource is;
            Header ct = m.getResponseHeader("Content-Type");
            String contentType = null;
            final String baseUri = m.getURI().toString();
            if (ct != null) {
                contentType = ct.getValue();
            }
            is = .buildTypedInputSource(baseUripublicId,
                    contentType);
            
            Header cl = m.getResponseHeader("Content-Language");
            if (cl != null) {
                is.setLanguage(cl.getValue().trim());
            }
            Header xuac = m.getResponseHeader("X-UA-Compatible");
            if (xuac != null) {
                String val = xuac.getValue().trim();
                if (!"ie=edge".equalsIgnoreCase(val)) {
                    SAXParseException spe = new SAXParseException(
                            "X-UA-Compatible HTTP header must have the value \u201CIE=edge\u201D,"
                                + " was \u201C" + val + "\u201D.",
                            publicIdsystemId, -1, -1);
                    .error(spe);
                }
            }
            final GetMethod meth = m;
            InputStream stream = m.getResponseBodyAsStream();
            if ( > -1) {
                stream = new BoundedInputStream(streambaseUri);
            }
            Header ce = m.getResponseHeader("Content-Encoding");
            if (ce != null) {
                String val = ce.getValue().trim();
                if ("gzip".equalsIgnoreCase(val)
                        || "x-gzip".equalsIgnoreCase(val)) {
                    stream = new GZIPInputStream(stream);
                    if ( > -1) {
                        stream = new BoundedInputStream(stream,
                                baseUri);
                    }
                }
            }
            is.setByteStream(new ObservableInputStream(stream,
                    new StreamObserver() {
                        private final Logger log4j = Logger.getLogger("nu.validator.xml.PrudentEntityResolver.StreamObserver");
                        private boolean released = false;
                        public void closeCalled() {
                            .debug("closeCalled");
                            if (!) {
                                .debug("closeCalled, not yet released");
                                 = true;
                                try {
                                    meth.releaseConnection();
                                } catch (Exception e) {
                                    .debug(
                                            "closeCalled, releaseConnection"e);
                                }
                            }
                        }
                        public void exceptionOccurred(Exception ex)
                                throws IOException {
                            if (!) {
                                 = true;
                                try {
                                    meth.abort();
                                } catch (Exception e) {
                                    .debug("exceptionOccurred, abort"e);
                                } finally {
                                    try {
                                        meth.releaseConnection();
                                    } catch (Exception e) {
                                        .debug(
                                                "exceptionOccurred, releaseConnection",
                                                e);
                                    }
                                }
                            }
                            if (ex instanceof SystemIdIOException) {
                                SystemIdIOException siie = (SystemIdIOExceptionex;
                                throw siie;
                            } else if (ex instanceof IOException) {
                                IOException ioe = (IOExceptionex;
                                throw new SystemIdIOException(baseUri,
                                        ioe.getMessage(), ioe);
                            } else if (ex instanceof RuntimeException) {
                                RuntimeException re = (RuntimeExceptionex;
                                throw re;
                            } else {
                                throw new RuntimeException(
                                        "API contract violation. Wrong exception type.",
                                        ex);
                            }
                        }
                        public void finalizerCalled() {
                            if (!) {
                                 = true;
                                try {
                                    meth.abort();
                                } catch (Exception e) {
                                    .debug("finalizerCalled, abort"e);
                                } finally {
                                    try {
                                        meth.releaseConnection();
                                    } catch (Exception e) {
                                        .debug(
                                                "finalizerCalled, releaseConnection",
                                                e);
                                    }
                                }
                            }
                        }
                    }));
            return is;
        } catch (IOException e) {
            if (m != null) {
                try {
                    m.abort();
                } catch (Exception ex) {
                    .debug("abort"ex);
                } finally {
                    try {
                        m.releaseConnection();
                    } catch (Exception ex) {
                        .debug("releaseConnection"ex);
                    }
                }
            }
            throw e;
        } catch (SAXException e) {
            if (m != null) {
                try {
                    m.abort();
                } catch (Exception ex) {
                    .debug("abort"ex);
                } finally {
                    try {
                        m.releaseConnection();
                    } catch (Exception ex) {
                        .debug("releaseConnection"ex);
                    }
                }
            }
            throw e;
        } catch (RuntimeException e) {
            if (m != null) {
                try {
                    m.abort();
                } catch (Exception ex) {
                    .debug("abort"ex);
                } finally {
                    try {
                        m.releaseConnection();
                    } catch (Exception ex) {
                        .debug("releaseConnection"ex);
                    }
                }
            }
            throw e;
        }
    }

    

Returns:
Returns the allowRnc.
    public boolean isAllowRnc() {
        return ;
    }

    

Parameters:
allowRnc The allowRnc to set.
    public void setAllowRnc(boolean allowRnc) {
        this. = allowRnc;
        this..setAllowRnc(allowRnc);
    }

    

Parameters:
allowHtml
    public void setAllowHtml(boolean allowHtml) {
        this. = allowHtml;
        this..setAllowHtml(allowHtml);
    }

    
Returns the acceptAllKnownXmlTypes.

Returns:
the acceptAllKnownXmlTypes
    public boolean isAcceptAllKnownXmlTypes() {
        return ;
    }

    
Sets the acceptAllKnownXmlTypes.

Parameters:
acceptAllKnownXmlTypes the acceptAllKnownXmlTypes to set
    public void setAcceptAllKnownXmlTypes(boolean acceptAllKnownXmlTypes) {
        this. = acceptAllKnownXmlTypes;
        this..setAcceptAllKnownXmlTypes(acceptAllKnownXmlTypes);
    }

    
Returns the allowGenericXml.

Returns:
the allowGenericXml
    public boolean isAllowGenericXml() {
        return ;
    }

    
Sets the allowGenericXml.

Parameters:
allowGenericXml the allowGenericXml to set
    public void setAllowGenericXml(boolean allowGenericXml) {
        this. = allowGenericXml;
        this..setAllowGenericXml(allowGenericXml);
    }

    
Returns the allowXhtml.

Returns:
the allowXhtml
    public boolean isAllowXhtml() {
        return ;
    }

    
Sets the allowXhtml.

Parameters:
allowXhtml the allowXhtml to set
    public void setAllowXhtml(boolean allowXhtml) {
        this. = allowXhtml;
        this..setAllowXhtml(allowXhtml);
    }
    private String buildAccept() {
        return "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
    }

    
Returns the allowHtml.

Returns:
the allowHtml
    public boolean isAllowHtml() {
        return ;
    }
    public boolean isOnlyHtmlAllowed() {
        return !isAllowGenericXml() && !isAllowRnc() && !isAllowXhtml();
    }
New to GrepCode? Check out our FAQ X