Example usage for com.fasterxml.jackson.core JsonParseException toString

List of usage examples for com.fasterxml.jackson.core JsonParseException toString

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonParseException toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:can.yrt.oba.serialization.JacksonSerializer.java

@Override
public <T> T createFromError(Class<T> cls, int code, String error) {
    // This is not very efficient, but it's an error case and it's easier
    // than instantiating one ourselves.
    final String jsonErr = toJson(error);
    final String json = getErrorJson(code, jsonErr);

    try {/*from   w  ww  . j a v a2 s  .c om*/
        // Hopefully this never returns null or throws.
        return mMapper.readValue(json, cls);
    } catch (JsonParseException e) {
        Log.e(TAG, e.toString());
    } catch (JsonMappingException e) {
        Log.e(TAG, e.toString());
    } catch (IOException e) {
        Log.e(TAG, e.toString());
    }
    return null;
}

From source file:org.opendatakit.survey.android.tasks.InstanceUploaderTask.java

@Override
protected InstanceUploadOutcome doInBackground(String... toUpload) {
    mOutcome = new InstanceUploadOutcome();
    mOutcome.mResults = new HashMap<String, String>();
    mOutcome.mAuthRequestingServer = null;

    String auth = PropertiesSingleton.getProperty(appName, PreferencesActivity.KEY_AUTH);
    setAuth(auth);//from  w  w  w.  j a  v a 2 s.co  m

    String urlString = null;

    /**
     * retrieve the URL string for the table, if defined... otherwise, use the
     * app property values to construct it.
     */
    {
        SQLiteDatabase db = null;

        Cursor c = null;
        try {
            db = DatabaseFactory.get().getDatabase(appContext, appName);
            c = db.query(DatabaseConstants.KEY_VALUE_STORE_ACTIVE_TABLE_NAME, null,
                    KeyValueStoreColumns.TABLE_ID + "=? AND " + KeyValueStoreColumns.PARTITION + "=? AND "
                            + KeyValueStoreColumns.ASPECT + "=? AND " + KeyValueStoreColumns.KEY + "=?",
                    new String[] { uploadTableId, KeyValueStoreConstants.PARTITION_TABLE,
                            KeyValueStoreConstants.ASPECT_DEFAULT, KeyValueStoreConstants.XML_SUBMISSION_URL },
                    null, null, null);
            if (c.getCount() == 1) {
                c.moveToFirst();
                int idxValue = c.getColumnIndex(KeyValueStoreColumns.VALUE);
                urlString = c.getString(idxValue);
            } else if (c.getCount() != 0) {
                throw new IllegalStateException(
                        "two or more entries for " + KeyValueStoreConstants.XML_SUBMISSION_URL);
            }
        } finally {
            c.close();
            db.releaseReference();
        }

        if (urlString == null) {
            urlString = PropertiesSingleton.getProperty(appName, PreferencesActivity.KEY_SERVER_URL);
            String submissionUrl = PropertiesSingleton.getProperty(appName,
                    PreferencesActivity.KEY_SUBMISSION_URL);
            urlString = urlString + submissionUrl;
        }
    }

    // FormInfo fi = new FormInfo(appContext, appName,
    // ODKFileUtils.getuploadingForm.formDefFile);
    // get shared HttpContext so that authentication and cookies are
    // retained.
    HttpContext localContext = ClientConnectionManagerFactory.get(appName).getHttpContext();
    HttpClient httpclient = ClientConnectionManagerFactory.get(appName)
            .createHttpClient(WebUtils.CONNECTION_TIMEOUT);

    Map<URI, URI> uriRemap = new HashMap<URI, URI>();

    for (int i = 0; i < toUpload.length; ++i) {
        if (isCancelled()) {
            return mOutcome;
        }
        publishProgress(i + 1, toUpload.length);

        Uri toUpdate = Uri.withAppendedPath(InstanceProviderAPI.CONTENT_URI,
                appName + "/" + uploadTableId + "/" + StringEscapeUtils.escapeHtml4(toUpload[i]));
        Cursor c = null;
        try {
            c = appContext.getContentResolver().query(toUpdate, null, null, null, null);
            if (c.getCount() == 1 && c.moveToFirst()) {

                String id = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(InstanceColumns._ID));
                String dataTableInstanceId = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(InstanceColumns.DATA_INSTANCE_ID));
                String lastOutcome = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(InstanceColumns.XML_PUBLISH_STATUS));
                String submissionInstanceId = ODKDataUtils.genUUID();
                // submissions always get a new legacy instance id UNLESS the last
                // submission failed,
                // in which case we retry the submission using the legacy instance id
                // associated with
                // that failure. This supports resumption of sends of forms with many
                // attachments.
                if (lastOutcome != null && lastOutcome.equals(InstanceColumns.STATUS_SUBMISSION_FAILED)) {
                    String lastId = ODKDatabaseUtils.get().getIndexAsString(c,
                            c.getColumnIndex(InstanceColumns.SUBMISSION_INSTANCE_ID));
                    if (lastId != null) {
                        submissionInstanceId = lastId;
                    }
                }
                c.close();

                FileSet instanceFiles;
                try {
                    instanceFiles = constructSubmissionFiles(dataTableInstanceId, submissionInstanceId);
                    // NOTE: /submission must not be translated! It is
                    // the well-known path on the server.

                    if (!uploadOneSubmission(urlString, toUpdate, id, submissionInstanceId, instanceFiles,
                            httpclient, localContext, uriRemap)) {
                        return mOutcome; // get credentials...
                    }
                } catch (JsonParseException e) {
                    WebLogger.getLogger(appName).printStackTrace(e);
                    mOutcome.mResults.put(id, fail + "unable to obtain manifest: " + dataTableInstanceId
                            + " :: details: " + e.toString());
                } catch (JsonMappingException e) {
                    WebLogger.getLogger(appName).printStackTrace(e);
                    mOutcome.mResults.put(id, fail + "unable to obtain manifest: " + dataTableInstanceId
                            + " :: details: " + e.toString());
                } catch (IOException e) {
                    WebLogger.getLogger(appName).printStackTrace(e);
                    mOutcome.mResults.put(id, fail + "unable to obtain manifest: " + dataTableInstanceId
                            + " :: details: " + e.toString());
                }
            } else {
                mOutcome.mResults.put("unknown",
                        fail + "unable to retrieve instance information via: " + toUpdate.toString());
            }
        } finally {
            if (c != null && !c.isClosed()) {
                c.close();
            }
        }
    }

    return mOutcome;
}

From source file:com.couchbase.lite.replicator.ChangeTracker.java

protected void runLoop() {
    paused = false;//from w ww  .j av  a 2  s  .c o m

    if (client == null) {
        // This is a race condition that can be reproduced by calling cbpuller.start() and cbpuller.stop()
        // directly afterwards.  What happens is that by the time the Changetracker thread fires up,
        // the cbpuller has already set this.client to null.  See issue #109
        Log.w(Log.TAG_CHANGE_TRACKER, "%s: ChangeTracker run() loop aborting because client == null", this);
        return;
    }

    if (mode == ChangeTrackerMode.Continuous) {
        // there is a failing unit test for this, and from looking at the code the Replication
        // object will never use Continuous mode anyway.  Explicitly prevent its use until
        // it is demonstrated to actually work.
        throw new RuntimeException("ChangeTracker does not correctly support continuous mode");
    }

    OkHttpClient httpClient = client.getOkHttpClient();

    backoff = new ChangeTrackerBackoff();

    while (running) {
        startTime = System.currentTimeMillis();

        Request.Builder builder = new Request.Builder();
        URL url = getChangesFeedURL();
        builder.url(url);
        if (usePOST) {
            builder.header("Content-Type", "application/json").addHeader("User-Agent", Manager.getUserAgent())
                    .addHeader("Accept-Encoding", "gzip").post(RequestBody.create(JSON, changesFeedPOSTBody()));
        }
        addRequestHeaders(builder);

        // Perform BASIC Authentication if needed
        builder = RequestUtils.preemptivelySetAuthCredentials(builder, url, authenticator);
        request = builder.build();

        try {
            String maskedRemoteWithoutCredentials = getChangesFeedURL().toString();
            maskedRemoteWithoutCredentials = maskedRemoteWithoutCredentials.replaceAll("://.*:.*@",
                    "://---:---@");
            Log.v(Log.TAG_CHANGE_TRACKER, "%s: Making request to %s", this, maskedRemoteWithoutCredentials);
            call = httpClient.newCall(request);
            Response response = call.execute();
            try {
                // In case response status is Error, ChangeTracker stops here
                if (isResponseFailed(response)) {
                    RequestUtils.closeResponseBody(response);
                    if (retryIfFailedPost(response))
                        continue;
                    break;
                }

                // Parse response body
                ResponseBody responseBody = response.body();

                Log.v(Log.TAG_CHANGE_TRACKER, "%s: got response. status: %s mode: %s", this, response.message(),
                        mode);
                if (responseBody != null) {
                    try {
                        Log.v(Log.TAG_CHANGE_TRACKER, "%s: /entity.getContent().  mode: %s", this, mode);
                        //inputStream = entity.getContent();
                        inputStream = responseBody.byteStream();
                        // decompress if contentEncoding is gzip
                        if (Utils.isGzip(response))
                            inputStream = new GZIPInputStream(inputStream);

                        if (mode == ChangeTrackerMode.LongPoll) { // continuous replications
                            // NOTE: 1. check content length, ObjectMapper().readValue() throws Exception if size is 0.
                            // NOTE: 2. HttpEntity.getContentLength() returns the number of bytes of the content, or a negative number if unknown.
                            // NOTE: 3. If Http Status is error, not parse response body
                            boolean responseOK = false; // default value
                            if (responseBody.contentLength() != 0 && response.code() < 300) {
                                try {
                                    Log.v(Log.TAG_CHANGE_TRACKER, "%s: readValue", this);
                                    Map<String, Object> fullBody = Manager.getObjectMapper()
                                            .readValue(inputStream, Map.class);
                                    Log.v(Log.TAG_CHANGE_TRACKER, "%s: /readValue.  fullBody: %s", this,
                                            fullBody);
                                    responseOK = receivedPollResponse(fullBody);
                                } catch (JsonParseException jpe) {
                                    Log.w(Log.TAG_CHANGE_TRACKER, "%s: json parsing error; %s", this,
                                            jpe.toString());
                                } catch (JsonMappingException jme) {
                                    Log.w(Log.TAG_CHANGE_TRACKER, "%s: json mapping error; %s", this,
                                            jme.toString());
                                }
                            }
                            Log.v(Log.TAG_CHANGE_TRACKER, "%s: responseOK: %s", this, responseOK);

                            if (responseOK) {
                                // TODO: this logic is questionable, there's lots
                                // TODO: of differences in the iOS changetracker code,
                                if (!caughtUp) {
                                    caughtUp = true;
                                    client.changeTrackerCaughtUp();
                                }
                                Log.v(Log.TAG_CHANGE_TRACKER, "%s: Starting new longpoll", this);
                                backoff.resetBackoff();
                                continue;
                            } else {
                                long elapsed = (System.currentTimeMillis() - startTime) / 1000;
                                Log.w(Log.TAG_CHANGE_TRACKER,
                                        "%s: Longpoll connection closed (by proxy?) after %d sec", this,
                                        elapsed);
                                if (elapsed >= 30) {
                                    // Looks like the connection got closed by a proxy (like AWS' load balancer) while the
                                    // server was waiting for a change to send, due to lack of activity.
                                    // Lower the heartbeat time to work around this, and reconnect:
                                    this.heartBeatSeconds = Math.min(this.heartBeatSeconds,
                                            (int) (elapsed * 0.75));
                                    Log.v(Log.TAG_CHANGE_TRACKER, "%s: Starting new longpoll", this);
                                    backoff.resetBackoff();
                                    continue;
                                } else {
                                    Log.d(Log.TAG_CHANGE_TRACKER, "%s: Change tracker calling stop (LongPoll)",
                                            this);
                                    client.changeTrackerFinished(this);
                                    break;
                                }
                            }
                        } else { // one-shot replications
                            Log.v(Log.TAG_CHANGE_TRACKER, "%s: readValue (oneshot)", this);
                            JsonFactory factory = new JsonFactory();
                            JsonParser jp = factory.createParser(inputStream);
                            JsonToken token;
                            // nextToken() is null => no more token
                            while (((token = jp.nextToken()) != JsonToken.START_ARRAY) && (token != null)) {
                                // ignore these tokens
                            }
                            while (jp.nextToken() == JsonToken.START_OBJECT) {
                                Map<String, Object> change = (Map) Manager.getObjectMapper().readValue(jp,
                                        Map.class);
                                if (!receivedChange(change)) {
                                    Log.w(Log.TAG_CHANGE_TRACKER,
                                            "Received unparseable change line from server: %s", change);
                                }
                                // if not running state anymore, exit from loop.
                                if (!running)
                                    break;
                            }
                            if (jp != null)
                                jp.close();

                            Log.v(Log.TAG_CHANGE_TRACKER, "%s: /readValue (oneshot)", this);
                            client.changeTrackerCaughtUp();
                            if (isContinuous()) { // if enclosing replication is continuous
                                mode = ChangeTrackerMode.LongPoll;
                            } else {
                                Log.d(Log.TAG_CHANGE_TRACKER, "%s: Change tracker calling stop (OneShot)",
                                        this);
                                client.changeTrackerFinished(this);
                                break;
                            }
                        }
                        backoff.resetBackoff();
                    } finally {
                        try {
                            if (inputStream != null) {
                                inputStream.close();
                                inputStream = null;
                            }
                        } catch (IOException e) {
                        }
                    }
                }
            } finally {
                RequestUtils.closeResponseBody(response);
            }
        } catch (Exception e) {
            if (!running && e instanceof IOException) {
                // in this case, just silently absorb the exception because it
                // frequently happens when we're shutting down and have to
                // close the socket underneath our read.
            } else {
                Log.w(Log.TAG_CHANGE_TRACKER, this + ": Exception in change tracker", e);
                this.error = e;
            }
            backoff.sleepAppropriateAmountOfTime();
        }
    }
    Log.v(Log.TAG_CHANGE_TRACKER, "%s: Change tracker run loop exiting", this);
}