Java Code Examples for org.json.JSONObject#write()

The following examples show how to use org.json.JSONObject#write() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AdditionalExecutor.java    From CF-rating-prediction with Apache License 2.0 6 votes vote down vote up
private static void matchesIdToNames(String[] args) {
  boolean gym = Boolean.getBoolean(args[1]);
  List<String> contests = CodeForcesSDK.getContestNames(gym);
  List<JSONObject> list = new ArrayList<>(contests.size());
  for (int contestId = contests.size() - 1; contestId > 0; contestId--) {
    JSONObject json = new JSONObject();
    json.put("contestId", contestId);
    json.put("name", contests.get(contestId));
    list.add(json);
  }

  JSONObject contestNames = new JSONObject();
  contestNames.put("status", "OK");
  contestNames.put("result", new JSONArray(list));

  String fileName = "contests/contestNames.json";
  try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(fileName))) {
    contestNames.write(writer);
    writer.write("\n");
  } catch (Exception ex) {
    System.err.println("Couldn't write contestNames\n"
      + ex.getMessage());
  }
}
 
Example 2
Source File: PastRatingDownloader.java    From CF-rating-prediction with Apache License 2.0 6 votes vote down vote up
private static boolean writeToFiles(String filePrefix, TreeMap<String, Integer> rating, String contestId) {
  boolean result = true;
  String fileName = getFileName(contestId, filePrefix);
  JSONObject json = toJSON(rating);

  try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(fileName))) {
    json.write(writer, 2, 0);
    writer.write("\n");
  } catch (Exception ex) {
    System.err.println("Couldn't write past rating to the file\n"
      + ex.getMessage());
    result = false;
  }

  return result;
}
 
Example 3
Source File: Console.java    From selenium-api with MIT License 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {
        if ("/requests".equals(req.getPathInfo())) {
            sendJson(pendingRequests(), req, resp);
        } else {
            sendJson(status(), req, resp);
        }
    } catch (JSONException je) {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        resp.setStatus(500);
        JSONObject error = new JSONObject();

        try {
            error.put("message", je.getMessage());
            error.put("location", je.getStackTrace());
            error.write(resp.getWriter());
        } catch (JSONException e1) {
          log.log(Level.WARNING, "Failed to write error response", e1);
        }

    }

}
 
Example 4
Source File: Utils.java    From SWET with MIT License 5 votes vote down vote up
public String writeDataJSON(Map<String, String> data, String defaultPayload) {
	String payload = defaultPayload;
	JSONObject json = new JSONObject();
	try {
		for (String key : data.keySet()) {
			json.put(key, data.get(key));
		}
		StringWriter wr = new StringWriter();
		json.write(wr);
		payload = wr.toString();
	} catch (JSONException e) {
		System.err.println("Exception (ignored): " + e);
	}
	return payload;
}
 
Example 5
Source File: CardinalityRepository.java    From rheem with Apache License 2.0 5 votes vote down vote up
/**
 * Writes the measuremnt to the {@link #repositoryPath}.
 */
private void write(JSONObject jsonMeasurement) {
    try {
        jsonMeasurement.write(this.getWriter());
        writer.write('\n');
    } catch (IOException e) {
        IOUtils.closeQuietly(this.writer);
        throw new RuntimeException("Could not open cardinality repository file for writing.", e);
    }
}
 
Example 6
Source File: ApiHandler.java    From datamill with ISC License 5 votes vote down vote up
private static void write(OutputStream outputStream, JSONObject json) {
    logger.debug("Returning {} response", json.get(STATUS_CODE));
    if (logger.isTraceEnabled()) {
        logger.trace("Response: {}", json);
    }

    try (OutputStreamWriter writer = new OutputStreamWriter(outputStream, Charsets.UTF_8)) {
        json.write(writer);
    } catch (IOException e) {
        logger.debug("Error while closing output response");
    }
}
 
Example 7
Source File: UrlShortener.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a shortened URL by calling the Google URL Shortener API.
 *
 * <p>Note: Error handling elided for simplicity.
 */
public String createShortUrl(String longUrl) throws Exception {
  ArrayList<String> scopes = new ArrayList<String>();
  scopes.add("https://www.googleapis.com/auth/urlshortener");
  final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
  final AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes);
  // The token asserts the identity reported by appIdentity.getServiceAccountName()
  JSONObject request = new JSONObject();
  request.put("longUrl", longUrl);

  URL url = new URL("https://www.googleapis.com/urlshortener/v1/url?pp=1");
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setDoOutput(true);
  connection.setRequestMethod("POST");
  connection.addRequestProperty("Content-Type", "application/json");
  connection.addRequestProperty("Authorization", "Bearer " + accessToken.getAccessToken());

  OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
  request.write(writer);
  writer.close();

  if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
    // Note: Should check the content-encoding.
    //       Any JSON parser can be used; this one is used for illustrative purposes.
    JSONTokener responseTokens = new JSONTokener(connection.getInputStream());
    JSONObject response = new JSONObject(responseTokens);
    return (String) response.get("id");
  } else {
    try (InputStream s = connection.getErrorStream();
        InputStreamReader r = new InputStreamReader(s, StandardCharsets.UTF_8)) {
      throw new RuntimeException(
          String.format(
              "got error (%d) response %s from %s",
              connection.getResponseCode(), CharStreams.toString(r), connection.toString()));
    }
  }
}
 
Example 8
Source File: HdfsTraceStorage.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
public void storeJson(Path storePath, JSONObject jsonObject) throws IOException {
  FSDataOutputStream outputStream = _fileSystem.create(storePath, false);
  try {
    OutputStreamWriter writer = new OutputStreamWriter(outputStream);
    jsonObject.write(writer);
    writer.close();
  } catch (JSONException e) {
    throw new IOException(e);
  }
}
 
Example 9
Source File: LogsServlet.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
private void listFiles(HttpServletResponse response) throws JSONException, IOException {
  JSONObject jsonObject = new JSONObject();
  File[] files = new File(_dir).listFiles();
  JSONArray array = new JSONArray();
  for (File file : files) {
    array.put(file.getName());
  }
  jsonObject.put("files", array);
  jsonObject.write(response.getWriter());
}
 
Example 10
Source File: FrontendUtils.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * @param jsonObject the {@link JSONObject} to serialize.
 * @return the {@link ReadableStreamChannel} containing UTF-8 formatted json.
 * @throws RestServiceException if there was an error during serialization.
 */
static ReadableStreamChannel serializeJsonToChannel(JSONObject jsonObject) throws RestServiceException {
  try {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try (Writer writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)) {
      jsonObject.write(writer);
    }
    return new ByteBufferReadableStreamChannel(ByteBuffer.wrap(outputStream.toByteArray()));
  } catch (Exception e) {
    throw new RestServiceException("Could not serialize response json.", e, RestServiceErrorCode.InternalServerError);
  }
}
 
Example 11
Source File: ExecutionLog.java    From rheem with Apache License 2.0 4 votes vote down vote up
/**
 * Writes the measuremnt to the {@link #repositoryPath}.
 */
private void write(JSONObject jsonMeasurement) throws IOException {
    jsonMeasurement.write(this.getWriter());
    writer.write('\n');
}
 
Example 12
Source File: DatastoreExportServlet.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

  // Validate outputURL parameter
  String outputUrlPrefix = request.getParameter("output_url_prefix");

  if (outputUrlPrefix == null || !outputUrlPrefix.matches("^gs://.*")) {
    // Send error response if outputURL not set or not a Cloud Storage bucket
    response.setStatus(HttpServletResponse.SC_CONFLICT);
    response.setContentType("text/plain");
    response.getWriter().println("Error: Must provide a valid output_url_prefix.");

  } else {

    // Put together export request headers
    URL url = new URL("https://datastore.googleapis.com/v1/projects/" + PROJECT_ID + ":export");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Content-Type", "application/json");

    // Get an access token to authorize export request
    ArrayList<String> scopes = new ArrayList<String>();
    scopes.add("https://www.googleapis.com/auth/datastore");
    final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
    final AppIdentityService.GetAccessTokenResult accessToken =
        AppIdentityServiceFactory.getAppIdentityService().getAccessToken(scopes);
    connection.addRequestProperty("Authorization", "Bearer " + accessToken.getAccessToken());

    // Build export request payload based on URL parameters
    // Required: output_url_prefix
    // Optional: entity filter
    JSONObject exportRequest = new JSONObject();

    // If output prefix ends with a slash, use as-is
    // Otherwise, add a timestamp to form unique output url
    if (!outputUrlPrefix.endsWith("/")) {
      String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
      outputUrlPrefix = outputUrlPrefix + "/" + timeStamp + "/";
    }

    // Add outputUrl to payload
    exportRequest.put("output_url_prefix", outputUrlPrefix);

    // Build optional entity filter to export subset of
    // kinds or namespaces
    JSONObject entityFilter = new JSONObject();

    // Read kind parameters and add to export request if not null
    String[] kinds = request.getParameterValues("kind");
    if (kinds != null) {
      JSONArray kindsJson = new JSONArray(kinds);
      entityFilter.put("kinds", kindsJson);
    }

    // Read namespace parameters and add to export request if not null
    String[] namespaces = request.getParameterValues("namespace_id");
    if (namespaces != null) {
      JSONArray namespacesJson = new JSONArray(namespaces);
      entityFilter.put("namespaceIds", namespacesJson);
    }

    // Add entity filter to payload
    // Finish export request payload
    exportRequest.put("entityFilter", entityFilter);

    // Send export request
    OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
    exportRequest.write(writer);
    writer.close();

    // Examine server's response
    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
      // Request failed, log errors and return
      InputStream s = connection.getErrorStream();
      InputStreamReader r = new InputStreamReader(s, StandardCharsets.UTF_8);
      String errorMessage =
          String.format(
              "got error (%d) response %s from %s",
              connection.getResponseCode(), CharStreams.toString(r), connection.toString());
      log.warning(errorMessage);
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      response.setContentType("text/plain");
      response.getWriter().println(
          "Failed to initiate export.");
      return;   
    }

    // Success, print export operation information
    JSONObject exportResponse = new JSONObject(new JSONTokener(connection.getInputStream()));

    response.setContentType("text/plain");
    response.getWriter().println(
        "Export started:\n" + exportResponse.toString(4));    
  }
}