Esempio n. 1
0
  /**
   * Search the tree of objects starting at the given <code>ServerActiveHtml</code> and return the
   * content of the first <code>Element</code> with the same name as this <code>Placeholder</code>
   * as the children of a new <code>List</code> if the <code>Element</code> does not have a any
   * placeholder (of the form placeholder-x = "foo").
   *
   * <p>Otherise return a singleton list of a <code>ServerActiveHtml</code> which has the children
   * of the found <code>Element</code> and the placeholders of this <code>Element</code>
   *
   * <p>Packaging the content of the matched <code>Element</code> as a <code>ServerActiveHtml</code>
   * allows the placeholders of the <code>Element</code> to be transferred to the <code>
   * ServerActiveHtml</code>
   *
   * <p>If no matching <code>Element</code> return a <code>List</code> with a <code>Fragment</code>
   * warning message
   *
   * @return A <code>ServerActiveHtml</code> containing the child of the matched <code>Element
   *     </code> or a warning <code>Fragment</code> if no matching <code>Element</code>
   */
  public List getReplacement(ServerActiveHtml sah) throws ServerActiveHtmlException {

    List result = new LinkedList();

    Element match = sah.findElement(getUseElement());

    if (match == null) {
      result.add(
          new Fragment(
              "<b>Warning: missing element for placeholder '" + getUseElement() + "'</b>"));
      return result;
    }

    if (match.getPlaceholders().isEmpty()) {
      for (Iterator children = match.getChildren().iterator(); children.hasNext(); ) {
        Deserializable child = (Deserializable) children.next();
        result.add(child);
      }
    } else {
      ServerActiveHtml wrapper = new ServerActiveHtml(REPLACEMENT_NAME);
      wrapper.setPlaceholders(match.getPlaceholders());
      for (Iterator children = match.getChildren().iterator(); children.hasNext(); ) {
        Deserializable child = (Deserializable) children.next();
        wrapper.add(child);
      }
      result.add(wrapper);
    }

    return result;
  }
  private QueryResult gatherResultInfoForSelectQuery(
      String queryString, int queryNr, boolean sorted, Document doc, String[] rows) {
    Element root = doc.getRootElement();

    // Get head information
    Element child =
        root.getChild("head", Namespace.getNamespace("http://www.w3.org/2005/sparql-results#"));

    // Get result rows (<head>)
    List headChildren =
        child.getChildren(
            "variable", Namespace.getNamespace("http://www.w3.org/2005/sparql-results#"));

    Iterator it = headChildren.iterator();
    ArrayList<String> headList = new ArrayList<String>();
    while (it.hasNext()) {
      headList.add(((Element) it.next()).getAttributeValue("name"));
    }

    List resultChildren =
        root.getChild("results", Namespace.getNamespace("http://www.w3.org/2005/sparql-results#"))
            .getChildren(
                "result", Namespace.getNamespace("http://www.w3.org/2005/sparql-results#"));
    int nrResults = resultChildren.size();

    QueryResult queryResult = new QueryResult(queryNr, queryString, nrResults, sorted, headList);

    it = resultChildren.iterator();
    while (it.hasNext()) {
      Element resultElement = (Element) it.next();
      String result = "";

      // get the row values and paste it together to one String
      for (int i = 0; i < rows.length; i++) {
        List bindings =
            resultElement.getChildren(
                "binding", Namespace.getNamespace("http://www.w3.org/2005/sparql-results#"));
        String rowName = rows[i];
        for (int j = 0; j < bindings.size(); j++) {
          Element binding = (Element) bindings.get(j);
          if (binding.getAttributeValue("name").equals(rowName))
            if (result.equals(""))
              result +=
                  rowName + ": " + ((Element) binding.getChildren().get(0)).getTextNormalize();
            else
              result +=
                  "\n"
                      + rowName
                      + ": "
                      + ((Element) binding.getChildren().get(0)).getTextNormalize();
        }
      }

      queryResult.addResult(result);
    }
    return queryResult;
  }
Esempio n. 3
0
  public void addVariables(Element inRoot) throws org.jdom2.DataConversionException {
    Element vs = inRoot.getChild("decoder").getChild("variables");

    Element segment = new Element("segment");
    segment.setAttribute("space", "253");
    root.addContent(segment);

    Iterator it = vs.getDescendants();
    while (it.hasNext()) {
      Object o = it.next();
      if (o instanceof Element) {
        Element e = (Element) o;
        if (e.getName().equals("variable")) {
          // get common attributes
          String comment = e.getAttributeValue("comment");
          for (Object oc : e.getChildren("comment")) {
            Element ec = (Element) oc;
            if (ec.getAttributeValue("lang", "xml").equals("")) comment = ec.getText();
          }
          String name = e.getAttributeValue("label");
          if (name.equals("")) name = e.getAttributeValue("item");
          for (Object on : e.getChildren("label")) {
            Element en = (Element) on;
            if (en.getAttributeValue("lang", "xml").equals("")) name = en.getText();
          }

          long cv = e.getAttribute("CV").getIntValue();

          // find subtype and process
          Element type;
          type = e.getChild("decVal");
          if (type != null) {
            segment.addContent(handleDecVal(type, cv, name, comment, e.getAttributeValue("mask")));
            continue;
          }
          type = e.getChild("enumVal");
          if (type != null) {
            segment.addContent(handleEnumVal(type, cv, name, comment, e.getAttributeValue("mask")));
            continue;
          }
          type = e.getChild("shortAddressVal");
          if (type != null) {
            segment.addContent(handleShortAddressVal(type, cv, name, comment));
            continue;
          }
          type = e.getChild("longAddressVal");
          if (type != null) {
            segment.addContent(handleLongAddressVal(type, cv, name, comment));
            continue;
          }
        }
      }
    }
  }
Esempio n. 4
0
 @Override
 public void compose(Element e, OutputStream stream, OutputStyle style, String base)
     throws Exception {
   this.base = base;
   OutputStreamWriter osw = new OutputStreamWriter(stream, "UTF-8");
   if (style == OutputStyle.CANONICAL) json = new JsonCreatorCanonical(osw);
   else json = new JsonCreatorGson(osw);
   json.setIndent(style == OutputStyle.PRETTY ? "  " : "");
   json.beginObject();
   prop("@type", "fhir:" + e.getType());
   prop("@context", jsonLDBase + "fhir.jsonld");
   prop("role", "fhir:treeRoot");
   String id = e.getChildValue("id");
   if (base != null && id != null) {
     if (base.endsWith("#")) prop("@id", base + e.getType() + "-" + id + ">");
     else prop("@id", Utilities.pathReverse(base, e.getType(), id));
   }
   Set<String> done = new HashSet<String>();
   for (Element child : e.getChildren()) {
     compose(e.getName(), e, done, child);
   }
   json.endObject();
   json.finish();
   osw.flush();
 }
Esempio n. 5
0
  private void compose(String path, Element element) throws IOException {
    Property p =
        element.hasElementProperty() ? element.getElementProperty() : element.getProperty();
    String en = getFormalName(element);

    if (element.fhirType().equals("xhtml")) {
      json.name(en);
      json.value(element.getValue());
    } else if (element.hasChildren() || element.hasComments() || element.hasValue()) {
      open(en);
      if (element.getProperty().isResource()) {
        prop("@type", "fhir:" + element.getType());
        //        element = element.getChildren().get(0);
      }
      if (element.isPrimitive() || isPrimitive(element.getType())) {
        if (element.hasValue()) primitiveValue(element);
      }

      Set<String> done = new HashSet<String>();
      for (Element child : element.getChildren()) {
        compose(path + "." + element.getName(), element, done, child);
      }
      if ("Coding".equals(element.getType())) decorateCoding(element);
      if ("CodeableConcept".equals(element.getType())) decorateCodeableConcept(element);
      if ("Reference".equals(element.getType())) decorateReference(element);

      close();
    }
  }
Esempio n. 6
0
  public static List<String> getEventsNameByXml() {
    SAXBuilder sxb = new SAXBuilder();
    Document document;
    List<String> listEvenementsString = null;
    //		Object obj=null;
    try {
      document = sxb.build(new File(xmlDefaultPath));

      //			listevents=getEventsNameByDoc(document);

      Element racine = document.getRootElement();

      //			System.out.println("racine="+racine.getText()+"finracine");
      List<Element> listEvenementsElement = racine.getChildren("evenement");
      listEvenementsString = new ArrayList<String>();

      for (Element evenementElement : listEvenementsElement) {
        listEvenementsString.add(evenementElement.getAttributeValue("nomEvent"));
      }

      //			System.out.println("listofEventsJdomtaille ="+listEvenementsString.size());

      // il faut valider le fichier xml avec la dtd
      //			JDomOperations.validateJDOM(document);
      //			afficheXml(document);
    } catch (Exception e) {
      // afficher un popup qui dit que le format du fichier xml entré n'est pas valide
      System.out.println("format xml non respecté");
      System.out.println(e.getMessage());
    }
    return listEvenementsString;
  }
Esempio n. 7
0
  public String SqlExcute(String xmlStr) {
    String outstr = "false";
    Document doc;
    Element rootNode;
    String intStr = Basic.decode(xmlStr);

    try {
      Reader reader = new StringReader(intStr);
      SAXBuilder ss = new SAXBuilder();
      doc = ss.build(reader);

      rootNode = doc.getRootElement();

      List list = rootNode.getChildren();

      DBTable datatable = new DBTable();

      for (int i = 0; i < list.size(); i++) {
        Element childRoot = (Element) list.get(i);
        // System.out.print(childRoot.getText());
        outstr = String.valueOf(datatable.SaveDateStr(childRoot.getText()));
      }

    } catch (JDOMException ex) {
      System.out.print(ex.getMessage());
    }
    return outstr;
  }
Esempio n. 8
0
	/**
	 *  普通版填写包的公共部分
	 * @param root	开始节点
	 * @param map	参数map
	 * @param sCycName	循环节点名
	 * @return
	 */
	public Element writeptPublicNode(Element root,HashMap map,String sCycName)
	{
		Element node=null;
		try
		{
			String sName="";
			String sValue="";
			List list=root.getChildren();
			for(int i=0;i<list.size();i++)
			{
				node=(Element)list.get(i);
				sName=node.getName();
				sName=sName.trim();
				sValue=(String)map.get(sName);
				//System.err.println("sName:"+sName+":"+sValue);
				if(sCycName.equals(sName)&&(root.getName()).trim().equals("ReqParamSet"))
				{
					//System.err.println("find cyc node:"+sName );
					return node;
				}
				else if(sValue!=null && !"".equals(sValue) )
					node.setText(sValue);
				node=writeptPublicNode(node,map,sCycName);
			}
		}catch(Exception ex)
		{
			ex.printStackTrace();
			System.err.println("error:"+ex.getMessage());
		}
		return node;
	}
Esempio n. 9
0
	/*
	 * 递归完成查找
	 * para: Element root 开始查找节点
	 */
	public Element findNode(Element root,String sNodeName)
	{
		Element node =null;
		try
		{
			String sName="";
			List list=root.getChildren();
			for(int i=0;i<list.size();i++)
			{
				node=(Element)list.get(i);
				sName=node.getName();
				sName=sName.trim();
				//System.err.println("node name:"+sName+"-"+sNodeName);
				if(sName.equals(sNodeName))
				{
					System.err.println("find the node:"+sName);
					return node;
				}
				node=findNode(node,sNodeName);
			}
		}catch(Exception ex)
		{
			ex.printStackTrace();
			System.err.println("error:"+ex.getMessage());
		}
		return node;
	}
Esempio n. 10
0
  private void composeList(String path, List<Element> list) throws IOException {
    // there will be at least one element
    String en = getFormalName(list.get(0));

    openArray(en);
    for (Element item : list) {
      open(null);
      json.name("index");
      json.value(item.getIndex());
      if (item.isPrimitive() || isPrimitive(item.getType())) {
        if (item.hasValue()) primitiveValue(item);
      }
      if (item.getProperty().isResource()) {
        prop("@type", "fhir:" + item.getType());
      }
      Set<String> done = new HashSet<String>();
      for (Element child : item.getChildren()) {
        compose(path + "." + item.getName(), item, done, child);
      }
      if ("Coding".equals(item.getType())) decorateCoding(item);
      if ("CodeableConcept".equals(item.getType())) decorateCodeableConcept(item);
      if ("Reference".equals(item.getType())) decorateReference(item);

      close();
    }
    closeArray();
  }
Esempio n. 11
0
  /**
   * Processes the messages from the server
   *
   * @param message
   */
  private synchronized void processServerMessage(String message) {
    SAXBuilder builder = new SAXBuilder();
    String what = new String();
    Document doc = null;

    try {
      doc = builder.build(new StringReader(message));
      Element root = doc.getRootElement();
      List childs = root.getChildren();
      Iterator i = childs.iterator();
      what = ((Element) i.next()).getName();
    } catch (Exception e) {
    }

    if (what.equalsIgnoreCase("LOGIN") == true) _login(doc);
    else if (what.equalsIgnoreCase("LOGOUT") == true) _logout(doc);
    else if (what.equalsIgnoreCase("MESSAGE") == true) _message(doc);
    else if (what.equalsIgnoreCase("WALL") == true) _wall(doc);
    else if (what.equalsIgnoreCase("CREATEGROUP") == true) _creategroup(doc);
    else if (what.equalsIgnoreCase("JOINGROUP") == true) _joingroup(doc);
    else if (what.equalsIgnoreCase("PARTGROUP") == true) _partgroup(doc);
    else if (what.equalsIgnoreCase("GROUPMESSAGE") == true) _groupmessage(doc);
    else if (what.equalsIgnoreCase("KICK") == true) _kick(doc);
    else if (what.equalsIgnoreCase("LISTUSER") == true) _listuser(doc);
    else if (what.equalsIgnoreCase("LISTGROUP") == true) _listgroup(doc);
  }
Esempio n. 12
0
  public boolean load() {
    try {
      if (new File(FILE_PATH).exists()) {
        FileInputStream FIS = new FileInputStream(FILE_PATH);
        JXMLBaseObject cobjXmlObj = new JXMLBaseObject();
        cobjXmlObj.InitXMLStream(FIS);
        FIS.close();

        Vector exps = new Vector();
        Element rootElmt = cobjXmlObj.GetElementByName(JCStoreTableModel.ROOT_NAME);
        for (Iterator i = rootElmt.getChildren().iterator(); i.hasNext(); ) {
          Element crtElmt = (Element) i.next();
          JCExpression exp = new JCExpression();
          exp.mId = crtElmt.getAttributeValue("id", "");
          exp.mName = crtElmt.getAttributeValue("name", "");
          exp.mShowValue = crtElmt.getAttributeValue("show", "");
          exp.mStoreValue = crtElmt.getAttributeValue("store", "");
          exps.add(exp);
        }
        if (mModel != null) {
          mModel.setExpression(exps);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
    return true;
  }
Esempio n. 13
0
  /** {@inheritDoc} */
  public void initializeFrom(Element element) throws DocumentSerializationException {
    for (Enumeration e = element.getChildren(); e.hasMoreElements(); ) {
      Element serviceElement = (TextElement) e.nextElement();
      String tagName = (String) serviceElement.getKey();

      if (tagName.equals("service")) {
        try {
          ModuleClassID moduleClassID =
              (ModuleClassID)
                  IDFactory.fromURI(
                      new URI(
                          DocumentSerializableUtilities.getString(
                              serviceElement, "moduleClassID", "ERROR")));

          try {
            ServiceMonitorFilter serviceMonitorFilter =
                MonitorResources.createServiceMonitorFilter(moduleClassID);
            serviceMonitorFilter.init(moduleClassID);
            Element serviceMonitorFilterElement =
                DocumentSerializableUtilities.getChildElement(serviceElement, "serviceFilter");
            serviceMonitorFilter.initializeFrom(serviceMonitorFilterElement);
            serviceMonitorFilters.put(moduleClassID, serviceMonitorFilter);
          } catch (Exception ex) {
            if (unknownModuleClassIDs == null) unknownModuleClassIDs = new LinkedList();

            unknownModuleClassIDs.add(moduleClassID);
          }
        } catch (URISyntaxException jex) {
          throw new DocumentSerializationException("Can't get ModuleClassID", jex);
        }
      }
    }
  }
 /** {@inheritDoc } */
 @Override
 public List<String> getValues(String nodeName) {
   List<Element> elements = getElements(nodeName);
   ArrayList<String> result = new ArrayList<String>();
   for (Element elt : elements) {
     if (elt.getChildren().size() > 0) {
       throw new XmlException(
           "Illegal use : the node "
               + nodeName
               + "has "
               + elt.getChildren().size()
               + " Childrens");
     }
     result.add(elt.getText());
   }
   return result;
 }
Esempio n. 15
0
  public ParseDoc(Object xmlFile, String rootId, TreeMap prevIdMap) {

    SAXBuilder saxBuilder = new SAXBuilder();

    try {
      if (xmlFile instanceof String) {
        document = saxBuilder.build((String) xmlFile);
      } else if (xmlFile instanceof URL) {
        document = saxBuilder.build((URL) xmlFile);
      }
      root = ParseUtils.parseRoot(document, rootId);
      objects = new TreeMap();

      // Build description string (but not for the snippets.xml file)
      if (xmlFile instanceof String) {
        List authorL = root.getChildren("author");
        String author = "<unknown>";
        if (root.getAttributeValue("name") != null) {
          author = root.getAttributeValue("name");
        } else if (authorL.size() > 0) {
          author = ((Element) authorL.get(0)).getValue();
        }
        String description =
            "from file "
                + xmlFile.toString()
                + " (author: "
                + author
                + ") on "
                + new Date().toString();
        HasIdentifiers.addGlobalIdentifier("_description_", description);
      }

      // Get all macro definitions, and remove them from document
      TreeMap macroMap = ParseUtils.getMacroDefs(root);

      // Process all macro expansions; replace macro expansion request with result
      ParseUtils.expandMacros(root, macroMap);

      // Get all elements in document, and assign identifiers to them;
      idMap = ParseUtils.parseId(root, prevIdMap);

      // Rewriting done; output debug XML code
      if (root.getAttributeValue("debug") != null) {
        XMLOutputter outputter = new XMLOutputter();
        FileOutputStream fos = new FileOutputStream(xmlFile + ".debug");
        outputter.output(document, fos);
        fos.close();
      }

    } catch (JDOMException e) { // indicates a well-formedness or other error

      throw new Error("JDOMException: " + e.getMessage());

    } catch (IOException e) { // indicates an IO problem

      throw new Error("IOException: " + e.getMessage());
    }
  }
Esempio n. 16
0
  private void load_snap_from_xml(Element snap, StructureCollection structs, LinkedList tempList)
      throws VisualizerLoadException {
    Iterator iterator = snap.getChildren().iterator();

    if (!iterator.hasNext()) throw new VisualizerLoadException("Ran out of elements");

    structs.loadTitle((Element) (iterator.next()), tempList, this);
    structs.calcDimsAndStartPts(tempList, this);

    if (!iterator.hasNext()) return;
    Element child = (Element) iterator.next();

    if (child.getName().compareTo("doc_url") == 0) {
      // load the doc_url
      add_a_documentation_URL(child.getText().trim());
      if (!iterator.hasNext()) return;
      child = (Element) iterator.next();
    }

    if (child.getName().compareTo("pseudocode_url") == 0) {
      // load the psuedocode_url
      add_a_pseudocode_URL(child.getText().trim());
      if (!iterator.hasNext()) return;
      child = (Element) iterator.next();
    }

    if (child.getName().compareTo("audio_text") == 0) {
      // load the psuedocode_url
      add_audio_text(child.getText().trim());
      if (!iterator.hasNext()) return;
      child = (Element) iterator.next();
    }

    // create & load the individual structures, hooking them into the StructureCollection.
    // linespernode : calculate it at end of loadStructure call
    while (child.getName().compareTo("question_ref") != 0) {
      StructureType child_struct = assignStructureType(child);
      child_struct.loadStructure(child, tempList, this);
      structs.addChild(child_struct);

      if (!iterator.hasNext()) return;
      child = (Element) iterator.next();
    }

    if (child.getName().compareTo("question_ref") == 0) {
      // set up question ref
      add_a_question_xml(child.getAttributeValue("ref"));
    } else
      // should never happen
      throw new VisualizerLoadException(
          "Expected question_ref element, but found " + child.getName());

    if (iterator.hasNext()) {
      child = (Element) iterator.next();
      throw new VisualizerLoadException(
          "Found " + child.getName() + " when expecting end of snap.");
    }
  } // load_snap_from_xml
Esempio n. 17
0
  /**
   * 1) Performs re-ranking using a linear function, which takes into account only three features:
   * newRank = 1 * oldRank + 10 * underconstrained_query + 10 * incosistent_tense; <br>
   * 2) Takes the hypothesis which is smallest in (new) rank as the best one. <br>
   * 3) Computes the semantic error rate (SER) as follows: -- a recognition is considered as
   * semantically correct if the dialogue move representation it produces is both a) non-null and b)
   * the same as the one that would have been produced from a perfect recognition result. -- if
   * dialogue move is not the same: then counts the number of deletions/insertions required in order
   * to obtain the perfect dialogue move.
   *
   * @deprecated Use instead the linear re-ranking with more than 3 feat and SER manually defined
   *     (available in xml file)
   * @param xmlFileName - input xml file containing both the n-best hypothesis and the reference
   *     transcription.
   * @return
   * @throws Exception
   */
  public float[] getER4LinearReranking3Feat(String xmlFileName) throws Exception {
    // read the xml file in order to get the utterance transcripts
    try {
      Document d =
          new org.jdom.input.SAXBuilder().build(new File(xmlFileName)); // PARSE THE XML FILE
      java.util.List nbestList = d.getRootElement().getChildren("nbest_data");
      float[] serArray = new float[nbestList.size()];
      int noUtt = 0;
      int minNewRankID = 1;

      for (int i = 0; i < nbestList.size(); i++) {
        Element nbestElem = (Element) nbestList.get(i);
        noUtt++;

        // In order to COMPUTE SEMANTIC ERROR RATE (ser),
        // get the dialogue_move feature value for the correct transcription
        // dialogue_move
        Element dmElem = nbestElem.getChild("dialogue_move");
        String refDM = "";
        if (dmElem != null) if (!dmElem.getValue().equalsIgnoreCase("")) refDM = dmElem.getValue();

        // In the xml tree: find hyp_transcription,
        // i.e. the transcription corresponding to the 1-rank predicted hypothesis
        java.util.List recList = nbestElem.getChildren("recognition");

        // PERFORM LINEAR RE-RANKING
        int minNewRank = 100;
        for (int j = 1; j < recList.size(); j++) {
          Element recElem = (Element) recList.get(j);
          int rank = new Integer(recElem.getChild("rank").getValue()).intValue();
          int uq = new Integer(recElem.getChild("underconstrained_query").getValue()).intValue();
          int it = new Integer(recElem.getChild("inconsistent_tense").getValue()).intValue();

          int newRank = rank + 10 * uq + 10 * it;
          if (newRank < minNewRank) {
            minNewRank = newRank;
            minNewRankID = j;
          }
        }

        Element recElem = (Element) recList.get(minNewRankID);
        Element dm4recElem = recElem.getChild("dialogue_move");
        String dm4rec = "";
        if (dm4recElem != null)
          if (!dm4recElem.getValue().equalsIgnoreCase("")) dm4rec = dm4recElem.getValue();

        WordErrorRate wer = new WordErrorRate(refDM, dm4rec, this.wordDeliminator);
        serArray[i] = wer.computeNumerator();
      }

      return serArray;
    } catch (IOException eIO) {
      eIO.printStackTrace();
    } catch (JDOMException eJDOM) {
      eJDOM.printStackTrace();
    }
    return null;
  }
Esempio n. 18
0
  public Element deserialize(Node c) throws NoSuchMethodException {

    if (c instanceof org.w3c.dom.Element) {
      org.w3c.dom.Element elm = (org.w3c.dom.Element) c;

      try {
        Element _elm =
            (Element)
                Class.forName(elm.getTagName().toLowerCase())
                    .getConstructors()[0]
                    .newInstance(getContext(), this);

        for (int i = 0; i < elm.getAttributes().getLength(); i++) {
          Node attrib = elm.getAttributes().item(i);
          String val = attrib.getNodeValue();
          String attribute = attrib.getNodeName();
          try {
            int valN = Integer.valueOf(val);
            elm.getClass()
                .getMethod("set" + capitalize(attribute), Integer.class)
                .invoke(elm, valN);
          } catch (Exception e) {
            _elm.getClass().getMethod("set" + capitalize(attribute), String.class).invoke(elm, val);
          }
          for (int j = 0; j < elm.getChildNodes().getLength(); j++) {

            Element f = deserialize(elm.getChildNodes().item(i));
            _elm.getChildren().add(f);
          }
        }
        return _elm;
      } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    return null;
  }
Esempio n. 19
0
  /**
   * Método public static void leerArchivoXML(ListaUsuarios listaDeUsuarios): Este método permite
   * leer un archivo XML que contiene los datos de los usuarios a través de jdom
   */
  public static void leerArchivoXML(ListaUsuario listaDeUsuarios) {
    try {
      SAXBuilder builder = new SAXBuilder();

      /* Se crea un documento nuevo con el nombre del archivo */
      Document doc = builder.build(nombreArchivo);

      /* Se obtiene la raíz del archivo (la etiqueta inicial) */
      Element raiz = doc.getRootElement();

      /* Se puede obtener el atributo de la raíz (de la etiqueta) */
      System.out.println(raiz.getAttributeValue("tipo"));

      /* Se obtienen todos los hijos cuya etiqueta esa "usuario"  */
      /* y se asignan esos hijos a un List                        */
      List listaUsuarios = raiz.getChildren("usuario");

      System.out.println("Formada por:" + listaUsuarios.size() + " usuarios");
      System.out.println("------------------");

      /* Se genera un iterador para recorrer el List que se generó */
      Iterator i = listaUsuarios.iterator();

      /* Se recorre el List */
      while (i.hasNext()) {
        /* Se obtiene cada uno y se asigna a un objeto de tipo Element */
        Element e = (Element) i.next();

        /* Se obtiene el nombre, apellido y cargo de cada una de las etiquetas  */
        /* hijas de usuario, es decir, nombre, apellido y cargo                 */
        Element nick = e.getChild("nick");
        Element clave = e.getChild("clave");
        Element nombre = e.getChild("nombre");
        Element apellido = e.getChild("apellido");
        Element fechanac = e.getChild("fechanac");
        Element avatar = e.getChild("avatar");

        /* Se crea un nodo nuevo con la información y se agrega a la lista de usuarios */
        Usuario elUsuario =
            new Usuario(
                nick.getText(),
                clave.getText(),
                nombre.getText(),
                apellido.getText(),
                fechanac.getText(),
                avatar.getText());

        listaDeUsuarios.AgregarElemento(elUsuario);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Esempio n. 20
0
 // get licensing features, with appropriate defaults
 @SuppressWarnings("unchecked")
 private void loadLicensingFeatures(Element licensingElt) {
   List<LicensingFeature> licensingFeats = new ArrayList<LicensingFeature>();
   boolean containsLexFeat = false;
   if (licensingElt != null) {
     for (Iterator<Element> it = licensingElt.getChildren("feat").iterator(); it.hasNext(); ) {
       Element featElt = it.next();
       String attr = featElt.getAttributeValue("attr");
       if (attr.equals("lex")) containsLexFeat = true;
       String val = featElt.getAttributeValue("val");
       List<String> alsoLicensedBy = null;
       String alsoVals = featElt.getAttributeValue("also-licensed-by");
       if (alsoVals != null) {
         alsoLicensedBy = Arrays.asList(alsoVals.split("\\s+"));
       }
       boolean licenseEmptyCats = true;
       boolean licenseMarkedCats = false;
       boolean instantiate = true;
       byte loc = LicensingFeature.BOTH;
       String lmc = featElt.getAttributeValue("license-marked-cats");
       if (lmc != null) {
         licenseMarkedCats = Boolean.valueOf(lmc).booleanValue();
         // change defaults
         licenseEmptyCats = false;
         loc = LicensingFeature.TARGET_ONLY;
         instantiate = false;
       }
       String lec = featElt.getAttributeValue("license-empty-cats");
       if (lec != null) {
         licenseEmptyCats = Boolean.valueOf(lec).booleanValue();
       }
       String inst = featElt.getAttributeValue("instantiate");
       if (inst != null) {
         instantiate = Boolean.valueOf(inst).booleanValue();
       }
       String locStr = featElt.getAttributeValue("location");
       if (locStr != null) {
         if (locStr.equals("target-only")) loc = LicensingFeature.TARGET_ONLY;
         if (locStr.equals("args-only")) loc = LicensingFeature.ARGS_ONLY;
         if (locStr.equals("both")) loc = LicensingFeature.BOTH;
       }
       licensingFeats.add(
           new LicensingFeature(
               attr, val, alsoLicensedBy, licenseEmptyCats, licenseMarkedCats, instantiate, loc));
     }
   }
   if (!containsLexFeat) {
     licensingFeats.add(LicensingFeature.defaultLexFeature);
   }
   _licensingFeatures = new LicensingFeature[licensingFeats.size()];
   licensingFeats.toArray(_licensingFeatures);
 }
Esempio n. 21
0
  /**
   * Process listuser from server
   *
   * @param doc
   */
  private void _listuser(Document doc) {
    StringBuffer userlist = new StringBuffer();

    Element root = doc.getRootElement();
    Element list = root.getChild("listuser");
    List users = list.getChildren("user");
    Iterator i = users.iterator();
    while (i.hasNext()) {
      userlist.append(((Element) i.next()).getText());
      userlist.append("\n");
    }
    sendMessage(SERVER, "Users: \n" + userlist);
  }
Esempio n. 22
0
  public Element handleEnumVal(Element type, long cv, String name, String comment, String mask)
      throws org.jdom2.DataConversionException {
    Element r;
    if (mask != null && !mask.equals("")) {
      r = new Element("bit");
      r.setAttribute("size", "8");
      r.setAttribute("mask", maskToInt(mask));
    } else {
      r = new Element("int");
    }
    r.setAttribute("origin", "" + (4278190080L + cv));
    r.addContent(new Element("name").addContent(name));
    if (comment != null && !comment.equals(""))
      r.addContent(new Element("description").addContent(comment));

    Element map = new Element("map");
    int counter = 0;
    r.addContent(map);
    for (Object c : type.getChildren("enumChoice")) {
      Element choice = (Element) c;

      if (choice.getAttribute("value") != null) {
        counter = choice.getAttribute("value").getIntValue();
      }

      String cname = choice.getAttributeValue("choice");
      for (Object oc : choice.getChildren("choice")) {
        Element ec = (Element) oc;
        if (ec.getAttributeValue("lang", "xml").equals("")) cname = ec.getText();
      }

      Element relation = new Element("relation");
      map.addContent(relation);
      relation.addContent(new Element("property").addContent("" + counter));
      relation.addContent(new Element("value").addContent(cname));
      counter++;
    }
    return r;
  }
Esempio n. 23
0
 private static void writeElement(XMLStreamWriter xtw, Element element) throws XMLStreamException {
   xtw.writeStartElement(element.getName());
   for (String attributeName : element.getAttributeNames()) {
     xtw.writeAttribute(attributeName, element.getAttributeValue(attributeName));
   }
   if (element.hasText()) {
     xtw.writeCharacters(element.getText());
   } else {
     for (Element child : element.getChildren()) {
       writeElement(xtw, child);
     }
   }
   xtw.writeEndElement();
 }
Esempio n. 24
0
  /**
   * Process listgroup from server
   *
   * @param doc
   */
  private void _listgroup(Document doc) {
    StringBuffer grouplist = new StringBuffer();

    Element root = doc.getRootElement();
    Element list = root.getChild("listgroup");
    List groups = list.getChildren("group");
    Iterator i = groups.iterator();
    while (i.hasNext()) {
      Element temp = (Element) i.next();
      grouplist.append(temp.getChild("name").getText());
      grouplist.append("\t");
      grouplist.append(temp.getChild("description").getText());
      grouplist.append("\n");
    }
    sendMessage(SERVER, "Groups: \n" + grouplist);
  }
Esempio n. 25
0
  private static List<Element> getListinTemp(String path) {
    SAXBuilder sxb = new SAXBuilder();
    Document document;
    List<Element> listElement = new ArrayList<Element>();

    try {
      document = sxb.build(new File(path));

      Element racine = document.getRootElement();
      listElement = racine.getChildren();
    } catch (Exception e) {
      e.getMessage();
    }

    return listElement;
  }
Esempio n. 26
0
 public void visitDFS(Element current, StringBuffer b) {
   Element item = null;
   if (current == null) return;
   String tagName = current.getName();
   String tmp = "<" + tagName + ">" + current.getText();
   b.append(tmp);
   List children = current.getChildren();
   Iterator it = children.iterator();
   while (it.hasNext()) {
     item = (Element) it.next();
     if (item != null) {
       visitDFS(item, b);
     }
   }
   b.append("</" + tagName + ">\n");
 }
Esempio n. 27
0
  public static List<String> getEventsNameByDoc(Document pdocument) {
    Element racine = pdocument.getRootElement();
    List<Element> listEvenementsElement = racine.getChildren("evenement");
    List<String> listEvenementsString = new ArrayList<String>();

    for (Element evenementElement : listEvenementsElement) {
      listEvenementsString.add(evenementElement.getAttributeValue("nomEvent"));
    }
    //		//On crée un Iterator sur notre liste
    //		Iterator i = listEvenementsElement.iterator();
    //		while (i.hasNext()){
    //			Element evenementElement = (Element)i.next();
    //			//On affiche le nom de l'élément courant
    //			System.out.println(courant.getChild("nom").getText());
    //		}
    return listEvenementsString;
  }
Esempio n. 28
0
  // Empieza La Carga de la Partida
  public static void leerArchivoXML(ListaPartida listaDePartidas) {
    try {
      SAXBuilder builder = new SAXBuilder();

      /* Se crea un documento nuevo con el nombre del archivo */
      Document doc = builder.build(nombreArchivoPartida);

      /* Se obtiene la raíz del archivo (la etiqueta inicial) */
      Element raiz = doc.getRootElement();

      /* Se puede obtener el atributo de la raíz (de la etiqueta) */
      System.out.println(raiz.getAttributeValue("tipo"));

      /* Se obtienen todos los hijos cuya etiqueta esa "usuario"  */
      /* y se asignan esos hijos a un List                        */
      List listaPartida = raiz.getChildren("partida");

      System.out.println("Formada por:" + listaPartida.size() + " Partidas");
      System.out.println("------------------");

      /* Se genera un iterador para recorrer el List que se generó */
      Iterator i = listaPartida.iterator();

      /* Se recorre el List */
      while (i.hasNext()) {
        /* Se obtiene cada uno y se asigna a un objeto de tipo Element */
        Element e = (Element) i.next();

        /* Se obtiene el nombre, apellido y cargo de cada una de las etiquetas  */
        /* hijas de usuario, es decir, nombre, apellido y cargo                 */
        Element nick = e.getChild("Usuario");
        Element ID = e.getChild("ID");
        Element fechaactual = e.getChild("fechaacual");
        Element fechainicio = e.getChild("fechainicio");
        /* Se crea un nodo nuevo con la información y se agrega a la lista de usuarios */
        Partida laPartida =
            new Partida(
                nick.getText(), ID.getContentSize(), fechaactual.getText(), fechainicio.getText());
        listaDePartidas.AgregarElemento(laPartida);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /** {@inheritDoc } */
  @Override
  public String get(String nodeName) {
    Element elt = getElement(nodeName);

    // getElement() returns null if there is no such nodeName
    if (elt == null) {
      throw new XmlException("No nodeName '" + nodeName + "' found, or other exception");
    } else {
      // We check that it's VerySimpleXml
      if (elt.getChildren().size() > 0) {
        throw new XmlException(
            "Bad use in RwtJdom.getValue() : The node :"
                + nodeName
                + " should not have any child ; it's not an expected Xml structure.");
      } else {
        return elt.getText();
      }
    }
  }
Esempio n. 30
0
  /**
   * Compute the best semantic error rate that can be achieved starting from n-best hypothesis.
   *
   * @param xmlFileName
   * @return a list of error rates corresponding to each utterance
   * @throws Exception
   */
  public float[] getBestERCanBeAchieved(String xmlFileName) throws Exception {
    // read the xml file in order to get the utterance transcripts
    try {
      Document d =
          new org.jdom.input.SAXBuilder().build(new File(xmlFileName)); // PARSE THE XML FILE
      java.util.List nbestList = d.getRootElement().getChildren("nbest_data");
      float[] serArray = new float[nbestList.size()];
      int noUtt = 0;
      for (int i = 0; i < nbestList.size(); i++) {
        Element nbestElem = (Element) nbestList.get(i);
        noUtt++;

        // In order to COMPUTE SEMANTIC ERROR RATE (SER)

        java.util.List recList = nbestElem.getChildren("recognition");

        float bestSER = 10000;
        // (start with k=1 since we skip first value in recList which corresponds to the correct
        // transcription)
        for (int k = 1; k < recList.size(); k++) {
          Element recElem = (Element) recList.get(k);

          Element semCorrectElem = recElem.getChild("semantically_correct");
          String semCorrect = semCorrectElem.getValue();
          int ser;
          if (semCorrect.equalsIgnoreCase("good")) ser = 0;
          else ser = 1;

          if (bestSER > ser) {
            bestSER = ser;
          }
        } // end for k
        serArray[i] = bestSER;
      }
      return serArray;
    } catch (IOException eIO) {
      eIO.printStackTrace();
    } catch (JDOMException eJDOM) {
      eJDOM.printStackTrace();
    }
    return null;
  }