Example #1
1
 /**
  * Factory method, equivalent to a "fromXML" for step creation. Looks for a class with the same
  * name as the XML tag, with the first letter capitalized. For example, <call /> is
  * abbot.script.Call.
  */
 public static Step createStep(Resolver resolver, Element el) throws InvalidScriptException {
   String tag = el.getName();
   Map attributes = createAttributeMap(el);
   String name = tag.substring(0, 1).toUpperCase() + tag.substring(1);
   if (tag.equals(TAG_WAIT)) {
     attributes.put(TAG_WAIT, "true");
     name = "Assert";
   }
   try {
     name = "abbot.script." + name;
     Log.debug("Instantiating " + name);
     Class cls = Class.forName(name);
     try {
       // Steps with contents require access to the XML element
       Class[] argTypes = new Class[] {Resolver.class, Element.class, Map.class};
       Constructor ctor = cls.getConstructor(argTypes);
       return (Step) ctor.newInstance(new Object[] {resolver, el, attributes});
     } catch (NoSuchMethodException nsm) {
       // All steps must support this ctor
       Class[] argTypes = new Class[] {Resolver.class, Map.class};
       Constructor ctor = cls.getConstructor(argTypes);
       return (Step) ctor.newInstance(new Object[] {resolver, attributes});
     }
   } catch (ClassNotFoundException cnf) {
     String msg = Strings.get("step.unknown_tag", new Object[] {tag});
     throw new InvalidScriptException(msg);
   } catch (InvocationTargetException ite) {
     Log.warn(ite);
     throw new InvalidScriptException(ite.getTargetException().getMessage());
   } catch (Exception exc) {
     Log.warn(exc);
     throw new InvalidScriptException(exc.getMessage());
   }
 }
  /**
   * 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();
    }
    ;
  }
  public void cargarConfiguracion() throws ConfiguracionException {

    try {
      SAXBuilder builder = new SAXBuilder();
      File xmlFile = new File(this.getPathConfig());
      Document document = (Document) builder.build(xmlFile);
      Element rootNode = document.getRootElement();
      this.setHoraUnificador(Integer.valueOf(rootNode.getChildText("horaUnificador")));
      this.setMinutoUnificador(Integer.valueOf(rootNode.getChildText("minutoUnificador")));
      this.setManianaOTardeUnificador(rootNode.getChildText("manianaOTardeUnificador"));

      this.setSmtp(rootNode.getChildText("smtp"));
      this.setPuerto(rootNode.getChildText("puerto"));
      this.setDesdeMail(rootNode.getChildText("desde"));
      this.setTLS(Boolean.valueOf(rootNode.getChildText("tls")));
      this.setAuth(Boolean.valueOf(rootNode.getChildText("auth")));
      this.setUser(rootNode.getChildText("user"));
      this.setPassword(rootNode.getChildText("password"));

      this.setIpBD(rootNode.getChildText("ipBD"));
      this.setPortBD(rootNode.getChildText("portBD"));

      this.setPathTempImages(rootNode.getChildText("pathTempImages"));
      this.setPathExportDesign(rootNode.getChildText("pathExportDesign"));
      this.setPathConfig(rootNode.getChildText("pathConfig"));
      this.setPathDownloadApp(rootNode.getChildText("pathDownloadApp"));
      this.setKeyGoogleMap(rootNode.getChildText("keyGoogleMap"));

    } catch (Exception e) {
      LogFwk.getInstance(Configuracion.class)
          .error("Error al leer el archivo de configuracion. Detalle: " + e.getMessage());
      throw new ConfiguracionException(
          "Error al leer el archivo de configuracion. Detalle: " + e.getMessage());
    }
  }
Example #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;
  }
Example #5
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;
  }
Example #6
0
 public List<CIBuild> getBuilds(CIJob job) throws PhrescoException {
   if (debugEnabled) {
     S_LOGGER.debug("Entering Method CIManagerImpl.getCIBuilds(CIJob job)");
   }
   List<CIBuild> ciBuilds = null;
   try {
     if (debugEnabled) {
       S_LOGGER.debug("getCIBuilds()  JobName = " + job.getName());
     }
     JsonArray jsonArray = getBuildsArray(job);
     ciBuilds = new ArrayList<CIBuild>(jsonArray.size());
     Gson gson = new Gson();
     CIBuild ciBuild = null;
     for (int i = 0; i < jsonArray.size(); i++) {
       ciBuild = gson.fromJson(jsonArray.get(i), CIBuild.class);
       setBuildStatus(ciBuild, job);
       String buildUrl = ciBuild.getUrl();
       String jenkinUrl = job.getJenkinsUrl() + ":" + job.getJenkinsPort();
       buildUrl =
           buildUrl.replaceAll(
               "localhost:" + job.getJenkinsPort(),
               jenkinUrl); // when displaying url it should display setup machine ip
       ciBuild.setUrl(buildUrl);
       ciBuilds.add(ciBuild);
     }
   } catch (Exception e) {
     if (debugEnabled) {
       S_LOGGER.debug(
           "Entering Method CIManagerImpl.getCIBuilds(CIJob job) " + e.getLocalizedMessage());
     }
   }
   return ciBuilds;
 }
Example #7
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 #8
0
  private void setSvnCredential(CIJob job) throws JDOMException, IOException {
    S_LOGGER.debug("Entering Method CIManagerImpl.setSvnCredential");
    try {
      String jenkinsTemplateDir = Utility.getJenkinsTemplateDir();
      String credentialFilePath = jenkinsTemplateDir + job.getRepoType() + HYPHEN + CREDENTIAL_XML;
      if (debugEnabled) {
        S_LOGGER.debug("credentialFilePath ... " + credentialFilePath);
      }
      File credentialFile = new File(credentialFilePath);

      SvnProcessor processor = new SvnProcessor(credentialFile);

      //			DataInputStream in = new DataInputStream(new FileInputStream(credentialFile));
      //			while (in.available() != 0) {
      //				System.out.println(in.readLine());
      //			}
      //			in.close();

      processor.changeNodeValue("credentials/entry//userName", job.getUserName());
      processor.changeNodeValue("credentials/entry//password", job.getPassword());
      processor.writeStream(new File(Utility.getJenkinsHome() + File.separator + job.getName()));

      // jenkins home location
      String jenkinsJobHome = System.getenv(JENKINS_HOME);
      StringBuilder builder = new StringBuilder(jenkinsJobHome);
      builder.append(File.separator);

      processor.writeStream(new File(builder.toString() + CI_CREDENTIAL_XML));
    } catch (Exception e) {
      S_LOGGER.error(
          "Entered into the catch block of CIManagerImpl.setSvnCredential "
              + e.getLocalizedMessage());
    }
  }
Example #9
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;
	}
Example #10
0
 /**
  * This creates an empty <code>Document</code> object based on a specific parser implementation.
  *
  * @return <code>Document</code> - created DOM Document.
  * @throws JDOMException when errors occur.
  */
 public Document createDocument() throws JDOMException {
   try {
     return (Document) Class.forName("org.apache.xerces.dom.DocumentImpl").newInstance();
   } catch (Exception e) {
     throw new JDOMException(
         e.getClass().getName() + ": " + e.getMessage() + " when creating document", e);
   }
 }
Example #11
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();
    }
  }
  // ------------------------------------------------------------------------------------------------
  // 描述:
  // 设计: 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 #13
0
  /**
   * This creates a new <code>{@link Document}</code> from an existing <code>InputStream</code> by
   * letting a DOM parser handle parsing using the supplied stream.
   *
   * @param in <code>InputStream</code> to parse.
   * @param validate <code>boolean</code> to indicate if validation should occur.
   * @return <code>Document</code> - instance ready for use.
   * @throws IOException when I/O error occurs.
   * @throws JDOMException when errors occur in parsing.
   */
  public Document getDocument(InputStream in, boolean validate) throws IOException, JDOMException {

    try {
      // Load the parser class
      Class parserClass = Class.forName("org.apache.xerces.parsers.DOMParser");
      Object parser = parserClass.newInstance();

      // Set validation
      Method setFeature =
          parserClass.getMethod("setFeature", new Class[] {java.lang.String.class, boolean.class});
      setFeature.invoke(
          parser, new Object[] {"http://xml.org/sax/features/validation", new Boolean(validate)});

      // Set namespaces true
      setFeature.invoke(
          parser, new Object[] {"http://xml.org/sax/features/namespaces", new Boolean(true)});

      // Set the error handler
      if (validate) {
        Method setErrorHandler =
            parserClass.getMethod("setErrorHandler", new Class[] {ErrorHandler.class});
        setErrorHandler.invoke(parser, new Object[] {new BuilderErrorHandler()});
      }

      // Parse the document
      Method parse = parserClass.getMethod("parse", new Class[] {org.xml.sax.InputSource.class});
      parse.invoke(parser, new Object[] {new InputSource(in)});

      // Get the Document object
      Method getDocument = parserClass.getMethod("getDocument", null);
      Document doc = (Document) getDocument.invoke(parser, null);

      return doc;
    } catch (InvocationTargetException e) {
      Throwable targetException = e.getTargetException();
      if (targetException instanceof org.xml.sax.SAXParseException) {
        SAXParseException parseException = (SAXParseException) targetException;
        throw new JDOMException(
            "Error on line "
                + parseException.getLineNumber()
                + " of XML document: "
                + parseException.getMessage(),
            e);
      } else if (targetException instanceof IOException) {
        IOException ioException = (IOException) targetException;
        throw ioException;
      } else {
        throw new JDOMException(targetException.getMessage(), e);
      }
    } catch (Exception e) {
      throw new JDOMException(e.getClass().getName() + ": " + e.getMessage(), e);
    }
  }
 /**
  * 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 #15
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 #16
0
  private void setMailCredential(CIJob job) {
    if (debugEnabled) {
      S_LOGGER.debug("Entering Method CIManagerImpl.setMailCredential");
    }
    try {
      String jenkinsTemplateDir = Utility.getJenkinsTemplateDir();
      String mailFilePath = jenkinsTemplateDir + MAIL + HYPHEN + CREDENTIAL_XML;
      if (debugEnabled) {
        S_LOGGER.debug("configFilePath ... " + mailFilePath);
      }
      File mailFile = new File(mailFilePath);

      SvnProcessor processor = new SvnProcessor(mailFile);

      //			DataInputStream in = new DataInputStream(new FileInputStream(mailFile));
      //			while (in.available() != 0) {
      //				System.out.println(in.readLine());
      //			}
      //			in.close();

      // Mail have to go with jenkins running email address
      InetAddress ownIP = InetAddress.getLocalHost();
      processor.changeNodeValue(
          CI_HUDSONURL,
          HTTP_PROTOCOL
              + PROTOCOL_POSTFIX
              + ownIP.getHostAddress()
              + COLON
              + job.getJenkinsPort()
              + FORWARD_SLASH
              + CI
              + FORWARD_SLASH);
      processor.changeNodeValue("smtpAuthUsername", job.getSenderEmailId());
      processor.changeNodeValue("smtpAuthPassword", job.getSenderEmailPassword());
      processor.changeNodeValue("adminAddress", job.getSenderEmailId());

      // jenkins home location
      String jenkinsJobHome = System.getenv(JENKINS_HOME);
      StringBuilder builder = new StringBuilder(jenkinsJobHome);
      builder.append(File.separator);

      processor.writeStream(new File(builder.toString() + CI_MAILER_XML));
    } catch (Exception e) {
      S_LOGGER.error(
          "Entered into the catch block of CIManagerImpl.setMailCredential "
              + e.getLocalizedMessage());
    }
  }
Example #17
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 #19
0
 /**
  * Look up an appropriate ComponentTester given an arbitrary Component-derived class. If the class
  * is derived from abbot.tester.ComponentTester, instantiate one; if it is derived from
  * java.awt.Component, return a matching Tester. Otherwise return abbot.tester.ComponentTester.
  *
  * <p>
  *
  * @throws ClassNotFoundException If the given class can't be found.
  * @throws IllegalArgumentException If the tester cannot be instantiated.
  */
 protected ComponentTester resolveTester(String className) throws ClassNotFoundException {
   Class testedClass = resolveClass(className);
   if (Component.class.isAssignableFrom(testedClass))
     return ComponentTester.getTester(testedClass);
   else if (ComponentTester.class.isAssignableFrom(testedClass)) {
     try {
       return (ComponentTester) testedClass.newInstance();
     } catch (Exception e) {
       String msg =
           "Custom ComponentTesters must provide "
               + "an accessible no-args Constructor: "
               + e.getMessage();
       throw new IllegalArgumentException(msg);
     }
   }
   String msg = "The given class '" + className + "' is neither a Component nor a ComponentTester";
   throw new IllegalArgumentException(msg);
 }
Example #20
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 #21
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 #22
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;
 }
  public DBConnection(String type) {
    if (type.equals("mysql")) {
      try {
        String userName = "";
        String password = "";
        String url = "";
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        mysqlCon = DriverManager.getConnection(url, userName, password);
        System.out.println("Database connection established");

        if (!mysqlCon.isClosed())
          System.out.println("Successfully connected to " + "MySQL server using TCP/IP...");

      } catch (Exception e) {
        System.err.println("Exception: " + e.getMessage());
      }
    } else if (type.equals("postgre")) {

    }
  }
Example #24
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 #25
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 #26
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 #27
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 #28
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 #29
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 #30
0
 private StructureType assignStructureType(Element structure) throws VisualizerLoadException {
   String name = structure.getName().toLowerCase();
   if (name.compareTo("graph") == 0) {
     if (structure.getAttributeValue("weighted").compareTo("true") == 0)
       return new Graph_Network("NETWORK");
     else return new Graph_Network("GRAPH");
   } else if (name.equals("array")) return new MD_Array();
   else if (name.equals("no3darray")) return new No3darray();
   else if (name.equals("linkedlist")) return new VisLinkedList();
   else if (name.equals("no3dlinkedlist")) return new No3dLinkedList();
   else if (name.equals("linkedlistnonull")) return new VisLinkedListNoNull();
   else if (name.equals("bargraph")) return new BarScat("BAR");
   else if (name.equals("scattergraph"))
     return new BarScat(
         "SCAT"); // not implemented in xml dtd, and does not have a load-from-xml method defined
   else if (name.equals("stack")) return new Stack();
   else if (name.equals("queue")) return new Queue();
   else if (name.equals("tree")) {
     if (structure.getChild("binary_node") != null) return new BinaryTree();
     else return new GeneralTree();
   } else if (name.equals("text")) return new TextStructure();
   // if the XML element name is different from your structure's name, you can do something like
   // this:
   // 	else if( name.equalsIgnoreCase("node"))
   // 	    return new Node();
   else if (name.equals("legend")) return new LegendofColors();
   else {
     // try dynamic typing
     try {
       return assignStructureType(name);
     } catch (Exception e) {
       throw new VisualizerLoadException(
           "Unable to instantiate class \"" + name + "\":\n" + e.getMessage());
     }
   }
 }