Exemplo n.º 1
0
  public static void exportDiffFiles(String diffXmlFile, String targetDir) throws Exception {
    SAXReader reader = new SAXReader();
    Document document = reader.read(new File(diffXmlFile));
    Element rootElement = document.getRootElement();
    Element rootFolder = rootElement.element(DiffXmlReader.TAG_FOLDER_COMP);
    Element ltpathElement = rootFolder.element(DiffXmlReader.TAG_LTPATH);
    String baseDir = ltpathElement.getTextTrim() + File.separator;

    List<String> diffList = DiffXmlReader.readDiffList(document);

    for (String path : diffList) {
      if (path.indexOf(File.separator + "test") != -1
          || path.indexOf(File.separator + "build") != -1) {
        continue;
      }

      File file = new File(path);
      String dir = file.getParent();
      String relativeDir = dir.substring(baseDir.length());

      String targetFolder = targetDir + relativeDir;
      File folder = new File(targetFolder);
      if (!folder.exists()) {
        folder.mkdirs();
      }
      FileUtils.copyFileToDirectory(file, folder);
    }
  }
Exemplo n.º 2
0
  /**
   * 解析周边参数
   *
   * @param inputStream
   * @return
   */
  @SuppressWarnings("unchecked")
  private static NewsMessage parseMusic(InputStream inputStream) {
    NewsMessage NewsMessage = null;

    try {
      // 使用dom4j解析xml字符串
      SAXReader reader = new SAXReader();
      Document document = reader.read(inputStream);
      // 得到xml根元素
      Element root = document.getRootElement();
      // count表示搜到的结果数
      String count = root.element("count").getText();
      // 当搜索到的结果数大于0时
      if (!"0".equals(count)) {
        // 结果
        Element poiList = root.element("poiList");
        List<Element> point = poiList.elements("point");

        // 逐个将point存到Map里面
      }

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

    return NewsMessage;
  }
  public static Map<String, CmisProperty> getCmisPropertiesForEntry(Element feedEntry) {
    Map<String, CmisProperty> props = new HashMap<String, CmisProperty>();

    Element objectElement = feedEntry.element(CMISRA_OBJECT);
    if (objectElement != null) {
      Element properitesElement = objectElement.element(CMIS_PROPERTIES);
      if (properitesElement != null) {
        List<Element> properties = properitesElement.elements();

        for (Element property : properties) {
          final String id = property.attributeValue("propertyDefinitionId");

          props.put(
              id,
              new CmisProperty(
                  property.getName(),
                  id,
                  property.attributeValue("localName"),
                  property.attributeValue("displayName"),
                  property.elementText(CMIS_VALUE)));
        }
      }
    }
    return props;
  }
 public static void fillFieldsfromXML(
     org.dom4j.Element el,
     ims.domain.DomainFactory factory,
     Hl7OutboundRegister obj,
     java.util.HashMap domMap)
     throws Exception {
   org.dom4j.Element fldEl;
   fldEl = el.element("ipAddress");
   if (fldEl != null) {
     obj.setIpAddress(new String(fldEl.getTextTrim()));
   }
   fldEl = el.element("regDateTime");
   if (fldEl != null) {
     obj.setRegDateTime(
         new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim()));
   }
   fldEl = el.element("servletContext");
   if (fldEl != null) {
     obj.setServletContext(new String(fldEl.getTextTrim()));
   }
   fldEl = el.element("lastUpdated");
   if (fldEl != null) {
     obj.setLastUpdated(
         new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim()));
   }
 }
 @SuppressWarnings("unchecked")
 @Override
 protected void initial_internal(Element rootElement) {
   Element EventKeyElement = rootElement.element("EventKey");
   if (EventKeyElement != null) {
     this.eventKey = EventKeyElement.getTextTrim();
   }
   Element SendPicsInfoElement = rootElement.element("SendPicsInfo");
   if (SendPicsInfoElement == null) {
     return;
   }
   Element CountElement = SendPicsInfoElement.element("Count");
   if (CountElement != null) {
     this.count =
         (CountElement != null
                 && CountElement.getTextTrim() != null
                 && !CountElement.getTextTrim().equals(""))
             ? Integer.parseInt(CountElement.getTextTrim())
             : 0;
   }
   Element PicListElement = SendPicsInfoElement.element("PicList");
   if (PicListElement == null) {
     return;
   }
   List<Element> itemElements = PicListElement.elements("item");
   if (itemElements != null && itemElements.size() > 0) {
     for (Element itemElement : itemElements) {
       Element PicMd5SumElement = itemElement.element("PicMd5Sum");
       if (PicMd5SumElement != null) {
         this.addPicMd5Sum(PicMd5SumElement.getTextTrim());
       }
     }
   }
 }
  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);
  }
 public static void fillFieldsfromXML(
     org.dom4j.Element el,
     ims.domain.DomainFactory factory,
     OrderSetComponent obj,
     java.util.HashMap domMap)
     throws Exception {
   org.dom4j.Element fldEl;
   fldEl = el.element("componentSeq");
   if (fldEl != null) {
     obj.setComponentSeq(new Integer(fldEl.getTextTrim()));
   }
   fldEl = el.element("investigation");
   if (fldEl != null) {
     fldEl = fldEl.element("class");
     obj.setInvestigation(
         ims.ocrr.configuration.domain.objects.Investigation.getInvestigationfromXML(
             fldEl, factory, domMap));
   }
   fldEl = el.element("orderSet");
   if (fldEl != null) {
     fldEl = fldEl.element("class");
     obj.setOrderSet(
         ims.ocrr.configuration.domain.objects.OrderSet.getOrderSetfromXML(
             fldEl, factory, domMap));
   }
 }
Exemplo n.º 8
0
  /** Reads and returns complex fault source data */
  private GEMSubductionFaultSourceData getComplexFaultSourceData(double deltaMFD, Element elem) {
    Element complexFaultGeometry = elem.element(COMPLEX_FAULT_GEOMETRY);

    FaultTrace faultTopEdge =
        getFaultTrace(
            complexFaultGeometry
                .element(FAULT_EDGES)
                .element(FAULT_TOP_EDGE)
                .element(LINE_STRING)
                .element(POS_LIST));
    FaultTrace faultBottomEdge =
        getFaultTrace(
            complexFaultGeometry
                .element(FAULT_EDGES)
                .element(FAULT_BOTTOM_EDGE)
                .element(LINE_STRING)
                .element(POS_LIST));
    double rake = Double.valueOf((String) elem.element(RAKE).getData());
    IncrementalMagFreqDist magFreqDist = getMagFreqDist(deltaMFD, elem);

    return new GEMSubductionFaultSourceData(
        extractIDFrom(elem),
        extractNameFrom(elem),
        extractTectonicRegionFrom(elem),
        faultTopEdge,
        faultBottomEdge,
        rake,
        magFreqDist,
        true);
  }
Exemplo n.º 9
0
 /**
  * Processes the Dojo configuration from the supplied {@link Element}
  *
  * @param configElement WebFrameworkConfigElement
  * @param elem Element
  */
 public static void processDojoConfiguration(
     WebFrameworkConfigElement configElement, Element elem) {
   Element dojoConfig = elem.element(DOJO_CONFIG);
   if (dojoConfig != null) {
     String dojoEnabled = dojoConfig.elementTextTrim(DOJO_ENABLED);
     if (dojoEnabled != null) {
       configElement.dojoEnabled = Boolean.valueOf(dojoEnabled);
     }
     String loaderTraceEnabled = dojoConfig.elementTextTrim(DOJO_LOADER_TRACE_ENABLED);
     if (loaderTraceEnabled != null) {
       configElement.dojoLoaderTraceEnabled = Boolean.valueOf(loaderTraceEnabled);
     }
     String bootstrapFile = dojoConfig.elementTextTrim(DOJO_BOOTSTRAP_FILE);
     if (bootstrapFile != null) {
       configElement.dojoBootstrapFile = bootstrapFile;
     }
     String pageWidget = dojoConfig.elementTextTrim(DOJO_PAGE_WIDGETS);
     if (pageWidget != null) {
       configElement.dojoPageWidget = pageWidget;
     }
     String baseUrl = dojoConfig.elementTextTrim(DOJO_BASE_URL);
     if (baseUrl != null) {
       configElement.dojoBaseUrl = baseUrl;
     }
     String messagesObject = dojoConfig.elementTextTrim(DOJO_MESSAGES_OBJECT);
     if (messagesObject != null) {
       configElement.dojoMessagesObject = messagesObject;
     }
     String messagesDefaultScope = dojoConfig.elementTextTrim(DOJO_MESSAGES_DEFAULT_SCOPE);
     if (messagesDefaultScope != null) {
       configElement.dojoMessagesDefaultScope = messagesDefaultScope;
     }
     String defaultLessConfig = dojoConfig.elementTextTrim(DOJO_DEFAULT_LESS_CONFIG);
     if (defaultLessConfig != null) {
       configElement.dojoDefaultLessConfig = defaultLessConfig;
     }
     String aikauVersion = dojoConfig.elementTextTrim(AIKAU_VERSION);
     if (aikauVersion != null) {
       configElement.aikauVersion = aikauVersion;
     }
     Element packages = dojoConfig.element(DOJO_PACKAGES);
     if (packages != null) {
       @SuppressWarnings("unchecked")
       List<Element> packageList = packages.elements(DOJO_PACKAGE);
       if (packageList != null) {
         for (Element packageEntry : packageList) {
           String name = packageEntry.attributeValue(DOJO_PACKAGE_NAME);
           String location = packageEntry.attributeValue(DOJO_PACKAGE_LOCATION);
           if (name != null && location != null) {
             configElement.dojoPackages.put(name, location);
             String main = packageEntry.attributeValue(DOJO_PACKAGE_MAIN);
             if (main != null) {
               configElement.dojoPackagesMain.put(name, main);
             }
           }
         }
       }
     }
   }
 }
Exemplo n.º 10
0
  public static String setGraphXml(String sourceNode, Map<String, String> map, String xml)
      throws IOException {
    Document doc = Dom4jUtil.loadXml(xml);
    Element root = doc.getRootElement();

    Element node = (Element) root.selectSingleNode("//bg:Gateway[@id='" + sourceNode + "']");
    Element portsEl = node.element("ports");
    List portList = portsEl.elements();

    for (int i = 0; i < portList.size(); i++) {
      Element portEl = (Element) portList.get(i);
      if ((portEl.attribute("x") != null) || (portEl.attribute("y") != null)) {
        String id = portEl.attributeValue("id");
        Element outNode =
            (Element) root.selectSingleNode("//bg:SequenceFlow[@startPort='" + id + "']");
        if (outNode != null) {
          String outPort = outNode.attributeValue("endPort");
          Element tmpNode = (Element) root.selectSingleNode("//ciied:Port[@id='" + outPort + "']");
          Element taskNode = tmpNode.getParent().getParent();
          String taskId = taskNode.attributeValue("id");

          Element conditionEl = outNode.element("condition");
          if (conditionEl != null) {
            outNode.remove(conditionEl);
          }
          if (map.containsKey(taskId)) {
            String condition = (String) map.get(taskId);
            Element elAdd = outNode.addElement("condition");
            elAdd.addText(condition);
          }
        }
      }
    }
    return doc.asXML();
  }
  @Override
  public Schedule getSchedule(ConnectorManager connectorManager, String connectorName) {
    Schedule schedule;

    Map<String, String> paramsMap = new HashMap<String, String>();
    paramsMap.put(ServletUtil.XMLTAG_CONNECTOR_NAME, connectorName);
    try {
      Element xml =
          ConnectorManagerRequestUtils.sendGet(connectorManager, "/getSchedule", paramsMap);
      Element connectorStatusElement = xml.element(ServletUtil.XMLTAG_CONNECTOR_STATUS);
      Element connectorScheduleElement =
          connectorStatusElement.element(ServletUtil.XMLTAG_CONNECTOR_SCHEDULES);

      String scheduleTxt = connectorScheduleElement.getTextTrim();
      if (!StringUtils.isEmpty(scheduleTxt)) {
        schedule = new Schedule(scheduleTxt);
      } else {
        schedule = null;
      }
    } catch (Exception e) {
      LOGGER.log(Level.SEVERE, "Error while trying to get schedule", e);
      schedule = null;
    }
    return schedule;
  }
Exemplo n.º 12
0
 /**
  * 通过Title 查询是相似分类信息
  *
  * @param xml
  * @return
  * @throws DocumentException
  */
 public static List<TradingReseCategory> selectCategoryByKey(String xml) throws Exception {
   List<TradingReseCategory> litrc = new ArrayList();
   // 商品分类目录查询
   Document document = formatStr2Doc(xml);
   Element rootElt = document.getRootElement();
   if (rootElt == null) {
     return litrc;
   }
   Element recommend = rootElt.element("SuggestedCategoryArray");
   if (recommend == null) {
     return litrc;
   }
   Iterator<Element> ite = recommend.elementIterator("SuggestedCategory");
   while (ite.hasNext()) {
     Element ele = ite.next();
     Element cate = ele.element("Category");
     Element PercentItemFound = ele.element("PercentItemFound");
     TradingReseCategory trc = new TradingReseCategory();
     trc.setId(Long.parseLong(cate.elementText("CategoryID")));
     trc.setCategoryId(cate.elementText("CategoryID"));
     Iterator<Element> ites = cate.elementIterator("CategoryParentName");
     String cateName = "";
     while (ites.hasNext()) {
       Element ent = ites.next();
       cateName = cateName + ent.getText() + ":";
     }
     trc.setCategoryKey(PercentItemFound.getText() + "%");
     trc.setCategoryName(cateName + cate.elementText("CategoryName"));
     litrc.add(trc);
   }
   return litrc;
 }
Exemplo n.º 13
0
  public void testMultiWithEmptyCollection() throws Exception {
    this.bean.setSomeList(new ArrayList());

    this.tag.setPath("someList");
    this.tag.setItems("${countries}");
    this.tag.setItemValue("isoCode");
    int result = this.tag.doStartTag();
    assertEquals(Tag.SKIP_BODY, result);

    String output = getWriter().toString();
    output = "<doc>" + output + "</doc>";

    SAXReader reader = new SAXReader();
    Document document = reader.read(new StringReader(output));
    Element rootElement = document.getRootElement();
    assertEquals(2, rootElement.elements().size());

    Element selectElement = rootElement.element("select");
    assertEquals("select", selectElement.getName());
    assertEquals("someList", selectElement.attribute("name").getValue());
    assertEquals("multiple", selectElement.attribute("multiple").getValue());

    List children = selectElement.elements();
    assertEquals("Incorrect number of children", 4, children.size());

    Element inputElement = rootElement.element("input");
    assertNotNull(inputElement);
  }
 /**
  * * 根据项目名获取项目所在的view名
  *
  * @param projectName
  * @return
  */
 public static String getProjectViewByProjectName(String projectName) {
   Document doc = null;
   try {
     doc = new SAXReader().read("/usr/share/tomcat6/.hudson/config.xml");
     Element rootEle = doc.getRootElement();
     Element viewEle = rootEle.element("views");
     Iterator<Element> listViewIt = viewEle.elementIterator("listView");
     while (listViewIt.hasNext()) {
       Element listViewEle = listViewIt.next();
       String viewName = listViewEle.elementText("name");
       Iterator<Element> projectNamesIt =
           listViewEle.element("jobNames").elementIterator("string");
       while (projectNamesIt.hasNext()) {
         if (projectName.equals(projectNamesIt.next().getStringValue())) return viewName;
       }
     }
   } catch (DocumentException e) {
     System.out.println(
         "preAntInitTool --> XMLTools --> getProjectViewByProjectName() : DocumentException");
   } catch (Exception e) {
     System.out.println(
         "preAntInitTool --> XMLTools --> getProjectViewByProjectName() : Exception");
   } finally {
     doc = null;
   }
   return null;
 }
  private void createReportItems(
      Document aggregateDoc,
      List<ReportExternalImport> insertableImportReports,
      List<ReportExternalImport> updatableImportReports) {

    String sendingSiteId = (String) aggregateDoc.getRootElement().element("site-id").getData();

    Set<String> eventDateSet = new HashSet<String>(); // to make sure no
    // duplicates

    for (Object reportObj : aggregateDoc.getRootElement().elements("reports")) {
      Element report = (Element) reportObj;
      String eventDate = (String) report.element("event-date").getData();
      eventDate = eventDate.split(" ")[0];

      if (!eventDateSet.contains(eventDate)) {
        eventDateSet.add(eventDate);

        String data = (String) report.element("data").getData();
        ReportExternalImport importReport =
            createReportExternalImport(sendingSiteId, eventDate, data);

        if (importReport.getId() == null) {
          insertableImportReports.add(importReport);
        } else {
          updatableImportReports.add(importReport);
        }
      }
    }
  }
Exemplo n.º 16
0
  private void loadDbConf(String dbConfClassPath) {
    try {
      ClassLoader loader = Thread.currentThread().getContextClassLoader();
      InputStream confInput = loader.getResourceAsStream(dbConfClassPath);
      SAXReader reader = new SAXReader();
      Document doc = reader.read(confInput);
      Element root = doc.getRootElement();
      this.timeBetweenEvictionRunsMillis =
          Long.parseLong(root.elementText("timeBetweenEvictionRunsMillis"));
      this.maxActive = Integer.parseInt(root.elementText("maxActive"));
      this.maxIdle = Integer.parseInt(root.elementText("maxIdle"));
      this.maxWait = Integer.parseInt(root.elementText("maxWait"));
      this.testWhileIdle = Boolean.parseBoolean(root.elementText("maxActive"));

      Element masterEle = root.element("masters");
      Map<String, DbInfo> masterDbInfoMap = this.parseDbInfo(masterEle.elements());
      Element slavesEle = root.element("slaves");
      Map<String, DbInfo> slaveDbInfoMap = this.parseDbInfo(slavesEle.elements());

      this.checkMasterSlave(masterDbInfoMap, slaveDbInfoMap);

      this.masterDbInfoMap.putAll(masterDbInfoMap);
      this.slaveDbInfoMap.putAll(slaveDbInfoMap);

    } catch (Exception e) {
      throw new RuntimeException("loadDbConf failed !" + e.getMessage());
    }
  }
Exemplo n.º 17
0
 /**
  * 得到反馈信息列表
  *
  * @param xml
  * @return
  * @throws DocumentException
  */
 public static List<TradingFeedBackDetail> getFeedBackListElement(String xml) throws Exception {
   List<TradingFeedBackDetail> lifb = new ArrayList();
   Document document = formatStr2Doc(xml);
   Element rootElt = document.getRootElement();
   Element recommend = rootElt.element("FeedbackDetailArray");
   Iterator<Element> iter = recommend.elementIterator("FeedbackDetail");
   while (iter.hasNext()) {
     Element element = iter.next();
     TradingFeedBackDetail tfbd = new TradingFeedBackDetail();
     tfbd.setCommentinguser(element.elementText("CommentingUser"));
     tfbd.setCommentinguserscore(Long.parseLong(element.elementText("CommentingUserScore")));
     tfbd.setCommenttext(
         StringEscapeUtils.escapeXml(element.element("CommentText").getStringValue()));
     tfbd.setCommenttime(DateUtils.returnDate(element.elementText("CommentTime")));
     tfbd.setCommenttype(element.elementText("CommentType"));
     tfbd.setItemid(element.elementText("ItemID"));
     tfbd.setRole(element.elementText("Role"));
     tfbd.setFeedbackid(element.elementText("FeedbackID"));
     tfbd.setTransactionid(element.elementText("TransactionID"));
     tfbd.setOrderlineitemid(element.elementText("OrderLineItemID"));
     tfbd.setItemtitle(element.elementText("ItemTitle"));
     tfbd.setCreateTime(new Date());
     if (element.elementText("ItemPrice") != null) {
       tfbd.setItemprice(Double.parseDouble(element.elementText("ItemPrice")));
     }
     lifb.add(tfbd);
   }
   return lifb;
 }
 @SuppressWarnings("unchecked")
 @Override
 public List<String> getConnectorInstanceNames(
     ConnectorManager connectorManager, String collectionName) {
   List<String> connectorInstanceNames = new ArrayList<String>();
   RecordCollectionServices collectionServices =
       ConstellioSpringUtils.getRecordCollectionServices();
   RecordCollection collection = collectionServices.get(collectionName);
   if (collection != null) {
     Element xml =
         ConnectorManagerRequestUtils.sendGet(connectorManager, "/getConnectorInstanceList", null);
     // ConnectorInstances / ConnectorInstance / ConnectorName
     if (xml.element(ServletUtil.XMLTAG_CONNECTOR_INSTANCES) != null) {
       List<Element> connectorIntanceElements =
           xml.element(ServletUtil.XMLTAG_CONNECTOR_INSTANCES)
               .elements(ServletUtil.XMLTAG_CONNECTOR_INSTANCE);
       for (Iterator<Element> it = connectorIntanceElements.iterator(); it.hasNext(); ) {
         Element connectorInstanceElement = (Element) it.next();
         Element connectorInstanceNameElement =
             connectorInstanceElement.element(ServletUtil.XMLTAG_CONNECTOR_NAME);
         String connectorInstanceName = connectorInstanceNameElement.getTextTrim();
         if (collection.getConnectorInstance(connectorInstanceName) != null) {
           connectorInstanceNames.add(connectorInstanceName);
         }
       }
     }
   }
   return connectorInstanceNames;
 }
Exemplo n.º 19
0
  /**
   * Reads a post signer request off the wire, sends it to the WS with a new callback for returning
   * the response.
   *
   * @param request the post signer request
   * @param responseCallback the callback to send the response back
   */
  void processPostSignerRequest(final IQ request, final PacketCallback responseCallback) {
    Element item = null, signatureElement = null;
    Element pubsubRequest = request.getElement().element("pubsub");
    Element publish = pubsubRequest.element("publish");
    if (publish != null) {
      item = publish.element("item");
      if (item != null) {
        signatureElement = item.element("signature");
      }
    }

    if (publish == null
        || item == null
        || signatureElement == null
        || signatureElement.attribute("domain") == null
        || signatureElement.attribute("algorithm") == null
        || signatureElement.element("certificate") == null) {
      responseCallback.error(FederationErrors.badRequest("Malformed post signer request"));
      return;
    }

    ProtocolSignerInfo signer;
    try {
      signer = XmppUtil.xmlToProtocolSignerInfo(signatureElement);
    } catch (UnknownSignerType e) {
      responseCallback.error(
          FederationErrors.badRequest("Could not understand signer algorithm: " + e));
      return;
    }

    WaveletFederationProvider.PostSignerInfoResponseListener listener =
        new WaveletFederationProvider.PostSignerInfoResponseListener() {
          @Override
          public void onFailure(FederationError error) {
            responseCallback.error(error);
          }

          @Override
          public void onSuccess() {
            IQ response = IQ.createResultIQ(request);

            Element pubsub = response.setChildElement("pubsub", XmppNamespace.NAMESPACE_PUBSUB);
            Element item = pubsub.addElement("publish").addElement("item");

            item.addAttribute("node", "signer");
            item.addElement("signature-response", XmppNamespace.NAMESPACE_WAVE_SERVER);

            responseCallback.run(response);
          }
        };

    // TODO(thorogood,arb): This field is a Bad Idea; it could be faked and not
    // be a provider we host on this instance. Instead, we should infer from the
    // "To:" JID.
    String targetDomain = signatureElement.attributeValue("domain");

    // The first argument is the domain we intend to send this information to.
    waveletProvider.postSignerInfo(targetDomain, signer, listener);
  }
Exemplo n.º 20
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;
 }
Exemplo n.º 21
0
 public static List<TradingPriceTracking> getPriceTrackingItem(String res, String title)
     throws Exception {
   List<TradingPriceTracking> list = new ArrayList<TradingPriceTracking>();
   Document document = formatStr2Doc(res);
   Element rootElt = document.getRootElement();
   Element searchResult = rootElt.element("searchResult");
   Iterator items = searchResult.elementIterator("item");
   while (items.hasNext()) {
     TradingPriceTracking priceTracking = new TradingPriceTracking();
     Element item = (Element) items.next();
     priceTracking.setItemid(SamplePaseXml.getSpecifyElementText(item, "itemId"));
     priceTracking.setCategoryid(
         SamplePaseXml.getSpecifyElementText(item, "primaryCategory", "categoryId"));
     priceTracking.setCategoryname(
         SamplePaseXml.getSpecifyElementText(item, "primaryCategory", "categoryName"));
     priceTracking.setCurrentprice(
         SamplePaseXml.getSpecifyElementText(item, "sellingStatus", "currentPrice"));
     priceTracking.setSellerusername(
         SamplePaseXml.getSpecifyElementText(item, "sellerInfo", "sellerUserName"));
     priceTracking.setTitle(SamplePaseXml.getSpecifyElementText(item, "title"));
     priceTracking.setBidcount(
         SamplePaseXml.getSpecifyElementText(item, "sellingStatus", "bidCount"));
     priceTracking.setPictureurl(SamplePaseXml.getSpecifyElementText(item, "galleryURL"));
     String starttime = SamplePaseXml.getSpecifyElementText(item, "listingInfo", "startTime");
     String endtime = SamplePaseXml.getSpecifyElementText(item, "listingInfo", "endTime");
     if (StringUtils.isNotBlank(starttime)) {
       priceTracking.setStarttime(DateUtils.returnDate(starttime));
     }
     if (StringUtils.isNotBlank(endtime)) {
       priceTracking.setEndtime(DateUtils.returnDate(endtime));
     }
     Element sellingStatus = item.element("sellingStatus");
     String currencyId1 = "";
     if (sellingStatus != null) {
       Element currentPrice = sellingStatus.element("currentPrice");
       if (currentPrice != null) {
         Attribute currencyId = currentPrice.attribute("currencyId");
         if (currencyId != null) {
           currencyId1 = currencyId.getValue();
         }
       }
     }
     priceTracking.setCurrencyid(currencyId1);
     Element shippingInfo = item.element("shippingInfo");
     if (shippingInfo != null) {
       Element shippingServiceCost = shippingInfo.element("shippingServiceCost");
       if (shippingServiceCost != null) {
         Attribute shippingcurrencyId = shippingServiceCost.attribute("currencyId");
         if (shippingcurrencyId != null) {
           priceTracking.setShippingcurrencyid(shippingcurrencyId.getValue());
         }
         priceTracking.setShippingservicecost(shippingServiceCost.getTextTrim());
       }
     }
     priceTracking.setQuerytitle(title);
     list.add(priceTracking);
   }
   return list;
 }
Exemplo n.º 22
0
  /** Reads focal mechanism data (strike, dip and rake) and returns {@link FocalMechanism} */
  private FocalMechanism getFocalMechanism(Element focalMech) {
    Element nodalPlane = focalMech.element(NODAL_PLANES).element(NODAL_PLANE1);

    double strike = Double.valueOf((String) nodalPlane.element(STRIKE).element(VALUE).getData());
    double dip = Double.valueOf((String) nodalPlane.element(DIP).element(VALUE).getData());
    double rake = Double.valueOf((String) nodalPlane.element(RAKE).element(VALUE).getData());
    return new FocalMechanism(strike, dip, rake);
  }
Exemplo n.º 23
0
 /**
  * Registers all JSP page servlets for a plugin.
  *
  * @param manager the plugin manager.
  * @param plugin the plugin.
  * @param webXML the web.xml file containing JSP page names to servlet class file mappings.
  */
 public static void registerServlets(PluginManager manager, Plugin plugin, File webXML) {
   pluginManager = manager;
   if (!webXML.exists()) {
     Log.error(
         "Could not register plugin servlets, file "
             + webXML.getAbsolutePath()
             + " does not exist.");
     return;
   }
   // Find the name of the plugin directory given that the webXML file
   // lives in plugins/[pluginName]/web/web.xml
   String pluginName = webXML.getParentFile().getParentFile().getParentFile().getName();
   try {
     // Make the reader non-validating so that it doesn't try to resolve external
     // DTD's. Trying to resolve external DTD's can break on some firewall configurations.
     SAXReader saxReader = new SAXReader(false);
     try {
       saxReader.setFeature(
           "http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
     } catch (SAXException e) {
       Log.warn("Error setting SAXReader feature", e);
     }
     Document doc = saxReader.read(webXML);
     // Find all <servlet> entries to discover name to class mapping.
     List classes = doc.selectNodes("//servlet");
     Map<String, Class> classMap = new HashMap<String, Class>();
     for (int i = 0; i < classes.size(); i++) {
       Element servletElement = (Element) classes.get(i);
       String name = servletElement.element("servlet-name").getTextTrim();
       String className = servletElement.element("servlet-class").getTextTrim();
       classMap.put(name, manager.loadClass(plugin, className));
     }
     // Find all <servelt-mapping> entries to discover name to URL mapping.
     List names = doc.selectNodes("//servlet-mapping");
     for (int i = 0; i < names.size(); i++) {
       Element nameElement = (Element) names.get(i);
       String name = nameElement.element("servlet-name").getTextTrim();
       String url = nameElement.element("url-pattern").getTextTrim();
       // Register the servlet for the URL.
       Class servletClass = classMap.get(name);
       if (servletClass == null) {
         Log.error("Unable to load servlet, " + name + ", servlet-class not found.");
         continue;
       }
       Object instance = servletClass.newInstance();
       if (instance instanceof GenericServlet) {
         // Initialize the servlet then add it to the map..
         ((GenericServlet) instance).init(servletConfig);
         servlets.put(pluginName + url, (GenericServlet) instance);
       } else {
         Log.warn("Could not load " + (pluginName + url) + ": not a servlet.");
       }
     }
   } catch (Throwable e) {
     Log.error(e.getMessage(), e);
   }
 }
  public static DownloadablePackageOptions parsePackages(InputStream in) {

    DownloadablePackageOptions options = new DownloadablePackageOptions();

    List<DownloadPackage> pkgs = new ArrayList<DownloadPackage>();
    Document document = parse(in);
    if (document != null) {

      String baseUrl =
          document.getRootElement().element("packageDefinitions").attributeValue("baseUrl");

      // parse package definition
      for (Object el :
          document.getRootElement().element("packageDefinitions").elements("package")) {
        DownloadPackage pkg = readPackageDefinition((Element) el, baseUrl);
        if (pkg != null) {
          pkgs.add(pkg);
        }
      }

      options.setAllPackages(pkgs);

      Element install = document.getRootElement().element("install");

      // get common packages
      if (install.element("common") != null) {
        for (Object el : install.element("common").elements("package")) {
          DownloadPackage pkg = readCommonPackage((Element) el, pkgs);
          if (pkg != null) {
            options.addCommonPackage(pkg);
          }
        }
      }

      nodeCounter = 0;
      // get package Options
      for (Object el : install.element("packageOptions").elements("package")) {
        DownloadablePackageOption pkg = readPackageOptions((Element) el, pkgs);
        if (pkg != null) {
          options.addOptions(pkg);
        }
      }

      // get presets
      if (document.getRootElement().element("presets") != null) {
        for (Object el : document.getRootElement().element("presets").elements("preset")) {
          Element preset = (Element) el;
          String presetId = preset.attribute("id").getValue();
          String presetLabel = preset.attribute("label").getValue();
          String pkgList = preset.getText();
          String[] presetPackages = pkgList.split(",");
          options.addPreset(presetId, presetLabel, presetPackages);
        }
      }
    }
    return options;
  }
  /**
   * @see
   *     org.springframework.extensions.config.xml.elementreader.ConfigElementReader#parse(org.dom4j.Element)
   */
  @SuppressWarnings("unchecked")
  public ConfigElement parse(Element element) {
    OpenSearchConfigElement configElement = null;

    if (element != null) {
      String elementName = element.getName();
      if (elementName.equals(ELEMENT_OPENSEARCH) == false) {
        throw new ConfigException(
            "OpenSearchElementReader can only parse "
                + ELEMENT_OPENSEARCH
                + "elements, the element passed was '"
                + elementName
                + "'");
      }

      // go through the registered engines
      configElement = new OpenSearchConfigElement();
      Element pluginsElem = element.element(ELEMENT_ENGINES);
      if (pluginsElem != null) {
        Iterator<Element> engines = pluginsElem.elementIterator(ELEMENT_ENGINE);
        while (engines.hasNext()) {
          // construct engine
          Element engineElem = engines.next();
          String label = engineElem.attributeValue(ATTR_LABEL);
          String labelId = engineElem.attributeValue(ATTR_LABEL_ID);
          String proxy = engineElem.attributeValue(ATTR_PROXY);
          EngineConfig engineCfg = new EngineConfig(label, labelId, proxy);

          // construct urls for engine
          Iterator<Element> urlsConfig = engineElem.elementIterator(ELEMENT_URL);
          while (urlsConfig.hasNext()) {
            Element urlConfig = urlsConfig.next();
            String type = urlConfig.attributeValue(ATTR_TYPE);
            String url = urlConfig.getTextTrim();
            engineCfg.addUrl(type, url);
          }

          // register engine config
          configElement.addEngine(engineCfg);
        }
      }

      // extract proxy configuration
      String url = null;
      Element proxyElem = element.element(ELEMENT_PROXY);
      if (proxyElem != null) {
        Element urlElem = proxyElem.element(ELEMENT_URL);
        if (urlElem != null) {
          url = urlElem.getTextTrim();
          ProxyConfig proxyCfg = new ProxyConfig(url);
          configElement.setProxy(proxyCfg);
        }
      }
    }

    return configElement;
  }
Exemplo n.º 26
0
  /**
   * 根据枚举信息格式化对象属性的值
   *
   * @param objattrValue
   * @param attribType
   * @param valueTables
   * @return
   * @throws Exception
   */
  private String formatObjAttribValue(
      String objattrValue, String attribType, List<ValueTableEntity> valueTables) throws Exception {
    if (StringUtil.isNullOrEmpty(objattrValue)) {
      return "";
    }

    String result = objattrValue;
    if (!StringUtil.isNullOrEmpty(attribType) && valueTables != null && valueTables.size() > 0) {
      if (!"106".equals(attribType)) {
        for (ValueTableEntity entity : valueTables) {
          if (entity.getAttribValue().equals(objattrValue)) {
            if (!StringUtil.isNullOrEmpty(entity.getValueDesc())) {
              result = entity.getValueDesc();
            } else {
              result = entity.getValueName();
            }
          }
        }
      } else if (!StringUtil.isNullOrEmpty(objattrValue)
          && !"NULL".equals(objattrValue.toUpperCase())) {
        // 表格数据
        Document table_doc = DocumentHelper.parseText(objattrValue);

        if (table_doc != null) {
          List tableValueList = table_doc.selectNodes("/DataSource/DataTable");

          if (tableValueList != null) {
            Iterator it = tableValueList.iterator();
            if (it != null) {
              Element itemEle;
              String subvalue;

              while (it.hasNext()) {
                itemEle = (Element) it.next();
                subvalue = itemEle.element("VALUE").getText();

                for (ValueTableEntity entity : valueTables) {
                  if (entity.getAttribValue().equals(subvalue)) {
                    if (!StringUtil.isNullOrEmpty(entity.getValueDesc())) {
                      itemEle.element("VALUE").setText(entity.getValueDesc());
                    } else {
                      itemEle.element("VALUE").setText(entity.getValueName());
                    }
                  }
                }
              }
            }
          }
        }

        result = table_doc.asXML();
      }
    }

    return result;
  }
Exemplo n.º 27
0
 /**
  * Reads magnitude frequency distribution data (truncated Gutenberg-Richter or incremental evenly
  * discretized) and returns {@link IncrementalMagFreqDist}
  */
 private IncrementalMagFreqDist getMagFreqDist(double deltaMFD, Element elem) {
   IncrementalMagFreqDist magFreqDist = null;
   if (elem.element(TRUNCATED_GUTENBERG_RICHTER) != null) {
     magFreqDist =
         getGutenbergRichterMagFreqDist(deltaMFD, elem.element(TRUNCATED_GUTENBERG_RICHTER));
   } else if (elem.element(EVENLY_DISCRETIZED_MAG_FREQ_DIST) != null) {
     magFreqDist = getEvenlyDiscretizedMagFreqDist(elem.element(EVENLY_DISCRETIZED_MAG_FREQ_DIST));
   }
   return magFreqDist;
 }
Exemplo n.º 28
0
 /**
  * Reads Gutenberg-Richter magnitude frequency distribution data and returns {@link
  * GutenbergRichterMagFreqDist}
  */
 private GutenbergRichterMagFreqDist getGutenbergRichterMagFreqDist(
     double deltaMFD, Element gutenbergRichter) {
   GutenbergRichterMagFreqDist magFreqDist;
   double aVal = Double.valueOf((String) gutenbergRichter.element(a_VALUE_CUMULATIVE).getData());
   double bVal = Double.valueOf((String) gutenbergRichter.element(b_VALUE).getData());
   double minMag = Double.valueOf((String) gutenbergRichter.element(MIN_MAGNITUDE).getData());
   double maxMag = Double.valueOf((String) gutenbergRichter.element(MAX_MAGNITUDE).getData());
   magFreqDist = createGrMfd(aVal, bVal, minMag, maxMag, deltaMFD);
   return magFreqDist;
 }
Exemplo n.º 29
0
 /**
  * Reads rupture depth distribution data (rupture magnitude vs. rupture depth) and returns an
  * {@link ArbitrarilyDiscretizedFunc}
  */
 private ArbitrarilyDiscretizedFunc getRuptureDepthDistribution(Element ruptureDepthDist) {
   ArbitrarilyDiscretizedFunc rupDepthDist = new ArbitrarilyDiscretizedFunc();
   String xVals = (String) ruptureDepthDist.element(MAGNITUDE).getData();
   String yVals = (String) ruptureDepthDist.element(DEPTH).getData();
   StringTokenizer xVal = new StringTokenizer(xVals);
   StringTokenizer yVal = new StringTokenizer(yVals);
   while (xVal.hasMoreTokens())
     rupDepthDist.set(Double.valueOf(xVal.nextToken()), Double.valueOf(yVal.nextToken()));
   return rupDepthDist;
 }
Exemplo n.º 30
0
 /** Parse the listenpoint from XML element */
 @Override
 public void parseFromXml(Element root, Runner runner) throws Exception {
   super.parseFromXml(root, runner);
   if (root.element("srtpSender") != null) {
     this.parseSRTPSender(root, 0);
   }
   if (root.element("srtpReceiver") != null) {
     this.parseSRTPSender(root, 1);
   }
 }