Example #1
0
 public void writeToStream(OutputStream stream) throws IOException {
   Element root = new Element(IWorkFlow.class.getName());
   fillDOMElement(root);
   Document doc = new Document(root);
   XMLOutputter output = new XMLOutputter();
   output.output(doc, stream);
 }
 public String createTable() {
   Element root = new Element("table");
   root.setAttribute("border", "0");
   Document doc = new Document(root);
   Element thead = new Element("thead");
   Element th = new Element("th");
   th.addContent("A header");
   th.setAttribute("class", "aka_header_border");
   thead.addContent(th);
   Element th2 = new Element("th");
   th2.addContent("Another header");
   th2.setAttribute("class", "aka_header_border");
   thead.addContent(th2);
   root.addContent(thead);
   Element tr1 = new Element("tr");
   Element td1 = new Element("td");
   td1.setAttribute("valign", "top");
   td1.setAttribute("class", "cellBorders");
   td1.setText("cell contents");
   tr1.addContent(td1);
   root.addContent(tr1);
   XMLOutputter outp = new XMLOutputter();
   Format format = Format.getPrettyFormat();
   format.setOmitDeclaration(true);
   outp.setFormat(format);
   Writer writer = new StringWriter();
   try {
     outp.output(doc, writer);
   } catch (IOException e) {
     e
         .printStackTrace(); // To change body of catch statement use File | Settings | File
                             // Templates.
   }
   return writer.toString();
 }
Example #3
0
  public static void enregistre(Document document, String fichierpath) {
    try {
      // vérifie si document n'est pas nul
      if (document == null) {
        document = new Document();
      }

      // On utilise ici un affichage classique avec getPrettyFormat()
      XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
      // Remarquez qu'il suffit simplement de créer une instance de FileOutputStream
      // avec en argument le nom du fichier pour effectuer la sérialisation.
      sortie.output(document, new FileOutputStream(fichierpath));
      //			new File(fichier).createNewFile();
    } catch (java.io.IOException e) {
    }
  }
Example #4
0
  public static void validateJDOM(Document pdocument) {
    try {

      //			XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
      DocType type = new DocType("evenement", "evenement.dtd");
      pdocument.setDocType(type);
      XMLOutputter outputter = new XMLOutputter();

      outputter.output(pdocument, System.out);

    } catch (IOException e) {
      System.out.println("format xml non respecté _ 2");
      //			e.printStackTrace();

    }
  }
Example #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();
		}

	}
 /**
  * Write a node to output. Node information includes path, modification, permission, owner and
  * group. For files, it also includes size, replication and block-size.
  */
 static void writeInfo(String parent, HdfsFileStatus i, XMLOutputter doc) throws IOException {
   final SimpleDateFormat ldf = df.get();
   doc.startTag(i.isDir() ? "directory" : "file");
   doc.attribute("path", i.getFullPath(new Path(parent)).toUri().getPath());
   doc.attribute("modified", ldf.format(new Date(i.getModificationTime())));
   doc.attribute("accesstime", ldf.format(new Date(i.getAccessTime())));
   if (!i.isDir()) {
     doc.attribute("size", String.valueOf(i.getLen()));
     doc.attribute("replication", String.valueOf(i.getReplication()));
     doc.attribute("blocksize", String.valueOf(i.getBlockSize()));
   }
   doc.attribute("permission", (i.isDir() ? "d" : "-") + i.getPermission());
   doc.attribute("owner", i.getOwner());
   doc.attribute("group", i.getGroup());
   doc.endTag();
 }
Example #7
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");

		}

	}
Example #8
0
 public static void outputDocument(Document document, Writer out) throws IOException {
   XMLOutputter outputter = new XMLOutputter();
   outputter.setFormat(Format.getPrettyFormat().setEncoding("UTF-8"));
   outputter.output(document, out);
 }
  /**
   * Service a GET request as described below. Request: {@code GET
   * http://<nn>:<port>/listPaths[/<path>][<?option>[&option]*] HTTP/1.1 }
   *
   * <p>Where <i>option</i> (default) in: recursive (&quot;no&quot;) filter (&quot;.*&quot;) exclude
   * (&quot;\..*\.crc&quot;)
   *
   * <p>Response: A flat list of files/directories in the following format: {@code <listing
   * path="..." recursive="(yes|no)" filter="..." time="yyyy-MM-dd hh:mm:ss UTC" version="...">
   * <directory path="..." modified="yyyy-MM-dd hh:mm:ss"/> <file path="..."
   * modified="yyyy-MM-dd'T'hh:mm:ssZ" accesstime="yyyy-MM-dd'T'hh:mm:ssZ" blocksize="..."
   * replication="..." size="..."/> </listing> }
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    final PrintWriter out = response.getWriter();
    final XMLOutputter doc = new XMLOutputter(out, "UTF-8");

    final Map<String, String> root = buildRoot(request, doc);
    final String path = root.get("path");
    final String filePath = ServletUtil.getDecodedPath(request, "/listPaths");

    try {
      final boolean recur = "yes".equals(root.get("recursive"));
      final Pattern filter = Pattern.compile(root.get("filter"));
      final Pattern exclude = Pattern.compile(root.get("exclude"));
      final Configuration conf =
          (Configuration) getServletContext().getAttribute(JspHelper.CURRENT_CONF);

      getUGI(request, conf)
          .doAs(
              new PrivilegedExceptionAction<Void>() {
                @Override
                public Void run() throws IOException {
                  ClientProtocol nn = createNameNodeProxy();
                  doc.declaration();
                  doc.startTag("listing");
                  for (Map.Entry<String, String> m : root.entrySet()) {
                    doc.attribute(m.getKey(), m.getValue());
                  }

                  HdfsFileStatus base = nn.getFileInfo(filePath);
                  if ((base != null) && base.isDir()) {
                    writeInfo(path, base, doc);
                  }

                  Stack<String> pathstack = new Stack<String>();
                  pathstack.push(path);
                  while (!pathstack.empty()) {
                    String p = pathstack.pop();
                    try {
                      byte[] lastReturnedName = HdfsFileStatus.EMPTY_NAME;
                      DirectoryListing thisListing;
                      do {
                        assert lastReturnedName != null;
                        thisListing = nn.getListing(p, lastReturnedName);
                        if (thisListing == null) {
                          if (lastReturnedName.length == 0) {
                            LOG.warn("ListPathsServlet - Path " + p + " does not exist");
                          }
                          break;
                        }
                        HdfsFileStatus[] listing = thisListing.getPartialListing();
                        for (HdfsFileStatus i : listing) {
                          String localName = i.getLocalName();
                          if (exclude.matcher(localName).matches()
                              || !filter.matcher(localName).matches()) {
                            continue;
                          }
                          if (recur && i.isDir()) {
                            pathstack.push(new Path(p, localName).toUri().getPath());
                          }
                          writeInfo(p, i, doc);
                        }
                        lastReturnedName = thisListing.getLastName();
                      } while (thisListing.hasMore());
                    } catch (IOException re) {
                      writeXml(re, p, doc);
                    }
                  }
                  return null;
                }
              });
    } catch (IOException ioe) {
      writeXml(ioe, path, doc);
    } catch (InterruptedException e) {
      LOG.warn("ListPathServlet encountered InterruptedException", e);
      response.sendError(400, e.getMessage());
    } finally {
      if (doc != null) {
        doc.endDocument();
      }
      if (out != null) {
        out.close();
      }
    }
  }
Example #10
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();
    }
  }
Example #11
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();
    }
  }
Example #12
0
 public String xmlToString(Document doc) {
   String xml;
   XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
   xml = out.outputString(doc);
   return xml;
 }