private Document getDocument(ServletInputStream inputStream, int contentLength) {
    int charCount = 0;
    byte[] byteBuffer = new byte[contentLength];

    while (true) {
      try {
        int readLength = inputStream.readLine(byteBuffer, charCount, 1024);
        // LogEvent.logFatal("IndicatorAggregationReportingServlet", String.valueOf(readLength), new
        // String(byteBuffer).trim());

        if (readLength == -1) {
          return DocumentHelper.parseText(new String(byteBuffer).trim());
        } else {
          charCount += readLength;
        }

      } catch (IOException e) {
        e.printStackTrace();
        return null;
      } catch (DocumentException de) {
        de.printStackTrace();
        return null;
      }
    }
  }
示例#2
0
  /**
   * 根据xml文件对象获得其Document对象
   *
   * @param xmlFile 待解析的XML文件对象
   * @return document对象
   * @throws IOException
   */
  public static Document getDocumentFromFile(File xmlFile) throws IOException {
    if (!xmlFile.exists()) {
      throw new FileNotFoundException("file " + xmlFile + " does not exist!");
    } else if (xmlFile.isDirectory()) {
      throw new IOException("file " + xmlFile + " exists but is a directory!");
    } else if (xmlFile.canRead() == false) {
      throw new IOException("file " + xmlFile + " cannot be read!");
    }

    Document document = null;
    SAXReader saxReader = new SAXReader();

    try {
      setReaderValidation(saxReader);

      document = saxReader.read(xmlFile);

      String namespace_uri = document.getRootElement().getNamespaceURI();
      if (!StringUtils.isEmptyString(namespace_uri)) {
        setReadernameSpace(saxReader, namespace_uri);
      }

    } catch (DocumentException e) {
      e.printStackTrace();
    }

    return document;
  }
示例#3
0
 /**
  * Creates a new XMLReader instance.
  *
  * @param stream XML source stream
  * @throws DocumentException if the XML could not be parsed
  */
 public XMLReader(InputStream stream) throws DocumentException {
   try {
     saxReader.read(stream);
   } catch (org.dom4j.DocumentException e) {
     throw new DocumentException(e.getMessage());
   }
 }
示例#4
0
 /**
  * Creates a new XMLReader instance.
  *
  * @param reader XML source reader
  * @throws DocumentException if the XML could not be parsed
  */
 public XMLReader(Reader reader) throws DocumentException {
   try {
     saxReader.read(reader);
   } catch (org.dom4j.DocumentException e) {
     throw new DocumentException(e.getMessage());
   }
 }
示例#5
0
 /**
  * Faz uma busca a partir do cep enviado, no site <a href="http://www.republicavirtual.com.br"
  * target="_blank">republicavirtual.com.br</a>, retornando o resultado em um objeto {@link
  * WebServiceCep}. <br>
  * <br>
  * N�o se faz necess�rio formata��es, a string pode ser enviada em qualquer formata��o, pois s�
  * ser�o consideradas os primeiros 8 numeros da string. <br>
  * Por Exemplo: <br>
  * Uma <tt>{@link String} "14.568-910"</tt> � automaticamente passada para <tt>"14568910"</tt>.
  * <br>
  * Uma <tt>{@link String} "1%4#5?55%16a8&910"</tt> � automaticamente passada para
  * <tt>"14555168"</tt>, s� levando em conta os primeiros 8 n�meros.
  *
  * @param cep N�mero do cep a ser carregado. S� ser�o considerados os primeiros 8 n�meros da
  *     {@link String} enviada. Todos os caracters n�o num�ricos ser�o removidos, e a string ser�
  *     truncada caso seja maior que 8 caracters.
  * @return {@link WebServiceCep} contendo as informa��es da pesquisa.
  */
 public static WebServiceCep searchCep(String cep) {
   cep = cep.replaceAll("\\D*", ""); // To numeric digits only
   if (cep.length() > 8) cep = cep.substring(0, 8);
   WebServiceCep loadCep = new WebServiceCep(cep);
   try {
     XmlEnums enums = new XmlEnums();
     for (Element e : getElements(cep))
       enums.getXml(e.getQualifiedName()).setCep(e.getText(), loadCep);
   } catch (DocumentException ex) {
     if (ex.getNestedException() != null
         && ex.getNestedException() instanceof java.net.UnknownHostException) {
       loadCep.setResultText("Site não encontrado.");
       loadCep.setResulCode(-14);
     } else {
       loadCep.setResultText("Não foi possivel ler o documento xml.");
       loadCep.setResulCode(-15);
     }
     loadCep.setExceptio(ex);
   } catch (MalformedURLException ex) {
     loadCep.setExceptio(ex);
     loadCep.setResultText("Erro na formação da url.");
     loadCep.setResulCode(-16);
   } catch (Exception ex) {
     loadCep.setExceptio(ex);
     loadCep.setResultText("Erro inesperado.");
     loadCep.setResulCode(-17);
   }
   return loadCep;
 }
示例#6
0
  public static void parse(String xml) {
    Document doc = null;
    try {
      doc = DocumentHelper.parseText(xml); // 将字符串转为XML

      Element rootElt = doc.getRootElement(); // 获取根节点smsReport

      Iterator iters = rootElt.elementIterator("sendResp"); // 获取根节点下的子节点sms

      while (iters.hasNext()) {
        Element recordEle1 = (Element) iters.next();
        Iterator iter = recordEle1.elementIterator("sms");
        int i = 0;
        // 遍历sms节点

        while (iter.hasNext()) {
          Element recordEle = (Element) iter.next();
          String phone = recordEle.elementTextTrim("phone"); // 拿到sms节点下的子节点stat值

          String smsID = recordEle.elementTextTrim("smsID"); // 拿到sms节点下的子节点stat值

          System.out.println(phone + "===" + smsID);
        }
      }
    } catch (DocumentException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public void updateXMLbyId(String id, UpLoadFile pat) {
    String xmlStr = xml2String();
    Document document = null;
    try {
      document = DocumentHelper.parseText(xmlStr);
    } catch (DocumentException e) {
      // TODO 自动生成的 catch 块
      e.printStackTrace();
    }
    Element rootElement = document.getRootElement();
    String rootStrV = rootElement.getStringValue();
    String rootStrT = rootElement.getText();
    List<Element> elements = rootElement.elements("file");

    for (Element ele : elements) {
      Element ide = ele.element("id");
      if (id.equalsIgnoreCase(ide.getTextTrim())) {
        Element nameElement = ele.element("name");
        Element crcElement = ele.element("crc");
        Element urlElement = ele.element("url");
        Element pathElement = ele.element("path");
        Element isUpElement = ele.element("isUpFastFDS");

        nameElement.setText(pat.getName());
        crcElement.setText(pat.getCrc());
        urlElement.setText(pat.getUrl());
        pathElement.setText(pat.getPath());
        isUpElement.setText(pat.getIsUpFastFDS());
      }
    }

    writeXML(file, document);
  }
示例#8
0
 public ModelAndView updateProject(HttpServletRequest request, HttpServletResponse response)
     throws Exception {
   Project project = (Project) BeanUtil.createBean(request, Project.class);
   Map<String, String> result = new HashMap<String, String>();
   boolean success = true;
   try {
     projectService.updateProject(project);
   } catch (ProjectExistException e) {
     logger.error("项目已经存在");
     result.put("errorMsg", "项目已经存在");
     success = false;
   } catch (ProjectNotExistException e) {
     logger.error("项目不存在");
     result.put("errorMsg", "项目不存在");
     success = false;
   } catch (DocumentException e) {
     logger.error(e.getMessage());
     result.put("errorMsg", "项目文件无法读取!");
     success = false;
   } catch (IOException e) {
     logger.error(e.getMessage());
     result.put("errorMsg", "项目文件无法写入!");
     success = false;
   }
   result.put("success", String.valueOf(success));
   return new ModelAndView(getView(request), result);
 }
 public List<Map<String, String>> findTaskNodes(String processDefinitionId) {
   List<Map<String, String>> list = new ArrayList<Map<String, String>>();
   RepositoryService repositoryService = processEngine.getRepositoryService();
   ProcessDefinition processDefinition =
       repositoryService
           .createProcessDefinitionQuery()
           .processDefinitionId(processDefinitionId)
           .uniqueResult();
   InputStream input =
       repositoryService.getResourceAsStream(
           processDefinition.getDeploymentId(), processDefinition.getKey() + ".jpdl.xml");
   try {
     Document doc = new SAXReader().read(input);
     for (Iterator i = doc.getRootElement().elementIterator("task"); i.hasNext(); ) {
       Element foo = (Element) i.next();
       String act = foo.attributeValue("name");
       Map<String, String> rec = new HashMap<String, String>();
       TaskUsers taskUsers =
           (TaskUsers)
               sessionFactory
                   .getCurrentSession()
                   .get(TaskUsers.class, processDefinitionId + "_" + act);
       rec.put("name", act);
       if (taskUsers != null) {
         rec.put("type", taskUsers.getType());
         rec.put("value", taskUsers.getEntityId());
         rec.put("text", taskUsers.getEntityName());
       }
       list.add(rec);
     }
   } catch (DocumentException e) {
     e.printStackTrace();
   }
   return list;
 }
示例#10
0
 /** 功能:XML报文解析函数 */
 public static HashMap GetMessage(String url) {
   SAXReader reader = new SAXReader();
   Document doc = null;
   HashMap hm = null;
   try {
     InputStream in = new URL(url).openStream();
     if (in != null) {
       doc = reader.read(in);
       hm = new HashMap();
       Element root = doc.getRootElement();
       for (Iterator it = root.elementIterator(); it.hasNext(); ) {
         Element e = (Element) it.next();
         if (e.nodeCount() > 1) {
           HashMap hm1 = new HashMap();
           for (Iterator it1 = e.elementIterator(); it1.hasNext(); ) {
             Element e1 = (Element) it1.next();
             hm1.put(e1.getName(), e1.getText());
           }
           hm.put(e.getName(), hm1);
         } else {
           hm.put(e.getName(), e.getText());
         }
       }
     }
     doc.clearContent();
     in.close();
   } catch (DocumentException e) {
     e.printStackTrace();
   } catch (MalformedURLException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return hm;
 }
  public ClassPathXmlApplicationContext(String xml) {

    this.xml = xml;
    try {
      map = this.parseXml(xml);
    } catch (DocumentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SecurityException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (NoSuchMethodException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InstantiationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
示例#12
0
  public static void addToFlex(String name) {
    SAXReader reader = new SAXReader();
    Document document;
    try {
      document = reader.read(new File(FLEX_CONFIG));
      Element flex = document.getRootElement();
      // Flex-------------------------------------------------------------
      Element destination = flex.addElement("destination");
      destination.addAttribute("id", name);
      Element properties = destination.addElement("properties");
      Element factory = properties.addElement("factory");
      Element source = properties.addElement("source");
      factory.addText("springFactory");
      source.addText(Tools.firstLowcase(name));

      // 更新保存----------------------------------------------------
      XMLWriter writer = new XMLWriter(new FileWriter(FLEX_CONFIG));
      writer.write(document);
      writer.close();

    } catch (DocumentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    SAXReader reader = new SAXReader();
    try {
      Document document = reader.read(new File("books.xml"));
      Element bookStore = document.getRootElement();

      Iterator it = bookStore.elementIterator();

      while (it.hasNext()) {
        Element book = (Element) it.next();
        List<org.dom4j.Attribute> bootAttrs = book.attributes();

        for (org.dom4j.Attribute attr : bootAttrs) {
          System.out.println("node name: " + attr.getName() + " - node value: " + attr.getValue());
        }
        Iterator itt = book.elementIterator();
        while (itt.hasNext()) {
          Element bookChild = (Element) itt.next();
          System.out.println(
              "sub node name: "
                  + bookChild.getName()
                  + " - sub node value: "
                  + bookChild.getStringValue());
        }
        System.out.println();
      }

    } catch (DocumentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
示例#14
0
  public static void main(String[] args) {

    try {
      Records records = new Records();
      List<RecordBean> recordList = new ArrayList<RecordBean>();

      SAXReader saxReader = new SAXReader();
      Document document = saxReader.read("test.xml");
      Element root = document.getRootElement();
      List<Element> elements = root.selectNodes("//RECORD");
      System.out.println(elements.size());
      for (Element element : elements) {
        RecordBean recordBean = new RecordBean();
        recordBean.setAuthor(element.elementText("FRatingNum"));
        recordBean.setImage(element.elementText("FDesc"));
        recordBean.setTitle(element.elementText("FTitle"));
        recordBean.setItemId(element.elementText("FItemId"));
        recordList.add(recordBean);
      }
      records.setRecords(recordList);
      JSONObject jsonObject = JSONObject.fromObject(records);
      System.out.println(jsonObject.toString());
    } catch (DocumentException e) {
      e.printStackTrace();
    }
  }
示例#15
0
 /**
  * 修改xml某节点的值
  *
  * @param inputXml 原xml文件
  * @param nodes 要修改的节点
  * @param attributename 属性名称
  * @param value 新值
  * @param outXml 输出文件路径及文件名 如果输出文件为null,则默认为原xml文件
  */
 public static void modifyDocument(
     File inputXml, String nodes, String attributename, String value, String outXml) {
   try {
     SAXReader saxReader = new SAXReader();
     Document document = saxReader.read(inputXml);
     List list = document.selectNodes(nodes);
     Iterator iter = list.iterator();
     while (iter.hasNext()) {
       Attribute attribute = (Attribute) iter.next();
       if (attribute.getName().equals(attributename)) attribute.setValue(value);
     }
     XMLWriter output;
     if (outXml != null) { // 指定输出文件
       output = new XMLWriter(new FileWriter(new File(outXml)));
     } else { // 输出文件为原文件
       output = new XMLWriter(new FileWriter(inputXml));
     }
     output.write(document);
     output.close();
   } catch (DocumentException e) {
     System.out.println(e.getMessage());
   } catch (IOException e) {
     System.out.println(e.getMessage());
   }
 }
示例#16
0
 public Map<Long, WeiboData> gexfDecoder(Resources res, String Filename) {
   SAXReader saxReader = new SAXReader();
   Document document = null;
   Map<Long, WeiboData> map = new HashMap<Long, WeiboData>();
   try {
     InputStream inpt_strm = res.getAssets().open(Filename);
     document = saxReader.read(inpt_strm);
   } catch (DocumentException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   Element root = document.getRootElement();
   Element graph = (Element) root.element("graph");
   List<Element> nodes = graph.element("nodes").elements("node");
   List<Element> edges = graph.element("edges").elements("edge");
   // 读取节点信息
   for (int i = 0; i < nodes.size(); i++) {
     Element node = nodes.get(i);
     // String sss = node.attribute("id").getText();
     long id = Long.parseLong(node.attribute("id").getText());
     String label = node.attribute("label").getText();
     List<Element> viz = node.content();
     Element color = viz.get(0);
     int color_b = Integer.parseInt(color.attribute("b").getText());
     int color_g = Integer.parseInt(color.attribute("g").getText());
     int color_r = Integer.parseInt(color.attribute("r").getText());
     int color_int = Color.argb(255, color_r, color_g, color_b);
     Element position = viz.get(1);
     float x = Float.parseFloat(position.attribute("x").getText());
     float y = Float.parseFloat(position.attribute("y").getText());
     float z = Float.parseFloat(position.attribute("z").getText());
     Element size = viz.get(2);
     float value = Float.parseFloat(size.attribute("value").getText());
     Element image = viz.get(3);
     String imageURI = image.attribute("uri").getText();
     System.out.println(label);
     WeiboData weibodata = new WeiboData(x, y, z, label, id, color_int, value, imageURI);
     map.put(id, weibodata);
   }
   for (int i = 0; i < edges.size(); i++) {
     Element edge = edges.get(i);
     long source_id = Long.parseLong(edge.attribute("source").getText());
     long target_id = Long.parseLong(edge.attribute("target").getText());
     WeiboData source = map.get(source_id);
     WeiboData target = map.get(target_id);
     if (source.parent == null) // 即还没有找到母节点
     {
       source.parent = target;
       target.childs.add(source);
     } else {
       target.parent = source;
       source.childs.add(target);
     }
   }
   return map;
 }
示例#17
0
文件: Dom4jComp.java 项目: Ancai/web
  /**
   * 修改XML文件中内容,并另存为一个新文件 重点掌握dom4j中如何添加节点,修改节点,删除节点
   *
   * @param filename 修改对象文件
   * @param newfilename 修改后另存为该文件
   * @return 返回操作结果, 0表失败, 1表成功
   */
  public int modifyXMLFile(String filename, String newfilename) {
    int returnValue = 0;
    SAXReader saxReader = new SAXReader();
    Document doc = null;
    try {
      /** 修改内容之一:如果book节点中show参数的内容为yes,则修改成no */
      /** 先用xpath查找对象 */
      doc = saxReader.read(new File(filename));
      List list = doc.selectNodes("/books/book/@show");
      Iterator iter = list.iterator();
      while (iter.hasNext()) {
        Attribute attr = (Attribute) iter.next();
        if ("yes".equals(attr.getValue())) {
          attr.setValue("no");
        }
      }
    } catch (DocumentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    /** 修改内容之二:把owner项内容改为Tshinghua 并在owner节点中加入date节点,date节点的内容为2004-09-11,还为date节点添加一个参数type */
    List list = doc.selectNodes("/books/owner");
    Iterator iter = list.iterator();
    if (iter.hasNext()) {
      Element ownEle = (Element) iter.next();
      ownEle.setText("Tshinghua");
      Element dateEle = ownEle.addElement("date");
      dateEle.setText("2012-12-17");
      dateEle.addAttribute("type", "Gregorian calendar");
    }

    /** 修改内容之三:若title内容为Dom4j Tutorials,则删除该节点 */
    List list2 = doc.selectNodes("/books/book");
    Iterator iter2 = list2.iterator();
    while (iter2.hasNext()) {
      Element bookEle = (Element) iter2.next();
      Iterator iterator = bookEle.elementIterator("title");
      while (iterator.hasNext()) {
        Element titleElement = (Element) iterator.next();
        if (titleElement.getText().equals("Dom4j Tutorials")) {
          bookEle.remove(titleElement);
        }
      }
    }

    try {
      /** 将document中的内容写入文件中 */
      XMLWriter writer = new XMLWriter(new FileWriter(new File(newfilename)));
      writer.write(doc);
      writer.close();
      /** 执行成功,需返回1 */
      returnValue = 1;
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    return returnValue;
  }
 public static Document stringToXml(String text) {
   try {
     return DocumentHelper.parseText(text);
   } catch (DocumentException e) {
     e.printStackTrace();
   }
   return null;
 }
示例#19
0
  /** 消息的接收与响应 */
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    resp.setCharacterEncoding("UTF-8");
    PrintWriter out = resp.getWriter();
    try {
      Map<String, String> map = MessageUtil.xmlToMap(req);
      String fromUserName = map.get("FromUserName");
      String toUserName = map.get("ToUserName");
      String msgType = map.get("MsgType");
      String content = map.get("Content");

      String message = null;
      if (MessageUtil.MESSAGE_TEXT.equals(msgType)) {
        if ("1".equals(content)) {
          message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.firstMenu());
        } else if ("2".equals(content)) {
          message = MessageUtil.initNewsMessage(toUserName, fromUserName);
        } else if ("3".equals(content)) {
          message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.threeMenu());
        } else if ("?".equals(content) || "?".equals(content)) {
          message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText());
        } else if (content.startsWith("翻译")) {
          String word = content.replaceAll("^翻译", "").trim();
          if ("".equals(word)) {
            message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.threeMenu());
          } else {
            message = MessageUtil.initText(toUserName, fromUserName, WeixinUtil.translate(word));
          }
        }
      } else if (MessageUtil.MESSAGE_EVNET.equals(msgType)) {
        String eventType = map.get("Event");
        if (MessageUtil.MESSAGE_SUBSCRIBE.equals(eventType)) {
          message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText());
        } else if (MessageUtil.MESSAGE_CLICK.equals(eventType)) {
          message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText());
        } else if (MessageUtil.MESSAGE_VIEW.equals(eventType)) {
          String url = map.get("EventKey");
          message = MessageUtil.initText(toUserName, fromUserName, url);
        } else if (MessageUtil.MESSAGE_SCANCODE.equals(eventType)) {
          String key = map.get("EventKey");
          message = MessageUtil.initText(toUserName, fromUserName, key);
        }
      } else if (MessageUtil.MESSAGE_LOCATION.equals(msgType)) {
        String label = map.get("Label");
        message = MessageUtil.initText(toUserName, fromUserName, label);
      }

      System.out.println(message);

      out.print(message);
    } catch (DocumentException e) {
      e.printStackTrace();
    } finally {
      out.close();
    }
  }
示例#20
0
  public static void addToSRCSpring(
      BaseTable tmp, String daopath, String servicepath, String actionpath) {
    SAXReader reader = new SAXReader();
    String name = tmp.getClass().getSimpleName();
    Document document;
    try {
      document = reader.read(new File(SRC_SPRING_CONFIG));
      Element beans = document.getRootElement();
      beans.addComment(
          "===================以下是" + name + tmp.getComment() + "相关的beans====================");
      // DAO-------------------------------------------------------------
      if (!daopath.equals("")) {
        Element dao = beans.addElement("bean");
        dao.addAttribute("id", Tools.firstLowcase(name + "DAO"));
        dao.addAttribute("class", daopath);
        dao.addAttribute("parent", "DAO");
      }
      // Server----------------------------------------------------------
      if (!servicepath.equals("")) {
        Element service = beans.addElement("bean");
        service.addAttribute("id", Tools.firstLowcase(name + "Service"));
        service.addAttribute("class", servicepath);
        service.addAttribute("parent", "BaseService");
        Element serProperty = service.addElement("property");
        serProperty.addAttribute("name", "dao");
        serProperty.addAttribute("ref", Tools.firstLowcase(name + "DAO"));
      }
      // action----------------------------------------------------------
      if (!actionpath.equals("")) {
        Element action = beans.addElement("bean");
        action.addAttribute("name", name);
        action.addAttribute("class", actionpath);
        Element actionProperty = action.addElement("property");
        actionProperty.addAttribute("name", name.toLowerCase() + "Service");
        actionProperty.addAttribute("ref", name + "Server");
      }
      // action----------------------------------------------------------
      //			Element action = beans.addElement("bean");
      //			action.addAttribute("name", name);
      //			action.addAttribute("class", "com.zb.template." + name + "Action");
      //			Element actionProperty = action.addElement("property");
      //			actionProperty.addAttribute("name", name.toLowerCase() + "Service");
      //			actionProperty.addAttribute("ref", name + "Server");

      // 更新保存----------------------------------------------------
      XMLWriter writer = new XMLWriter(new FileWriter(SRC_SPRING_CONFIG));
      writer.write(document);
      writer.close();

    } catch (DocumentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
示例#21
0
  public void addNotListedOldTasks(String dataSetId) {
    try {
      DataSource dataSource =
          ConfigSingleton.getRepoxContextUtil()
              .getRepoxManager()
              .getDataManager()
              .getDataSourceContainer(dataSetId)
              .getDataSource();

      for (String logFileName : dataSource.getLogFilenames()) {
        boolean matchFound = false;
        for (OldTask oldTask : dataSource.getOldTasksList()) {
          if (oldTask.getLogName().equals(logFileName)) {
            matchFound = true;
            break;
          }
        }

        if (!matchFound && dataSource.getStatus() != DataSource.StatusDS.RUNNING) {
          String oldTaskId = dataSetId + "_" + UUID.randomUUID().toString();
          StatusAndRecords statusAndRecords =
              getStatusAndRecordsFromLogFile(dataSetId, logFileName);
          OldTask oldTask =
              new OldTask(
                  dataSource,
                  oldTaskId,
                  logFileName,
                  "incrementalIngest",
                  statusAndRecords.getStatus(),
                  "0",
                  "3",
                  "300",
                  convertDateToString(getLogFileDate(dataSetId, logFileName)),
                  statusAndRecords.getRecords());
          dataSource.getOldTasksList().add(oldTask);
          ConfigSingleton.getRepoxContextUtil()
              .getRepoxManager()
              .getDataManager()
              .saveOldTask(oldTask);
          log.warn("New Old Tasks added from Log Files for the data set: " + dataSetId);
        }
      }

    } catch (DocumentException e) {
      e.printStackTrace(); // To change body of catch statement use File | Settings | File
      // Templates.
    } catch (IOException e) {
      e.printStackTrace(); // To change body of catch statement use File | Settings | File
      // Templates.
    } catch (StringIndexOutOfBoundsException e) {
      // Do nothing
    } catch (ArrayIndexOutOfBoundsException e) {
      // Do nothing
    } catch (Exception e) {
      // Do nothing
    }
  }
示例#22
0
  private void initializeClient(final InetAddress IP, final Integer remotePort)
      throws DBlncrException {
    Socket nodeSd = null;
    BufferedReader in = null;
    PrintWriter out = null;
    Document msgDocument = null;

    try {
      nodeSd = new Socket(IP, remotePort);
    } catch (IOException e) {
      System.err.println(e);
      System.exit(1);
    }

    try {
      /* obtain an input stream to the node ... */
      in = new BufferedReader(new InputStreamReader(nodeSd.getInputStream()));
      out = new PrintWriter(nodeSd.getOutputStream(), true);
    } catch (IOException e1) {
      logger.error("Could not create in out buffers");
      e1.printStackTrace();
      throw new DBlncrException();
    }
    // send add message
    AddMeMessage request = new AddMeMessage(null);
    out.println(request.request());

    // get response with ID
    try {
      msgDocument = DocumentHelper.parseText(in.readLine());
    } catch (DocumentException e) {
      logger.error("Message received in non XML format");
      e.printStackTrace();
    } catch (IOException e) {
      logger.error("Message could not be recieved");
      e.printStackTrace();
    }
    AddMeMessage response = new AddMeMessage(msgDocument);

    // create and add node
    response.processAdd(nodeSd, out);

    // initialize state wrapper
    StateWrapper st = StateWrapper.getInstance();
    st.setState(Initialization.getInstance());

    // request node list
    InfoMessage im = new InfoMessage(null);
    this.om.dispatchMsg(im.request(), response.getSenderNodeID());

    /* start a new thread to handle the new node */
    Thread t = new Thread(new Node(response.getSenderNodeID()));
    t.start();

    // start server etc
  }
示例#23
0
 public Document createDocument(String source) {
   Document document = null;
   try {
     document = DocumentHelper.parseText(source);
   } catch (DocumentException e) {
     e.printStackTrace(); // To change body of catch statement use File |
     // Settings | File Templates.
   }
   return document;
 }
示例#24
0
 public ClaimDao(String fileName) {
   this.fileName = fileName;
   try {
     this.document = XmlUtils.parseXml(this.fileName);
     // Get root element
     root = document.getRootElement();
   } catch (DocumentException e) {
     e.printStackTrace();
   }
 }
 public static Document parse(InputStream in) {
   Document document = null;
   SAXReader reader = new SAXReader();
   try {
     document = reader.read(in);
   } catch (DocumentException e) {
     e.printStackTrace();
   }
   return document;
 }
示例#26
0
 /** 解析xml */
 public void parseXml() {
   try {
     Document document = this.saxReader.read(new File(this.xmlPath));
     Element root = document.getRootElement();
     this.parseConsumers(root);
   } catch (DocumentException e) {
     e.printStackTrace();
     logger.error("rocket.xml解析异常,error=" + e.getMessage());
   }
 }
示例#27
0
 public static void readRoot() {
   try {
     SAXReader reader = new SAXReader();
     InputStream in = XmlParse.class.getClassLoader().getResourceAsStream("web.xml");
     Document doc = reader.read(in);
     Element root = doc.getRootElement();
     readNode(root, "读取web.xml得到json or xml");
   } catch (DocumentException e) {
     e.printStackTrace();
   }
 }
 /**
  * Import lockup data from an xml-file.
  *
  * @param file
  */
 public void importFromXML(File file) {
   try {
     SAXReader reader = new SAXReader(false);
     Document configuration = reader.read(file);
     Element root = configuration.getRootElement();
     importFromXML(root);
   } catch (DocumentException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
示例#29
0
  public static Document readXml() {
    Document document = null;
    File file = new File("C:/workspace/SimpleIoc/src/Spring.xml");
    try {
      document = (Document) new SAXReader().read(file);
    } catch (DocumentException e) {
      e.printStackTrace();
    }

    return document;
  }
 /**
  * 根据InputStream 文件流取得document对象
  *
  * @param inputStream
  * @return
  */
 public static Document getDocument(InputStream inputStream) {
   SAXReader reader = new SAXReader();
   Document document = null;
   try {
     document = reader.read(inputStream);
   } catch (DocumentException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   return document;
 }