Ejemplo n.º 1
0
 /** @throws Exception */
 public void delete() throws Exception {
   Connection delConnection = null;
   String sName = (String) oInput.get("archetype");
   if (!SourceVersion.isName(sName))
     throw new Exception("name " + sName + " is not a valid java identifier");
   PreparedStatement oStmt = null;
   try {
     delConnection = OpenShiftDerbySource.getConnection();
     oStmt = delConnection.prepareStatement("DELETE FROM " + sName + " WHERE id" + sName + " = ?");
     oStmt.setString(1, (String) oInput.get("id" + sName));
     int nRows = oStmt.executeUpdate();
     if (nRows == 0) throw new Exception("no rows deleted");
   } finally {
     if (delConnection != null)
       try {
         delConnection.close();
       } catch (SQLException logOrIgnore) {
       }
     if (oStmt != null)
       try {
         oStmt.close();
       } catch (SQLException logOrIgnore) {
       }
   }
 }
Ejemplo n.º 2
0
 /**
  * @param rs the result set from the meta data
  * @return the SQL that can be used to do an update
  * @throws Exception
  */
 private String doUpdate(ResultSet rs) throws Exception {
   int nColNo = 0;
   String sName = (String) oInput.get("archetype");
   String sSQL = "UPDATE " + sName + " SET ";
   while (rs.next()) {
     String sColName = rs.getString(1);
     if (nColNo++ > 0) {
       sSQL += ", ";
     }
     sSQL += sColName + " = ?";
     aBindVars.add((String) oInput.get(sColName));
   }
   sSQL += " WHERE id" + sName + " = ?";
   aBindVars.add(oInput.get("id" + sName).toString());
   return sSQL;
 }
Ejemplo n.º 3
0
 /**
  * @param rs the result set from the metadata
  * @return the SQL that can be used to do an update
  * @throws Exception
  */
 private String doInsert(ResultSet rs) throws Exception {
   int nColNo = 0;
   String sName = (String) oInput.get("archetype");
   String sSQL = "INSERT INTO " + sName + "(";
   String sValues = ") VALUES(";
   while (rs.next()) {
     String sColName = rs.getString(1);
     if (nColNo++ > 0) {
       sSQL += ", ";
       sValues += ", ";
     }
     sSQL += sColName;
     sValues += "?";
     aBindVars.add((String) oInput.get(sColName));
   }
   sSQL += sValues + ")";
   return sSQL;
 }
  /** Handles new incoming object. */
  private void handle(JSONObject incomingObject) {
    if (!incomingObject.containsKey("class")) return;

    try {
      String classField = (String) incomingObject.get("class");

      if (classField.equals("loginko")) {
        showError(null, null, "Unauthorized. Cannot login: "******"errorstring"));

        logger.error("Error login: "******"errorstring"));

        destroy();

        return;
      } else if (classField.equals("login_id_ok")) {
        SipAccountIDImpl accountID = (SipAccountIDImpl) sipProvider.getAccountID();

        boolean useSipCredentials = accountID.isClistOptionUseSipCredentials();

        String password;
        if (useSipCredentials) {
          password = SipActivator.getProtocolProviderFactory().loadPassword(accountID);
        } else {
          password = accountID.getClistOptionPassword();
        }

        if (!authorize((String) incomingObject.get("sessionid"), password))
          logger.error("Error login authorization!");

        return;
      } else if (classField.equals("login_pass_ok")) {
        if (!sendCapas((JSONArray) incomingObject.get("capalist")))
          logger.error("Error send capas!");

        return;
      } else if (classField.equals("login_capas_ok")) {
        if (!sendFeatures(
            (String) incomingObject.get("astid"), (String) incomingObject.get("xivo_userid")))
          logger.error("Problem send features get!");

        return;
      } else if (classField.equals("features")) {
        if (!getPhoneList()) logger.error("Problem send get phones!");

        return;
      } else if (classField.equals("phones")) {
        phonesRecieved(incomingObject);
        return;
      } else if (classField.equals("disconn")) {
        destroy();
        return;
      } else {
        if (logger.isTraceEnabled()) logger.trace("unhandled classField: " + incomingObject);
        return;
      }
    } catch (Throwable t) {
      logger.error("Error handling incoming object", t);
    }
  }
Ejemplo n.º 5
0
  public void trapException(String output) throws CrowdFlowerException {

    try {
      JSONObject error = new JSONObject(output);

      if (error.has("error")) {
        throw new CrowdFlowerException(error.get("error").toString());
      }

    } catch (JSONException e) {
      // ignore
    }
  }
  private Note resolveNoteData(JSONObject inputJSON) {
    if (!((inputJSON.has("noteTitle"))
        && (inputJSON.has("noteURL"))
        && (inputJSON.has("subjectID"))
        && (inputJSON.has("userID")))) {
      return null;
    } else {
      try {
        hibernate.controllers.SubjectsController subjectsController =
            new hibernate.controllers.SubjectsController();
        Subject subject =
            subjectsController.readSubject(Integer.parseInt(inputJSON.get("subjectID").toString()));

        hibernate.controllers.UsersController usersController =
            new hibernate.controllers.UsersController();
        User user = usersController.readUser(Integer.parseInt(inputJSON.get("userID").toString()));

        return new Note(
            inputJSON.getString("noteTitle"), inputJSON.getString("noteURL"), subject, user);
      } catch (NullPointerException ex) {
        return null;
      }
    }
  }
Ejemplo n.º 7
0
  /**
   * Performs a test by sending HTTP Gets to the URL, and records the number of bytes returned. Each
   * test results are documented and displayed in standard out with the following information:
   *
   * <p>URL - The source URL of the test REQ CNT - How many times this test has run START - The
   * start time of the last test run STOP - The stop time of the last test run THREAD - The thread
   * id handling this test case RESULT - The result of the test. Either the number of bytes returned
   * or an error message.
   */
  private void doTest() {
    String result = "";
    this.reqCount++;

    // Connect and run test steps
    Date startTime = new Date();
    try {
      ClientResource client = new ClientResource(this.myURL);

      // place order
      JSONObject json = new JSONObject();
      json.put("payment", "quarter");
      json.put("action", "place-order");
      client.post(new JsonRepresentation(json), MediaType.APPLICATION_JSON);

      // Get Gumball Count
      Representation result_string = client.get();
      JSONObject json_count = new JSONObject(result_string.getText());
      result = Integer.toString((int) json_count.get("count"));
    } catch (Exception e) {
      result = e.toString();
    } finally {
      Date stopTime = new Date();
      // Print Report of Result:
      System.out.println(
          "======================================\n"
              + "URL     => "
              + this.myURL
              + "\n"
              + "REQ CNT => "
              + this.reqCount
              + "\n"
              + "START   => "
              + startTime
              + "\n"
              + "STOP    => "
              + stopTime
              + "\n"
              + "THREAD  => "
              + Thread.currentThread().getName()
              + "\n"
              + "RESULT  => "
              + result
              + "\n");
    }
  }
  @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);
      }
    }
  }
  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();
  }
  /** @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();
    }
  }
Ejemplo n.º 11
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;
  }
Ejemplo n.º 12
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;
  }
  /**
   * tries to parse the given json message into a query object
   *
   * @param json_file a json that fulfills the exchange format between frontend and middleware
   * @return a query object that holds the information in the json message
   */
  public static Query parse(String json_file) {

    try {
      Query query = new Query();
      Object obj = JSONValue.parse(json_file);
      // System.out.println(obj);
      JSONObject j = (JSONObject) obj;
      // System.out.println(j);
      // sources
      if (j.get("source") != null) {
        /*
        JSONArray jArray = (JSONArray)j.get("sources");
        ArrayList<String> sources = new ArrayList<String>();
        for (int i = 0; i < jArray.size(); i++){
        	sources.add(jArray.get(i).toString());
        }
        */
        if (((String) (j.get("source"))).equals("dbSNP")) {
          query.s_Source = (short) 0;
        }
        if (((String) (j.get("source"))).equals("1000GenomesProject")) {
          query.s_Source = (short) 1;
        }
      }
      // chromosome
      if (j.get("chromosome") != null) {
        if (((String) j.get("chromosome")).equals("X")) {
          query.s_Chromosome = 23;
        } else if (((String) j.get("chromosome")).equals("Y")) {
          query.s_Chromosome = 24;
        } else if (((String) j.get("chromosome")).equals("MT")) {
          query.s_Chromosome = 25;
        } else {
          query.s_Chromosome = (short) Integer.parseInt((String) j.get("chromosome"));
        }
      }
      // position
      if (j.get("intervall") != null) {
        JSONObject pos_obj = (JSONObject) j.get("intervall");
        query.i_Start = (int) (long) pos_obj.get("from");
        query.i_End = (int) (long) pos_obj.get("to");
        query.i_ZoomLevel = (int) (long) pos_obj.get("size");
      }
      // gene search
      if (j.get("search") != null) {
        query.x_Search = (String) j.get("search");
      }
      // prefix
      if (j.get("prefix") != null) {
        query.b_isPrefix = (boolean) j.get("prefix");
      } else {
        query.b_isPrefix = false;
      }
      /*
      // subintervals
      if (j.get("subintervals") != null){
      	query.subintervals = (int)(long) j.get("subintervals");
      }
      */
      // hasDetail flag
      if (j.get("hasDetail") != null) {
        query.b_hasDetail = (boolean) j.get("hasDetail");
      }
      if (j.get("filter") != null) {
        JSONObject fil_obj = (JSONObject) j.get("filter");
        if (((boolean) fil_obj.get("male")) && !((boolean) fil_obj.get("female"))) {
          query.s_Gender = (short) 0;
        } else if (!((boolean) fil_obj.get("male")) && ((boolean) fil_obj.get("female"))) {
          query.s_Gender = (short) 1;
        }
        query.i_RelFrq = (int) (long) fil_obj.get("relfrq");
        JSONArray orig_array = (JSONArray) fil_obj.get("origin");
        query.s_Country = new short[orig_array.size()];
        for (int i = 0; i < orig_array.size(); i++) {
          query.s_Country[i] = IndexController.getNumber((String) orig_array.get(i));
        }
      }
      return query;
    } catch (Exception e) {
      System.out.println("Unknown query format");
      return null;
    }

    /*
    try{
    	Query query = new Query();
    	Integer randomID = get_random_number();
    	query.queryID = randomID;
    	queryID_pool.remove(randomID);
    	Object obj = JSONValue.parse(json_file);
    	//System.out.println(obj);
    	JSONObject j = (JSONObject) obj;
    	//System.out.println(j);
    	// sources
    	if (j.get("source") != null){
    		query.source = (String)j.get("source");
    	}
    	// chromosome
    	if (j.get("chromosome") != null){
    		query.chromosome = (int) (long) j.get("chromosome");
    	}
    	// position
    	if (j.get("intervall") != null){
    		JSONObject pos_obj = (JSONObject) j.get("intervall");
    		Integer[] pos = new Integer[2];
    		pos[0] =  (int)(long)pos_obj.get("from");
    		pos[1] =  (int)(long)pos_obj.get("to");
    		query.zoom_level = (int)(long)pos_obj.get("size");
    		query.position = pos;
    	}
    	// gene search
    	if (j.get("search") != null){
    		query.search = (String) j.get("search");
    	}
    	// prefix
    	if (j.get("prefix") != null){
    		query.isPrefix = (boolean)j.get("prefix");
    	}
    	else{
    		query.isPrefix = false;
    	}

    	// hasDetail flag
    	if (j.get("hasDetail") != null){
    		query.hasDetail = (boolean) j.get("hasDetail");
    	}
    	if (j.get("filter") != null){
    		Filter fil = new Filter();
    		JSONObject fil_obj = (JSONObject)j.get("filter");
    		fil.male = (boolean)fil_obj.get("male");
    		fil.female = (boolean) fil_obj.get("female");
    		fil.relfrq = (int) (long)fil_obj.get("origin");
    		JSONArray orig_array = (JSONArray) fil_obj.get("origin");
    		String[] orig = new String[orig_array.size()];
    		for (int i = 0; i < orig_array.size(); i++){
    			orig[i] = (String)orig_array.get(i);
    		}
    		fil.origin = orig;
    		query.filter = fil;
    	}
    	return query;
    }
    catch(Exception e){
    	System.out.println("Unknown query format");
    	return null;
    }
    */
  }
  /**
   * parses received phones list and creates/resolves groups and contacts
   *
   * @param objReceived the obj with data.
   */
  private void phonesRecieved(JSONObject objReceived) {
    try {
      if (!objReceived.get("function").equals("sendlist") || !objReceived.containsKey("payload"))
        return;

      JSONObject payload = (JSONObject) objReceived.get("payload");
      /*
       * FIXME The following contains two very inefficient Map-iterating
       * loops.
       */
      Iterator iter = payload.keySet().iterator();
      List<JSONObject> phoneList = new ArrayList<JSONObject>();
      while (iter.hasNext()) {
        JSONObject obj = (JSONObject) payload.get(iter.next());
        Iterator phonesIter = obj.keySet().iterator();
        while (phonesIter.hasNext()) phoneList.add((JSONObject) obj.get(phonesIter.next()));
      }

      for (JSONObject phone : phoneList) {
        try {
          // don't handle non sip phones
          if (!((String) phone.get("tech")).equalsIgnoreCase("sip")) continue;

          String groupName = (String) phone.get("context");

          ContactGroupSipImpl parentGroup = findGroupByName(groupName);

          if (parentGroup == null) {
            parentGroup = new ContactGroupSipImpl(groupName, sipProvider);
            parentGroup.setPersistent(true);
            getRootGroup().addSubgroup(parentGroup);

            fireGroupEvent(parentGroup, ServerStoredGroupEvent.GROUP_CREATED_EVENT);
          }

          String number = (String) phone.get("number");

          Address address = sipProvider.parseAddressString(number);

          // if the contact is already in the contact list
          ContactSipImpl contact = parentOperationSet.resolveContactID(address.toString());

          if (contact == null) {
            contact = new ContactSipImpl(address, sipProvider);
            contact.setDisplayName(phone.get("firstname") + " " + phone.get("lastname"));
            contact.setResolved(true);
            parentGroup.addContact(contact);

            fireContactAdded(parentGroup, contact);
          } else {
            contact.setDisplayName(phone.get("firstname") + " " + phone.get("lastname"));
            contact.setResolved(true);

            fireContactResolved(parentGroup, contact);
          }
        } catch (Throwable t) {
          logger.error("Error parsing " + phone);
        }
      }
    } catch (Throwable t) {
      logger.error("Error init list from server", t);
    }
  }
Ejemplo n.º 15
0
  /** @throws Exception */
  public void save() throws Exception {
    // these are external variables
    Connection insConnection = null;
    PreparedStatement oStmt = null;
    ResultSet rs = null;
    try {
      // get idDispClass
      insConnection = OpenShiftDerbySource.getConnection();
      String sName = (String) oInput.get("archetype");
      oStmt = insConnection.prepareStatement("SELECT idDispClass FROM DispClass WHERE name = ?");
      oStmt.setString(1, sName);
      rs = oStmt.executeQuery();
      rs.next();
      long idDispClass = rs.getLong(1);
      oStmt.close();
      rs.close();
      // get attributes to build sql
      oStmt =
          insConnection.prepareStatement("SELECT name FROM DispAttribute where idDispClass = ?");
      oStmt.setLong(1, idDispClass);
      rs = oStmt.executeQuery();
      String sSQL = null;
      boolean bInsert = false;
      aBindVars.clear();
      if (oInput.get("id" + oInput.get("archetype")) == null) {
        sSQL = doInsert(rs);
        bInsert = true;
      } else {
        sSQL = doUpdate(rs);
      }
      oStmt.close();
      oStmt = insConnection.prepareStatement(sSQL, Statement.RETURN_GENERATED_KEYS);
      int nColumn = 1;

      // set the bindvars, whice were previously cleared and updated by either the insert or update
      // SQL production
      for (String sValue : aBindVars) {
        oStmt.setString(nColumn++, sValue);
      }
      int nRowsAffected = oStmt.executeUpdate();
      if (nRowsAffected == 0) throw new Exception("0 rows updated by insert");
      if (bInsert) {
        // set the inserted id in to our object
        rs.close();
        rs = oStmt.getGeneratedKeys();
        if (rs.next()) {
          set("id" + sName, rs.getString(1));
        } else {
          throw new SQLException("Creating " + sName + " failed, no generated key obtained.");
        }
      }
    } finally {
      if (insConnection != null)
        try {
          insConnection.close();
        } catch (SQLException logOrIgnore) {
        }
      if (rs != null)
        try {
          rs.close();
        } catch (SQLException logOrIgnore) {
        }
      if (oStmt != null)
        try {
          oStmt.close();
        } catch (SQLException logOrIgnore) {
        }
    }
  }
Ejemplo n.º 16
0
 /**
  * getter and setter for any attribute
  *
  * @param sKey
  * @return
  */
 public String get(String sKey) {
   return (String) oInput.get(sKey);
 }