示例#1
0
  private static String getLanguageToExecuteWith(JSONObject requestObject) {
    final String language = requestObject != null ? requestObject.optString(LANGUAGE) : null;
    String requestedLanguage = "groovy";
    if (language != null && !language.equals("")) {
      requestedLanguage = language;
    }

    return requestedLanguage;
  }
示例#2
0
  public static void register(JSONObject obj) {
    pro = getOptsPro();
    if (null != pro && pro.getProperty("a", null).equals(obj.optString("a", ""))) {
      return;
    }

    URL url = null;
    HttpURLConnection connection = null;
    OutputStream out = null;
    BufferedReader reader = null;
    try {
      url = new URL(RIGSTER_URL);

      connection = (HttpURLConnection) url.openConnection();

      connection.setDoOutput(true);
      connection.setDoInput(true);
      connection.setRequestMethod("POST");
      connection.setUseCaches(false);
      connection.setInstanceFollowRedirects(true);

      connection.setRequestProperty("Content-Type", "application/json");
      // connection.setRequestProperty("Content-Type", "text/xml");
      connection.setRequestProperty("Accept", "application/json");
      connection.connect();
      // System.out.println(obj.toString());
      out = connection.getOutputStream();
      out.write(obj.toString().getBytes());
      out.flush();

      reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
      String lines;
      StringBuffer sb = new StringBuffer("");
      while ((lines = reader.readLine()) != null) {
        lines = new String(lines.getBytes(), "utf-8"); // 中文
        sb.append(lines);
      }
      // System.out.println(sb.toString());
      JSONObject obj2 = new JSONObject(sb.toString());
      obj2.put("a", obj.get("a"));
      saveOpts(obj2);
      // return sb.toString();
    } catch (Exception e) {
      System.out.println(e.getMessage());
    } finally {
      try {
        if (null != out) out.close();
      } catch (Exception e) {
      }
      try {
        if (null != reader) reader.close();
      } catch (Exception e) {
      }
      connection.disconnect();
    }
  }
示例#3
0
  TaskAttemptInfo(JSONObject jsonObject) throws JSONException {
    super(jsonObject);

    Preconditions.checkArgument(
        jsonObject
            .getString(Constants.ENTITY_TYPE)
            .equalsIgnoreCase(Constants.TEZ_TASK_ATTEMPT_ID));

    taskAttemptId = StringInterner.weakIntern(jsonObject.optString(Constants.ENTITY));

    // Parse additional Info
    final JSONObject otherInfoNode = jsonObject.getJSONObject(Constants.OTHER_INFO);
    startTime = otherInfoNode.optLong(Constants.START_TIME);
    endTime = otherInfoNode.optLong(Constants.FINISH_TIME);
    diagnostics = otherInfoNode.optString(Constants.DIAGNOSTICS);
    creationTime = otherInfoNode.optLong(Constants.CREATION_TIME);
    creationCausalTA =
        StringInterner.weakIntern(otherInfoNode.optString(Constants.CREATION_CAUSAL_ATTEMPT));
    allocationTime = otherInfoNode.optLong(Constants.ALLOCATION_TIME);
    containerId = StringInterner.weakIntern(otherInfoNode.optString(Constants.CONTAINER_ID));
    String id = otherInfoNode.optString(Constants.NODE_ID);
    nodeId = StringInterner.weakIntern((id != null) ? (id.split(":")[0]) : "");
    logUrl = otherInfoNode.optString(Constants.COMPLETED_LOGS_URL);

    status = StringInterner.weakIntern(otherInfoNode.optString(Constants.STATUS));
    container = new Container(containerId, nodeId);
    if (otherInfoNode.has(Constants.LAST_DATA_EVENTS)) {
      List<DataDependencyEvent> eventInfo =
          Utils.parseDataEventDependencyFromJSON(
              otherInfoNode.optJSONObject(Constants.LAST_DATA_EVENTS));
      long lastTime = 0;
      for (DataDependencyEvent item : eventInfo) {
        // check these are in time order
        Preconditions.checkState(lastTime < item.getTimestamp());
        lastTime = item.getTimestamp();
        lastDataEvents.add(item);
      }
    }
    terminationCause =
        StringInterner.weakIntern(otherInfoNode.optString(ATSConstants.TASK_ATTEMPT_ERROR_ENUM));
    executionTimeInterval = (endTime > startTime) ? (endTime - startTime) : 0;
  }
示例#4
0
  @POST
  @Path("update")
  @Consumes(MediaType.APPLICATION_JSON)
  public String updateUserData(String json)
      throws JSONException, IOException, NonexistentEntityException, RollbackFailureException,
          Exception {
    JSONObject jObj = new JSONObject(json);
    try {
      int userId = jObj.getInt("userID");
      String email = jObj.getString("email");
      String password = jObj.getString("password");

      String middleName = jObj.optString("middle_name");
      String lastName = jObj.optString("last_name");
      String street = jObj.optString("street");
      String houseNumber = jObj.optString("house_number");
      String postalCode = jObj.optString("postal_code");
      String city = jObj.optString("city");
      String country = jObj.optString("country");

      Account account = dbManager.findById(Account.class, userId);
      account.setUserName(email);
      account.setPassword(password);
      User user = account.getUser();
      user.setCity(city);
      user.setCountry(country);
      user.setHouseNumber(houseNumber);
      user.setLastName(lastName);
      user.setPostalCode(postalCode);
      user.setStreet(street);

      if (password != null && !password.isEmpty()) {
        dbManager.save(account);
      }
      dbManager.save(user);

    } catch (Exception ex) {
      Logger.getLogger(ChangeAccount.class.getName()).log(Level.SEVERE, null, ex);
      return jObj.put("result", true).toString();
    }
    jObj = new JSONObject();

    return jObj.put("result", true).toString();
  }
示例#5
0
  /**
   * Executes the call to the REST Service and processes the response.
   *
   * @return The service response.
   */
  public UserInfoResponse exec() {
    // Prepare request parameters
    initClientRequest();
    clientRequest.header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
    clientRequest.setHttpMethod(getHttpMethod());

    if (getRequest().getAuthorizationMethod() == null
        || getRequest().getAuthorizationMethod()
            == AuthorizationMethod.AUTHORIZATION_REQUEST_HEADER_FIELD) {
      if (StringUtils.isNotBlank(getRequest().getAccessToken())) {
        clientRequest.header("Authorization", "Bearer " + getRequest().getAccessToken());
      }
    } else if (getRequest().getAuthorizationMethod()
        == AuthorizationMethod.FORM_ENCODED_BODY_PARAMETER) {
      if (StringUtils.isNotBlank(getRequest().getAccessToken())) {
        clientRequest.formParameter("access_token", getRequest().getAccessToken());
      }
    } else if (getRequest().getAuthorizationMethod() == AuthorizationMethod.URL_QUERY_PARAMETER) {
      if (StringUtils.isNotBlank(getRequest().getAccessToken())) {
        clientRequest.queryParameter("access_token", getRequest().getAccessToken());
      }
    }

    // Call REST Service and handle response
    try {
      if (getRequest().getAuthorizationMethod() == null
          || getRequest().getAuthorizationMethod()
              == AuthorizationMethod.AUTHORIZATION_REQUEST_HEADER_FIELD
          || getRequest().getAuthorizationMethod() == AuthorizationMethod.URL_QUERY_PARAMETER) {
        clientResponse = clientRequest.get(String.class);
      } else if (getRequest().getAuthorizationMethod()
          == AuthorizationMethod.FORM_ENCODED_BODY_PARAMETER) {
        clientResponse = clientRequest.post(String.class);
      }

      int status = clientResponse.getStatus();

      setResponse(new UserInfoResponse(status));

      String entity = clientResponse.getEntity(String.class);
      getResponse().setEntity(entity);
      getResponse().setHeaders(clientResponse.getHeaders());
      if (StringUtils.isNotBlank(entity)) {
        List<String> contentType = clientResponse.getHeaders().get("Content-Type");
        if (contentType != null && contentType.contains("application/jwt")) {
          String[] jwtParts = entity.split("\\.");
          if (jwtParts.length == 5) {
            byte[] sharedSymmetricKey =
                sharedKey != null ? sharedKey.getBytes(Util.UTF8_STRING_ENCODING) : null;
            Jwe jwe = Jwe.parse(entity, rsaPrivateKey, sharedSymmetricKey);
            getResponse().setClaims(jwe.getClaims().toMap());
          } else {
            Jwt jwt = Jwt.parse(entity);
            JwsValidator jwtValidator = new JwsValidator(jwt, sharedKey, jwksUri, null);
            if (jwtValidator.validateSignature()) {
              getResponse().setClaims(jwt.getClaims().toMap());
            }
          }
        } else {
          try {
            JSONObject jsonObj = new JSONObject(entity);

            if (jsonObj.has("error")) {
              getResponse()
                  .setErrorType(UserInfoErrorResponseType.fromString(jsonObj.getString("error")));
              jsonObj.remove("error");
            }
            if (jsonObj.has("error_description")) {
              getResponse().setErrorDescription(jsonObj.getString("error_description"));
              jsonObj.remove("error_description");
            }
            if (jsonObj.has("error_uri")) {
              getResponse().setErrorUri(jsonObj.getString("error_uri"));
              jsonObj.remove("error_uri");
            }

            for (Iterator<String> iterator = jsonObj.keys(); iterator.hasNext(); ) {
              String key = iterator.next();
              List<String> values = new ArrayList<String>();

              JSONArray jsonArray = jsonObj.optJSONArray(key);
              if (jsonArray != null) {
                for (int i = 0; i < jsonArray.length(); i++) {
                  String value = jsonArray.optString(i);
                  if (value != null) {
                    values.add(value);
                  }
                }
              } else {
                String value = jsonObj.optString(key);
                if (value != null) {
                  values.add(value);
                }
              }

              getResponse().getClaims().put(key, values);
            }
          } catch (JSONException e) {
            e.printStackTrace();
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      closeConnection();
    }

    return getResponse();
  }
示例#6
0
  /**
   * This method allow to insert data to the data table.
   *
   * @param incomingData
   * @return
   * @throws Exception
   */
  @POST
  @Path("/insert")
  @Consumes({MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_JSON})
  @Produces(MediaType.APPLICATION_JSON)
  public Response addData(String incomingData) throws Exception {

    String returnString = null;
    JSONArray jsonArray = new JSONArray();
    JSONObject jsonObject = new JSONObject();
    SchemaPostgresDB dao = new SchemaPostgresDB();

    try {

      /*
       * We can create a new instance and it will accept a JSON string
       * By doing this, we can now access the data.
       */
      JSONObject data = new JSONObject(incomingData);
      System.out.println("jsonData: " + data.toString());

      /*
       * Example:
       * data.optString("stream");
       * The optString example above will also return data but if stream does not
       * exist, it will return a BLANK string.
       *
       * data.optString("stream", NULL);
       * You can add a second parameter, it will return NULL if stream does not
       * exist.
       */
      int http_code =
          dao.insertIntoData(
              data.optInt("stream"),
              data.optInt("page"),
              data.optString("content"),
              data.optInt("jumpToPage"),
              data.optInt("jumpToStream"),
              data.optString("desc"));

      if (http_code == 200) {
        /*
         * The put method allows you to add data to a JSONObject.
         * The first parameter is the KEY (no spaces)
         * The second parameter is the Value
         */
        jsonObject.put("HTTP_CODE", "200");
        jsonObject.put("MSG", "Item has been entered successfully");
        /*
         * When you are dealing with JSONArrays, the put method is used to add
         * JSONObjects into JSONArray.
         */
        returnString = jsonArray.put(jsonObject).toString();
      } else {
        return Response.status(500).entity("Unable to enter Item").build();
      }

      System.out.println("returnString: " + returnString);

    } catch (Exception e) {
      e.printStackTrace();
      return Response.status(500).entity("Server was not able to process your request").build();
    }

    return Response.ok(returnString).build();
  }
  /**
   * Enrich portClassHier with class/interface names that map to a list of parent
   * classes/interfaces. For any class encountered, find its parents too.<br>
   * Also find the port types which have assignable schema classes.
   *
   * @param oper Operator to work on
   * @param portClassHierarchy In-Out param that contains a mapping of class/interface to its
   *     parents
   * @param portTypesWithSchemaClasses Json that will contain all the ports which have any schema
   *     classes.
   */
  public void buildAdditionalPortInfo(
      JSONObject oper, JSONObject portClassHierarchy, JSONObject portTypesWithSchemaClasses) {
    try {
      JSONArray ports = oper.getJSONArray(OperatorDiscoverer.PORT_TYPE_INFO_KEY);
      for (int i = 0; i < ports.length(); i++) {
        JSONObject port = ports.getJSONObject(i);

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

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

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

        // finding port types with schema classes
        if (portTypesWithSchemaClasses.has(portType)) {
          // already present in the json so skipping
          continue;
        }
        if (portType.equals("byte")
            || portType.equals("short")
            || portType.equals("char")
            || portType.equals("int")
            || portType.equals("long")
            || portType.equals("float")
            || portType.equals("double")
            || portType.equals("java.lang.String")
            || portType.equals("java.lang.Object")) {
          // ignoring primitives, strings and object types as this information is needed only for
          // complex types.
          continue;
        }
        if (port.has("typeArgs")) {
          // ignoring any type with generics
          continue;
        }
        boolean hasSchemaClasses = false;
        List<String> instantiableDescendants = typeGraph.getInstantiableDescendants(portType);
        if (instantiableDescendants != null) {
          for (String descendant : instantiableDescendants) {
            try {
              if (typeGraph.isInstantiableBean(descendant)) {
                hasSchemaClasses = true;
                break;
              }
            } catch (JSONException ex) {
              LOG.warn("checking descendant is instantiable {}", descendant);
            }
          }
        }
        portTypesWithSchemaClasses.put(portType, hasSchemaClasses);
      }
    } catch (JSONException e) {
      // should not reach this
      LOG.error("JSON Exception {}", e);
      throw new RuntimeException(e);
    }
  }