Esempio n. 1
0
  /**
   * Метод получения предложений на текущем языке
   *
   * @param id код предложения
   * @return строка предложения
   */
  public static String get(String id) {
    try {

      // узел с определенным id
      Node sentenceNode =
          (Node)
              xPathDictionary.evaluate("id('" + id + "')", documentDictionary, XPathConstants.NODE);

      // получение предложения на текущем языке
      NodeList list = sentenceNode.getChildNodes();
      for (int i = 0; i < list.getLength(); i++) {
        Node currentNode = list.item(i);
        if (language.equals(currentNode.getNodeName())) {
          return currentNode.getChildNodes().item(0).getNodeValue();
        }
      }

    } catch (XPathExpressionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      System.exit(0);
    }

    // возвращаем пустую строку, если произошла ошибка
    return "";
  }
  @Override
  protected String verifyWpsResponse(final String responseStr) throws Exception {
    final Document responseData = XmlDocumentBuilder.parse(responseStr, false);
    Assert.assertNotNull(responseData);
    // System.out.println(XmlDocumentBuilder.toString(responseData));

    XPath xpath = XmlDocumentBuilder.createXPath();
    String jobIdStr = null;
    try {
      Assert.assertEquals(processId, xpath.evaluate(".//Process/Identifier", responseData));
      NodeList returnedNodes = XPathAPI.selectNodeList(responseData, ".//ProcessOutputs/Output");
      Assert.assertEquals(1, returnedNodes.getLength());
      Assert.assertEquals(
          "jobId", xpath.evaluate(".//ProcessOutputs/Output/Identifier", responseData));
      Assert.assertEquals(
          "string",
          xpath.evaluate(".//ProcessOutputs/Output/Data/LiteralData/@dataType", responseData));
      jobIdStr = xpath.evaluate(".//ProcessOutputs/Output/Data/LiteralData", responseData);
      Assert.assertNotNull(UUID.fromString(jobIdStr));
    } catch (XPathExpressionException e) {
      Assert.fail("Error parsing response document: " + e.getMessage());
    }

    return jobIdStr;
  }
Esempio n. 3
0
    @Override
    protected String doInBackground(String... strings) {
      try {
        TelephonyManager telephonyManager =
            (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String query = SoapRequest1.getDepartament(telephonyManager.getDeviceId());
        ArrayList<String> parse = XMLParser.getReturnCode2(query);
        Log.d("ELEMENTS", query);
        if (parse.get(0).equals("0")) {
          state = true;
          return query;
        } else return parse.get(1);

      } catch (IOException e) {
        e.printStackTrace();
        return "No se pudo conectar con el servidor, compruebe se conexión a internet y reintente";
      } catch (SAXException e) {
        e.printStackTrace();
        return "Error al leer el XML, por favor reintente";
      } catch (ParserConfigurationException e) {
        e.printStackTrace();
        return "Error al leer el XML, por favor reintente";
      } catch (XPathExpressionException e) {
        e.printStackTrace();
        return "Error al leer el XML, por favor reintente";
      } catch (Exception e) {
        e.printStackTrace();
        return "Ha ocurrido un error, por favor reintente";
      }
    }
Esempio n. 4
0
    @Override
    protected String doInBackground(String... strings) {
      TelephonyManager telephonyManager =
          (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
      try {
        String query =
            SoapRequest1.sendCheckList(
                telephonyManager.getDeviceId(),
                estaciones.get(station.getSelectedItemPosition()).getId(),
                modulos,
                imagenes);

        ArrayList<String> response = XMLParser.getReturnCode2(query);

        ok = response.get(0).equals("0");
        if (ok) return query;
        else return response.get(1);

      } catch (SAXException e) {
        e.printStackTrace();
        return "Error al leer el XML";
      } catch (ParserConfigurationException e) {
        e.printStackTrace();
        return "Error al leer el XML";
      } catch (XPathExpressionException e) {
        e.printStackTrace();
        return "Error al leer el XML";
      } catch (IOException e) {
        e.printStackTrace();
        return "Error al leer el XML";
      } catch (Exception e) {
        e.printStackTrace();
        return "Ha ocurrido un error";
      }
    }
Esempio n. 5
0
  /**
   * Removes all the given tags from the document.
   *
   * @param dom the document object.
   * @param tagName the tag name, examples: script, style, meta
   * @return the changed dom.
   */
  public static Document removeTags(Document dom, String tagName) {
    if (dom != null) {
      // NodeList list = dom.getElementsByTagName("SCRIPT");

      NodeList list;
      try {
        list = XPathHelper.evaluateXpathExpression(dom, "//" + tagName.toUpperCase());

        while (list.getLength() > 0) {
          Node sc = list.item(0);

          if (sc != null) {
            sc.getParentNode().removeChild(sc);
          }

          list = XPathHelper.evaluateXpathExpression(dom, "//" + tagName.toUpperCase());
          // list = dom.getElementsByTagName("SCRIPT");
        }
      } catch (XPathExpressionException e) {
        LOGGER.error(e.getMessage(), e);
      }

      return dom;
    }

    return null;
  }
Esempio n. 6
0
    @Override
    public void run() {
      final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      final XPath xPath = XPathFactory.newInstance().newXPath();
      final String expression = "//" + TAG_TRACK_POINT;
      final String speedExpression = "//" + TAG_SPEED;

      NodeList nodeList = null;
      NodeList speedList = null;
      try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(traceFile);
        nodeList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
        speedList =
            (NodeList) xPath.compile(speedExpression).evaluate(document, XPathConstants.NODESET);
      } catch (ParserConfigurationException e) {
        e.printStackTrace();
      } catch (SAXException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } catch (XPathExpressionException e) {
        e.printStackTrace();
      }

      parse(nodeList, speedList);
    }
 private void checkBomVersionInPom(String xml) {
   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
   DocumentBuilder builder;
   Document doc = null;
   try {
     builder = factory.newDocumentBuilder();
     doc = builder.parse(new InputSource(new StringReader(xml)));
   } catch (SAXException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (ParserConfigurationException e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
   }
   XPathFactory xPathfactory = XPathFactory.newInstance();
   XPath xpath = xPathfactory.newXPath();
   XPathExpression expr = null;
   String bom_version = null;
   try {
     expr = xpath.compile("/project/properties/version.jboss.bom");
     bom_version = (String) expr.evaluate(doc, XPathConstants.STRING);
   } catch (XPathExpressionException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   assertEquals(
       "jboss bom version in pom differs from the one given by wizard", version, bom_version);
 }
Esempio n. 8
0
  public String extractInfoObjectIdentifier(String infoObjectResponse) {

    String reportId = null;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    // dbf.setNamespaceAware(true);
    try {
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(new ByteArrayInputStream(infoObjectResponse.getBytes("UTF-8")));

      XPathFactory factory = XPathFactory.newInstance();
      XPath xpath = factory.newXPath();
      XPathExpression expr = xpath.compile("//info-object");
      Object result = expr.evaluate(doc, XPathConstants.NODESET);

      NodeList nodes = (NodeList) result;
      Node item = nodes.item(0);
      if (item != null) {
        NamedNodeMap attributesMap = item.getAttributes();
        Node idAttribute = attributesMap.getNamedItem("id");
        reportId = idAttribute.getNodeValue();
      }

    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (XPathExpressionException e) {
      e.printStackTrace();
    }

    return reportId;
  }
Esempio n. 9
0
  /**
   * Performs an XPATH lookup in an xml document whose filename is specified by the first parameter
   * (assumed to be in the auxiliary subdirectory) The XPATH expression is supplied as the second
   * string parameter The return value is of type string e.g. this is currently used primarily for
   * looking up the Company Prefix Index for encoding a GS1 Company Prefix into a 64-bit EPC tag
   */
  private String xpathlookup(String xml, String expression) {

    try {

      // Parse the XML as a W3C document.
      DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      Document document =
          builder.parse(new File(xmldir + File.separator + "auxiliary" + File.separator + xml));

      XPath xpath = XPathFactory.newInstance().newXPath();

      String rv = (String) xpath.evaluate(expression, document, XPathConstants.STRING);

      return rv;

    } catch (ParserConfigurationException e) {
      System.err.println("ParserConfigurationException caught...");
      e.printStackTrace();
      return null;
    } catch (XPathExpressionException e) {
      System.err.println("XPathExpressionException caught...");
      e.printStackTrace();
      return null;
    } catch (SAXException e) {
      System.err.println("SAXException caught...");
      e.printStackTrace();
      return null;
    } catch (IOException e) {
      System.err.println("IOException caught...");
      e.printStackTrace();
      return null;
    }
  }
Esempio n. 10
0
  /**
   * Runs an XPath expression on this node.
   *
   * @param env
   * @param expression
   * @return array of results
   * @throws XPathExpressionException
   */
  public Value xpath(Env env, String expression) {
    try {
      XPath xpath = XPathFactory.newInstance().newXPath();

      InputSource is = new InputSource(asXML(env).toInputStream());
      NodeList nodes = (NodeList) xpath.evaluate(expression, is, XPathConstants.NODESET);

      int nodeLength = nodes.getLength();

      if (nodeLength == 0) return NullValue.NULL;

      // There are matching nodes
      ArrayValue result = new ArrayValueImpl();
      for (int i = 0; i < nodeLength; i++) {
        Node node = nodes.item(i);

        boolean isPrefix = node.getPrefix() != null;

        SimpleXMLElement xml =
            buildNode(env, _cls, null, nodes.item(i), node.getNamespaceURI(), isPrefix);

        result.put(wrapJava(env, _cls, xml));
      }

      return result;
    } catch (XPathExpressionException e) {
      env.warning(e);
      log.log(Level.FINE, e.getMessage());

      return NullValue.NULL;
    }
  }
  // read data from the starting XML file (people.xml)
  // and put them into a PeopleStore instance
  public static void initializeDB() {
    HealthProfileReader HP = new HealthProfileReader();
    List<String> peopleInfo = null;
    try {
      peopleInfo = HP.readallinfo();
    } catch (XPathExpressionException e) {
      e.printStackTrace();
    }

    // "saves" all the retrieved information about people
    for (int i = 0; i < peopleInfo.size(); i += 8) {
      Person pallino =
          new Person(
              peopleInfo.get(i + 0), // id
              peopleInfo.get(i + 1), // firstname
              peopleInfo.get(i + 2), // lastname
              peopleInfo.get(i + 3)); // birthdate

      pallino.setHProfile(
          new HealthProfile(
              peopleInfo.get(i + 4), // last update
              Double.parseDouble(peopleInfo.get(i + 5)), // weight
              Double.parseDouble(peopleInfo.get(i + 6)))); // height
      // bmi will be calculated in HealthProfile

      people.getData().add(pallino);
    }
  }
Esempio n. 12
0
  protected List<String> getHiddenAttributeNames() {
    ArrayList<String> hiddenAttributeNames = null;

    try {
      InputStream resource = getClass().getClassLoader().getResourceAsStream("amConsoleConfig.xml");
      Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(resource);
      NodeList nodes =
          (NodeList)
              XPathFactory.newInstance()
                  .newXPath()
                  .evaluate(
                      "//consoleconfig/servicesconfig/consoleservice/@realmEnableHideAttrName",
                      doc,
                      XPathConstants.NODESET);
      String rawList = nodes.item(0).getNodeValue();
      hiddenAttributeNames = new ArrayList<String>(Arrays.asList(rawList.split(" ")));
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (XPathExpressionException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return hiddenAttributeNames;
  }
Esempio n. 13
0
  private Node evaluateXPathNode(
      Node bindings, Node target, String expression, NamespaceContext namespaceContext) {
    NodeList nlst;
    try {
      xpath.setNamespaceContext(namespaceContext);
      nlst = (NodeList) xpath.evaluate(expression, target, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
      reportError(
          (Element) bindings, WsdlMessages.INTERNALIZER_X_PATH_EVALUATION_ERROR(e.getMessage()), e);
      return null; // abort processing this <jaxb:bindings>
    }

    if (nlst.getLength() == 0) {
      reportError(
          (Element) bindings, WsdlMessages.INTERNALIZER_X_PATH_EVALUATES_TO_NO_TARGET(expression));
      return null; // abort
    }

    if (nlst.getLength() != 1) {
      reportError(
          (Element) bindings,
          WsdlMessages.INTERNALIZER_X_PATH_EVAULATES_TO_TOO_MANY_TARGETS(
              expression, nlst.getLength()));
      return null; // abort
    }

    Node rnode = nlst.item(0);
    if (!(rnode instanceof Element)) {
      reportError(
          (Element) bindings,
          WsdlMessages.INTERNALIZER_X_PATH_EVALUATES_TO_NON_ELEMENT(expression));
      return null; // abort
    }
    return rnode;
  }
  public static void main(String[] args) {

    CodeExtractor myCode = new CodeExtractor(4);
    // myCode.parseFile("http://java.sun.com/docs/books/tutorial/java/nutsandbolts/for.html");
    myCode.parseFile("http://www.javadeveloper.co.in/java-example/java-hashmap-example.html");

    String docString = myCode.getDoc();
    try {
      XPath xPath = XPathFactory.newInstance().newXPath();
      XPathExpression nodeXPathExpr =
          xPath.compile("/codesnippets/text | /codesnippets/sourcecode");
      InputSource inputSource = new InputSource(new ByteArrayInputStream(docString.getBytes()));

      NodeList allNodes = (NodeList) nodeXPathExpr.evaluate(inputSource, XPathConstants.NODESET);

      int nodeNumber = allNodes.getLength();
      System.out.println("Text Found:: " + nodeNumber + " nodes.");
      System.out.println("========================================");

      for (int i = 0; i < nodeNumber; i++) {
        Node node = allNodes.item(i);

        String content = node.getTextContent();
        // content = StringEscapeUtils.unescapeHtml(content).trim();
        System.out.println(node + ":--->:" + node.getNodeName());
        if (node.getTextContent() != null) System.out.println("--->" + content);
        System.out.println("========================================");
      }

    } catch (XPathExpressionException e) {
      e.printStackTrace();
    }
  }
 /**
  * Update an application in the manifest
  *
  * @param app app to replace for
  */
 public void updateApplication(PhoneLabApplication app) {
   try {
     Node node =
         (Node)
             xpath.evaluate(
                 "/manifest/statusmonitor/parameter[@package_name='" + app.getPackageName() + "']",
                 document,
                 XPathConstants.NODE);
     if (node != null) { // exist
       Node parentNode = node.getParentNode();
       parentNode.removeChild(node);
       Element newElement = document.createElement("application");
       if (app.getPackageName() != null)
         newElement.setAttribute("package_name", app.getPackageName());
       if (app.getName() != null) newElement.setAttribute("name", app.getName());
       if (app.getDescription() != null)
         newElement.setAttribute("description", app.getDescription());
       if (app.getType() != null) newElement.setAttribute("type", app.getType());
       if (app.getStartTime() != null) newElement.setAttribute("start_time", app.getStartTime());
       if (app.getEndTime() != null) newElement.setAttribute("end_time", app.getEndTime());
       if (app.getDownload() != null) newElement.setAttribute("download", app.getDownload());
       if (app.getVersion() != null) newElement.setAttribute("version", app.getVersion());
       if (app.getAction() != null) newElement.setAttribute("action", app.getAction());
       document.getFirstChild().appendChild(newElement);
     }
   } catch (XPathExpressionException e) {
     e.printStackTrace();
   }
 }
Esempio n. 16
0
  public List<String> getOriginCatalogs() {

    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();

    List<String> catalogs = new ArrayList<String>();
    try {
      XPathExpression expr = xpath.compile("//Resolver");

      NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
      for (int i = 0; i < nodes.getLength(); i++) {
        XPathExpression hasAliasExp = xpath.compile("./alias");
        NodeList aliases = (NodeList) hasAliasExp.evaluate(nodes.item(i), XPathConstants.NODESET);
        if (aliases.getLength() > 0) {
          XPathExpression nameAttribute = xpath.compile("@name");
          String name = (String) nameAttribute.evaluate(nodes.item(i), XPathConstants.STRING);
          catalogs.add(name);
        }
      }

    } catch (XPathExpressionException e) {
      e.printStackTrace();
    }

    return catalogs;
  }
  private Element evaluateXPathNode(
      Node target, String expression, NamespaceContext namespaceContext) {
    NodeList nlst;
    try {
      xpath.setNamespaceContext(namespaceContext);
      nlst = (NodeList) xpath.evaluate(expression, target, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
      Util.fail("internalizer.XPathEvaluationError", e.getMessage());
      return null; // abort processing this <jaxb:bindings>
    }

    if (nlst.getLength() == 0) {
      Util.fail("internalizer.XPathEvaluatesToNoTarget", new Object[] {expression});
      return null; // abort
    }

    if (nlst.getLength() != 1) {
      Util.fail(
          "internalizer.XPathEvaulatesToTooManyTargets",
          new Object[] {expression, nlst.getLength()});
      return null; // abort
    }

    Node rnode = nlst.item(0);
    if (!(rnode instanceof Element)) {
      Util.fail("internalizer.XPathEvaluatesToNonElement", new Object[] {expression});
      return null; // abort
    }
    return (Element) rnode;
  }
Esempio n. 18
0
  /**
   * Initialize the GuideXML class with a local file XML path
   *
   * @param context the app context
   * @param guideId the guide identifier
   * @param path the local file name of the guide XML file
   */
  public GuideXML(Context context, String guideId, String path) {
    mContext = context;
    mGuideId = guideId;

    FileReader fr = null;
    try {
      fr = new FileReader(path);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      return;
    }
    InputSource inputSource = new InputSource(fr);

    mTagCounts = new HashMap<String, Integer>();
    mTags = new HashMap<String, Set<String>>();

    try {
      // Read root node so we won't re-parse the XML file every time we evaluate an XPath
      XPath xpath = XPathFactory.newInstance().newXPath();
      setRootNode((Node) xpath.evaluate("/", inputSource, XPathConstants.NODE));

      // Parse all taxon tags
      parseTags();
    } catch (XPathExpressionException e) {
      e.printStackTrace();
    }
  }
Esempio n. 19
0
  public void retrieveNews() {

    try {

      //			HttpClient client = new DefaultHttpClient();
      //			HttpResponse response = client.execute(new
      // HttpGet("http://uaonline.ua.pt/xml/contents_xml.asp"));
      //			HttpEntity tmpEntity = response.getEntity();

      //			SAXParser xmlParser = SAXParserFactory.newInstance().newSAXParser();
      //			XMLReader xmlReader = xmlParser.getXMLReader();
      //			NewsHandler newsHandler = new NewsHandler();
      //			xmlReader.setContentHandler(newsHandler);
      //
      //			Reader test = new InputStreamReader(uaNewsURL.openStream());
      //			InputSource is = new InputSource(test);
      //			is.setEncoding("ISO-8859-1");
      //			xmlReader.parse(is);
      //			return newsHandler.getFeed();

      URL uaNewsURL = new URL("http://uaonline.ua.pt/xml/contents_xml.asp");
      DocumentBuilder xmlBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      Document xmlNews = xmlBuilder.parse(uaNewsURL.openStream());

      XPath query;
      NodeList newsItems;
      query = XPathFactory.newInstance().newXPath();
      Object result = query.compile("/rss/channel/item").evaluate(xmlNews, XPathConstants.NODESET);
      newsItems = (NodeList) result;

      NewsItem tempItem;
      Element tmpElem;
      for (int i = 0; i < newsItems.getLength(); i++) {
        tmpElem = (Element) newsItems.item(i);

        tempItem = parseInfo(tmpElem);
        this.addItem(tempItem);
      }

    } catch (MalformedURLException e) {
      System.out.println("NewsFeed: retrieveNews: " + e.getMessage());
      System.out.println(
          "NewsFeed: retrieveNews: MalformedURLException " + e.getLocalizedMessage());
    } catch (ParserConfigurationException e) {
      System.out.println("NewsFeed: retrieveNews: " + e.getMessage());
      System.out.println(
          "NewsFeed: retrieveNews: ParserConfigurationException " + e.getLocalizedMessage());
    } catch (IOException e) {
      System.out.println("NewsFeed: retrieveNews: " + e.getMessage());
      System.out.println("NewsFeed: retrieveNews: IOException " + e.getLocalizedMessage());
    } catch (XPathExpressionException e) {
      System.out.println("NewsFeed: retrieveNews: " + e.getMessage());
      System.out.println(
          "NewsFeed: retrieveNews: XPathExpressionException " + e.getLocalizedMessage());
    } catch (SAXException e) {
      System.out.println("NewsFeed: retrieveNews: " + e.getMessage());
      System.out.println("NewsFeed: retrieveNews: SAXException " + e.getLocalizedMessage());
    }
  }
Esempio n. 20
0
 public KModuleDeploymentService() {
   try {
     processIdXPathExpression = XPathFactory.newInstance().newXPath().compile(PROCESS_ID_XPATH);
   } catch (XPathExpressionException e) {
     logger.error(
         "Unable to parse '{}' XPath expression due to {}", PROCESS_ID_XPATH, e.getMessage());
   }
 }
Esempio n. 21
0
 public String getStr(String path) {
   try {
     if (!"".equals(root) && root != null) path = root + "/" + path;
     return pather.evaluate(path, doc);
   } catch (XPathExpressionException e) {
     e.printStackTrace();
   }
   return "";
 }
Esempio n. 22
0
 /**
  * Najde Node podle XPath vyrazu
  *
  * @param document
  * @param xPathExpression
  * @return uzel
  * @throws ProblemException
  * @author mstastny
  */
 public static Node findNode(Node document, String xPathExpression) throws ProblemException {
   try {
     XPath xpath = XPathFactory.newInstance().newXPath();
     Node node = (Node) xpath.evaluate(xPathExpression, document, XPathConstants.NODE);
     return node;
   } catch (XPathExpressionException e) {
     logger.error(e.toString(), e);
     throw new ProblemException(e, XmlProblem.XPATH, e.toString());
   }
 }
Esempio n. 23
0
  private void initFromXml(Element ele, Version fileVersion) throws ParseException {
    try {
      partNumber = SaveUtil.parseValue(ele, "@id", partNumber);
      title = SaveUtil.parseValue(ele, "title", title);
      instrument = SaveUtil.parseValue(ele, "instrument", instrument);
      for (Element trackEle : XmlUtil.selectElements(ele, "track")) {
        // Try to find the specified track in the midi sequence by name, in case it moved
        int t = findTrackNumberByName(SaveUtil.parseValue(trackEle, "@name", ""));
        // Fall back to the track ID if that didn't work
        if (t == -1) t = SaveUtil.parseValue(trackEle, "@id", -1);

        if (t < 0 || t >= getTrackCount()) {
          throw SaveUtil.invalidValueException(
              trackEle, "Could not find track number " + t + " in original MIDI file");
        }

        // Now set the track info
        trackEnabled[t] = true;
        enabledTrackCount++;
        trackTranspose[t] = SaveUtil.parseValue(trackEle, "transpose", trackTranspose[t]);
        trackVolumeAdjust[t] = SaveUtil.parseValue(trackEle, "volumeAdjust", trackVolumeAdjust[t]);

        if (instrument.isPercussion) {
          Element drumsEle = XmlUtil.selectSingleElement(trackEle, "drumsEnabled");
          if (drumsEle != null) {
            boolean defaultEnabled =
                SaveUtil.parseValue(drumsEle, "@defaultEnabled", !isCowbellPart());

            BitSet[] enabledSet;
            if (isCowbellPart()) {
              if (cowbellsEnabled == null) cowbellsEnabled = new BitSet[getTrackCount()];
              enabledSet = cowbellsEnabled;
            } else {
              if (drumsEnabled == null) drumsEnabled = new BitSet[getTrackCount()];
              enabledSet = drumsEnabled;
            }

            enabledSet[t] = new BitSet(MidiConstants.NOTE_COUNT);
            if (defaultEnabled) enabledSet[t].set(0, MidiConstants.NOTE_COUNT, true);

            for (Element drumEle : XmlUtil.selectElements(drumsEle, "note")) {
              int id = SaveUtil.parseValue(drumEle, "@id", -1);
              if (id >= 0 && id < MidiConstants.NOTE_COUNT)
                enabledSet[t].set(id, SaveUtil.parseValue(drumEle, "@isEnabled", !defaultEnabled));
            }
          }

          Element drumMapEle = XmlUtil.selectSingleElement(trackEle, "drumMap");
          if (drumMapEle != null) drumNoteMap[t] = DrumNoteMap.loadFromXml(drumMapEle, fileVersion);
        }
      }
    } catch (XPathExpressionException e) {
      throw new ParseException("XPath error: " + e.getMessage(), null);
    }
  }
Esempio n. 24
0
 public String getAttr(String path, String attrName) {
   if (!"".equals(root) && root != null) path = root + "/" + path;
   try {
     return pather.evaluate(
         new StringBuilder().append(path).append("/@").append(attrName).toString(), doc);
   } catch (XPathExpressionException e) {
     e.printStackTrace(); // To change body of catch statement use File | Settings | File
     // Templates.
   }
   return "";
 }
  private List<ICompletionProposal> proposeParameter(
      IJavaProject project,
      final int offset,
      final int length,
      Node statementNode,
      final boolean searchReadable,
      final String matchString) {
    List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
    if (statementNode == null) return proposals;
    String statementId = null;
    String paramType = null;
    NamedNodeMap statementAttrs = statementNode.getAttributes();
    for (int i = 0; i < statementAttrs.getLength(); i++) {
      Node attr = statementAttrs.item(i);
      String attrName = attr.getNodeName();
      if ("id".equals(attrName)) statementId = attr.getNodeValue();
      else if ("parameterType".equals(attrName)) paramType = attr.getNodeValue();
    }
    if (statementId == null || statementId.length() == 0) return proposals;

    if (paramType != null) {
      String resolved = TypeAliasCache.getInstance().resolveAlias(project, paramType, null);
      proposals =
          ProposalComputorHelper.proposePropertyFor(
              project,
              offset,
              length,
              resolved != null ? resolved : paramType,
              searchReadable,
              -1,
              matchString);
    } else {
      try {
        final List<MapperMethodInfo> methodInfos = new ArrayList<MapperMethodInfo>();
        String mapperFqn = MybatipseXmlUtil.getNamespace(statementNode.getOwnerDocument());
        JavaMapperUtil.findMapperMethod(
            methodInfos, project, mapperFqn, statementId, true, new RejectStatementAnnotation());
        if (methodInfos.size() > 0) {
          proposals =
              ProposalComputorHelper.proposeParameters(
                  project,
                  offset,
                  length,
                  methodInfos.get(0).getParams(),
                  searchReadable,
                  matchString);
        }
      } catch (XPathExpressionException e) {
        Activator.log(Status.ERROR, e.getMessage(), e);
      }
    }
    return proposals;
  }
Esempio n. 26
0
  public PlacesFile() throws ParserConfigurationException {

    // this.setErrorMessage(ApiConstants.IMAPISuccessCode, "");

    try {
      this.builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

      this.document =
          builder.parse(ApiConfigClass.class.getResourceAsStream("/PlacesTranslation(TypeB).xml"));
      XPath xpath = XPathFactory.newInstance().newXPath();

      if (this.XpahthPlaces != null) {
        NodeList nodesDuch =
            (NodeList) xpath.evaluate(this.XpahthPlacesDutch, document, XPathConstants.NODESET);
        NodeList nodesEnglish =
            (NodeList) xpath.evaluate(this.XpahthPlacesEnglish, document, XPathConstants.NODESET);
        if (nodesDuch != null && nodesEnglish != null) {

          int howmanyNodes = nodesDuch.getLength();

          for (int i = 0; i < howmanyNodes; i++) {

            String Dutch = "", English = "";

            Node xNodeDuch = nodesDuch.item(i);
            Dutch = xNodeDuch.getNodeValue();

            Node xNodeEnglish = nodesEnglish.item(i);
            try {
              English = xNodeEnglish.getNodeValue();
            } catch (DOMException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }

            this.placesTrans.put(Dutch, English);
          }
        }
      }

    } catch (SAXException e) {
      String tempMsg = "SAXException occured:\r\n" + e.getMessage();
      this.setErrorMessage(ApiConstants.IMAPIFailCode, tempMsg);
      Utilities.handleException(e);
    } catch (IOException e) {
      String tempMsg = "IOException occured:\r\n" + e.getMessage();
      this.setErrorMessage(ApiConstants.IMAPIFailCode, tempMsg);
      Utilities.handleException(e);
    } catch (XPathExpressionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Esempio n. 27
0
  public static Node selectSingleNode(String express, Object source) { // 查找节点,并返回第一个符合条件节点
    Node result = null;
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    try {
      result = (Node) xpath.evaluate(express, source, XPathConstants.NODE);
    } catch (XPathExpressionException e) {
      e.printStackTrace();
    }

    return result;
  }
 public LFParseEnricher() {
   XPathFactory factory = XPathFactory.newInstance();
   xpath = factory.newXPath();
   try {
     theoryXPath = xpath.compile("//theory");
     viewXPath = xpath.compile("//view");
     viewXPath = xpath.compile("//include");
   } catch (XPathExpressionException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Esempio n. 29
0
  /**
   * Extracts the workflow from the plan.
   *
   * @param plan the plan to extract the workflow from.
   * @return The workflow File
   * @throws PluginException if an error occurs extracting the workflow from the plan.
   */
  private File getWorkflowFile(final Document plan) throws PluginException {

    final XPathFactory xPathfactory = XPathFactory.newInstance();
    final XPath xpath = xPathfactory.newXPath();

    Writer writer = null;
    try {

      xpath.setNamespaceContext(new PlanNamespaceContext());
      final XPathExpression expr = xpath.compile(xpathSelectWorkflow);
      final Element elementWorkflow = (Element) expr.evaluate(plan, XPathConstants.NODE);

      // Prepare the DOM document for writing
      final Source source = new DOMSource(elementWorkflow);
      final File workflowFile = new File(new File(RODA_HOME, "data"), WORKFLOW_FILENAME);
      writer = new OutputStreamWriter(new FileOutputStream(workflowFile));
      final Result result = new StreamResult(writer);

      // Write the DOM document to the file
      final Transformer xformer = TransformerFactory.newInstance().newTransformer();
      xformer.transform(source, result);

      writer.close();

      return workflowFile;

    } catch (XPathExpressionException e) {
      logger.error("Error compiling XPATH expression or evaluating the plan - " + e.getMessage());
      throw new PluginException(
          "Error compiling XPATH expression or evaluating the plan - " + e.getMessage(), e);
    } catch (FileNotFoundException e) {
      logger.error("Error opening output file for writting - " + e.getMessage());
      throw new PluginException("Error opening output file for writting - " + e.getMessage(), e);
    } catch (TransformerFactoryConfigurationError e) {
      logger.error("Error writing workflow file - " + e.getMessage());
      throw new PluginException("Error writing workflow file - " + e.getMessage(), e);
    } catch (TransformerException e) {
      logger.error("Error writing workflow file - " + e.getMessage());
      throw new PluginException("Error writing workflow file - " + e.getMessage(), e);
    } catch (IOException e) {
      logger.error("Error writing workflow file - " + e.getMessage());
      throw new PluginException("Error writing workflow file - " + e.getMessage(), e);
    } finally {

      if (writer != null) {
        try {
          writer.close();
        } catch (IOException e) {
          logger.error("Error closing output writer - " + e.getMessage());
        }
      }
    }
  }
Esempio n. 30
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    javax.servlet.http.Cookie[] theCookies = request.getCookies();

    String param = null;
    boolean foundit = false;
    if (theCookies != null) {
      for (javax.servlet.http.Cookie theCookie : theCookies) {
        if (theCookie.getName().equals("vector")) {
          param = java.net.URLDecoder.decode(theCookie.getValue(), "UTF-8");
          foundit = true;
        }
      }
      if (!foundit) {
        // no cookie found in collection
        param = "";
      }
    } else {
      // no cookies
      param = "";
    }

    String bar = new Test().doSomething(param);

    try {
      java.io.FileInputStream file =
          new java.io.FileInputStream(
              org.owasp.benchmark.helpers.Utils.getFileFromClasspath(
                  "employees.xml", this.getClass().getClassLoader()));
      javax.xml.parsers.DocumentBuilderFactory builderFactory =
          javax.xml.parsers.DocumentBuilderFactory.newInstance();
      javax.xml.parsers.DocumentBuilder builder = builderFactory.newDocumentBuilder();
      org.w3c.dom.Document xmlDocument = builder.parse(file);
      javax.xml.xpath.XPathFactory xpf = javax.xml.xpath.XPathFactory.newInstance();
      javax.xml.xpath.XPath xp = xpf.newXPath();

      response.getWriter().println("Your query results are: <br/>");
      String expression = "/Employees/Employee[@emplid='" + bar + "']";
      response.getWriter().println(xp.evaluate(expression, xmlDocument) + "<br/>");

    } catch (javax.xml.xpath.XPathExpressionException e) {
      // OK to swallow
      System.out.println("XPath expression exception caught and swallowed: " + e.getMessage());
    } catch (javax.xml.parsers.ParserConfigurationException e) {
      System.out.println("XPath expression exception caught and swallowed: " + e.getMessage());
    } catch (org.xml.sax.SAXException e) {
      System.out.println("XPath expression exception caught and swallowed: " + e.getMessage());
    }
  } // end doPost