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;
  }
 @PUT
 @Path("/edit")
 @Consumes(MediaType.APPLICATION_JSON)
 public void editNote(String inputData) {
   JSONObject inputJSON = new JSONObject(inputData);
   if ((inputJSON.has("sessionID"))
       && UsersController.checkLogin(inputJSON.getString("sessionID"))) {
     if (inputJSON.has("noteID")) {
       int id = Integer.parseInt(inputJSON.getString("noteID"));
       editNote(inputData, id);
     }
     // w przeciwnym wypadku nic nie robi
   }
 }
Esempio n. 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();
    }
  }
Esempio n. 4
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;
 }
 @PUT
 @Path("/edit/{id}")
 @Consumes(MediaType.APPLICATION_JSON)
 public void editNote(String inputData, @PathParam("id") int id) {
   JSONObject inputJSON = new JSONObject(inputData);
   if ((inputJSON.has("sessionID"))
       && UsersController.checkLogin(inputJSON.getString("sessionID"))) {
     Note newNote = resolveNoteData(inputJSON);
     if (inputJSON.has("noteID")) inputJSON.remove("noteID"); // na wszelki wypadek - ID podano
     hibernate.controllers.NotesController notesController =
         new hibernate.controllers.NotesController();
     if (newNote != null) notesController.updateNote(newNote, id);
   }
 }
  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;
      }
    }
  }
Esempio n. 7
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);
  }
 @POST
 @Path("/create")
 @Consumes(MediaType.APPLICATION_JSON)
 public void createNote(String inputData) {
   JSONObject inputJSON = new JSONObject(inputData);
   if ((inputJSON.has("sessionID"))
       && UsersController.checkLogin(inputJSON.getString("sessionID"))) {
     if (inputJSON.has("noteID"))
       inputJSON.remove("noteID"); // na wszelki wypadek - chcemy generowaæ ID automatycznie
     Note newNote = resolveNoteData(inputJSON);
     hibernate.controllers.NotesController notesController =
         new hibernate.controllers.NotesController();
     if (newNote != null) notesController.addNote(newNote);
   }
 }
  //
  // 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();
    }
  }
  /**
   * Returns control when task is complete.
   *
   * @param json
   * @param logger
   */
  private String waitForDeploymentCompletion(JSON json, OctopusApi api, Log logger) {
    final long WAIT_TIME = 5000;
    final double WAIT_RANDOM_SCALER = 100.0;
    JSONObject jsonObj = (JSONObject) json;
    String id = jsonObj.getString("TaskId");
    Task task = null;
    String lastState = "Unknown";
    try {
      task = api.getTask(id);
    } catch (IOException ex) {
      logger.error("Error getting task: " + ex.getMessage());
      return null;
    }

    logger.info("Task info:");
    logger.info("\tId: " + task.getId());
    logger.info("\tName: " + task.getName());
    logger.info("\tDesc: " + task.getDescription());
    logger.info("\tState: " + task.getState());
    logger.info("\n\nStarting wait...");
    boolean completed = task.getIsCompleted();
    while (!completed) {
      try {
        task = api.getTask(id);
      } catch (IOException ex) {
        logger.error("Error getting task: " + ex.getMessage());
        return null;
      }

      completed = task.getIsCompleted();
      lastState = task.getState();
      logger.info("Task state: " + lastState);
      if (completed) {
        break;
      }
      try {
        Thread.sleep(WAIT_TIME + (long) (Math.random() * WAIT_RANDOM_SCALER));
      } catch (InterruptedException ex) {
        logger.info("Wait interrupted!");
        logger.info(ex.getMessage());
        completed = true; // bail out of wait loop
      }
    }
    logger.info("Wait complete!");
    return lastState;
  }
 @POST
 @Path("/view/{id}")
 @Consumes(MediaType.APPLICATION_JSON)
 @Produces(MediaType.APPLICATION_JSON)
 public String viewNote(String inputData, @PathParam("id") int id) {
   JSONObject inputJSON = new JSONObject(inputData);
   if ((inputJSON.has("sessionID"))
       && UsersController.checkLogin(inputJSON.getString("sessionID"))) {
     hibernate.controllers.NotesController notesController =
         new hibernate.controllers.NotesController();
     Note note = notesController.readNote(id);
     if (note != null) {
       JSONObject jsonNote = getJSONNote(note);
       return jsonNote.toString();
     } else {
       return "No subject of ID == " + id + "!";
     }
   } else return "Invalid session!";
 }
  @DELETE
  @Path("/{id}")
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces("text/plain")
  public String deleteNote(String inputData, @PathParam("id") int id) {
    JSONObject inputJSON = new JSONObject(inputData);
    if ((inputJSON.has("sessionID"))
        && UsersController.checkLogin(inputJSON.getString("sessionID"))) {
      try {
        hibernate.controllers.NotesController notesController =
            new hibernate.controllers.NotesController();
        notesController.deleteNote(id);

        return "OK";
      } catch (Exception ex) {
        return ex.getMessage();
      }
    } else return "Invalid session!";
  }
 @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!";
 }
Esempio n. 14
0
  /**
   * Load constructor that takes a JSONObject containing the layouts data.
   *
   * @param nwidth width of layout
   * @param nheight height of layout
   * @param jsono JSON Object with data
   * @throws JSONException data in incorrect format.
   */
  public SpringyLayout(int nwidth, int nheight, JSONObject jsono) throws JSONException {
    boolean p;
    try {
      String className = jsono.getString("algorithm");
      if (className.equals(this.getClass().getName())) {
      } else {
        System.err.print("JSON layout settings from incompatible class: " + className);
      }
    } catch (JSONException e) {
      logger.log(Level.WARNING, "Error loading JSON algorithm", e);
      System.err.println(e);
    }

    try {
      p = jsono.getBoolean("PauseState");
    } catch (JSONException e) {
      logger.log(Level.WARNING, "Error loading JSON pause", e);
      System.err.println("PauseSate missing from saved file!" + " Reverting to default values");
      p = false;
    }

    setup(nwidth, nheight, p);
  }
  public void ProcessAnswer(int type, String result) {
    System.out.println("-----ProcessAnswer");
    System.out.println("-----type = ");
    System.out.println("-----result = " + result);
    switch (type) {
      case REQUEST_SESSION:
        {
          try {
            JSONObject jsonResponse = new JSONObject(result);
            JSONObject jsonSessionItem = jsonResponse.getJSONObject("session");
            TOKEN = jsonSessionItem.getString("token");
            System.out.println("-----TOKEN = " + TOKEN);
            doRequest(REQUEST_SIGN_UP_USER);
          } catch (Exception ex) {
            DebugStorage.getInstance()
                .Log(0, "<PushAuthScreen> ProcessAnswer REQUEST_SESSION ", ex);
            onClose();
          }
          break;
        }
      case REQUEST_SIGN_UP_USER:
        {
          System.out.println("-----<ProcessAnswer> REQUEST_SIGN_UP_USER");
          try {
            doRequest(REQUEST_SESSION_WITH_USER_AND_DEVICE_PARAMS);
          } catch (Exception ex) {
            DebugStorage.getInstance()
                .Log(0, "<PushAuthScreen> ProcessAnswer REQUEST_SIGN_UP_USER ", ex);
          }
          break;
        }

      case REQUEST_SESSION_WITH_USER_AND_DEVICE_PARAMS:
        {
          try {
            JSONObject jsonResponse = new JSONObject(result);
            JSONObject jsonSessionItem = jsonResponse.getJSONObject("session");
            TOKEN = jsonSessionItem.getString("token");
            System.out.println("----- TOKEN for get push token = " + TOKEN);
            doRequest(REQUEST_PUSH_TOKEN);
          } catch (Exception ex) {
            DebugStorage.getInstance()
                .Log(0, "<PushAuthScreen> ProcessAnswer REQUEST_SESSION ", ex);
            onClose();
          }
          break;
        }
      case REQUEST_PUSH_TOKEN:
        {
          try {
            System.out.println("-----<ProcessAnswer> REQUEST_PUSH_TOKEN");
            doRequest(REQUEST_PUSH_SUBSCRIBE);
          } catch (Exception ex) {
            DebugStorage.getInstance()
                .Log(0, "<PushAuthScreen> ProcessAnswer REQUEST_PUSH_SUBSCRIBE  Exception ", ex);
            onClose();
          }
          break;
        }
      case REQUEST_PUSH_SUBSCRIBE:
        {
          try {
            System.out.println("-----<ProcessAnswer> REQUEST_PUSH_SUBSCRIBE");
            // doRequest(REQUEST_PUSH_SUBSCRIBE);
          } catch (Exception ex) {
            DebugStorage.getInstance()
                .Log(0, "<PushAuthScreen> ProcessAnswer REQUEST_PUSH_SUBSCRIBE  Exception ", ex);
            onClose();
          }
          break;
        }

      default:
        break;
    }
  }
Esempio n. 16
0
  //
  // ONE TIME ADD CITATIONS
  //
  //
  private static void oneTimeAddCitations() {

    String jsonString = "";

    try {
      jsonString = readFile("./json/citations.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());

      set1 = new HashSet<>();

      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 citationDate = " ";
        Boolean isCitationDateNull = element.isNull("citation_date");
        if (!isCitationDateNull) citationDate = element.getString("citation_date");
        String firstName = element.getString("first_name");
        String lastName = element.getString("last_name");
        String firstLastName = firstName + lastName;
        firstLastName = firstLastName.toLowerCase();
        set1.add(firstLastName);

        // System.out.println(firstLastName);
        String dob = " ";
        Boolean isDobNull = element.isNull("date_of_birth");
        if (!isDobNull) {
          dob = element.getString("date_of_birth");
          dob = (dob.split(" "))[0];
        }

        // pick a ssn from list
        String ssn = ssnList.get(ssnCounter);
        ssnCounter--;
        ssnHashMap.put(firstLastName, ssn);

        System.out.println(firstLastName + " " + ssn);

        // compute salt
        final Random ran = new SecureRandom();
        byte[] salt = new byte[32];
        ran.nextBytes(salt);
        String saltString = Base64.encodeBase64String(salt);

        // System.out.println("saltstring: " + saltString);
        saltHashMap.put(firstLastName, saltString);

        // compute ripemd160 hash of ssn + salt
        String saltPlusSsn = saltString + ssn;
        // System.out.println("salt plus ssn: " + saltPlusSsn);

        String resultingHash = "";
        try {
          byte[] r = saltPlusSsn.getBytes("US-ASCII");
          RIPEMD160Digest d = new RIPEMD160Digest();
          d.update(r, 0, r.length);
          byte[] o = new byte[d.getDigestSize()];
          d.doFinal(o, 0);
          ByteArrayOutputStream baos = new ByteArrayOutputStream(40);
          Hex.encode(o, baos);
          resultingHash = new String(baos.toByteArray(), StandardCharsets.UTF_8);

          hashedssnHashMap.put(firstLastName, resultingHash);
        } catch (UnsupportedEncodingException e) {
          System.out.println(e);
        } catch (IOException i) {
          System.out.println(i);
        }

        String fldob = firstLastName + dob;
        String da = " ";
        Boolean isDaNull = element.isNull("defendant_address");
        if (!isDaNull) da = element.getString("defendant_address");
        String dc = " ";
        Boolean isDcNull = element.isNull("defendant_city");
        if (!isDcNull) dc = element.getString("defendant_city");
        String ds = " ";
        Boolean isDsNull = element.isNull("defendant_state");
        if (!isDsNull) ds = element.getString("defendant_state");
        String dln = " ";
        Boolean isDlnNull = element.isNull("drivers_license_number");
        if (!isDlnNull) dln = element.getString("drivers_license_number");
        String cd = " ";
        Boolean isCdNull = element.isNull("court_date");
        if (!isCdNull) cd = element.getString("court_date");
        String cl = " ";
        Boolean isClNull = element.isNull("court_location");
        if (!isClNull) cl = element.getString("court_location");
        String ca = " ";
        Boolean isCaNull = element.isNull("court_address");
        if (!isCaNull) ca = element.getString("court_address");
        /*
        Map<String, AttributeValue> item = newCitationItem(citationNumber, citationDate, firstName, lastName, firstLastName, dob, fldob, resultingHash, da, dc, ds, dln, cd, cl, ca);
        PutItemRequest putItemRequest = new PutItemRequest("citations-table", item);
        PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
        */
      }
    } catch (JSONException e) {
      // JSON Parsing error
      e.printStackTrace();
    }
  }
Esempio n. 17
0
  //
  // ONE TIME ADD WARRANTS
  //
  //
  private static void oneTimeAddWarrants() {

    String jsonString = "";

    try {
      jsonString = readFile("./json/warrants.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());

      set2 = new HashSet<>();

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

        String defendant = element.getString("Defendant");

        String strarr[] = defendant.split(" ");
        String temp = strarr[1];
        int len = strarr[0].length();
        strarr[0] = strarr[0].substring(0, len - 1);
        strarr[1] = strarr[0];
        strarr[0] = temp;

        String firstLast = strarr[0] + strarr[1];
        firstLast = firstLast.toLowerCase();

        set2.add(firstLast);
        // System.out.println(firstLast);

        int zipCode = 0;
        Boolean isZipCodeNull = element.isNull("ZIP Code");
        if (!isZipCodeNull) zipCode = element.getInt("ZIP Code");
        String dob = element.getString("Date of Birth");
        String caseNumber = element.getString("Case Number");

        String firstLastDOB = firstLast + dob;

        // pick a ssn from list
        String ssn = ssnList.get(ssnCounter);
        ssnCounter--;
        ssnHashMap.put(firstLast, ssn);

        // compute salt
        final Random ran = new SecureRandom();
        byte[] salt = new byte[32];
        ran.nextBytes(salt);
        String saltString = Base64.encodeBase64String(salt);

        // System.out.println("saltstring: " + saltString);
        saltHashMap.put(firstLast, saltString);

        // compute ripemd160 hash of ssn + salt
        String saltPlusSsn = saltString + ssn;
        // System.out.println("salt plus ssn: " + saltPlusSsn);

        String resultingHash = "";
        try {
          byte[] r = saltPlusSsn.getBytes("US-ASCII");
          RIPEMD160Digest d = new RIPEMD160Digest();
          d.update(r, 0, r.length);
          byte[] o = new byte[d.getDigestSize()];
          d.doFinal(o, 0);
          ByteArrayOutputStream baos = new ByteArrayOutputStream(40);
          Hex.encode(o, baos);
          resultingHash = new String(baos.toByteArray(), StandardCharsets.UTF_8);

          hashedssnHashMap.put(firstLast, resultingHash);
        } catch (UnsupportedEncodingException e) {
          System.out.println(e);
        } catch (IOException i) {
          System.out.println(i);
        }

        // compareNames();

        Map<String, AttributeValue> item =
            newWarrantItem(
                firstLast, firstLastDOB, resultingHash, defendant, zipCode, dob, caseNumber);
        PutItemRequest putItemRequest = new PutItemRequest("warrants-table", item);
        PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
      }
    } catch (JSONException e) {
      // JSON Parsing error
      e.printStackTrace();
    }
  }
Esempio n. 18
0
  private boolean handlePost(
      HttpServletRequest request, HttpServletResponse response, String pathString)
      throws IOException, JSONException, ServletException, URISyntaxException, CoreException,
          NoHeadException, NoMessageException, ConcurrentRefUpdateException,
          WrongRepositoryStateException {
    // make sure required fields are set
    JSONObject toAdd = OrionServlet.readJSONRequest(request);
    if (toAdd.optBoolean(GitConstants.KEY_PULL, false)) {
      GitUtils.createGitCredentialsProvider(toAdd);
      GitCredentialsProvider cp = GitUtils.createGitCredentialsProvider(toAdd);
      boolean force = toAdd.optBoolean(GitConstants.KEY_FORCE, false);
      return pull(request, response, cp, pathString, force);
    }

    Clone clone = new Clone();
    String url = toAdd.optString(GitConstants.KEY_URL, null);
    // method handles repository clone or just repository init
    // decision is based on existence of GitUrl argument
    boolean initOnly;
    if (url == null || url.isEmpty()) initOnly = true;
    else {
      initOnly = false;
      if (!validateCloneUrl(url, request, response)) return true;
      clone.setUrl(new URIish(url));
    }
    String cloneName = toAdd.optString(ProtocolConstants.KEY_NAME, null);
    if (cloneName == null) cloneName = request.getHeader(ProtocolConstants.HEADER_SLUG);
    // expected path /workspace/{workspaceId}
    String workspacePath = toAdd.optString(ProtocolConstants.KEY_LOCATION, null);
    // expected path /file/{workspaceId}/{projectName}[/{path}]
    String filePathString = toAdd.optString(ProtocolConstants.KEY_PATH, null);
    IPath filePath = filePathString == null ? null : new Path(filePathString);
    if (filePath != null && filePath.segmentCount() < 3) filePath = null;
    if (filePath == null && workspacePath == null) {
      String msg =
          NLS.bind(
              "Either {0} or {1} should be provided: {2}",
              new Object[] {ProtocolConstants.KEY_PATH, ProtocolConstants.KEY_LOCATION, toAdd});
      return statusHandler.handleRequest(
          request,
          response,
          new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
    }
    // only during init operation filePath or cloneName must be provided
    // during clone operation, name can be obtained from URL
    if (initOnly && filePath == null && cloneName == null) {
      String msg =
          NLS.bind(
              "Either {0} or {1} should be provided: {2}",
              new Object[] {ProtocolConstants.KEY_PATH, GitConstants.KEY_NAME, toAdd});
      return statusHandler.handleRequest(
          request,
          response,
          new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
    }
    if (!validateCloneName(cloneName, request, response)) return true;

    // prepare the WebClone object, create a new project if necessary
    WebProject webProject = null;
    boolean webProjectExists = false;
    if (filePath != null) {
      // path format is /file/{workspaceId}/{projectName}/[filePath]
      clone.setId(filePath.toString());
      webProject = GitUtils.projectFromPath(filePath);
      // workspace path format needs to be used if project does not exist
      if (webProject == null) {
        String msg = NLS.bind("Specified project does not exist: {0}", filePath.segment(2));
        return statusHandler.handleRequest(
            request,
            response,
            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
      }
      webProjectExists = true;
      clone.setContentLocation(
          webProject.getProjectStore().getFileStore(filePath.removeFirstSegments(3)).toURI());
      if (cloneName == null)
        cloneName = filePath.segmentCount() > 2 ? filePath.lastSegment() : webProject.getName();
    } else if (workspacePath != null) {
      IPath path = new Path(workspacePath);
      // TODO: move this to CloneJob
      // if so, modify init part to create a new project if necessary
      WebWorkspace workspace = WebWorkspace.fromId(path.segment(1));
      String id = WebProject.nextProjectId();
      if (cloneName == null) cloneName = new URIish(url).getHumanishName();
      cloneName = getUniqueProjectName(workspace, cloneName);
      webProjectExists = false;
      webProject = WebProject.fromId(id);
      webProject.setName(cloneName);

      try {
        WorkspaceResourceHandler.computeProjectLocation(request, webProject, null, false);
      } 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 statusHandler.handleRequest(
            request,
            response,
            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
      } catch (URISyntaxException e) {
        // should not happen, we do not allow linking at this point
      }

      try {
        // If all went well, add project to workspace
        WorkspaceResourceHandler.addProject(request.getRemoteUser(), workspace, webProject);
      } catch (CoreException e) {
        return statusHandler.handleRequest(
            request,
            response,
            new ServerStatus(
                IStatus.ERROR,
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Error persisting project state",
                e));
      }

      URI baseLocation = getURI(request);
      baseLocation =
          new URI(
              baseLocation.getScheme(),
              baseLocation.getUserInfo(),
              baseLocation.getHost(),
              baseLocation.getPort(),
              workspacePath,
              baseLocation.getQuery(),
              baseLocation.getFragment());
      clone.setId(GitUtils.pathFromProject(workspace, webProject).toString());
      clone.setContentLocation(webProject.getProjectStore().toURI());
    }
    clone.setName(cloneName);
    clone.setBaseLocation(getURI(request));
    JSONObject cloneObject = clone.toJSON();
    String cloneLocation = cloneObject.getString(ProtocolConstants.KEY_LOCATION);

    if (initOnly) {
      // git init
      InitJob job =
          new InitJob(
              clone, TaskJobHandler.getUserId(request), request.getRemoteUser(), cloneLocation);
      return TaskJobHandler.handleTaskJob(request, response, job, statusHandler);
    }
    // git clone
    // prepare creds
    GitCredentialsProvider cp = GitUtils.createGitCredentialsProvider(toAdd);
    cp.setUri(new URIish(clone.getUrl()));

    // if all went well, clone
    CloneJob job =
        new CloneJob(
            clone,
            TaskJobHandler.getUserId(request),
            cp,
            request.getRemoteUser(),
            cloneLocation,
            webProjectExists
                ? null
                : webProject /* used for cleaning up, so null when not needed */);
    return TaskJobHandler.handleTaskJob(request, response, job, statusHandler);
  }
  public void doProcess(HttpServletRequest req, HttpServletResponse res, boolean isPost) {
    StringBuffer bodyContent = null;
    OutputStream out = null;
    PrintWriter writer = null;
    String serviceKey = null;

    try {
      BufferedReader in = req.getReader();
      String line = null;
      while ((line = in.readLine()) != null) {
        if (bodyContent == null) bodyContent = new StringBuffer();
        bodyContent.append(line);
      }
    } catch (Exception e) {
    }
    try {
      if (requireSession) {
        // check to see if there was a session created for this request
        // if not assume it was from another domain and blow up
        // Wrap this to prevent Portlet exeptions
        HttpSession session = req.getSession(false);
        if (session == null) {
          res.setStatus(HttpServletResponse.SC_FORBIDDEN);
          return;
        }
      }
      serviceKey = req.getParameter("id");
      // only to preven regressions - Remove before 1.0
      if (serviceKey == null) serviceKey = req.getParameter("key");
      // check if the services have been loaded or if they need to be reloaded
      if (services == null || configUpdated()) {
        getServices(res);
      }
      String urlString = null;
      String xslURLString = null;
      String userName = null;
      String password = null;
      String format = "json";
      String callback = req.getParameter("callback");
      String urlParams = req.getParameter("urlparams");
      String countString = req.getParameter("count");
      // encode the url to prevent spaces from being passed along
      if (urlParams != null) {
        urlParams = urlParams.replace(' ', '+');
      }

      try {
        if (services.has(serviceKey)) {
          JSONObject service = services.getJSONObject(serviceKey);
          // default to the service default if no url parameters are specified
          if (urlParams == null && service.has("defaultURLParams")) {
            urlParams = service.getString("defaultURLParams");
          }
          String serviceURL = service.getString("url");
          // build the URL
          if (urlParams != null && serviceURL.indexOf("?") == -1) {
            serviceURL += "?";
          } else if (urlParams != null) {
            serviceURL += "&";
          }
          String apikey = "";
          if (service.has("username")) userName = service.getString("username");
          if (service.has("password")) password = service.getString("password");
          if (service.has("apikey")) apikey = service.getString("apikey");
          urlString = serviceURL + apikey;
          if (urlParams != null) urlString += "&" + urlParams;
          if (service.has("xslStyleSheet")) {
            xslURLString = service.getString("xslStyleSheet");
          }
        }
        // code for passing the url directly through instead of using configuration file
        else if (req.getParameter("url") != null) {
          String serviceURL = req.getParameter("url");
          // build the URL
          if (urlParams != null && serviceURL.indexOf("?") == -1) {
            serviceURL += "?";
          } else if (urlParams != null) {
            serviceURL += "&";
          }
          urlString = serviceURL;
          if (urlParams != null) urlString += urlParams;
        } else {
          writer = res.getWriter();
          if (serviceKey == null)
            writer.write("XmlHttpProxyServlet Error: id parameter specifying serivce required.");
          else
            writer.write(
                "XmlHttpProxyServlet Error : service for id '" + serviceKey + "' not  found.");
          writer.flush();
          return;
        }
      } catch (Exception ex) {
        getLogger().severe("XmlHttpProxyServlet Error loading service: " + ex);
      }

      Map paramsMap = new HashMap();
      paramsMap.put("format", format);
      // do not allow for xdomain unless the context level setting is enabled.
      if (callback != null && allowXDomain) {
        paramsMap.put("callback", callback);
      }
      if (countString != null) {
        paramsMap.put("count", countString);
      }

      InputStream xslInputStream = null;

      if (urlString == null) {
        writer = res.getWriter();
        writer.write(
            "XmlHttpProxyServlet parameters:  id[Required] urlparams[Optional] format[Optional] callback[Optional]");
        writer.flush();
        return;
      }
      // default to JSON
      res.setContentType(responseContentType);
      out = res.getOutputStream();
      // get the stream for the xsl stylesheet
      if (xslURLString != null) {
        // check the web root for the resource
        URL xslURL = null;
        xslURL = ctx.getResource(resourcesDir + "xsl/" + xslURLString);
        // if not in the web root check the classpath
        if (xslURL == null) {
          xslURL =
              XmlHttpProxyServlet.class.getResource(classpathResourcesDir + "xsl/" + xslURLString);
        }
        if (xslURL != null) {
          xslInputStream = xslURL.openStream();
        } else {
          String message =
              "Could not locate the XSL stylesheet provided for service id "
                  + serviceKey
                  + ". Please check the XMLHttpProxy configuration.";
          getLogger().severe(message);
          try {
            out.write(message.getBytes());
            out.flush();
            return;
          } catch (java.io.IOException iox) {
          }
        }
      }
      if (!isPost) {
        xhp.doGet(urlString, out, xslInputStream, paramsMap, userName, password);
      } else {
        if (bodyContent == null)
          getLogger()
              .info(
                  "XmlHttpProxyServlet attempting to post to url "
                      + urlString
                      + " with no body content");
        xhp.doPost(
            urlString,
            out,
            xslInputStream,
            paramsMap,
            bodyContent.toString(),
            req.getContentType(),
            userName,
            password);
      }
    } catch (Exception iox) {
      iox.printStackTrace();
      getLogger().severe("XmlHttpProxyServlet: caught " + iox);
      try {
        writer = res.getWriter();
        writer.write(iox.toString());
        writer.flush();
      } catch (java.io.IOException ix) {
        ix.printStackTrace();
      }
      return;
    } finally {
      try {
        if (out != null) out.close();
        if (writer != null) writer.close();
      } catch (java.io.IOException iox) {
      }
    }
  }
  @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);
      }
    }
  }
      @Override
      public void onComplete(String response, Object state) {
        try {
          Log.i(TAG, response);
          json = Util.parseJson(response);

          // photos are in the form of a json array
          child = json.getJSONArray("data");

          int total = child.length();

          // contains links to photos
          links = new ArrayList<String>(total);

          // adds link to each photo to our list after replacing the "https" from url
          // DownloadManager does not support https in gingerbread
          for (int i = 0; i < total; i++) {
            photo_json = child.getJSONObject(i);

            if (dl_high_res_pics) {
              JSONArray image_set = photo_json.getJSONArray("images");

              // highest resolution picture has the index zero in the images jsonarray
              JSONObject highest_res_pic = image_set.getJSONObject(0);
              String http_replaced =
                  highest_res_pic.getString("source").replaceFirst("https", "http");
              links.add(i, http_replaced);
            } else {
              // source property of the json object points to the photo's link
              String http_replaced = photo_json.getString("source").replaceFirst("https", "http");
              links.add(i, http_replaced);
            }
          }

          download_photos.this.runOnUiThread(
              new Runnable() {
                public void run() {
                  //	mytask = new DownloadImageTask();
                  //	mytask.execute(links);
                  // start downloading using asynctask
                  // new DownloadImageTask().execute(links);
                  // downloadThread.setPath(path);
                  // downloadThread.setWholeTasks(links.size());
                  if (resume_file.exists()) {

                    initial_value = readProgress()[0];
                    final_value = links.size();
                    // case if the task is already completed
                    if (initial_value == final_value) {
                      completed = true;
                      resume_pause.setVisibility(View.GONE);

                      progress_download.setMax(final_value);
                      progress_download.setProgress(0); // bug in progress bar
                      progress_download.setProgress(initial_value);

                      progress_text.setText("Completed.");
                      mtext.setText(
                          getText(R.string.download_textview_message_1)
                              + " "
                              + path.toString()
                              + ". ");

                    }

                    // case if some of the photos are already downloaded
                    else {
                      progress_download.setMax(links.size());
                      // progress_download.setProgress(0);	//bug in progress bar
                      progress_download.setProgress(initial_value);

                      // N.B if i= initial_value -1, then one image will be downloaded again. so to
                      // save cost we start with i = initial_value
                      for (int i = initial_value; i < links.size(); i++) {
                        mtext.setText(
                            getText(R.string.download_textview_message_1)
                                + " "
                                + path.toString()
                                + ". ");
                        // downloadThread.setRunningTask(i + 1);
                        downloadThread.enqueueDownload(
                            new DownloadTask(
                                links.get(i), path, i + 1, final_value, download_photos.this));
                      }
                    }
                  }

                  // case if the task is entirely new task
                  else {
                    for (int i = 0; i < links.size(); i++) {
                      mtext.setText(
                          getText(R.string.download_textview_message_1)
                              + " "
                              + path.toString()
                              + ". ");
                      // downloadThread.setRunningTask(i + 1);
                      downloadThread.enqueueDownload(
                          new DownloadTask(
                              links.get(i), path, i + 1, links.size(), download_photos.this));
                    }
                  }
                }
              });
        } catch (JSONException ex) {
          Log.e(TAG, "JSONEXception : " + ex.getMessage());
        }
      }