Search in sources :

Example 16 with JSONStringer

use of org.json.JSONStringer in project mobile-center-sdk-android by Microsoft.

the class ErrorModelTest method deserializeInvalidBase64forErrorAttachment.

@Test
public void deserializeInvalidBase64forErrorAttachment() throws JSONException {
    ErrorAttachmentLog log = new ErrorAttachmentLog();
    log.setTimestamp(new Date());
    log.setId(UUID.randomUUID());
    log.setErrorId(UUID.randomUUID());
    log.setData(new byte[0]);
    log.setContentType("text/plain");
    JSONStringer jsonWriter = new JSONStringer();
    jsonWriter.object();
    log.write(jsonWriter);
    jsonWriter.endObject();
    JSONObject json = new JSONObject(jsonWriter.toString());
    json.put(DATA, "a");
    try {
        new ErrorAttachmentLog().read(json);
        Assert.fail("Expected json exception here");
    } catch (JSONException e) {
        assertEquals("bad base-64", e.getMessage());
    }
}
Also used : JSONObject(org.json.JSONObject) JSONException(org.json.JSONException) JSONStringer(org.json.JSONStringer) Date(java.util.Date) Test(org.junit.Test)

Example 17 with JSONStringer

use of org.json.JSONStringer in project mobile-center-sdk-android by Microsoft.

the class DefaultLogSerializerTest method failToUsePrettyJson.

@Test
public void failToUsePrettyJson() throws Exception {
    /* Mock logs to verify interactions. */
    mockStatic(MobileCenterLog.class);
    when(MobileCenterLog.getLogLevel()).thenReturn(Log.VERBOSE);
    /* Mock stub JSONStringer. */
    JSONStringer stringer = mock(JSONStringer.class);
    whenNew(JSONStringer.class).withAnyArguments().thenReturn(stringer);
    when(stringer.key(anyString())).thenReturn(stringer);
    when(stringer.toString()).thenReturn("{}");
    /*
         * We are in test folder so the stub does not contain the private methods,
         * this test thus simulates what happens if we can't access the private methods
         * via reflection to use pretty json. We check it serializes gracefully.
         */
    assertEquals("{}", new DefaultLogSerializer().serializeContainer(mock(LogContainer.class)));
    /* And that it logs why the pretty json could not be used. */
    verifyStatic();
    MobileCenterLog.error(eq(MobileCenter.LOG_TAG), anyString(), any(NoSuchMethodError.class));
}
Also used : JSONStringer(org.json.JSONStringer) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 18 with JSONStringer

use of org.json.JSONStringer in project vidtry by commonsguy.

the class URLHistory method save.

void save(Writer out) throws JSONException, IOException {
    JSONStringer json = new JSONStringer().object();
    for (HistoryItem h : spareCopy) {
        h.emit(json);
    }
    out.write(json.endObject().toString());
}
Also used : JSONStringer(org.json.JSONStringer)

Example 19 with JSONStringer

use of org.json.JSONStringer in project Parse-SDK-Android by ParsePlatform.

the class ParseRESTCommand method toDeterministicString.

// Encodes the object to JSON, but ensures that JSONObjects
// and nested JSONObjects are encoded with keys in alphabetical order.
/** package */
static String toDeterministicString(Object o) throws JSONException {
    JSONStringer stringer = new JSONStringer();
    addToStringer(stringer, o);
    return stringer.toString();
}
Also used : JSONStringer(org.json.JSONStringer)

Example 20 with JSONStringer

use of org.json.JSONStringer in project quorrabot by GloriousEggroll.

the class GameWispAPI method readJsonFromUrl.

@SuppressWarnings("UseSpecificCatch")
private static JSONObject readJsonFromUrl(String methodType, String urlAddress) {
    JSONObject jsonResult = new JSONObject("{}");
    InputStream inputStream = null;
    OutputStream outputStream = null;
    URL urlRaw;
    HttpsURLConnection urlConn;
    String jsonText = "";
    if (sAccessToken.length() == 0) {
        if (!noAccessWarning) {
            com.gmt2001.Console.err.println("GameWispAPI: Attempting to use GameWisp API without key. Disable GameWisp module.");
            noAccessWarning = true;
        }
        JSONStringer jsonObject = new JSONStringer();
        return (new JSONObject(jsonObject.object().key("result").object().key("status").value(-1).endObject().endObject().toString()));
    }
    try {
        urlRaw = new URL(urlAddress);
        urlConn = (HttpsURLConnection) urlRaw.openConnection();
        urlConn.setDoInput(true);
        urlConn.setRequestMethod(methodType);
        urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 QuorraBot/2015");
        if (methodType.equals("POST")) {
            urlConn.setDoOutput(true);
            urlConn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        } else {
            urlConn.addRequestProperty("Content-Type", "application/json");
        }
        urlConn.connect();
        if (urlConn.getResponseCode() == 200) {
            inputStream = urlConn.getInputStream();
        } else {
            inputStream = urlConn.getErrorStream();
        }
        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
        jsonText = readAll(rd);
        jsonResult = new JSONObject(jsonText);
        fillJSONObject(jsonResult, true, methodType, urlAddress, urlConn.getResponseCode(), "", "", jsonText);
    } catch (JSONException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "JSONException", ex.getMessage(), jsonText);
        com.gmt2001.Console.err.println("GameWispAPI::Bad JSON (" + urlAddress + "): " + jsonText.substring(0, 100) + "...");
    } catch (NullPointerException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "NullPointerException", ex.getMessage(), "");
        com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (MalformedURLException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "MalformedURLException", ex.getMessage(), "");
        com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (SocketTimeoutException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "SocketTimeoutException", ex.getMessage(), "");
        com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (IOException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "IOException", ex.getMessage(), "");
        com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (Exception ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "Exception", ex.getMessage(), "");
        com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ex) {
                fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "IOException", ex.getMessage(), "");
                com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage());
            }
        }
    }
    return (jsonResult);
}
Also used : MalformedURLException(java.net.MalformedURLException) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) BufferedOutputStream(java.io.BufferedOutputStream) JSONException(org.json.JSONException) IOException(java.io.IOException) URL(java.net.URL) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) JSONException(org.json.JSONException) SocketTimeoutException(java.net.SocketTimeoutException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SocketTimeoutException(java.net.SocketTimeoutException) JSONObject(org.json.JSONObject) BufferedReader(java.io.BufferedReader) JSONStringer(org.json.JSONStringer) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Aggregations

JSONStringer (org.json.JSONStringer)34 Test (org.junit.Test)16 JSONObject (org.json.JSONObject)12 JSONException (org.json.JSONException)7 ArrayList (java.util.ArrayList)4 NonNull (android.support.annotation.NonNull)2 IOException (java.io.IOException)2 Date (java.util.Date)2 HashMap (java.util.HashMap)2 HttpResponse (org.apache.http.HttpResponse)2 HttpPost (org.apache.http.client.methods.HttpPost)2 StringEntity (org.apache.http.entity.StringEntity)2 InSequence (org.jboss.arquillian.junit.InSequence)2 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)2 Log (com.microsoft.appcenter.ingestion.models.Log)1 AppCenterLog (com.microsoft.appcenter.utils.AppCenterLog)1 Log (com.microsoft.azure.mobile.ingestion.models.Log)1 MobileCenterLog (com.microsoft.azure.mobile.utils.MobileCenterLog)1 BufferedOutputStream (java.io.BufferedOutputStream)1 BufferedReader (java.io.BufferedReader)1