Example #1
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 #2
0
  public List getUserList() {
    List<Map> list = new ArrayList<Map>();

    try {

      /*
      String apiUrl=rallyApiHost+"/user?query="+
      	"((TeamMemberships%20%3D%20https%3A%2F%2Frally1.rallydev.com%2Fslm%2Fwebservice%2F1.34%2Fproject%2F6169133135)%20or%20"+
      	"(TeamMemberships%20%3D%20https%3A%2F%2Frally1.rallydev.com%2Fslm%2Fwebservice%2F1.34%2Fproject%2F6083311244))"+
      	"&fetch=true&order=Name&start=1&pagesize=100";
      */

      String apiUrl =
          rallyApiHost
              + "/user?query=(Disabled%20=%20false)"
              + "&fetch=true&order=Name&start=1&pagesize=100";

      log.info("apiUrl=" + apiUrl);

      String responseXML = getRallyXML(apiUrl);

      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("//Object");
      List xlist = xpath.selectNodes(root);

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {

        Map map = new HashMap();

        Element item = (Element) iter.next();

        String userRef = item.getAttribute("ref").getValue();
        String userName = item.getAttribute("refObjectName").getValue();
        String userObjectId = item.getChildText("ObjectID");

        map.put("userRef", userRef);
        map.put("userObjectId", userObjectId);
        map.put("userName", userName);

        list.add(map);
      }

    } catch (Exception ex) {
      log.error("", ex);
    }

    return list;
  }
 private String getConfigValue(String setting, String name, Document doc)
     throws XPathExpressionException {
   XPathFactory xPathfactory = XPathFactory.newInstance();
   XPath xpath = xPathfactory.newXPath();
   XPathExpression userExpr =
       xpath.compile(
           "wikipediaminer/setting[@name=\""
               + setting
               + "\"]/param[@name=\""
               + name
               + "\"]/@value");
   return userExpr.evaluate(doc);
 }
Example #4
0
 static void assertAD(
     Document d,
     @SuppressWarnings("unused") String mname,
     String name,
     String id,
     String min,
     String max,
     String deflt,
     int cardinality,
     String type,
     String description,
     @SuppressWarnings("unused") String[] optionvalues,
     @SuppressWarnings("unused") String optionLabels[])
     throws XPathExpressionException {
   assertEquals(
       name, xpath.evaluate("//OCD/AD[@id='" + id + "']/@name", d, XPathConstants.STRING));
   assertEquals(id, xpath.evaluate("//OCD/AD[@id='" + id + "']/@id", d, XPathConstants.STRING));
   assertEquals(
       min == null ? "" : min,
       xpath.evaluate("//OCD/AD[@id='" + id + "']/@min", d, XPathConstants.STRING));
   assertEquals(
       max == null ? "" : max,
       xpath.evaluate("//OCD/AD[@id='" + id + "']/@max", d, XPathConstants.STRING));
   assertEquals(
       deflt == null ? "" : deflt,
       xpath.evaluate("//OCD/AD[@id='" + id + "']/@deflt", d, XPathConstants.STRING));
   assertEquals(
       cardinality + "",
       xpath.evaluate("//OCD/AD[@id='" + id + "']/@cardinality", d, XPathConstants.STRING));
   assertEquals(
       type, xpath.evaluate("//OCD/AD[@id='" + id + "']/@type", d, XPathConstants.STRING));
   assertEquals(
       description == null ? "" : description,
       xpath.evaluate("//OCD/AD[@id='" + id + "']/@description", d, XPathConstants.STRING));
 }
Example #5
0
  static {
    try {
      dbf.setNamespaceAware(true);
      db = dbf.newDocumentBuilder();
      xpath.setNamespaceContext(
          new NamespaceContext() {

            @Override
            public Iterator<String> getPrefixes(String namespaceURI) {
              return Arrays.asList("md").iterator();
            }

            @Override
            public String getPrefix(String namespaceURI) {
              return "md";
            }

            @Override
            public String getNamespaceURI(String prefix) {
              return "http://www.osgi.org/xmlns/metatype/v1.1.0";
            }
          });
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
      throw new ExceptionInInitializerError(e);
    }
  }
Example #6
0
  public List getProjectList() {
    List<Map> list = new ArrayList<Map>();

    try {

      String apiUrl = rallyApiHost + "/project?" + "fetch=true&order=Name&start=1&pagesize=200";

      log.info("rallyApiUrl:" + apiUrl);

      String responseXML = getRallyXML(apiUrl);

      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("//Object");
      List xlist = xpath.selectNodes(root);

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {

        Map map = new HashMap();

        Element item = (Element) iter.next();
        String objId = item.getChildText("ObjectID");
        String name = item.getChildText("Name");
        String state = item.getChildText("State");

        map.put("objId", objId);
        map.put("name", name);
        map.put("state", state);

        list.add(map);
      }

    } catch (Exception ex) {
      log.error("ERROR: ", ex);
    }

    return list;
  }
Example #7
0
  public static void testSimple() throws Exception {
    Builder b = new Builder();
    b.addClasspath(new File("bin"));
    b.setProperty("Export-Package", "test.metatype");
    b.setProperty("-metatype", "*");
    b.build();
    Resource r =
        b.getJar().getResource("OSGI-INF/metatype/test.metatype.MetatypeTest$TestSimple.xml");
    assertEquals(0, b.getErrors().size());
    assertEquals(0, b.getWarnings().size());
    System.err.println(b.getJar().getResources().keySet());
    assertNotNull(r);
    IO.copy(r.openInputStream(), System.err);

    Document d = db.parse(r.openInputStream());

    assertEquals("TestSimple", xpath.evaluate("//OCD/@name", d));
    assertEquals("simple", xpath.evaluate("//OCD/@description", d));
    assertEquals("test.metatype.MetatypeTest$TestSimple", xpath.evaluate("//OCD/@id", d));
    assertEquals("test.metatype.MetatypeTest$TestSimple", xpath.evaluate("//Designate/@pid", d));
    assertEquals("test.metatype.MetatypeTest$TestSimple", xpath.evaluate("//Object/@ocdref", d));
    assertEquals("simple", xpath.evaluate("//OCD/AD[@id='simple']/@id", d));
    assertEquals("Simple", xpath.evaluate("//OCD/AD[@id='simple']/@name", d));
    assertEquals("String", xpath.evaluate("//OCD/AD[@id='simple']/@type", d));
    assertEquals("true", xpath.evaluate("//OCD/AD[@id='notSoSimple']/@required", d));
    /**
     * https://github.com/bndtools/bnd/issues/281
     *
     * <p>Using the Bnd annotations library (1.52.3), the generated metatype file will have
     * required='false' for all fields annotated with @Meta.AD(). When this annotation is omitted,
     * or when the required property is explicitly set, the field is correctly marked as required.
     * Taking a glance at the code, the bug appears to be due to aQute.bnd.osgi.Annotation using
     * aQute.bnd.annotation.metatype.Configurable internally for bridging Bnd-annotations to
     * Java-annotations. This configurable only obtains the values from the Bnd-annotation, omitting
     * the defaults defined in the Java annotation. The workaround is to explicitly mention the
     * required property on each field annotated with @Meta.AD.
     */
    assertEquals("true", xpath.evaluate("//OCD/AD[@id='simple']/@required", d));
    assertEquals(
        Integer.MAX_VALUE + "", xpath.evaluate("//OCD/AD[@id='notSoSimple']/@cardinality", d));
  }
Example #8
0
  static void assertOCD(
      Builder b,
      String cname,
      String id,
      String name,
      String description,
      String designate,
      boolean factory,
      String localization)
      throws Exception {
    Resource r = b.getJar().getResource("OSGI-INF/metatype/" + cname + ".xml");
    assertNotNull(r);
    IO.copy(r.openInputStream(), System.err);
    Document d = db.parse(r.openInputStream());
    assertEquals(id, xpath.evaluate("//OCD/@id", d, XPathConstants.STRING));
    assertEquals(name, xpath.evaluate("//OCD/@name", d, XPathConstants.STRING));
    assertEquals(
        localization == null ? cname : localization,
        xpath.evaluate("//OCD/@localization", d, XPathConstants.STRING));
    assertEquals(
        description == null ? "" : description,
        xpath.evaluate("//OCD/@description", d, XPathConstants.STRING));

    if (designate == null) {
      assertEquals(id, xpath.evaluate("//Designate/@pid", d, XPathConstants.STRING));
      if (factory)
        assertEquals(id, xpath.evaluate("//Designate/@factoryPid", d, XPathConstants.STRING));
    } else {
      assertEquals(designate, xpath.evaluate("//Designate/@pid", d, XPathConstants.STRING));
      if (factory)
        assertEquals(
            designate, xpath.evaluate("//Designate/@factoryPid", d, XPathConstants.STRING));
    }

    assertEquals(id, xpath.evaluate("//Object/@ocdref", d, XPathConstants.STRING));
  }
Example #9
0
  // public List getUserStoryList(String sessionId,String iterationId,ServletOutputStream out) {
  public List getUserStoryList(String sessionId, String iterationId, PrintWriter out) {

    List<Map> list = new ArrayList<Map>();

    statusMap.put(sessionId, "0");

    try {

      String apiURL =
          rallyApiHost
              + "/hierarchicalrequirement?"
              + "query=(Iteration%20=%20"
              + rallyApiHost
              + "/iteration/"
              + iterationId
              + ")&fetch=true&start=1&pagesize=100";

      log.info("getUserStoryList apiURL=" + apiURL);

      String responseXML = getRallyXML(apiURL);

      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("//Object");
      List xlist = xpath.selectNodes(root);

      int totalSteps = xlist.size() + 1;
      int currentStep = 0;

      List taskRefLink = new ArrayList();

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {
        double totalTimeSpent = 0.0D;

        Map map = new HashMap();

        Element item = (Element) iter.next();
        String objId = item.getChildText("ObjectID");
        String name = item.getChildText("Name");
        String planEstimate = item.getChildText("PlanEstimate");
        String formattedId = item.getChildText("FormattedID");

        String taskActualTotal = item.getChildText("TaskActualTotal");
        String taskEstimateTotal = item.getChildText("TaskEstimateTotal");
        String taskRemainingTotal = item.getChildText("TaskRemainingTotal");
        String scheduleState = item.getChildText("ScheduleState");

        Element ownerElement = item.getChild("Owner");

        String owner = "";
        String ownerRef = "";

        if (ownerElement != null) {
          owner = ownerElement.getAttributeValue("refObjectName");
        }

        Element taskElements = item.getChild("Tasks");
        // List taskElementList=taskElements.getContent();
        List taskElementList = taskElements.getChildren();

        List taskList = new ArrayList();

        log.info("taskElements.getChildren=" + taskElements);
        log.info("taskList=" + taskElementList);

        for (int i = 0; i < taskElementList.size(); i++) {
          Element taskElement = (Element) taskElementList.get(i);

          String taskRef = taskElement.getAttributeValue("ref");

          String[] objectIdArr = taskRef.split("/");
          String objectId = objectIdArr[objectIdArr.length - 1];

          log.info("objectId=" + objectId);

          // Map taskMap=getTaskMap(taskRef);
          Map taskMap = getTaskMapBatch(objectId);

          double taskTimeSpentTotal =
              Double.parseDouble((String) taskMap.get("taskTimeSpentTotal"));
          totalTimeSpent += taskTimeSpentTotal;
          taskList.add(taskMap);
        }

        map.put("type", "userstory");
        map.put("formattedId", formattedId);
        map.put("name", name);
        map.put("taskStatus", scheduleState);
        map.put("owner", owner);
        map.put("planEstimate", planEstimate);
        map.put("taskEstimateTotal", taskEstimateTotal);
        map.put("taskRemainingTotal", taskRemainingTotal);
        map.put("taskTimeSpentTotal", "" + totalTimeSpent);

        list.add(map);
        list.addAll(taskList);

        ++currentStep;
        double percentage = 100.0D * currentStep / totalSteps;
        String status = "" + Math.round(percentage);
        statusMap.put(sessionId, status);

        out.println("<script>parent.updateProcessStatus('" + status + "%')</script>" + status);
        out.flush();
        log.info("out.flush..." + status);

        // log.info("status="+status+" sessionId="+sessionId);
        // log.info("L1 statusMap="+statusMap+" "+statusMap.hashCode());

      }

      double planEstimate = 0.0D;
      double taskEstimateTotal = 0.0D;
      double taskRemainingTotal = 0.0D;
      double taskTimeSpentTotal = 0.0D;
      Map iterationMap = new HashMap();
      for (Map map : list) {
        String type = (String) map.get("type");

        String planEstimateStr = (String) map.get("planEstimate");

        log.info("planEstimateStr=" + planEstimateStr);

        if ("userstory".equals(type)) {

          if (planEstimateStr != null) {
            planEstimate += Double.parseDouble(planEstimateStr);
          }
          taskEstimateTotal += Double.parseDouble((String) map.get("taskEstimateTotal"));
          taskRemainingTotal += Double.parseDouble((String) map.get("taskRemainingTotal"));
          taskTimeSpentTotal += Double.parseDouble((String) map.get("taskTimeSpentTotal"));
        }
      }

      apiURL = rallyApiHost + "/iteration/" + iterationId + "?fetch=true";
      log.info("iteration apiURL=" + apiURL);
      responseXML = getRallyXML(apiURL);

      bSAX = new org.jdom.input.SAXBuilder();
      doc = bSAX.build(new StringReader(responseXML));
      root = doc.getRootElement();

      xpath = XPath.newInstance("//Iteration");
      xlist = xpath.selectNodes(root);

      String projName = "";
      String iterName = "";
      String iterState = "";

      iter = xlist.iterator();
      while (iter.hasNext()) {
        Element item = (Element) iter.next();

        iterName = item.getChildText("Name");
        iterState = item.getChildText("State");
        Element projElement = item.getChild("Project");
        projName = projElement.getAttributeValue("refObjectName");
      }

      iterationMap.put("type", "iteration");
      iterationMap.put("formattedId", "");
      iterationMap.put("name", projName + " - " + iterName);
      iterationMap.put("taskStatus", iterState);
      iterationMap.put("owner", "");

      iterationMap.put("planEstimate", "" + planEstimate);
      iterationMap.put("taskEstimateTotal", "" + taskEstimateTotal);
      iterationMap.put("taskRemainingTotal", "" + taskRemainingTotal);
      iterationMap.put("taskTimeSpentTotal", "" + taskTimeSpentTotal);

      list.add(0, iterationMap);

      statusMap.put(sessionId, "100");

      log.info("L2 statusMap=" + statusMap);

      log.info("L2 verify=" + getProcessStatus(sessionId));
      log.info("-----------");

      // String jsonData=JsonUtil.encodeObj(list);
      String jsonData = JSONValue.toJSONString(list);

      out.println("<script>parent.tableResult=" + jsonData + "</script>");
      out.println("<script>parent.showTableResult()</script>");

    } catch (Exception ex) {
      log.error("ERROR: ", ex);
    }

    return list;
  }
Example #10
0
  public List getIterationList(String projectId) {
    List<Map> list = new ArrayList<Map>();

    try {

      String apiUrl =
          rallyApiHost
              + "/iteration?"
              + "project="
              + rallyApiHost
              + "/project/"
              + projectId
              + "&fetch=true&order=Name%20desc&start=1&pagesize=100";

      String checkProjectRef = rallyApiHost + "/project/" + projectId;

      log.info("rallyApiUrl:" + apiUrl);
      log.info("checkProjectRef:" + checkProjectRef);

      String responseXML = getRallyXML(apiUrl);

      SimpleDateFormat ISO8601FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
      Date currentDate = new Date();

      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("//Object");
      List xlist = xpath.selectNodes(root);

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {

        Map map = new HashMap();

        Element item = (Element) iter.next();
        String objId = item.getChildText("ObjectID");
        String name = item.getChildText("Name");
        String state = item.getChildText("State");

        String startDateStr = item.getChildText("StartDate");
        String endDateStr = item.getChildText("EndDate");

        Date startDate = ISO8601FORMAT.parse(startDateStr);
        Date endDate = ISO8601FORMAT.parse(endDateStr);

        boolean isCurrent = false;

        int startCheck = startDate.compareTo(currentDate);
        int endCheck = endDate.compareTo(currentDate);

        if (startCheck < 0 && endCheck > 0) {
          isCurrent = true;
        }

        log.info("name=" + name + " isCurrent=" + isCurrent);

        String releaseRef = item.getAttribute("ref").getValue();

        // In child project, parent object have to be filiered
        Element projectElement = item.getChild("Project");
        String projectRef = projectElement.getAttributeValue("ref");

        if (projectRef.equals(checkProjectRef)) {

          map.put("objId", objId);
          map.put("rallyRef", releaseRef);
          map.put("name", name);
          map.put("state", state);
          map.put("isCurrent", "" + isCurrent);

          list.add(map);
        }
      }

      log.info("-----------");

    } catch (Exception ex) {
      log.error("ERROR: ", ex);
    }

    return list;
  }
Example #11
0
  public List getUserTimeSpentByDate(String userObjectId, String startDate, String endDate) {
    List list = new ArrayList();

    log.info("userObjectId=" + userObjectId);
    log.info("startDate=" + startDate);
    log.info("endDate=" + endDate);

    try {

      String apiUrl =
          rallyApiHost
              + "/timeentryvalue?query=((TimeEntryItem.User.ObjectId%20=%20"
              + userObjectId
              + ")"
              + "%20and%20((DateVal%20%3E=%20"
              + startDate
              + ")%20and%20(DateVal%20%3C=%20"
              + endDate
              + ")))"
              + "&start=1&pagesize=100&fetch=true";

      log.info("apiUrl=" + apiUrl);

      String responseXML = getRallyXML(apiUrl);

      log.info("responseXML=" + responseXML);

      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("//Object");
      List xlist = xpath.selectNodes(root);

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {

        // Map map=new HashMap();

        Element item = (Element) iter.next();

        String hours = item.getChildText("Hours");

        Element timeEntryItemElement = item.getChild("TimeEntryItem");
        String timeEntryItemRef = timeEntryItemElement.getAttributeValue("ref");

        Map map = getUserStoryTaskMap(timeEntryItemRef);

        String checkTaskId = (String) map.get("taskFormattedId");

        boolean isExist = false;
        for (int i = 0; i < list.size(); i++) {
          Map existMap = (Map) list.get(i);

          log.info("existMap=" + existMap);

          String existTaskId = (String) existMap.get("taskFormattedId");

          log.info("existTaskId=" + existTaskId);
          log.info("checkTaskId=" + checkTaskId);

          if (existTaskId != null && existTaskId.equals(checkTaskId)) {
            isExist = true;
            String existHours = (String) existMap.get("hours");
            double eHour = 0.0D;
            if (!"".equals(existHours)) {
              eHour = Double.parseDouble(existHours);
            }
            double nHour = 0.0D;

            if (!"".equals(hours)) {
              nHour = Double.parseDouble(hours);
            }

            log.info("nHour=" + nHour);
            log.info("eHour=" + eHour);

            nHour += eHour;
            log.info("2 nHour=" + nHour);
            existMap.put("hours", "" + nHour);

            break;
          }
        }

        if (!isExist) {
          map.put("hours", hours);
          list.add(map);
        }

        log.info("hours=" + hours);
        log.info("timeEntryItemRef=" + timeEntryItemRef);

        // list.add(map);

      }

      Collections.sort(
          list,
          new Comparator<Map<String, String>>() {
            public int compare(Map<String, String> m1, Map<String, String> m2) {
              if (m1.get("projectName") == null || m2.get("projectName") == null) return -1;
              return m1.get("projectName").compareTo(m2.get("projectName"));
            }
          });

      // Sum up the total time
      double totalTaskEstimate = 0.0D;
      double totalTaskRemaining = 0.0D;
      double totalHours = 0.0D;
      for (int i = 0; i < list.size(); i++) {
        Map map = (Map) list.get(i);

        log.info("taskEstimate=" + (String) map.get("taskEstimate"));
        log.info("taskRemaining=" + (String) map.get("taskRemaining"));
        log.info("hours=" + (String) map.get("hours"));

        log.info("map==" + map);

        try {
          double taskEstimate = Double.parseDouble((String) map.get("taskEstimate"));
          double taskRemaining = Double.parseDouble((String) map.get("taskRemaining"));
          double hours = Double.parseDouble((String) map.get("hours"));

          totalTaskEstimate += taskEstimate;
          totalTaskRemaining += taskRemaining;
          totalHours += hours;
        } catch (Exception e) {
          log.info("ERROR in parsing number" + e);
        }
      }

      Map firstMap = new HashMap();

      firstMap.put("taskFormattedId", "");
      firstMap.put("taskName", "");
      firstMap.put("taskState", "");
      firstMap.put("owner", "");
      firstMap.put("taskEstimate", "" + totalTaskEstimate);
      firstMap.put("taskRemaining", "" + totalTaskRemaining);
      firstMap.put("hours", "" + totalHours);
      firstMap.put("projectName", "");
      firstMap.put("iterationName", "");

      list.add(0, firstMap);

    } catch (Exception ex) {
      log.error("", ex);
    }

    return list;
  }
  @Override
  public HashSet<ScoredAnnotation> solveSa2W(String text) throws AnnotationException {
    HashSet<ScoredAnnotation> res;
    try {
      res = new HashSet<ScoredAnnotation>();
      lastTime = Calendar.getInstance().getTimeInMillis();

      URL wikiApi = new URL(url);
      String parameters =
          "references=true&repeatMode=all&minProbability=0.0&source="
              + URLEncoder.encode(text, "UTF-8");
      HttpURLConnection slConnection = (HttpURLConnection) wikiApi.openConnection();
      slConnection.setRequestProperty("accept", "text/xml");
      slConnection.setDoOutput(true);
      slConnection.setDoInput(true);
      slConnection.setRequestMethod("POST");
      slConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      slConnection.setRequestProperty("charset", "utf-8");
      slConnection.setRequestProperty(
          "Content-Length", "" + Integer.toString(parameters.getBytes().length));
      slConnection.setUseCaches(false);

      DataOutputStream wr = new DataOutputStream(slConnection.getOutputStream());
      wr.writeBytes(parameters);
      wr.flush();
      wr.close();
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document doc = builder.parse(slConnection.getInputStream());

      /*			URL wikiApi = new URL(url+"?references=true&repeatMode=all&minProbability=0.0&source="+URLEncoder.encode(text, "UTF-8"));
      			URLConnection wikiConnection = wikiApi.openConnection();
      			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      			DocumentBuilder builder = factory.newDocumentBuilder();
      			Document doc = builder.parse(wikiConnection.getInputStream());
      */

      lastTime = Calendar.getInstance().getTimeInMillis() - lastTime;

      XPathFactory xPathfactory = XPathFactory.newInstance();
      XPath xpath = xPathfactory.newXPath();
      XPathExpression idExpr = xpath.compile("//detectedTopic/@id");
      XPathExpression weightExpr = xpath.compile("//detectedTopic/@weight");
      XPathExpression referenceExpr = xpath.compile("//detectedTopic/references");

      NodeList ids = (NodeList) idExpr.evaluate(doc, XPathConstants.NODESET);
      NodeList weights = (NodeList) weightExpr.evaluate(doc, XPathConstants.NODESET);
      NodeList references = (NodeList) referenceExpr.evaluate(doc, XPathConstants.NODESET);

      for (int i = 0; i < weights.getLength(); i++) {
        if (weights.item(i).getNodeType() != Node.TEXT_NODE) {
          int id = Integer.parseInt(ids.item(i).getNodeValue());
          float weight = Float.parseFloat(weights.item(i).getNodeValue());
          //					System.out.println("ID="+ids.item(i).getNodeValue()+" weight="+weight);
          XPathExpression startExpr =
              xpath.compile("//detectedTopic[@id=" + id + "]/references/reference/@start");
          XPathExpression endExpr =
              xpath.compile("//detectedTopic[@id=" + id + "]/references/reference/@end");
          NodeList starts =
              (NodeList) startExpr.evaluate(references.item(i), XPathConstants.NODESET);
          NodeList ends = (NodeList) endExpr.evaluate(references.item(i), XPathConstants.NODESET);
          for (int j = 0; j < starts.getLength(); j++) {
            int start = Integer.parseInt(starts.item(j).getNodeValue());
            int end = Integer.parseInt(ends.item(j).getNodeValue());
            int len = end - start;
            res.add(new ScoredAnnotation(start, len, id, weight));
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      throw new AnnotationException(
          "An error occurred while querying Wikipedia Miner API. Message: " + e.getMessage());
    }
    return res;
  }
 /**
  * This calls the external Moodle web service.
  *
  * <p>params String containing the parameters of the call.<br>
  * elements NodeList containing name/value pairs of returned XML data.
  *
  * @param params String
  * @return elements NodeList
  * @throws MoodleRestException
  */
 public static NodeList call(String params) throws MoodleRestException {
   NodeList elements = null;
   try {
     URL getUrl = new URL(url);
     HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
     connection.setRequestMethod("POST");
     connection.setRequestProperty("Accept", "application/xml");
     connection.setDoOutput(true);
     OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
     writer.write(params);
     writer.flush();
     writer.close();
     // Used for testing
     StringBuilder buffer = new StringBuilder();
     BufferedReader reader =
         new BufferedReader(new InputStreamReader(connection.getInputStream()));
     String line = reader.readLine();
     buffer.append(line).append('\n');
     // FindPath fp=new FindPath();
     InputStream resource =
         ClassLoader.getSystemClassLoader()
             .getResourceAsStream("net/beaconhillcott/moodlerest/EntityInjection.xml");
     BufferedReader entities = new BufferedReader(new InputStreamReader(/*fp.*/ resource));
     String entitiesLine = null;
     while ((entitiesLine = entities.readLine()) != null) {
       // System.out.println(entitiesLine);
       buffer.append(entitiesLine).append('\n');
     }
     entities.close();
     boolean error = false;
     while ((line = reader.readLine()) != null) {
       // System.out.println(line);
       if (error)
         throw new MoodleRestException(
             line.substring(line.indexOf('>') + 1, line.indexOf('<', line.indexOf('>') + 1)));
       if (line.contains("<EXCEPTION")) error = true;
       buffer.append(line).append('\n');
     }
     reader.close();
     if (debug) {
       System.out.println(buffer.toString());
     }
     XPath xpath = XPathFactory.newInstance().newXPath();
     // InputSource source=new InputSource(connection.getInputStream());
     InputSource source = new InputSource(new ByteArrayInputStream(buffer.toString().getBytes()));
     elements = (NodeList) xpath.evaluate("//VALUE", source, XPathConstants.NODESET);
     // Used for testing
     if (debug) {
       for (int i = 0; i < elements.getLength(); i++) {
         String parent =
             elements
                 .item(i)
                 .getParentNode()
                 .getParentNode()
                 .getParentNode()
                 .getParentNode()
                 .getNodeName();
         if (parent.equals("KEY"))
           parent =
               elements
                   .item(i)
                   .getParentNode()
                   .getParentNode()
                   .getParentNode()
                   .getParentNode()
                   .getAttributes()
                   .getNamedItem("name")
                   .getNodeValue();
         String content = elements.item(i).getTextContent();
         String nodeName =
             elements.item(i).getParentNode().getAttributes().getNamedItem("name").getNodeValue();
         System.out.println("parent=" + parent + " nodeName=" + nodeName + " content=" + content);
       }
     }
     connection.disconnect();
   } catch (XPathExpressionException ex) {
     Logger.getLogger(MoodleCallRestWebService.class.getName()).log(Level.SEVERE, null, ex);
   } catch (IOException ex) {
     Logger.getLogger(MoodleCallRestWebService.class.getName()).log(Level.SEVERE, null, ex);
   }
   return elements;
 }
Example #14
0
  public static void testReturnTypes() throws Exception {
    Builder b = new Builder();
    b.addClasspath(new File("bin"));
    b.setProperty("Export-Package", "test.metatype");
    b.setProperty("-metatype", "*");
    b.build();
    Resource r =
        b.getJar().getResource("OSGI-INF/metatype/test.metatype.MetatypeTest$TestReturnTypes.xml");
    assertEquals(0, b.getErrors().size());
    assertEquals(0, b.getWarnings().size());
    System.err.println(b.getJar().getResources().keySet());
    assertNotNull(r);
    IO.copy(r.openInputStream(), System.err);

    Document d = db.parse(r.openInputStream());
    assertEquals(
        "http://www.osgi.org/xmlns/metatype/v1.1.0", d.getDocumentElement().getNamespaceURI());
    // Primitives
    assertEquals("Boolean", xpath.evaluate("//OCD/AD[@id='rpBoolean']/@type", d));
    assertEquals("Byte", xpath.evaluate("//OCD/AD[@id='rpByte']/@type", d));
    assertEquals("Character", xpath.evaluate("//OCD/AD[@id='rpCharacter']/@type", d));
    assertEquals("Short", xpath.evaluate("//OCD/AD[@id='rpShort']/@type", d));
    assertEquals("Integer", xpath.evaluate("//OCD/AD[@id='rpInt']/@type", d));
    assertEquals("Long", xpath.evaluate("//OCD/AD[@id='rpLong']/@type", d));
    assertEquals("Float", xpath.evaluate("//OCD/AD[@id='rpFloat']/@type", d));
    assertEquals("Double", xpath.evaluate("//OCD/AD[@id='rpDouble']/@type", d));

    // Primitive Wrappers
    assertEquals("Boolean", xpath.evaluate("//OCD/AD[@id='rBoolean']/@type", d));
    assertEquals("Byte", xpath.evaluate("//OCD/AD[@id='rByte']/@type", d));
    assertEquals("Character", xpath.evaluate("//OCD/AD[@id='rCharacter']/@type", d));
    assertEquals("Short", xpath.evaluate("//OCD/AD[@id='rShort']/@type", d));
    assertEquals("Integer", xpath.evaluate("//OCD/AD[@id='rInt']/@type", d));
    assertEquals("Long", xpath.evaluate("//OCD/AD[@id='rLong']/@type", d));
    assertEquals("Float", xpath.evaluate("//OCD/AD[@id='rFloat']/@type", d));
    assertEquals("Double", xpath.evaluate("//OCD/AD[@id='rDouble']/@type", d));

    // Primitive Arrays
    assertEquals("Boolean", xpath.evaluate("//OCD/AD[@id='rpaBoolean']/@type", d));
    assertEquals("Byte", xpath.evaluate("//OCD/AD[@id='rpaByte']/@type", d));
    assertEquals("Character", xpath.evaluate("//OCD/AD[@id='rpaCharacter']/@type", d));
    assertEquals("Short", xpath.evaluate("//OCD/AD[@id='rpaShort']/@type", d));
    assertEquals("Integer", xpath.evaluate("//OCD/AD[@id='rpaInt']/@type", d));
    assertEquals("Long", xpath.evaluate("//OCD/AD[@id='rpaLong']/@type", d));
    assertEquals("Float", xpath.evaluate("//OCD/AD[@id='rpaFloat']/@type", d));
    assertEquals("Double", xpath.evaluate("//OCD/AD[@id='rpaDouble']/@type", d));

    assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='rpaBoolean']/@cardinality", d));
    assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='rpaByte']/@cardinality", d));
    assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='rpaCharacter']/@cardinality", d));
    assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='rpaShort']/@cardinality", d));
    assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='rpaInt']/@cardinality", d));
    assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='rpaLong']/@cardinality", d));
    assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='rpaFloat']/@cardinality", d));
    assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='rpaDouble']/@cardinality", d));

    // Wrapper + Object arrays
    assertEquals("Boolean", xpath.evaluate("//OCD/AD[@id='raBoolean']/@type", d));
    assertEquals("Byte", xpath.evaluate("//OCD/AD[@id='raByte']/@type", d));
    assertEquals("Character", xpath.evaluate("//OCD/AD[@id='raCharacter']/@type", d));
    assertEquals("Short", xpath.evaluate("//OCD/AD[@id='raShort']/@type", d));
    assertEquals("Integer", xpath.evaluate("//OCD/AD[@id='raInt']/@type", d));
    assertEquals("Long", xpath.evaluate("//OCD/AD[@id='raLong']/@type", d));
    assertEquals("Float", xpath.evaluate("//OCD/AD[@id='raFloat']/@type", d));
    assertEquals("Double", xpath.evaluate("//OCD/AD[@id='raDouble']/@type", d));
    assertEquals("String", xpath.evaluate("//OCD/AD[@id='raString']/@type", d));
    assertEquals("String", xpath.evaluate("//OCD/AD[@id='raURI']/@type", d));

    assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='raBoolean']/@cardinality", d));
    assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='raByte']/@cardinality", d));
    assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='raCharacter']/@cardinality", d));
    assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='raShort']/@cardinality", d));
    assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='raInt']/@cardinality", d));
    assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='raLong']/@cardinality", d));
    assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='raFloat']/@cardinality", d));
    assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='raDouble']/@cardinality", d));
    assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='raString']/@cardinality", d));
    assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='raURI']/@cardinality", d));

    // Wrapper + Object collections
    assertEquals("Boolean", xpath.evaluate("//OCD/AD[@id='rBooleans']/@type", d));
    assertEquals("Byte", xpath.evaluate("//OCD/AD[@id='rBytes']/@type", d));
    assertEquals("Character", xpath.evaluate("//OCD/AD[@id='rCharacter']/@type", d));
    assertEquals("Short", xpath.evaluate("//OCD/AD[@id='rShorts']/@type", d));
    assertEquals("Integer", xpath.evaluate("//OCD/AD[@id='rInts']/@type", d));
    assertEquals("Long", xpath.evaluate("//OCD/AD[@id='rLongs']/@type", d));
    assertEquals("Float", xpath.evaluate("//OCD/AD[@id='rFloats']/@type", d));
    assertEquals("Double", xpath.evaluate("//OCD/AD[@id='rDoubles']/@type", d));
    assertEquals("String", xpath.evaluate("//OCD/AD[@id='rStrings']/@type", d));
    assertEquals("String", xpath.evaluate("//OCD/AD[@id='rURIs']/@type", d));

    assertEquals("-2147483648", xpath.evaluate("//OCD/AD[@id='rBooleans']/@cardinality", d));
    assertEquals("-2147483648", xpath.evaluate("//OCD/AD[@id='rBytes']/@cardinality", d));
    assertEquals("-2147483648", xpath.evaluate("//OCD/AD[@id='rCharacters']/@cardinality", d));
    assertEquals("-2147483648", xpath.evaluate("//OCD/AD[@id='rShorts']/@cardinality", d));
    assertEquals("-2147483648", xpath.evaluate("//OCD/AD[@id='rInts']/@cardinality", d));
    assertEquals("-2147483648", xpath.evaluate("//OCD/AD[@id='rLongs']/@cardinality", d));
    assertEquals("-2147483648", xpath.evaluate("//OCD/AD[@id='rFloats']/@cardinality", d));
    assertEquals("-2147483648", xpath.evaluate("//OCD/AD[@id='rDoubles']/@cardinality", d));
    assertEquals("-2147483648", xpath.evaluate("//OCD/AD[@id='rStrings']/@cardinality", d));
    assertEquals("-2147483648", xpath.evaluate("//OCD/AD[@id='rURIs']/@cardinality", d));
  }