Example #1
0
 public void testAll() throws Exception {
   XMLHelper xmlHelper = new XMLHelper();
   ClassLoader cl = Thread.currentThread().getContextClassLoader();
   InputStream is = cl.getResourceAsStream("org/hibernate/test/annotations/reflection/orm.xml");
   assertNotNull("ORM.xml not found", is);
   XMLContext context = new XMLContext();
   List errors = new ArrayList();
   SAXReader saxReader =
       xmlHelper.createSAXReader("XML InputStream", errors, EJB3DTDEntityResolver.INSTANCE);
   // saxReader.setValidation( false );
   try {
     saxReader.setFeature("http://apache.org/xml/features/validation/schema", true);
   } catch (SAXNotSupportedException e) {
     saxReader.setValidation(false);
   }
   org.dom4j.Document doc;
   try {
     doc = saxReader.read(new InputSource(new BufferedInputStream(is)));
   } finally {
     try {
       is.close();
     } catch (IOException ioe) {
       // log.warn( "Could not close input stream", ioe );
     }
   }
   assertEquals(0, errors.size());
   context.addDocument(doc);
 }
  @Test
  public void html() throws Exception {
    String subject = "html";
    buildSMTPAppender(subject, SYNCHRONOUS);
    smtpAppender.setAsynchronousSending(false);
    smtpAppender.setLayout(buildHTMLLayout());
    smtpAppender.start();
    logger.addAppender(smtpAppender);
    logger.debug("html");
    logger.error("en error", new Exception("an exception"));

    MimeMultipart mp = verifyAndExtractMimeMultipart(subject);

    // verifyAndExtractMimeMultipart strict adherence to xhtml1-strict.dtd
    SAXReader reader = new SAXReader();
    reader.setValidation(true);
    reader.setEntityResolver(new XHTMLEntityResolver());
    byte[] messageBytes = getAsByteArray(mp.getBodyPart(0).getInputStream());
    ByteArrayInputStream bais = new ByteArrayInputStream(messageBytes);
    try {
      reader.read(bais);
    } catch (DocumentException de) {
      System.out.println("incoming message:");
      System.out.println(new String(messageBytes));
      throw de;
    }
  }
Example #3
0
 private Document getDocument() {
   // TODO Auto-generated method stub
   InputStream is = getFileStream();
   try {
     if (document == null) {
       SAXReader sr = new SAXReader();
       sr.setValidation(false);
       if (is == null) {
         throw new RuntimeException("can not find config File..." + configFile);
       }
       document = sr.read(is);
     }
   } catch (Exception e) {
     LOGGER.error(e.getMessage(), e);
     throw new RuntimeException("get xml file failed");
   } finally {
     if (is != null) {
       try {
         is.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
   return document;
 }
 public ValidatorSaxHandler(File filePath) throws DocumentException {
   super();
   SAXReader reader = new SAXReader();
   reader.setValidation(false);
   reader.setIncludeInternalDTDDeclarations(false);
   reader.setIncludeExternalDTDDeclarations(false);
   reader.setEntityResolver(new NoDtdEntityResolver());
   document = reader.read(filePath);
 }
Example #5
0
 /**
  * 处理XML头部采用DTD验证, 以下设置忽略验证,否则无法取到节点信息
  *
  * @param reader document解析器
  */
 private static void setReaderValidation(SAXReader reader) {
   // 处理XML头部采用DTD验证, 以下设置忽略验证,否则无法取到节点信息
   reader.setValidation(false);
   reader.setEntityResolver(
       new EntityResolver() {
         public InputSource resolveEntity(String publicId, String systemId)
             throws SAXException, IOException {
           return new InputSource(new StringReader(""));
         }
       });
 }
Example #6
0
  public static org.dom4j.Element readStrToDOM4J(final String data) throws Exception {
    SAXReader saxReader = new SAXReader();

    saxReader.setValidation(false);
    saxReader.setStripWhitespaceText(true);
    saxReader.setFeature("http://xml.org/sax/features/namespaces", false);
    saxReader.getXMLReader().setFeature("http://xml.org/sax/features/namespaces", false);

    // saxReader.setFeature("http://apache.org/xml/features/validation/schema", false);
    // saxReader.setFeature("http://xml.org/sax/features/validation", false);
    // saxReader.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
    //                   (FormViewFactory.class.getResource("../form.xsd")).getPath());

    org.dom4j.Document document = saxReader.read(new StringReader(data));
    return document.getRootElement();
  }
  /**
   * Constructor
   *
   * @param request HttpServletRequest
   */
  public VtiSoapRequest(HttpServletRequest request) {
    super(request);
    try {
      SAXReader reader = new SAXReader();
      reader.setValidation(false);
      document = reader.read(request.getInputStream());

      String ns = document.getRootElement().getNamespaceURI();
      if (SOAP_11_ENVELOPE_NS.equals(ns)) {
        version = "1.1";
      } else if (SOAP_12_ENVELOPE_NS.equals(ns)) {
        version = "1.2";
      }
    } catch (Exception e) {
      document = null;
    }
  }
  @Test
  public void html() throws Exception {
    buildSMTPAppender(smtpServer.getSmtp().getPort(), SYNCHRONOUS);
    smtpAppender.setAsynchronousSending(false);
    smtpAppender.setLayout(buildHTMLLayout(lc));
    smtpAppender.start();
    logger.addAppender(smtpAppender);
    logger.debug("hello");
    logger.error("an error", new Exception("an exception"));

    MimeMultipart mp = verify(smtpServer, TEST_SUBJECT);

    // verify strict adherence to xhtml1-strict.dtd
    SAXReader reader = new SAXReader();
    reader.setValidation(true);
    reader.setEntityResolver(new XHTMLEntityResolver());
    reader.read(mp.getBodyPart(0).getInputStream());
  }
  /*
   * (non-Javadoc)
   *
   * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
   */
  public void init(FilterConfig filterConfig) throws ServletException {
    FileInputStream in = null;

    try {
      xSendFileKey = filterConfig.getInitParameter("xSendFileKey");
      if (StringUtils.isBlank(xSendFileKey)) {
        xSendFileKey = "X-Accel-Redirect";
      }
      if ("web".equals(xSendFileKey)) {
        pagesLocation = filterConfig.getServletContext().getRealPath("/");
        pagesLocation = pagesLocation.replace(File.separatorChar, '/');
        prefix = filterConfig.getInitParameter("pagesLocation");
        if (StringUtils.isBlank(prefix)) {
          prefix = "/p";
          pagesLocation += "p";
        } else {
          if (prefix.startsWith("/")) {
            pagesLocation += prefix.substring(1);
          } else {
            pagesLocation += prefix;
            prefix = "/" + prefix;
          }
        }
      } else {
        pagesLocation = filterConfig.getInitParameter("pagesLocation");
        if (StringUtils.isBlank(pagesLocation)) {
          throw new ServletException("静态化页面存放位置没有配置");
        }
        if (pagesLocation.endsWith("/")) {
          pagesLocation = pagesLocation.substring(0, pagesLocation.length() - 1);
        }
        int idx = pagesLocation.lastIndexOf('/');
        if (idx != -1) {
          prefix = pagesLocation.substring(idx);
        }
      }

      defaultHost = filterConfig.getInitParameter("defaultHost");
      if (StringUtils.isBlank(defaultHost)) {
        defaultHost = "localhost";
      }

      in = new FileInputStream(filterConfig.getServletContext().getRealPath(pageMappingFile));
      SAXReader reader = new SAXReader();
      reader.setValidation(false);
      Document doc = reader.read(in);
      Element root = doc.getRootElement();

      if (root != null) {
        Element element = null;
        Page page = null;
        int beginIndex = 0;
        int endIndex = 0;
        String paramName = null;
        Iterator<Element> it = root.elementIterator();

        while (it.hasNext()) {
          beginIndex = 0;
          endIndex = 0;
          page = new Page();
          element = it.next();
          page.url = element.elementTextTrim("url");
          page.path = element.elementTextTrim("path");
          page.paramNames = new LinkedList<String>();

          while (true) {
            beginIndex = page.path.indexOf("${", beginIndex);

            if (beginIndex < 0) {
              break;
            }

            endIndex = page.path.indexOf("}", beginIndex);

            if (endIndex < 0) {
              break;
            }

            paramName = page.path.substring(beginIndex + 2, endIndex);
            page.paramNames.add(paramName);
            page.path =
                page.path.replace("${" + paramName + "}", "%" + page.paramNames.size() + "$s");
          }

          try {
            page.cronExpression = new CronExpression(element.elementTextTrim("cronExpression"));
          } catch (Exception ex) {
          }
          try {
            page.refreshInterval =
                Long.parseLong(element.elementTextTrim("refreshInterval")) * 1000;
          } catch (Exception ex) {
            page.refreshInterval = Long.MAX_VALUE;
          }

          page.description = element.elementTextTrim("description");
          pageMappings.put(page.url, page);
        }
      }
    } catch (Exception ex) {
      throw new ServletException(ex);
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (Exception ex) {
        }
      }
    }
  }
  public static DocumentCacheItem doc2DocumentCacheItem(BasicDBObject doc) {
    try {
      String itemId = doc.get("item_id").toString();

      XMLConfig extra = null;
      if (doc.get("item_extra") != null) {
        extra = new XMLConfig();
        extra.loadString(doc.get("item_extra").toString());
      }

      HashMap<String, String> params = new HashMap<String, String>();
      HashMap<String, String> metas = new HashMap<String, String>();

      Document document = null;
      SAXReader reader = new SAXReader();
      reader.setValidation(false);
      try {
        document = reader.read(new StringReader(doc.get("item_params").toString()));

        Element elmParams = (Element) document.selectSingleNode("params");
        if (elmParams != null) {
          List<Element> items = elmParams.elements();
          Iterator<Element> iterItems = items.iterator();
          while (iterItems.hasNext()) {
            Element item = (Element) iterItems.next();
            params.put(item.getName(), item.getText());
          }
        }
      } catch (DocumentException de) {
        IOException ioe = new IOException();
        ioe.initCause(de);
        throw ioe;
      }

      reader = new SAXReader();
      reader.setValidation(false);
      try {
        document = reader.read(new StringReader(doc.get("item_metas").toString()));

        Element elmMetas = (Element) document.selectSingleNode("metas");
        if (elmMetas != null) {
          List<Element> items = elmMetas.elements();
          Iterator<Element> iterItems = items.iterator();
          while (iterItems.hasNext()) {
            Element item = (Element) iterItems.next();
            metas.put(
                item.getName()
                    .replace(':', '_')
                    .replace('-', '_')
                    .replace('.', '_')
                    .replace('/', '_'),
                item.getText());
          }
        }
      } catch (DocumentException de) {
        IOException ioe = new IOException();
        ioe.initCause(de);
        throw ioe;
      }

      InputStream inputSource =
          new ByteArrayInputStream(doc.get("content_base64").toString().getBytes());
      InputStream streamData = new Base64.InputStream(inputSource, Base64.DECODE);

      return new DocumentCacheItem(itemId, streamData, params, metas, extra);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }