Пример #1
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;
	}
Пример #2
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;
	}
Пример #3
0
  protected String getRallyAPIError(String responseXML) {
    String errorMsg = "";

    try {

      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("//Errors");
      List xlist = xpath.selectNodes(root);

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {

        Element item = (Element) iter.next();
        errorMsg = item.getChildText("OperationResultError");
      }

    } catch (Exception e) {
      errorMsg = e.toString();
    }

    return errorMsg;
  }
Пример #4
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();
    }
  }
Пример #5
0
	/**
	 * 
	 * @param 普通版list	参数列表
	 */
	public void writeptParaList(ArrayList list)
	{
		
		try {
			String sCaseName="";
			String sItem="";
			String sCycName="";
			HashMap map=null;
			Document doc = builder.build(xmlFileName);
			Element root = doc.getRootElement();
			Element element = root;
			Element cycNode=null;
			
			map=(HashMap)list.get(0);	//参数文件map
			sItem="Description";
			sCaseName=(String)map.get(sItem);
			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, "Description=" + sCaseName );
		
			sItem="CysName";
			sCycName=(String)map.get(sItem);
			
			map=(HashMap)list.get(1);	//public 参数map
			cycNode=writeptPublicNode(element,map,sCycName);
			
			if( writeCycNode(cycNode,list)==false)	//循环 参数
			  System.err.println(" write cyc node fail");
			
			XMLOutputter outputter = new XMLOutputter("", false, "GB2312");
			PrintWriter out = new PrintWriter(new BufferedWriter(
					new FileWriter(xmlFileName)));

			Document myDocument = root.getDocument();
			outputter.output(myDocument, out);
			out.close();

		} catch (JDOMException jdome) {
			jdome.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
Пример #6
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();
    }
  }
Пример #7
0
 /**
  * Connect to the server
  *
  * @param host Serverhost
  * @param port Serverport
  */
 private void connect(String host, int port) {
   if (_status == NOTCONNECTED) {
     try {
       socket = new Socket(host, port);
     } catch (Exception ex) {
       ex.printStackTrace();
     }
     try {
       reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
       writer = new PrintWriter(socket.getOutputStream(), true);
       _status = CONNECTED;
     } catch (IOException ex) {
       ex.printStackTrace();
     }
     if (_status == CONNECTED) {
       thread = new Thread(this);
       thread.start();
     }
   }
 }
Пример #8
0
  /** Reads the XML data and create the data */
  public void readDOMDataElement(Element element, IDataSets datasets) {
    // start with source data
    for (Object child : CodeFragment.getDataElementsOfType(CodeFragment.TYPE.SOURCE, element)) {
      Element code = (Element) child;
      try {
        collectSourceDataFromDOM(code, datasets);
      } catch (Exception e) {
        e.printStackTrace();
        Util.errorMessage(
            "Failed to load source "
                + code.getAttributeValue("name")
                + ", error "
                + e.getMessage());
      }
    }

    // process the data
    for (Object child : CodeFragment.getDataElementsOfType(CodeFragment.TYPE.GENERATED, element)) {
      Element code = (Element) child;
      try {
        processDataFromDOM(code, datasets);
      } catch (Exception e) {
        e.printStackTrace();
        Util.errorMessage("Failed to run process " + e.getMessage());
      }
    }
  }
Пример #9
0
	/** 
	 * 
	 * @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 ;
	}
Пример #10
0
	//改写XML文件的某一元素的值
	//strRoute为XML文件从根元素开始到该元素的父元素的路径
	//strElement为需要读取的元素
	//flag为当XML含有多个同名元素时,需要改写元素所处的序号
	public void write(String strRoute, String strElement, String strSet,
			int flag) {
		//SAXBuilder builder=new SAXBuilder();
		try {
			String str = null;
			Document doc = builder.build(xmlFileName);
			Element root = doc.getRootElement();
			Element element = root;

			StringTokenizer st = new StringTokenizer(strRoute, ":");
			str = st.nextToken();

			while (st.hasMoreTokens()) {
				str = st.nextToken();
				//mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,str);
				element = element.getChild(str);

			}

			//	mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,"test :"+str);
			element = (Element) element.getParent();

			//若需要改写的不是XML文件的第一个同名元素,则获取该元素
			//方法为:将之前的元素依次移到后面,需要改写的元素前移至第一个
			/*
			 * if(flag>1) { int j=flag; while(j!=1) {
			 * 
			 * Element tmp=element.getChild(str);
			 * element.addContent(tmp.detach()); j--; } }
			 */
			element = element.getChild(str).getChild(strElement);

			//	mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,"gettxt
			// "+element.getText());

			element.setText(strSet);

			//若需要改写的不是XML文件的第一个同名元素
			//上面改变了次序,需要在成功改写后恢复原有次序
			/*
			 * if(flag!=1) {
			 * 
			 * java.util.List children=element.getChildren(); Iterator
			 * iterator=children.iterator(); int count=0;
			 * while(iterator.hasNext()) { Element
			 * child=(Element)iterator.next(); count++; }
			 * 
			 * System.out.println("count"+count);
			 * 
			 * k=(count+1-flag)%count;
			 * 
			 * while(k!=0) { Element tmp=element.getChild(str);
			 * element.addContent(tmp.detach()); k--; } }
			 *  
			 */
			XMLOutputter outputter = new XMLOutputter("", false, "GB2312");
			PrintWriter out = new PrintWriter(new BufferedWriter(
					new FileWriter(xmlFileName)));

			Document myDocument = root.getDocument();

			outputter.output(myDocument, out);
			out.close();

		} catch (JDOMException jdome) {
			jdome.printStackTrace();
//			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, xmlFileName
//					+ " is not well-formed\n");

		} catch (IOException ioe) {
			ioe.printStackTrace();
//			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, ioe);

		} catch (Exception e) {
			e.printStackTrace();
//			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,
//					"write not succeed\n");

		}

	}
Пример #11
0
  /**
   * Método public static void guardarArchivoXML(ListaUsuarios listaDeUsuarios): Este método permite
   * guardar la lista de usuarios en un archivo XML. El procesamiento se hace con jdom
   */
  public static void guardarArchivoXML(ListaUsuario listaDeUsuarios) {
    Usuario nodoAuxiliar;

    /* Se crea una raiz de la estructura */
    Element root = new Element("usuarios");

    /* Es posible agregar atributos a la estructura inicial */
    root.setAttribute("tipo", "lista de usuarios");

    Iterator iterador = listaDeUsuarios.getIterator();

    while (iterador.hasNext()) {
      /* Se crea la etiqueta "usuario" */
      Element usuarios = new Element("usuario");

      nodoAuxiliar = (Usuario) iterador.next();

      /* Se crean las etiquetas nombre, apellido y cargo */
      Element nick = new Element("nick");
      Element clave = new Element("clave");
      Element nombre = new Element("nombre");
      Element apellido = new Element("apellido");
      Element fechanac = new Element("fechanac");
      Element avatar = new Element("avatar");

      /* Se inicializa cada etiqueta con sus valores de la lista */
      nick.setText(nodoAuxiliar.getNickname());
      clave.setText(nodoAuxiliar.getClave());
      nombre.setText(nodoAuxiliar.getNombre());
      apellido.setText(nodoAuxiliar.getApellido());
      fechanac.setText(nodoAuxiliar.getFechanaci());
      avatar.setText(nodoAuxiliar.getAvatar());

      /* Se añaden las etiquetas a la etiqueta principal (usuario)    */
      /* estableciendo que un usuario tiene nombre, apellido y cargo  */
      usuarios.addContent(nick);
      usuarios.addContent(clave);
      usuarios.addContent(nombre);
      usuarios.addContent(apellido);
      usuarios.addContent(fechanac);
      usuarios.addContent(avatar);

      /* Se añade el nuevo usuario a la estructura XML */
      root.addContent(usuarios);
    }

    /* Se crea un documento nuevo */
    Document doc = new Document(root);

    try {
      /* Se genera un flujo de salida de datos XML */
      XMLOutputter out = new XMLOutputter();

      /* Se asocia el flujo de salida con el archivo donde se guardaran los datos */
      FileOutputStream file = new FileOutputStream(nombreArchivo);

      /* Se manda el documento generado hacia el archivo XML */
      out.output(doc, file);

      /* Se limpia el buffer ocupado por el objeto file y se manda a cerrar el archivo */
      file.flush();
      file.close();

      /* En este caso se manda a imprimir el archivo por la consola   */
      /* ESTE PROCESO NO ES OBLIGATORIO PARA PROCESAR EL XML          */
      out.output(doc, System.out);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #12
0
  public static void guardarArchivoXML(ListaPartida listaDePartidas, boolean valor) {
    Ficha nodoAuxiliarPote;
    Ficha nodoAuxiliarUsuario;
    Ficha nodoAuxiliarServidor;
    Partida partidaActual;
    Ficha fichaActual;

    /* Se crea una raiz de la estructura */
    Element root = new Element("fichas");

    /* Es posible agregar atributos a la estructura inicial */
    root.setAttribute("tipo", "lista de fichas");

    Iterator iteradorPartida = listaDePartidas.getIterator();
    Iterator iteradorFichaUsuario;
    Iterator iteradorFichaPote;
    Iterator iteradorFichaServidor;

    Element ID;
    Element fichaPote;
    Element fichaUsuario;
    Element fichaServidor;
    Element fichaX;
    Element fichaY;

    while (iteradorPartida.hasNext()) {
      ID = new Element("ID");
      fichaPote = new Element("fichapote");
      fichaUsuario = new Element("fichausuario");
      fichaServidor = new Element("fichaservidor");

      partidaActual = (Partida) iteradorPartida.next();

      ID.setAttribute("id", Integer.toString(partidaActual.getID()));

      iteradorFichaPote = partidaActual.getFichapote().getIterator();

      while (iteradorFichaPote.hasNext()) {
        fichaX = new Element("X");
        fichaY = new Element("Y");
        fichaActual = (Ficha) iteradorFichaPote.next();
        fichaX.setText(Integer.toString(fichaActual.getX()));
        fichaY.setText(Integer.toString(fichaActual.getY()));
        fichaPote.addContent(fichaX);
        fichaPote.addContent(fichaY);
      }

      ID.addContent(fichaPote);

      iteradorFichaUsuario = partidaActual.getFichausuario().getIterator();

      while (iteradorFichaUsuario.hasNext()) {
        fichaX = new Element("X");
        fichaY = new Element("Y");
        fichaActual = (Ficha) iteradorFichaUsuario.next();
        fichaX.setText(Integer.toString(fichaActual.getX()));
        fichaY.setText(Integer.toString(fichaActual.getY()));
        fichaUsuario.addContent(fichaX);
        fichaUsuario.addContent(fichaY);
      }

      ID.addContent(fichaUsuario);

      iteradorFichaServidor = partidaActual.getFichaservidor().getIterator();

      while (iteradorFichaServidor.hasNext()) {
        fichaX = new Element("X");
        fichaY = new Element("Y");
        fichaActual = (Ficha) iteradorFichaServidor.next();
        fichaX.setText(Integer.toString(fichaActual.getX()));
        fichaY.setText(Integer.toString(fichaActual.getY()));
        fichaServidor.addContent(fichaX);
        fichaServidor.addContent(fichaY);
      }

      ID.addContent(fichaServidor);

      root.addContent(ID);
    }

    /* Se crea un documento nuevo */
    Document doc = new Document(root);

    try {
      /* Se genera un flujo de salida de datos XML */
      XMLOutputter out = new XMLOutputter();

      /* Se asocia el flujo de salida con el archivo donde se guardaran los datos */
      FileOutputStream file = new FileOutputStream(nombreArchivoFicha);

      /* Se manda el documento generado hacia el archivo XML */
      out.output(doc, file);

      /* Se limpia el buffer ocupado por el objeto file y se manda a cerrar el archivo */
      file.flush();
      file.close();

      /* En este caso se manda a imprimir el archivo por la consola   */
      /* ESTE PROCESO NO ES OBLIGATORIO PARA PROCESAR EL XML          */
      out.output(doc, System.out);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }