package com.soundcloud.api.examples;


import com.soundcloud.api.ApiWrapper;
import com.soundcloud.api.Http;
import com.soundcloud.api.Request;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;

import java.io.File;

/**
 * Access a protected resource from the server. This needs a prepared (serialized) API
 * wrapper instance (create one with CreateWrapper).
 *
 * @see CreateWrapper
 */
public final class GetResource {
    public static void main(String[] args) throws Exception {
        final File wrapperFile = CreateWrapper.WRAPPER_SER;

        if (args.length == 0) {
            System.err.println("GetResource resource");
            System.exit(1);
        } else if (!wrapperFile.exists()) {
            System.err.println("\nThe serialised wrapper (" + wrapperFile + ") does not exist.\n" +
                    "Run CreateWrapper first to create it.");
            System.exit(1);
        } else {
            final ApiWrapper wrapper = ApiWrapper.fromFile(wrapperFile);
            final Request resource = Request.to(args[0]);
            System.out.println("GET " + resource);
            try {
                HttpResponse resp = wrapper.get(resource);
                if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    System.out.println("\n" + Http.getJSON(resp).toString(4));
                } else {
                    System.err.println("Invalid status received: " + resp.getStatusLine());
                }
            } finally {
                // serialise wrapper state again (token might have been refreshed)
                wrapper.toFile(wrapperFile);
            }
        }
    }
}

@@ -208,16 +208,102 @@
 pStatus;
+%0Aimport org.json.JSONArray;%0Aimport org.json.JSONException;%0Aimport org.json.JSONObject;
 %0A%0Aimport
@@ -1403,37 +1403,39 @@
 %22 + 
-Http.getJSON(resp).to
+formatJSON(Http.get
 String(
-4
+resp)
 ));%0A
@@ -1676,16 +1676,16 @@
 reshed)%0A
-
         
@@ -1750,11 +1750,321 @@
  %7D%0A    %7D
+%0A%0A    static String formatJSON(String s) %7B%0A        try %7B%0A            return new JSONObject(s).toString(4);%0A        %7D catch (JSONException e) %7B%0A            try %7B%0A                return new JSONArray(s).toString(4);%0A            %7D catch (JSONException e2) %7B%0A                return s;%0A            %7D%0A        %7D%0A    %7D
 %0A%7D%0A

Fix broken JSON formatting