Get JSON response for GET

@param   request Request object for GET
@throws  JSONException
@return  {@link JSONObject}
322504
public static JSONObject getJSONObject(HttpGet request) throws JSONException {
        return UpworkRestClient.getJSONObject(request, METHOD_GET, new HashMap<String, String>());
    }
1032802
public JSONObject getJson() throws JSONException {
        JSONObject json = create();
        if (getDescription() != null && !getDescription().isEmpty())
          json.put("description", getDescription());
        if (attributes != null && !attributes.isEmpty()) {
            json.put("attributes", Attribute.getAttributesJson(attributes));
        }
        if (activities != null && !activities.isEmpty()) {
            JSONArray activitiesJson = new JSONArray();
            for (Activity activity : activities) {
                JSONObject activityJson = activity.getJson();
                List<Transition> transitions = getAllTransitions(activity.getId());
                if (transitions != null && !transitions.isEmpty()) {
                    JSONArray transitionsJson = new JSONArray();
                    for (Transition transition : transitions) {
                        JSONObject transitionJson = transition.getJson();
                        if (transition.getToId() < 0) // newly created
                            transitionJson.put("to", getActivityVO(transition.getToId()).getLogicalId());
                        transitionsJson.put(transitionJson);
                    }
                    activityJson.put("transitions", transitionsJson);
                }
                activitiesJson.put(activityJson);
            }
            json.put("activities", activitiesJson);
        }
        if (subprocesses != null && !subprocesses.isEmpty()) {
            JSONArray subprocsJson = new JSONArray();
            for (Process subproc : subprocesses) {
                JSONObject subprocJson = subproc.getJson();
                String logicalId = subproc.getAttribute(WorkAttributeConstant.LOGICAL_ID);
                subprocJson.put("id", logicalId);
                subprocJson.put("name", subproc.getName());
                if (subprocJson.has("version"))
                  subprocJson.remove("version");
                subprocsJson.put(subprocJson);
            }
            json.put("subprocesses", subprocsJson);
        }
        if (textNotes != null && !textNotes.isEmpty()) {
            JSONArray textNotesJson = new JSONArray();
            for (TextNote textNote : textNotes)
                textNotesJson.put(textNote.getJson());
            json.put("textNotes", textNotesJson);
        }
        if (variables != null && !variables.isEmpty()) {
            JSONObject variablesJson = create();
            for (Variable variable : variables)
                variablesJson.put(variable.getJsonName(), variable.getJson());
            json.put("variables", variablesJson);
        }

        return json;
    }
588430
protected JsonRpcResponse execute(JsonRpcRequest request) {
        if (request == null) {
            return new JsonRpcResponse(null, JsonRpcError.parseError(null));
        }

        String serviceName = null;
        String methodName = request.getMethod();
        int lastIndex = methodName.lastIndexOf('.');
        if (lastIndex >= 0) {
            serviceName = methodName.substring(0, lastIndex);
            methodName = methodName.substring(lastIndex + 1);
        }

        ServiceEntry<?> serviceEntry = serviceRegistry.getService(serviceName);
        if (serviceEntry == null) {
            return new JsonRpcResponse(null, JsonRpcError.methodNotFoundError(null));
        }
        Set<Method> methods = serviceEntry.getMethods(methodName);
        if (methods == null || methods.isEmpty()) {
            return new JsonRpcResponse(null, JsonRpcError.methodNotFoundError(null));
        }

        String id = request.getId();
        Node[] params = request.getParams();
        Method method = findExecutableMethod(methods, params);
        if (method == null) {
            return new JsonRpcResponse(null, JsonRpcError.invalidParamsError(null));
        }

        Object service = serviceEntry.getService();
        Object[] args = getParameters(method, params);
        try {
            Object invokeValue = method.invoke(service, args);

            if (id == null) {
                return null;
            }

            Node result = jsonImpl.convert(invokeValue);
            return new JsonRpcResponse(id, result);
        } catch (Throwable t) {
            if (t instanceof InvocationTargetException) {
                t = ((InvocationTargetException) t).getTargetException();
            }
            LOG.debug("executing error : " + method, t);
            return new JsonRpcResponse(id, JsonRpcError.serverError(2, "Server error", t));
        }
    }
422819
function json (request) {

    var type = request.headers.get('Content-Type') || '';

    if (isObject(request.body) && type.indexOf('application/json') === 0) {
        request.body = JSON.stringify(request.body);
    }

    return function (response) {

        return response.bodyText ? when(response.text(), function (text) {

            var type = response.headers.get('Content-Type') || '';

            if (type.indexOf('application/json') === 0 || isJson(text)) {

                try {
                    response.body = JSON.parse(text);
                } catch (e) {
                    response.body = null;
                }

            } else {
                response.body = text;
            }

            return response;

        }) : response;

    };
}
61028
@RequestMapping(value = "/userSession", method = RequestMethod.GET)
    @ResponseBody
    public JsonObject<?> session(HttpServletRequest request) {
        JsonObject<?> ret = JsonObject.create();
        String cookieValueUsername = CookieUtils.getCookieValue(request,
                UserWebConstant.CookieKey.USERNAME.getValue());
        String cookieValuePwd = CookieUtils.getCookieValue(request,
                UserWebConstant.CookieKey.PWDMD5.getValue());
        if (LoginValidator.isValid(cookieValueUsername, cookieValuePwd)) {
            LOG.info("Already logon with username=" + cookieValueUsername);
            ret.addData("id", UserWebConstant.USERMAP.get(cookieValueUsername).getUserId());
            ret.addData("name", cookieValueUsername);
            return ret;
        } else {
            ret.setStatus(GlobalResponseStatusMsg.NOT_LOGIN.getCode());
            ret.addStatusInfo(GlobalResponseStatusMsg.NOT_LOGIN.getMessage().getMessage());
        }

        return ret;
    }
83407
@SuppressWarnings("unchecked")
	public static <T> Response<T> getInstanceOfParameterizedType(Request<T> request) {
		Type superclazz = request.getClass().getGenericSuperclass();
		try {
			Type parameterizedTypeClazz = ((ParameterizedType) superclazz).getActualTypeArguments()[0];
			return (Response<T>) ((Class<T>) parameterizedTypeClazz).newInstance();
		} catch (Exception e) {
			return null;
		}
	}
807260
public T get(String json) throws IOException, JsonFormatException {
		JsonPullParser parser = JsonPullParser.newParser(json);
		return get(parser, null);
	}
622268
public JSONObject getJson() throws JSONException {
        JSONObject json = create();
        json.put("id", getLogicalId());
        json.put("to", "A" + toId);
        if (completionCode != null)
            json.put("resultCode", completionCode);
        if (eventType != null)
            json.put("event", EventType.getEventTypeName(eventType));
        if (attributes != null && ! attributes.isEmpty())
            json.put("attributes", Attribute.getAttributesJson(attributes));
        return json;
    }
968538
public JSONObject toJson() throws JSONException {

        JSONObject result = new JSONObject();
        if (m_detailId != null) {
            result.put(JSON_DETAIL, "" + m_detailId);
        }
        if (m_siteRoot != null) {
            result.put(JSON_SITEROOT, m_siteRoot);
        }
        if (m_structureId != null) {
            result.put(JSON_STRUCTUREID, "" + m_structureId);
        }
        if (m_projectId != null) {
            result.put(JSON_PROJECT, "" + m_projectId);
        }
        if (m_type != null) {
            result.put(JSON_TYPE, "" + m_type.getJsonId());
        }
        return result;
    }
422745
private JsonNode executeRequest(HttpPost request) throws IOException, GroovesharkException {

        HttpResponse response = httpClient.execute(request);

        if (debugLogging) {
            logRequest(request, response);
        }

        String responsePayload = CharStreams.toString(new InputStreamReader(response.getEntity()
                .getContent(), Charsets.UTF_8));

        // Parse response JSON
        try {
            return jsonMapper.readTree(new StringReader(responsePayload));
        } catch (JsonProcessingException e) {
            throw new GroovesharkException.ServerErrorException(
                    "Failed to parse response - received data was not valid JSON: " + responsePayload);
        }
    }
695234
public static String getRequestBody(HttpServletRequest request) {
		if(request.getMethod().equals("GET") || request.getMethod().equals("DELETE")) {
			return null;
		}
		
		StringBuilder stringBuilder = new StringBuilder();
		BufferedReader bufferedReader = null;
		try {
			InputStream inputStream = request.getInputStream();
			if (inputStream != null) {
				bufferedReader = new BufferedReader(new InputStreamReader(
						inputStream));
				char[] charBuffer = new char[128];
				int bytesRead = -1;
				while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
					stringBuilder.append(charBuffer, 0, bytesRead);
				}
			} else {
				stringBuilder.append("");
			}
		} catch (IOException ex) {
			// to nothing
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException ex) {

				}
			}
		}

		if (!StringUtils.isEmpty(stringBuilder)) {
			return stringBuilder.toString();
		}

		if (request.getParameterMap().keySet().size() > 0) {
			return request.getParameterMap().keySet().toArray()[0].toString();
		}

        return null;
	}
8574
@Internal
    public static Optional<NettyMutableHttpResponse> get(NettyHttpRequest<?> request) {
        NettyMutableHttpResponse nettyHttpResponse = request.attr(KEY).get();
        return Optional.ofNullable(nettyHttpResponse);
    }
844968
public Object get(String key) throws JSONException {
        if (key == null) {
            throw new JSONException("Null key.");
        }
        Object object = this.opt(key);
        if (object == null) {
            throw new JSONException("JSONObject[" + quote(key) + "] not found.");
        }
        return object;
    }
665628
public CopyObjectResponse copyObject(CopyObjectRequest request) {
        checkNotNull(request, "request should not be null.");
        assertStringNotNullOrEmpty(request.getSourceKey(), "object key should not be null or empty");

        InternalRequest internalRequest = this.createRequest(request, HttpMethodName.PUT);

        String copySourceHeader = "/" + request.getSourceBucketName() + "/" + request.getSourceKey();
        copySourceHeader = HttpUtils.normalizePath(copySourceHeader);
        internalRequest.addHeader(Headers.BCE_COPY_SOURCE, copySourceHeader);
        if (request.getETag() != null) {
            internalRequest.addHeader(Headers.BCE_COPY_SOURCE_IF_MATCH,
                    "\"" + request.getETag() + "\"");
        }
        if (request.getNoneMatchETagConstraint() != null) {
            internalRequest.addHeader(
                    Headers.BCE_COPY_SOURCE_IF_NONE_MATCH, "\"" + request.getNoneMatchETagConstraint() + "\"");
        }
        if (request.getUnmodifiedSinceConstraint() != null) {
            internalRequest.addHeader(
                    Headers.BCE_COPY_SOURCE_IF_UNMODIFIED_SINCE, request.getUnmodifiedSinceConstraint());
        }
        if (request.getModifiedSinceConstraint() != null) {
            internalRequest.addHeader(
                    Headers.BCE_COPY_SOURCE_IF_MODIFIED_SINCE, request.getModifiedSinceConstraint());
        }
        if (request.getStorageClass() != null) {
            internalRequest.addHeader(Headers.BCE_STORAGE_CLASS, request.getStorageClass());
        }
        ObjectMetadata newObjectMetadata = request.getNewObjectMetadata();
        if (newObjectMetadata != null) {
            internalRequest.addHeader(Headers.BCE_COPY_METADATA_DIRECTIVE, "replace");
            populateRequestMetadata(internalRequest, newObjectMetadata);
        } else {
            internalRequest.addHeader(Headers.BCE_COPY_METADATA_DIRECTIVE, "copy");
        }

        this.setZeroContentLength(internalRequest);

        CopyObjectResponseWithExceptionInfo intermidiateRes = this.invokeHttpClient(internalRequest,
                CopyObjectResponseWithExceptionInfo.class);
        // handle exception
        if (intermidiateRes.getETag() == null 
                && intermidiateRes.getLastModified() == null) {
            if (intermidiateRes.getMessage() != null) {
                BceServiceException bse = new BceServiceException(intermidiateRes.getMessage());
                bse.setErrorCode(intermidiateRes.getCode());
                bse.setRequestId(intermidiateRes.getRequestId());
                if (bse.getErrorCode() == "InternalError") {
                    bse.setErrorType(ErrorType.Service);
                } else {
                    bse.setErrorType(ErrorType.Client);
                }
                bse.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                throw bse;
            }
        }
        return (CopyObjectResponse) intermidiateRes;
    }
315121
private static JSONObject doGetRequest(HttpGet httpGet) throws JSONException {
        JSONObject json = null;
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpResponse response;
        
        try {
        	response = httpClient.execute(httpGet);
            
            if(response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    InputStream instream = entity.getContent();
                    String result = convertStreamToString(instream);
                    instream.close();
                    
                    json = new JSONObject(result);
                }
            } else {
            	json = UpworkRestClient.genError(response);
            }
        } catch (ClientProtocolException e) {
            json = UpworkRestClient.genError(HTTP_RESPONSE_503, "Exception: ClientProtocolException");
        } catch (IOException e) {
            json = UpworkRestClient.genError(HTTP_RESPONSE_503, "Exception: IOException");
        } catch (JSONException e) {
            json = UpworkRestClient.genError(HTTP_RESPONSE_503, "Exception: JSONException");  
        } catch (Exception e) {
            json = UpworkRestClient.genError(HTTP_RESPONSE_503, "Exception: Exception " + e.toString());
        } finally {
            httpGet.abort();
        }
        
        return json;
    }
52449
public String postJson(String endpoint, JSONObject json) throws IOException {
        return this.postJson(endpoint, "", json);
    }
239621
public JsonNode get(Integer expectedResponseCode) throws IOException {
    HttpURLConnection conn = getUrlConnection();
    byte[] responseData;
    try {
      if (!NetworkUtils.sendHttpGetRequest(conn)) {
        throw new IOException("Failed to send get request to " + endpointURI);
      }

      // Check the response code
      if (!NetworkUtils.checkHttpResponseCode(conn, expectedResponseCode)) {
        throw new IOException("Unexpected response from connection. Expected "
            + expectedResponseCode + " but received " + conn.getResponseCode());
      }

      responseData = NetworkUtils.readHttpResponse(conn);

    } finally {
      conn.disconnect();
    }

    // parse of the json
    JsonNode podDefinition;

    try {
      // read the json data
      ObjectMapper mapper = new ObjectMapper();
      podDefinition = mapper.readTree(responseData);
    } catch (IOException ioe) {
      throw new IOException("Failed to parse JSON response from API");
    }

    return podDefinition;
  }