/**
   * Reports a failure if reading the given resource does <U>not</U> cause the expected exception at
   * the expected location.
   */
  private void assertException(String resource, int expectedLine, String expectedMsg) {
    Throwable failure = null;
    try {
      generatorSetResources_.read(resource);
    } catch (Throwable t) {
      failure = t;
    }

    if (failure == null) {
      fail("Expected exception not thrown.");
    }

    Throwable cause;
    for (cause = failure.getCause();
        !(cause == null || cause instanceof SAXParseException);
        cause = cause.getCause()) ;

    if (cause == null) {
      throw new RuntimeException("Unexpected exception thrown", failure);
    }

    SAXParseException spe = (SAXParseException) cause;
    assertEquals("Exception line", expectedLine, spe.getLineNumber());

    String actualMsg =
        spe.getException() == null ? spe.getMessage() : spe.getException().getMessage();
    assertEquals("Exception message", expectedMsg, actualMsg);
  }
  public void updateList(String fileName, int corridorSize) {
    tilesToDownload.clear();
    File file = new File(fileName);
    if (file.exists() && file.isFile()) {
      try {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true); // never forget this!
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document document = builder.parse(file);

        Node gpxNode = document.getFirstChild();
        if (!gpxNode.getNodeName().equalsIgnoreCase("gpx")) {
          throw new RuntimeException("invalid file!");
        }

        // Object result = expr.evaluate(document, XPathConstants.NODESET);
        // NodeList nodes = (NodeList) result;
        NodeList nodes = gpxNode.getChildNodes();
        int detectedTrackNumber = 0;
        for (int i = 0; i < nodes.getLength(); i++) {
          if (nodes.item(i).getLocalName() != null
              && nodes.item(i).getLocalName().equalsIgnoreCase("trk")) {
            detectedTrackNumber++;
            // if (detectedTrackNumber == 1) {
            // Download all zoomlevels
            for (int zoomLevel : getDownloadZoomLevels()) {
              // handle all trgSegments
              NodeList trkSegs = nodes.item(i).getChildNodes();
              for (int indexTrkSeg = 0; indexTrkSeg < trkSegs.getLength(); indexTrkSeg++) {
                if (trkSegs.item(indexTrkSeg).getLocalName() != null
                    && trkSegs.item(indexTrkSeg).getLocalName().equalsIgnoreCase("trkseg")) {
                  // handle all trkpts
                  NodeList trkPts = trkSegs.item(indexTrkSeg).getChildNodes();
                  for (int indexTrkPt = 0; indexTrkPt < trkPts.getLength(); indexTrkPt++) {
                    if (trkPts.item(indexTrkPt).getLocalName() != null
                        && trkPts.item(indexTrkPt).getLocalName().equalsIgnoreCase("trkpt")) {
                      handleTrkPt(trkPts.item(indexTrkPt), zoomLevel, corridorSize);
                    }
                  }
                }
              }
            }
            // }
          }
        }
      } catch (SAXParseException spe) {
        Exception e = (spe.getException() != null) ? spe.getException() : spe;
        log.log(
            Level.SEVERE, "Error parsing " + spe.getSystemId() + " line " + spe.getLineNumber(), e);
      } catch (SAXException sxe) {
        Exception e = (sxe.getException() != null) ? sxe.getException() : sxe;
        log.log(Level.SEVERE, "Error parsing GPX", e);
      } catch (ParserConfigurationException pce) {
        log.log(Level.SEVERE, "Error in parser configuration", pce);
      } catch (IOException ioe) {
        log.log(Level.SEVERE, "Error parsing GPX", ioe);
      }
    }
  }
Ejemplo n.º 3
0
  public ByteArrayOutputStream cleanup(InputStream xml) throws XServerException {
    inputXml = xml;

    // Use the default (non-validating) parser
    SAXParserFactory factory = SAXParserFactory.newInstance();

    try {
      // Parse the input
      SAXParser saxParser = factory.newSAXParser();
      saxParser.parse(inputXml, this);

      // close the stream
      inputXml.close();
    } catch (SAXParseException spe) {
      // Use the contained exception, if any
      Exception x = spe;

      if (spe.getException() != null) {
        x = spe.getException();
      }

      // Error generated by the parser
      LOG.warn(
          "XMLCleanup.cleanup() parsing exception: "
              + spe.getMessage()
              + " - xml line "
              + spe.getLineNumber()
              + ", uri "
              + spe.getSystemId(),
          x);
    } catch (SAXException sxe) {
      // Error generated by this application
      // (or a parser-initialization error)
      Exception x = sxe;

      if (sxe.getException() != null) {
        x = sxe.getException();
      }

      LOG.warn("XMLCleanup.cleanup() SAX exception: " + sxe.getMessage(), x);
    } catch (ParserConfigurationException pce) {
      // Parser with specified options can't be built
      LOG.warn("XMLCleanup.cleanup() SAX parser cannot be built with " + "specified options");
    } catch (IOException ioe) {
      // I/O error
      LOG.warn("XMLCleanup.cleanup() IO exception", ioe);
    } catch (Throwable t) {
      LOG.warn("XMLCleanup.cleanup() exception", t);
    }

    if (error) {
      throw new XServerException(error_code, error_text);
    }

    return bytes;
  }
 private MarshalSAXParseException marshalSAXParseException(SAXParseException exception) {
   return new MarshalSAXParseException(
       exception.getLocalizedMessage(),
       exception.getPublicId(),
       exception.getSystemId(),
       exception.getLineNumber(),
       exception.getColumnNumber(),
       exception.getException(),
       marshalRecord.getOwningObject());
 }
 /** Constructor. */
 protected XMLContentHandler(String eventFile, String agentFile) {
   myEngine = EventEngine.theStack;
   agentTable = new Hashtable();
   try {
     XMLReader saxParser =
         (XMLReader) Class.forName("org.apache.xerces.parsers.SAXParser").newInstance();
     saxParser.setContentHandler(this);
     saxParser.setFeature("http://xml.org/sax/features/validation", true);
     // parse the xml specification for the event tags.
     saxParser.parse(agentFile);
     saxParser.parse(eventFile);
   } catch (SAXParseException spe) {
     // Error generated by the parser
     System.out.println(
         "\n** Parsing error" + ", line " + spe.getLineNumber() + ", uri " + spe.getSystemId());
     System.out.println("   " + spe.getMessage());
     // Use the contained exception, if any
     Exception x = spe;
     if (spe.getException() != null) x = spe.getException();
     x.printStackTrace();
     System.exit(0);
   } catch (SAXException sxe) {
     // Error generated by this application
     // (or a parser-initialization error)
     Exception x = sxe;
     if (sxe.getException() != null) x = sxe.getException();
     x.printStackTrace();
     System.exit(0);
   } catch (IOException ioe) {
     // I/O error
     ioe.printStackTrace();
     System.exit(0);
   } catch (Exception pce) {
     // Parser with specified options can't be built
     pce.printStackTrace();
     System.exit(0);
   }
 }
Ejemplo n.º 6
0
  public static Source readXMLFile(String xmlFileName) {

    Source domSource = null;

    try {
      Document domDoc = builder.parse(new File(xmlFileName));
      domSource = new javax.xml.transform.dom.DOMSource(domDoc);

    } catch (SAXParseException spe) {
      // Error generated by the parser
      System.out.println(
          "\n** Parsing error" + ", line " + spe.getLineNumber() + ", uri " + spe.getSystemId());
      System.out.println("  " + spe.getMessage());

      // Use the contained exception, if any
      Exception x = spe;
      if (spe.getException() != null) x = spe.getException();
      x.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }

    return domSource;
  }
Ejemplo n.º 7
0
  private void propagateEvent(int severity, SAXParseException saxException) throws SAXException {

    // get location info:
    //     sax locators simply use the location info embedded in the
    //     sax exception, dom locators keep a reference to their DOMScanner
    //     and call back to figure out where the error occurred.
    ValidationEventLocator vel = locator.getLocation(saxException);

    ValidationEventImpl ve = new ValidationEventImpl(severity, saxException.getMessage(), vel);

    Exception e = saxException.getException();
    if (e != null) {
      ve.setLinkedException(e);
    } else {
      ve.setLinkedException(saxException);
    }

    // call the client's event handler.
    host.handleEvent(ve, severity != ValidationEvent.FATAL_ERROR);
  }
  private void processFile(String currentFile) throws DITAOTException {
    File fileToParse;
    final File file = new File(currentFile);
    if (file.isAbsolute()) {
      fileToParse = file;
      currentFile = FileUtils.getRelativePath(rootFile, currentFile);
    } else {
      fileToParse = new File(baseInputDir, currentFile);
    }
    try {
      fileToParse = fileToParse.getCanonicalFile();
    } catch (final IOException e1) {
      logger.logError(e1.toString());
    }
    logger.logInfo("Processing " + fileToParse.getAbsolutePath());
    String msg = null;
    final Properties params = new Properties();
    params.put("%1", currentFile);

    if (!fileToParse.exists()) {
      logger.logError(MessageUtils.getMessage("DOTX008E", params).toString());
      return;
    }
    try {
      if (FileUtils.isValidTarget(currentFile.toLowerCase())) {
        reader.setTranstype(transtype);
        reader.setCurrentDir(new File(currentFile).getParent());
        reader.parse(fileToParse);

      } else {
        // edited by Alan on Date:2009-11-02 for Work Item:#1590 start
        // logger.logWarn("Input file name is not valid DITA file name.");
        final Properties prop = new Properties();
        prop.put("%1", fileToParse);
        logger.logWarn(MessageUtils.getMessage("DOTJ053W", params).toString());
        // edited by Alan on Date:2009-11-02 for Work Item:#1590 end
      }

      // don't put it into dita.list if it is invalid
      if (reader.isValidInput()) {
        processParseResult(currentFile);
        categorizeCurrentFile(currentFile);
      } else if (!currentFile.equals(inputFile)) {
        logger.logWarn(MessageUtils.getMessage("DOTJ021W", params).toString());
      }
    } catch (final SAXParseException sax) {

      // To check whether the inner third level is DITAOTBuildException
      // :FATALERROR
      final Exception inner = sax.getException();
      if (inner != null && inner instanceof DITAOTException) { // second
        // level
        logger.logInfo(inner.getMessage());
        throw (DITAOTException) inner;
      }
      if (currentFile.equals(inputFile)) {
        // stop the build if exception thrown when parsing input file.
        final MessageBean msgBean = MessageUtils.getMessage("DOTJ012F", params);
        msg = MessageUtils.getMessage("DOTJ012F", params).toString();
        msg = new StringBuffer(msg).append(":").append(sax.getMessage()).toString();
        throw new DITAOTException(msgBean, sax, msg);
      }
      final StringBuffer buff = new StringBuffer();
      msg = MessageUtils.getMessage("DOTJ013E", params).toString();
      buff.append(msg).append(LINE_SEPARATOR).append(sax.getMessage());
      logger.logError(buff.toString());
    } catch (final Exception e) {

      if (currentFile.equals(inputFile)) {
        // stop the build if exception thrown when parsing input file.
        final MessageBean msgBean = MessageUtils.getMessage("DOTJ012F", params);
        msg = MessageUtils.getMessage("DOTJ012F", params).toString();
        msg = new StringBuffer(msg).append(":").append(e.getMessage()).toString();
        throw new DITAOTException(msgBean, e, msg);
      }
      final StringBuffer buff = new StringBuffer();
      msg = MessageUtils.getMessage("DOTJ013E", params).toString();
      buff.append(msg).append(LINE_SEPARATOR).append(e.getMessage());
      logger.logError(buff.toString());
    }

    if (!reader.isValidInput() && currentFile.equals(inputFile)) {

      if (xmlValidate == true) {
        // stop the build if all content in the input file was filtered
        // out.
        msg = MessageUtils.getMessage("DOTJ022F", params).toString();
        throw new DITAOTException(msg);
      } else {
        // stop the build if the content of the file is not valid.
        msg = MessageUtils.getMessage("DOTJ034F", params).toString();
        throw new DITAOTException(msg);
      }
    }

    doneList.add(currentFile);
    reader.reset();
  }
  /**
   * Parses the project file, configuring the project as it goes.
   *
   * @param project the current project
   * @param source the xml source
   * @param handler the root handler to use (contains the current context)
   * @exception BuildException if the configuration is invalid or cannot be read
   */
  public void parse(Project project, Object source, RootHandler handler) throws BuildException {

    AntXMLContext context = handler.context;

    File buildFile = null;
    URL url = null;
    String buildFileName = null;

    if (source instanceof File) {
      buildFile = (File) source;
    } else if (source instanceof URL) {
      url = (URL) source;
    } else if (source instanceof Resource) {
      FileProvider fp = (FileProvider) ((Resource) source).as(FileProvider.class);
      if (fp != null) {
        buildFile = fp.getFile();
      } else {
        URLProvider up = (URLProvider) ((Resource) source).as(URLProvider.class);
        if (up != null) {
          url = up.getURL();
        }
      }
    }
    if (buildFile != null) {
      buildFile = FILE_UTILS.normalize(buildFile.getAbsolutePath());
      context.setBuildFile(buildFile);
      buildFileName = buildFile.toString();
    } else if (url != null) {
      try {
        context.setBuildFile((File) null);
        context.setBuildFile(url);
      } catch (java.net.MalformedURLException ex) {
        throw new BuildException(ex);
      }
      buildFileName = url.toString();
    } else {
      throw new BuildException(
          "Source " + source.getClass().getName() + " not supported by this plugin");
    }
    InputStream inputStream = null;
    InputSource inputSource = null;
    ZipFile zf = null;

    try {
      /** SAX 2 style parser used to parse the given file. */
      XMLReader parser = JAXPUtils.getNamespaceXMLReader();

      String uri = null;
      if (buildFile != null) {
        uri = FILE_UTILS.toURI(buildFile.getAbsolutePath());
        inputStream = new FileInputStream(buildFile);
      } else {
        uri = url.toString();
        int pling = -1;
        if (uri.startsWith("jar:file") && (pling = uri.indexOf("!/")) > -1) {
          zf = new ZipFile(org.apache.tools.ant.launch.Locator.fromJarURI(uri), "UTF-8");
          inputStream = zf.getInputStream(zf.getEntry(uri.substring(pling + 1)));
        } else {
          inputStream = url.openStream();
        }
      }

      inputSource = new InputSource(inputStream);
      if (uri != null) {
        inputSource.setSystemId(uri);
      }
      project.log(
          "parsing buildfile "
              + buildFileName
              + " with URI = "
              + uri
              + (zf != null ? " from a zip file" : ""),
          Project.MSG_VERBOSE);

      DefaultHandler hb = handler;

      parser.setContentHandler(hb);
      parser.setEntityResolver(hb);
      parser.setErrorHandler(hb);
      parser.setDTDHandler(hb);
      parser.parse(inputSource);
    } catch (SAXParseException exc) {
      Location location =
          new Location(exc.getSystemId(), exc.getLineNumber(), exc.getColumnNumber());

      Throwable t = exc.getException();
      if (t instanceof BuildException) {
        BuildException be = (BuildException) t;
        if (be.getLocation() == Location.UNKNOWN_LOCATION) {
          be.setLocation(location);
        }
        throw be;
      }
      throw new BuildException(exc.getMessage(), t == null ? exc : t, location);
    } catch (SAXException exc) {
      Throwable t = exc.getException();
      if (t instanceof BuildException) {
        throw (BuildException) t;
      }
      throw new BuildException(exc.getMessage(), t == null ? exc : t);
    } catch (FileNotFoundException exc) {
      throw new BuildException(exc);
    } catch (UnsupportedEncodingException exc) {
      throw new BuildException("Encoding of project file " + buildFileName + " is invalid.", exc);
    } catch (IOException exc) {
      throw new BuildException(
          "Error reading project file " + buildFileName + ": " + exc.getMessage(), exc);
    } finally {
      FileUtils.close(inputStream);
      ZipFile.closeQuietly(zf);
    }
  }