public void renderPortalPagePortletBody(
      Appendable writer,
      Map<String, Object> context,
      ModelScreenWidget.PortalPage portalPage,
      GenericValue portalPortlet)
      throws GeneralException, IOException {
    String portalPortletId = portalPortlet.getString("portalPortletId");
    String screenName = portalPortlet.getString("screenName");
    String screenLocation = portalPortlet.getString("screenLocation");

    ModelScreen modelScreen = null;
    if (UtilValidate.isNotEmpty(screenName) && UtilValidate.isNotEmpty(screenLocation)) {
      try {
        modelScreen = ScreenFactory.getScreenFromLocation(screenLocation, screenName);
      } catch (IOException e) {
        String errMsg = "Error rendering portlet ID [" + portalPortletId + "]: " + e.toString();
        Debug.logError(e, errMsg, module);
        throw new RuntimeException(errMsg);
      } catch (SAXException e) {
        String errMsg = "Error rendering portlet ID [" + portalPortletId + "]: " + e.toString();
        Debug.logError(e, errMsg, module);
        throw new RuntimeException(errMsg);
      } catch (ParserConfigurationException e) {
        String errMsg = "Error rendering portlet ID [" + portalPortletId + "]: " + e.toString();
        Debug.logError(e, errMsg, module);
        throw new RuntimeException(errMsg);
      }
    }
    modelScreen.renderScreenString(writer, context, this);
  }
예제 #2
0
  public synchronized void unpack(ISOComponent c, InputStream in) throws ISOException, IOException {
    LogEvent evt = new LogEvent(this, "unpack");
    try {
      if (!(c instanceof ISOMsg)) throw new ISOException("Can't call packager on non Composite");

      while (!stk.empty())
        // purge from possible previous error
        stk.pop();

      reader.parse(new InputSource(in));
      if (stk.empty()) throw new ISOException("error parsing");

      ISOMsg m = (ISOMsg) c;
      m.merge((ISOMsg) stk.pop());

      if (logger != null) evt.addMessage(m);
    } catch (ISOException e) {
      evt.addMessage(e);
      throw e;
    } catch (SAXException e) {
      evt.addMessage(e);
      throw new ISOException(e.toString());
    } finally {
      Logger.log(evt);
    }
  }
예제 #3
0
  /**
   * Parses an XML document.
   *
   * @param xmlin the XML document.
   * @return the ParseOutput object from walking and processing the node.
   * @throws Exception if there are IO or XML parsing exceptions.
   */
  public Object parse(InputStream xmlin) throws Exception {
    DocumentBuilder db = null;
    try {
      db = XMLUtils.getSafeDocumentBuilder(false);
    } catch (ParserConfigurationException e) {
      throw new Exception("DBG:Got ParserConfigurationException:" + e.toString());
    }

    Document doc = null;
    try {
      doc = db.parse(xmlin);
    } catch (SAXParseException e) {
      throw new Exception(
          "DBG:Got SAXParseException:"
              + e.toString()
              + "line:"
              + e.getLineNumber()
              + " col :"
              + e.getColumnNumber());
    } catch (SAXException e) {
      throw new Exception("DBG:Got SAXException:" + e.toString());
    } catch (IOException ex) {
      throw new Exception("DBG: Got IOException:" + ex.toString());
    }

    Element elem = doc.getDocumentElement();
    return (walkTree(elem));
  }
예제 #4
0
  private NodeList load()
      throws IOException, FileNotFoundException, ParserConfigurationException, SAXException,
          TransformerException {
    InputStream fis = null;
    NodeList nl = null;
    try {
      DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

      fis = new FileInputStream(fileName);
      nl = XPathAPI.selectNodeList(builder.parse(fis), xpath);
      log.debug("found " + nl.getLength());

    } catch (FileNotFoundException e) {
      log.warn(e.toString());
      throw e;
    } catch (IOException e) {
      log.warn(e.toString());
      throw e;
    } catch (ParserConfigurationException e) {
      log.warn(e.toString());
      throw e;
    } catch (SAXException e) {
      log.warn(e.toString());
      throw e;
    } catch (TransformerException e) {
      log.warn(e.toString());
      throw e;
    } finally {
      JOrphanUtils.closeQuietly(fis);
    }
    return nl;
  }
예제 #5
0
  public synchronized int unpack(ISOComponent c, byte[] b) throws ISOException {
    LogEvent evt = new LogEvent(this, "unpack");
    try {
      if (!(c instanceof ISOMsg)) throw new ISOException("Can't call packager on non Composite");

      stk.clear();

      InputSource src = new InputSource(new ByteArrayInputStream(b));
      reader.parse(src);
      if (stk.empty()) throw new ISOException("error parsing");

      ISOMsg m = (ISOMsg) c;
      m.merge((ISOMsg) stk.pop());

      if (logger != null) evt.addMessage(m);
      return b.length;
    } catch (ISOException e) {
      evt.addMessage(e);
      throw e;
    } catch (IOException e) {
      evt.addMessage(e);
      throw new ISOException(e.toString());
    } catch (SAXException e) {
      evt.addMessage(e);
      throw new ISOException(e.toString());
    } finally {
      Logger.log(evt);
    }
  }
예제 #6
0
  /** Default constructor. */
  private Modelica() {
    final String schemaPath =
        ScilabConstants.SCI.getAbsolutePath() + XcosConstants.XCOS_ETC + SCHEMA_FILENAME;

    JAXBContext jaxbContext;
    try {
      jaxbContext = JAXBContext.newInstance(MODEL_CLASS_PACKAGE);
      marshaller = jaxbContext.createMarshaller();
      unmarshaller = jaxbContext.createUnmarshaller();

      Schema schema =
          SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
              .newSchema(new File(schemaPath));

      marshaller.setSchema(schema);
      unmarshaller.setSchema(schema);

      /*
       * Customize the file to be handled by the xml2modelica and
       * modelicat tool.
       */
      marshaller.setProperty(Marshaller.JAXB_ENCODING, LATIN1_ENCODING);

      marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
    } catch (JAXBException e) {
      throw new RuntimeException(e);
    } catch (SAXException e) {
      Logger.getLogger(Modelica.class.getName()).severe(e.toString());
    }
  }
 /** Loads edits file, uses visitor to process all elements */
 public void loadEdits() throws IOException {
   try {
     XMLReader xr = XMLReaderFactory.createXMLReader();
     xr.setContentHandler(this);
     xr.setErrorHandler(this);
     xr.setDTDHandler(null);
     xr.parse(new InputSource(fileReader));
     visitor.close(null);
   } catch (SAXParseException e) {
     System.out.println(
         "XML parsing error: "
             + "\n"
             + "Line:    "
             + e.getLineNumber()
             + "\n"
             + "URI:     "
             + e.getSystemId()
             + "\n"
             + "Message: "
             + e.getMessage());
     visitor.close(e);
     throw new IOException(e.toString());
   } catch (SAXException e) {
     visitor.close(e);
     throw new IOException(e.toString());
   } catch (RuntimeException e) {
     visitor.close(e);
     throw e;
   } finally {
     fileReader.close();
   }
 }
예제 #8
0
  /** @param configFile configuration file */
  private void parseConfigFile(final InputStream configFile) {

    String ribElementName;
    String ribElementClassName;

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    try {
      DocumentBuilder builder = factory.newDocumentBuilder();
      document = builder.parse(configFile);
    } catch (ParserConfigurationException pce) {
      logger.error(pce.toString());
    } catch (IOException ioe) {
      logger.error(ioe.toString());
    } catch (SAXException spe) {
      logger.error(spe.toString());
    } catch (IllegalArgumentException iae) {
      logger.error(iae.toString());
    }

    // Get the root
    Element root = document.getDocumentElement();

    // Get all the packages
    NodeList ribPackages = root.getElementsByTagName("package");

    // Loop through all the packages
    for (int i = 0; i < ribPackages.getLength(); i++) {

      Node ribPackage = ribPackages.item(i);

      NodeList ribElements = ribPackage.getChildNodes();
      String packageName = ribPackage.getAttributes().getNamedItem("name").getNodeValue();

      logger.debug("Package: " + packageName);

      // Loop through all elements in this package
      for (int x = 0; x < ribElements.getLength(); x++) {

        // Get values
        Node ribElement = ribElements.item(x);

        if (ribElement.getNodeType() == Node.ELEMENT_NODE) {
          NamedNodeMap ribElementAttributes = ribElement.getAttributes();
          ribElementName = ribElementAttributes.getNamedItem("name").getNodeValue();
          ribElementClassName = ribElementAttributes.getNamedItem("classname").getNodeValue();
          rib.put(ribElementName, packageName + "." + ribElementClassName);
          logger.debug("Class name: " + ribElementClassName);
        }
      }
    }
  }
  /**
   * Parses a report from the given stream.
   *
   * @param stream Input stream
   * @return The parsed SmsReport instance
   * @throws IOException if parsing the input string failed
   */
  public static SmsReport getInstance(InputStream stream) throws IOException {
    try {
      DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
      Document document = documentBuilder.parse(new InputSource(stream));

      return getInstance(document);
    } catch (ParserConfigurationException e) {
      throw new RuntimeException(e);
    } catch (SAXException e) {
      throw new IOException(e.toString());
    }
  }
예제 #10
0
 private void testXSDConfigXML(String xmlFileName) throws SAXException, IOException {
   SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
   URL schemaResource =
       XMLConfigBuilderTest.class.getClassLoader().getResource("hazelcast-config-3.6.xsd");
   InputStream xmlResource =
       XMLConfigBuilderTest.class.getClassLoader().getResourceAsStream(xmlFileName);
   Schema schema = factory.newSchema(schemaResource);
   Source source = new StreamSource(xmlResource);
   Validator validator = schema.newValidator();
   try {
     validator.validate(source);
   } catch (SAXException ex) {
     fail(xmlFileName + " is not valid because: " + ex.toString());
   }
 }
예제 #11
0
 public LODSetParser(File dir, Logger LOGGER) throws ParserConfigurationException, SAXException {
   lodSets = new ArrayList<LODSet>();
   File[] files = dir.listFiles();
   for (File file : files) {
     if (file.isFile()) {
       SAXParser parser;
       parser = SAXParserFactory.newInstance().newSAXParser();
       DefaultHandler lodSetHandler = new LODSetHandler();
       try {
         parser.parse(file, lodSetHandler);
         lodSets.add(((LODSetHandler) lodSetHandler).getLodSet());
       } catch (SAXException e) {
         LOGGER.warning("Fail parsing the file '" + file.getName() + "': " + e.toString());
       } catch (IOException e) {
         LOGGER.warning("Fail parsing the file '" + file.getName() + "': " + e.toString());
       }
     }
   }
 }
예제 #12
0
  /**
   * Reads an XML document from an input source and copies its values into the specified object
   *
   * @param ob The object to receive the values
   * @param source The location of the XML document
   * @throws IOException If there is an error reading the document
   */
  public void readObject(Object ob, InputSource source) throws IOException {
    try {
      // Create a document builder to read the document
      DocumentBuilder builder = factory.newDocumentBuilder();

      // Read the document
      Document doc = builder.parse(source);

      // Get the root element
      Element element = doc.getDocumentElement();

      // Copy the root element into the bean
      readObject(ob, element);
    } catch (SAXException exc) {
      throw new IOException("Error parsing XML document: " + exc.toString());
    } catch (ParserConfigurationException exc) {
      throw new IOException("Error parsing XML document: " + exc.toString());
    }
  }
예제 #13
0
  private void exportCharacters() {
    Object[] selectedValues = herolabsCharacterList.getSelectedValues();
    HeroLabPathfinderDigester dig = new HeroLabPathfinderDigester();
    boolean success = true;
    ArrayList<Character> notExported = new ArrayList<Character>();

    for (Object object : selectedValues) {
      Character character = (Character) object;
      try {
        if (!dig.saveCharacter(config, character)) {
          notExported.add(character);
        }
      } catch (IOException io) {
        success = false;
        errorDialog(io.getMessage(), "Something bad happened:" + io.toString());

      } catch (SAXException saxe) {
        success = false;
        errorDialog(saxe.getMessage(), "Something bad happened:" + saxe.toString());
      } catch (Exception e) {
        success = false;
        errorDialog(e.getMessage(), "Something bad happened:" + e.toString());
      }
    }

    if (success) {
      String message =
          "Successfully exported "
              + (selectedValues.length - notExported.size())
              + " out of "
              + selectedValues.length
              + " Maptools token(s).";
      if (!notExported.isEmpty()) {
        message +=
            "  "
                + notExported.size()
                + " tokens were not exported as they are not fully configured.";
        // TODO: do something more useful with this collection
      }

      JOptionPane.showMessageDialog(panel, message);
    }
  }
예제 #14
0
  @Deprecated
  public Document Deconstruct(String xmldata) {
    Document rv = null;
    if (xmldata != null) {
      String xmlbuf = xmldata.trim();
      if (xmlbuf.length() > 0) {
        InputSource is = new InputSource(new StringReader(xmlbuf));
        DocumentBuilderFactory f = null;
        DocumentBuilder p = null;

        f = DocumentBuilderFactory.newInstance();

        try {
          p = f.newDocumentBuilder();
        } catch (ParserConfigurationException ex) {
          if (ERROR_ENABLED) logger.error("ParserConfigurationException " + ex.toString());
        }

        //				if (DEBUG_ENABLED) logger.debug("Parser configured");

        boolean parsed = false;
        if (p != null) {
          try {
            rv = p.parse(is);
            if (rv != null) parsed = true;
            //						if (DEBUG_ENABLED && rv != null) logger.debug("Parse successful");
          } catch (SAXParseException ex) {
            if (ERROR_ENABLED)
              logger.error("SAX Parse Error " + ex.toString() + " at line " + ex.getLineNumber());
          } catch (SAXException ex) {
            if (ERROR_ENABLED) logger.error("SAX Error " + ex.toString());
          } catch (Exception ex) {
            if (ERROR_ENABLED) logger.error("XML Error " + ex.toString());
          }
          if (!parsed) {
            if (ERROR_ENABLED) logger.error("Parsing failed for \n" + xmldata);
          }
        }
      }
    }
    //		if (DEBUG_ENABLED) logger.debug("Leaving method");
    return rv;
  }
  /**
   * Perform the publication.
   *
   * @param build Build on which to apply publication
   * @param launcher Unused
   * @param listener Unused
   * @return boolean true if the publishing successfully complete true if the publishing could not
   *     complete
   * @throws IOException In case of file IO mismatch
   * @throws InterruptedException In case of interuption
   */
  @Override
  public boolean perform(
      final AbstractBuild<?, ?> build, final Launcher launcher, final BuildListener listener)
      throws IOException, InterruptedException {

    /** Define if we must parse multiple file by searching for ',' in the name var. */
    String[] files = name.split(",");

    ArrayList<String> filesToParse = new ArrayList<String>();
    for (int i = 0; i < files.length; i++) {
      FileSet fileSet = new FileSet();
      File workspace = build.getArtifactsDir();
      fileSet.setDir(workspace);
      fileSet.setIncludes(files[i].trim());
      Project antProject = new Project();
      fileSet.setProject(antProject);
      String[] tmpFiles = fileSet.getDirectoryScanner(antProject).getIncludedFiles();

      for (int j = 0; j < tmpFiles.length; j++) {
        filesToParse.add(tmpFiles[j]);
      }
    }

    try {
      ACIPluginBuildAction buildAction;
      buildAction = new ACIPluginBuildAction(build, filesToParse);
      build.addAction(buildAction);
    } catch (ParserConfigurationException ex) {
      listener.getLogger().println(ex.toString());
      return false;
    } catch (SAXException ex) {
      listener.getLogger().println(ex.toString());
      return false;
    } catch (URISyntaxException ex) {
      listener.getLogger().println(ex.toString());
      return false;
    }
    return true;
  }
예제 #16
0
  private static Document parseXml(String strXml) {
    Document doc = null;
    String strError;
    try {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();

      StringReader reader = new StringReader(strXml);
      InputSource inputSource = new InputSource(reader);

      doc = db.parse(inputSource);

      return doc;
    } catch (IOException ioe) {
      strError = ioe.toString();
    } catch (ParserConfigurationException pce) {
      strError = pce.toString();
    } catch (SAXException se) {
      strError = se.toString();
    } catch (Exception e) {
      strError = e.toString();
    }
    return null;
  }
예제 #17
0
  public static DotClassPath parse(File dotClasspath, List<Link> links) throws IOException {
    Document dotClasspathXml;
    try {
      dotClasspathXml =
          XMLUtil.parse(
              new InputSource(Utilities.toURI(dotClasspath).toString()),
              false,
              true,
              XMLUtil.defaultErrorHandler(),
              null);
    } catch (SAXException e) {
      IOException ioe =
          (IOException) new IOException(dotClasspath + ": " + e.toString()).initCause(e); // NOI18N
      throw ioe;
    }
    Element classpathEl = dotClasspathXml.getDocumentElement();
    if (!"classpath".equals(classpathEl.getLocalName())) { // NOI18N
      return empty();
    }
    List<Element> classpathEntryEls;
    try {
      classpathEntryEls = XMLUtil.findSubElements(classpathEl);
    } catch (IllegalArgumentException x) {
      throw new IOException(x);
    }
    if (classpathEntryEls == null) {
      return empty();
    }

    // accessrules are ignored as they are not supported in NB anyway, eg:
    /*
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER">
        <accessrules>
            <accessrule kind="accessible" pattern="com/sun/management/*"/>
            <accessrule kind="nonaccessible" pattern="com/sun/**"/>
        </accessrules>
    </classpathentry>
     */

    List<DotClassPathEntry> classpath = new ArrayList<DotClassPathEntry>();
    List<DotClassPathEntry> sources = new ArrayList<DotClassPathEntry>();
    DotClassPathEntry output = null;
    DotClassPathEntry jre = null;
    for (Element classpathEntry : classpathEntryEls) {
      Map<String, String> props = new HashMap<String, String>();
      NamedNodeMap attrs = classpathEntry.getAttributes();
      String linkName = null;
      for (int i = 0; i < attrs.getLength(); i++) {
        Node n = attrs.item(i);
        String key = n.getNodeName();
        String value = classpathEntry.getAttribute(n.getNodeName());
        if (DotClassPathEntry.ATTRIBUTE_PATH.equals(key)) {
          String resolvedLink = resolveLink(value, links);
          if (resolvedLink != null) {
            linkName = value;
            value = resolvedLink;
          }
        }
        props.put(key, value);
      }
      Element entryAttrs = XMLUtil.findElement(classpathEntry, "attributes", null); // NOI18N
      if (entryAttrs != null) {
        /*
        <classpathentry kind="lib" path="/home/dev/hibernate-annotations-3.3.1.GA/lib/hibernate-commons-annotations.jar" sourcepath="/home/dev/hibernate-annotations-3.3.1.GA/src">
            <attributes>
                <attribute name="javadoc_location" value="file:/home/dev/hibernate-annotations-3.3.1.GA/doc/api/"/>
            </attributes>
        </classpathentry>
         */
        List<Element> attrsList = XMLUtil.findSubElements(entryAttrs);
        if (attrsList != null) {
          for (Element e : attrsList) {
            props.put(e.getAttribute("name"), e.getAttribute("value")); // NOI18N
          }
        }
      }
      DotClassPathEntry entry = new DotClassPathEntry(props, linkName);
      if (entry.getKind() == DotClassPathEntry.Kind.SOURCE) {
        sources.add(entry);
      } else if (entry.getKind() == DotClassPathEntry.Kind.OUTPUT) {
        assert output == null : "there should be always just one default output"; // NOI18N
        output = entry;
      } else if (entry.getKind() == DotClassPathEntry.Kind.CONTAINER
          && entry.getRawPath().startsWith(Workspace.DEFAULT_JRE_CONTAINER)) {
        jre = entry;
      } else {
        classpath.add(entry);
      }
    }
    return new DotClassPath(classpath, sources, output, jre);
  }
예제 #18
0
  public void run() {
    for (; ; ) {
      while (!_start && !_stop) {
        try {
          sleep(TIMEOUT);
        } catch (InterruptedException e) {
          System.err.println(e.toString());
        }
      }

      if (_stop) {
        return;
      }

      synchronized (this) {
        String url = null;
        StreamConnection s = null;
        DataInputStream dis = null;
        java.io.InputStream input = null;
        try {
          s = (StreamConnection) Connector.open(getUrl(), Connector.READ, true);
          HttpConnection httpConn = (HttpConnection) s;
          httpConn.setRequestProperty("User-Agent", ipokiUserAgent);

          int status = httpConn.getResponseCode();
          if (status == HttpConnection.HTTP_OK) {
            try {
              DocumentBuilder doc = DocumentBuilderFactory.newInstance().newDocumentBuilder();
              dis = s.openDataInputStream();
              Document d = doc.parse(dis);
              dis.close();
              dis = null;
              Element el = d.getDocumentElement();
              _theUrl = el.getFirstChild().getNodeValue();
              url = getUrl();
            } catch (SAXException e) {
              System.err.println(e.toString());
            } catch (ParserConfigurationException e) {
              System.err.println(e.toString());
            }
          }
          s.close();
          s = null;
          if (url != null) {
            s = (StreamConnection) Connector.open(url);
            httpConn = (HttpConnection) s;
            httpConn.setRequestProperty("User-Agent", ipokiUserAgent);
            status = httpConn.getResponseCode();
            if (status == HttpConnection.HTTP_OK) {
              bv.addElement(data[0]);
              input = s.openInputStream();
              byte[] data = new byte[1];
              ByteVector bv = new ByteVector();
              while (-1 != input.read(data)) {
                bv.addElement(data[0]);
              }
              final byte[] png = bv.getArray();
              input.close();
              input = null;
              s.close();
              s = null;
              try {
                _mapScreen._app.invokeLater(
                    new Runnable() {
                      public void run() {
                        _mapScreen.mapField.setBitmap(Bitmap.createBitmapFromPNG(png, 0, -1));
                      }
                    });
              } catch (Exception e) {
                System.err.println(e.toString());
              }
            }
          }
        } catch (java.io.IOException e) {
          System.err.println(e.toString());
        } finally {
          try {
            if (dis != null) {
              dis.close();
              dis = null;
            }
          } catch (java.io.IOException e) {
            // pass
          }
          try {
            if (input != null) {
              input.close();
              input = null;
            }
          } catch (java.io.IOException e) {
            // pass
          }
          try {
            if (s != null) {
              s.close();
              s = null;
            }
          } catch (java.io.IOException e) {
            // pass
          }
        }
        _start = false;
      } // synchronized
    } // for
  } // run
예제 #19
0
  public List<Show> parse(InputStream inputStream) {

    try {
      InputSource inputSource = new InputSource(inputStream);
      XMLReader xmlReader = XMLReaderFactory.createXMLReader("org.xmlpull.v1.sax2.Driver");

      RootElement rootElement = new RootElement("Data");
      Element seriesElement = rootElement.getChild("Series");
      seriesElement.setStartElementListener(
          new StartElementListener() {
            public void start(Attributes attributes) {
              Log.i(TAG, "Begin parsing show");
              current = new Show();
            }
          });
      seriesElement.setEndElementListener(
          new EndElementListener() {
            public void end() {
              Log.i(TAG, "End parsing show");
              parsed.add(current);
              current = null;
            }
          });

      Element idElement = seriesElement.requireChild("id");
      idElement.setEndTextElementListener(
          new EndTextElementListener() {
            public void end(String body) {
              int id = Integer.parseInt(body);

              Log.i(TAG, String.format("Parsed ID: %d", id));
              current.setId(id);
            }
          });

      Element nameElement = seriesElement.requireChild("SeriesName");
      nameElement.setEndTextElementListener(
          new EndTextElementListener() {
            public void end(String body) {
              Log.i(TAG, String.format("Parsed name: %s", body));
              current.setName(body);
            }
          });

      Element languageElement = seriesElement.getChild("language");
      languageElement.setEndTextElementListener(
          new EndTextElementListener() {
            public void end(String body) {
              Log.i(TAG, String.format("Parsed language: %s", body));
              current.setLanguage(body);
            }
          });

      Element overviewElement = seriesElement.getChild("Overview");
      overviewElement.setEndTextElementListener(
          new EndTextElementListener() {
            public void end(String body) {
              Log.i(TAG, String.format("Parsed overview: %s", body));
              current.setOverview(body);
            }
          });

      Element firstAiredElement = seriesElement.getChild("FirstAired");
      firstAiredElement.setEndTextElementListener(
          new EndTextElementListener() {
            public void end(String body) {
              try {
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
                Date firstAired = df.parse(body);

                Log.i(TAG, String.format("Parsed first aired date: %s", firstAired.toString()));
                current.setFirstAired(firstAired);

              } catch (ParseException e) {
                Log.w(TAG, "Error parsing first aired date: " + e.toString());
                current.setFirstAired(null);
              }
            }
          });

      xmlReader.setContentHandler(rootElement.getContentHandler());

      current = null;
      parsed = new LinkedList<Show>();
      xmlReader.parse(inputSource);

      return parsed;

    } catch (SAXException e) {
      Log.w(TAG, "SAXException - parse: " + e.toString());
      return null;
    } catch (IOException e) {
      Log.w(TAG, "IOException - parse: " + e.toString());
      return null;
    }
  }
예제 #20
0
  /* Stylesheet is useless and just kept to keep the consistency with
   * builddoc V1 */
  public String process(String sourceDoc, String styleSheet) throws Throwable {
    String fileToExec = null;

    if (!new File(sourceDoc).isFile()) {
      System.err.println("Could not find master document: " + sourceDoc);
      return null;
    }

    try {
      Converter converter = null;
      ImageConverter imgConvert = new ImageConverter();

      switch (format) {
        case JAVAHELP:
          if (!isToolbox) {
            imgConvert.loadMD5s(ScilabConstants.SCI.getPath() + "/modules/helptools/etc");
          }
          converter = new JavaHelpDocbookTagConverter(sourceDoc, this, imgConvert);
          break;
        case HTML:
          converter = new HTMLDocbookTagConverter(sourceDoc, this, imgConvert);
          break;
        case WEB:
          if (!isToolbox) {
            imgConvert.loadMD5s(ScilabConstants.SCI.getPath() + "/modules/helptools/etc");
          }
          converter = new HTMLDocbookTagConverter(sourceDoc, this, imgConvert);
          break;
        case CHM:
          if (!isToolbox) {
            imgConvert.loadMD5s(ScilabConstants.SCI.getPath() + "/modules/helptools/etc");
          }
          converter = new CHMDocbookTagConverter(sourceDoc, this, imgConvert);
          break;
        case FO:
          converter = new FODocbookTagConverter(sourceDoc, this, imgConvert);
          break;
        case JAR_ONLY:
          converter = new JarOnlyConverter(this);
          break;
        case PDF:
        case PS:
          converter = new FopConverter(this);
          break;
        default:
          System.err.printf("%s is not a supported format.\n", format);
          return null;
      }

      converter.registerAllExternalXMLHandlers();

      converter.convert();

      converter.install();

      if (imgConvert.getScilabImageConverter() != null) {
        fileToExec = imgConvert.getScilabImageConverter().getFileWithScilabCode();
      }

    } catch (SAXException e) {
      System.err.println("An error occurred during the conversion:");
      System.err.println(e.toString());
    } catch (Throwable e) {
      System.err.println("An error occurred during the conversion:\n");
      e.printStackTrace();
      throw e;
    }

    return fileToExec;
  }
예제 #21
0
  /**
   * JavaMail Service that gets body content from a Screen Widget defined in the product store
   * record and if available as attachment also.
   *
   * @param dctx The DispatchContext that this service is operating in
   * @param rServiceContext Map containing the input parameters
   * @return Map with the result of the service, the output parameters
   */
  public static Map<String, Object> sendMailFromScreen(
      DispatchContext dctx, Map<String, ? extends Object> rServiceContext) {
    Map<String, Object> serviceContext = UtilMisc.makeMapWritable(rServiceContext);
    LocalDispatcher dispatcher = dctx.getDispatcher();
    String webSiteId = (String) serviceContext.remove("webSiteId");
    String bodyText = (String) serviceContext.remove("bodyText");
    String bodyScreenUri = (String) serviceContext.remove("bodyScreenUri");
    String xslfoAttachScreenLocationParam =
        (String) serviceContext.remove("xslfoAttachScreenLocation");
    String attachmentNameParam = (String) serviceContext.remove("attachmentName");
    List<String> xslfoAttachScreenLocationListParam =
        UtilGenerics.checkList(serviceContext.remove("xslfoAttachScreenLocationList"));
    List<String> attachmentNameListParam =
        UtilGenerics.checkList(serviceContext.remove("attachmentNameList"));

    List<String> xslfoAttachScreenLocationList = FastList.newInstance();
    List<String> attachmentNameList = FastList.newInstance();
    if (UtilValidate.isNotEmpty(xslfoAttachScreenLocationParam))
      xslfoAttachScreenLocationList.add(xslfoAttachScreenLocationParam);
    if (UtilValidate.isNotEmpty(attachmentNameParam)) attachmentNameList.add(attachmentNameParam);
    if (UtilValidate.isNotEmpty(xslfoAttachScreenLocationListParam))
      xslfoAttachScreenLocationList.addAll(xslfoAttachScreenLocationListParam);
    if (UtilValidate.isNotEmpty(attachmentNameListParam))
      attachmentNameList.addAll(attachmentNameListParam);

    Locale locale = (Locale) serviceContext.get("locale");
    Map<String, Object> bodyParameters =
        UtilGenerics.checkMap(serviceContext.remove("bodyParameters"));
    if (bodyParameters == null) {
      bodyParameters = MapStack.create();
    }
    if (!bodyParameters.containsKey("locale")) {
      bodyParameters.put("locale", locale);
    } else {
      locale = (Locale) bodyParameters.get("locale");
    }
    String partyId = (String) serviceContext.get("partyId");
    if (partyId == null) {
      partyId = (String) bodyParameters.get("partyId");
    }
    String orderId = (String) bodyParameters.get("orderId");
    String custRequestId = (String) bodyParameters.get("custRequestId");

    bodyParameters.put("communicationEventId", serviceContext.get("communicationEventId"));
    NotificationServices.setBaseUrl(dctx.getDelegator(), webSiteId, bodyParameters);
    String contentType = (String) serviceContext.remove("contentType");

    StringWriter bodyWriter = new StringWriter();

    MapStack<String> screenContext = MapStack.create();
    screenContext.put("locale", locale);
    ScreenRenderer screens = new ScreenRenderer(bodyWriter, screenContext, htmlScreenRenderer);
    screens.populateContextForService(dctx, bodyParameters);
    screenContext.putAll(bodyParameters);

    if (bodyScreenUri != null) {
      try {
        screens.render(bodyScreenUri);
      } catch (GeneralException e) {
        Debug.logError(e, "Error rendering screen for email: " + e.toString(), module);
        return ServiceUtil.returnError(
            UtilProperties.getMessage(
                resource,
                "CommonEmailSendRenderingScreenEmailError",
                UtilMisc.toMap("errorString", e.toString()),
                locale));
      } catch (IOException e) {
        Debug.logError(e, "Error rendering screen for email: " + e.toString(), module);
        return ServiceUtil.returnError(
            UtilProperties.getMessage(
                resource,
                "CommonEmailSendRenderingScreenEmailError",
                UtilMisc.toMap("errorString", e.toString()),
                locale));
      } catch (SAXException e) {
        Debug.logError(e, "Error rendering screen for email: " + e.toString(), module);
        return ServiceUtil.returnError(
            UtilProperties.getMessage(
                resource,
                "CommonEmailSendRenderingScreenEmailError",
                UtilMisc.toMap("errorString", e.toString()),
                locale));
      } catch (ParserConfigurationException e) {
        Debug.logError(e, "Error rendering screen for email: " + e.toString(), module);
        return ServiceUtil.returnError(
            UtilProperties.getMessage(
                resource,
                "CommonEmailSendRenderingScreenEmailError",
                UtilMisc.toMap("errorString", e.toString()),
                locale));
      }
    }

    boolean isMultiPart = false;

    // check if attachment screen location passed in
    if (UtilValidate.isNotEmpty(xslfoAttachScreenLocationList)) {
      List<Map<String, ? extends Object>> bodyParts = FastList.newInstance();
      if (bodyText != null) {
        bodyText = FlexibleStringExpander.expandString(bodyText, screenContext, locale);
        bodyParts.add(UtilMisc.<String, Object>toMap("content", bodyText, "type", "text/html"));
      } else {
        bodyParts.add(
            UtilMisc.<String, Object>toMap("content", bodyWriter.toString(), "type", "text/html"));
      }

      for (int i = 0; i < xslfoAttachScreenLocationList.size(); i++) {
        String xslfoAttachScreenLocation = xslfoAttachScreenLocationList.get(i);
        String attachmentName = "Details.pdf";
        if (UtilValidate.isNotEmpty(attachmentNameList) && attachmentNameList.size() >= i) {
          attachmentName = attachmentNameList.get(i);
        }
        isMultiPart = true;
        // start processing fo pdf attachment
        try {
          Writer writer = new StringWriter();
          MapStack<String> screenContextAtt = MapStack.create();
          // substitute the freemarker variables...
          ScreenRenderer screensAtt = new ScreenRenderer(writer, screenContext, foScreenRenderer);
          screensAtt.populateContextForService(dctx, bodyParameters);
          screenContextAtt.putAll(bodyParameters);
          screensAtt.render(xslfoAttachScreenLocation);

          /*
          try { // save generated fo file for debugging
              String buf = writer.toString();
              java.io.FileWriter fw = new java.io.FileWriter(new java.io.File("/tmp/file1.xml"));
              fw.write(buf.toString());
              fw.close();
          } catch (IOException e) {
              Debug.logError(e, "Couldn't save xsl-fo xml debug file: " + e.toString(), module);
          }
          */

          // create the input stream for the generation
          StreamSource src = new StreamSource(new StringReader(writer.toString()));

          // create the output stream for the generation
          ByteArrayOutputStream baos = new ByteArrayOutputStream();

          Fop fop = ApacheFopWorker.createFopInstance(baos, MimeConstants.MIME_PDF);
          ApacheFopWorker.transform(src, null, fop);

          // and generate the PDF
          baos.flush();
          baos.close();

          // store in the list of maps for sendmail....
          bodyParts.add(
              UtilMisc.<String, Object>toMap(
                  "content",
                  baos.toByteArray(),
                  "type",
                  "application/pdf",
                  "filename",
                  attachmentName));
        } catch (GeneralException ge) {
          Debug.logError(ge, "Error rendering PDF attachment for email: " + ge.toString(), module);
          return ServiceUtil.returnError(
              UtilProperties.getMessage(
                  resource,
                  "CommonEmailSendRenderingScreenPdfError",
                  UtilMisc.toMap("errorString", ge.toString()),
                  locale));
        } catch (IOException ie) {
          Debug.logError(ie, "Error rendering PDF attachment for email: " + ie.toString(), module);
          return ServiceUtil.returnError(
              UtilProperties.getMessage(
                  resource,
                  "CommonEmailSendRenderingScreenPdfError",
                  UtilMisc.toMap("errorString", ie.toString()),
                  locale));
        } catch (FOPException fe) {
          Debug.logError(fe, "Error rendering PDF attachment for email: " + fe.toString(), module);
          return ServiceUtil.returnError(
              UtilProperties.getMessage(
                  resource,
                  "CommonEmailSendRenderingScreenPdfError",
                  UtilMisc.toMap("errorString", fe.toString()),
                  locale));
        } catch (SAXException se) {
          Debug.logError(se, "Error rendering PDF attachment for email: " + se.toString(), module);
          return ServiceUtil.returnError(
              UtilProperties.getMessage(
                  resource,
                  "CommonEmailSendRenderingScreenPdfError",
                  UtilMisc.toMap("errorString", se.toString()),
                  locale));
        } catch (ParserConfigurationException pe) {
          Debug.logError(pe, "Error rendering PDF attachment for email: " + pe.toString(), module);
          return ServiceUtil.returnError(
              UtilProperties.getMessage(
                  resource,
                  "CommonEmailSendRenderingScreenPdfError",
                  UtilMisc.toMap("errorString", pe.toString()),
                  locale));
        }

        serviceContext.put("bodyParts", bodyParts);
      }
    } else {
      isMultiPart = false;
      // store body and type for single part message in the context.
      if (bodyText != null) {
        bodyText = FlexibleStringExpander.expandString(bodyText, screenContext, locale);
        serviceContext.put("body", bodyText);
      } else {
        serviceContext.put("body", bodyWriter.toString());
      }

      // Only override the default contentType in case of plaintext, since other contentTypes may be
      // multipart
      //    and would require specific handling.
      if (contentType != null && contentType.equalsIgnoreCase("text/plain")) {
        serviceContext.put("contentType", "text/plain");
      } else {
        serviceContext.put("contentType", "text/html");
      }
    }

    // also expand the subject at this point, just in case it has the FlexibleStringExpander syntax
    // in it...
    String subject = (String) serviceContext.remove("subject");
    subject = FlexibleStringExpander.expandString(subject, screenContext, locale);
    Debug.logInfo("Expanded email subject to: " + subject, module);
    serviceContext.put("subject", subject);
    serviceContext.put("partyId", partyId);
    if (UtilValidate.isNotEmpty(orderId)) {
      serviceContext.put("orderId", orderId);
    }
    if (UtilValidate.isNotEmpty(custRequestId)) {
      serviceContext.put("custRequestId", custRequestId);
    }

    if (Debug.verboseOn())
      Debug.logVerbose("sendMailFromScreen sendMail context: " + serviceContext, module);

    Map<String, Object> result = ServiceUtil.returnSuccess();
    Map<String, Object> sendMailResult;
    try {
      if (isMultiPart) {
        sendMailResult = dispatcher.runSync("sendMailMultiPart", serviceContext);
      } else {
        sendMailResult = dispatcher.runSync("sendMail", serviceContext);
      }
    } catch (Exception e) {
      Debug.logError(e, "Error send email:" + e.toString(), module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource,
              "CommonEmailSendError",
              UtilMisc.toMap("errorString", e.toString()),
              locale));
    }
    if (ServiceUtil.isError(sendMailResult)) {
      return ServiceUtil.returnError(ServiceUtil.getErrorMessage(sendMailResult));
    }

    result.put("messageWrapper", sendMailResult.get("messageWrapper"));
    result.put("body", bodyWriter.toString());
    result.put("subject", subject);
    result.put("communicationEventId", sendMailResult.get("communicationEventId"));
    if (UtilValidate.isNotEmpty(orderId)) {
      result.put("orderId", orderId);
    }
    if (UtilValidate.isNotEmpty(custRequestId)) {
      result.put("custRequestId", custRequestId);
    }
    return result;
  }
예제 #22
0
  /**
   * getXMLValue
   *
   * <p>From a XML element, get a values map
   *
   * @param fileFullPath File path to parse
   * @return Map contains asked attribute values by attribute name
   */
  public static Map<String, Object> getXMLValue(String fileFullPath, Locale locale)
      throws IllegalStateException, IOException {

    /* VARIABLES */
    Document document;
    Element rootElt;
    Map<String, Map<String, String>> valueMap = FastMap.newInstance();
    Map<String, Object> result = FastMap.newInstance();

    /* PARSING */
    try {
      document = UtilXml.readXmlDocument(new FileInputStream(fileFullPath), fileFullPath);
    } catch (ParserConfigurationException e) {
      String errMsg =
          UtilProperties.getMessage(
                  resource, "ImageTransform.errors_occured_during_parsing", locale)
              + " ImageProperties.xml "
              + e.toString();
      Debug.logError(errMsg, module);
      result.put("errorMessage", "error");
      return result;
    } catch (SAXException e) {
      String errMsg =
          UtilProperties.getMessage(
                  resource, "ImageTransform.errors_occured_during_parsing", locale)
              + " ImageProperties.xml "
              + e.toString();
      Debug.logError(errMsg, module);
      result.put("errorMessage", "error");
      return result;
    } catch (IOException e) {
      String errMsg =
          UtilProperties.getMessage(
                  resource,
                  "ImageTransform.error_prevents_the document_from_being_fully_parsed",
                  locale)
              + e.toString();
      Debug.logError(errMsg, module);
      result.put("errorMessage", "error");
      return result;
    }
    // set Root Element
    try {
      rootElt = document.getDocumentElement();
    } catch (IllegalStateException e) {
      String errMsg =
          UtilProperties.getMessage(
                  resource, "ImageTransform.root_element_has_not_been_set", locale)
              + e.toString();
      Debug.logError(errMsg, module);
      result.put("errorMessage", "error");
      return result;
    }

    /* get NAME and VALUE */
    List<? extends Element> children =
        UtilXml.childElementList(
            rootElt); // FIXME : despite upgrading to jdom 1.1, it seems that getChildren is pre 1.5
                      // java code (ie getChildren does not retun List<Element> but only List)
    for (Element currentElt : children) {
      Map<String, String> eltMap = FastMap.newInstance();
      List<? extends Element> children2 = UtilXml.childElementList(currentElt);
      if (children2.size() > 0) {
        Map<String, String> childMap = FastMap.newInstance();
        // loop over Children 1st level
        for (Element currentChild : children2) {
          childMap.put(currentChild.getAttribute("name"), currentChild.getAttribute("value"));
        }
        valueMap.put(currentElt.getAttribute("name"), childMap);
      } else {
        eltMap.put(currentElt.getAttribute("name"), currentElt.getAttribute("value"));
        valueMap.put(currentElt.getNodeName(), eltMap);
      }
    }

    result.put("responseMessage", "success");
    result.put("xml", valueMap);
    return result;
  }
예제 #23
0
  @Override
  public Collection<cgCache> parse(
      final InputStream stream, final CancellableHandler progressHandler)
      throws IOException, ParserException {
    resetCache();
    final RootElement root = new RootElement(namespace, "gpx");
    final Element waypoint = root.getChild(namespace, "wpt");

    // waypoint - attributes
    waypoint.setStartElementListener(
        new StartElementListener() {

          @Override
          public void start(Attributes attrs) {
            try {
              if (attrs.getIndex("lat") > -1 && attrs.getIndex("lon") > -1) {
                cache.setCoords(
                    new Geopoint(
                        new Double(attrs.getValue("lat")), new Double(attrs.getValue("lon"))));
              }
            } catch (Exception e) {
              Log.w(Settings.tag, "Failed to parse waypoint's latitude and/or longitude.");
            }
          }
        });

    // waypoint
    waypoint.setEndElementListener(
        new EndElementListener() {

          @Override
          public void end() {
            // try to find geocode somewhere else
            if (StringUtils.isBlank(cache.getGeocode())) {
              findGeoCode(name);
              findGeoCode(desc);
              findGeoCode(cmt);
            }
            // take the name as code, if nothing else is available
            if (StringUtils.isBlank(cache.getGeocode())) {
              if (StringUtils.isNotBlank(name)) {
                cache.setGeocode(name.trim());
              }
            }

            if (StringUtils.isNotBlank(cache.getGeocode())
                && cache.getCoords() != null
                && ((type == null && sym == null)
                    || StringUtils.contains(type, "geocache")
                    || StringUtils.contains(sym, "geocache"))) {
              fixCache(cache);
              cache.setListId(listId);
              cache.setDetailed(true);

              createNoteFromGSAKUserdata();

              result.put(cache.getGeocode(), cache);
              showProgressMessage(progressHandler, progressStream.getProgress());
            } else if (StringUtils.isNotBlank(cache.getName())
                && cache.getCoords() != null
                && StringUtils.contains(type, "waypoint")) {
              addWaypointToCache();
            }

            resetCache();
          }

          private void addWaypointToCache() {
            fixCache(cache);

            if (cache.getName().length() > 2) {
              final String cacheGeocodeForWaypoint = "GC" + cache.getName().substring(2);

              // lookup cache for waypoint in already parsed caches
              final cgCache cacheForWaypoint = result.get(cacheGeocodeForWaypoint);
              if (cacheForWaypoint != null) {
                final cgWaypoint waypoint =
                    new cgWaypoint(cache.getShortdesc(), convertWaypointSym2Type(sym));
                waypoint.setId(-1);
                waypoint.setGeocode(cacheGeocodeForWaypoint);
                waypoint.setPrefix(cache.getName().substring(0, 2));
                waypoint.setLookup("---");
                // there is no lookup code in gpx file
                waypoint.setCoords(cache.getCoords());
                waypoint.setNote(cache.getDescription());

                ArrayList<cgWaypoint> mergedWayPoints = new ArrayList<cgWaypoint>();
                mergedWayPoints.addAll(cacheForWaypoint.getWaypoints());

                cgWaypoint.mergeWayPoints(
                    mergedWayPoints, Collections.singletonList(waypoint), true);
                cacheForWaypoint.setWaypoints(mergedWayPoints);
                result.put(cacheGeocodeForWaypoint, cacheForWaypoint);
                showProgressMessage(progressHandler, progressStream.getProgress());
              }
            }
          }
        });

    // waypoint.time
    waypoint
        .getChild(namespace, "time")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String body) {
                try {
                  cache.setHidden(parseDate(body));
                } catch (Exception e) {
                  Log.w(Settings.tag, "Failed to parse cache date: " + e.toString());
                }
              }
            });

    // waypoint.getName()
    waypoint
        .getChild(namespace, "name")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String body) {
                name = body;

                final String content = body.trim();
                cache.setName(content);

                findGeoCode(cache.getName());
              }
            });

    // waypoint.desc
    waypoint
        .getChild(namespace, "desc")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String body) {
                desc = body;

                cache.setShortdesc(validate(body));
              }
            });

    // waypoint.cmt
    waypoint
        .getChild(namespace, "cmt")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String body) {
                cmt = body;

                cache.setDescription(validate(body));
              }
            });

    // waypoint.getType()
    waypoint
        .getChild(namespace, "type")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String body) {
                final String[] content = body.split("\\|");
                if (content.length > 0) {
                  type = content[0].toLowerCase().trim();
                }
              }
            });

    // waypoint.sym
    waypoint
        .getChild(namespace, "sym")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(final String body) {
                sym = body.toLowerCase();
                if (sym.contains("geocache") && sym.contains("found")) {
                  cache.setFound(true);
                }
              }
            });

    // waypoint.url
    waypoint
        .getChild(namespace, "url")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String url) {
                final Matcher matcher = patternGuid.matcher(url);
                if (matcher.matches()) {
                  final String guid = matcher.group(1);
                  if (StringUtils.isNotBlank(guid)) {
                    cache.setGuid(guid);
                  }
                }
              }
            });

    // for GPX 1.0, cache info comes from waypoint node (so called private children,
    // for GPX 1.1 from extensions node
    final Element cacheParent = getCacheParent(waypoint);

    // GSAK extensions
    final Element gsak = cacheParent.getChild(GSAK_NS, "wptExtension");
    gsak.getChild(GSAK_NS, "Watch")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String watchList) {
                cache.setOnWatchlist(Boolean.valueOf(watchList.trim()).booleanValue());
              }
            });

    gsak.getChild(GSAK_NS, "UserData").setEndTextElementListener(new UserDataListener(1));

    for (int i = 2; i <= 4; i++) {
      gsak.getChild(GSAK_NS, "User" + i).setEndTextElementListener(new UserDataListener(i));
    }

    // 3 different versions of the GC schema
    for (String nsGC : nsGCList) {
      // waypoints.cache
      final Element gcCache = cacheParent.getChild(nsGC, "cache");

      gcCache.setStartElementListener(
          new StartElementListener() {

            @Override
            public void start(Attributes attrs) {
              try {
                if (attrs.getIndex("id") > -1) {
                  cache.setCacheId(attrs.getValue("id"));
                }
                if (attrs.getIndex("archived") > -1) {
                  cache.setArchived(attrs.getValue("archived").equalsIgnoreCase("true"));
                }
                if (attrs.getIndex("available") > -1) {
                  cache.setDisabled(!attrs.getValue("available").equalsIgnoreCase("true"));
                }
              } catch (Exception e) {
                Log.w(Settings.tag, "Failed to parse cache attributes.");
              }
            }
          });

      // waypoint.cache.getName()
      gcCache
          .getChild(nsGC, "name")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String cacheName) {
                  cache.setName(validate(cacheName));
                }
              });

      // waypoint.cache.getOwner()
      gcCache
          .getChild(nsGC, "owner")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String cacheOwner) {
                  cache.setOwner(validate(cacheOwner));
                }
              });

      // waypoint.cache.getType()
      gcCache
          .getChild(nsGC, "type")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String body) {
                  cache.setType(CacheType.getByPattern(validate(body.toLowerCase())));
                }
              });

      // waypoint.cache.container
      gcCache
          .getChild(nsGC, "container")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String body) {
                  cache.setSize(CacheSize.getById(validate(body.toLowerCase())));
                }
              });

      // waypoint.cache.getAttributes()
      // @see issue #299

      // <groundspeak:attributes>
      //   <groundspeak:attribute id="32" inc="1">Bicycles</groundspeak:attribute>
      //   <groundspeak:attribute id="13" inc="1">Available at all times</groundspeak:attribute>
      // where inc = 0 => _no, inc = 1 => _yes
      // IDs see array CACHE_ATTRIBUTES
      final Element gcAttributes = gcCache.getChild(nsGC, "attributes");

      // waypoint.cache.attribute
      final Element gcAttribute = gcAttributes.getChild(nsGC, "attribute");

      gcAttribute.setStartElementListener(
          new StartElementListener() {
            @Override
            public void start(Attributes attrs) {
              try {
                if (attrs.getIndex("id") > -1 && attrs.getIndex("inc") > -1) {
                  int attributeId = Integer.parseInt(attrs.getValue("id"));
                  boolean attributeActive = Integer.parseInt(attrs.getValue("inc")) != 0;
                  String internalId =
                      CacheAttributeTranslator.getInternalId(attributeId, attributeActive);
                  if (internalId != null) {
                    cache.addAttribute(internalId);
                  }
                }
              } catch (NumberFormatException e) {
                // nothing
              }
            }
          });

      // waypoint.cache.getDifficulty()
      gcCache
          .getChild(nsGC, "difficulty")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String body) {
                  try {
                    cache.setDifficulty(Float.parseFloat(body));
                  } catch (NumberFormatException e) {
                    Log.w(Settings.tag, "Failed to parse difficulty: " + e.toString());
                  }
                }
              });

      // waypoint.cache.getTerrain()
      gcCache
          .getChild(nsGC, "terrain")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String body) {
                  try {
                    cache.setTerrain(Float.parseFloat(body));
                  } catch (NumberFormatException e) {
                    Log.w(Settings.tag, "Failed to parse terrain: " + e.toString());
                  }
                }
              });

      // waypoint.cache.country
      gcCache
          .getChild(nsGC, "country")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String country) {
                  if (StringUtils.isBlank(cache.getLocation())) {
                    cache.setLocation(validate(country));
                  } else {
                    cache.setLocation(cache.getLocation() + ", " + country.trim());
                  }
                }
              });

      // waypoint.cache.state
      gcCache
          .getChild(nsGC, "state")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String state) {
                  String trimmedState = state.trim();
                  if (StringUtils.isNotEmpty(trimmedState)) { // state can be completely empty
                    if (StringUtils.isBlank(cache.getLocation())) {
                      cache.setLocation(validate(state));
                    } else {
                      cache.setLocation(trimmedState + ", " + cache.getLocation());
                    }
                  }
                }
              });

      // waypoint.cache.encoded_hints
      gcCache
          .getChild(nsGC, "encoded_hints")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String encoded) {
                  cache.setHint(validate(encoded));
                }
              });

      gcCache
          .getChild(nsGC, "short_description")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String shortDesc) {
                  cache.setShortdesc(validate(shortDesc));
                }
              });

      gcCache
          .getChild(nsGC, "long_description")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String desc) {
                  cache.setDescription(validate(desc));
                }
              });

      // waypoint.cache.travelbugs
      final Element gcTBs = gcCache.getChild(nsGC, "travelbugs");

      // waypoint.cache.travelbug
      final Element gcTB = gcTBs.getChild(nsGC, "travelbug");

      // waypoint.cache.travelbugs.travelbug
      gcTB.setStartElementListener(
          new StartElementListener() {

            @Override
            public void start(Attributes attrs) {
              trackable = new cgTrackable();

              try {
                if (attrs.getIndex("ref") > -1) {
                  trackable.setGeocode(attrs.getValue("ref").toUpperCase());
                }
              } catch (Exception e) {
                // nothing
              }
            }
          });

      gcTB.setEndElementListener(
          new EndElementListener() {

            @Override
            public void end() {
              if (StringUtils.isNotBlank(trackable.getGeocode())
                  && StringUtils.isNotBlank(trackable.getName())) {
                if (cache.getInventory() == null) {
                  cache.setInventory(new ArrayList<cgTrackable>());
                }
                cache.getInventory().add(trackable);
              }
            }
          });

      // waypoint.cache.travelbugs.travelbug.getName()
      gcTB.getChild(nsGC, "name")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String tbName) {
                  trackable.setName(validate(tbName));
                }
              });

      // waypoint.cache.logs
      final Element gcLogs = gcCache.getChild(nsGC, "logs");

      // waypoint.cache.log
      final Element gcLog = gcLogs.getChild(nsGC, "log");

      gcLog.setStartElementListener(
          new StartElementListener() {

            @Override
            public void start(Attributes attrs) {
              log = new cgLog();

              try {
                if (attrs.getIndex("id") > -1) {
                  log.id = Integer.parseInt(attrs.getValue("id"));
                }
              } catch (Exception e) {
                // nothing
              }
            }
          });

      gcLog.setEndElementListener(
          new EndElementListener() {

            @Override
            public void end() {
              if (StringUtils.isNotBlank(log.log)) {
                cache.appendLog(log);
              }
            }
          });

      // waypoint.cache.logs.log.date
      gcLog
          .getChild(nsGC, "date")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String body) {
                  try {
                    log.date = parseDate(body).getTime();
                  } catch (Exception e) {
                    Log.w(Settings.tag, "Failed to parse log date: " + e.toString());
                  }
                }
              });

      // waypoint.cache.logs.log.getType()
      gcLog
          .getChild(nsGC, "type")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String body) {
                  final String logType = validate(body).toLowerCase();
                  log.type = LogType.getByType(logType);
                }
              });

      // waypoint.cache.logs.log.finder
      gcLog
          .getChild(nsGC, "finder")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String finderName) {
                  log.author = validate(finderName);
                }
              });

      // waypoint.cache.logs.log.text
      gcLog
          .getChild(nsGC, "text")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String logText) {
                  log.log = validate(logText);
                }
              });
    }

    try {
      progressStream = new ProgressInputStream(stream);
      Xml.parse(progressStream, Xml.Encoding.UTF_8, root.getContentHandler());
      return result.values();
    } catch (SAXException e) {
      Log.e(
          Settings.tag,
          "Cannot parse .gpx file as GPX " + version + ": could not parse XML - " + e.toString());
      throw new ParserException(
          "Cannot parse .gpx file as GPX " + version + ": could not parse XML", e);
    }
  }
예제 #24
0
  public long parse(final InputStream stream, Handler handlerIn) {
    handler = handlerIn;

    final RootElement root = new RootElement(namespace, "gpx");
    final Element waypoint = root.getChild(namespace, "wpt");

    // waypoint - attributes
    waypoint.setStartElementListener(
        new StartElementListener() {

          @Override
          public void start(Attributes attrs) {
            try {
              if (attrs.getIndex("lat") > -1) {
                cache.latitude = new Double(attrs.getValue("lat"));
              }
              if (attrs.getIndex("lon") > -1) {
                cache.longitude = new Double(attrs.getValue("lon"));
              }
            } catch (Exception e) {
              Log.w(cgSettings.tag, "Failed to parse waypoint's latitude and/or longitude.");
            }
          }
        });

    // waypoint
    waypoint.setEndElementListener(
        new EndElementListener() {

          @Override
          public void end() {
            if (cache.geocode == null || cache.geocode.length() == 0) {
              // try to find geocode somewhere else
              findGeoCode(name);
              findGeoCode(desc);
              findGeoCode(cmt);
            }

            if (cache.geocode != null
                && cache.geocode.length() > 0
                && cache.latitude != null
                && cache.longitude != null
                && ((type == null && sym == null)
                    || (type != null && type.indexOf("geocache") > -1)
                    || (sym != null && sym.indexOf("geocache") > -1))) {
              fixCache(cache);
              cache.reason = listId;
              cache.detailed = true;

              app.addCacheToSearch(search, cache);
            }

            showFinishedMessage(handler, search);

            type = null;
            sym = null;
            name = null;
            desc = null;
            cmt = null;

            cache = null;
            cache = new cgCache();
          }
        });

    // waypoint.time
    waypoint
        .getChild(namespace, "time")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String body) {
                try {
                  cache.hidden = parseDate(body);
                } catch (Exception e) {
                  Log.w(cgSettings.tag, "Failed to parse cache date: " + e.toString());
                }
              }
            });

    // waypoint.name
    waypoint
        .getChild(namespace, "name")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String body) {
                name = body;

                final String content = body.trim();
                cache.name = content;

                findGeoCode(cache.name);
                findGeoCode(cache.description);
              }
            });

    // waypoint.desc
    waypoint
        .getChild(namespace, "desc")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String body) {
                desc = body;

                cache.shortdesc = validate(body);
              }
            });

    // waypoint.cmt
    waypoint
        .getChild(namespace, "cmt")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String body) {
                cmt = body;

                cache.description = validate(body);
              }
            });

    // waypoint.type
    waypoint
        .getChild(namespace, "type")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String body) {
                final String[] content = body.split("\\|");
                if (content.length > 0) {
                  type = content[0].toLowerCase().trim();
                }
              }
            });

    // waypoint.sym
    waypoint
        .getChild(namespace, "sym")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String body) {
                body = body.toLowerCase();
                sym = body;
                if (body.indexOf("geocache") != -1 && body.indexOf("found") != -1) {
                  cache.found = true;
                }
              }
            });

    // waypoint.url
    waypoint
        .getChild(namespace, "url")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String url) {
                final Matcher matcher = patternGuid.matcher(url);
                if (matcher.matches()) {
                  String guid = matcher.group(1);
                  if (guid.length() > 0) {
                    cache.guid = guid;
                  }
                }
              }
            });

    // for GPX 1.0, cache info comes from waypoint node (so called private children,
    // for GPX 1.1 from extensions node
    final Element cacheParent = getCacheParent(waypoint);

    for (String nsGC : nsGCList) {
      // waypoints.cache
      final Element gcCache = cacheParent.getChild(nsGC, "cache");

      gcCache.setStartElementListener(
          new StartElementListener() {

            @Override
            public void start(Attributes attrs) {
              try {
                if (attrs.getIndex("id") > -1) {
                  cache.cacheid = attrs.getValue("id");
                }
                if (attrs.getIndex("archived") > -1) {
                  cache.archived = attrs.getValue("archived").equalsIgnoreCase("true");
                }
                if (attrs.getIndex("available") > -1) {
                  cache.disabled = !attrs.getValue("available").equalsIgnoreCase("true");
                }
              } catch (Exception e) {
                Log.w(cgSettings.tag, "Failed to parse cache attributes.");
              }
            }
          });

      // waypoint.cache.name
      gcCache
          .getChild(nsGC, "name")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String cacheName) {
                  cache.name = validate(cacheName);
                }
              });

      // waypoint.cache.owner
      gcCache
          .getChild(nsGC, "owner")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String cacheOwner) {
                  cache.owner = validate(cacheOwner);
                }
              });

      // waypoint.cache.type
      gcCache
          .getChild(nsGC, "type")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String body) {
                  setType(validate(body.toLowerCase()));
                }
              });

      // waypoint.cache.container
      gcCache
          .getChild(nsGC, "container")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String body) {
                  cache.size = validate(body.toLowerCase());
                }
              });

      // waypoint.cache.attributes
      // @see issue #299

      // <groundspeak:attributes>
      //   <groundspeak:attribute id="32" inc="1">Bicycles</groundspeak:attribute>
      //   <groundspeak:attribute id="13" inc="1">Available at all times</groundspeak:attribute>
      // where inc = 0 => _no, inc = 1 => _yes
      // IDs see array CACHE_ATTRIBUTES
      final Element gcAttributes = gcCache.getChild(nsGC, "attributes");

      // waypoint.cache.attribute
      final Element gcAttribute = gcAttributes.getChild(nsGC, "attribute");

      gcAttribute.setStartElementListener(
          new StartElementListener() {
            @Override
            public void start(Attributes attrs) {
              try {
                if (attrs.getIndex("id") > -1 && attrs.getIndex("inc") > -1) {
                  int attributeId = Integer.parseInt(attrs.getValue("id"));
                  boolean attributeActive = Integer.parseInt(attrs.getValue("inc")) != 0;
                  String internalId =
                      CacheAttributeTranslator.getInternalId(attributeId, attributeActive);
                  if (internalId != null) {
                    if (cache.attributes == null) {
                      cache.attributes = new ArrayList<String>();
                    }
                    cache.attributes.add(internalId);
                  }
                }
              } catch (NumberFormatException e) {
                // nothing
              }
            }
          });

      // waypoint.cache.difficulty
      gcCache
          .getChild(nsGC, "difficulty")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String body) {
                  try {
                    cache.difficulty = new Float(body);
                  } catch (Exception e) {
                    Log.w(cgSettings.tag, "Failed to parse difficulty: " + e.toString());
                  }
                }
              });

      // waypoint.cache.terrain
      gcCache
          .getChild(nsGC, "terrain")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String body) {
                  try {
                    cache.terrain = new Float(body);
                  } catch (Exception e) {
                    Log.w(cgSettings.tag, "Failed to parse terrain: " + e.toString());
                  }
                }
              });

      // waypoint.cache.country
      gcCache
          .getChild(nsGC, "country")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String country) {
                  if (cache.location == null || cache.location.length() == 0) {
                    cache.location = validate(country);
                  } else {
                    cache.location = cache.location + ", " + country.trim();
                  }
                }
              });

      // waypoint.cache.state
      gcCache
          .getChild(nsGC, "state")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String state) {
                  if (cache.location == null || cache.location.length() == 0) {
                    cache.location = validate(state);
                  } else {
                    cache.location = state.trim() + ", " + cache.location;
                  }
                }
              });

      // waypoint.cache.encoded_hints
      gcCache
          .getChild(nsGC, "encoded_hints")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String encoded) {
                  cache.hint = validate(encoded);
                }
              });

      gcCache
          .getChild(nsGC, "short_description")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String shortDesc) {
                  cache.shortdesc = validate(shortDesc);
                }
              });

      gcCache
          .getChild(nsGC, "long_description")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String desc) {
                  cache.description = validate(desc);
                }
              });

      // waypoint.cache.travelbugs
      final Element gcTBs = gcCache.getChild(nsGC, "travelbugs");

      // waypoint.cache.travelbugs.travelbug
      gcTBs
          .getChild(nsGC, "travelbug")
          .setStartElementListener(
              new StartElementListener() {

                @Override
                public void start(Attributes attrs) {
                  trackable = new cgTrackable();

                  try {
                    if (attrs.getIndex("ref") > -1) {
                      trackable.geocode = attrs.getValue("ref").toUpperCase();
                    }
                  } catch (Exception e) {
                    // nothing
                  }
                }
              });

      // waypoint.cache.travelbug
      final Element gcTB = gcTBs.getChild(nsGC, "travelbug");

      gcTB.setEndElementListener(
          new EndElementListener() {

            @Override
            public void end() {
              if (trackable.geocode != null
                  && trackable.geocode.length() > 0
                  && trackable.name != null
                  && trackable.name.length() > 0) {
                if (cache.inventory == null) {
                  cache.inventory = new ArrayList<cgTrackable>();
                }
                cache.inventory.add(trackable);
              }
            }
          });

      // waypoint.cache.travelbugs.travelbug.name
      gcTB.getChild(nsGC, "name")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String tbName) {
                  trackable.name = validate(tbName);
                }
              });

      // waypoint.cache.logs
      final Element gcLogs = gcCache.getChild(nsGC, "logs");

      // waypoint.cache.log
      final Element gcLog = gcLogs.getChild(nsGC, "log");

      gcLog.setStartElementListener(
          new StartElementListener() {

            @Override
            public void start(Attributes attrs) {
              log = new cgLog();

              try {
                if (attrs.getIndex("id") > -1) {
                  log.id = Integer.parseInt(attrs.getValue("id"));
                }
              } catch (Exception e) {
                // nothing
              }
            }
          });

      gcLog.setEndElementListener(
          new EndElementListener() {

            @Override
            public void end() {
              if (log.log != null && log.log.length() > 0) {
                if (cache.logs == null) {
                  cache.logs = new ArrayList<cgLog>();
                }
                cache.logs.add(log);
              }
            }
          });

      // waypoint.cache.logs.log.date
      gcLog
          .getChild(nsGC, "date")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String body) {
                  try {
                    log.date = parseDate(body).getTime();
                  } catch (Exception e) {
                    Log.w(cgSettings.tag, "Failed to parse log date: " + e.toString());
                  }
                }
              });

      // waypoint.cache.logs.log.type
      gcLog
          .getChild(nsGC, "type")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String body) {
                  final String logType = validate(body).toLowerCase();
                  if (cgBase.logTypes0.containsKey(logType)) {
                    log.type = cgBase.logTypes0.get(logType);
                  } else {
                    log.type = cgBase.LOG_NOTE;
                  }
                }
              });

      // waypoint.cache.logs.log.finder
      gcLog
          .getChild(nsGC, "finder")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String finderName) {
                  log.author = validate(finderName);
                }
              });

      // waypoint.cache.logs.log.text
      gcLog
          .getChild(nsGC, "text")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String logText) {
                  log.log = validate(logText);
                }
              });
    }
    boolean parsed = false;
    try {
      Xml.parse(stream, Xml.Encoding.UTF_8, root.getContentHandler());
      parsed = true;
    } catch (IOException e) {
      Log.e(cgSettings.tag, "Cannot parse .gpx file as GPX " + version + ": could not read file!");
    } catch (SAXException e) {
      Log.e(
          cgSettings.tag,
          "Cannot parse .gpx file as GPX " + version + ": could not parse XML - " + e.toString());
    }
    return parsed ? search.getCurrentId() : 0L;
  }