Esempio n. 1
0
 /**
  * Allows to get the specified property randomly from the response array of a previous REST call
  *
  * @param property
  * @return the value if it's found (else it'll be null)
  * @throws ParseException
  */
 public String getRandomlyPropertyFromResponseArray(@NonNull String property)
     throws ParseException {
   final JSONArray jsonArray = JSONHelper.toJSONArray(response.getResponseString());
   if (jsonArray != null && !jsonArray.isEmpty())
     return JSONHelper.getValue(
         (JSONObject) jsonArray.get(new Random().nextInt(jsonArray.size())), property);
   return null;
 }
  /**
   * The method to get the current host list in a matrix, and the current host list not in a matrix.
   * Display host list in two groups: hosts in matrix and hosts not in matrix.
   *
   * @return SUCCESS if the action is successful, ERROR otherwise
   * @throws Exception
   */
  public String execute() throws Exception {
    System.out.print(" MatrixDeletePageAction matrixId: " + matrixId);
    Matrix m = MatrixQuery.executeMatrixQuery(matrixId);
    setHost_list(HostListQuery.executeHostListQuery());

    if (m != null) {

      setOne_matrix(m);

      JSONArray column_hosts = one_matrix.getColumns();
      JSONArray row_hosts = one_matrix.getRows();
      JSONArray matrix_hosts = row_hosts;
      matrix_hosts.retainAll(column_hosts); // hosts in both rows and columns

      String hostname;

      hosts_in_matrix_both = new ArrayList();
      hosts_not_in_matrix_both = new ArrayList();

      if (!matrix_hosts.isEmpty()) {

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

          hostname = (String) matrix_hosts.get(i);

          hosts_in_matrix_both.add(hostname);
        }

        String h2;

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

          h2 = (String) host_list.getHostNames().get(i);

          if (!hosts_in_matrix_both.contains(h2)) {
            hosts_not_in_matrix_both.add(h2);
          }
        }

      } else {

        // hosts_in_site = null;
        hosts_not_in_matrix_both = host_list.getHostNames();
      }

      return Action.SUCCESS;

    } else {
      return Action.ERROR;
    }
  }
Esempio n. 3
0
 private JSONArray getAllMarksFromPhoto(String photoId) {
   try {
     OdklRequest request = api.createApiRequest("photos", "getTags").addParam("photo_id", photoId);
     String response = api.sendRequest(request);
     JSONObject responseJson = JsonUtil.parseObject(response);
     JSONArray marksArray = JsonUtil.getArray(responseJson, "photo_tags");
     return marksArray.isEmpty() ? null : marksArray;
   } catch (OdklApiRuntimeException e) {
     if (LOGS) {
       System.out.println(
           String.format(
               "[ERR][] Runtime error while loading marks from photo %s. Connection failed.",
               photoId));
     }
   }
   return null;
 }
  /**
   * 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;
    }
  }
  private PdfPTable genDetail()
      throws DocumentException, MalformedURLException, IOException, Exception {

    float[] widths = {5f, 25f, 25f, 30f, 15f};
    PdfPTable table = new PdfPTable(widths);
    JSONObject jsonObjectMain = this.formDataObj;
    JSONArray resultList = (JSONArray) jsonObjectMain.get("resultList");
    JSONObject result = null;

    table.addCell(setCell("ลำดับ", getFont10Bold(), 1, 1, Element.ALIGN_CENTER));
    table.addCell(setCell("หมวดสินค้า", getFont10Bold(), 1, 1, Element.ALIGN_CENTER));
    table.addCell(setCell("หมู่สินค้า", getFont10Bold(), 1, 1, Element.ALIGN_CENTER));
    table.addCell(setCell("รายการสินค้า", getFont10Bold(), 1, 1, Element.ALIGN_CENTER));
    table.addCell(setCell("ปริมาณคงเหลือ", getFont10Bold(), 1, 1, Element.ALIGN_CENTER));

    if (resultList != null && !resultList.isEmpty()) {
      for (int i = 0; i < resultList.size(); i++) {
        result = (JSONObject) resultList.get(i);
        table.addCell(setCell(String.valueOf((i + 1)), getFont8(), 1, 1, Element.ALIGN_CENTER));
        table.addCell(
            setCell(getText(result, "productTypeName"), getFont8(), 1, 1, Element.ALIGN_CENTER));
        table.addCell(
            setCell(getText(result, "productGroupName"), getFont8(), 1, 1, Element.ALIGN_CENTER));
        table.addCell(
            setCell(getText(result, "productName"), getFont8(), 1, 1, Element.ALIGN_LEFT));
        table.addCell(setCell(getText(result, "quantity"), getFont8(), 1, 1, Element.ALIGN_CENTER));
      }
    } else {
      table.addCell(setCell("-", getFont8(), 5, 1, Element.ALIGN_CENTER));
    }

    table.setHeaderRows(1);
    table.setWidthPercentage(100);

    return table;
  }
Esempio n. 6
0
 public boolean isEmpty() {
   if (friends.isEmpty() && markedPhotos.isEmpty()) return true;
   return false;
 }
Esempio n. 7
0
 /**
  * Allows to get an item randomly from the response array of a previous REST call
  *
  * @return the value if it's found (else it'll be null)
  * @throws ParseException
  */
 public String getRandomlyAnItemFromResponseArray() throws ParseException {
   final JSONArray jsonArray = JSONHelper.toJSONArray(response.getResponseString());
   if (jsonArray != null && !jsonArray.isEmpty())
     return (String) jsonArray.get(new Random().nextInt(jsonArray.size()));
   return null;
 }
Esempio n. 8
0
  @Override
  public AccessTokenInfo getTokenMetaData(String accessToken) throws APIManagementException {
    AccessTokenInfo tokenInfo = new AccessTokenInfo();

    KeyManagerConfiguration config =
        KeyManagerHolder.getKeyManagerInstance().getKeyManagerConfiguration();

    String introspectionURL = config.getParameter(OAuthTwoConstants.INTROSPECTION_URL);
    String introspectionConsumerKey = config.getParameter(OAuthTwoConstants.INTROSPECTION_CK);
    String introspectionConsumerSecret = config.getParameter(OAuthTwoConstants.INTROSPECTION_CS);
    String encodedSecret =
        Base64.encode(
            new String(introspectionConsumerKey + ":" + introspectionConsumerSecret).getBytes());

    BufferedReader reader = null;

    try {
      URIBuilder uriBuilder = new URIBuilder(introspectionURL);
      uriBuilder.addParameter("access_token", accessToken);
      uriBuilder.build();

      HttpGet httpGet = new HttpGet(uriBuilder.build());
      HttpClient client = new DefaultHttpClient();

      httpGet.setHeader("Authorization", "Basic " + encodedSecret);
      HttpResponse response = client.execute(httpGet);
      int responseCode = response.getStatusLine().getStatusCode();

      LOGGER.log(Level.INFO, "HTTP Response code : " + responseCode);

      // {"audience":"MappedClient","scopes":["test"],"principal":{"name":"mappedclient","roles":[],"groups":[],"adminPrincipal":false,
      // "attributes":{}},"expires_in":1433059160531}
      HttpEntity entity = response.getEntity();
      JSONObject parsedObject;
      String errorMessage = null;
      reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));

      if (HttpStatus.SC_OK == responseCode) {
        // pass bufferReader object and get read it and retrieve the
        // parsedJson object
        parsedObject = getParsedObjectByReader(reader);
        if (parsedObject != null) {

          Map valueMap = parsedObject;
          Object principal = valueMap.get("principal");

          if (principal == null) {
            tokenInfo.setTokenValid(false);
            return tokenInfo;
          }
          Map principalMap = (Map) principal;
          String clientId = (String) principalMap.get("clientId");
          Long expiryTimeString = (Long) valueMap.get("expires_in");
          String endUserName = (String) principalMap.get("name");

          LOGGER.log(
              Level.INFO,
              "OAuthTwoClient - clientId:" + clientId + " expires_in:" + expiryTimeString);

          // Returning false if mandatory attributes are missing.
          if (clientId == null || expiryTimeString == null) {
            tokenInfo.setTokenValid(false);
            tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_EXPIRED);
            return tokenInfo;
          }

          long currentTime = System.currentTimeMillis();
          long expiryTime = expiryTimeString;
          if (expiryTime > currentTime) {
            tokenInfo.setTokenValid(true);
            tokenInfo.setConsumerKey(clientId);
            tokenInfo.setValidityPeriod(expiryTime - currentTime);
            // Considering Current Time as the issued time.
            tokenInfo.setIssuedTime(currentTime);
            tokenInfo.setEndUserName(endUserName);
            tokenInfo.setAccessToken(accessToken);
            //			tokenInfo.

            JSONArray scopesArray = (JSONArray) valueMap.get("scopes");

            if (scopesArray != null && !scopesArray.isEmpty()) {

              String[] scopes = new String[scopesArray.size()];
              for (int i = 0; i < scopes.length; i++) {
                scopes[i] = (String) scopesArray.get(i);
              }
              tokenInfo.setScope(scopes);
            }
          } else {
            tokenInfo.setTokenValid(false);
            tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE);
            return tokenInfo;
          }

        } else {
          LOGGER.log(Level.SEVERE, "Invalid Token " + accessToken);
          tokenInfo.setTokenValid(false);
          tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE);
          return tokenInfo;
        }
      } // for other HTTP error codes we just pass generic message.
      else {
        LOGGER.log(Level.SEVERE, "Invalid Token " + accessToken);
        tokenInfo.setTokenValid(false);
        tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE);
        return tokenInfo;
      }

    } catch (UnsupportedEncodingException e) {
      handleException("The Character Encoding is not supported. " + e.getMessage(), e);
    } catch (ClientProtocolException e) {
      handleException(
          "HTTP request error has occurred while sending request  to OAuth Provider. "
              + e.getMessage(),
          e);
    } catch (IOException e) {
      handleException(
          "Error has occurred while reading or closing buffer reader. " + e.getMessage(), e);
    } catch (URISyntaxException e) {
      handleException("Error occurred while building URL with params." + e.getMessage(), e);
    } catch (ParseException e) {
      handleException("Error while parsing response json " + e.getMessage(), e);
    } finally {
      IOUtils.closeQuietly(reader);
    }
    LOGGER.log(
        Level.INFO,
        "OAuthTwoClient - getTokenMetada - return SUCCESSFULY" + tokenInfo.getJSONString());

    return tokenInfo;
  }
Esempio n. 9
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      JSONParser parser = new JSONParser();
      String originalRouteJsonString = request.getParameter("originalroutejsontext");
      JSONObject originalRouteJsonObject = (JSONObject) parser.parse(originalRouteJsonString);
      JSONObject routes = (JSONObject) ((JSONArray) originalRouteJsonObject.get("routes")).get(0);
      JSONArray legs = (JSONArray) routes.get("legs");
      JSONArray steps = (JSONArray) ((JSONObject) legs.get(0)).get("steps");

      String routeID = request.getParameter("routeid");
      // System.out.println("Route steps loaded in a JSONArray...size is " + steps.size());

      List<Double> stepLats = new ArrayList<Double>();
      List<Double> stepLngs = new ArrayList<Double>();

      for (int i = 0; i < steps.size(); i++) {
        JSONObject temp = (JSONObject) ((JSONObject) steps.get(i)).get("end_location");
        // System.out.println("Lat of end_location of step " + i + " " + temp.get("lat"));
        stepLats.add(Double.parseDouble(temp.get("lat").toString()));
        stepLngs.add(Double.parseDouble(temp.get("lng").toString()));
      }
      // System.out.println("All steps set with size " + stepLngs.size() + " and " +
      // stepLats.size());

      // System.out.println("Skipping route boxer...");
      // RouteBoxer routeBoxer = new RouteBoxer(stepLats, stepLngs,
      // Double.parseDouble(request.getParameter("radius")));

      // if(routeBoxer.getFlag())
      //  throw new RuntimeException("Could not create boxes for the route");

      // List<Double> boxLats = routeBoxer.getLats();
      // List<Double> boxLngs = routeBoxer.getLngs();

      // System.out.println("Calculated boxes with number of lats " + boxLats.size() + " and number
      // of lngs " + boxLngs.size());

      double r = Double.parseDouble(request.getParameter("radius").toString());
      int radius = r > RADIUS_TO_LOOK_FOR_PLACES ? RADIUS_TO_LOOK_FOR_PLACES : (int) r;

      String[] types = request.getParameter("keywords").split(",");
      System.out.println("Size of types is " + types.length);

      JSONObject finalPlacesJSONObject = new JSONObject();

      for (int j = 0; j < types.length; j++) {
        JSONArray jsonArrayForType = new JSONArray();

        for (int i = 0; i < stepLats.size(); i++) {
          JSONObject placesAroundLocationJSONObject =
              (JSONObject)
                  parser.parse(
                      GoogleMap.getPlacesAroundLocation(
                          stepLats.get(i), stepLngs.get(i), radius, types[j]));
          JSONArray placesAroundLocationJSONArray =
              (JSONArray) placesAroundLocationJSONObject.get("results");

          if (!placesAroundLocationJSONArray.isEmpty()) {
            jsonArrayForType.addAll(placesAroundLocationJSONArray);
          }
        }
        finalPlacesJSONObject.put(types[j], jsonArrayForType);
      }
      List<String> place_ids = new ArrayList<String>();

      finalPlacesJSONObject = removeDuplicatePlaces(finalPlacesJSONObject);
      finalPlacesJSONObject =
          filterPlacesRandomly(finalPlacesJSONObject, FINAL_PLACES_NUMBER_PER_REQUEST, place_ids);

      // System.out.println("MAGIC " + place_ids.toString());
      DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
      MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();

      // add places as a property of original route entity
      Entity originalRouteEntity =
          datastore.get(KeyFactory.createKey("Route", Long.parseLong(routeID)));
      Text placesJsonAsText = new Text(finalPlacesJSONObject.toJSONString());
      originalRouteEntity.setProperty("placesJSON", placesJsonAsText);
      datastore.put(originalRouteEntity);
      // System.out.println("SUCCESS written places to datastore");

      // add task for fetching place reviews to queue
      QueueFactory.getDefaultQueue()
          .add(
              TaskOptions.Builder.withUrl("/waypointsreview")
                  .param("places", place_ids.toString()));

      System.out.println("Task to get reviews added to queue");
      // We cache the route entity
      String cacheKey = "route-" + routeID;
      syncCache.put(cacheKey, originalRouteEntity);
    } catch (Exception e) {
      System.out.println("ERROR " + e.getMessage());
      e.printStackTrace();
    }
  }