/**
   * Method to parse a Var (Variable)
   *
   * @param var Element The XOM element that represents the Var to be parsed.
   * @return Returns the data structure that represents the Var in a way that can be used by the
   *     reasoning engine.
   * @throws ParseException Thrown if there is an error parsing the Var.
   */
  private Term parseVar(Element var) throws ParseException {
    String symbolName = var.getValue().trim();

    if (symbolName.isEmpty()) {
      symbolName = generateAnonymousIdentifier();
    }

    int sym = this.internVariable(symbolName);
    int typeid = parseTypeAttribute(var);

    logger.debug("Parsing variable: symbol = " + sym + " type = " + typeid);

    Vector<Integer> v;

    if (this.varClasses.containsKey(sym)) {
      v = varClasses.get(sym);
    } else {
      v = new Vector<Integer>();
      varClasses.put(sym, v);
    }

    v.add(typeid);

    logger.debug("Added Type Information");

    return new Term(sym, SymbolTable.INOROLE, typeid);
  }
  private static boolean isLive(String aServer) {
    try {
      URL url = new URL(aServer + "health");
      HttpURLConnection uc = (HttpURLConnection) url.openConnection();

      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(BUNDLE.get("TC_STATUS_CHECK"), url);
      }

      if (uc.getResponseCode() == 200) {
        Document xml = new Builder().build(uc.getInputStream());
        Element response = (Element) xml.getRootElement();
        Element health = response.getFirstChildElement("health");
        String status = health.getValue();

        if (status.equals("dying") || status.equals("sick")) {
          if (LOGGER.isWarnEnabled()) {
            LOGGER.warn(BUNDLE.get("TC_SERVER_STATUS"), status);
          }

          return true;
        } else if (status.equals("ok")) {
          return true;
        } else {
          LOGGER.error(BUNDLE.get("TC_UNEXPECTED_STATUS"), status);
        }
      }
    } catch (UnknownHostException details) {
      LOGGER.error(BUNDLE.get("TC_UNKNOWN_HOST"), details.getMessage());
    } catch (Exception details) {
      LOGGER.error(details.getMessage());
    }

    return false;
  }
  /**
   * Method to parse a Slot
   *
   * @param slot Element The XOM element that represents the slot to be parsed.
   * @return Returns the data structure that represents the slot in a way that can be used by the
   *     reasoning engine.
   * @throws ParseException Thrown if there is an error parsing the slot.
   */
  private Term parseSlot(Element slot) throws ParseException {
    Elements children = slot.getChildElements();

    Element firstChildName = children.get(0);
    boolean dataSlot = false;
    if (firstChildName.getLocalName().equals(tagNames.DATA)) {
      dataSlot = true;
    }

    if (!firstChildName.getLocalName().equals(tagNames.IND)
        && !firstChildName.getLocalName().equals(tagNames.DATA)) {
      throw new ParseException("In a <slot> only <Ind> and <Data> are allowed.");
    }
    // Getting the Role from the symbol Table, it will assign one if it
    // doesnt already exist
    int role = SymbolTable.internRole(firstChildName.getValue().trim());

    Element element = children.get(1);
    Term term = parseDefaultElement(element);

    term.setRole(role);

    if (dataSlot) {
      term.setDataSlot(true);
    }

    return term;
  }
  private static void cacheImage(String aServer, String aID) {
    try {
      String id = URLEncoder.encode(aID, "UTF-8");
      String baseURL = aServer + "view/image/" + id;
      URL url = new URL(baseURL + "/info.xml");
      HttpURLConnection uc = (HttpURLConnection) url.openConnection();
      int status = uc.getResponseCode();

      if (status == 200) {
        Document xml = new Builder().build(uc.getInputStream());
        Element info = (Element) xml.getRootElement();
        Element elem = info.getFirstChildElement("identifier", IIIF_NS);
        Element hElem = info.getFirstChildElement("height", IIIF_NS);
        Element wElem = info.getFirstChildElement("width", IIIF_NS);
        String idValue = elem.getValue();

        try {
          int height = Integer.parseInt(hElem.getValue());
          int width = Integer.parseInt(wElem.getValue());
          Iterator<String> tileIterator;
          List<String> tiles;

          if (idValue.equals(aID) && height > 0 && width > 0) {
            if (idValue.startsWith("/") && LOGGER.isWarnEnabled()) {
              LOGGER.warn(BUNDLE.get("TC_SLASH_ID"), aID);
            }

            tiles = CacheUtils.getCachingQueries(height, width);
            tileIterator = tiles.iterator();

            while (tileIterator.hasNext()) {
              cacheTile(baseURL + tileIterator.next());
            }
          } else if (LOGGER.isErrorEnabled()) {
            LOGGER.error(BUNDLE.get("TC_ID_404"), aID);
          }
        } catch (NumberFormatException nfe) {
          LOGGER.error(BUNDLE.get("TC_INVALID_DIMS"), aID);
        }
      } else {
        LOGGER.error(BUNDLE.get("TC_SERVER_STATUS_CODE"), status);
      }
    } catch (Exception details) {
      LOGGER.error(details.getMessage());
    }
  }
  /**
   * Read urn.
   *
   * @param file the file
   * @return The URN specified in the METS file or null if the METS file doesn't specify an URN
   * @throws IOException Signals that an I/O exception has occurred.
   * @throws ParseException the parse exception
   * @author Thomas Kleinke
   */
  public String readURN(File file) throws IOException, ParseException {

    FileInputStream fileInputStream = new FileInputStream(file);
    BOMInputStream bomInputStream = new BOMInputStream(fileInputStream);

    XMLReader xmlReader = null;
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {
      xmlReader = spf.newSAXParser().getXMLReader();
    } catch (Exception e) {
      fileInputStream.close();
      bomInputStream.close();
      throw new IOException("Error creating SAX parser", e);
    }
    xmlReader.setErrorHandler(err);
    NodeFactory nodeFactory = new PremisXmlReaderNodeFactory();
    Builder parser = new Builder(xmlReader, false, nodeFactory);
    logger.trace("Successfully built builder and XML reader");

    try {
      String urn = null;

      Document doc = parser.build(bomInputStream);
      Element root = doc.getRootElement();

      Element dmdSecEl = root.getFirstChildElement("dmdSec", METS_NS);
      if (dmdSecEl == null) return null;

      Element mdWrapEl = dmdSecEl.getFirstChildElement("mdWrap", METS_NS);
      if (mdWrapEl == null) return null;

      Element xmlDataEl = mdWrapEl.getFirstChildElement("xmlData", METS_NS);
      if (xmlDataEl == null) return null;

      Element modsEl = xmlDataEl.getFirstChildElement("mods", MODS_NS);
      if (modsEl == null) return null;

      Elements identifierEls = modsEl.getChildElements("identifier", MODS_NS);
      for (int i = 0; i < identifierEls.size(); i++) {
        Element element = identifierEls.get(i);
        Attribute attribute = element.getAttribute("type");
        if (attribute.getValue().toLowerCase().equals("urn")) urn = element.getValue();
      }

      if (urn != null && urn.equals("")) urn = null;

      return urn;
    } catch (ValidityException ve) {
      throw new IOException(ve);
    } catch (ParsingException pe) {
      throw new IOException(pe);
    } catch (IOException ie) {
      throw new IOException(ie);
    } finally {
      fileInputStream.close();
      bomInputStream.close();
    }
  }
  /**
   * Parse a simple element that just contains plain data (like <Ind> and <Data>).
   *
   * @param element The element to parse
   * @return A Term data structure that represents the element in a way that can be understood by
   *     the reasoning engine.
   * @throws ParseException Thrown if the type specified in the optional type attribute is invalid.
   */
  private Term parseSimpleElement(Element element) throws ParseException {
    String symbolName = element.getValue().trim();

    if (symbolName.isEmpty()) {
      symbolName = generateAnonymousIdentifier();
    }

    int sym = SymbolTable.internSymbol(symbolName);
    int typeid = parseTypeAttribute(element);

    return new Term(sym, SymbolTable.INOROLE, typeid);
  }
  public int getContentMetadata(Integer csaId, Integer wholesaleOfferId, Integer consumerOfferID)
      throws ICTomorrowApiException {
    try {
      FormEncodedPayload data = new FormEncodedPayload();

      addOptionalParameter(data, "csa_id", csaId);
      addOptionalParameter(data, "wholesale_offer_id", wholesaleOfferId);
      addOptionalParameter(data, "consumer_offer_id", consumerOfferID);
      Element resultElem = getResultElement(client.post(GET_CONTENT_METADATA_URL, data));
      return Integer.valueOf(resultElem.getValue().trim());
    } catch (HttpException e) {
      throw new ICTomorrowApiException("Exception while recording consumer activity", e);
    }
  }
  /**
   * Unmarshal the text element into this object.
   *
   * <p>This unmarshaller only handles plain text content, although it can recognise the three
   * different type elements of text, html and xhtml. This is an area that can be improved in a
   * future implementation, if necessary.
   *
   * @param element The text element.
   * @param validationProperties
   * @throws UnmarshallException If the specified element is not of the correct type, where the
   *     localname is used to specify the valid name. Also thrown if there is an issue accessing the
   *     data.
   */
  public SwordValidationInfo unmarshall(Element element, Properties validationProperties)
      throws UnmarshallException {
    if (!isInstanceOf(element, xmlName)) {
      return handleIncorrectElement(element, validationProperties);
    }

    ArrayList<SwordValidationInfo> validationItems = new ArrayList<SwordValidationInfo>();
    ArrayList<SwordValidationInfo> attributeItems = new ArrayList<SwordValidationInfo>();

    try {
      processUnexpectedAttributes(element, attributeItems);

      int length = element.getChildCount();
      if (length > 0) {
        try {
          unmarshallContent(element);
        } catch (UnmarshallException ume) {
          log.error(
              "Error accessing the content of the " + xmlName.getQualifiedName() + "  element");
          if (validationProperties == null) {
            throw ume;
          } else {
            SwordValidationInfo info =
                new SwordValidationInfo(
                    xmlName, SwordValidationInfo.ERROR_WITH_CONTENT, SwordValidationInfoType.ERROR);
            info.setContentDescription(element.getValue());
            validationItems.add(info);
          }
        }
      }

    } catch (Exception ex) {
      log.error("Unable to parse an element in " + getQualifiedName() + ": " + ex.getMessage());
      if (validationProperties == null) {
        throw new UnmarshallException("Unable to parse an element in " + getQualifiedName(), ex);
      }
    }

    SwordValidationInfo result = null;
    if (validationProperties != null) {
      result = validate(validationItems, attributeItems, validationProperties);
    }
    return result;
  }
  /**
   * Method to parse a Skolem constant
   *
   * @param sko Element The XOM element that represents the Skolem to be parsed.
   * @return Returns the data structure that represents the Skolem in a way that can be used by the
   *     reasoning engine.
   * @throws ParseException Thrown if there is an error parsing the Skolem.
   */
  private Term parseSkolem(Element sko) throws ParseException {
    String skoname = sko.getValue().trim();

    if (skoname.isEmpty()) {
      return new Term(
          SymbolTable.internSymbol("$gensym" + SymbolTable.genid++),
          SymbolTable.INOROLE,
          Types.ITHING);
    } else {
      if (this.skolemMap.containsKey(skoname)) {
        String sym = skolemMap.get(skoname);
        return new Term(SymbolTable.internSymbol(sym), SymbolTable.INOROLE, Types.ITHING);
      } else {
        String sym = "$gensym" + (SymbolTable.genid++) + "$" + skoname;
        skolemMap.put(skoname, sym);
        return new Term(SymbolTable.internSymbol(sym), SymbolTable.INOROLE, Types.ITHING);
      }
    }
  }
 public static void runCommentExamples(Element template) {
   Text2XMLTemplateConverter tc = new Text2XMLTemplateConverter(template);
   Nodes exampleInputComments = template.query("comment[@class='" + EXAMPLE_INPUT + "' and @id]");
   if (exampleInputComments.size() == 0) {
     throw new RuntimeException("No examples found");
   }
   for (int j = 0; j < exampleInputComments.size(); j++) {
     Element exampleInput = (Element) exampleInputComments.get(j);
     String id = exampleInput.getAttributeValue(ID);
     if (id == null) {
       throw new RuntimeException("outputElement must have id: ");
     }
     Element outputElement = getOutputElement(template, id);
     if (outputElement == null) {
       throw new RuntimeException("Cannot create OutputElement: " + id);
     }
     String exampleContent = exampleInput.getValue();
     Element outputXML = parseText(tc, exampleContent);
     JumboTestUtils.assertEqualsCanonically("template", outputElement, outputXML, true);
   }
 }
Beispiel #11
0
  /**
   * Method to parse a Expr (Expresion)
   *
   * @param expr Element The XOM element that represents the Expr to be parsed.
   * @return Returns the data structure that represents the Expr in a way that can be used by the
   *     reasoning engine.
   * @throws ParseException Thrown if there is an error parsing the Expr.
   */
  private Term parseExpression(Element expr) throws ParseException {
    Elements children = expr.getChildElements();
    Element op = children.get(0);

    boolean foundOp = false;

    if (op.getLocalName().equals(tagNames.OP)) {
      foundOp = true;
    }

    Element fun = null;
    if (foundOp) {
      Elements funTag = op.getChildElements();
      fun = funTag.get(0);

      // Remove <op> element including its child element <Fun>, so
      // it will not be parsed twice
      expr.removeChild(op);
    }

    if (!foundOp) {
      fun = children.get(0);

      // Remove <Fun> element so that it will not be parsed twice
      expr.removeChild(fun);
    }

    if (!fun.getLocalName().equals(tagNames.FUN)) {
      throw new ParseException("First child of op in an Expr must be a Fun element.");
    }

    int symbol = SymbolTable.internSymbol(fun.getValue().trim());
    int typeid = parseTypeAttribute(expr);

    Vector<Term> subterms = parseDefaultElements(expr);
    Term t = new Term(symbol, SymbolTable.INOROLE, typeid, subterms);
    return t;
  }
  public TestCaseTemplateParameter(String xmlData) throws Exception {

    Document doc = new Builder().build(xmlData, null);
    Element root = doc.getRootElement();

    Elements importElements = root.getChildElements("import");
    for (int i = 0; i < importElements.size(); i++) {
      Element importElement = importElements.get(i);
      this.addImport(importElement.getValue());
    }

    Elements classToMockElements = root.getChildElements("classToMock");
    for (int i = 0; i < classToMockElements.size(); i++) {
      Element classToMockElement = classToMockElements.get(i);
      Element classNameElement = classToMockElement.getFirstChildElement("className");
      Element instanceNameElement = classToMockElement.getFirstChildElement("instanceName");
      this.addClassToMockInstanceName(classNameElement.getValue(), instanceNameElement.getValue());
      Elements invokeElements = classToMockElement.getChildElements("invoke");
      ArrayList<String> invokeList = new ArrayList<String>();
      for (int j = 0; j < invokeElements.size(); j++) {
        Element invokeElement = invokeElements.get(j);
        invokeList.add(invokeElement.getValue());
      }
      this.addJMockInvokeSequence(classNameElement.getValue(), invokeList.toArray(new String[0]));
    }

    this.setPackageName(root.getFirstChildElement("packageName").getValue());
    this.setClassUnderTest(root.getFirstChildElement("classUnderTest").getValue());

    Elements constructorArguments = root.getChildElements("constructorArgument");
    for (int i = 0; i < constructorArguments.size(); i++) {
      Element constructorArgumentElement = constructorArguments.get(i);
      String type = constructorArgumentElement.getFirstChildElement("type").getValue();
      String value = constructorArgumentElement.getFirstChildElement("value").getValue();
      this.addConstructorArgument(type, value);
    }

    this.setMethodUnderTest(root.getFirstChildElement("methodUnderTest").getValue());

    Elements methodParameters = root.getChildElements("methodParameter");
    for (int i = 0; i < methodParameters.size(); i++) {
      Element methodParameterElement = methodParameters.get(i);
      String type = methodParameterElement.getFirstChildElement("type").getValue();
      String name = methodParameterElement.getFirstChildElement("name").getValue();
      this.addMethodParameter(type, name);
    }

    this.setStaticMethod(
        Boolean.parseBoolean(root.getFirstChildElement("isStaticMethod").getValue()));

    if (root.getFirstChildElement("singletonMethod") != null) {
      this.setSingletonMethod(root.getFirstChildElement("singletonMethod").getValue());
    }

    if (root.getFirstChildElement("checkStateMethod") != null) {
      this.setCheckStateMethod(root.getFirstChildElement("checkStateMethod").getValue());
    }

    this.setReturnType(root.getFirstChildElement("returnType").getValue());

    if (root.getFirstChildElement("delta") != null) {
      this.setDelta(Double.parseDouble(root.getFirstChildElement("delta").getValue()));
    }
  }
 /** @see net.sf.memoranda.Event#getText() */
 public String getText() {
   return _elem.getValue();
 }
Beispiel #14
0
  /**
   * Method to parse an Atom
   *
   * @param Atom Element The XOM element that represents the Atom to be parsed.
   * @param head boolean This tells the engine if the atom is a head of a rule.
   * @param neg boolean This tells the engine if the atom is a negative atom (Neg)
   * @return Returns the data structure that represents the Atom in a way that can be used by the
   *     reasoning engine.
   * @throws ParseException Thrown if there is an error parsing the Atom.
   */
  private Term parseAtom(Element atom, boolean head, boolean neg) throws ParseException {

    boolean foundoid = false;

    Elements children = atom.getChildElements();

    // checking for op tag before the rel
    Element op = getFirstChildElement(atom, tagNames.OP);

    Element rel = null;

    if (op != null) {
      Elements relTag = op.getChildElements();
      rel = relTag.get(0);
    } else {
      rel = getFirstChildElement(atom, tagNames.REL);
    }

    if (rel == null) {
      throw new ParseException("In an <Atom>, first child of <op> must be a <Rel>.");
    }

    String relname = rel.getValue().trim();
    if (neg) {
      relname = "$neg-" + relname;
    }

    int symbol = SymbolTable.internSymbol(relname);

    Vector<Term> subterms = new Vector<Term>();
    int startIndex = getFirstChildElementIndex(children, 0) + 1;
    for (int i = startIndex; i < children.size(); i++) {
      Element element = children.get(i);
      Term term = null;
      if (element.getLocalName().equals(tagNames.OID)) {
        if (foundoid) {
          throw new ParseException("<Atom> must contain a most one <oid>.");
        }
        term = parseOid(element);
        foundoid = true;
      } else {
        term = parseDefaultElement(element);
      }
      subterms.add(term);
    }

    // Generate a fake OID if the atom does not have one.
    // This is a requirement put in place by the reasoner.
    if (!foundoid) {
      if (head) {
        String symname = "$gensym" + SymbolTable.genid++;
        int symid = SymbolTable.internSymbol(symname);
        Term t2 = new Term(symid, SymbolTable.IOID, Types.IOBJECT);
        subterms.add(t2);
      } else {
        String varname = generateAnonymousIdentifier();
        int symid = this.internVariable(varname);
        Vector<Integer> types = new Vector<Integer>();
        types.add(Types.IOBJECT);
        this.varClasses.put(symid, types);
        Term t2 = new Term(symid, SymbolTable.IOID, Types.IOBJECT);
        subterms.add(t2);
      }
    }

    Term t = new Term(symbol, SymbolTable.INOROLE, Types.IOBJECT, subterms);
    t.setAtom(true);
    return t;
  }
 private static List<CoreMap> toTimexCoreMaps(Element docElem, CoreMap originalDocument) {
   // --Collect Token Offsets
   HashMap<Integer, Integer> beginMap = new HashMap<Integer, Integer>();
   HashMap<Integer, Integer> endMap = new HashMap<Integer, Integer>();
   boolean haveTokenOffsets = true;
   for (CoreMap sent : originalDocument.get(CoreAnnotations.SentencesAnnotation.class)) {
     for (CoreLabel token : sent.get(CoreAnnotations.TokensAnnotation.class)) {
       Integer tokBegin = token.get(CoreAnnotations.TokenBeginAnnotation.class);
       Integer tokEnd = token.get(CoreAnnotations.TokenEndAnnotation.class);
       if (tokBegin == null || tokEnd == null) {
         haveTokenOffsets = false;
       }
       int charBegin = token.get(CoreAnnotations.CharacterOffsetBeginAnnotation.class);
       int charEnd = token.get(CoreAnnotations.CharacterOffsetEndAnnotation.class);
       beginMap.put(charBegin, tokBegin);
       endMap.put(charEnd, tokEnd);
     }
   }
   // --Set Timexes
   List<CoreMap> timexMaps = new ArrayList<CoreMap>();
   int offset = 0;
   Element textElem = docElem.getFirstChildElement("text");
   for (int i = 0; i < textElem.getChildCount(); i++) {
     Node content = textElem.getChild(i);
     if (content instanceof Text) {
       Text text = (Text) content;
       offset += text.getValue().length();
     } else if (content instanceof Element) {
       Element child = (Element) content;
       if (child.getLocalName().equals("TIMEX3")) {
         Timex timex = new Timex(child);
         if (child.getChildCount() != 1) {
           throw new RuntimeException("TIMEX3 should only contain text " + child);
         }
         String timexText = child.getValue();
         CoreMap timexMap = new ArrayCoreMap();
         // (timex)
         timexMap.set(TimexAnnotation.class, timex);
         // (text)
         timexMap.set(CoreAnnotations.TextAnnotation.class, timexText);
         // (characters)
         int charBegin = offset;
         timexMap.set(CoreAnnotations.CharacterOffsetBeginAnnotation.class, charBegin);
         offset += timexText.length();
         int charEnd = offset;
         timexMap.set(CoreAnnotations.CharacterOffsetEndAnnotation.class, charEnd);
         // (tokens)
         if (haveTokenOffsets) {
           Integer tokBegin = beginMap.get(charBegin);
           int searchStep = 1; // if no exact match, search around the character offset
           while (tokBegin == null) {
             tokBegin = beginMap.get(charBegin - searchStep);
             if (tokBegin == null) {
               tokBegin = beginMap.get(charBegin + searchStep);
             }
             searchStep += 1;
           }
           searchStep = 1;
           Integer tokEnd = endMap.get(charEnd);
           while (tokEnd == null) {
             tokEnd = endMap.get(charEnd - searchStep);
             if (tokEnd == null) {
               tokEnd = endMap.get(charEnd + searchStep);
             }
             searchStep += 1;
           }
           timexMap.set(CoreAnnotations.TokenBeginAnnotation.class, tokBegin);
           timexMap.set(CoreAnnotations.TokenEndAnnotation.class, tokEnd);
         }
         // (add)
         timexMaps.add(timexMap);
       } else {
         throw new RuntimeException("unexpected element " + child);
       }
     } else {
       throw new RuntimeException("unexpected content " + content);
     }
   }
   return timexMaps;
 }