示例#1
0
 public JSONArray toJSONArray() throws JSONException {
   JSONArray json = new JSONArray();
   for (Iterator<ExportValue> i = values.values().iterator(); i.hasNext(); ) {
     json.put(i.next().toJSONObject());
   }
   return json;
 }
示例#2
0
 public JSONObject asJSONTreeAux(ConcurrentHashMap<DomainConcept, DomainConcept> written) {
   JSONObject jsonObj = new JSONObject();
   try {
     jsonObj.put("class", "ClassModel");
     jsonObj.put("id", id);
     if (written.contains(this)) {
       return jsonObj;
     }
     written.put(this, this);
     if (getHasArcs() != null) {
       JSONArray jsonHasArcs = new JSONArray();
       for (Arc row : getHasArcs()) {
         jsonHasArcs.put(row.asJSONTreeAux(written));
       }
       jsonObj.put("hasArcs", jsonHasArcs);
     }
     if (getHasPropertySet() != null) {
       jsonObj.put("hasPropertySet", getHasPropertySet().asJSONTreeAux(written));
     }
     jsonObj.put("id", getId());
     if (getHasDomainNodes() != null) {
       jsonObj.put("hasDomainNodes", getHasDomainNodes().asJSONTreeAux(written));
     }
     written.remove(this);
   } catch (Exception e1) {
     logWriter.error("Error in marshalling to JSON ", e1);
   }
   return jsonObj;
 }
示例#3
0
  private void getTrafficSpots() {
    controller.showProgressBar();
    String uploadWebsite =
        "http://" + controller.selectedCity.URL + "/php/trafficstatus.cache?dummy=ert43";
    String[] ArrayOfData = null;
    StreamConnection c = null;
    InputStream s = null;
    StringBuffer b = new StringBuffer();

    String url = uploadWebsite;
    System.out.print(url);
    try {
      c = (StreamConnection) Connector.open(url);
      s = c.openDataInputStream();
      int ch;
      int k = 0;
      while ((ch = s.read()) != -1) {
        System.out.print((char) ch);
        b.append((char) ch);
      }
      // System.out.println("b"+b);
      try {
        JSONObject ff1 = new JSONObject(b.toString());
        String data1 = ff1.getString("locations");
        JSONArray jsonArray1 = new JSONArray(data1);
        Vector TrafficStatus = new Vector();
        for (int i = 0; i < jsonArray1.length(); i++) {

          System.out.println(jsonArray1.getJSONArray(i).getString(3));
          double aDoubleLat = Double.parseDouble(jsonArray1.getJSONArray(i).getString(1));
          double aDoubleLon = Double.parseDouble(jsonArray1.getJSONArray(i).getString(2));
          System.out.println(aDoubleLat + " " + aDoubleLon);
          TrafficStatus.addElement(
              new LocationPointer(
                  jsonArray1.getJSONArray(i).getString(3),
                  (float) aDoubleLon,
                  (float) aDoubleLat,
                  1,
                  true));
        }
        controller.setCurrentScreen(controller.TrafficSpots(TrafficStatus));
      } catch (Exception E) {
        controller.setCurrentScreen(traf);
        new Thread() {
          public void run() {
            controller.showAlert("Error in network connection.", Alert.FOREVER, AlertType.INFO);
          }
        }.start();
      }

    } catch (Exception e) {

      controller.setCurrentScreen(traf);
      new Thread() {
        public void run() {
          controller.showAlert("Error in network connection.", Alert.FOREVER, AlertType.INFO);
        }
      }.start();
    }
  }
示例#4
0
 /** method to update data in caching layer object from JSON * */
 public boolean updateFromJSON(JSONObject jsonObj) {
   try {
     JSONArray hasArcsArray = jsonObj.optJSONArray("hasArcs");
     if (hasArcsArray != null) {
       ArrayList<Arc> aListOfHasArcs = new ArrayList<Arc>(hasArcsArray.length());
       for (int i = 0; i < hasArcsArray.length(); i++) {
         int id = hasArcsArray.optInt(i);
         if (ArcManager.getInstance().get(id) != null) {
           aListOfHasArcs.add(ArcManager.getInstance().get(id));
         }
       }
       setHasArcs(aListOfHasArcs);
     }
     if (!jsonObj.isNull("hasPropertySet")) {
       int hasPropertySetId = jsonObj.optInt("hasPropertySet");
       PropertySet value = PropertySetManager.getInstance().get(hasPropertySetId);
       if (value != null) {
         setHasPropertySet(value);
       }
     }
     if (!jsonObj.isNull("hasDomainNodes")) {
       int hasDomainNodesId = jsonObj.optInt("hasDomainNodes");
       NodeList value = NodeListManager.getInstance().get(hasDomainNodesId);
       if (value != null) {
         setHasDomainNodes(value);
       }
     }
   } catch (Exception e) {
     logWriter.error("Failure updating from JSON", e);
     return false;
   }
   return true;
 }
  private JSONArray enrichProperties(String operatorClass, JSONArray properties)
      throws JSONException {
    JSONArray result = new JSONArray();
    for (int i = 0; i < properties.length(); i++) {
      JSONObject propJ = properties.getJSONObject(i);
      String propName = WordUtils.capitalize(propJ.getString("name"));
      String getPrefix =
          (propJ.getString("type").equals("boolean")
                  || propJ.getString("type").equals("java.lang.Boolean"))
              ? "is"
              : "get";
      String setPrefix = "set";
      OperatorClassInfo oci =
          getOperatorClassWithGetterSetter(
              operatorClass, setPrefix + propName, getPrefix + propName);
      if (oci == null) {
        result.put(propJ);
        continue;
      }
      MethodInfo setterInfo = oci.setMethods.get(setPrefix + propName);
      MethodInfo getterInfo = oci.getMethods.get(getPrefix + propName);

      if ((getterInfo != null && getterInfo.omitFromUI)
          || (setterInfo != null && setterInfo.omitFromUI)) {
        continue;
      }
      if (setterInfo != null) {
        addTagsToProperties(setterInfo, propJ);
      } else if (getterInfo != null) {
        addTagsToProperties(getterInfo, propJ);
      }
      result.put(propJ);
    }
    return result;
  }
示例#6
0
 /**
  * Produce a JSONArray containing the names of the elements of this JSONObject.
  *
  * @return A JSONArray containing the key strings, or null if the JSONObject is empty.
  */
 public JSONArray names() {
   final JSONArray ja = new JSONArray();
   final Iterator keys = this.keys();
   while (keys.hasNext()) {
     ja.put(keys.next());
   }
   return ja.length() == 0 ? null : ja;
 }
示例#7
0
 /**
  * Produce a JSONArray containing the values of the members of this JSONObject.
  *
  * @param names A JSONArray containing a list of key strings. This determines the sequence of the
  *     values in the result.
  * @return A JSONArray of values.
  * @throws JSONException If any of the values are non-finite numbers.
  */
 public JSONArray toJSONArray(JSONArray names) throws JSONException {
   if ((names == null) || (names.length() == 0)) {
     return null;
   }
   final JSONArray ja = new JSONArray();
   for (int i = 0; i < names.length(); i += 1) {
     ja.put(this.opt(names.getString(i)));
   }
   return ja;
 }
示例#8
0
 public static boolean hasUpdate(int projectID, String version) {
   try {
     HttpURLConnection con =
         (HttpURLConnection)
             (new URL("https://api.curseforge.com/servermods/files?projectIds=" + projectID))
                 .openConnection();
     con.setRequestMethod("GET");
     con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; JVM)");
     con.setRequestProperty("Pragma", "no-cache");
     con.connect();
     JSONArray json = (JSONArray) JSONValue.parse(new InputStreamReader(con.getInputStream()));
     String[] cdigits =
         ((String) ((JSONObject) json.get(json.size() - 1)).get("name"))
             .toLowerCase()
             .split("\\.");
     String[] vdigits = version.toLowerCase().split("\\.");
     int max = vdigits.length > cdigits.length ? cdigits.length : vdigits.length;
     int a;
     int b;
     for (int i = 0; i < max; i++) {
       a = b = 0;
       try {
         a = Integer.parseInt(cdigits[i]);
       } catch (Throwable t1) {
         char[] c = cdigits[i].toCharArray();
         for (int j = 0; j < c.length; j++) {
           a += (c[j] << ((c.length - (j + 1)) * 8));
         }
       }
       try {
         b = Integer.parseInt(vdigits[i]);
       } catch (Throwable t1) {
         char[] c = vdigits[i].toCharArray();
         for (int j = 0; j < c.length; j++) {
           b += (c[j] << ((c.length - (j + 1)) * 8));
         }
       }
       if (a > b) {
         return true;
       } else if (a < b) {
         return false;
       } else if ((i == max - 1) && (cdigits.length > vdigits.length)) {
         return true;
       }
     }
   } catch (Throwable t) {
   }
   return false;
 }
示例#9
0
  /**
   * Write the contents of the JSONObject as JSON text to a writer. For compactness, no whitespace
   * is added.
   *
   * <p>Warning: This method assumes that the data structure is acyclical.
   *
   * @return The writer.
   * @throws JSONException
   */
  public Writer write(Writer writer) throws JSONException {
    try {
      boolean commanate = false;
      final Iterator keys = this.keys();
      writer.write('{');

      while (keys.hasNext()) {
        if (commanate) {
          writer.write(',');
        }
        final Object key = keys.next();
        writer.write(JSONObject.quote(key.toString()));
        writer.write(':');
        final Object value = this.map.get(key);
        if (value instanceof JSONObject) {
          ((JSONObject) value).write(writer);
        } else if (value instanceof JSONArray) {
          ((JSONArray) value).write(writer);
        } else {
          writer.write(JSONObject.valueToString(value));
        }
        commanate = true;
      }
      writer.write('}');
      return writer;
    } catch (final IOException exception) {
      throw new JSONException(exception);
    }
  }
示例#10
0
  /**
   * Write the contents of the JSONObject as JSON text to a writer. For compactness, no whitespace
   * is added.
   *
   * <p>Warning: This method assumes that the data structure is acyclical.
   *
   * @return The writer.
   * @throws JSONException
   */
  public Writer write(Writer writer) throws JSONException {
    try {
      boolean b = false;
      Iterator keys = keys();
      writer.write('{');

      while (keys.hasNext()) {
        if (b) {
          writer.write(',');
        }
        Object k = keys.next();
        writer.write(quote(k.toString()));
        writer.write(':');
        Object v = this.map.get(k);
        if (v instanceof JSONObject) {
          ((JSONObject) v).write(writer);
        } else if (v instanceof JSONArray) {
          ((JSONArray) v).write(writer);
        } else {
          writer.write(valueToString(v));
        }
        b = true;
      }
      writer.write('}');
      return writer;
    } catch (IOException e) {
      throw new JSONException(e);
    }
  }
示例#11
0
  //
  // ONE TIME ADD VIOLATIONS
  //
  //
  private static void oneTimeAddViolations() {

    String jsonString = "";

    try {
      jsonString = readFile("./json/violations.json", StandardCharsets.UTF_8);
    } catch (IOException e) {
      System.out.println(e);
    }

    try {
      JSONObject rootObject = new JSONObject(jsonString); // Parse the JSON to a JSONObject
      JSONArray rows = rootObject.getJSONArray("stuff"); // Get all JSONArray rows

      System.out.println("row lengths: " + rows.length());

      for (int j = 0; j < rows.length(); j++) { // Iterate each element in the elements array
        JSONObject element = rows.getJSONObject(j); // Get the element object

        int id = element.getInt("id");
        int citationNumber = element.getInt("citation_number");
        String violationNumber = element.getString("violation_number");
        String violationDescription = element.getString("violation_description");
        String warrantStatus = element.getString("warrant_status");
        String warrantNumber = " ";
        Boolean isWarrantNumberNull = element.isNull("warrant_number");
        if (!isWarrantNumberNull) warrantNumber = element.getString("warrant_number");
        String status = element.getString("status");
        String statusDate = element.getString("status_date");
        String fineAmount = " ";
        Boolean isFineAmountNull = element.isNull("fine_amount");
        if (!isFineAmountNull) fineAmount = element.getString("fine_amount");
        String courtCost = " ";
        Boolean isCourtCostNull = element.isNull("court_cost");
        if (!isCourtCostNull) courtCost = element.getString("court_cost");
        /*
        Map<String, AttributeValue> item = newViolationItem(citationNumber, violationNumber, violationDescription, warrantStatus, warrantNumber, status, statusDate, fineAmount, courtCost);
        PutItemRequest putItemRequest = new PutItemRequest("violations-table", item);
        PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
        */
      }
    } catch (JSONException e) {
      // JSON Parsing error
      e.printStackTrace();
    }
  }
  /**
   * Sends login command.
   *
   * @param capalistParam param from previous command.
   * @return is command successful.
   */
  @SuppressWarnings("unchecked")
  private boolean sendCapas(JSONArray capalistParam) {
    if (connection == null || capalistParam == null || capalistParam.isEmpty()) return false;

    JSONObject obj = new JSONObject();
    try {
      obj.put("class", "login_capas");
      obj.put("capaid", capalistParam.get(0));
      obj.put("lastconnwins", "false");
      obj.put("loginkind", "agent");
      obj.put("state", "");

      return send(obj);
    } catch (Exception e) {
      logger.error("Error login", e);
      return false;
    }
  }
 @POST
 @Path("/view")
 @Consumes(MediaType.APPLICATION_JSON)
 @Produces(MediaType.APPLICATION_JSON)
 public String viewAllNotes(String inputData) {
   JSONObject inputJSON = new JSONObject(inputData);
   if ((inputJSON.has("sessionID"))
       && UsersController.checkLogin(inputJSON.getString("sessionID"))) {
     hibernate.controllers.NotesController notesController =
         new hibernate.controllers.NotesController();
     List<Note> notes = notesController.readAllNotes();
     JSONArray results = new JSONArray();
     JSONObject jsonNote;
     for (Note note : notes) {
       jsonNote = getJSONNote(note);
       results.put(jsonNote);
     }
     return results.toString();
   } else return "Invalid session!";
 }
示例#14
0
 /**
  * Accumulate values under a key. It is similar to the put method except that if there is already
  * an object stored under the key then a JSONArray is stored under the key to hold all of the
  * accumulated values. If there is already a JSONArray, then the new value is appended to it. In
  * contrast, the put method replaces the previous value.
  *
  * <p>If only one value is accumulated that is not a JSONArray, then the result will be the same
  * as using put. But if multiple values are accumulated, then the result will be like append.
  *
  * @param key A key string.
  * @param value An object to be accumulated under the key.
  * @return this.
  * @throws JSONException If the value is an invalid number or if the key is null.
  */
 public JSONObject accumulate(String key, Object value) throws JSONException {
   JSONObject.testValidity(value);
   final Object object = this.opt(key);
   if (object == null) {
     this.put(key, value instanceof JSONArray ? new JSONArray().put(value) : value);
   } else if (object instanceof JSONArray) {
     ((JSONArray) object).put(value);
   } else {
     this.put(key, new JSONArray().put(object).put(value));
   }
   return this;
 }
示例#15
0
 /**
  * Accumulate values under a key. It is similar to the put method except that if there is already
  * an object stored under the key then a JSONArray is stored under the key to hold all of the
  * accumulated values. If there is already a JSONArray, then the new value is appended to it. In
  * contrast, the put method replaces the previous value.
  *
  * @param key A key string.
  * @param value An object to be accumulated under the key.
  * @return this.
  * @throws JSONException If the value is an invalid number or if the key is null.
  */
 public JSONObject accumulate(String key, Object value) throws JSONException {
   testValidity(value);
   Object o = opt(key);
   if (o == null) {
     put(key, value instanceof JSONArray ? new JSONArray().put(value) : value);
   } else if (o instanceof JSONArray) {
     ((JSONArray) o).put(value);
   } else {
     put(key, new JSONArray().put(o).put(value));
   }
   return this;
 }
示例#16
0
  @RequestMapping(
      value = "/getCityApi",
      method = {RequestMethod.GET, RequestMethod.POST})
  public String getCityApi(
      HttpServletRequest request,
      @RequestParam(value = "locationname") String locationname,
      ModelMap model) {

    Map<Object, Object> map = new HashMap<Object, Object>();
    JSONArray jSONArray = new JSONArray();
    try {
      String status = "active";
      List<City> cityList = cityService.getCityApi(locationname, status);
      if (cityList != null && cityList.size() > 0) {
        for (int i = 0; i < cityList.size(); i++) {
          City city = (City) cityList.get(i);
          String cityName = (String) city.getCity();
          String stateName = (String) city.getState();

          int ID = (Integer) (city.getId());
          JSONObject jSONObject = new JSONObject();

          jSONObject.put("id", ID);
          jSONObject.put("text", cityName);
          jSONArray.put(jSONObject);
        }
        utilities.setSuccessResponse(response, jSONArray.toString());
      } else {
        throw new ConstException(ConstException.ERR_CODE_NO_DATA, ConstException.ERR_MSG_NO_DATA);
      }
    } catch (Exception ex) {
      logger.error("getCity :" + ex.getMessage());
      utilities.setErrResponse(ex, response);
    }
    model.addAttribute("model", jSONArray.toString());
    return "home";
  }
示例#17
0
 /** method to marshall data from caching layer object to JSON * */
 public JSONObject asJSON() {
   JSONObject jsonObj = new JSONObject();
   try {
     jsonObj.put("class", "ClassModel");
     jsonObj.put("id", id);
     if (getHasArcs() != null) {
       JSONArray jsonHasArcs = new JSONArray();
       for (Arc row : getHasArcs()) {
         jsonHasArcs.put(row.getId());
       }
       jsonObj.put("hasArcs", jsonHasArcs);
     }
     if (getHasPropertySet() != null) {
       jsonObj.put("hasPropertySet", getHasPropertySet().getId());
     }
     jsonObj.put("id", getId());
     if (getHasDomainNodes() != null) {
       jsonObj.put("hasDomainNodes", getHasDomainNodes().getId());
     }
   } catch (Exception e1) {
     logWriter.error("Error in marshalling to JSON ", e1);
   }
   return jsonObj;
 }
  private void makeAttributeJSONArray(final SimpleFeatureType layerSft) throws JSONException {
    List<ConfiguredAttribute> cas = applicationLayer.getAttributes();
    // Sort the attributes, by featuretype and the featuretyp
    Collections.sort(
        cas,
        new Comparator<ConfiguredAttribute>() {
          @Override
          public int compare(ConfiguredAttribute o1, ConfiguredAttribute o2) {
            if (o1.getFeatureType() == null) {
              return -1;
            }
            if (o2.getFeatureType() == null) {
              return 1;
            }
            if (o1.getFeatureType().getId().equals(layerSft.getId())) {
              return -1;
            }
            if (o2.getFeatureType().getId().equals(layerSft.getId())) {
              return 1;
            }
            return o1.getFeatureType().getId().compareTo(o2.getFeatureType().getId());
          }
        });
    for (ConfiguredAttribute ca : cas) {
      JSONObject j = ca.toJSONObject();

      // Copy alias over from feature type
      SimpleFeatureType sft = ca.getFeatureType();
      if (sft == null) {
        sft = layerSft;
      }
      AttributeDescriptor ad = sft.getAttribute(ca.getAttributeName());
      j.put("alias", ad.getAlias());
      j.put("featureTypeAttribute", ad.toJSONObject());

      attributesJSON.put(j);
    }
  }
 static Writer writeValue(Writer writer, Object value) throws JSONException, IOException {
   if (value == null) {
     writer.write("null");
   } else if (value instanceof JSONObject) {
     ((JSONObject) value).write(writer);
   } else if (value instanceof JSONArray) {
     ((JSONArray) value).write(writer);
   } else if (value instanceof Map) {
     Map<?, ?> map = (Map<?, ?>) value;
     new JSONObject(map).write(writer);
   } else if (value instanceof Collection) {
     Collection<?> coll = (Collection<?>) value;
     new JSONArray(coll).write(writer);
   } else if (value.getClass().isArray()) {
     new JSONArray(value).write(writer);
   } else if (value instanceof Number) {
     writer.write(numberToString((Number) value));
   } else if (value instanceof Boolean) {
     writer.write(value.toString());
   } else {
     quote(value.toString(), writer);
   }
   return writer;
 }
示例#20
0
 /** Returns whether the user can access the given project */
 private boolean isAccessAllowed(String userName, WebProject webProject) {
   try {
     WebUser webUser = WebUser.fromUserId(userName);
     JSONArray workspacesJSON = webUser.getWorkspacesJSON();
     for (int i = 0; i < workspacesJSON.length(); i++) {
       JSONObject workspace = workspacesJSON.getJSONObject(i);
       String workspaceId = workspace.getString(ProtocolConstants.KEY_ID);
       WebWorkspace webWorkspace = WebWorkspace.fromId(workspaceId);
       JSONArray projectsJSON = webWorkspace.getProjectsJSON();
       for (int j = 0; j < projectsJSON.length(); j++) {
         JSONObject project = projectsJSON.getJSONObject(j);
         String projectId = project.getString(ProtocolConstants.KEY_ID);
         if (projectId.equals(webProject.getId())) return true;
       }
     }
   } catch (JSONException e) {
     // ignore, deny access
   }
   return false;
 }
示例#21
0
  /**
   * Looks for the project in all workspaces of the user and removes it when found.
   *
   * @see WorkspaceResourceHandler#handleRemoveProject(HttpServletRequest, HttpServletResponse,
   *     WebWorkspace)
   * @param userName the user name
   * @param webProject the project to remove
   * @return ServerStatus <code>OK</code> if the project has been found and successfully removed,
   *     <code>ERROR</code> if an error occurred or the project couldn't be found
   */
  public static ServerStatus removeProject(String userName, WebProject webProject) {
    try {
      WebUser webUser = WebUser.fromUserId(userName);
      JSONArray workspacesJSON = webUser.getWorkspacesJSON();
      for (int i = 0; i < workspacesJSON.length(); i++) {
        JSONObject workspace = workspacesJSON.getJSONObject(i);
        String workspaceId = workspace.getString(ProtocolConstants.KEY_ID);
        WebWorkspace webWorkspace = WebWorkspace.fromId(workspaceId);
        JSONArray projectsJSON = webWorkspace.getProjectsJSON();
        for (int j = 0; j < projectsJSON.length(); j++) {
          JSONObject project = projectsJSON.getJSONObject(j);
          String projectId = project.getString(ProtocolConstants.KEY_ID);
          if (projectId.equals(webProject.getId())) {
            // If found, remove project from workspace
            try {
              WorkspaceResourceHandler.removeProject(userName, webWorkspace, webProject);
            } catch (CoreException e) {
              // we are unable to write in the platform location!
              String msg =
                  NLS.bind(
                      "Server content location could not be written: {0}",
                      Activator.getDefault().getRootLocationURI());
              return new ServerStatus(
                  IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
            }

            return new ServerStatus(IStatus.OK, HttpServletResponse.SC_OK, null, null);
          }
        }
      }
    } catch (JSONException e) {
      // ignore, no project will be harmed
    }
    // FIXME: not sure about this one
    return new ServerStatus(IStatus.OK, HttpServletResponse.SC_OK, null, null);
  }
  public Resolution save() throws JSONException {
    // Only remove details which are editable and re-added layer if not empty,
    // retain other details possibly used in other parts than this page
    // See JSP for which keys are edited
    applicationLayer
        .getDetails()
        .keySet()
        .removeAll(
            Arrays.asList(
                "titleAlias",
                "legendImageUrl",
                "transparency",
                "influenceradius",
                "summary.title",
                "summary.image",
                "summary.description",
                "summary.link",
                "editfunction.title",
                "style",
                "summary.noHtmlEncode",
                "summary.nl2br"));
    for (Map.Entry<String, String> e : details.entrySet()) {
      if (e.getValue() != null) { // Don't insert null value ClobElement
        applicationLayer.getDetails().put(e.getKey(), new ClobElement(e.getValue()));
      }
    }

    applicationLayer.getReaders().clear();
    for (String groupName : groupsRead) {
      applicationLayer.getReaders().add(groupName);
    }

    applicationLayer.getWriters().clear();
    for (String groupName : groupsWrite) {
      applicationLayer.getWriters().add(groupName);
    }

    if (applicationLayer.getAttributes() != null && applicationLayer.getAttributes().size() > 0) {
      List<ConfiguredAttribute> appAttributes = applicationLayer.getAttributes();
      int i = 0;

      for (Iterator it = appAttributes.iterator(); it.hasNext(); ) {
        ConfiguredAttribute appAttribute = (ConfiguredAttribute) it.next();
        // save visible
        if (selectedAttributes.contains(appAttribute.getFullName())) {
          appAttribute.setVisible(true);
        } else {
          appAttribute.setVisible(false);
        }

        // save editable
        if (attributesJSON.length() > i) {
          JSONObject attribute = attributesJSON.getJSONObject(i);

          if (attribute.has("editable")) {
            appAttribute.setEditable(new Boolean(attribute.get("editable").toString()));
          }
          if (attribute.has("editalias")) {
            appAttribute.setEditAlias(attribute.get("editalias").toString());
          }
          if (attribute.has("editvalues")) {
            appAttribute.setEditValues(attribute.get("editvalues").toString());
          }
          if (attribute.has("editHeight")) {
            appAttribute.setEditHeight(attribute.get("editHeight").toString());
          }

          // save selectable
          if (attribute.has("selectable")) {
            appAttribute.setSelectable(new Boolean(attribute.get("selectable").toString()));
          }
          if (attribute.has("filterable")) {
            appAttribute.setFilterable(new Boolean(attribute.get("filterable").toString()));
          }

          if (attribute.has("defaultValue")) {
            appAttribute.setDefaultValue(attribute.get("defaultValue").toString());
          }
        }
        i++;
      }
    }

    Stripersist.getEntityManager().persist(applicationLayer);
    application.authorizationsModified();

    displayName = applicationLayer.getDisplayName();

    Stripersist.getEntityManager().getTransaction().commit();

    getContext().getMessages().add(new SimpleMessage("De kaartlaag is opgeslagen"));
    return edit();
  }
  @Before
  public void synchronizeFeatureTypeAndLoadInfo() throws JSONException {

    Layer layer = applicationLayer.getService().getSingleLayer(applicationLayer.getLayerName());
    if (layer == null) {
      getContext()
          .getValidationErrors()
          .addGlobalError(
              new SimpleError(
                  "Laag niet gevonden bij originele service - verwijder deze laag uit niveau"));
      return;
    }

    for (StyleLibrary sld : layer.getService().getStyleLibraries()) {
      Map style = new HashMap();
      JSONObject styleTitleJson = new JSONObject();

      style.put("id", "sld:" + sld.getId());
      style.put(
          "title", "SLD stijl: " + sld.getTitle() + (sld.isDefaultStyle() ? " (standaard)" : ""));

      // Find stuff for layerName
      if (sld.getNamedLayerUserStylesJson() != null) {
        JSONObject sldNamedLayerJson = new JSONObject(sld.getNamedLayerUserStylesJson());
        if (sldNamedLayerJson.has(layer.getName())) {
          JSONObject namedLayer = sldNamedLayerJson.getJSONObject(layer.getName());
          if (namedLayer.has("title")) {
            styleTitleJson.put("namedLayerTitle", namedLayer.get("title"));
          }
          JSONArray userStyles = namedLayer.getJSONArray("styles");
          if (userStyles.length() > 0) {
            JSONObject userStyle = userStyles.getJSONObject(0);
            if (userStyle.has("title")) {
              styleTitleJson.put("styleTitle", userStyle.get("title"));
            }
          }
        }
      }
      styles.add(style);
      stylesTitleJson.put((String) style.get("id"), styleTitleJson);
    }
    if (layer.getDetails().containsKey(Layer.DETAIL_WMS_STYLES)) {
      JSONArray wmsStyles =
          new JSONArray(layer.getDetails().get(Layer.DETAIL_WMS_STYLES).getValue());
      for (int i = 0; i < wmsStyles.length(); i++) {
        JSONObject wmsStyle = wmsStyles.getJSONObject(i);
        Map style = new HashMap();
        style.put("id", "wms:" + wmsStyle.getString("name"));
        style.put(
            "title",
            "WMS server stijl: "
                + wmsStyle.getString("name")
                + " ("
                + wmsStyle.getString("title")
                + ")");
        JSONObject styleTitleJson = new JSONObject();
        styleTitleJson.put("styleTitle", wmsStyle.getString("title"));
        styles.add(style);
        stylesTitleJson.put((String) style.get("id"), styleTitleJson);
      }
    }
    if (!styles.isEmpty()) {
      List<Map> temp = new ArrayList();
      Map s = new HashMap();
      s.put("id", "registry_default");
      s.put("title", "In gegevensregister als standaard ingestelde SLD");
      temp.add(s);
      s = new HashMap();
      s.put("id", "none");
      s.put("title", "Geen: standaard stijl van WMS service zelf");
      temp.add(s);
      temp.addAll(styles);
      styles = temp;
    }

    // Synchronize configured attributes with layer feature type

    if (layer.getFeatureType() == null || layer.getFeatureType().getAttributes().isEmpty()) {
      applicationLayer.getAttributes().clear();
    } else {
      List<String> attributesToRetain = new ArrayList();

      SimpleFeatureType sft = layer.getFeatureType();
      editable = sft.isWriteable();
      // Rebuild ApplicationLayer.attributes according to Layer FeatureType
      // New attributes are added at the end of the list; the original
      // order is only used when the Application.attributes list is empty
      // So a feature for reordering attributes per applicationLayer is
      // possible.
      // New Attributes from a join or related featureType are added at the
      // end of the list.
      attributesToRetain = rebuildAttributes(sft);

      // JSON info about attributed required for editing
      makeAttributeJSONArray(layer.getFeatureType());
      // Remove ConfiguredAttributes which are no longer present
      List<ConfiguredAttribute> attributesToRemove = new ArrayList();
      for (ConfiguredAttribute ca : applicationLayer.getAttributes()) {
        if (ca.getFeatureType() == null) {
          ca.setFeatureType(layer.getFeatureType());
        }
        if (!attributesToRetain.contains(ca.getFullName())) {
          // Do not modify list we are iterating over
          attributesToRemove.add(ca);
          if (!"save".equals(getContext().getEventName())) {
            getContext()
                .getMessages()
                .add(
                    new SimpleMessage(
                        "Attribuut \"{0}\" niet meer beschikbaar in attribuutbron: wordt verwijderd na opslaan",
                        ca.getAttributeName()));
          }
        }
      }
      for (ConfiguredAttribute ca : attributesToRemove) {
        applicationLayer.getAttributes().remove(ca);
        Stripersist.getEntityManager().remove(ca);
      }
    }
  }
示例#24
0
 private boolean handleGet(
     HttpServletRequest request, HttpServletResponse response, String pathString)
     throws IOException, JSONException, ServletException, URISyntaxException, CoreException {
   IPath path = pathString == null ? Path.EMPTY : new Path(pathString);
   URI baseLocation = getURI(request);
   String user = request.getRemoteUser();
   // expected path format is 'workspace/{workspaceId}' or
   // 'file/{workspaceId}/{projectName}/{path}]'
   if ("workspace".equals(path.segment(0)) && path.segmentCount() == 2) { // $NON-NLS-1$
     // all clones in the workspace
     if (WebWorkspace.exists(path.segment(1))) {
       WebWorkspace workspace = WebWorkspace.fromId(path.segment(1));
       JSONObject result = new JSONObject();
       JSONArray children = new JSONArray();
       for (WebProject webProject : workspace.getProjects()) {
         // this is the location of the project metadata
         if (isAccessAllowed(user, webProject)) {
           IPath projectPath = GitUtils.pathFromProject(workspace, webProject);
           Map<IPath, File> gitDirs = GitUtils.getGitDirs(projectPath, Traverse.GO_DOWN);
           for (Map.Entry<IPath, File> entry : gitDirs.entrySet()) {
             children.put(new Clone().toJSON(entry, baseLocation));
           }
         }
       }
       result.put(ProtocolConstants.KEY_TYPE, Clone.TYPE);
       result.put(ProtocolConstants.KEY_CHILDREN, children);
       OrionServlet.writeJSONResponse(request, response, result);
       return true;
     }
     String msg = NLS.bind("Nothing found for the given ID: {0}", path);
     return statusHandler.handleRequest(
         request,
         response,
         new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
   } else if ("file".equals(path.segment(0)) && path.segmentCount() > 1) { // $NON-NLS-1$
     // clones under given path
     WebProject webProject = GitUtils.projectFromPath(path);
     IPath projectRelativePath = path.removeFirstSegments(3);
     if (webProject != null
         && isAccessAllowed(user, webProject)
         && webProject.getProjectStore().getFileStore(projectRelativePath).fetchInfo().exists()) {
       Map<IPath, File> gitDirs = GitUtils.getGitDirs(path, Traverse.GO_DOWN);
       JSONObject result = new JSONObject();
       JSONArray children = new JSONArray();
       for (Map.Entry<IPath, File> entry : gitDirs.entrySet()) {
         children.put(new Clone().toJSON(entry, baseLocation));
       }
       result.put(ProtocolConstants.KEY_TYPE, Clone.TYPE);
       result.put(ProtocolConstants.KEY_CHILDREN, children);
       OrionServlet.writeJSONResponse(request, response, result);
       return true;
     }
     String msg = NLS.bind("Nothing found for the given ID: {0}", path);
     return statusHandler.handleRequest(
         request,
         response,
         new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
   }
   // else the request is malformed
   String msg = NLS.bind("Invalid clone request: {0}", path);
   return statusHandler.handleRequest(
       request,
       response,
       new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
 }
  /**
   * Enrich portClassHier with class/interface names that map to a list of parent
   * classes/interfaces. For any class encountered, find its parents too.<br>
   * Also find the port types which have assignable schema classes.
   *
   * @param oper Operator to work on
   * @param portClassHierarchy In-Out param that contains a mapping of class/interface to its
   *     parents
   * @param portTypesWithSchemaClasses Json that will contain all the ports which have any schema
   *     classes.
   */
  public void buildAdditionalPortInfo(
      JSONObject oper, JSONObject portClassHierarchy, JSONObject portTypesWithSchemaClasses) {
    try {
      JSONArray ports = oper.getJSONArray(OperatorDiscoverer.PORT_TYPE_INFO_KEY);
      for (int i = 0; i < ports.length(); i++) {
        JSONObject port = ports.getJSONObject(i);

        String portType = port.optString("type");
        if (portType == null) {
          // skipping if port type is null
          continue;
        }

        if (typeGraph.size() == 0) {
          buildTypeGraph();
        }

        try {
          // building port class hierarchy
          LinkedList<String> queue = Lists.newLinkedList();
          queue.add(portType);
          while (!queue.isEmpty()) {
            String currentType = queue.remove();
            if (portClassHierarchy.has(currentType)) {
              // already present in the json so we skip.
              continue;
            }
            List<String> immediateParents = typeGraph.getParents(currentType);
            if (immediateParents == null) {
              portClassHierarchy.put(currentType, Lists.<String>newArrayList());
              continue;
            }
            portClassHierarchy.put(currentType, immediateParents);
            queue.addAll(immediateParents);
          }
        } catch (JSONException e) {
          LOG.warn("building port type hierarchy {}", portType, e);
        }

        // finding port types with schema classes
        if (portTypesWithSchemaClasses.has(portType)) {
          // already present in the json so skipping
          continue;
        }
        if (portType.equals("byte")
            || portType.equals("short")
            || portType.equals("char")
            || portType.equals("int")
            || portType.equals("long")
            || portType.equals("float")
            || portType.equals("double")
            || portType.equals("java.lang.String")
            || portType.equals("java.lang.Object")) {
          // ignoring primitives, strings and object types as this information is needed only for
          // complex types.
          continue;
        }
        if (port.has("typeArgs")) {
          // ignoring any type with generics
          continue;
        }
        boolean hasSchemaClasses = false;
        List<String> instantiableDescendants = typeGraph.getInstantiableDescendants(portType);
        if (instantiableDescendants != null) {
          for (String descendant : instantiableDescendants) {
            try {
              if (typeGraph.isInstantiableBean(descendant)) {
                hasSchemaClasses = true;
                break;
              }
            } catch (JSONException ex) {
              LOG.warn("checking descendant is instantiable {}", descendant);
            }
          }
        }
        portTypesWithSchemaClasses.put(portType, hasSchemaClasses);
      }
    } catch (JSONException e) {
      // should not reach this
      LOG.error("JSON Exception {}", e);
      throw new RuntimeException(e);
    }
  }
示例#26
0
  private boolean handlePut(
      HttpServletRequest request, HttpServletResponse response, String pathString)
      throws GitAPIException, CoreException, IOException, JSONException, ServletException {
    IPath path = pathString == null ? Path.EMPTY : new Path(pathString);
    if (path.segment(0).equals("file") && path.segmentCount() > 1) { // $NON-NLS-1$

      // make sure a clone is addressed
      WebProject webProject = GitUtils.projectFromPath(path);
      if (isAccessAllowed(request.getRemoteUser(), webProject)) {
        Map<IPath, File> gitDirs = GitUtils.getGitDirs(path, Traverse.CURRENT);
        if (gitDirs.isEmpty()) {
          String msg = NLS.bind("Request path is not a git repository: {0}", path);
          return statusHandler.handleRequest(
              request,
              response,
              new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
        }
        File gitDir = gitDirs.values().iterator().next();

        // make sure required fields are set
        JSONObject toCheckout = OrionServlet.readJSONRequest(request);
        JSONArray paths = toCheckout.optJSONArray(ProtocolConstants.KEY_PATH);
        String branch = toCheckout.optString(GitConstants.KEY_BRANCH_NAME, null);
        String tag = toCheckout.optString(GitConstants.KEY_TAG_NAME, null);
        boolean removeUntracked = toCheckout.optBoolean(GitConstants.KEY_REMOVE_UNTRACKED, false);
        if ((paths == null || paths.length() == 0) && branch == null && tag == null) {
          String msg =
              NLS.bind(
                  "Either '{0}' or '{1}' or '{2}' should be provided, got: {3}",
                  new Object[] {
                    ProtocolConstants.KEY_PATH,
                    GitConstants.KEY_BRANCH_NAME,
                    GitConstants.KEY_TAG_NAME,
                    toCheckout
                  });
          return statusHandler.handleRequest(
              request,
              response,
              new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
        }

        Git git = new Git(new FileRepository(gitDir));
        if (paths != null) {
          Set<String> toRemove = new HashSet<String>();
          CheckoutCommand checkout = git.checkout();
          for (int i = 0; i < paths.length(); i++) {
            String p = paths.getString(i);
            if (removeUntracked && !isInIndex(git.getRepository(), p)) toRemove.add(p);
            checkout.addPath(p);
          }
          checkout.call();
          for (String p : toRemove) {
            File f = new File(git.getRepository().getWorkTree(), p);
            f.delete();
          }
          return true;
        } else if (tag != null && branch != null) {
          CheckoutCommand co = git.checkout();
          try {
            co.setName(branch).setStartPoint(tag).setCreateBranch(true).call();
            return true;
          } catch (RefNotFoundException e) {
            String msg = NLS.bind("Tag not found: {0}", tag);
            return statusHandler.handleRequest(
                request,
                response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, e));
          } catch (GitAPIException e) {
            if (org.eclipse.jgit.api.CheckoutResult.Status.CONFLICTS.equals(
                co.getResult().getStatus())) {
              return statusHandler.handleRequest(
                  request,
                  response,
                  new ServerStatus(
                      IStatus.ERROR, HttpServletResponse.SC_CONFLICT, "Checkout aborted.", e));
            }
            // TODO: handle other exceptions
          }
        } else if (branch != null) {

          if (!isLocalBranch(git, branch)) {
            String msg = NLS.bind("{0} is not a branch.", branch);
            return statusHandler.handleRequest(
                request,
                response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
          }

          CheckoutCommand co = git.checkout();
          try {
            co.setName(Constants.R_HEADS + branch).call();
            return true;
          } catch (CheckoutConflictException e) {
            return statusHandler.handleRequest(
                request,
                response,
                new ServerStatus(
                    IStatus.ERROR, HttpServletResponse.SC_CONFLICT, "Checkout aborted.", e));
          } catch (RefNotFoundException e) {
            String msg = NLS.bind("Branch name not found: {0}", branch);
            return statusHandler.handleRequest(
                request,
                response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, e));
          } // TODO: handle other exceptions
        }
      } else {
        String msg = NLS.bind("Nothing found for the given ID: {0}", path);
        return statusHandler.handleRequest(
            request,
            response,
            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
      }
    }
    String msg = NLS.bind("Invalid checkout request {0}", pathString);
    return statusHandler.handleRequest(
        request,
        response,
        new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
  }
示例#27
0
  public double getTimeSpentByTask(String taskNo) throws Exception {

    double timeSpent = 0.0D;

    String apiURL = "https://rally1.rallydev.com/slm/webservice/1.34/adhoc";

    String requestJSON =
        "{"
            + "\"task\" : \"/task?query=(FormattedID%20=%20"
            + taskNo
            + ")&fetch=true\","
            + "\"timeentryitem\":\"/timeentryitem?query=(Task.FormattedID%20=%20"
            + taskNo
            + ")&fetch=Values\","
            + "\"timespent\":\"${timeentryitem.Values.Hours}\""
            + "}";

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

    String responseJSON = postRallyXML(apiURL, requestJSON);

    // log.info("responseJSON="+responseJSON);

    // Map jsonMap=JsonUtil.jsonToMap(responseJSON);
    JSONParser parser = new JSONParser();
    Map jsonMap = (Map) parser.parse(responseJSON);

    /*
    //log.info("jsonMap="+jsonMap);

    String taskObjId="";
    String taskFormattedId="";
    String taskName="";
    String estimate="";
    String toDo="";
    String taskState="";
    String taskOwner="";
    String userstoryFormattedId="";

    //Get task info
    JSONObject taskMap=(JSONObject)jsonMap.get("task");
    JSONArray taskArray=(JSONArray)taskMap.get("Results");
    if(taskArray!=null && taskArray.size()>0) {
    	JSONObject taskInfo=(JSONObject)taskArray.get(0);
    	//log.info("taskMap="+taskMap);
    	//log.info("taskInfo="+taskInfo);

    	taskObjId=(taskInfo.get("ObjectID")).toString();
    	taskFormattedId=(taskInfo.get("FormattedID")).toString();
    	taskState=(taskInfo.get("State")).toString();

    	Object taskNameObj=taskInfo.get("Name");
    	taskName=taskNameObj==null ? "" : taskNameObj.toString();

    	Object estimateObject=taskInfo.get("Estimate");
    	estimate=estimateObject==null ? "" : estimateObject.toString();

    	Object toDoObject=taskInfo.get("ToDo");
    	toDo=toDoObject==null ? "" : toDoObject.toString();

    	JSONObject ownerMap=(JSONObject)taskInfo.get("Owner");
    	log.info("ownerMap="+ownerMap);
    	if(ownerMap!=null) {
    		taskOwner=(String)ownerMap.get("_refObjectName");
    		if(taskOwner==null) {
    			taskOwner="";
    		}
    	}
    }

    //Get user story info
    JSONObject userstoryMap=(JSONObject)jsonMap.get("userstory");
    JSONArray userstoryArray=(JSONArray)userstoryMap.get("Results");
    if(userstoryArray!=null && userstoryArray.size()>0) {
    	JSONObject userstoryInfo=(JSONObject)userstoryArray.get(0);

    	userstoryFormattedId=(userstoryInfo.get("FormattedID")).toString();
    	log.info("userstoryFormattedId="+userstoryFormattedId);
    }
    */

    // Calculate timeSpent
    JSONArray timeSpentList = (JSONArray) jsonMap.get("timespent");
    log.info("timeSpentList=" + timeSpentList);

    // double timeSpent=0.0;
    for (int i = 0; i < timeSpentList.size(); i++) {
      String timeSpentString = (String) timeSpentList.get(i);

      if (timeSpentString != null) {
        timeSpent += Double.parseDouble(timeSpentString);
      }
    }

    return timeSpent;
  }
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  @SuppressWarnings("unchecked")
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("application/json");
    response.setHeader("Cache-Control", "nocache");
    response.setCharacterEncoding("utf-8");
    PrintWriter out = response.getWriter();
    StringWriter result = new StringWriter();

    // get received JSON data from request
    BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
    String postData = "";
    if (br != null) {
      postData = br.readLine();
    }

    try {
      JSONObject json = (JSONObject) new JSONParser().parse(postData);
      JSONObject resultObj = new JSONObject();
      JSONArray list = new JSONArray();
      List<Tracking> trackingList = new ArrayList<Tracking>();

      // get the website list
      if (json.get("type").equals("websiteslist")) {
        trackingList = trackingDao.websiteList(pool);
        for (Tracking item : trackingList) {
          list.add(item.getWebsite());
        }
      }
      // render report
      else if (json.get("type").equals("submit")) {
        if (json.get("criteria").equals("date")) {
          // render repoty by date
          trackingList = trackingDao.getListByDate(pool, json.get("date").toString());
        } else if (json.get("criteria").equals("daterange")) {
          // render repoty by date range
          trackingList =
              trackingDao.getListByDateRange(
                  pool, json.get("fromdate").toString(), json.get("todate").toString());
        } else if (json.get("criteria").equals("website")) {
          // render repoty by website
          String website = (json.get("website") == null ? "" : json.get("website").toString());
          trackingList = trackingDao.getListByWebsite(pool, website);
        }

        for (Tracking item : trackingList) {
          JSONObject trackingObj = new JSONObject();
          trackingObj.put("date", item.getDate());
          trackingObj.put("website", item.getWebsite());
          trackingObj.put("visit", item.getVisit());
          list.add(trackingObj);
        }
      }
      resultObj.put("result", list);
      resultObj.writeJSONString(result);
      // finally output the json string
      out.print(result.toString());
    } catch (ParseException | SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
示例#29
0
  public Map getTaskMapBatch(String objectId) throws Exception {

    Map map = new HashMap();

    String apiURL = "https://rally1.rallydev.com/slm/webservice/1.34/adhoc";

    String requestJSON =
        "{"
            + "\"task\" : \"/task?query=(ObjectID%20=%20"
            + objectId
            + ")&fetch=true\","
            + "\"userstory\" : \"/hierarchicalrequirement?query=(ObjectID%20=%20${task.WorkProduct.ObjectID})&fetch=FormattedID\","
            + "\"timeentryitem\":\"/timeentryitem?query=(Task.ObjectID%20=%20"
            + objectId
            + ")&fetch=Values\","
            + "\"timespent\":\"${timeentryitem.Values.Hours}\""
            + "}";

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

    String responseJSON = postRallyXML(apiURL, requestJSON);

    // log.info("responseJSON="+responseJSON);

    // Map jsonMap=JsonUtil.jsonToMap(responseJSON);
    JSONParser parser = new JSONParser();
    Map jsonMap = (Map) parser.parse(responseJSON);

    // log.info("jsonMap="+jsonMap);

    String taskObjId = "";
    String taskFormattedId = "";
    String taskName = "";
    String estimate = "";
    String toDo = "";
    String taskState = "";
    String taskOwner = "";
    String userstoryFormattedId = "";

    // Get task info
    JSONObject taskMap = (JSONObject) jsonMap.get("task");
    JSONArray taskArray = (JSONArray) taskMap.get("Results");
    if (taskArray != null && taskArray.size() > 0) {
      JSONObject taskInfo = (JSONObject) taskArray.get(0);
      // log.info("taskMap="+taskMap);
      // log.info("taskInfo="+taskInfo);

      taskObjId = (taskInfo.get("ObjectID")).toString();
      taskFormattedId = (taskInfo.get("FormattedID")).toString();
      taskState = (taskInfo.get("State")).toString();

      Object taskNameObj = taskInfo.get("Name");
      taskName = taskNameObj == null ? "" : taskNameObj.toString();

      Object estimateObject = taskInfo.get("Estimate");
      estimate = estimateObject == null ? "" : estimateObject.toString();

      Object toDoObject = taskInfo.get("ToDo");
      toDo = toDoObject == null ? "" : toDoObject.toString();

      JSONObject ownerMap = (JSONObject) taskInfo.get("Owner");
      log.info("ownerMap=" + ownerMap);
      if (ownerMap != null) {
        taskOwner = (String) ownerMap.get("_refObjectName");
        if (taskOwner == null) {
          taskOwner = "";
        }
      }
    }

    // Get user story info
    JSONObject userstoryMap = (JSONObject) jsonMap.get("userstory");
    JSONArray userstoryArray = (JSONArray) userstoryMap.get("Results");
    if (userstoryArray != null && userstoryArray.size() > 0) {
      JSONObject userstoryInfo = (JSONObject) userstoryArray.get(0);

      userstoryFormattedId = (userstoryInfo.get("FormattedID")).toString();
      log.info("userstoryFormattedId=" + userstoryFormattedId);
    }

    // Calculate timeSpent
    JSONArray timeSpentList = (JSONArray) jsonMap.get("timespent");
    log.info("timeSpentList=" + timeSpentList);

    double timeSpent = 0.0;
    for (int i = 0; i < timeSpentList.size(); i++) {
      String timeSpentString = (String) timeSpentList.get(i);

      if (timeSpentString != null) {
        timeSpent += Double.parseDouble(timeSpentString);
      }
    }

    map.put("type", "task");
    map.put("formattedId", taskFormattedId);
    map.put("usId", userstoryFormattedId);
    map.put("name", taskName);
    map.put("taskStatus", taskState);
    map.put("owner", taskOwner);
    map.put("taskEstimateTotal", estimate);
    map.put("taskRemainingTotal", toDo);
    map.put("taskTimeSpentTotal", "" + timeSpent);

    return map;
  }
示例#30
0
  public Map getUserStoryTaskMap(String timeEntryItemRef) throws Exception {
    Map taskMap = new HashMap();

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

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

    String apiURL = "https://rally1.rallydev.com/slm/webservice/1.34/adhoc";

    String requestJSON =
        "{"
            + "\"timeentryitem\" : \"/timeentryitem?query=(ObjectID%20=%20"
            + objectId
            + ")&fetch=true\","
            + "\"task\" : \"/task?query=(ObjectID%20=%20${timeentryitem.Task.ObjectID})&fetch=true\","
            + "\"userstory\" : \"/hierarchicalrequirement?query=(ObjectID%20=%20${task.WorkProduct.ObjectID})&fetch=true\","
            + "\"defect\" : \"/defect?query=(ObjectID%20=%20${task.WorkProduct.ObjectID})&fetch=true\""
            + "}";

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

    String responseJSON = postRallyXML(apiURL, requestJSON);

    // Bypass"%;" to avoid exception
    responseJSON = responseJSON.replace("%;", ";");
    responseJSON = responseJSON.replace("%", "");

    Map jsonMap = JsonUtil.jsonToMap(responseJSON);

    String usRef = "";
    String usName = "";
    String usFormattedId = "";
    String usPlanEstimate = "";
    String usTaskEstimateTotal = "";
    String usTaskRemainingTotal = "";
    String usState = "";
    String usOwner = "";

    Map usMap = new HashMap();

    // Get user story info
    JSONObject userstoryMap = (JSONObject) jsonMap.get("userstory");
    JSONArray userstoryArray = (JSONArray) userstoryMap.get("Results");
    if (userstoryArray == null || userstoryArray.size() == 0) {
      userstoryMap = (JSONObject) jsonMap.get("defect");
      userstoryArray = (JSONArray) userstoryMap.get("Results");
    }

    if (userstoryArray != null && userstoryArray.size() > 0) {
      JSONObject userstoryInfo = (JSONObject) userstoryArray.get(0);
      // log.info("userstoryInfo="+userstoryInfo);
      usRef = (userstoryInfo.get("_ref")).toString();
      usFormattedId = (userstoryInfo.get("FormattedID")).toString();
      usName = (userstoryInfo.get("Name")).toString();
      usState = (userstoryInfo.get("ScheduleState")).toString();

      if (userstoryInfo.get("PlanEstimate") != null)
        usPlanEstimate = (userstoryInfo.get("PlanEstimate")).toString();

      if (userstoryInfo.get("TaskEstimateTotal") != null)
        usTaskEstimateTotal = (userstoryInfo.get("TaskEstimateTotal")).toString();

      if (userstoryInfo.get("TaskRemainingTotal") != null)
        usTaskRemainingTotal = (userstoryInfo.get("TaskRemainingTotal")).toString();

      JSONObject ownerMap = (JSONObject) userstoryInfo.get("Owner");
      if (ownerMap != null) {
        usOwner = (String) ownerMap.get("_refObjectName");
        if (usOwner == null) {
          usOwner = "";
        }
      }
    }

    Map usDetailMap = new HashMap();

    usDetailMap.put("usFormattedId", usFormattedId);
    usDetailMap.put("usName", usName);
    usDetailMap.put("usPlanEstimate", usPlanEstimate);
    usDetailMap.put("usTaskEstimateTotal", usTaskEstimateTotal);
    usDetailMap.put("usTaskRemainingTotal", usTaskRemainingTotal);
    usDetailMap.put("usOwner", usOwner);
    usDetailMap.put("usState", usState);

    usMap.put(usRef, usDetailMap);

    // log.info("usMap="+usMap);

    String taskObjId = "";
    String taskFormattedId = "";
    String taskName = "";
    String estimate = "";
    String toDo = "";
    String taskState = "";
    String taskOwner = "";
    String projectName = "";
    String iterationName = "";
    String workProductRef = "";

    List taskList = new ArrayList();

    // Get task info
    JSONObject taskJsonMap = (JSONObject) jsonMap.get("task");
    JSONArray taskArray = (JSONArray) taskJsonMap.get("Results");
    if (taskArray != null && taskArray.size() > 0) {

      for (int i = 0; i < taskArray.size(); i++) {

        JSONObject taskInfo = (JSONObject) taskArray.get(0);
        // log.info("taskMap="+taskMap);
        // log.info("taskInfo="+taskInfo);

        taskObjId = (taskInfo.get("ObjectID")).toString();
        taskFormattedId = (taskInfo.get("FormattedID")).toString();
        taskState = (taskInfo.get("State")).toString();

        Object taskNameObj = taskInfo.get("Name");
        taskName = taskNameObj == null ? "" : taskNameObj.toString();

        Object estimateObject = taskInfo.get("Estimate");
        estimate = estimateObject == null ? "" : estimateObject.toString();

        Object toDoObject = taskInfo.get("ToDo");
        toDo = toDoObject == null ? "" : toDoObject.toString();

        JSONObject ownerMap = (JSONObject) taskInfo.get("Owner");
        // log.info("ownerMap="+ownerMap);
        if (ownerMap != null) {
          taskOwner = (String) ownerMap.get("_refObjectName");
          if (taskOwner == null) {
            taskOwner = "";
          }
        }

        JSONObject workProductMap = (JSONObject) taskInfo.get("WorkProduct");
        // log.info("workProductMap="+workProductMap);
        if (workProductMap != null) {
          workProductRef = (String) workProductMap.get("_ref");
          if (workProductRef == null) {
            workProductRef = "";
          }
        }

        JSONObject projectMap = (JSONObject) taskInfo.get("Project");
        // log.info("projectMap="+projectMap);
        if (projectMap != null) {
          projectName = (String) projectMap.get("_refObjectName");
          if (projectName == null) {
            projectName = "";
          }
        }

        JSONObject iterationMap = (JSONObject) taskInfo.get("Iteration");
        // log.info("iterationMap="+iterationMap);
        if (iterationMap != null) {
          iterationName = (String) iterationMap.get("_refObjectName");
          if (iterationName == null) {
            iterationName = "";
          }
        }

        taskMap.put("taskFormattedId", taskFormattedId);
        taskMap.put("taskName", taskName);
        taskMap.put("taskState", taskState);
        taskMap.put("owner", taskOwner);
        taskMap.put("taskEstimate", estimate);
        taskMap.put("taskRemaining", toDo);
        taskMap.put("projectName", projectName);
        taskMap.put("iterationName", iterationName);

        Map map = (Map) usMap.get(workProductRef);
        taskMap.put("usName", map.get("usFormattedId") + " " + map.get("usName"));

        log.info("taskMap=" + taskMap);
      } // for taskArray
    }

    return taskMap;
  }