コード例 #1
0
  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;
  }
コード例 #2
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);
  }
コード例 #3
0
ファイル: MonitorFilter.java プロジェクト: Rikatouka/net.jxta
  /** {@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);
        }
      }
    }
  }
コード例 #4
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;
  }
コード例 #5
0
ファイル: XMLParsor.java プロジェクト: raisedragon/practice
	/*
	 * 递归完成查找
	 * 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;
	}
コード例 #6
0
ファイル: XMLParsor.java プロジェクト: raisedragon/practice
	/**
	 *  普通版填写包的公共部分
	 * @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;
	}
コード例 #7
0
ファイル: draw.java プロジェクト: bossiernesto/jvmbytecodes
  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
コード例 #8
0
ファイル: ParseDoc.java プロジェクト: psathyrella/hmmoc-1.3
  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());
    }
  }
コード例 #9
0
ファイル: ArchivoXml.java プロジェクト: rotslop/mjidomino
  /**
   * 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();
    }
  }
コード例 #10
0
ファイル: Lexicon.java プロジェクト: kevinkissi/openccg
 // 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);
 }
コード例 #11
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);
  }
コード例 #12
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);
  }
コード例 #13
0
ファイル: ArchivoXml.java プロジェクト: rotslop/mjidomino
  // 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();
    }
  }
コード例 #14
0
ファイル: XMLParsor.java プロジェクト: raisedragon/practice
	/**
	 *  新增循环节点
	 * @param cycNode 循环节点
	 * @return
	 */
	public Element addCycNode(Element cycNode)
	{
		Element node=cycNode;
		Element child=null;
		Element newNode=null;
		Element tmpNode=null;
		String sName="";
		if(cycNode==null)
			return newNode;
		newNode=new Element(node.getName());
		node.getParent().addContent(newNode);
		List cList=node.getChildren();
		for(int i=0;i<cList.size();i++)
		{
			child=(Element)cList.get(i);
			sName=child.getName();
			sName=sName.trim();
			tmpNode=new Element(sName);
			newNode.addContent(tmpNode);
		}
		return newNode;
	}
コード例 #15
0
  /** {@inheritDoc} */
  public void initializeFrom(Element element) throws DocumentSerializationException {
    for (Enumeration e = element.getChildren(); e.hasMoreElements(); ) {
      Element childElement = (TextElement) e.nextElement();
      String tagName = (String) childElement.getKey();

      if (tagName.equals("transportMetric")) {
        TransportMetric transportMetric =
            (TransportMetric)
                DocumentSerializableUtilities.getDocumentSerializable(
                    childElement, TransportMetric.class);
        transportMetrics.add(transportMetric);
      }
      if (tagName.equals("moduleClassID")) {
        try {
          moduleClassID =
              (ModuleClassID)
                  IDFactory.fromURI(new URI(DocumentSerializableUtilities.getString(childElement)));
        } catch (URISyntaxException jex) {
          throw new DocumentSerializationException("Can't read moduleClassID", jex);
        }
      }
    }
  }
コード例 #16
0
ファイル: KeyBinding.java プロジェクト: mahogny/Endrov
  /** Make a keybinding out of an XML element */
  public static KeyBinding readXML(Element e) {
    try {
      String plugin = e.getAttributeValue("plugin");
      String desc = e.getAttributeValue("desc");
      KeyBinding b = new KeyBinding(plugin, desc, null);

      for (Object neo : e.getChildren()) {
        Element ne = (Element) neo;
        if (ne.getName().equals("char"))
          b.types.add(new TypeChar(ne.getAttributeValue("char").charAt(0)));
        else if (ne.getName().equals("keycode"))
          b.types.add(
              new TypeKeycode(
                  ne.getAttribute("keyCode").getIntValue(),
                  ne.getAttribute("modifier").getIntValue()));
        else if (ne.getName().equals("jinput"))
          b.types.add(
              new TypeJInput(
                  ne.getAttributeValue("ident"), ne.getAttribute("value").getFloatValue()));
      }

      // backwards compatibility
      if (e.getAttribute("key") != null) {
        TypeChar kb = new TypeChar(e.getAttributeValue("key").charAt(0));
        b.types.add(kb);
      } else if (e.getAttribute("keyCode") != null) {
        TypeKeycode kb =
            new TypeKeycode(
                e.getAttribute("keyCode").getIntValue(), e.getAttribute("modifier").getIntValue());
        b.types.add(kb);
      }
      return b;
    } catch (DataConversionException e1) {
      e1.printStackTrace();
      return null;
    }
  }
コード例 #17
0
ファイル: XMLParsor.java プロジェクト: raisedragon/practice
	/** 
	 * 
	 * @param map	需要写入的参数map
	 * @param start 开始节点
	 * @param bNew  是否新增节点再写入参数
	 * @return
	 */
	public void writeParaMap(Element start,HashMap map)
	{
		try
		{
			String sName="";
			String sValue="";
			Element node=null;
			List list=start.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);
				if(sValue!=null && !"".equals(sValue) );
					node.setText(sValue);
			}
		}catch(Exception ex)
		{
			ex.printStackTrace();
			System.err.println("error:"+ex.getMessage());
		}
		return ;
	}
コード例 #18
0
  public void initializeFrom(Element element) throws DocumentSerializationException {
    state = null;

    for (Enumeration e = element.getChildren(); e.hasMoreElements(); ) {
      Element childElement = (TextElement) e.nextElement();
      String tagName = (String) childElement.getKey();

      if (tagName.equals("peerID")) {
        String peerIDText = DocumentSerializableUtilities.getString(childElement);

        peerID = MetricUtilities.getPeerIdFromString(peerIDText);
      } else if (tagName.equals("state")) {
        state = DocumentSerializableUtilities.getString(childElement);
      } else if (tagName.equals("transitionTime")) {
        transitionTime = DocumentSerializableUtilities.getLong(childElement);
      } else if (tagName.equals("lastLeaseRenewalTime")) {
        lastLeaseRenewalTime = DocumentSerializableUtilities.getLong(childElement);
      } else if (tagName.equals("lease")) {
        lease = DocumentSerializableUtilities.getLong(childElement);
      } else if (tagName.equals("numConnects")) {
        numConnects = DocumentSerializableUtilities.getInt(childElement);
      } else if (tagName.equals("numLeaseRenewals")) {
        numLeaseRenewals = DocumentSerializableUtilities.getInt(childElement);
      } else if (tagName.equals("numDisconnects")) {
        numDisconnects = DocumentSerializableUtilities.getInt(childElement);
      } else if (tagName.equals("numConnectionsRefused")) {
        numConnectionsRefused = DocumentSerializableUtilities.getInt(childElement);
      } else if (tagName.equals("numErrorsAddingClient")) {
        numErrorsAddingClient = DocumentSerializableUtilities.getInt(childElement);
      } else if (tagName.equals("numUnableToRespondToConnectRequest")) {
        numUnableToRespondToConnectRequest = DocumentSerializableUtilities.getInt(childElement);
      } else if (tagName.equals("totalTimeConnected")) {
        totalTimeConnected = DocumentSerializableUtilities.getLong(childElement);
      }
    }
  }
コード例 #19
0
  public static String getSimplePieChart(Map dataSource, String objectName, HttpSession session)
      throws Throwable {
    DefaultPieDataset dataset = new DefaultPieDataset();

    Element chartObject =
        XMLHandler.getElementByAttribute(getChartObjectList(), "name", objectName);

    String title = chartObject.getAttributeValue("title");

    int width = Integer.parseInt(chartObject.getAttributeValue("width"));
    int height = Integer.parseInt(chartObject.getAttributeValue("height"));

    Element LabelKeys = chartObject.getChild("Labels");
    Element ValueKeys = chartObject.getChild("Values");

    String valueKey = ValueKeys.getText();
    String valueType = ValueKeys.getAttributeValue("type");
    List labelKeys = LabelKeys.getChildren("Label");
    String labelKey = LabelKeys.getText();

    if (valueType.equalsIgnoreCase("number")) {
      for (int i = 0; i < dataSource.size(); i++) {
        Map rec = (Map) dataSource.get("ROW" + i);
        Number value = (Number) rec.get(valueKey);
        String label;
        if (labelKeys.isEmpty()) {
          label = DataFilter.show(rec, labelKey);
        } else {
          label = ((Element) labelKeys.get(i)).getText();
        }
        dataset.setValue(label, value);
      }
    } else {
      for (int i = 0; i < dataSource.size(); i++) {
        Map rec = (Map) dataSource.get("ROW" + i);
        double value = (Double) rec.get(valueKey);
        String label;
        if (labelKeys.isEmpty()) {
          label = DataFilter.show(rec, labelKey);
        } else {
          label = ((Element) labelKeys.get(i)).getText();
        }
        dataset.setValue(label, value);
      }
    }

    JFreeChart chart =
        ChartFactory.createPieChart3D(
            title,
            dataset,
            chartObject.getAttribute("showLegend").getBooleanValue(),
            chartObject.getAttribute("showToolTips").getBooleanValue(),
            chartObject.getAttribute("urls").getBooleanValue());

    PiePlot3D pie3dplot = (PiePlot3D) chart.getPlot();

    float alpha = 0.7F;
    if (chartObject.getAttribute("alpha") != null) {
      alpha = chartObject.getAttribute("alpha").getFloatValue();
    }
    pie3dplot.setForegroundAlpha(alpha);

    return ServletUtilities.saveChartAsPNG(chart, width, height, null, session);
  }
  /**
   * 设置默认值
   *
   * @param dv
   * @param formName
   * @param actionType
   * @return
   */
  private S_FrameWork_Query_OperationValueObject setDefault(
      S_FrameWork_Query_OperationValueObject valueObject, String formName, String actionType) {

    String entityName = "S_FrameWork_Query_Operation"; // 代码自动生成
    Document doc = DomService.getXMLDocFromEntity(entityName, formName);
    // 1.遍历所有节点,判断是否有默认设置
    // 2.比较actionType,看是否当前默认设置的操作
    // 3.反射设置当前属性的默认值
    try {

      if (doc == null) {
        return valueObject;
      }
      String methordName = "";

      Element root = doc.getRootElement();
      java.util.List elements = root.getChildren("item");
      Element tempElm = null;
      String s = null;
      String sType = "string";
      String sDBType = "String";
      DefaultValue dv = new DefaultValue();
      String whendefault = "";
      String defaultValue = "";

      for (int i = 0; i < elements.size(); i++) {
        tempElm = (Element) elements.get(i);
        s = tempElm.getAttribute("name").getValue();
        methordName = "set" + s.substring(0, 1).toUpperCase() + s.substring(1, s.length());
        if ((tempElm.getAttribute("datatype") != null
            && tempElm.getAttribute("datatype").getValue() != null)) {
          if (tempElm.getAttribute("dbtype") == null) {
            sType = tempElm.getAttribute("datatype").getValue();
          } else {
            sType = tempElm.getAttribute("dbtype").getValue();
          }
        }

        // 设置缺省值;当新增加的时候,设置缺省值,此处只在初始化和load的时候设置;修改的时候不设置
        // updated by wzp 20050323
        if (tempElm.getAttribute("datatype") != null
            && tempElm.getAttribute("default") != null
            && tempElm.getAttribute("whendefault") != null) {
          whendefault = tempElm.getAttribute("whendefault").getValue();
          defaultValue = tempElm.getAttribute("default").getValue();
          // 如何判断是新增?
          if (actionType.toLowerCase().indexOf("init_") == 0
              && whendefault.toLowerCase().indexOf("init") > -1) {
            // 初始化
            valueObject = this.invokeMethord(valueObject, methordName, sType, defaultValue);
          } else if (actionType.toLowerCase().indexOf("create_") == 0
              && whendefault.toLowerCase().indexOf("create") > -1) {
            // 创建
            valueObject = this.invokeMethord(valueObject, methordName, sType, defaultValue);
          } else if (actionType.toLowerCase().indexOf("save_") == 0
              && whendefault.toLowerCase().indexOf("save") > -1) {
            // 修改
            valueObject = this.invokeMethord(valueObject, methordName, sType, defaultValue);
          }
        }
      }

    } catch (Exception exe) {
      exe.printStackTrace();
    }

    return valueObject;
  }
コード例 #21
0
  // public List getUserStoryList(String sessionId,String iterationId,ServletOutputStream out) {
  public List getUserStoryList(String sessionId, String iterationId, PrintWriter out) {

    List<Map> list = new ArrayList<Map>();

    statusMap.put(sessionId, "0");

    try {

      String apiURL =
          rallyApiHost
              + "/hierarchicalrequirement?"
              + "query=(Iteration%20=%20"
              + rallyApiHost
              + "/iteration/"
              + iterationId
              + ")&fetch=true&start=1&pagesize=100";

      log.info("getUserStoryList apiURL=" + apiURL);

      String responseXML = getRallyXML(apiURL);

      org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder();
      org.jdom.Document doc = bSAX.build(new StringReader(responseXML));
      Element root = doc.getRootElement();

      XPath xpath = XPath.newInstance("//Object");
      List xlist = xpath.selectNodes(root);

      int totalSteps = xlist.size() + 1;
      int currentStep = 0;

      List taskRefLink = new ArrayList();

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {
        double totalTimeSpent = 0.0D;

        Map map = new HashMap();

        Element item = (Element) iter.next();
        String objId = item.getChildText("ObjectID");
        String name = item.getChildText("Name");
        String planEstimate = item.getChildText("PlanEstimate");
        String formattedId = item.getChildText("FormattedID");

        String taskActualTotal = item.getChildText("TaskActualTotal");
        String taskEstimateTotal = item.getChildText("TaskEstimateTotal");
        String taskRemainingTotal = item.getChildText("TaskRemainingTotal");
        String scheduleState = item.getChildText("ScheduleState");

        Element ownerElement = item.getChild("Owner");

        String owner = "";
        String ownerRef = "";

        if (ownerElement != null) {
          owner = ownerElement.getAttributeValue("refObjectName");
        }

        Element taskElements = item.getChild("Tasks");
        // List taskElementList=taskElements.getContent();
        List taskElementList = taskElements.getChildren();

        List taskList = new ArrayList();

        log.info("taskElements.getChildren=" + taskElements);
        log.info("taskList=" + taskElementList);

        for (int i = 0; i < taskElementList.size(); i++) {
          Element taskElement = (Element) taskElementList.get(i);

          String taskRef = taskElement.getAttributeValue("ref");

          String[] objectIdArr = taskRef.split("/");
          String objectId = objectIdArr[objectIdArr.length - 1];

          log.info("objectId=" + objectId);

          // Map taskMap=getTaskMap(taskRef);
          Map taskMap = getTaskMapBatch(objectId);

          double taskTimeSpentTotal =
              Double.parseDouble((String) taskMap.get("taskTimeSpentTotal"));
          totalTimeSpent += taskTimeSpentTotal;
          taskList.add(taskMap);
        }

        map.put("type", "userstory");
        map.put("formattedId", formattedId);
        map.put("name", name);
        map.put("taskStatus", scheduleState);
        map.put("owner", owner);
        map.put("planEstimate", planEstimate);
        map.put("taskEstimateTotal", taskEstimateTotal);
        map.put("taskRemainingTotal", taskRemainingTotal);
        map.put("taskTimeSpentTotal", "" + totalTimeSpent);

        list.add(map);
        list.addAll(taskList);

        ++currentStep;
        double percentage = 100.0D * currentStep / totalSteps;
        String status = "" + Math.round(percentage);
        statusMap.put(sessionId, status);

        out.println("<script>parent.updateProcessStatus('" + status + "%')</script>" + status);
        out.flush();
        log.info("out.flush..." + status);

        // log.info("status="+status+" sessionId="+sessionId);
        // log.info("L1 statusMap="+statusMap+" "+statusMap.hashCode());

      }

      double planEstimate = 0.0D;
      double taskEstimateTotal = 0.0D;
      double taskRemainingTotal = 0.0D;
      double taskTimeSpentTotal = 0.0D;
      Map iterationMap = new HashMap();
      for (Map map : list) {
        String type = (String) map.get("type");

        String planEstimateStr = (String) map.get("planEstimate");

        log.info("planEstimateStr=" + planEstimateStr);

        if ("userstory".equals(type)) {

          if (planEstimateStr != null) {
            planEstimate += Double.parseDouble(planEstimateStr);
          }
          taskEstimateTotal += Double.parseDouble((String) map.get("taskEstimateTotal"));
          taskRemainingTotal += Double.parseDouble((String) map.get("taskRemainingTotal"));
          taskTimeSpentTotal += Double.parseDouble((String) map.get("taskTimeSpentTotal"));
        }
      }

      apiURL = rallyApiHost + "/iteration/" + iterationId + "?fetch=true";
      log.info("iteration apiURL=" + apiURL);
      responseXML = getRallyXML(apiURL);

      bSAX = new org.jdom.input.SAXBuilder();
      doc = bSAX.build(new StringReader(responseXML));
      root = doc.getRootElement();

      xpath = XPath.newInstance("//Iteration");
      xlist = xpath.selectNodes(root);

      String projName = "";
      String iterName = "";
      String iterState = "";

      iter = xlist.iterator();
      while (iter.hasNext()) {
        Element item = (Element) iter.next();

        iterName = item.getChildText("Name");
        iterState = item.getChildText("State");
        Element projElement = item.getChild("Project");
        projName = projElement.getAttributeValue("refObjectName");
      }

      iterationMap.put("type", "iteration");
      iterationMap.put("formattedId", "");
      iterationMap.put("name", projName + " - " + iterName);
      iterationMap.put("taskStatus", iterState);
      iterationMap.put("owner", "");

      iterationMap.put("planEstimate", "" + planEstimate);
      iterationMap.put("taskEstimateTotal", "" + taskEstimateTotal);
      iterationMap.put("taskRemainingTotal", "" + taskRemainingTotal);
      iterationMap.put("taskTimeSpentTotal", "" + taskTimeSpentTotal);

      list.add(0, iterationMap);

      statusMap.put(sessionId, "100");

      log.info("L2 statusMap=" + statusMap);

      log.info("L2 verify=" + getProcessStatus(sessionId));
      log.info("-----------");

      // String jsonData=JsonUtil.encodeObj(list);
      String jsonData = JSONValue.toJSONString(list);

      out.println("<script>parent.tableResult=" + jsonData + "</script>");
      out.println("<script>parent.showTableResult()</script>");

    } catch (Exception ex) {
      log.error("ERROR: ", ex);
    }

    return list;
  }
コード例 #22
0
 private static List getChartObjectList() {
   Element root = XMLHandler.openXML(CONFIGFILE);
   return root.getChildren("Object");
 }