Example #1
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());
      }
    }
  }
Example #2
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;
  }
  /**
   * Computes semantic error rate (SER) for a baseline algorithm, which changes the rankings of the
   * 6-best hypothesis by using the following linear function: rank' = rank + 10 *
   * underconstrained_query + 10 * incosnsistent_tense. The effect is to pick the first (i.e.
   * smallest in rank) hypothesis which doesn't fail on one of underconstrained_query or
   * incosnsistent_tense.
   *
   * @deprecated
   */
  public void computeER4LinearRerankingBaseline3Feat(String errOutFN1, String xmlDirName) {
    try {
      BufferedWriter errOutBR = getBufferedWriter(errOutFN1);
      float fiveFoldCV_sumWER = 0;
      for (int k = 1; k < 6; k++) {
        String xmlFileName = xmlDirName + "nbest_test_fold" + k + ".xml";
        float[] wer = getER4LinearReranking(xmlFileName);

        float averageSER = 0;
        for (int i = 0; i < wer.length; i++) {
          averageSER += wer[i];
        }
        averageSER = averageSER / (float) wer.length;
        fiveFoldCV_sumWER += averageSER;
        errOutBR.write(
            "Linear reranking, for fold no  = "
                + k
                + " , the average WER = "
                + averageSER * 100
                + "%");
        errOutBR.write("\n");
        // System.out.println("Linear reranking, for fold no  = " + k + " , the average WER = " +
        // averageSER*100 + "%");
      }

      // System.out.println("Linear reranking, Average SER = " + 100 * (fiveFoldCV_sumWER/5) + "%");
      errOutBR.write("Linear reranking, Average SER = " + 100 * (fiveFoldCV_sumWER / 5) + "%");
      errOutBR.flush();
      errOutBR.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    ;
  }
Example #4
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;
	}
Example #5
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;
	}
  // ------------------------------------------------------------------------------------------------
  // 描述:
  // 设计: Skyline(2001.12.29)
  // 实现: Skyline
  // 修改:
  // ------------------------------------------------------------------------------------------------
  public JFunctionStub getFunctionByID(String ID, Object OwnerObject) {
    IFunction IF = null;
    JFunctionStub FS = null;
    String FT;
    try {
      for (int i = 0; i < FunctionList.size(); i++) {
        FS = (JFunctionStub) FunctionList.get(i);
        //        System.out.println(FS.FunctionID);
        FT = FS.FunctionID + "_";
        if (FS.FunctionID.equals(ID) || FT.equals(ID)) {
          if (FS.Function == null) {
            FS.FunctionClass = Class.forName(FS.ClassName);
            FS.Function = (IFunction) FS.FunctionClass.newInstance();
            FS.Function.InitFunction(FS);
          }
          /* else { // modify by liukun 找到了就直接返回吧 20100715
            return FS;
          }
          */
          //
          if (OwnerObject != null && OwnerObject instanceof Hashtable) {
            Hashtable OTable = (Hashtable) OwnerObject;
            JFunctionStub fs = (JFunctionStub) OTable.get(ID);
            if (fs == null) {
              fs = new JFunctionStub();
              fs.ClassName = FS.ClassName;
              fs.FunctionClass = FS.FunctionClass;
              fs.FunctionID = FS.FunctionID;
              OTable.put(ID, fs);
            }
            if (fs.Function == null) {
              fs.FunctionClass = Class.forName(FS.ClassName);
              fs.Function = (IFunction) FS.FunctionClass.newInstance();
              fs.Function.InitFunction(FS);
            }
            FS = fs;
          } else {
            /**
             * 如果不在用户列表中则需要重新初始化函数 不能直接用系统缓存因为系统缓存只在登录时初始 这样对于像BB类函数,缓冲坐标的行为就可能会出错(中间修改过行列) modified
             * by hufeng 2007.11.20
             */
            FS.Function = (IFunction) FS.FunctionClass.newInstance();
            FS.Function.InitFunction(FS);
          }

          return FS;
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
Example #7
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();
    }
  }
 /**
  * Constructor de la clase.
  *
  * @param pBExport preferencias de exportación.
  */
 public ElemExpFile(preferencesBeanExport pBExport) {
   super("File");
   try {
     pOperation = new preferencesOperation();
     this.setPBExport(pBExport);
     this.setType();
     this.setSource();
     this.setDestination();
     this.setMultipleFiles();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Example #9
0
 public void save() {
   try {
     if (mModel != null) {
       JXMLBaseObject cobjXmlObj = mModel.toXml();
       String dataStr = cobjXmlObj.GetRootXMLString();
       FileOutputStream FOS = new FileOutputStream(FILE_PATH);
       FOS.write(dataStr.getBytes());
       FOS.flush();
       FOS.close();
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Example #10
0
 /**
  * @param book
  * @param startRow
  * @param startCol
  * @param endRow
  * @param endCol
  * @return
  */
 public static String coor2Formula(
     JBook book, int startRow, int startCol, int endRow, int endCol) {
   String T1 = null, T2 = null, Text = null;
   try {
     T1 = book.formatRCNr(startRow, startCol, false);
     if (startRow == endRow && startCol == endCol) {
       Text = T1;
     } else {
       T2 = book.formatRCNr(endRow, endCol, false);
       Text = T1 + ":" + T2;
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   return Text;
 }
 private int countResults(InputStream s) throws SocketTimeoutException {
   ResultHandler handler = new ResultHandler();
   int count = 0;
   try {
     SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
     //		  ByteArrayInputStream bis = new ByteArrayInputStream(s.getBytes("UTF-8"));
     saxParser.parse(s, handler);
     count = handler.getCount();
   } catch (SocketTimeoutException e) {
     throw new SocketTimeoutException();
   } catch (Exception e) {
     System.err.println("SAX Error");
     e.printStackTrace();
     return -1;
   }
   return count;
 }
Example #12
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();
		}

	}
Example #13
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();
    }
  }
Example #14
0
 /**
  * 解析参数 形式:BBLX:TZ01,BBBH:0110,CS:@CQSM@;@YYYY@2004
  *
  * @param params
  * @return
  */
 public static Hashtable parseQueryParams(String params) {
   try {
     if (params != null && params.length() > 0) {
       String[] keys = params.split(",");
       Hashtable map = new Hashtable();
       for (int i = 0; i < keys.length; i++) {
         String crtStr = keys[i];
         int index = crtStr.indexOf(":");
         String key = crtStr.substring(0, index); // 去除:
         String value = crtStr.substring(index + 1);
         map.put(key, value);
       }
       return map;
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   return null;
 }
Example #15
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();
     }
   }
 }
Example #16
0
 /**
  * 解析参数
  *
  * @param params
  * @return
  */
 public static Hashtable parseParams(String params) {
   try {
     if (params != null && params.length() > 0) {
       String[] keys = params.split(";");
       Hashtable map = new Hashtable();
       for (int i = 0; i < keys.length; i++) {
         String crtStr = keys[i];
         int index = crtStr.lastIndexOf("@") + 1;
         String key = crtStr.substring(1, index - 1); // 去除@
         String value = crtStr.substring(index);
         map.put(key, value);
       }
       return map;
     }
   } catch (Exception e) {
     System.out.println("解析参数出现错误:" + params);
     e.printStackTrace();
   }
   return new Hashtable();
 }
Example #17
0
  public String getEnumType(String enumType, String fieldTitle) {

    try {
      EnumerationBean enumBean = EnumerationType.getEnu(enumType);

      // Iterator keys=enumBean.getEnu().keySet().iterator();
      Object[] keys = enumBean.getKeys().toArray();

      StringBuffer StrBuf = new StringBuffer();

      String[] fieldTitlearr = fieldTitle.split(",");

      StrBuf.append(
          "<table id='Data_dropDown' class=\"dropDownTable\"  width='100%' border='0'  cellspacing='1' cellpadding='1' >");

      StrBuf.append("<tr height='20'   class=\"dropDownHead\" >");

      for (int i = 0; i < fieldTitlearr.length; i++) {
        StrBuf.append("<td align=\"center\">" + fieldTitlearr[i] + "</td> ");
      }
      StrBuf.append("</tr>");

      for (int i = 0; i < keys.length; i++) {
        Object key = keys[i];

        StrBuf.append("<tr  onclick=\"TRClick(this)\" height='20' class=\"gridEvenRow\">");
        String[] enumStr = ((String) enumBean.getValue(key)).split(";");
        StrBuf.append("<td  align =\"left\" >" + key.toString() + "</td>");
        StrBuf.append("<td  align =\"left\" >" + enumStr[0] + "</td>");
        StrBuf.append("</tr>");
      }
      StrBuf.append("</table>");

      return StrBuf.toString();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "";
  }
Example #18
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 ;
	}
Example #19
0
  private /*synchronized*/ void readQuestions(StringTokenizer st) throws VisualizerLoadException {
    String tmpStr =
        "STARTQUESTIONS\n"; // When CG's QuestionFactory parses from a string, it looks for
    // a line with STARTQUESTIONS -- hence we add it artificially here
    try { // Build the string for the QuestionFactory
      while (st.hasMoreTokens()) {
        tmpStr += st.nextToken() + "\n";
      }
    } catch (Exception e) {
      e.printStackTrace();
      throw new VisualizerLoadException("Ooof!  bad question format");
    }

    try {
      // System.out.println(tmpStr);
      // Problem -- must make this be line oriented
      GaigsAV.questionCollection = QuestionFactory.parseScript(tmpStr);
    } catch (QuestionParseException e) {
      e.printStackTrace();
      System.out.println("Error parsing questions.");
      throw new VisualizerLoadException("Ooof!  bad question format");
      // throw new IOException();
    }
  } // readQuestions(st)
Example #20
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 #21
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();
    }
  }
  /**
   * Validates whether the the form values are valid.
   *
   * @param String sAction
   * @return boolean
   */
  private boolean isFormValid(String sAction) {
    boolean bReturn = true;
    ApplicationUSOM objectManager = (ApplicationUSOM) getUSOM();
    if (sAction.equalsIgnoreCase(Save_S_FrameWork_Query_Operation)
        || sAction.equalsIgnoreCase(Create_S_FrameWork_Query_Operation)) {
      /////////////////////////////////////////////////////
      // To Do:  Post Submit Form Validation
      /////////////////////////////////////////////////////

      try {
        // if creating, create an empty one first
        if (sAction.equalsIgnoreCase(Create_S_FrameWork_Query_Operation)) {
          m_S_FrameWork_Query_OperationValueObject = new S_FrameWork_Query_OperationValueObject();
        } else // must be saving an existing one, so get it from the cache
        {

          m_S_FrameWork_Query_OperationValueObject =
              objectManager.getCurrentS_FrameWork_Query_Operation();

          // for update the cache usom
          beforeSaveValueObject = m_S_FrameWork_Query_OperationValueObject;

          if (m_S_FrameWork_Query_OperationValueObject == null) {
            logMessage(
                FrameworkLogEventType.DEBUG_LOG_EVENT_TYPE,
                "S_FrameWork_Query_OperationWorkerBean:isFormValid() - failed to acquire the Current S_FrameWork_Query_Operation from the Application USOM. ");
            return (false);
          }
        }

        // AIB Generated Section - Do Not Modify Within

        m_S_FrameWork_Query_OperationValueObject.setOPERATION_CODE(
            StringService.strToStr(getServletRequestParameter("oPERATION_CODE")));

        m_S_FrameWork_Query_OperationValueObject.setFORMSN(
            StringService.strToStr(getServletRequestParameter("fORMSN")));

        m_S_FrameWork_Query_OperationValueObject.setOPERATION_NAME(
            StringService.strToStr(getServletRequestParameter("oPERATION_NAME")));

        m_S_FrameWork_Query_OperationValueObject.setOPERATION_VALUE(
            StringService.strToStr(getServletRequestParameter("oPERATION_VALUE")));

        m_S_FrameWork_Query_OperationValueObject.setOPERATION_ORDER(
            StringService.strToStr(getServletRequestParameter("oPERATION_ORDER")));

        m_S_FrameWork_Query_OperationValueObject.setEXT1(
            StringService.strToStr(getServletRequestParameter("eXT1")));

        m_S_FrameWork_Query_OperationValueObject.setEXT2(
            StringService.strToStr(getServletRequestParameter("eXT2")));

        m_S_FrameWork_Query_OperationValueObject.setEXT3(
            StringService.strToStr(getServletRequestParameter("eXT3")));

        m_S_FrameWork_Query_OperationValueObject.setEXT4(
            StringService.strToStr(getServletRequestParameter("eXT4")));

        m_S_FrameWork_Query_OperationValueObject.setEXT5(
            StringService.strToStr(getServletRequestParameter("eXT5")));

        m_S_FrameWork_Query_OperationValueObject.setDepartmentCode(
            StringService.strToStr(getServletRequestParameter("departmentCode")));

        m_S_FrameWork_Query_OperationValueObject.setCreator(
            StringService.strToStr(getServletRequestParameter("creator")));

        m_S_FrameWork_Query_OperationValueObject.setSecurityGrade(
            StringService.strToStr(getServletRequestParameter("securityGrade")));

        m_S_FrameWork_Query_OperationValueObject.setCreatedTime(
            formatToTimestamp(getServletRequestParameter("createdTime")));

        m_S_FrameWork_Query_OperationValueObject.setLastUpdatedBy(
            StringService.strToStr(getServletRequestParameter("lastUpdatedBy")));

        m_S_FrameWork_Query_OperationValueObject.setLastUpdatedTime(
            formatToTimestamp(getServletRequestParameter("lastUpdatedTime")));

        m_S_FrameWork_Query_OperationValueObject.setRefreshTime(
            formatToTimestamp(getServletRequestParameter("refreshTime")));

        m_S_FrameWork_Query_OperationValueObject.setUploadFlag(
            StringService.strToStr(getServletRequestParameter("uploadFlag")));

        m_S_FrameWork_Query_OperationValueObject.setDownloadFlag(
            StringService.strToStr(getServletRequestParameter("downloadFlag")));

        m_S_FrameWork_Query_OperationValueObject.setDeleteFlag(
            StringService.strToStr(getServletRequestParameter("deleteFlag")));

        // ~AIB Generated

      } catch (Exception exc) {
        logMessage(
            FrameworkLogEventType.DEBUG_LOG_EVENT_TYPE,
            "S_FrameWork_Query_OperationWorkerBean:isFormValid() - Exception caught - " + exc);
        exc.printStackTrace();
        bReturn = false;
      }
    }

    return bReturn;
  }
  /**
   * 设置默认值
   *
   * @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;
  }
  /**
   * 执行反射
   *
   * @param valueObject
   * @param methordName
   * @param type
   * @param defaultValue
   * @return
   */
  private S_FrameWork_Query_OperationValueObject invokeMethord(
      S_FrameWork_Query_OperationValueObject valueObject,
      String methordName,
      String type,
      String defaultValue) {

    // 映射
    String[] paramStr;
    Integer[] paramI;
    Timestamp[] paramDate;
    Float[] paramfl;
    Date[] paramSqlDate;
    java.lang.reflect.Method m;
    Object b;
    DefaultValue dv = new DefaultValue();
    HttpServletRequest request = super.getHttpServletRequest();
    dv.setRequest(request);
    dv.setObjectManager((ApplicationUSOM) getUSOM());

    try {

      // 1.判断数据类型
      // 2.设置默认值
      // 3.默认值有三种:系统信息,用户信息,request信息,session信息
      if (type.equalsIgnoreCase("String")) {

        paramStr = new String[] {dv.setDefault(defaultValue)}; // 字符串
        m =
            (S_FrameWork_Query_OperationValueObject.class)
                .getMethod(methordName, new Class[] {String.class});
        b = m.invoke(valueObject, paramStr);
        return valueObject;

      } else if (type.equalsIgnoreCase("float")) {

        paramfl = new Float[] {Float.valueOf(dv.setDefault(defaultValue))}; // 字符串
        m =
            (S_FrameWork_Query_OperationValueObject.class)
                .getMethod(methordName, new Class[] {Float.class});
        b = m.invoke(valueObject, paramfl);
        return valueObject;

      } else if (type.equalsIgnoreCase("integer")) {

        paramI = new Integer[] {new Integer(dv.setDefault(defaultValue))}; // 整型
        m =
            (S_FrameWork_Query_OperationValueObject.class)
                .getMethod(methordName, new Class[] {int.class});
        b = m.invoke(valueObject, paramI);
        return valueObject;

      } else if (type.equalsIgnoreCase("datetime") || type.equalsIgnoreCase("date")) {

        try {
          paramDate = new Timestamp[] {formatToTimestamp(dv.setDefault(defaultValue))}; // 日期
          m =
              (S_FrameWork_Query_OperationValueObject.class)
                  .getMethod(methordName, new Class[] {Timestamp.class});
          b = m.invoke(valueObject, paramDate);
          return valueObject;
        } catch (Exception e) {
          try {
            paramSqlDate = new Date[] {formatToSQLDATE(dv.setDefault(defaultValue))}; // 日期
            m =
                (S_FrameWork_Query_OperationValueObject.class)
                    .getMethod(methordName, new Class[] {java.sql.Date.class});
            b = m.invoke(valueObject, paramSqlDate);
            return valueObject;
          } catch (Exception e1) {
            e1.printStackTrace();
          }
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
    return valueObject;
  }
Example #25
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 #26
0
  /** Initializes the GUI. */
  private void initGUI() {
    try {
      getShell()
          .addDisposeListener(
              new DisposeListener() {
                public void widgetDisposed(DisposeEvent evt) {
                  shellWidgetDisposed(evt);
                }
              });

      getShell()
          .addControlListener(
              new ControlAdapter() {
                public void controlResized(ControlEvent evt) {
                  shellControlResized(evt);
                }
              });

      getShell()
          .addControlListener(
              new ControlAdapter() {
                public void controlMoved(ControlEvent evt) {
                  shellControlMoved(evt);
                }
              });

      GridLayout thisLayout = new GridLayout();
      this.setLayout(thisLayout);
      {
        GridData toolBarLData = new GridData();
        toolBarLData.grabExcessHorizontalSpace = true;
        toolBarLData.horizontalAlignment = GridData.FILL;
        toolBar = new ToolBar(this, SWT.FLAT);
        toolBar.setLayoutData(toolBarLData);
        toolBar.setBackgroundImage(SWTResourceManager.getImage("images/ToolbarBackground.gif"));
        {
          newToolItem = new ToolItem(toolBar, SWT.NONE);
          newToolItem.setImage(SWTResourceManager.getImage("images/new.gif"));
          newToolItem.setToolTipText("New");
        }
        {
          openToolItem = new ToolItem(toolBar, SWT.NONE);
          openToolItem.setToolTipText("Open");
          openToolItem.setImage(SWTResourceManager.getImage("images/open.gif"));
          openToolItem.addSelectionListener(
              new SelectionAdapter() {
                public void widgetSelected(SelectionEvent evt) {
                  openToolItemWidgetSelected(evt);
                }
              });
        }
        {
          saveToolItem = new ToolItem(toolBar, SWT.NONE);
          saveToolItem.setToolTipText("Save");
          saveToolItem.setImage(SWTResourceManager.getImage("images/save.gif"));
        }
      }
      {
        clientArea = new Composite(this, SWT.NONE);
        GridData clientAreaLData = new GridData();
        clientAreaLData.grabExcessHorizontalSpace = true;
        clientAreaLData.grabExcessVerticalSpace = true;
        clientAreaLData.horizontalAlignment = GridData.FILL;
        clientAreaLData.verticalAlignment = GridData.FILL;
        clientArea.setLayoutData(clientAreaLData);
        clientArea.setLayout(null);
      }
      {
        statusArea = new Composite(this, SWT.NONE);
        GridLayout statusAreaLayout = new GridLayout();
        statusAreaLayout.makeColumnsEqualWidth = true;
        statusAreaLayout.horizontalSpacing = 0;
        statusAreaLayout.marginHeight = 0;
        statusAreaLayout.marginWidth = 0;
        statusAreaLayout.verticalSpacing = 0;
        statusAreaLayout.marginLeft = 3;
        statusAreaLayout.marginRight = 3;
        statusAreaLayout.marginTop = 3;
        statusAreaLayout.marginBottom = 3;
        statusArea.setLayout(statusAreaLayout);
        GridData statusAreaLData = new GridData();
        statusAreaLData.horizontalAlignment = GridData.FILL;
        statusAreaLData.grabExcessHorizontalSpace = true;
        statusArea.setLayoutData(statusAreaLData);
        statusArea.setBackground(SWTResourceManager.getColor(239, 237, 224));
        {
          statusText = new Label(statusArea, SWT.BORDER);
          statusText.setText(" Ready");
          GridData txtStatusLData = new GridData();
          txtStatusLData.horizontalAlignment = GridData.FILL;
          txtStatusLData.grabExcessHorizontalSpace = true;
          txtStatusLData.verticalIndent = 3;
          statusText.setLayoutData(txtStatusLData);
        }
      }
      thisLayout.verticalSpacing = 0;
      thisLayout.marginWidth = 0;
      thisLayout.marginHeight = 0;
      thisLayout.horizontalSpacing = 0;
      thisLayout.marginTop = 3;
      this.setSize(474, 312);
      {
        menu1 = new Menu(getShell(), SWT.BAR);
        getShell().setMenuBar(menu1);
        {
          fileMenuItem = new MenuItem(menu1, SWT.CASCADE);
          fileMenuItem.setText("&File");
          {
            fileMenu = new Menu(fileMenuItem);
            {
              newFileMenuItem = new MenuItem(fileMenu, SWT.PUSH);
              newFileMenuItem.setText("&New");
              newFileMenuItem.setImage(SWTResourceManager.getImage("images/new.gif"));
            }
            {
              openFileMenuItem = new MenuItem(fileMenu, SWT.PUSH);
              openFileMenuItem.setText("&Open");
              openFileMenuItem.setImage(SWTResourceManager.getImage("images/open.gif"));
              openFileMenuItem.addSelectionListener(
                  new SelectionAdapter() {
                    public void widgetSelected(SelectionEvent evt) {
                      openFileMenuItemWidgetSelected(evt);
                    }
                  });
            }
            {
              closeFileMenuItem = new MenuItem(fileMenu, SWT.CASCADE);
              closeFileMenuItem.setText("Close");
            }
            {
              fileMenuSep1 = new MenuItem(fileMenu, SWT.SEPARATOR);
            }
            {
              saveFileMenuItem = new MenuItem(fileMenu, SWT.PUSH);
              saveFileMenuItem.setText("&Save");
              saveFileMenuItem.setImage(SWTResourceManager.getImage("images/save.gif"));
              saveFileMenuItem.addSelectionListener(
                  new SelectionAdapter() {
                    public void widgetSelected(SelectionEvent evt) {
                      saveFileMenuItemWidgetSelected(evt);
                    }
                  });
            }
            {
              fileMenuSep2 = new MenuItem(fileMenu, SWT.SEPARATOR);
            }
            {
              exitMenuItem = new MenuItem(fileMenu, SWT.CASCADE);
              exitMenuItem.setText("E&xit");
              exitMenuItem.addSelectionListener(
                  new SelectionAdapter() {
                    public void widgetSelected(SelectionEvent evt) {
                      exitMenuItemWidgetSelected(evt);
                    }
                  });
            }
            fileMenuItem.setMenu(fileMenu);
          }
        }
        {
          helpMenuItem = new MenuItem(menu1, SWT.CASCADE);
          helpMenuItem.setText("&Help");
          {
            helpMenu = new Menu(helpMenuItem);
            {
              aboutMenuItem = new MenuItem(helpMenu, SWT.CASCADE);
              aboutMenuItem.setText("&About");
              aboutMenuItem.addSelectionListener(
                  new SelectionAdapter() {
                    public void widgetSelected(SelectionEvent evt) {
                      aboutMenuItemWidgetSelected(evt);
                    }
                  });
            }
            helpMenuItem.setMenu(helpMenu);
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }